Files
praxisandClaude Fable 5.2 8a24c445b0 Content pipeline and operator tools
367 files, from working commit b1a079a.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-19 01:32:48 +02:00

339 lines
21 KiB
Python

#!/usr/bin/env python3
"""Bounded TVFS inspection for the existing additive CASC asset pipeline.
No client/storage mutation or network. Contracts: local CascLib TVFS path/span
reader and wowdev/TACTSharp TVFSInstance (header flags are BIG endian). WoW
children contain40hex FileDataID+CKey names; legacy ROOT is a separate view.
"""
import hashlib
import json
import re
import struct
def table_width(size):
if type(size)is not int or not 0<size<=0xffffffff:raise ValueError('TVFS table size bound')
return max(1,(size.bit_length()+7)//8)
def layout(raw):
if not isinstance(raw,bytes)or not 38<=len(raw)<=134217728 or raw[:4]!=b'TVFS':
raise ValueError('Bounded native TVFS bytes required')
version,header,key,patch=raw[4:8];flags=int.from_bytes(raw[8:12],'big')
if version!=1 or key!=9 or patch!=9 or flags&~15 or header!=(46 if flags&2 else 38):
raise ValueError('Unreviewed native TVFS header/layout')
if header>len(raw):raise ValueError('Truncated TVFS header')
fields=struct.unpack_from('>6I',raw,12);tables={}
for name,i in(('paths',0),('vfs',2),('container',4)):
offset,size=fields[i:i+2];tables[name]=dict(offset=offset,size=size)
if flags&2:
offset,size=struct.unpack_from('>2I',raw,38);tables['specs']=dict(offset=offset,size=size)
ranges=[]
for name,entry in tables.items():
offset,size=entry['offset'],entry['size']
if size==0 or offset<header or offset>len(raw)or size>len(raw)-offset:
raise ValueError('TVFS table extent')
ranges.append((offset,offset+size,name))
ranges.sort()
if any(a[1]>b[0]for a,b in zip(ranges,ranges[1:])):raise ValueError('Overlapping TVFS tables')
depth=int.from_bytes(raw[36:38],'big')
if not 1<=depth<=64:raise ValueError('TVFS depth bound')
return dict(header_size=header,key_size=key,flags=flags,max_depth=depth,tables=tables,
cft_offset_width=table_width(tables['container']['size']),
spec_offset_width=table_width(tables['specs']['size'])if 'specs'in tables else 0,
md5=hashlib.md5(raw).hexdigest(),sha256=hashlib.sha256(raw).hexdigest())
def paths(raw,header=None):
"""Flatten the witnessed radix tree; retain explicit VFS offsets.
Folder lengths INCLUDE their4byte value. Separators and non-valued path
fragments retain their scope; duplicate or malformed paths are rejected.
"""
header=layout(raw)if header is None else header;table=header['tables']['paths'];records={};nodes=0
def walk(pos,end,prefix,depth):
nonlocal nodes
if depth>64 or depth>header['max_depth']:raise ValueError('TVFS path recursion/declared-depth bound')
while pos<end:
nodes+=1
if nodes>5000000:raise ValueError('TVFS path node bound')
saved=prefix;start=pos;pre=False;post=False
if raw[pos]==0:pre=True;pos+=1
if pos>=end:raise ValueError('Truncated TVFS path name')
name=b''
if raw[pos]!=255:
size=raw[pos];pos+=1
if size>end-pos:raise ValueError('TVFS path name extent')
name=raw[pos:pos+size];pos+=size
if any(c<32 or c>126 for c in name):raise ValueError('Non-ASCII TVFS path fragment')
if pos<end and raw[pos]==0:post=True;pos+=1
valued=pos<end and raw[pos]==255
if not valued:post=True
prefix+=('/'if pre else'')+name.decode('ascii')+('/'if post else'')
if len(prefix)>512:raise ValueError('TVFS path length bound')
if not valued:continue
if end-pos<5:raise ValueError('Truncated TVFS node value')
value=int.from_bytes(raw[pos+1:pos+5],'big');pos+=5
if value&0x80000000:
size=(value&0x7fffffff)-4
if size<0 or size>end-pos:raise ValueError('TVFS folder extent')
walk(pos,pos+size,prefix,depth+1);pos+=size
else:
if prefix in records:raise ValueError('Duplicate TVFS full path')
if value>=header['tables']['vfs']['size']:raise ValueError('TVFS file offset outside table')
records[prefix]=dict(vfs_offset=value,path_node_offset=start,depth=depth)
prefix=saved
walk(table['offset'],table['offset']+table['size'],'',0)
return records
def spans(raw,entry,header=None):
"""Read explicit span offsets/lengths and partial EKeys without guessing CFT extras."""
header=layout(raw)if header is None else header;table=header['tables']['vfs'];cft=header['tables']['container']
value=entry['vfs_offset'];pos=table['offset']+value;end=table['offset']+table['size']
if type(value)is not int or not 0<=value<table['size']:raise ValueError('TVFS VFS offset bound')
count=raw[pos];pos+=1
if not 1<=count<=224:raise ValueError('Unreviewed/deleted TVFS span kind')
width=header['cft_offset_width'];stride=8+width
if count>(end-pos)//stride:raise ValueError('Truncated TVFS spans')
records=[]
for _ in range(count):
offset,length=struct.unpack_from('>2I',raw,pos);container=int.from_bytes(raw[pos+8:pos+stride],'big');pos+=stride
if not length or container>cft['size']-header['key_size']:raise ValueError('TVFS container span extent')
begin=cft['offset']+container
records.append(dict(content_offset=offset,content_length=length,cft_offset=container,
encoding_key_prefix=raw[begin:begin+header['key_size']].hex()))
return records
def wow_file_name(name):
if not isinstance(name,str)or not re.fullmatch('[0-9A-Fa-f]{40}',name):return None
return dict(file_data_id=int(name[:8],16),content_key=name[8:].lower())
def container_record(raw,span,header=None):
"""Observed flags7 CFT: EKey9,size32,specOffset,decoded32,CKey16,patchCount8.
All828actual top records and independent native M2/SKIN/texture controls
establish these offsets. Patch bodies are deliberately not interpreted.
"""
header=layout(raw)if header is None else header
if header['flags']!=7:raise ValueError('Observed flags7 CFT required')
table=header['tables']['container'];width=header['spec_offset_width'];size=34+width
offset=span['cft_offset']
if type(offset)is not int or not 0<=offset<=table['size']-size:raise ValueError('TVFS CFT entry extent')
p=table['offset']+offset;record=raw[p:p+size];spec=int.from_bytes(record[13:13+width],'big');pos=13+width
decoded=int.from_bytes(record[pos:pos+4],'big');pos+=4;ckey=record[pos:pos+16].hex();pos+=16
est=header['tables']['specs']
if spec>=est['size']:raise ValueError('TVFS ESpec offset extent')
zero=raw.find(b'\0',est['offset']+spec,est['offset']+est['size'])
if zero<0:raise ValueError('TVFS ESpec terminator')
return dict(encoding_key_prefix=record[:9].hex(),encoded_size=int.from_bytes(record[9:13],'big'),
decoded_size=decoded,content_key=ckey,spec_offset=spec,
encoding_spec=raw[est['offset']+spec:zero].decode('ascii'),patch_count=record[pos],record_bytes=size)
def serialize_paths(entries):
"""Deterministic compressed radix tree for flat WoW generic namespaces.
Works on sorted ranges, avoiding a separate object for every name byte.
This supports existing40hex children and16hex/.root top names; hierarchical
separators and a file that prefixes another file require a separate contract.
"""
if not isinstance(entries,dict)or not 1<=len(entries)<=5000000:raise ValueError('TVFS path map bound')
items=sorted(entries.items())
for name,value in items:
if(not isinstance(name,str)or not 1<=len(name)<=254 or any(ord(c)<32 or ord(c)>126 or c in'/\\'for c in name)
or type(value)is not int or not 0<=value<0x80000000):raise ValueError('Flat TVFS path/value required')
if any(b[0].startswith(a[0])for a,b in zip(items,items[1:])):raise ValueError('TVFS file-prefix collision')
maximum=0
def emit(lo,hi,start,depth):
nonlocal maximum
if depth>=64:raise ValueError('TVFS serialized depth bound')
first,last=items[lo][0],items[hi-1][0];common=start
while common<min(len(first),len(last))and first[common]==last[common]:common+=1
if hi-lo==1:
maximum=max(maximum,depth);fragment=first[start:].encode('ascii')
return bytes([len(fragment)])+fragment+b'\xff'+items[lo][1].to_bytes(4,'big')
# A forest has no zero-length name node: zero denotes a separator.
nested=common>start;fragments=[];begin=lo
for i in range(lo+1,hi+1):
if i==hi or items[i][0][common]!=items[begin][0][common]:
fragments.append(emit(begin,i,common,depth+1 if nested else depth));begin=i
body=b''.join(fragments)
if not nested:return body
if len(body)>0x7fffffff-4:raise ValueError('TVFS folder byte bound')
fragment=first[start:common].encode('ascii')
return bytes([len(fragment)])+fragment+b'\xff'+(0x80000000|len(body)+4).to_bytes(4,'big')+body
result=emit(0,len(items),0,0)
return result,max(1,maximum)
def _replace_tables(raw,header,replacements,depth):
"""Preserve table order, unknown padding and unrelated header bytes."""
positions={'paths':12,'vfs':20,'container':28,'specs':38};out=bytearray(raw[:header['header_size']]);cursor=header['header_size']
for name,entry in sorted(header['tables'].items(),key=lambda x:x[1]['offset']):
out.extend(raw[cursor:entry['offset']]);payload=replacements[name]
struct.pack_into('>II',out,positions[name],len(out),len(payload));out.extend(payload);cursor=entry['offset']+entry['size']
out.extend(raw[cursor:]);struct.pack_into('>H',out,36,depth);return bytes(out)
def _stage_references(raw,references,h,original):
from casc_asset_package import reviewed_encoding_spec
mapping={n:r['vfs_offset']for n,r in original.items()};before=dict(mapping)
tables={name:raw[t['offset']:t['offset']+t['size']]for name,t in h['tables'].items()}
specs=bytearray(tables['specs']);cft=bytearray(tables['container']);vfs=bytearray(tables['vfs']);spec_offsets={};pos=0
while pos<len(specs):
end=specs.find(0,pos)
if end<0:raise ValueError('TVFS ESpec table terminator')
spec_offsets.setdefault(bytes(specs[pos:end]),pos);pos=end+1
fields={'content_key','encoding_key','decoded_size','encoded_size','encoding_spec'}
for name,row in sorted(references.items()):
if not isinstance(row,dict)or set(row)!=fields:raise ValueError('Complete TVFS reference identity required')
for key in('content_key','encoding_key'):
if not isinstance(row[key],str)or not re.fullmatch('[0-9a-f]{32}',row[key])or row[key]=='0'*32:raise ValueError('Positive TVFS digest required')
for key in('encoded_size','decoded_size'):
if type(row[key])is not int or not 0<row[key]<=0xffffffff:raise ValueError('TVFS single-span size bound')
# Existing native metadata uses this compact256KiB/Z recipe. Never
# accept an arbitrary old encrypted spec for a newly published object.
value=row['encoding_spec']
if value in('b:{256K*=z}','b:256K*=z'):
spec=value.encode('ascii')
if spec not in spec_offsets:raise ValueError('Witnessed compact TVFS metadata spec required')
else:spec=reviewed_encoding_spec(value)
if spec not in spec_offsets:spec_offsets[spec]=len(specs);specs.extend(spec+b'\0')
if table_width(len(specs))!=h['spec_offset_width']:raise ValueError('TVFS ESpec width growth requires CFT rewrite')
record=(bytes.fromhex(row['encoding_key'])[:9]+row['encoded_size'].to_bytes(4,'big')+
spec_offsets[spec].to_bytes(h['spec_offset_width'],'big')+row['decoded_size'].to_bytes(4,'big')+
bytes.fromhex(row['content_key'])+b'\0')
offset=len(cft);cft.extend(record)
if table_width(len(cft))!=h['cft_offset_width']:raise ValueError('TVFS CFT width growth requires VFS rewrite')
mapping[name]=len(vfs)
vfs.extend(b'\x01'+bytes(4)+row['decoded_size'].to_bytes(4,'big')+offset.to_bytes(h['cft_offset_width'],'big'))
path_data,depth=serialize_paths(mapping);tables.update(paths=path_data,container=bytes(cft),vfs=bytes(vfs),specs=bytes(specs))
result=_replace_tables(raw,h,tables,depth);checked=layout(result);after=paths(result,checked)
if {n:r['vfs_offset']for n,r in after.items()}!=mapping:raise ValueError('TVFS path serialization changed identity')
if any(mapping[n]!=offset for n,offset in before.items()if n not in references):raise ValueError('Unrelated TVFS path changed')
for name in('container','vfs','specs'):
old=h['tables'][name];new=checked['tables'][name]
if memoryview(raw)[old['offset']:old['offset']+old['size']]!=memoryview(result)[new['offset']:new['offset']+old['size']]:
raise ValueError('Original TVFS table prefix changed')
for name,row in references.items():
observed=spans(result,after[name],checked)
if len(observed)!=1 or observed[0]['content_offset']!=0 or observed[0]['content_length']!=row['decoded_size']:
raise ValueError('Staged TVFS span identity differs')
record=container_record(result,observed[0],checked)
if(any(record[k]!=row[k]for k in('content_key','encoded_size','decoded_size','encoding_spec'))or
record['encoding_key_prefix']!=row['encoding_key'][:18]or record['patch_count']!=0):
raise ValueError('Staged TVFS container identity differs')
return result,dict(kind='additive-native-tvfs-stage',original_md5=h['md5'],staged_md5=checked['md5'],
original_paths=len(original),new_paths=len(set(references)-before.keys()),
replaced_paths=sorted(set(references)&before.keys()),all_other_path_offsets_preserved=True,
old_cft_vfs_and_spec_prefixes_preserved=True,installed=False,native_rendering_verified=False)
def extend_files(raw,additions,*,expected_md5):
"""Add generic files, preserving all original CFT/VFS/spec byte prefixes.
Width growth rejects; no IDs allocated, storage written or client installed.
"""
h=layout(raw)
if h['md5']!=expected_md5:raise ValueError('Native TVFS content pin differs')
if h['flags']!=7:raise ValueError('Observed flags7 TVFS child required')
if not isinstance(additions,list)or not 1<=len(additions)<=8192:raise ValueError('TVFS addition bound')
original=paths(raw,h)
if any(wow_file_name(name)is None for name in original):raise ValueError('Generic40hex TVFS child required')
ids={int(n[:8],16)for n in original};fields={'file_data_id','content_key','encoding_key','decoded_size','encoded_size','encoding_spec'};references={}
for row in additions:
if not isinstance(row,dict)or set(row)!=fields:raise ValueError('Complete TVFS asset identity required')
ident=row['file_data_id']
if type(ident)is not int or not 0<ident<=0xffffffff or ident in ids:raise ValueError('TVFS FileDataID collision/bound')
ck=row['content_key']
if not isinstance(ck,str)or not re.fullmatch('[0-9a-f]{32}',ck):raise ValueError('TVFS asset content digest required')
name=f'{ident:08X}'+ck.upper();references[name]={k:v for k,v in row.items()if k!='file_data_id'};ids.add(ident)
return _stage_references(raw,references,h,original)
def extend_file_aliases(raw,aliases,*,expected_md5,local_encoding_proof,local_encoding_proof_sha256):
"""Add owned numeric names for exact existing, locally indexed containers.
Alias the original VFS offset. No container, span or ESpec is rewritten,
and no new-object compression-spec admission rule is relaxed.
"""
h=layout(raw)
if h['md5']!=expected_md5 or h['flags']!=7:
raise ValueError('Pinned flags7 TVFS alias parent required')
if (not isinstance(local_encoding_proof,bytes)or not 1<=len(local_encoding_proof)<=16777216 or
hashlib.sha256(local_encoding_proof).hexdigest()!=local_encoding_proof_sha256):
raise ValueError('Pinned local encoding proof differs')
try:proof=json.loads(local_encoding_proof)
except (ValueError,UnicodeDecodeError):raise ValueError('Local encoding proof JSON required')from None
if (not isinstance(proof,dict)or not isinstance(proof.get('status'),str)or
not proof['status'].startswith('PASS_')or not isinstance(proof.get('rows'),list)):
raise ValueError('Completed local encoding proof required')
approved={}
for row in proof['rows']:
reuse=row.get('reuse_candidate')if isinstance(row,dict)else None
if (not isinstance(reuse,dict)or row.get('status')!='REUSE_EXISTING_LOCALLY_INDEXED_ENCODING'or
not reuse.get('local_index',{}).get('locally_indexed_candidate')or
not any(r.get('span_within_segment')is True for r in reuse['local_index'].get('matches',[]))):
continue
metadata=reuse.get('encoded_metadata')
if not isinstance(metadata,dict):continue
approved[(row['content_key'],reuse['encoding_key'])]=dict(content_key=row['content_key'],
encoding_key=reuse['encoding_key'],decoded_size=row['decoded_size'],
encoded_size=metadata['encoded_size'],encoding_spec=metadata['encoding_spec'])
if not isinstance(aliases,list)or not 1<=len(aliases)<=8192:
raise ValueError('Bounded complete TVFS alias family required')
original=paths(raw,h)
if any(wow_file_name(n)is None for n in original):raise ValueError('Generic40hex TVFS alias child required')
ids={int(n[:8],16)for n in original};mapping={n:r['vfs_offset']for n,r in original.items()};added=[]
fields={'file_data_id','source_name','content_key','encoding_key','decoded_size','encoded_size','encoding_spec'}
for row in aliases:
if not isinstance(row,dict)or set(row)!=fields:raise ValueError('Complete TVFS alias identity required')
ident=row['file_data_id'];source=row['source_name'];name_info=wow_file_name(source)
if type(ident)is not int or not 0<ident<=0xffffffff or ident in ids:
raise ValueError('TVFS alias target FileDataID collision/bound')
if name_info is None or source not in original or name_info['content_key']!=row['content_key']:
raise ValueError('Existing exact-CKey TVFS alias source required')
identity={k:row[k]for k in fields-{'file_data_id','source_name'}}
if approved.get((row['content_key'],row['encoding_key']))!=identity:
raise ValueError('TVFS alias local encoding tuple unproved')
spans_found=spans(raw,original[source],h)
if len(spans_found)!=1 or spans_found[0]['content_offset']!=0 or spans_found[0]['content_length']!=row['decoded_size']:
raise ValueError('Whole single-span TVFS alias source required')
record=container_record(raw,spans_found[0],h)
if (record['patch_count']!=0 or record['encoding_key_prefix']!=row['encoding_key'][:18]or
any(record[k]!=row[k]for k in('content_key','decoded_size','encoded_size','encoding_spec'))):
raise ValueError('TVFS alias actual container tuple differs')
target=f'{ident:08X}'+row['content_key'].upper();mapping[target]=mapping[source];ids.add(ident)
added.append(dict(file_data_id=ident,source_name=source,target_name=target,vfs_offset=mapping[source],
content_key=row['content_key'],encoding_key=row['encoding_key']))
tables={n:raw[r['offset']:r['offset']+r['size']]for n,r in h['tables'].items()}
tables['paths'],depth=serialize_paths(mapping);result=_replace_tables(raw,h,tables,depth)
after_h=layout(result);after=paths(result,after_h)
if {n:r['vfs_offset']for n,r in after.items()}!=mapping:raise ValueError('TVFS alias lookup identity changed')
for name in('container','vfs','specs'):
a=h['tables'][name];b=after_h['tables'][name]
if raw[a['offset']:a['offset']+a['size']]!=result[b['offset']:b['offset']+b['size']]:
raise ValueError('TVFS alias changed original container/span/spec bytes')
return result,dict(kind='existing-local-container-TVFS-namespace-aliases',original_md5=h['md5'],
staged_md5=after_h['md5'],aliases=added,new_paths=len(added),all_original_path_offsets_preserved=True,
CFT_VFS_ESpec_bytes_and_offsets_exact=True,local_encoding_proof_sha256=local_encoding_proof_sha256,
new_objects_framed=0,installed=False,native_rendering_verified=False)
def replace_references(raw,replacements,*,expected_md5):
"""Update explicit existing parent references by appending independent rows.
Shared old CFT/VFS rows are never overwritten, so aliases remain unchanged.
The namespace names and all unrelated references retain their identities.
"""
h=layout(raw)
if h['md5']!=expected_md5:raise ValueError('Native TVFS content pin differs')
if h['flags']!=7:raise ValueError('Observed flags7 TVFS parent required')
if not isinstance(replacements,dict)or not 1<=len(replacements)<=4096:raise ValueError('TVFS reference replacement bound')
original=paths(raw,h)
if any(not isinstance(n,str)or n not in original for n in replacements):raise ValueError('Existing TVFS namespace reference required')
return _stage_references(raw,replacements,h,original)