"""Deploy only the owner-authorized immutable opening. No SQL/service changes.""" from pathlib import Path import ctypes, hashlib, json, os, re, subprocess, sys, zipfile from datetime import datetime, timezone ROOT=Path(__file__).resolve().parents[2] PREP=ROOT/'outputs/investmoz-staff-preparation-20261012' OUT=ROOT/'outputs/investmoz-workflow-opening-20261012' PRIVATE=ROOT/'storage/app/private/investmoz-v2/portal-audit' PHP='C:/laragon/bin/php/php-8.5.11-Win32-vs17-x64/php.exe' DELIVERY='2e2f16c83483' ZIP_HASH='13ddf150f0f7ab03de83437064bf32f34a382727880e9c7470faf87a9d035819' MANIFEST_HASH='1da64a6def3d1ffe814e0fea8ac7b0f654320715032bfe7d89dabf750988cd64' MODE=sys.argv[1] assert MODE in ['stage','enable','contain'] def read(p): return json.loads(Path(p).read_text(encoding='utf-8-sig')) def sha(p): return hashlib.sha256(Path(p).read_bytes()).hexdigest() def save(p,v): Path(p).write_text(json.dumps(v,ensure_ascii=False,indent=2)+'\n',encoding='utf-8') def now(): return datetime.now(timezone.utc) folder=PREP/('abertura-workflow-'+DELIVERY) archive=folder/('investmoz-abertura-'+DELIVERY+'.zip') assert sha(archive)==ZIP_HASH and sha(folder/'manifesto-final.json')==MANIFEST_HASH manifest=read(folder/'manifesto-final.json') flags=list(manifest['flags']) assert len(flags)==3 and all(manifest['flags'].values()) assert manifest['schema_changes']==manifest['service_changes']==0 and manifest['migrations']==[] assert not (ROOT/'bootstrap/cache/config.php').exists() and not list((ROOT/'bootstrap/cache').glob('routes-*.php')), 'Unexpected configuration or route cache' OUT.mkdir(exist_ok=True) receipt_file=PRIVATE/'workflow-opening-2e2f16c83483-execution.json' def inspect(name): r=subprocess.run([PHP,str(PREP/'deployment-state-readonly.php')],cwd=ROOT,capture_output=True,text=True,encoding='utf-8',timeout=30) assert r.returncode==0, 'Read-only inspection failed; details withheld' result=json.loads(r.stdout); save(OUT/name,result) assert result['target']=='investemoz:5432' and result['app_url']=='https://portal-investidor.test' assert result['flags']['organization_country_enabled'] and result['flags']['profile_administration_enabled'] assert not result['flags']['notifications_enabled'] and not result['flags']['opportunity_modular_profiles_qa_enabled'] assert result['scanner']['available'] and result['queue']==[] assert len(result['staff'])==3 and all(x['email_verified'] and x['mfa_confirmed'] for x in result['staff']) return result def replace(target,data): target=Path(target); assert target.resolve().is_relative_to(ROOT.resolve()) target.parent.mkdir(parents=True,exist_ok=True) temp=target.with_name(target.name+'.opening-2e2f16c83483-new'); assert not temp.exists() if target==ROOT/'.env': # Retain the existing secured file/DACL. Windows refuses ReplaceFile on # this live configuration file; one exclusive FileStream writes the # reviewed bytes without exposing keys or widening access. temp.write_bytes(data) command="""$ErrorActionPreference='Stop'; $taskEnv='C:\\laragon\\www\\portal-investidor\\.env'; $taskTemp=$taskEnv+'.opening-2e2f16c83483-new'; Set-Acl -LiteralPath $taskTemp -AclObject (Get-Acl -LiteralPath $taskEnv); $taskBytes=[IO.File]::ReadAllBytes($taskTemp); $taskStream=[IO.File]::Open($taskEnv,[IO.FileMode]::Open,[IO.FileAccess]::Write,[IO.FileShare]::None); try { $taskStream.Write($taskBytes,0,$taskBytes.Length); $taskStream.SetLength($taskBytes.Length); $taskStream.Flush($true) } finally { $taskStream.Dispose() }; Remove-Item -LiteralPath $taskTemp""" completed=subprocess.run(['powershell.exe','-NoProfile','-Command',command],capture_output=True) assert completed.returncode==0, 'Configuration write failed; diagnostic details withheld' assert target.read_bytes()==data return temp.write_bytes(data) if target.exists(): # Windows ReplaceFile merges/preserves the replaced file's DACL and metadata. api=ctypes.WinDLL('kernel32',use_last_error=True).ReplaceFileW api.argtypes=[ctypes.c_wchar_p,ctypes.c_wchar_p,ctypes.c_wchar_p,ctypes.c_uint32,ctypes.c_void_p,ctypes.c_void_p] api.restype=ctypes.c_int if not api(str(target),str(temp),None,0,None,None): raise ctypes.WinError(ctypes.get_last_error()) else: os.replace(temp,target) def record(): save(receipt_file,receipt); save(OUT/'manifesto-execucao.json',receipt) if MODE=='stage': assert not receipt_file.exists(), 'Already staged: inspect receipt instead of repeating' before=inspect('destino-antes.json') assert all(not before['flags'][key] for key in ['profile_access_enabled','opportunity_dashboard_access_enabled','opportunity_specialized_drafts_enabled']) backup=read(PRIVATE/'internal-designation-target-backup.json') assert backup['result']=='passed' and backup['restore_verified'] and backup['files_verified'] assert backup['target']['database']=='investemoz' and int(backup['target']['port'])==5432 assert backup['restored_target']['port']==55441 and backup['restored_target']['database'].endswith('_test') assert now()