Files
ats-native-fsd/tools/verify_prefab_asset_overlays.py
2026-10-06 18:11:59 +00:00

149 lines
7.1 KiB
Python

"""Verify PPD provenance against all currently mounted archives, read-only.
Absence is an exact path-hash index query. Other archives' resource payloads
are not read: header and entry/metadata table fingerprints prove which index
was checked. The selected source archive has a separate full-content hash.
"""
import hashlib
import json
from pathlib import Path
import re
import os
import tempfile
try:
from .extract_hashfs_assets import HashFSReader, HEADER
from .hashfs_cityhash import cityhash64
except ImportError:
from extract_hashfs_assets import HashFSReader, HEADER
from hashfs_cityhash import cityhash64
ROOT = Path(__file__).resolve().parents[1]
LOG = Path.home()/'Documents/American Truck Simulator/game.log.txt'
CACHE = ROOT/'diagnostics/map-cache/prefab-navigation.json'
def mounted_archives(text):
mounted = {}
fingerprints = {}
for line in text.splitlines():
pack = re.search(r'\[hashfs\] (.*?\.scs): Created and validated, \d+ entries \(([0-9A-F]+)\)', line)
if pack:
fingerprints[pack[1]] = pack[2]
unmount = re.search(r'\[hashfs\] (.*?\.scs): Unmounted', line)
if unmount:
for name in list(mounted):
if Path(name).name == unmount[1]: del mounted[name]
mount = re.search(r'\[fs\] device (.*?) mounted to (\w+) pool\.', line)
if mount and mount[1].lower().endswith('.scs'):
name = str(Path(mount[1]).resolve())
mounted.pop(name, None)
mounted[name] = dict(path=name, pool=mount[2],
game_log_pack_fingerprint=fingerprints.get(Path(name).name))
if not mounted:
raise ValueError('Current mounted archive list is unavailable')
return list(mounted.values())
def archive_index_fingerprint(path):
path = Path(path)
stat = path.stat()
with path.open('rb') as stream:
header = stream.read(HEADER.size)
fields = HEADER.unpack(header)
regions = []
for offset, size in ((fields[8], fields[5]), (fields[9], fields[7])):
if size > 128*1024*1024 or offset+size > stat.st_size:
raise ValueError('Archive index fingerprint region outside bounds')
stream.seek(offset)
data = stream.read(size)
if len(data) != size: raise ValueError('Incomplete archive index fingerprint')
regions.append(dict(offset=offset, size=size, sha256=hashlib.sha256(data).hexdigest()))
return dict(path=str(path.resolve()), size=stat.st_size, mtime_ns=stat.st_mtime_ns,
header_size=HEADER.size, header_sha256=hashlib.sha256(header).hexdigest(),
index_regions=regions, entry_count=fields[4],
fingerprint_kind='header-and-compressed-entry-metadata-tables')
def verify_overlays(cache, text=None):
text = LOG.read_text(encoding='utf-8', errors='replace') if text is None else text
mounts = mounted_archives(text)
target_paths = [p['asset_path'].lstrip('/') for p in cache['prefabs'].values()]
expected_source = Path(cache['archives'][0]['path']).resolve()
checked, overrides = [], []
for mount in mounts:
path = Path(mount['path'])
before = archive_index_fingerprint(path)
reader = HashFSReader(path)
try:
presence = {name: cityhash64(str(reader.salt)+name if reader.salt else name) in reader.entries
for name in target_paths}
finally:
reader.close()
after = archive_index_fingerprint(path)
if before != after:
raise ValueError('Mounted archive changed during overlay index query')
checked.append(dict(**after, pool=mount['pool'],
game_log_pack_fingerprint=mount['game_log_pack_fingerprint'],
present_assets=[name for name, present in presence.items() if present]))
if path.resolve() != expected_source and any(presence.values()):
overrides.append(dict(path=str(path), assets=checked[-1]['present_assets']))
source = next((entry for entry in checked if Path(entry['path']).resolve() == expected_source), None)
if source is None or set(source['present_assets']) != set(target_paths):
raise ValueError('Expected mounted source does not contain both selected assets')
# Directory-based active mods cannot hide behind an archive-only check.
active = re.findall(r'\[mods\] Active local mod (.*?) \(name:', text)
active_headers = re.findall(r'\[mods\] Active (\d+) mods \(local: (\d+), workshop: (\d+)\)', text)
if (not active_headers or int(active_headers[-1][2]) != 0
or int(active_headers[-1][0]) != len(active)):
raise ValueError('Current Workshop/active-mod population is not verified')
if active != cache['mod_order']:
raise ValueError('Active mod order differs from validated cache')
mod_folder = LOG.parent/'mod'
if any((mod_folder/name).is_dir() for name in active):
raise ValueError('Active loose-directory mod requires separate overlay validation')
if overrides:
raise ValueError('Selected prefab assets also occur in other loaded archives: '+str(overrides))
versions = re.findall(r'Loaded pack set version ([\d.]+)', text)
if not versions or versions[-1] != cache['game_version']:
raise ValueError('Loaded pack version differs from prefab cache')
cache['asset_overlay_verified'] = True
cache['overlay_provenance'] = dict(
kind='exact-path-hash-absence-in-every-other-mounted-archive',
selected_paths=target_paths, selected_source_archive=str(expected_source),
loaded_archive_order=[m['path'] for m in mounts], checked_archives=checked,
game_log_path=str(LOG), game_log_snapshot_sha256=hashlib.sha256(text.encode('utf-8')).hexdigest(),
game_version=versions[-1], mod_order=active,
no_other_loaded_archive_contains_selected_assets=True,
directory_mods_present=False)
return cache
def atomic_write_json(destination, data):
destination = Path(destination)
stream = tempfile.NamedTemporaryFile(mode='w', encoding='utf-8', dir=destination.parent,
prefix=destination.name+'.', suffix='.tmp', delete=False)
pending = stream.name
try:
with stream:
json.dump(data, stream, indent=2)
stream.flush()
os.fsync(stream.fileno())
os.replace(pending, destination)
finally:
if Path(pending).exists(): Path(pending).unlink()
def main():
cache = verify_overlays(json.loads(CACHE.read_text(encoding='utf-8')))
atomic_write_json(CACHE, cache)
checked = cache['overlay_provenance']['checked_archives']
print(json.dumps(dict(asset_overlay_verified=True, checked_archives=len(checked),
sole_source=cache['overlay_provenance']['selected_source_archive'], overrides=[],
important_checks=[dict(path=c['path'], present_assets=c['present_assets'])
for c in checked if Path(c['path']).name in ('base.scs','base_share.scs','dlc_arizona.scs')
or c['pool']=='mod'])))
if __name__ == '__main__': main()