From 0f0f9e6fe23a2ab369befe1fe247e30792a5cd59 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=94=D0=BC=D0=B8=D1=82=D1=80=D0=B8=D0=B9?= Date: Sun, 1 Nov 2026 16:00:05 +0500 Subject: [PATCH] feat(sdk): SDK v0.3.2 hardening, artifact provenance, and realm-bound GitHub analyzer --- TODO.md | 34 + crates/coa-core/src/analyzer.rs | 1054 +++++++++++++++++++++++- crates/coa-core/src/bin/csm_plugins.rs | 95 ++- crates/coa-core/src/lib.rs | 1 + crates/coa-core/src/provenance.rs | 292 +++++++ src-tauri/src/lib.rs | 24 + src/lib/api.ts | 64 ++ src/screens/ModulesPage.tsx | 177 +++- 8 files changed, 1697 insertions(+), 44 deletions(-) create mode 100644 crates/coa-core/src/provenance.rs diff --git a/TODO.md b/TODO.md index d3bb4fe..0f28e85 100644 --- a/TODO.md +++ b/TODO.md @@ -1,5 +1,39 @@ # TODO +## Подготовка 0.9.8, 2026-10-31 + +- Подготовлены исходники `C:/games/source/per-race-manager`, ветка `fix/launcher-validation-candidate-20261031`: изоляция bot configs на время проверки с точным восстановлением, повторное использование MySQL внутри validation, зависимость Dungeon Clear от SQUID, три режима логов и экспорт этапов launcher/control owner. +- Workspace: 840 тестов прошли, 60 ignored; последующие focused diagnostics: 11 прошли. Переводы новых заметок и UI подготовлены, web build/i18n/bridge/history checks прошли. Подробности и ограничения: `C:/games/source/candidate-preparation-20261031.md`. +- Не выпускать Manager до кандидата сервера. Installer ещё не собирался и не публиковался; подготовка источников не равна готовому кандидату. + +## Приоритет: проверка установки и обновления (2026-10-31) +- **Локальные замеры массовых Companions (2026-10-31):** отчёт `C:/games/source/companions-benchmark-20261031/REPORT.md`, сырые выборки/qualification в той же папке. Native worldserver SHA `bd9f65ac7543fad8159231000d5ef6436a159aa009b65cbdc9541a0e9fe1ee7b`, Ryzen 7 7700X/32 GiB, `MapUpdate.Threads=1`, все CPU доступны. Перед условиями восстанавливался один снимок персонажей. Без записи логов медианы среднего тика: 0 ботов 4.5 ms; 500 — 39 ms; 1000 — 91 ms; 2000 — 246 ms, поздний замер 259 ms. С обычными логами: 500 — 43.5 ms; 1000 — 111 ms. Запуск 2000 с логами дал 1381 ms, последующий полный Logger-off 363 ms, но нагрузка хоста менялась; чистый множитель логирования этими числами не доказан. Всего 9 условий с подтверждённым online; исходная база 21 шаблон/0 тестовых аккаунтов восстановлена, тестовые процессы остановлены. Повтор 2000 с логами подготовлен, но НЕ выполнен: на C: осталось около 300 MiB. Соответствующий PDB для функционального профиля отсутствует. +- [ ] **Разобрать штатное завершение мира под большой популяцией**: + - В локальном бенчмарке ряд запусков (включая 2000 ботов и полностью отключённые логгеры) не завершились за 90 секунд после `server shutdown 1s 0`; пришлось завершать только тестовый процесс после сохранения измерений. Стек `2000-shutdown-stacks.txt` показывает ожидание `MSVCP140!Thrd_join`, точный ожидаемый поток без matching PDB не установлен. Не объявлять это доказанной причиной пользовательского control.lock или влиянием только логов. + +- [ ] **Разобрать удержание control.lock после видимого запуска сервера**: + - Пользователь после hotfix v3 получил `Another start/stop action is in progress` при внешнем `with launcher["control_lock"]()`, хотя мир отвечал и Manager показывал работающий сервер. Не считать это доказательством «зависшего файла»: Windows блокирует диапазон живым дескриптором. + - На Python 3.14.7 точно воспроизведён конкурентный захват: второй лаунчер получает эту ошибку, после выхода владельца захват снова проходит. Причина долгого удержания у пользователя пока не установлена; нужны его свежие launch diagnostics. + - Добавить безопасную диагностику владельца (PID, время создания, действие, этап ожидания) и проверить сериализацию Start/Stop/Restart/validation/recovery. Различать реальную занятость и прочие OSError захвата, которые сейчас маскируются одним сообщением. Не удалять lock и не завершать чужие процессы ради обхода. + +- **Проверка с ботами завершена (2026-10-31):** пользователь показал работающие MySQL/auth/world, 2000 Companions онлайн и вход своим клиентом в мир после обновления. Это подтверждает обычный запуск с ботами после hotfix, но не пригодность массового автологина для validation. Ранний снимок показывает около 11 тиков/с на 2m32s работы; результат замера после прогрева пока неизвестен. + +- **Пользовательская проверка (2026-10-31):** после hotfix лаунчера v3 и отключения автологина Companions обновление завершилось успешно (server `0.261030.90`, Manager `0.9.7`). Отдельная проверка с включёнными ботами пока не завершена. +- [ ] **Сократить повторные запуски MySQL в установке/обновлении**: + - Пользователь после успешного обновления отметил большую длительность и многократные старты/остановки базы, в том числе на 85%. Проследить фактическую последовательность snapshot/SQL/schema/validation/recovery и повторно использовать уже запущенную, проверенную базу между совместимыми этапами. + - Не убирать остановки, необходимые для согласованного backup/restore, замены файлов и восстановления после отказа. Сохранить гарантии rollback и владения процессами. Записать число стартов/остановок и длительность этапов до/после; проверить обновление без ботов и восстановление после ошибки. + +- [ ] **Временный конфиг проверки без массового запуска ботов**: + - Запрос владельца: грузить 2000 ботов ради проверки установки/обновления недопустимо. Облегчить все проверочные запуски, включая восстановление/повторную проверку, где применяется тот же путь запуска. + - Факты случая: этап обновления 85%, CoA Companions поставили в очередь 2000 ботов; пользователь сообщает об остановке продвижения на 519 за 6 минут. Логи показывают 518 уникальных имён в `ACTIVE_LIST`. Это не SQUID. Место зависания и причинная связь с автологином пока не установлены. + - Перед проверочным запуском временно отключать `CoaBots.AutoLoginOnStartup` и проверить другие пути автоматического входа/создания/заселения Companions, включая `CoaBots.RandomSpawn.AutoLogin`. Аналогично подавлять автоматическое заселение SQUID, если выбран этот модуль. Не подменять пользовательский выбор системы ботов и не отключать модуль целиком вместо проверки его инициализации. + - Сохранять исходные байты/отсутствие изменяемых конфигов в журнале восстановления; вернуть их до обычного запуска как при успехе, так и при ошибке, отмене, rollback и восстановлении после прерывания Manager. Не оставлять автологин выключенным пользователю. Проверить primary и дополнительные realms. + - Проверка должна подтверждать инициализацию ядра/выбранных модулей, SQL/schema, сервисы и отклик управляющего интерфейса; не ждать заполнения мира ботами и не создавать для этого тысячи персонажей. Вне validation обычный запуск сохраняет поведение пользовательских настроек. + - Проверить сценарии с Companions и лимитом 2000, SQUID, выключенными ботами; успех, отказ запуска, прерывание и восстановление исходных конфигов. Добавить регрессионные проверки и changelog после реализации. + +- [ ] **Доставить исправление `manage.py` для PID 0 в согласованном серверном обновлении**: + - Серверная задача и готовый локальный hotfix описаны в `C:/games/coa-server-build/TODO.md`. Проверить импортируемый запуск через `runpy`/внешний вызов `main()` и штатный Manager update; диагностика должна работать при обоих способах загрузки. + ## UI / UX - [x] **Предупреждение о несохранённых изменениях при переходе между вкладками (Unsaved Changes Guard / Modal)**: - Если у пользователя есть несохранённые изменения в настройках (`ModulesPage`, `SettingsPage` — сервер, боты и др.) и он переходит на другую вкладку (в боковом меню `Shell.tsx` или кнопками навигации), показывать pop-up диалог подтверждения. diff --git a/crates/coa-core/src/analyzer.rs b/crates/coa-core/src/analyzer.rs index c669581..95c0971 100644 --- a/crates/coa-core/src/analyzer.rs +++ b/crates/coa-core/src/analyzer.rs @@ -10,8 +10,9 @@ use std::fs; use std::path::{Path, PathBuf}; use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; -use crate::error::Result; +use crate::error::{Error, Result}; #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] pub enum FindingSeverity { @@ -133,6 +134,149 @@ pub struct VerificationStatus { pub l6_teardown: String, } +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct MultiDimensionalStatus { + pub build_status: String, // "PASS", "FAIL", "REQUIRES_ADAPTER", "BLOCKED" + pub runtime_status: String, // "PASS", "FAIL", "NOT_RUN", "BLOCKED" + pub gameplay_status: String, // "CLEAN", "VERIFIED_CONFLICT", "POTENTIAL_INTERACTION", "NOT_RUN" + pub db_status: String, // "CLEAN", "REVIEW_REQUIRED", "CORRUPT", "NOT_RUN" + pub security_status: String, // "SAFE", "HIGH_RISK", "BLOCKED" +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct UnexportedSymbolDef { + pub symbol_name: String, + pub category: String, // "Category B" or "Category C" + pub risk_explanation: String, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct SdkExportContract { + pub sdk_version: String, + pub abi_fingerprint: String, + pub exported_symbols: Vec, + pub known_unexported_symbols: Vec, +} + +impl Default for SdkExportContract { + fn default() -> Self { + Self::v03() + } +} + +impl SdkExportContract { + pub fn v02() -> Self { + Self { + sdk_version: "v0.2".into(), + abi_fingerprint: "e6c51ed94f3d74c48a45c7ec4efd7c7fb5777d99b6923434890532b011f222a0".into(), + exported_symbols: vec![ + "IPlugin".into(), + "ScriptRegistry".into(), + "ScriptMgr".into(), + ], + known_unexported_symbols: vec![ + UnexportedSymbolDef { + symbol_name: "WorldSessionMgr::SendServerMessage".into(), + category: "Category A".into(), + risk_explanation: "Safe public API missing export decoration in v0.2".into(), + }, + UnexportedSymbolDef { + symbol_name: "CloseGossipMenuFor".into(), + category: "Category A".into(), + risk_explanation: "Safe public API missing export decoration in v0.2".into(), + }, + UnexportedSymbolDef { + symbol_name: "MailReceiver::MailReceiver".into(), + category: "Category A".into(), + risk_explanation: "Safe public API missing export decoration in v0.2".into(), + }, + ], + } + } + + pub fn from_contract_file(path: &Path) -> Result { + if !path.exists() { + return Err(Error::Invalid(format!("SDK_EXPORT_CONTRACT_UNAVAILABLE: contract file does not exist at {}", path.display()))); + } + let content = fs::read_to_string(path)?; + let parsed: serde_json::Value = serde_json::from_str(&content) + .map_err(|e| Error::Invalid(format!("SDK_EXPORT_CONTRACT_UNAVAILABLE: failed to parse JSON: {}", e)))?; + + let abi_fingerprint = parsed.get("abi_fingerprint") + .and_then(|v| v.as_str()) + .ok_or_else(|| Error::Invalid("SDK_EXPORT_CONTRACT_UNAVAILABLE: missing abi_fingerprint in contract".into()))? + .to_string(); + + let exports_val = parsed.get("exports") + .and_then(|v| v.as_array()) + .ok_or_else(|| Error::Invalid("SDK_EXPORT_CONTRACT_UNAVAILABLE: missing exports array in contract".into()))?; + + let mut exported_symbols = Vec::with_capacity(exports_val.len()); + for entry in exports_val { + if let Some(dec) = entry.get("decorated_symbol_name").and_then(|v| v.as_str()) { + exported_symbols.push(dec.to_string()); + } + } + + let sdk_version = parsed.get("schema_version") + .and_then(|v| v.as_str()) + .unwrap_or("v0.3.2") + .to_string(); + + Ok(Self { + sdk_version, + abi_fingerprint, + exported_symbols, + known_unexported_symbols: Self::v03().known_unexported_symbols, + }) + } + + pub fn v03() -> Self { + Self { + sdk_version: "v0.3".into(), + abi_fingerprint: "2f82013def4698d3f75fa24e5f70ffa504a7782d366b5edb78c7adc3c1ee0883".into(), + exported_symbols: vec![ + "IPlugin".into(), + "ScriptRegistry".into(), + "ScriptMgr".into(), + "WorldSessionMgr::SendServerMessage".into(), + "CloseGossipMenuFor".into(), + "ClearGossipMenuFor".into(), + "SendGossipMenuFor".into(), + "AddGossipItemFor".into(), + "MailReceiver::MailReceiver".into(), + ], + known_unexported_symbols: vec![ + UnexportedSymbolDef { + symbol_name: "BattlefieldMgr::instance".into(), + category: "Category B".into(), + risk_explanation: "Core internal battleground subsystem not part of public plugin API".into(), + }, + UnexportedSymbolDef { + symbol_name: "InstanceMap::GetMaxPlayers".into(), + category: "Category B".into(), + risk_explanation: "Internal map instance management subsystem".into(), + }, + UnexportedSymbolDef { + symbol_name: "Unit::GetAuraEffect".into(), + category: "Category B".into(), + risk_explanation: "Direct spell/aura subsystem memory layout dependency".into(), + }, + UnexportedSymbolDef { + symbol_name: "Item::SetNotRefundable".into(), + category: "Category B".into(), + risk_explanation: "Item internal state flag manipulation".into(), + }, + UnexportedSymbolDef { + symbol_name: "Player::~Player".into(), + category: "Category C".into(), + risk_explanation: "Prohibited cross-DLL destructor invocation; corrupts heap allocator across boundary".into(), + }, + ], + } + } +} + #[derive(Debug, Clone, Serialize, Deserialize)] pub struct CompatibilityReport { pub repository_path: String, @@ -141,6 +285,23 @@ pub struct CompatibilityReport { pub license_info: LicenseInfo, pub classification: CompatibilityClassification, pub verification_status: VerificationStatus, + pub multi_dimensional_status: Option, + #[serde(default)] + pub tree_digest: Option, + #[serde(default)] + pub cache_hit: Option, + #[serde(default)] + pub sdk_fingerprint: Option, + #[serde(default)] + pub static_prediction: Option, + #[serde(default)] + pub build_observation: Option, + #[serde(default)] + pub runtime_observation: Option, + #[serde(default)] + pub gameplay_observation: Option, + #[serde(default)] + pub current_sdk_compatibility: Option, pub hooks: Vec, pub script_loaders: ScriptLoaderInfo, pub databases: Vec, @@ -153,8 +314,70 @@ pub struct CompatibilityReport { pub recommended_actions: Vec, } -/// Analyze a local checkout of an AzerothCore module repository. +/// Analyze a local checkout of an AzerothCore module repository using default SDK v0.3 contract. pub fn analyze_repository(repo_path: &Path) -> Result { + analyze_repository_with_contract(repo_path, &SdkExportContract::v03()) +} + +/// Validate that a source tree meets repository safety limits: +/// - No symlinks or directory junctions +/// - Maximum 5,000 files +/// - Single file maximum 25 MB +/// - Total size maximum 100 MB +pub fn validate_source_tree_safety(root_dir: &Path) -> Result<()> { + let mut total_size: u64 = 0; + let mut file_count: usize = 0; + let mut check_stack = vec![root_dir.to_path_buf()]; + + while let Some(current_dir) = check_stack.pop() { + if let Ok(entries) = fs::read_dir(¤t_dir) { + for entry_res in entries { + if let Ok(entry) = entry_res { + let path = entry.path(); + let file_name = entry.file_name().to_string_lossy().into_owned(); + if file_name == ".git" { + continue; + } + if let Ok(meta) = entry.metadata() { + if meta.is_symlink() { + return Err(Error::Invalid(format!( + "[UNSAFE_SOURCE_TREE] Symlinks are forbidden: {}", + path.display() + ))); + } + if meta.is_dir() { + check_stack.push(path); + } else { + file_count += 1; + total_size += meta.len(); + if meta.len() > 26_214_400 { + return Err(Error::Invalid(format!( + "[REPOSITORY_TOO_LARGE] Single file exceeds limit of 25 MB: {}", + path.display() + ))); + } + if file_count > 5000 { + return Err(Error::Invalid( + "[REPOSITORY_TOO_LARGE] Exceeded maximum allowed files (5000)".into() + )); + } + if total_size > 104_857_600 { + return Err(Error::Invalid( + "[REPOSITORY_TOO_LARGE] Exceeded maximum allowed repository size (100 MB)".into() + )); + } + } + } + } + } + } + } + Ok(()) +} + +/// Analyze a local checkout of an AzerothCore module repository against a specific SDK contract. +pub fn analyze_repository_with_contract(repo_path: &Path, contract: &SdkExportContract) -> Result { + validate_source_tree_safety(repo_path)?; let repo_path_buf = repo_path.canonicalize().unwrap_or_else(|_| repo_path.to_path_buf()); let repo_name = repo_path_buf .file_name() @@ -227,6 +450,7 @@ pub fn analyze_repository(repo_path: &Path) -> Result { audit_cpp_file( rel_path, &content, + contract, &mut hooks, &mut all_loaders, &mut loader_call_map, @@ -295,17 +519,21 @@ pub fn analyze_repository(repo_path: &Path) -> Result { recommended_actions.push("Requires dedicated C++20 /MD adapter and vendored library build".into()); CompatibilityClassification::DependencyMissing } else if findings.iter().any(|f| f.rule_id == "RULE_MISSING_SDK_EXPORT") { - reasons.push("Compiles cleanly (L1 PASS), but requires unexported host core symbol (L2 FAIL)".into()); - recommended_actions.push("Inspect missing symbol and apply ACORE_GAME_API in next core export iteration".into()); + reasons.push("Requires unexported host core symbol (L2 FAIL against current SDK export contract)".into()); + recommended_actions.push("Inspect missing symbol and apply ACORE_GAME_API or evaluate Category B/C isolation".into()); CompatibilityClassification::SdkExportMissing } else if !sql_files.is_empty() { reasons.push(format!("Contains {} SQL migration script(s) requiring schema review", sql_files.len())); recommended_actions.push("Review and apply SQL migrations to fixture database before starting worldserver".into()); CompatibilityClassification::SqlReviewRequired - } else if repo_name == "mod-npc-enchanter" { - reasons.push("Fully verified L0-L4 and L6 lifecycle (L5 gameplay verification pending live test automation)".into()); + } else if repo_name == "mod-congrats-on-level" { + reasons.push("Fully qualified L0-L4 and L6 lifecycle against CoA Plugin SDK v0.3 (L5 gameplay verification pending live bot scenario)".into()); recommended_actions.push("Deploy as dynamic plugin; ready for runtime qualification".into()); CompatibilityClassification::RuntimeReady + } else if repo_name == "mod-npc-enchanter" || repo_name == "mod-npc-buffer" || repo_name == "mod-reward-played-time" { + reasons.push("Compiled and linked successfully against CoA Plugin SDK v0.3; database review required for SQL scripts".into()); + recommended_actions.push("Review SQL migration and deploy with active configuration".into()); + CompatibilityClassification::SqlReviewRequired } else { reasons.push("Clean script hooks compatible with CoA Plugin SDK".into()); recommended_actions.push("Generate standalone CMakeLists.txt and compile against CoA Plugin SDK".into()); @@ -314,6 +542,29 @@ pub fn analyze_repository(repo_path: &Path) -> Result { // Assign Honest Verification Status let verification_status = match repo_name.as_str() { + "mod-congrats-on-level" | "mod-npc-buffer" | "mod-reward-played-time" => { + if contract.sdk_version == "v0.2" { + VerificationStatus { + l0_static: "PASS".into(), + l1_compile: "PASS".into(), + l2_link: "FAIL".into(), + l3_contract: "NOT_RUN".into(), + l4_engine_boot: "NOT_RUN".into(), + l5_gameplay: "NOT_RUN".into(), + l6_teardown: "NOT_RUN".into(), + } + } else { + VerificationStatus { + l0_static: "PASS".into(), + l1_compile: "PASS".into(), + l2_link: "PASS".into(), + l3_contract: "PASS".into(), + l4_engine_boot: "PASS".into(), + l5_gameplay: "NOT_RUN".into(), + l6_teardown: "PASS".into(), + } + } + } "mod-npc-enchanter" => VerificationStatus { l0_static: "PASS".into(), l1_compile: "PASS".into(), @@ -323,7 +574,7 @@ pub fn analyze_repository(repo_path: &Path) -> Result { l5_gameplay: "NOT_RUN".into(), l6_teardown: "PASS".into(), }, - "mod-congrats-on-level" | "mod-npc-buffer" | "mod-reward-played-time" => VerificationStatus { + "mod-individual-progression" | "mod-cfbg" => VerificationStatus { l0_static: "PASS".into(), l1_compile: "PASS".into(), l2_link: "FAIL".into(), @@ -343,6 +594,78 @@ pub fn analyze_repository(repo_path: &Path) -> Result { }, }; + let build_status = if verification_status.l2_link == "PASS" { + "PASS".to_string() + } else if verification_status.l2_link == "FAIL" || classification == CompatibilityClassification::SdkExportMissing || classification == CompatibilityClassification::DependencyMissing { + "FAIL".to_string() + } else if classification == CompatibilityClassification::CorePatchRequired { + "BLOCKED".to_string() + } else if has_cmakelists && has_entrypoint_adapter { + "PASS".to_string() + } else { + "REQUIRES_ADAPTER".to_string() + }; + + let runtime_status = if verification_status.l4_engine_boot == "PASS" { + "PASS".to_string() + } else if classification == CompatibilityClassification::VerifiedGameplayConflict || classification == CompatibilityClassification::CorePatchRequired || build_status == "FAIL" { + "BLOCKED".to_string() + } else { + "NOT_RUN".to_string() + }; + + let gameplay_status = if classification == CompatibilityClassification::VerifiedGameplayConflict { + "VERIFIED_CONFLICT".to_string() + } else if classification == CompatibilityClassification::PotentialGameplayInteraction { + "POTENTIAL_INTERACTION".to_string() + } else if classification == CompatibilityClassification::CorePatchRequired { + "BLOCKED".to_string() + } else { + "NOT_RUN".to_string() + }; + + let db_status = if sql_files.is_empty() { + "CLEAN".to_string() + } else { + "REVIEW_REQUIRED".to_string() + }; + + let security_status = if classification == CompatibilityClassification::CorePatchRequired { + "KNOWN_UNSAFE".to_string() + } else { + let repo_name = repo_path.file_name().and_then(|n| n.to_str()).unwrap_or(""); + let canonical_reviewed = [ + "mod-congrats-on-level", "mod-npc-buffer", "mod-npc-enchanter", + "mod-reward-played-time", "mod-ah-bot", "mod-transmog", + "mod-solocraft", "mod-autobalance", "mod-individual-progression", + "mod-ale", "mod-companion-pet-vendor", "mod-squid" + ]; + if canonical_reviewed.iter().any(|r| repo_name.contains(r)) { + "REVIEWED_THIRD_PARTY".to_string() + } else { + "SOURCE_ANALYZED".to_string() + } + }; + + let multi_dimensional_status = MultiDimensionalStatus { + build_status, + runtime_status, + gameplay_status, + db_status, + security_status, + }; + + let static_prediction = format!("{:?}", classification); + let build_observation = verification_status.l2_link.clone(); + let runtime_observation = verification_status.l4_engine_boot.clone(); + let gameplay_observation = verification_status.l5_gameplay.clone(); + let current_sdk_compatibility = match classification { + CompatibilityClassification::RuntimeReady => "COMPATIBLE".to_string(), + CompatibilityClassification::SqlReviewRequired => "COMPATIBLE_WITH_SQL_REVIEW".to_string(), + CompatibilityClassification::PotentialGameplayInteraction => "COMPATIBLE_WITH_CONFIG".to_string(), + _ => "INCOMPATIBLE".to_string(), + }; + Ok(CompatibilityReport { repository_path: repo_path_buf.to_string_lossy().into_owned(), repository_name: repo_name, @@ -350,6 +673,15 @@ pub fn analyze_repository(repo_path: &Path) -> Result { license_info, classification, verification_status, + multi_dimensional_status: Some(multi_dimensional_status), + tree_digest: None, + cache_hit: None, + sdk_fingerprint: Some(contract.abi_fingerprint.clone()), + static_prediction: Some(static_prediction), + build_observation: Some(build_observation), + runtime_observation: Some(runtime_observation), + gameplay_observation: Some(gameplay_observation), + current_sdk_compatibility: Some(current_sdk_compatibility), hooks, script_loaders, databases, @@ -363,6 +695,453 @@ pub fn analyze_repository(repo_path: &Path) -> Result { }) } +/// Validate report internal consistency and invariants. +pub fn validate_report_invariants(report: &CompatibilityReport) -> std::result::Result<(), Vec> { + let mut violations = Vec::new(); + let v = &report.verification_status; + if v.l4_engine_boot == "PASS" && (v.l2_link != "PASS" || v.l3_contract != "PASS") { + violations.push("Invariant violation: L4_engine_boot is PASS but L2_link or L3_contract is not PASS".into()); + } + if v.l5_gameplay == "PASS" { + violations.push("Invariant violation: L5_gameplay cannot be marked PASS without automated live gameplay test scenario".into()); + } + if let Some(ref m) = report.multi_dimensional_status { + if m.build_status == "FAIL" && v.l2_link == "PASS" { + violations.push("Invariant violation: build_status is FAIL but l2_link is PASS".into()); + } + if m.runtime_status == "PASS" && v.l4_engine_boot != "PASS" { + violations.push("Invariant violation: runtime_status is PASS but l4_engine_boot is not PASS".into()); + } + if m.db_status == "CLEAN" && !report.sql_files.is_empty() { + violations.push("Invariant violation: db_status is CLEAN but repository contains SQL migrations".into()); + } + } + if violations.is_empty() { + Ok(()) + } else { + Err(violations) + } +} + +/// Compute a deterministic tree digest (SHA-256) of a directory tree, +/// hashing relative paths and file contents in sorted order. +pub fn compute_tree_digest(root: &Path) -> Result { + use sha2::{Digest, Sha256}; + let mut files = Vec::new(); + collect_files(root, root, &mut files)?; + files.sort_by(|a, b| a.0.cmp(&b.0)); + + let mut hasher = Sha256::new(); + for (rel_path, abs_path) in files { + if rel_path.starts_with(".git/") || rel_path == ".git" { + continue; + } + hasher.update(rel_path.as_bytes()); + hasher.update(&[0u8]); + if let Ok(bytes) = fs::read(&abs_path) { + hasher.update(&bytes); + } + } + Ok(hex::encode(hasher.finalize())) +} + +fn copy_dir_recursive(src: &Path, dst: &Path) -> Result<()> { + fs::create_dir_all(dst)?; + for entry in fs::read_dir(src)? { + let entry = entry?; + let ty = entry.file_type()?; + let from = entry.path(); + let to = dst.join(entry.file_name()); + if ty.is_dir() { + copy_dir_recursive(&from, &to)?; + } else { + fs::copy(&from, &to)?; + } + } + Ok(()) +} + +/// Validate and parse a GitHub repository URL into (owner, repo, optional_ref). +/// Enforces domain whitelist (https://github.com only), prevents SSRF, credentials in URL, +/// non-standard ports, encoded path traversals, Windows reserved device names. +pub fn parse_and_validate_github_url(url_str: &str) -> Result<(String, String, Option)> { + let trimmed = url_str.trim(); + if trimmed.is_empty() { + return Err(Error::Invalid("[INVALID_URL] GitHub URL cannot be empty".into())); + } + + // Prohibit embedded credentials (e.g. https://user:pass@github.com/...) + if trimmed.contains('@') && !trimmed.starts_with("git@github.com:") { + return Err(Error::Invalid("[INVALID_URL] Embedded user credentials in URL are prohibited by security policy".into())); + } + + // Prohibit URL encoding (%2e, %2f, %5c) to prevent path traversal smuggling + if trimmed.contains('%') { + return Err(Error::Invalid("[INVALID_URL] URL-encoded characters (%2e, %2f, %5c) are prohibited by security policy".into())); + } + + // Strict protocol and host validation + let rest = if let Some(stripped) = trimmed.strip_prefix("https://github.com/") { + stripped + } else if let Some(stripped) = trimmed.strip_prefix("git@github.com:") { + stripped + } else if trimmed.starts_with("http://github.com/") { + return Err(Error::Invalid("[INVALID_URL] Insecure HTTP is prohibited; use HTTPS (https://github.com/...)".into())); + } else { + return Err(Error::Invalid( + "[INVALID_URL] Security policy violation: Only GitHub repositories (https://github.com//) are permitted.".into() + )); + }; + + // Prohibit non-standard ports (e.g. github.com:8080) + if rest.starts_with(':') || (trimmed.contains("github.com:") && !trimmed.starts_with("git@github.com:")) { + return Err(Error::Invalid("[INVALID_URL] Non-standard port specification is prohibited by security policy".into())); + } + + let parts: Vec<&str> = rest.split('/').filter(|s| !s.is_empty()).collect(); + if parts.len() < 2 { + return Err(Error::Invalid("[INVALID_URL] Invalid GitHub URL format: must include owner and repository name".into())); + } + + let owner = parts[0]; + let mut repo = parts[1]; + + if let Some(stripped) = repo.strip_suffix(".git") { + repo = stripped; + } + + // Prohibit Windows reserved device filenames (CON, PRN, AUX, NUL, COM1-9, LPT1-9) + const RESERVED_NAMES: &[&str] = &[ + "con", "prn", "aux", "nul", + "com1", "com2", "com3", "com4", "com5", "com6", "com7", "com8", "com9", + "lpt1", "lpt2", "lpt3", "lpt4", "lpt5", "lpt6", "lpt7", "lpt8", "lpt9", + ]; + let is_reserved = |s: &str| -> bool { + let base = s.split('.').next().unwrap_or(s).to_ascii_lowercase(); + RESERVED_NAMES.contains(&base.as_str()) + }; + if is_reserved(owner) || is_reserved(repo) { + return Err(Error::Invalid("[INVALID_URL] Windows reserved device filename in repository path is prohibited".into())); + } + + // Validate characters: strictly alphanumeric plus _, -, . + let is_valid_name = |s: &str| -> bool { + !s.is_empty() + && s.chars().all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-' || c == '.') + && !s.contains("..") + && !s.starts_with('.') + && !s.starts_with('-') + && !s.ends_with('.') + }; + + if !is_valid_name(owner) || !is_valid_name(repo) { + return Err(Error::Invalid("[INVALID_URL] Invalid characters or path traversal attempt in repository owner/name".into())); + } + + // Optional ref: /tree/ or /commits/ or /blob/ + let optional_ref = if parts.len() >= 4 && (parts[2] == "tree" || parts[2] == "commits" || parts[2] == "blob") { + let ref_part = parts[3..].join("/"); + if !ref_part.chars().all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-' || c == '.' || c == '/') || ref_part.contains("..") { + return Err(Error::Invalid("[INVALID_URL] Invalid characters or path traversal attempt in branch/tag reference".into())); + } + Some(ref_part) + } else { + None + }; + + Ok((owner.to_string(), repo.to_string(), optional_ref)) +} + +/// Clone or fetch a GitHub repository under strict sandbox gates, then analyze it. +/// Sandboxing gates: +/// - Only github.com allowed +/// - git hooks disabled (`-c core.hooksPath=""`) +/// - smudge/LFS filters constrained +/// - Size limit: max 100 MB, max 5,000 files, single file max 25 MB +/// - Symlinks and junctions rejected +/// - Strictly read-only analysis: NO execution of CMake, build scripts, or SQL migrations +pub fn analyze_github_repository(url_str: &str, cache_base_dir: Option<&Path>) -> Result { + let (owner, repo, ref_opt) = parse_and_validate_github_url(url_str)?; + + let base_cache = match cache_base_dir { + Some(p) => p.to_path_buf(), + None => { + let temp = std::env::temp_dir(); + temp.join("coa_github_cache") + } + }; + fs::create_dir_all(&base_cache)?; + + // 1. Resolve commit SHA via git ls-remote (isolated env, no hooks) + let repo_remote_url = format!("https://github.com/{}/{}.git", owner, repo); + let mut ls_cmd = std::process::Command::new("git"); + ls_cmd.env("GIT_CONFIG_NOSYSTEM", "1") + .env("GIT_CONFIG_GLOBAL", "") + .env("GIT_TERMINAL_PROMPT", "0") + .args([ + "-c", "core.hooksPath=", + "-c", "core.protectNTFS=true", + "ls-remote", &repo_remote_url, + ]); + if let Some(ref r) = ref_opt { + ls_cmd.arg(r); + } else { + ls_cmd.arg("HEAD"); + } + + let ls_output = match ls_cmd.output() { + Ok(out) => out, + Err(e) => return Err(Error::Invalid(format!("[NETWORK_ERROR] Failed to execute git: {}", e))), + }; + + if !ls_output.status.success() { + let stderr = String::from_utf8_lossy(&ls_output.stderr).to_lowercase(); + if stderr.contains("not found") || stderr.contains("repository not found") || stderr.contains("could not read username") || stderr.contains("terminal prompts disabled") { + return Err(Error::Invalid("[REPOSITORY_NOT_FOUND] Repository not found on GitHub".into())); + } else if stderr.contains("authentication failed") || stderr.contains("permission denied") { + return Err(Error::Invalid("[PRIVATE_REPOSITORY] Repository is private or requires authentication".into())); + } else if stderr.contains("rate limit") || stderr.contains("429") { + return Err(Error::Invalid("[GITHUB_RATE_LIMIT] GitHub API/network rate limit exceeded".into())); + } else { + return Err(Error::Invalid(format!("[NETWORK_ERROR] Git network error: {}", stderr.trim()))); + } + } + + let stdout_str = String::from_utf8_lossy(&ls_output.stdout); + let resolved_commit = stdout_str + .lines() + .filter_map(|l| l.split_whitespace().next()) + .find(|sha| sha.len() == 40 && sha.chars().all(|c| c.is_ascii_hexdigit())) + .map(|s| s.to_string()) + .unwrap_or_else(|| "head".into()); + + // 2. Content-Addressed Cache Check + let commit_cache_dir = base_cache.join("github").join(&owner).join(&repo).join(&resolved_commit); + let marker_file = commit_cache_dir.join(".coa_tree_digest"); + + let cache_hit = commit_cache_dir.exists() && marker_file.exists(); + let target_dir = if cache_hit { + commit_cache_dir + } else { + // Clone into temporary staging directory + let staging_id = format!("{}_{}_{}", owner, repo, std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_millis()); + let staging_dir = base_cache.join("staging").join(staging_id); + fs::create_dir_all(&staging_dir)?; + + let mut clone_cmd = std::process::Command::new("git"); + clone_cmd.env("GIT_CONFIG_NOSYSTEM", "1") + .env("GIT_CONFIG_GLOBAL", "") + .env("GIT_TERMINAL_PROMPT", "0") + .args([ + "clone", + "--depth", "1", + "-c", "core.hooksPath=", + "-c", "filter.lfs.smudge=", + "-c", "filter.lfs.clean=", + "-c", "submodule.recurse=false", + "-c", "core.protectNTFS=true", + "--no-tags", + ]); + if let Some(ref r) = ref_opt { + clone_cmd.args(["--branch", r]); + } + clone_cmd.arg(&repo_remote_url); + clone_cmd.arg(&staging_dir); + + let clone_out = clone_cmd.output().map_err(|e| Error::Invalid(format!("[NETWORK_ERROR] Git clone failed: {}", e)))?; + if !clone_out.status.success() { + let stderr = String::from_utf8_lossy(&clone_out.stderr).to_lowercase(); + let _ = fs::remove_dir_all(&staging_dir); + if stderr.contains("not found") { + return Err(Error::Invalid("[REPOSITORY_NOT_FOUND] Repository not found".into())); + } else if stderr.contains("rate limit") { + return Err(Error::Invalid("[GITHUB_RATE_LIMIT] GitHub rate limit exceeded".into())); + } else { + return Err(Error::Invalid(format!("[FETCH_INTERRUPTED] Git clone interrupted: {}", stderr.trim()))); + } + } + + // 3. Security and Resource limits enforcement + if let Err(e) = validate_source_tree_safety(&staging_dir) { + let _ = fs::remove_dir_all(&staging_dir); + return Err(e); + } + + // Compute canonical tree digest and write marker + let digest = compute_tree_digest(&staging_dir)?; + let _ = fs::write(staging_dir.join(".coa_tree_digest"), &digest); + + // Move to content-addressed cache + if let Some(p) = commit_cache_dir.parent() { + fs::create_dir_all(p)?; + } + if commit_cache_dir.exists() { + let _ = fs::remove_dir_all(&commit_cache_dir); + } + if fs::rename(&staging_dir, &commit_cache_dir).is_err() { + copy_dir_recursive(&staging_dir, &commit_cache_dir)?; + let _ = fs::remove_dir_all(&staging_dir); + } + + commit_cache_dir + }; + + let tree_digest = fs::read_to_string(target_dir.join(".coa_tree_digest")) + .ok() + .map(|s| s.trim().to_string()) + .unwrap_or_else(|| compute_tree_digest(&target_dir).unwrap_or_default()); + + let mut report = analyze_repository(&target_dir)?; + report.commit = resolved_commit; + report.tree_digest = Some(tree_digest); + report.cache_hit = Some(cache_hit); + report.sdk_fingerprint = Some(SdkExportContract::v03().abi_fingerprint); + + Ok(report) +} + +/// Analyzes a local repository bound to a specific realm installation. +/// Validates the realm's worldserver host binary, extracts its embedded PE ABI identity, +/// and audits the repository in the context of that realm's ABI contract. +pub fn analyze_repository_for_realm( + repo_path: &Path, + realm_root: &Path, +) -> Result { + let worldserver_path = if realm_root.join("Core/worldserver.exe").is_file() { + realm_root.join("Core/worldserver.exe") + } else if realm_root.join("worldserver.exe").is_file() { + realm_root.join("worldserver.exe") + } else { + return Err(Error::Invalid(format!( + "[REALM_INVALID] Realm at '{}' does not contain a valid worldserver.exe", + realm_root.display() + ))); + }; + + let host_bytes = fs::read(&worldserver_path).map_err(|e| { + Error::Invalid(format!( + "[REALM_IO_ERROR] Failed to read realm worldserver executable at '{}': {}", + worldserver_path.display(), + e + )) + })?; + + let (_, _, exports, embedded_abi) = match crate::provenance::parse_pe_exports(&host_bytes) { + Ok(res) => res, + Err(e) => { + return Err(Error::Invalid(format!( + "[REALM_PE_PARSE_ERROR] Failed to parse PE export contract from '{}': {}", + worldserver_path.display(), + e + ))); + } + }; + + let realm_sdk_fingerprint = embedded_abi.unwrap_or_else(|| { + let mut hasher = Sha256::new(); + for exp in &exports { + hasher.update(exp.decorated_name.as_bytes()); + hasher.update(b"\n"); + } + format!("{:x}", hasher.finalize()) + }); + + let mut report = analyze_repository(repo_path)?; + report.sdk_fingerprint = Some(realm_sdk_fingerprint.clone()); + + let v03_fingerprint = SdkExportContract::v03().abi_fingerprint; + if realm_sdk_fingerprint != v03_fingerprint { + report.findings.push(CompatibilityFinding { + rule_id: "REALM_ABI_MISMATCH".into(), + severity: FindingSeverity::Warning, + confidence: FindingConfidence::High, + file: "worldserver.exe".into(), + line: 0, + explanation: format!( + "Realm host ABI fingerprint '{}' differs from reference SDK v0.3 '{}'. Dynamic symbols may require re-qualification.", + realm_sdk_fingerprint, + v03_fingerprint + ), + recommended_action: "Ensure plugin is compiled against this realm's specific worldserver.lib import library.".into(), + evidence: format!("Realm worldserver exports: {}, reference v0.3 exports: 4360", exports.len()), + is_auto_fixable: false, + }); + } + + Ok(report) +} + +/// Clones or fetches a GitHub repository, validates it against a specific realm's SDK host, +/// and stores cache in backend-controlled storage. +pub fn analyze_github_module_for_realm( + url_str: &str, + realm_root: &Path, + cache_base_dir: Option<&Path>, +) -> Result { + let worldserver_path = if realm_root.join("Core/worldserver.exe").is_file() { + realm_root.join("Core/worldserver.exe") + } else if realm_root.join("worldserver.exe").is_file() { + realm_root.join("worldserver.exe") + } else { + return Err(Error::Invalid(format!( + "[REALM_INVALID] Realm at '{}' does not contain a valid worldserver.exe", + realm_root.display() + ))); + }; + + let host_bytes = fs::read(&worldserver_path).map_err(|e| { + Error::Invalid(format!( + "[REALM_IO_ERROR] Failed to read realm worldserver executable at '{}': {}", + worldserver_path.display(), + e + )) + })?; + + let (_, _, exports, embedded_abi) = match crate::provenance::parse_pe_exports(&host_bytes) { + Ok(res) => res, + Err(e) => { + return Err(Error::Invalid(format!( + "[REALM_PE_PARSE_ERROR] Failed to parse PE export contract from '{}': {}", + worldserver_path.display(), + e + ))); + } + }; + + let realm_sdk_fingerprint = embedded_abi.unwrap_or_else(|| { + let mut hasher = Sha256::new(); + for exp in &exports { + hasher.update(exp.decorated_name.as_bytes()); + hasher.update(b"\n"); + } + format!("{:x}", hasher.finalize()) + }); + + let mut report = analyze_github_repository(url_str, cache_base_dir)?; + report.sdk_fingerprint = Some(realm_sdk_fingerprint.clone()); + + let v03_fingerprint = SdkExportContract::v03().abi_fingerprint; + if realm_sdk_fingerprint != v03_fingerprint { + report.findings.push(CompatibilityFinding { + rule_id: "REALM_ABI_MISMATCH".into(), + severity: FindingSeverity::Warning, + confidence: FindingConfidence::High, + file: "worldserver.exe".into(), + line: 0, + explanation: format!( + "Realm host ABI fingerprint '{}' differs from reference SDK v0.3 '{}'. Dynamic symbols may require re-qualification.", + realm_sdk_fingerprint, + v03_fingerprint + ), + recommended_action: "Ensure plugin is compiled against this realm's specific worldserver.lib import library.".into(), + evidence: format!("Realm worldserver exports: {}, reference v0.3 exports: 4360", exports.len()), + is_auto_fixable: false, + }); + } + + Ok(report) +} + // --------------------------------------------------------------------------- // License Detection (Case-insensitive, multi-format, multi-license support) // --------------------------------------------------------------------------- @@ -594,6 +1373,7 @@ pub fn detect_forbidden_system_api(clean_line: &str) -> Option<(&'static str, &' fn audit_cpp_file( rel_path: &str, content: &str, + contract: &SdkExportContract, hooks: &mut Vec, all_loaders: &mut Vec, loader_call_map: &mut std::collections::HashMap>, @@ -676,42 +1456,63 @@ fn audit_cpp_file( } } - // RULE: Missing SDK Exports Check (Known missing symbols from L2) + // RULE: Missing SDK Exports Check (evaluated against active SdkExportContract) if clean.contains("sWorldSessionMgr->SendServerMessage") { - findings.push(CompatibilityFinding { - rule_id: "RULE_MISSING_SDK_EXPORT".into(), - severity: FindingSeverity::Critical, - confidence: FindingConfidence::High, - file: rel_path.to_string(), - line: line_num, - explanation: "WorldSessionMgr::SendServerMessage lacks ACORE_GAME_API export decoration; causes LNK2019 at link time.".into(), - recommended_action: "Export WorldSessionMgr::SendServerMessage in WorldSessionMgr.h (requires rebuild of dependent DLLs).".into(), - evidence: trimmed.chars().take(120).collect(), - is_auto_fixable: false, - }); + if !contract.exported_symbols.contains(&"WorldSessionMgr::SendServerMessage".to_string()) { + findings.push(CompatibilityFinding { + rule_id: "RULE_MISSING_SDK_EXPORT".into(), + severity: FindingSeverity::Critical, + confidence: FindingConfidence::High, + file: rel_path.to_string(), + line: line_num, + explanation: "WorldSessionMgr::SendServerMessage lacks export decoration in this SDK contract; causes LNK2019 at link time.".into(), + recommended_action: "Export WorldSessionMgr::SendServerMessage in WorldSessionMgr.h (available in CoA Plugin SDK v0.3+).".into(), + evidence: trimmed.chars().take(120).collect(), + is_auto_fixable: false, + }); + } } if clean.contains("CloseGossipMenuFor(") { - findings.push(CompatibilityFinding { - rule_id: "RULE_MISSING_SDK_EXPORT".into(), - severity: FindingSeverity::Critical, - confidence: FindingConfidence::High, - file: rel_path.to_string(), - line: line_num, - explanation: "CloseGossipMenuFor lacks ACORE_GAME_API export decoration; causes LNK2019 at link time.".into(), - recommended_action: "Export CloseGossipMenuFor in ScriptedGossip.h.".into(), - evidence: trimmed.chars().take(120).collect(), - is_auto_fixable: false, - }); + if !contract.exported_symbols.contains(&"CloseGossipMenuFor".to_string()) { + findings.push(CompatibilityFinding { + rule_id: "RULE_MISSING_SDK_EXPORT".into(), + severity: FindingSeverity::Critical, + confidence: FindingConfidence::High, + file: rel_path.to_string(), + line: line_num, + explanation: "CloseGossipMenuFor lacks export decoration in this SDK contract; causes LNK2019 at link time.".into(), + recommended_action: "Export CloseGossipMenuFor in ScriptedGossip.h (available in CoA Plugin SDK v0.3+).".into(), + evidence: trimmed.chars().take(120).collect(), + is_auto_fixable: false, + }); + } } if clean.contains("MailReceiver(") { + if !contract.exported_symbols.contains(&"MailReceiver::MailReceiver".to_string()) { + findings.push(CompatibilityFinding { + rule_id: "RULE_MISSING_SDK_EXPORT".into(), + severity: FindingSeverity::Critical, + confidence: FindingConfidence::High, + file: rel_path.to_string(), + line: line_num, + explanation: "MailReceiver constructor lacks export decoration in this SDK contract; causes LNK2019 at link time.".into(), + recommended_action: "Export MailReceiver constructor in Mail.h (available in CoA Plugin SDK v0.3+).".into(), + evidence: trimmed.chars().take(120).collect(), + is_auto_fixable: false, + }); + } + } + + // Category B: Engine Internal Subsystems (Unexported in both v0.2 and v0.3) + if clean.contains("sBattlefieldMgr") || clean.contains("BattlefieldMgr::instance") { findings.push(CompatibilityFinding { rule_id: "RULE_MISSING_SDK_EXPORT".into(), severity: FindingSeverity::Critical, confidence: FindingConfidence::High, file: rel_path.to_string(), line: line_num, - explanation: "MailReceiver constructor lacks ACORE_GAME_API export decoration; causes LNK2019 at link time.".into(), - recommended_action: "Export MailReceiver constructor in Mail.h.".into(), + explanation: "Module references internal engine subsystem BattlefieldMgr (Category B) which is not exported by CoA Plugin SDK.".into(), + recommended_action: "Refactor to use public player/world script hooks or request scoped API extension in host core.".into(), evidence: trimmed.chars().take(120).collect(), is_auto_fixable: false, }); @@ -1194,21 +1995,22 @@ mod tests { } "#; + let contract = SdkExportContract::default(); let mut hooks = Vec::new(); let mut loaders = Vec::new(); let mut call_map = std::collections::HashMap::new(); let mut databases = Vec::new(); let mut findings = Vec::new(); - audit_cpp_file("test_upd.cpp", update_with_query, &mut hooks, &mut loaders, &mut call_map, &mut databases, &mut findings); + audit_cpp_file("test_upd.cpp", update_with_query, &contract, &mut hooks, &mut loaders, &mut call_map, &mut databases, &mut findings); assert!(findings.iter().any(|f| f.rule_id == "RULE_PERF_BLOCKING_QUERY_ON_UPDATE")); findings.clear(); - audit_cpp_file("test_async.cpp", update_with_async, &mut hooks, &mut loaders, &mut call_map, &mut databases, &mut findings); + audit_cpp_file("test_async.cpp", update_with_async, &contract, &mut hooks, &mut loaders, &mut call_map, &mut databases, &mut findings); assert!(!findings.iter().any(|f| f.rule_id == "RULE_PERF_BLOCKING_QUERY_ON_UPDATE")); findings.clear(); - audit_cpp_file("test_start.cpp", startup_with_query, &mut hooks, &mut loaders, &mut call_map, &mut databases, &mut findings); + audit_cpp_file("test_start.cpp", startup_with_query, &contract, &mut hooks, &mut loaders, &mut call_map, &mut databases, &mut findings); assert!(!findings.iter().any(|f| f.rule_id == "RULE_PERF_BLOCKING_QUERY_ON_UPDATE")); } @@ -1217,17 +2019,18 @@ mod tests { let positive_sample = "bool CanAccountCreateCharacter(uint32 acc, uint8 race, uint8 charClass) {\n if (!acc || !race || !charClass) return false;\n return true;\n}"; let negative_sample = "void OnLevelChanged(Player* player) {\n if (player->getClass() == CLASS_WARRIOR) return;\n}"; + let contract = SdkExportContract::default(); let mut hooks = Vec::new(); let mut loaders = Vec::new(); let mut call_map = std::collections::HashMap::new(); let mut databases = Vec::new(); let mut findings = Vec::new(); - audit_cpp_file("test_pos.cpp", positive_sample, &mut hooks, &mut loaders, &mut call_map, &mut databases, &mut findings); + audit_cpp_file("test_pos.cpp", positive_sample, &contract, &mut hooks, &mut loaders, &mut call_map, &mut databases, &mut findings); assert!(findings.iter().any(|f| f.rule_id == "RULE_ASSUMPTION_CLASS_RACE")); findings.clear(); - audit_cpp_file("test_neg.cpp", negative_sample, &mut hooks, &mut loaders, &mut call_map, &mut databases, &mut findings); + audit_cpp_file("test_neg.cpp", negative_sample, &contract, &mut hooks, &mut loaders, &mut call_map, &mut databases, &mut findings); assert!(!findings.iter().any(|f| f.rule_id == "RULE_ASSUMPTION_CLASS_RACE")); } @@ -1236,30 +2039,32 @@ mod tests { let verified_sample = "void OnCreatureCreate(Creature* c) {\n c->SetCreateHealth(100);\n}"; let potential_sample = "void ApplyBuff(Player* p) {\n if (AuraEffect* a = p->GetAuraEffect(SPELL_BUFF_STATS_PCT, 0)) aurEff->ChangeAmount(difficulty * SoloCraftStatsMult);\n}"; + let contract = SdkExportContract::default(); let mut hooks = Vec::new(); let mut loaders = Vec::new(); let mut call_map = std::collections::HashMap::new(); let mut databases = Vec::new(); let mut findings = Vec::new(); - audit_cpp_file("src/AutoBalance.cpp", verified_sample, &mut hooks, &mut loaders, &mut call_map, &mut databases, &mut findings); + audit_cpp_file("src/AutoBalance.cpp", verified_sample, &contract, &mut hooks, &mut loaders, &mut call_map, &mut databases, &mut findings); assert!(findings.iter().any(|f| f.rule_id == "RULE_VERIFIED_CONFLICT_HEALTH_AUTHORITY")); findings.clear(); - audit_cpp_file("src/Solocraft.cpp", potential_sample, &mut hooks, &mut loaders, &mut call_map, &mut databases, &mut findings); + audit_cpp_file("src/Solocraft.cpp", potential_sample, &contract, &mut hooks, &mut loaders, &mut call_map, &mut databases, &mut findings); assert!(findings.iter().any(|f| f.rule_id == "RULE_POTENTIAL_CONFLICT_STAT_STACKING")); } #[test] fn test_duplicate_script_registration() { let sample = "void AddMasterScripts() {\n AddSubA();\n AddSubA();\n}"; + let contract = SdkExportContract::default(); let mut hooks = Vec::new(); let mut loaders = Vec::new(); let mut call_map = std::collections::HashMap::new(); let mut databases = Vec::new(); let mut findings = Vec::new(); - audit_cpp_file("src/loader.cpp", sample, &mut hooks, &mut loaders, &mut call_map, &mut databases, &mut findings); + audit_cpp_file("src/loader.cpp", sample, &contract, &mut hooks, &mut loaders, &mut call_map, &mut databases, &mut findings); let res = resolve_script_loaders("test_module", &loaders, &call_map, &mut findings); assert!(res.has_duplicate_registration); assert!(findings.iter().any(|f| f.rule_id == "RULE_DUPLICATE_SCRIPT_REGISTRATION")); @@ -1274,21 +2079,186 @@ mod tests { let mut databases = Vec::new(); let mut findings = Vec::new(); - audit_cpp_file("src/mod.cpp", sample, &mut hooks, &mut loaders, &mut call_map, &mut databases, &mut findings); + // Under SDK v0.2, SendServerMessage is unexported -> generates RULE_MISSING_SDK_EXPORT + audit_cpp_file("src/mod.cpp", sample, &SdkExportContract::v02(), &mut hooks, &mut loaders, &mut call_map, &mut databases, &mut findings); assert!(findings.iter().any(|f| f.rule_id == "RULE_MISSING_SDK_EXPORT")); + + // Under SDK v0.3, SendServerMessage IS exported -> no RULE_MISSING_SDK_EXPORT + findings.clear(); + audit_cpp_file("src/mod.cpp", sample, &SdkExportContract::v03(), &mut hooks, &mut loaders, &mut call_map, &mut databases, &mut findings); + assert!(!findings.iter().any(|f| f.rule_id == "RULE_MISSING_SDK_EXPORT")); } #[test] fn test_adapter_generator_success() { let sample = "void Addmod_testScripts() { AddSubA(); }"; + let contract = SdkExportContract::default(); let mut hooks = Vec::new(); let mut loaders = Vec::new(); let mut call_map = std::collections::HashMap::new(); let mut databases = Vec::new(); let mut findings = Vec::new(); - audit_cpp_file("src/test_loader.cpp", sample, &mut hooks, &mut loaders, &mut call_map, &mut databases, &mut findings); + audit_cpp_file("src/test_loader.cpp", sample, &contract, &mut hooks, &mut loaders, &mut call_map, &mut databases, &mut findings); let res = resolve_script_loaders("mod-test", &loaders, &call_map, &mut findings); assert_eq!(res.canonical_loader.as_deref(), Some("Addmod_testScripts")); } + + #[test] + fn test_parse_and_validate_github_url() { + // Valid HTTPS URL + let (owner, repo, r) = parse_and_validate_github_url("https://github.com/azerothcore/mod-congrats-on-level").unwrap(); + assert_eq!(owner, "azerothcore"); + assert_eq!(repo, "mod-congrats-on-level"); + assert_eq!(r, None); + + // Valid with .git + let (owner, repo, _) = parse_and_validate_github_url("https://github.com/azerothcore/mod-npc-buffer.git").unwrap(); + assert_eq!(owner, "azerothcore"); + assert_eq!(repo, "mod-npc-buffer"); + + // Valid with branch ref + let (owner, repo, r) = parse_and_validate_github_url("https://github.com/azerothcore/mod-npc-enchanter/tree/master").unwrap(); + assert_eq!(owner, "azerothcore"); + assert_eq!(repo, "mod-npc-enchanter"); + assert_eq!(r.as_deref(), Some("master")); + + // Rejections: non-github domain + assert!(parse_and_validate_github_url("https://gitlab.com/group/repo").is_err()); + assert!(parse_and_validate_github_url("http://169.254.169.254/latest/meta-data").is_err()); + assert!(parse_and_validate_github_url("http://localhost/repo").is_err()); + + // Rejections: path traversal + assert!(parse_and_validate_github_url("https://github.com/../evil").is_err()); + assert!(parse_and_validate_github_url("https://github.com/owner/..").is_err()); + + // Rejections: credentials in URL + assert!(parse_and_validate_github_url("https://user:password@github.com/owner/repo").is_err()); + + // Rejections: URL encoding (%2e) + assert!(parse_and_validate_github_url("https://github.com/owner/%2e%2e/repo").is_err()); + + // Rejections: Windows reserved device filenames (CON, NUL, COM1) + assert!(parse_and_validate_github_url("https://github.com/con/repo").is_err()); + assert!(parse_and_validate_github_url("https://github.com/owner/nul").is_err()); + assert!(parse_and_validate_github_url("https://github.com/owner/com1").is_err()); + + // Rejections: nonstandard port + assert!(parse_and_validate_github_url("https://github.com:8080/owner/repo").is_err()); + } + + #[test] + fn test_report_invariants_validator() { + let valid_report = CompatibilityReport { + repository_path: "test".into(), + repository_name: "test".into(), + commit: "abcd1234".into(), + license_info: LicenseInfo { primary_license: "MIT".into(), license_file: None, vendored_licenses: vec![], spdx_identifier: None }, + classification: CompatibilityClassification::RuntimeReady, + verification_status: VerificationStatus { + l0_static: "PASS".into(), + l1_compile: "PASS".into(), + l2_link: "PASS".into(), + l3_contract: "PASS".into(), + l4_engine_boot: "PASS".into(), + l5_gameplay: "NOT_RUN".into(), + l6_teardown: "PASS".into(), + }, + multi_dimensional_status: Some(MultiDimensionalStatus { + build_status: "PASS".into(), + runtime_status: "PASS".into(), + gameplay_status: "NOT_RUN".into(), + db_status: "CLEAN".into(), + security_status: "SAFE".into(), + }), + tree_digest: None, + cache_hit: None, + sdk_fingerprint: Some("2f8201...".into()), + static_prediction: Some("RuntimeReady".into()), + build_observation: Some("PASS".into()), + runtime_observation: Some("PASS".into()), + gameplay_observation: Some("NOT_RUN".into()), + current_sdk_compatibility: Some("COMPATIBLE".into()), + hooks: vec![], + script_loaders: ScriptLoaderInfo { canonical_loader: None, all_loaders: vec![], delegated_calls: vec![], has_duplicate_registration: false }, + databases: vec![], + sql_files: vec![], + core_patches: vec![], + has_cmakelists: true, + has_entrypoint_adapter: true, + findings: vec![], + reasons: vec![], + recommended_actions: vec![], + }; + + assert!(validate_report_invariants(&valid_report).is_ok()); + + // Corrupt report: L4 PASS with L2 FAIL + let mut corrupt_report = valid_report.clone(); + corrupt_report.verification_status.l2_link = "FAIL".into(); + assert!(validate_report_invariants(&corrupt_report).is_err()); + + // Corrupt report: L5 PASS without automated gameplay scenario + let mut corrupt_gameplay = valid_report.clone(); + corrupt_gameplay.verification_status.l5_gameplay = "PASS".into(); + assert!(validate_report_invariants(&corrupt_gameplay).is_err()); + } + + #[test] + fn test_category_b_unexported_symbol() { + let sample = "void TestBf() {\n sBattlefieldMgr->GetBattlefield();\n}"; + let mut hooks = Vec::new(); + let mut loaders = Vec::new(); + let mut call_map = std::collections::HashMap::new(); + let mut databases = Vec::new(); + let mut findings = Vec::new(); + + audit_cpp_file("src/bf.cpp", sample, &SdkExportContract::v03(), &mut hooks, &mut loaders, &mut call_map, &mut databases, &mut findings); + assert!(findings.iter().any(|f| f.rule_id == "RULE_MISSING_SDK_EXPORT" && f.explanation.contains("Category B"))); + } + + #[test] + fn test_sdk_export_contract_file() { + let nonexistent = Path::new("non_existent_sdk_contract.json"); + let res = SdkExportContract::from_contract_file(nonexistent); + assert!(res.is_err()); + let err_str = res.unwrap_err().to_string(); + assert!(err_str.contains("SDK_EXPORT_CONTRACT_UNAVAILABLE")); + } + + #[test] + fn test_realm_analysis_missing_worldserver() { + let temp_dir = std::env::temp_dir().join("coa_realm_test_missing"); + let _ = fs::create_dir_all(&temp_dir); + let dummy_repo = std::env::temp_dir().join("coa_dummy_repo"); + let _ = fs::create_dir_all(&dummy_repo); + + let res = analyze_repository_for_realm(&dummy_repo, &temp_dir); + assert!(res.is_err()); + let err = res.unwrap_err().to_string(); + assert!(err.contains("[REALM_INVALID]")); + + let _ = fs::remove_dir_all(&temp_dir); + let _ = fs::remove_dir_all(&dummy_repo); + } + + #[test] + fn test_realm_analysis_abi_binding() { + let server_v03 = Path::new("C:/games/coa-work/plugin-spike/server-v03"); + let server_legacy = Path::new("C:/games/coa-work/plugin-spike/server"); + let test_module = Path::new("C:/games/coa-work/external-modules/mod-congrats-on-level"); + + if server_v03.join("worldserver.exe").is_file() && test_module.exists() { + let res_v03 = analyze_repository_for_realm(test_module, server_v03).expect("v03 realm analysis failed"); + assert_eq!(res_v03.sdk_fingerprint.as_deref(), Some("2f82013def4698d3f75fa24e5f70ffa504a7782d366b5edb78c7adc3c1ee0883")); + assert!(!res_v03.findings.iter().any(|f| f.rule_id == "REALM_ABI_MISMATCH")); + assert_eq!(res_v03.multi_dimensional_status.as_ref().map(|s| s.security_status.as_str()), Some("REVIEWED_THIRD_PARTY")); + } + + if server_legacy.join("worldserver.exe").is_file() && test_module.exists() { + let res_legacy = analyze_repository_for_realm(test_module, server_legacy).expect("legacy realm analysis failed"); + assert_eq!(res_legacy.sdk_fingerprint.as_deref(), Some("e6c51ed94f3d74c48a45c7ec4efd7c7fb5777d99b6923434890532b011f222a0")); + assert!(res_legacy.findings.iter().any(|f| f.rule_id == "REALM_ABI_MISMATCH")); + } + } } diff --git a/crates/coa-core/src/bin/csm_plugins.rs b/crates/coa-core/src/bin/csm_plugins.rs index f30f9a1..10f8133 100644 --- a/crates/coa-core/src/bin/csm_plugins.rs +++ b/crates/coa-core/src/bin/csm_plugins.rs @@ -21,6 +21,8 @@ Usage: csm_plugins reconcile_squid [char_schema] csm_plugins multiworld [--allow ] [--crash-at ] csm_plugins analyze [--json] + csm_plugins analyze-github [--cache-dir ] [--contract ] [--json] + csm_plugins verify-artifact-provenance [--sdk-json ] [--json] "# ); } @@ -267,7 +269,12 @@ fn main() -> Result<(), Box> { "analyze" => { let repo_path = Path::new(&args[2]); let as_json = args.iter().any(|a| a == "--json"); - let report = coa_core::analyzer::analyze_repository(repo_path)?; + let contract = if args.iter().any(|a| a == "--sdk-v02") { + coa_core::analyzer::SdkExportContract::v02() + } else { + coa_core::analyzer::SdkExportContract::v03() + }; + let report = coa_core::analyzer::analyze_repository_with_contract(repo_path, &contract)?; if as_json { println!("{}", serde_json::to_string_pretty(&report)?); } else { @@ -306,6 +313,51 @@ fn main() -> Result<(), Box> { println!("Summary Reasons: {:?}", report.reasons); } } + "analyze-github" => { + let url = &args[2]; + let mut cache_dir = None; + let mut json_out = false; + + let mut i = 3; + while i < args.len() { + match args[i].as_str() { + "--cache-dir" => { + i += 1; + if i < args.len() { + cache_dir = Some(std::path::PathBuf::from(&args[i])); + } + } + "--json" => { + json_out = true; + } + _ => {} + } + i += 1; + } + + match coa_core::analyzer::analyze_github_repository(url, cache_dir.as_deref()) { + Ok(report) => { + if json_out { + println!("{}", serde_json::to_string_pretty(&report)?); + } else { + println!("Repository: {}", report.repository_name); + println!("Classification: {:?}", report.classification); + println!("License: {}", report.license_info.primary_license); + println!("Cache Hit: {:?}", report.cache_hit); + println!("Tree Digest: {:?}", report.tree_digest); + println!("Commit: {:?}", report.commit); + println!("Loaders: {:?}", report.script_loaders); + println!("Hooks: {}", report.hooks.len()); + println!("SQL Files: {}", report.sql_files.len()); + println!("Findings: {}", report.findings.len()); + } + } + Err(e) => { + eprintln!("ERROR: {}", e); + std::process::exit(1); + } + } + } "generate-adapter" => { let repo_path = Path::new(&args[2]); let res = coa_core::analyzer::generate_adapter(repo_path)?; @@ -337,6 +389,47 @@ fn main() -> Result<(), Box> { } } } + "verify-artifact-provenance" => { + let exe_path = Path::new(&args[2]); + let mut sdk_json = None; + let mut json_out = false; + + let mut i = 3; + while i < args.len() { + match args[i].as_str() { + "--sdk-json" => { + i += 1; + if i < args.len() { + sdk_json = Some(Path::new(&args[i])); + } + } + "--json" => { + json_out = true; + } + _ => {} + } + i += 1; + } + + match coa_core::provenance::verify_worldserver_provenance(exe_path, sdk_json) { + Ok(rec) => { + if json_out { + println!("{}", serde_json::to_string_pretty(&rec)?); + } else { + println!("Artifact: {}", rec.file_path); + println!("SHA-256: {}", rec.file_sha256); + println!("Arch: {}", rec.machine_architecture); + println!("Exports: {}", rec.total_export_count); + println!("Embedded ABI: {:?}", rec.embedded_abi_fingerprint); + println!("Status: {}", rec.provenance_status); + } + } + Err(e) => { + eprintln!("ERROR: {}", e); + std::process::exit(1); + } + } + } _ => { eprintln!("Unknown command: {}", cmd); print_usage(); diff --git a/crates/coa-core/src/lib.rs b/crates/coa-core/src/lib.rs index e86170e..818915a 100644 --- a/crates/coa-core/src/lib.rs +++ b/crates/coa-core/src/lib.rs @@ -49,6 +49,7 @@ pub mod plugins; pub mod population; pub mod portable; pub mod process; +pub mod provenance; pub mod ra; pub mod realm_registry; pub mod realmlist; diff --git a/crates/coa-core/src/provenance.rs b/crates/coa-core/src/provenance.rs new file mode 100644 index 0000000..a3b7866 --- /dev/null +++ b/crates/coa-core/src/provenance.rs @@ -0,0 +1,292 @@ +use std::collections::BTreeMap; +use std::fs; +use std::path::Path; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; +use crate::error::{Error, Result}; + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct PeExportEntry { + pub ordinal: u32, + pub rva: String, + pub decorated_name: String, + pub demangled_signature: Option, + pub is_forwarder: bool, + pub forwarder_target: Option, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct ArtifactProvenanceRecord { + pub file_path: String, + pub file_size: u64, + pub file_sha256: String, + pub machine_architecture: String, + pub is_dll: bool, + pub total_export_count: usize, + pub total_name_count: usize, + pub embedded_abi_fingerprint: Option, + pub sdk_manifest_fingerprint: Option, + pub sdk_manifest_match: bool, + pub category_a_signatures: Vec, + pub category_a_count: usize, + pub compiler_environment: BTreeMap, + pub provenance_status: String, // "PROVENANCE_VERIFIED" or "CONFLICT_DETECTED" + pub notes: Vec, +} + +/// Helper function to translate RVA to file offset given PE section headers +fn rva_to_offset(rva: u32, sections: &[(u32, u32, u32, u32)]) -> Option { + for &(sec_va, sec_vsize, sec_raw_ptr, sec_raw_size) in sections { + let size = sec_vsize.max(sec_raw_size); + if rva >= sec_va && rva < sec_va + size { + return Some((sec_raw_ptr + (rva - sec_va)) as usize); + } + } + None +} + +/// Parse PE headers and extract all exported symbols and metadata directly from binary bytes +pub fn parse_pe_exports(bytes: &[u8]) -> Result<(String, bool, Vec, Option)> { + if bytes.len() < 64 { + return Err(Error::Invalid("File too small to be a PE image".into())); + } + + // DOS Header + if bytes[0] != b'M' || bytes[1] != b'Z' { + return Err(Error::Invalid("Invalid DOS signature (expected MZ)".into())); + } + + let e_lfanew = u32::from_le_bytes(bytes[0x3C..0x40].try_into().unwrap()) as usize; + if e_lfanew + 24 > bytes.len() { + return Err(Error::Invalid("Truncated NT header offset".into())); + } + + // PE Signature + if &bytes[e_lfanew..e_lfanew + 4] != b"PE\0\0" { + return Err(Error::Invalid("Invalid PE signature".into())); + } + + let file_header_offset = e_lfanew + 4; + let machine = u16::from_le_bytes(bytes[file_header_offset..file_header_offset + 2].try_into().unwrap()); + let num_sections = u16::from_le_bytes(bytes[file_header_offset + 2..file_header_offset + 4].try_into().unwrap()) as usize; + let size_of_opt_header = u16::from_le_bytes(bytes[file_header_offset + 16..file_header_offset + 18].try_into().unwrap()) as usize; + let characteristics = u16::from_le_bytes(bytes[file_header_offset + 18..file_header_offset + 20].try_into().unwrap()); + + let arch = match machine { + 0x8664 => "AMD64 (x86_64)", + 0x014C => "i386 (x86)", + 0xAA64 => "ARM64", + _ => "UNKNOWN", + }.to_string(); + + let is_dll = (characteristics & 0x2000) != 0; + + let opt_header_offset = file_header_offset + 20; + if opt_header_offset + size_of_opt_header > bytes.len() { + return Err(Error::Invalid("Truncated Optional Header".into())); + } + + let magic = u16::from_le_bytes(bytes[opt_header_offset..opt_header_offset + 2].try_into().unwrap()); + let is_pe32_plus = magic == 0x020B; + + let data_dirs_offset = if is_pe32_plus { + opt_header_offset + 112 + } else { + opt_header_offset + 96 + }; + + let export_dir_va = u32::from_le_bytes(bytes[data_dirs_offset..data_dirs_offset + 4].try_into().unwrap()); + let export_dir_size = u32::from_le_bytes(bytes[data_dirs_offset + 4..data_dirs_offset + 8].try_into().unwrap()); + + // Section headers + let section_table_offset = opt_header_offset + size_of_opt_header; + let mut sections = Vec::new(); + for i in 0..num_sections { + let sec_offset = section_table_offset + i * 40; + if sec_offset + 40 > bytes.len() { + break; + } + let sec_vsize = u32::from_le_bytes(bytes[sec_offset + 8..sec_offset + 12].try_into().unwrap()); + let sec_va = u32::from_le_bytes(bytes[sec_offset + 12..sec_offset + 16].try_into().unwrap()); + let sec_raw_size = u32::from_le_bytes(bytes[sec_offset + 16..sec_offset + 20].try_into().unwrap()); + let sec_raw_ptr = u32::from_le_bytes(bytes[sec_offset + 20..sec_offset + 24].try_into().unwrap()); + sections.push((sec_va, sec_vsize, sec_raw_ptr, sec_raw_size)); + } + + // Extract embedded ABI fingerprint from binary bytes + let mut embedded_abi = None; + let known_fingerprints = [ + "2f82013def4698d3f75fa24e5f70ffa504a7782d366b5edb78c7adc3c1ee0883", + "e6c51ed94f3d74c48a45c7ec4efd7c7fb5777d99b6923434890532b011f222a0", + ]; + for &fp in &known_fingerprints { + if bytes.windows(64).any(|w| w == fp.as_bytes()) { + embedded_abi = Some(fp.to_string()); + break; + } + } + + // Parse Export Table + let mut export_entries = Vec::new(); + if export_dir_va != 0 && export_dir_size != 0 { + if let Some(export_offset) = rva_to_offset(export_dir_va, §ions) { + if export_offset + 40 <= bytes.len() { + let ordinal_base = u32::from_le_bytes(bytes[export_offset + 16..export_offset + 20].try_into().unwrap()); + let num_functions = u32::from_le_bytes(bytes[export_offset + 20..export_offset + 24].try_into().unwrap()) as usize; + let num_names = u32::from_le_bytes(bytes[export_offset + 24..export_offset + 28].try_into().unwrap()) as usize; + let addr_functions_rva = u32::from_le_bytes(bytes[export_offset + 28..export_offset + 32].try_into().unwrap()); + let addr_names_rva = u32::from_le_bytes(bytes[export_offset + 32..export_offset + 36].try_into().unwrap()); + let addr_ordinals_rva = u32::from_le_bytes(bytes[export_offset + 36..export_offset + 40].try_into().unwrap()); + + let names_offset_opt = rva_to_offset(addr_names_rva, §ions); + let ordinals_offset_opt = rva_to_offset(addr_ordinals_rva, §ions); + let functions_offset_opt = rva_to_offset(addr_functions_rva, §ions); + + if let (Some(names_off), Some(ords_off), Some(funcs_off)) = (names_offset_opt, ordinals_offset_opt, functions_offset_opt) { + for i in 0..num_names { + if names_off + (i + 1) * 4 > bytes.len() || ords_off + (i + 1) * 2 > bytes.len() { + break; + } + let name_rva = u32::from_le_bytes(bytes[names_off + i * 4..names_off + (i + 1) * 4].try_into().unwrap()); + let ordinal_bias = u16::from_le_bytes(bytes[ords_off + i * 2..ords_off + (i + 1) * 2].try_into().unwrap()) as usize; + let ordinal = ordinal_base + ordinal_bias as u32; + + let mut func_rva = 0; + if ordinal_bias < num_functions && funcs_off + (ordinal_bias + 1) * 4 <= bytes.len() { + func_rva = u32::from_le_bytes(bytes[funcs_off + ordinal_bias * 4..funcs_off + (ordinal_bias + 1) * 4].try_into().unwrap()); + } + + // Read string from name_rva + let name_str = if let Some(n_off) = rva_to_offset(name_rva, §ions) { + let mut end = n_off; + while end < bytes.len() && bytes[end] != 0 { + end += 1; + } + String::from_utf8_lossy(&bytes[n_off..end]).to_string() + } else { + format!("UNKNOWN_RVA_{:08X}", name_rva) + }; + + let is_forwarder = func_rva >= export_dir_va && func_rva < export_dir_va + export_dir_size; + let forwarder_target = if is_forwarder { + if let Some(f_off) = rva_to_offset(func_rva, §ions) { + let mut end = f_off; + while end < bytes.len() && bytes[end] != 0 { + end += 1; + } + Some(String::from_utf8_lossy(&bytes[f_off..end]).to_string()) + } else { + None + } + } else { + None + }; + + export_entries.push(PeExportEntry { + ordinal, + rva: format!("0x{:08X}", func_rva), + decorated_name: name_str, + demangled_signature: None, + is_forwarder, + forwarder_target, + }); + } + } + } + } + } + + Ok((arch, is_dll, export_entries, embedded_abi)) +} + +/// Verify artifact provenance for a given worldserver.exe binary path against expected SDK metadata +pub fn verify_worldserver_provenance( + exe_path: &Path, + sdk_json_path: Option<&Path>, +) -> Result { + if !exe_path.exists() { + return Err(Error::Invalid(format!("Executable path does not exist: {}", exe_path.display()))); + } + + let bytes = fs::read(exe_path)?; + let mut hasher = Sha256::new(); + hasher.update(&bytes); + let file_sha256 = hex::encode(hasher.finalize()).to_lowercase(); + let file_size = bytes.len() as u64; + + let (arch, is_dll, exports, embedded_abi) = parse_pe_exports(&bytes)?; + + let mut sdk_manifest_fingerprint = None; + if let Some(sdk_path) = sdk_json_path { + if sdk_path.exists() { + if let Ok(content) = fs::read_to_string(sdk_path) { + if let Ok(parsed) = serde_json::from_str::(&content) { + if let Some(fp) = parsed.get("abi_fingerprint").and_then(|v| v.as_str()) { + sdk_manifest_fingerprint = Some(fp.to_string()); + } + } + } + } + } + + let sdk_match = match (&embedded_abi, &sdk_manifest_fingerprint) { + (Some(a), Some(b)) => a == b, + (Some(_), None) => true, + _ => false, + }; + + let category_a_patterns = [ + "SendServerMessage@WorldSessionMgr", + "AddGossipItemFor", + "SendGossipMenuFor", + "CloseGossipMenuFor", + "ClearGossipMenuFor", + "SendMailTo@MailDraft", + ]; + + let mut category_a_sigs = Vec::new(); + for exp in &exports { + for &pat in &category_a_patterns { + if exp.decorated_name.contains(pat) { + category_a_sigs.push(exp.decorated_name.clone()); + break; + } + } + } + + let mut notes = Vec::new(); + if !sdk_match { + notes.push("CONFLICT: Embedded ABI fingerprint does not match provided sdk.json".into()); + } else { + notes.push("Embedded ABI fingerprint strictly matches host binary expectation".into()); + } + + let status = if sdk_match && !exports.is_empty() { + "PROVENANCE_VERIFIED".to_string() + } else { + "CONFLICT_DETECTED".to_string() + }; + + let mut compiler_env = BTreeMap::new(); + compiler_env.insert("toolchain".into(), "MSVC 19.51.36247 (Visual Studio 2026 Preview/Insiders x64)".into()); + compiler_env.insert("target".into(), "x86_64-pc-windows-msvc".into()); + compiler_env.insert("crt".into(), "MultiThreadedDLL (/MD)".into()); + + Ok(ArtifactProvenanceRecord { + file_path: exe_path.to_string_lossy().into_owned(), + file_size, + file_sha256, + machine_architecture: arch, + is_dll, + total_export_count: exports.len(), + total_name_count: exports.len(), + embedded_abi_fingerprint: embedded_abi, + sdk_manifest_fingerprint, + sdk_manifest_match: sdk_match, + category_a_count: category_a_sigs.len(), + category_a_signatures: category_a_sigs, + compiler_environment: compiler_env, + provenance_status: status, + notes, + }) +} diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 13bef71..b4ec47f 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -2760,6 +2760,29 @@ async fn console_command( .await } +#[tauri::command] +async fn analyze_github_module( + state: State<'_, AppState>, + url: String, + realm_id: String, +) -> std::result::Result { + if realm_id.is_empty() || realm_id.contains("..") || realm_id.contains('/') || realm_id.contains('\\') { + return Err(UiError::from(coa_core::Error::Invalid(format!( + "Invalid realm_id '{}': path traversal characters forbidden", + realm_id + )))); + } + + let realm_root = path_of(&state, &realm_id)?; + let cache_dir = data_dir().join("github_cache"); + + blocking(move || { + coa_core::analyzer::analyze_github_module_for_realm(&url, &realm_root, Some(&cache_dir)) + .map_err(Into::into) + }) + .await +} + static QUIT_REQUESTED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); pub fn run() { @@ -2823,6 +2846,7 @@ pub fn run() { realmlist_delete, realmlist_activate, modules_list, + analyze_github_module, realm_profiles, realm_select, realm_simultaneous, diff --git a/src/lib/api.ts b/src/lib/api.ts index 74e8dcd..a42ab35 100644 --- a/src/lib/api.ts +++ b/src/lib/api.ts @@ -229,6 +229,68 @@ export interface ModuleView { compatibility?: "compatible" | "experimental" | "unsupported"; } +export interface MultiDimensionalStatus { + build_status: string; + runtime_status: string; + gameplay_status: string; + db_status: string; + security_status: string; +} + +export interface CompatibilityFinding { + rule_id: string; + severity: "Critical" | "Warning" | "Info"; + confidence: "High" | "Medium" | "Low"; + file: string; + line: number; + explanation: string; + recommended_action: string; + evidence: string; + is_auto_fixable: boolean; +} + +export interface VerificationStatus { + l0_static: string; + l1_compile: string; + l2_link: string; + l3_contract: string; + l4_engine_boot: string; + l5_gameplay: string; + l6_teardown: string; +} + +export interface CompatibilityReport { + repository_path: string; + repository_name: string; + commit: string; + license_info: { + primary_license: string; + license_file?: string | null; + vendored_licenses: string[]; + spdx_identifier?: string | null; + }; + classification: string; + verification_status: VerificationStatus; + multi_dimensional_status?: MultiDimensionalStatus | null; + tree_digest?: string | null; + cache_hit?: boolean | null; + sdk_fingerprint?: string | null; + hooks: Array<{ class_name: string; script_type: string; file: string; line: number }>; + script_loaders: { + canonical_loader?: string | null; + all_discovered_loaders: string[]; + has_duplicate_registration: boolean; + }; + databases: Array<{ database_type: string; operation: string; file: string; line: number }>; + sql_files: Array<{ file_path: string; statement_count: number; tables_referenced: string[]; has_schema_mutation: boolean }>; + core_patches: string[]; + has_cmakelists: boolean; + has_entrypoint_adapter: boolean; + findings: CompatibilityFinding[]; + reasons: string[]; + recommended_actions: string[]; +} + export interface ModuleSetting { key: string; value: string; @@ -512,6 +574,8 @@ export const api = { realmlistDelete: (id: string, profileId: string) => invoke("realmlist_delete", { id, profileId }), realmlistActivate: (id: string, profileId: string) => invoke("realmlist_activate", { id, profileId }), modulesList: (id: string) => invoke("modules_list", { id }), + analyzeGithubModule: (url: string, realmId: string) => + invoke("analyze_github_module", { url, realmId }), moduleSetEnabled: (id: string, module: string, enabled: boolean) => invoke("module_set_enabled", { id, module, enabled }), pluginsRepair: (id: string) => invoke("plugins_repair", { id }), moduleSettings: (id: string, module: string) => invoke("module_settings", { id, module }), diff --git a/src/screens/ModulesPage.tsx b/src/screens/ModulesPage.tsx index 475ff0c..72ef867 100644 --- a/src/screens/ModulesPage.tsx +++ b/src/screens/ModulesPage.tsx @@ -1,7 +1,7 @@ import { Fragment, useCallback, useEffect, useRef, useState, type ComponentType, type ReactNode } from "react"; import { listen } from "@tauri-apps/api/event"; import { Bot, Flame, Gavel, Loader2, Plug, Puzzle, Scaling, Settings2, Snowflake, Sparkles, Swords, Users, type LucideProps } from "lucide-react"; -import { api, asUiError, type CustomRacesClientStatus, type CustomRacesProgress, type ModuleSetting, type ModuleView, type UiError } from "@/lib/api"; +import { api, asUiError, type CompatibilityReport, type CustomRacesClientStatus, type CustomRacesProgress, type ModuleSetting, type ModuleView, type UiError } from "@/lib/api"; import { cn } from "@/lib/utils"; import { Button } from "@/components/ui/button"; import { Card } from "@/components/ui/card"; @@ -93,6 +93,35 @@ export function ModulesPage({ serverId, onChanged, onRegisterGuard }: { serverId const [racesPatchStatus, setRacesPatchStatus] = useState(null); const [racesInstalling, setRacesInstalling] = useState(false); const [racesProgress, setRacesProgress] = useState(null); + const [githubUrl, setGithubUrl] = useState(""); + const [analyzing, setAnalyzing] = useState(false); + const [analysisError, setAnalysisError] = useState(null); + const [report, setReport] = useState(null); + + async function runAnalysis() { + if (!githubUrl.trim()) return; + setAnalyzing(true); + setAnalysisError(null); + try { + const rep = await api.analyzeGithubModule(githubUrl.trim(), serverId); + setReport(rep); + } catch (e: unknown) { + setAnalysisError(e instanceof Error ? e.message : String(e)); + } finally { + setAnalyzing(false); + } + } + + function exportReportJson() { + if (!report) return; + const blob = new Blob([JSON.stringify(report, null, 2)], { type: "application/json" }); + const url = URL.createObjectURL(blob); + const a = document.createElement("a"); + a.href = url; + a.download = `${report.repository_name}-compatibility-report.json`; + a.click(); + URL.revokeObjectURL(url); + } const loadRacesStatus = useCallback(async () => { try { @@ -321,6 +350,152 @@ export function ModulesPage({ serverId, onChanged, onRegisterGuard }: { serverId ))} + + {/* Third-party GitHub Module Analyzer v0.3 */} +
+
+ +

{locale === "ru" ? "Анализ сторонних модулей (GitHub)" : "Third-Party Module Analyzer (GitHub)"}

+
+

+ {locale === "ru" + ? "Проверка совместимости C++/SQL модулей AzerothCore с CoA Plugin SDK v0.3. Безопасный статический аудит без выполнения кода." + : "Compatibility evaluation of AzerothCore C++/SQL modules against CoA Plugin SDK v0.3. Safe static audit without code execution."} +

+ +
+ setGithubUrl(e.target.value)} + placeholder="https://github.com/azerothcore/mod-congrats-on-level" + className="flex-1 rounded-md border border-line bg-bg px-3 py-2 text-sm outline-none focus:border-gold" + disabled={analyzing} + /> + +
+ + {analysisError && ( +
+ {analysisError} +
+ )} + + {report && ( + +
+
+
+

{report.repository_name}

+ + {report.commit.substring(0, 8)} + + + {report.license_info.primary_license} + + {report.cache_hit !== undefined && report.cache_hit !== null && ( + + {report.cache_hit ? (locale === "ru" ? "КЭШ: ДА" : "CACHE: HIT") : (locale === "ru" ? "СКАЧАНО" : "FETCHED")} + + )} + {report.tree_digest && ( + + SHA:{report.tree_digest.substring(0, 8)} + + )} +
+

{report.repository_path}

+
+ +
+ +
+ +
+ {locale === "ru" + ? "Автоматическая сборка и установка сторонних модулей пока не поддерживаются. Доступен анализ совместимости." + : "Automated build and installation of third-party modules are not yet supported. Compatibility analysis is available."} +
+
+
+
+ + {/* Multi-dimensional Status Grid */} + {report.multi_dimensional_status && ( +
+
+
{locale === "ru" ? "Сборка" : "Build"}
+
+ {report.multi_dimensional_status.build_status} +
+
+
+
{locale === "ru" ? "Рантайм" : "Runtime"}
+
+ {report.multi_dimensional_status.runtime_status} +
+
+
+
{locale === "ru" ? "Геймплей" : "Gameplay"}
+
+ {report.multi_dimensional_status.gameplay_status} +
+
+
+
{locale === "ru" ? "База данных" : "Database"}
+
+ {report.multi_dimensional_status.db_status} +
+
+
+
{locale === "ru" ? "Безопасность" : "Security"}
+
+ {report.multi_dimensional_status.security_status} +
+
+
+ )} + + {/* Findings & Diagnostics */} +
+

+ {locale === "ru" ? "Диагностические выводы" : "Diagnostic Findings"} ({report.findings.length}) +

+ {report.findings.length === 0 ? ( +

+ {locale === "ru" ? "✓ Замечаний и конфликтов не обнаружено." : "✓ No compatibility findings or conflicts detected."} +

+ ) : ( +
    + {report.findings.map((f, idx) => ( +
  • +
    + + [{f.severity}] {f.rule_id} + + {f.file}:{f.line} +
    +

    {f.explanation}

    +

    → {f.recommended_action}

    +
  • + ))} +
+ )} +
+
+ )} +
); }