Files
LonaRPG-Online-Games/ModScripts/999999999999999999999_WebMapIntegrity.rb
T
2026-10-29 21:59:06 +04:00

644 lines
23 KiB
Ruby

# encoding: UTF-8
#==============================================================================
# Web map integrity check
#------------------------------------------------------------------------------
# During game startup, read the current manifest from the HTTPS endpoint once
# and keep it only in process memory. Before every real map change:
# 1. find the exact map file used by $data_mapinfos in the memory manifest;
# 2. calculate SHA-256 of the local map file;
# 3. cancel the transfer and disconnect when verification fails.
#
# Deliberately has no fallback to the local Secure.json. A network or manifest
# error is a failed verification, not permission to enter an unchecked map.
#==============================================================================
return if defined?($mp_web_map_integrity_loaded) && $mp_web_map_integrity_loaded
$mp_web_map_integrity_loaded = true
begin
require 'digest'
require 'digest/sha2'
rescue LoadError
end
module MPWebMapIntegrity
MANIFEST_URL = 'https://lonarpg.online/Secure/Secure.json'
HOST = 'lonarpg.online'
PORT = 443
REQUEST_PATH = '/Secure/Secure.json'
MAX_BYTES = 4 * 1024 * 1024
TIMEOUT_MS = 10_000
VERIFY_ATTEMPTS = 1
RETRY_DELAY_SECONDS = 0.20
FAILURE_LOG = File.join('UserData', 'map_integrity.log')
Result = Struct.new(:ok, :code, :path, :expected, :actual, :details)
@blocked = false
@last_error = nil
@manifest_cache = nil
@manifest_error = nil
@manifest_loaded = false
module WinHTTP
module_function
WINHTTP_ACCESS_TYPE_DEFAULT_PROXY = 0
WINHTTP_FLAG_SECURE = 0x00800000
WINHTTP_QUERY_STATUS_CODE = 19
WINHTTP_QUERY_FLAG_NUMBER = 0x20000000
def function(handle, name, args, result)
Fiddle::Function.new(
handle[name], args, result,
Ruby310Compat.respond_to?(:stdcall_abi) ? Ruby310Compat.stdcall_abi : Fiddle::Function::DEFAULT
)
end
def init
return true if @ready
raise 'Ruby310Compat is unavailable' unless defined?(Ruby310Compat)
raise 'Fiddle is unavailable' unless Ruby310Compat.fiddle_ready?
@dll = Ruby310Compat.open_library('winhttp.dll')
p = Fiddle::TYPE_VOIDP
i = Fiddle::TYPE_INT
@open = function(@dll, 'WinHttpOpen', [p, i, p, p, i], p)
@connect = function(@dll, 'WinHttpConnect', [p, p, i, i], p)
@open_request = function(@dll, 'WinHttpOpenRequest', [p, p, p, p, p, p, i], p)
@set_timeouts = function(@dll, 'WinHttpSetTimeouts', [p, i, i, i, i], i)
@send_request = function(@dll, 'WinHttpSendRequest', [p, p, i, p, i, i, p], i)
@receive_response = function(@dll, 'WinHttpReceiveResponse', [p, p], i)
@query_headers = function(@dll, 'WinHttpQueryHeaders', [p, i, p, p, p, p], i)
@query_available = function(@dll, 'WinHttpQueryDataAvailable', [p, p], i)
@read_data = function(@dll, 'WinHttpReadData', [p, p, i, p], i)
@close = function(@dll, 'WinHttpCloseHandle', [p], i)
@ready = true
end
def wide(text)
text.to_s.encode(Encoding::UTF_16LE).b + "\0\0".b
end
def ptr(value)
return 0 if value.nil?
return value if defined?(Fiddle::Pointer) && value.is_a?(Fiddle::Pointer)
return Fiddle::Pointer[value] if value.is_a?(String)
value
end
def valid_handle?(handle)
!handle.nil? && handle.to_i != 0
rescue
false
end
def close(handle)
@close.call(handle) if @close && valid_handle?(handle)
rescue
end
def status_code(request)
value = "\0".b * 4
length = [4].pack('L<')
level = WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER
ok = @query_headers.call(request, level, 0, ptr(value), ptr(length), 0)
raise 'WinHTTP could not read the HTTP status' if ok.to_i == 0
value.unpack1('L<').to_i
end
def read_body(request)
body = ''.b
loop do
available_buffer = "\0".b * 4
ok = @query_available.call(request, ptr(available_buffer))
raise 'WinHTTP could not query response data' if ok.to_i == 0
available = available_buffer.unpack1('L<').to_i
break if available <= 0
raise "manifest is larger than #{MAX_BYTES} bytes" if body.bytesize + available > MAX_BYTES
chunk = "\0".b * available
read_buffer = "\0".b * 4
ok = @read_data.call(request, ptr(chunk), available, ptr(read_buffer))
raise 'WinHTTP could not read response data' if ok.to_i == 0
read = read_buffer.unpack1('L<').to_i
raise 'WinHTTP returned an invalid response chunk' if read < 0 || read > available
break if read == 0
body << chunk.byteslice(0, read)
end
body
end
def get(host, port, path)
# mkxp-z ships its own HTTPS client. Prefer it because some release
# builds intentionally omit Ruby's Fiddle extension even on Windows.
if defined?(HTTPLite) && HTTPLite.respond_to?(:get)
url = "https://#{host}#{path}"
headers = {
'Cache-Control' => 'no-cache',
'Pragma' => 'no-cache'
}
response = HTTPLite.get(url, headers, true)
raise 'HTTPLite returned an invalid response' unless response.is_a?(Hash)
status = response[:status]
status = response['status'] if status.nil?
raise "manifest server returned HTTP #{status}" unless status.to_i == 200
body = response[:body]
body = response['body'] if body.nil?
body = body.to_s.b
raise "manifest is larger than #{MAX_BYTES} bytes" if body.bytesize > MAX_BYTES
return body
end
# Compatibility fallback for engines without HTTPLite.
init
session = connection = request = nil
begin
agent = wide('LonaRPG-MapIntegrity/1.0')
server = wide(host)
verb = wide('GET')
object = wide(path)
header_text = "Cache-Control: no-cache\r\nPragma: no-cache\r\n"
headers = wide(header_text)
session = @open.call(ptr(agent), WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, 0, 0, 0)
raise 'WinHttpOpen failed' unless valid_handle?(session)
@set_timeouts.call(session, TIMEOUT_MS, TIMEOUT_MS, TIMEOUT_MS, TIMEOUT_MS)
connection = @connect.call(session, ptr(server), port.to_i, 0)
raise 'WinHttpConnect failed' unless valid_handle?(connection)
request = @open_request.call(connection, ptr(verb), ptr(object), 0, 0, 0, WINHTTP_FLAG_SECURE)
raise 'WinHttpOpenRequest failed' unless valid_handle?(request)
@set_timeouts.call(request, TIMEOUT_MS, TIMEOUT_MS, TIMEOUT_MS, TIMEOUT_MS)
# WinHttpSendRequest receives a UTF-16 buffer. Passing -1 here is not
# reliable for the wide API and can fail with ERROR_INVALID_PARAMETER.
ok = @send_request.call(request, ptr(headers), header_text.length, 0, 0, 0, 0)
raise 'WinHttpSendRequest failed' if ok.to_i == 0
ok = @receive_response.call(request, 0)
raise 'WinHttpReceiveResponse failed' if ok.to_i == 0
status = status_code(request)
raise "manifest server returned HTTP #{status}" unless status == 200
read_body(request)
ensure
close(request)
close(connection)
close(session)
end
end
end
module_function
def log(message)
puts "[MAP-INTEGRITY] #{message}"
rescue
end
def log_failure(message)
text = "#{Time.now.strftime('%Y-%m-%d %H:%M:%S')} [MAP-INTEGRITY] #{message}\n"
begin
Dir.mkdir('UserData') unless Dir.exist?('UserData')
File.open(FAILURE_LOG, 'ab') { |stream| stream.write(text) }
rescue
end
log(message)
rescue
end
def parse_json(text)
normalized = if defined?(Ruby310Compat) && Ruby310Compat.respond_to?(:normalize_json_source)
Ruby310Compat.normalize_json_source(text)
else
text
end
# LonaRPG's bundled JSON module defines JSON.parse as its internal
# zero-argument parser (the optional argument is only a debug flag). It
# does not accept JSON source like stdlib JSON.parse does, so calling it
# first parses stale module state and commonly returns nil. JSON.decode
# is the public entry point which loads the supplied source into that
# parser.
return JSON.decode(normalized) if defined?(JSON) && JSON.respond_to?(:decode)
if defined?(Ruby310Compat) && Ruby310Compat.respond_to?(:decode_json_text)
return Ruby310Compat.decode_json_text(normalized)
end
return JSON.parse(normalized) if defined?(JSON) && JSON.respond_to?(:parse)
raise 'JSON parser is unavailable'
end
def fetch_manifest(attempt = 1)
# A unique query prevents an intermediary from serving an older manifest
# immediately after the administrator publishes a new Secure.json.
nonce = "#{Time.now.to_i}-#{rand(1_000_000)}-#{attempt.to_i}"
body = WinHTTP.get(HOST, PORT, "#{REQUEST_PATH}?integrity=#{nonce}")
raise 'manifest response is empty' if body.nil? || body.empty?
text = if defined?(Ruby310Compat) && Ruby310Compat.respond_to?(:normalize_json_source)
Ruby310Compat.normalize_json_source(body)
else
body.to_s
end
# The bundled JSON decoder is extremely slow on the 3000+ entry manifest
# and freezes the render loop during every transfer. Validate the envelope
# here and extract only the requested flat file record in manifest_record.
stripped = text.to_s.strip
raise 'manifest root is not an object' unless stripped.start_with?('{') && stripped.end_with?('}')
algorithm = stripped.match(/"algorithm"\s*:\s*"([^"]+)"/i)
raise 'manifest algorithm is not SHA-256' unless algorithm && algorithm[1].to_s.upcase == 'SHA-256'
raise 'manifest files list is missing' unless stripped =~ /"files"\s*:\s*\[/i
stripped
end
def preload_manifest
return !@manifest_cache.nil? if @manifest_loaded
@manifest_loaded = true
@manifest_cache = fetch_manifest(1).freeze
@manifest_error = nil
log("manifest loaded into memory bytes=#{@manifest_cache.bytesize}")
true
rescue Exception => e
@manifest_cache = nil
@manifest_error = e
log_failure("manifest preload failed: #{e.class}: #{e.message}")
false
end
def memory_manifest
preload_manifest unless @manifest_loaded
return @manifest_cache unless @manifest_cache.nil?
error = @manifest_error
raise error if error
raise 'web manifest is unavailable in memory'
end
def clear_manifest
@manifest_cache = nil
@manifest_error = nil
@manifest_loaded = false
true
rescue
false
end
def map_path(map_token)
info = nil
begin
info = $data_mapinfos[map_token] if defined?($data_mapinfos) && $data_mapinfos
rescue
end
if info.nil? && map_token.respond_to?(:to_i)
begin
info = $data_mapinfos[map_token.to_i] if defined?($data_mapinfos) && $data_mapinfos
rescue
end
end
filename = info.filename.to_s if info && info.respond_to?(:filename)
if filename.nil? || filename.empty?
id = info.respond_to?(:id) ? info.id.to_i : map_token.to_i
filename = format('Data/Map%03d.rvdata2', id) if id > 0
end
normalize_path(filename)
end
def normalize_path(path)
clean = path.to_s.tr('\\', '/').sub(%r{\A\./+}, '')
raise 'map path is empty' if clean.empty?
raise 'absolute map paths are forbidden' if clean =~ %r{\A(?:/|[A-Za-z]:/)}
raise 'parent path segments are forbidden' if clean.split('/').include?('..')
clean
end
def actual_file_path(relative_path)
root = File.expand_path('.', Dir.pwd.to_s)
full = File.expand_path(relative_path.gsub('/', File::SEPARATOR), root)
prefix = root.end_with?(File::SEPARATOR) ? root : root + File::SEPARATOR
unless full.downcase.start_with?(prefix.downcase)
raise 'map path escapes the game directory'
end
full
end
def manifest_record(manifest, relative_path)
wanted = relative_path.to_s.downcase
if manifest.is_a?(String)
# Secure.json file records are flat JSON objects. Searching for the one
# requested path avoids constructing thousands of Ruby hashes merely to
# verify a single map.
escaped_path = relative_path.to_s.tr('\\', '/').gsub('\\', '\\\\').gsub('"', '\\"')
object_pattern = /\{[^{}]*"path"\s*:\s*"#{Regexp.escape(escaped_path)}"[^{}]*\}/i
object_match = manifest.match(object_pattern)
return nil unless object_match
object_text = object_match[0]
hash_match = object_text.match(/"sha256"\s*:\s*"([0-9a-fA-F]+)"/)
return nil unless hash_match
bytes_match = object_text.match(/"bytes"\s*:\s*(\d+)/)
return {
'path' => relative_path.to_s,
'sha256' => hash_match[1],
'bytes' => bytes_match ? bytes_match[1].to_i : nil
}
end
manifest['files'].each do |entry|
next unless entry.is_a?(Hash)
candidate = entry['path'].to_s.tr('\\', '/').sub(%r{\A\./+}, '')
return entry if candidate.downcase == wanted
end
nil
end
def sha256_file(path)
raise 'Digest::SHA256 is unavailable' unless defined?(Digest::SHA256)
digest = Digest::SHA256.new
File.open(path, 'rb') do |stream|
while (chunk = stream.read(1024 * 1024))
digest.update(chunk)
end
end
digest.hexdigest.downcase
end
def verify_once(map_token, attempt)
path = map_path(map_token)
manifest = memory_manifest
record = manifest_record(manifest, path)
return Result.new(false, :not_listed, path, '', '', 'map is absent from the web manifest') if record.nil?
expected = record['sha256'].to_s.strip.downcase
unless expected =~ /\A[0-9a-f]{64}\z/
return Result.new(false, :bad_manifest_hash, path, expected, '', 'manifest contains an invalid SHA-256')
end
full_path = actual_file_path(path)
return Result.new(false, :missing_file, path, expected, '', 'local map file is missing') unless File.file?(full_path)
expected_bytes = record['bytes']
if !expected_bytes.nil? && File.size(full_path).to_i != expected_bytes.to_i
actual = sha256_file(full_path)
return Result.new(false, :size_mismatch, path, expected, actual, 'local map size differs')
end
actual = sha256_file(full_path)
ok = secure_equal?(expected, actual)
Result.new(ok, ok ? :ok : :hash_mismatch, path, expected, actual, ok ? '' : 'local map SHA-256 differs')
rescue Exception => e
Result.new(false, :verification_error, (map_path(map_token) rescue ''), '', '', "#{e.class}: #{e.message}")
end
def verify(map_token)
last_result = nil
1.upto(VERIFY_ATTEMPTS) do |attempt|
last_result = verify_once(map_token, attempt)
return last_result if last_result.ok
# The web manifest is an immutable in-memory snapshot for this process;
# repeating a failed comparison cannot produce a different result.
break if last_result.code == :missing_file
log_failure(
"attempt=#{attempt}/#{VERIFY_ATTEMPTS} code=#{last_result.code} " +
"path=#{last_result.path.inspect} details=#{last_result.details}"
)
sleep(RETRY_DELAY_SECONDS) if attempt < VERIFY_ATTEMPTS
end
if last_result
if VERIFY_ATTEMPTS > 1 && last_result.code != :missing_file
last_result.details = "after #{VERIFY_ATTEMPTS} attempts: #{last_result.details}"
end
return last_result
end
Result.new(false, :verification_error, (map_path(map_token) rescue ''), '', '', 'verification returned no result')
rescue Exception => e
Result.new(false, :verification_error, (map_path(map_token) rescue ''), '', '', "#{e.class}: #{e.message}")
end
def secure_equal?(left, right)
a = left.to_s
b = right.to_s
return false unless a.bytesize == b.bytesize
diff = 0
a.bytes.each_with_index { |byte, index| diff |= byte ^ b.getbyte(index) }
diff == 0
rescue
false
end
def real_map_change?(map_token)
return false unless defined?($game_map) && $game_map
destination = map_path(map_token)
current_token = if $game_map.respond_to?(:map_id_rec)
$game_map.map_id_rec
else
$game_map.map_id
end
current = map_path(current_token)
destination.downcase != current.downcase
rescue
true
end
def blocked_message(result)
case result.code
when :hash_mismatch, :size_mismatch
"Переход отменён: файл карты изменён или повреждён.\n#{result.path}"
when :not_listed
"Переход отменён: карты нет в веб-манифесте безопасности.\n#{result.path}"
when :missing_file
"Переход отменён: файл карты отсутствует.\n#{result.path}"
when :bad_manifest_hash
"Переход отменён: сервер вернул некорректный хеш карты.\n#{result.path}"
else
"Переход отменён: не удалось проверить карту через\n#{MANIFEST_URL}\n\n#{result.details}"
end
rescue
'Переход отменён: проверка целостности карты не пройдена.'
end
def owner?
defined?(LonaIntegrity) && LonaIntegrity.respond_to?(:owner?) && LonaIntegrity.owner?
rescue
false
end
def block!(result)
@blocked = true
@last_error = result
log_failure(
"BLOCK code=#{result.code} path=#{result.path.inspect} " +
"expected=#{result.expected} actual=#{result.actual} details=#{result.details}"
)
begin
WebSocket.disconnect if defined?(WebSocket) && WebSocket.respond_to?(:connected?) && WebSocket.connected?
rescue
end
begin
if defined?(SceneManager) && defined?(Scene_MPMapIntegrityBlocked)
SceneManager.snapshot_for_background(false) rescue nil
SceneManager.goto(Scene_MPMapIntegrityBlocked)
end
rescue => e
log("could not open blocked dialog: #{e.class}: #{e.message}")
begin
msgbox(blocked_message(result))
SceneManager.exit if defined?(SceneManager)
rescue
end
end
false
end
def verify_transfer(map_token)
result = verify(map_token)
if result.ok
log("OK #{result.path} sha256=#{result.actual}")
true
elsif owner?
log("OWNER BYPASS code=#{result.code} path=#{result.path.inspect} details=#{result.details}")
true
else
block!(result)
end
end
def blocked?
!!@blocked
end
def last_error
@last_error
end
end
#==============================================================================
# Non-owner failure dialog. There are no choices: after the player advances
# through the Fortune Teller's message, SceneManager.exit closes the game.
#==============================================================================
class Scene_MPMapIntegrityBlocked < Scene_Base
def start
super
create_integrity_background
create_integrity_dialog
end
def create_integrity_background
@integrity_background = Sprite.new
@integrity_background.z = 0
@integrity_background_bitmap = Bitmap.new(Graphics.width, Graphics.height)
@integrity_background_bitmap.fill_rect(
0, 0, Graphics.width, Graphics.height, Color.new(0, 0, 0, 255)
)
@integrity_background.bitmap = @integrity_background_bitmap
rescue => e
puts "[MAP-INTEGRITY] blocked background failed: #{e.class}: #{e.message}" rescue nil
end
def create_integrity_dialog
@integrity_dialog_started = true
@integrity_exit_requested = false
@message_window = Window_Message.new
$game_message.clear
$game_message.background = 0
$game_message.position = 2
result = MPWebMapIntegrity.last_error
path = result && !result.path.to_s.empty? ? result.path.to_s : 'неизвестная карта'
if result && result.code == :verification_error
message =
"\\ph\\SETpl[TellerConfused]\\SETpr[nil]\\c[4]Гадалка:\\C[0] Нити судьбы дрожат...\\n Веб-манифест не загрузился при запуске игры.\f" +
"\\SETpl[TellerOkay]\\c[4]Гадалка:\\C[0] Это не означает, что файл карты изменён.\\n Не удалось проверить: \\C[6]#{path}\\C[0]\f" +
"\\SETpl[TellerAngry]\\c[4]Гадалка:\\C[0] Игра будет закрыта для безопасности. Попробуй войти снова."
else
message =
"\\ph\\SETpl[TellerConfused]\\SETpr[nil]\\c[4]Гадалка:\\C[0] Нити судьбы оборвались...\\n Файлы игры были изменены или не прошли проверку.\f" +
"\\SETpl[TellerAngry]\\c[4]Гадалка:\\C[0] Путь к этой карте закрыт.\\n \\C[6]#{path}\\C[0]\f" +
"\\SETpl[TellerOkay]\\c[4]Гадалка:\\C[0] Игра будет закрыта. Установи чистую версию LonaRPG Online."
end
$game_message.add(message)
rescue => e
puts "[MAP-INTEGRITY] blocked dialog failed: #{e.class}: #{e.message}" rescue nil
@integrity_exit_requested = true
end
def update
super
$game_portraits.update if defined?($game_portraits) && $game_portraits
if @integrity_exit_requested || (@integrity_dialog_started && !$game_message.busy?)
@integrity_exit_requested = false
$game_message.clear rescue nil
$game_portraits.hide_all_portraits(true) rescue nil
SceneManager.exit
end
rescue => e
puts "[MAP-INTEGRITY] blocked dialog update failed: #{e.class}: #{e.message}" rescue nil
SceneManager.exit rescue nil
end
def terminate
@integrity_background.dispose if @integrity_background && !@integrity_background.disposed? rescue nil
@integrity_background_bitmap.dispose if @integrity_background_bitmap && !@integrity_background_bitmap.disposed? rescue nil
super
end
end
module MPWebMapIntegrityPlayerPatch
def perform_transfer(*args, &block)
if transfer?
target = instance_variable_get(:@new_map_id)
if MPWebMapIntegrity.real_map_change?(target)
unless MPWebMapIntegrity.verify_transfer(target)
clear_transfer_info rescue nil
return false
end
end
end
super(*args, &block)
end
end
if defined?(Game_Player)
begin
unless Game_Player.ancestors.include?(MPWebMapIntegrityPlayerPatch)
Game_Player.prepend(MPWebMapIntegrityPlayerPatch)
end
rescue => e
puts "[MAP-INTEGRITY] hook failed: #{e.class}: #{e.message}" rescue nil
end
end
# Download Secure.json once while the normal game loading screen is active.
# The ensure block drops the only retained reference when SceneManager.run ends;
# process termination then releases the backing memory as usual.
module MPWebMapIntegritySceneManagerPatch
def run(*args, &block)
begin
if defined?($loading_screen) && $loading_screen && $loading_screen.respond_to?(:step_progress)
$loading_screen.step_progress('Веб-проверка карт')
end
rescue
end
MPWebMapIntegrity.preload_manifest
super(*args, &block)
ensure
MPWebMapIntegrity.clear_manifest
end
end
if defined?(SceneManager) && SceneManager.respond_to?(:run)
begin
manager_singleton = class << SceneManager; self; end
unless manager_singleton.ancestors.include?(MPWebMapIntegritySceneManagerPatch)
manager_singleton.prepend(MPWebMapIntegritySceneManagerPatch)
end
rescue => e
puts "[MAP-INTEGRITY] startup hook failed: #{e.class}: #{e.message}" rescue nil
end
end