#!/usr/bin/env python3 """Read-only whitelist sync of actual SPARK-2 gateway sources; run in workspace ordinary shell.""" import base64 import hashlib import json from pathlib import Path import re import subprocess import sys REMOTE=r''' import base64,hashlib,importlib.metadata,json,os,platform,re,sys from pathlib import Path root=Path('/home/gorios-spark-2/lan-voice') assert root.is_dir() and (root/'gateway.py').is_file(), 'actual gateway source missing' excluded={'.runtime','.git','.venv','venv','models','node_modules','__pycache__','logs','tmp','artifacts','cache','data','voices','assets','build','dist'} def allowed(path): if any(part.startswith('.') or part in excluded for part in path.parts): return False if any(x in path.name.lower() for x in ('diagnostic','report','private-key','credential')): return False if len(path.parts)==1: return path.suffix=='.py' or path.name in ('requirements.txt','requirements.lock','requirements-dev.txt','pyproject.toml','setup.cfg','README.md','LICENSE','LICENSE.txt') group=path.parts[0] if group in ('tests','scripts'): return path.suffix in ('.py','.sh') if group=='personas': return path.name.endswith('.lorebook.json') or path.suffix in ('.md','.txt') if group=='web': return path.suffix in ('.html','.js','.css','.svg') if group in ('deploy','config'): return path.suffix in ('.py','.sh','.md','.service','.toml','.ini','.conf') or path.name.endswith('.example') return False files={};total=0 for folder,dirs,names in os.walk(root,followlinks=False): dirs[:]=[name for name in dirs if not name.startswith('.') and name not in excluded and not (Path(folder)/name).is_symlink()] for name in names: source=Path(folder)/name;relative=source.relative_to(root) if not allowed(relative) or source.is_symlink() or not source.is_file(): continue if source.stat().st_size>2_000_000: raise RuntimeError('source file exceeds bound: '+str(relative)) data=source.read_bytes();data.decode('utf-8') total+=len(data) if total>20_000_000: raise RuntimeError('whitelist archive exceeds 20MB') files[str(relative)]={'sha256':hashlib.sha256(data).hexdigest(),'bytes':len(data),'content':base64.b64encode(data).decode()} required={'gateway.py','protocol.py','vad.py','history.py','guest_sessions.py','persona_resolver.py','segmentation.py','tts_debug.py','face_context.py','app.py','tests_fake.py'} assert required.issubset(files), 'required deployed modules missing' assert any(name.startswith('tests/') for name in files), 'tests missing' assert any(name.startswith('web/') for name in files), 'browser source missing' assert {'personas/lvbu.lorebook.json','personas/yangmi.lorebook.json'}.issubset(files), 'public lore missing' for name,row in files.items(): if hashlib.sha256((root/name).read_bytes()).hexdigest()!=row['sha256']: raise RuntimeError('concurrent source edit: '+name) packages={} for dist in importlib.metadata.distributions(): name,version=dist.metadata.get('Name',''),dist.version if not re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9_.-]*',name) or not re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9_.+!-]*',version): raise RuntimeError('non-version package metadata') packages[name.lower().replace('_','-')]=version source=base64.b64decode(files['gateway.py']['content']).decode() version=re.search(r"^VERSION\s*=\s*['\"]([^'\"]+)",source,re.M) print(json.dumps({'files':files,'code_version':version[1] if version else 'unknown','python':platform.python_version(),'machine':platform.machine(),'packages':packages,'archive_scope':'whitelisted source only; no runtime/models/credentials'})) ''' def scan(name, data): text=data.decode('utf-8') forbidden=['-----BEGIN '+kind+'-----' for kind in ('PRIVATE KEY','OPENSSH PRIVATE KEY','RSA PRIVATE KEY','EC PRIVATE KEY')] if any(value in text for value in forbidden): raise RuntimeError(f'Private key marker in {name}') patterns=[r'(?i)Bearer\s+[A-Za-z0-9_\-]{24,}', r'''(?i)(?:LAN_GATEWAY_TOKEN|LAN_VAD_TOKEN|password|api_key|access_token)\s*[=:]\s*["']?([A-Za-z0-9_+/=.-]{24,})''', r'https?://[^\s/]+@'] for pattern in patterns: for match in re.finditer(pattern,text): if match.lastindex and match.group(1).startswith('REPLACE_'): continue # A fixed reserved-domain negative fixture tests rejecting URL credentials. if name.endswith('tests/test_llm_provider.py') and match.group(0)=='http://user:password@' and text[match.end():].startswith('example.com/v1'): continue raise RuntimeError(f'Possible embedded secret in {name}; inspect locally before any Git add') def main(): root=Path(__file__).resolve().parents[1] target=root/'gateway' assert target.is_dir() and (target/'scripts/check-archive.py').is_file() command=('cd /home/gorios-spark-2/lan-voice && if [ -x .venv/bin/python ]; then exec .venv/bin/python -; elif [ -x venv/bin/python ]; then exec venv/bin/python -; else exec python3 -; fi') result=subprocess.run(['ssh','-o','BatchMode=yes','-o','ConnectTimeout=5','gorios-spark-2@192.168.31.61',command],input=REMOTE.encode(),capture_output=True,timeout=90) if result.returncode: print('Read-only remote archive failed; no raw source/stderr printed.');raise SystemExit(result.returncode) data=json.loads(result.stdout) expected=json.loads((root/'logs/voice-investigation/gateway-deploy.json').read_text())['gateway_sha256'] assert data['files']['gateway.py']['sha256']==expected, 'deployed gateway changed; review before archiving baseline' previous=json.loads((target/'SOURCE_MANIFEST.json').read_text()) if (target/'SOURCE_MANIFEST.json').exists() else {'files':{}} planned={};manifest={} for name,row in sorted(data['files'].items()): relative=Path(name) assert not relative.is_absolute() and '..' not in relative.parts out={'README.md':'docs/UPSTREAM_README.md','requirements.lock':'requirements.upstream.lock'}.get(name,name) content=base64.b64decode(row['content'],validate=True) assert hashlib.sha256(content).hexdigest()==row['sha256'] scan(out,content) planned[out]=content manifest[out]={'source':name,'sha256':row['sha256'],'bytes':len(content)} # Added v0.4.0 regressions were staged for deployment, not installed into production tests/. for name in ('test_face_context.py','test_gateway_reply_face.py'): out='tests/'+name;content=(root/'backend'/name).read_bytes();scan(out,content) planned[out]=content manifest[out]={'source':'workspace:backend/'+name,'sha256':hashlib.sha256(content).hexdigest(),'bytes':len(content)} lock=('# Deployed gateway Python '+data['python']+' / '+data['machine']+'; distribution versions only, no private URLs.\n'+ '\n'.join(name+'=='+version for name,version in sorted(data['packages'].items()))+'\n').encode() planned['requirements.lock']=lock manifest['requirements.lock']={'source':'deployed interpreter distribution metadata','sha256':hashlib.sha256(lock).hexdigest(),'bytes':len(lock)} for name,content in planned.items(): destination=target/name if destination.exists() and destination.read_bytes()!=content: before=previous['files'].get(name) assert before and hashlib.sha256(destination.read_bytes()).hexdigest()==before['sha256'], f'preserve local edit: {name}' for name,content in planned.items(): destination=target/name;destination.parent.mkdir(parents=True,exist_ok=True);destination.write_bytes(content) archive={'baseline_android_commit':'9b428fb76ffa1468aa46124b33d9c598cf3740d8','source':'SPARK-2 deployed lan-voice gateway','code_version':data['code_version'], 'python':data['python'],'machine':data['machine'],'scope':data['archive_scope'],'files':manifest} (target/'SOURCE_MANIFEST.json').write_text(json.dumps(archive,ensure_ascii=False,indent=2)+'\n') # Check the restored tree in isolation with the existing remote interpreter; do not install anything. import io,tarfile stream=io.BytesIO() with tarfile.open(fileobj=stream,mode='w:gz') as tar: for path in sorted(target.rglob('*')): if path.is_file() and '__pycache__' not in path.parts: tar.add(path,arcname=path.relative_to(target),recursive=False) payload=base64.b64encode(stream.getvalue()).decode() checker=""" import base64,io,subprocess,sys,tarfile,tempfile,json from pathlib import Path with tempfile.TemporaryDirectory(prefix='gateway-source-archive-') as folder: with tarfile.open(fileobj=io.BytesIO(base64.b64decode(payload)),mode='r:gz') as tar: for item in tar.getmembers(): assert item.isfile() and not Path(item.name).is_absolute() and '..' not in Path(item.name).parts tar.extractall(folder,filter='data') result=subprocess.run([sys.executable,str(Path(folder)/'scripts/check-archive.py')],cwd=folder,stdout=subprocess.PIPE,stderr=subprocess.STDOUT,timeout=90) print(json.dumps({'status':'passed' if result.returncode==0 else 'failed','test_output':result.stdout.decode(errors='replace')})) raise SystemExit(result.returncode) """ verified=subprocess.run(['ssh','-o','BatchMode=yes','-o','ConnectTimeout=5','gorios-spark-2@192.168.31.61',command],input=('payload='+repr(payload)+'\n'+checker).encode(),capture_output=True,timeout=120) check=json.loads(verified.stdout) if verified.stdout else {'status':'remote_check_failed'} check.update(source_files=len(manifest),deployed_gateway_sha256=expected,source_version=data['code_version']) (root/'logs/voice-investigation/gateway-archive.json').write_text(json.dumps(check,indent=2)+'\n') print(f'gateway/ archived {len(manifest)} source/lock files; isolated archive tests {check["status"]}; no deployment/restart') raise SystemExit(verified.returncode) if __name__=='__main__': main()