$e::class,'source'=>basename($e->getFile()),'line'=>$e->getLine()];if($e instanceof Illuminate\Database\QueryException){$safe['SQLSTATE']=$e->getCode();$safe['SQL_template_without_bindings']=$e->getSql();}fwrite(STDERR,json_encode($safe));exit(1);}); $mode=$argv[1]??'';if(!in_array($mode,['--qa','--apply-active'],true))throw new RuntimeException('Explicit mode required'); $root=dirname(__DIR__,2);require $root.'/vendor/autoload.php';$app=require $root.'/bootstrap/app.php';(new Illuminate\Foundation\Bootstrap\LoadEnvironmentVariables)->bootstrap($app);(new Illuminate\Foundation\Bootstrap\LoadConfiguration)->bootstrap($app); $location=json_decode(ltrim(file_get_contents(__DIR__.'/C132-private-location.json'),"\xEF\xBB\xBF"),true,512,JSON_THROW_ON_ERROR)['private_directory']; $backup=json_decode(file_get_contents(__DIR__.'/C132-backup-restoration.json'),true,512,JSON_THROW_ON_ERROR);$privateBackup=json_decode(file_get_contents($location.'/recovery/backup-proof-private.json'),true,512,JSON_THROW_ON_ERROR); if(empty($backup['restore_verified'])||hash_file('sha256',$privateBackup['dump'])!==$backup['dump_sha256']||time()-strtotime($backup['at'])>3600)throw new RuntimeException('Restore proof stale or changed'); $assessment=json_decode(file_get_contents(__DIR__.'/C132-usability.json'),true,512,JSON_THROW_ON_ERROR);$ids=$assessment['current_seed_affected_user_ids'];sort($ids);if($ids!==[14,15,16,17])throw new RuntimeException('Affected scope differs'); $active=config('database.connections.'.config('database.default'));if($active['driver']!=='pgsql'||!empty($active['url'])||(int)$active['port']!==5432||$active['database']!=='investemoz')throw new RuntimeException('Active configuration differs'); if($mode==='--apply-active'){ $qa=json_decode(file_get_contents(__DIR__.'/C132-rotation-QA.json'),true,512,JSON_THROW_ON_ERROR);if($qa['result']!=='passed'||$qa['affected_ids']!==$ids||$qa['backup_sha256']!==$backup['dump_sha256'])throw new RuntimeException('QA proof mismatch'); $connection=$active; }else{$connection=[...$active,'host'=>'127.0.0.1','port'=>55441,'database'=>$backup['restore_target']['database'],'username'=>'postgres','password'=>''];if(!preg_match('/^c132_incident_\d{8}_\d{6}_test$/',$connection['database']))throw new RuntimeException('QA name refused');} $manager=new Illuminate\Database\Capsule\Manager($app);$manager->addConnection($connection);$manager->setAsGlobal();$manager->bootEloquent(); Illuminate\Support\Facades\Facade::setFacadeApplication($app);$app->instance('db',$manager->getDatabaseManager());$app->bind('db.schema',fn()=>$manager->getConnection()->getSchemaBuilder()); $dispatcher=new Illuminate\Events\Dispatcher($app);$app->instance('events',$dispatcher);Illuminate\Support\Facades\Facade::clearResolvedInstance('events');Illuminate\Support\Facades\Facade::clearResolvedInstance('db');Illuminate\Support\Facades\Facade::clearResolvedInstance('db.schema'); $db=$manager->getConnection();$identity=(array)$db->selectOne('SELECT current_database() as database,inet_server_port() as port'); if($identity['database']!==$connection['database']||(int)$identity['port']!==(int)$connection['port'])throw new RuntimeException('Actual target differs'); if($mode==='--qa'&&(int)$identity['port']!==55441)throw new RuntimeException('QA cannot write active'); if($mode==='--apply-active'&&hash_file('sha256',$root.'/config/inertia.php')!=='80c68e12bf6cb64e39931e2467b43909893cea3eb6d04c3c1e68bdcb1236dfb7')throw new RuntimeException('Containment not applied'); $key=config('app.key');$crypt=new Illuminate\Encryption\Encrypter(str_starts_with($key,'base64:')?base64_decode(substr($key,7),true):$key,config('app.cipher'));Laravel\Fortify\Fortify::encryptUsing($crypt); $provider=new Laravel\Fortify\TwoFactorAuthenticationProvider(new PragmaRX\Google2FA\Google2FA());$action=new Laravel\Fortify\Actions\EnableTwoFactorAuthentication($provider); $access=new App\Services\PortalProfileAccess();$engine=new PragmaRX\Google2FA\Google2FA(); $incidentId='ead504de-19c1-4d84-9eca-d5649b8a456a';$correlation=$mode==='--qa'?'1f50aa2c-9063-4de3-aee4-f3b4be2a46c6':$incidentId; if($db->table('audit_events')->where('source_system','C132-incident-response')->where('correlation_id',$correlation)->exists())throw new RuntimeException('Operation already recorded; inspect before repetition'); $allBefore=$db->table('users')->orderBy('id')->get()->map(fn($u)=>(array)$u)->keyBy('id')->all(); $grantsBefore=$db->table('portal_role_assignments')->orderBy('id')->get()->toJson();$pairBefore=$db->table('portal_superuser_pair')->orderBy('id')->get()->toJson(); $protectedDir=$location.'/'.($mode==='--qa'?'QA-rotation-test':'handoff-affected-users'); if(is_dir($protectedDir)){if($mode!=='--qa'||array_diff(scandir($protectedDir),['.','..'])!==[])throw new RuntimeException('Existing handoff directory; inspect first');} else mkdir($protectedDir,0700,true); $checks=[];$users=[]; $capturedCandidates=json_decode(file_get_contents($location.'/secret-candidates-private.json'),true,512,JSON_THROW_ON_ERROR); $capturedSeeds=array_values(array_map(fn($x)=>strtoupper($x['value']),array_filter($capturedCandidates,fn($x)=>$x['kind']==='MFA_or_other_secret'&&is_string($x['value'])&&preg_match('/^[A-Z2-7]{16,}$/i',$x['value'])))); $db->beginTransaction(); try{ foreach($ids as$id){ $u=App\Models\User::query()->whereKey($id)->lockForUpdate()->firstOrFail();if($u->two_factor_confirmed_at===null||$u->two_factor_secret===null)throw new RuntimeException('MFA state changed'); $oldSecret=$crypt->decrypt($u->two_factor_secret);$oldRecovery=$u->two_factor_recovery_codes;$confirmed=$u->getRawOriginal('two_factor_confirmed_at');$password=$u->getRawOriginal('password');$revision=(int)$u->portal_access_revision; if($mode==='--apply-active'&&!in_array(strtoupper($oldSecret),$capturedSeeds,true))throw new RuntimeException('Current affected seed no longer matches exposure; stop before commit'); // The existing Fortify force-enrollment action replaces the seed and recovery codes. Keeping the confirmed flag enforces MFA at every login during secure handoff. $sessionsBefore=$db->table('sessions')->where('user_id',$id)->count();$tokensBefore=$db->getSchemaBuilder()->hasTable('personal_access_tokens')?$db->table('personal_access_tokens')->where('tokenable_type',App\Models\User::class)->where('tokenable_id',$id)->count():0; $action($u,true);$access->revokeSessions($u);$u->refresh(); $newSecret=$crypt->decrypt($u->two_factor_secret); if(hash_equals($oldSecret,$newSecret)||$oldRecovery===$u->two_factor_recovery_codes||$u->getRawOriginal('password')!==$password||$u->getRawOriginal('two_factor_confirmed_at')!==$confirmed||(int)$u->portal_access_revision!==$revision+1)throw new RuntimeException('Rotation invariants failed'); $newCode=$engine->getCurrentOtp($newSecret);$oldCode=$engine->getCurrentOtp($oldSecret); if(!$provider->verify($newSecret,$newCode)||$provider->verify($newSecret,$oldCode))throw new RuntimeException('MFA rotation validation failed'); $uri=$provider->qrCodeUrl(config('app.name'),$u->email,$newSecret); $svg=(new BaconQrCode\Writer(new BaconQrCode\Renderer\ImageRenderer(new BaconQrCode\Renderer\RendererStyle\RendererStyle(256),new BaconQrCode\Renderer\Image\SvgImageBackEnd())))->writeString($uri); $name=htmlspecialchars($u->name,ENT_QUOTES,'UTF-8');$email=htmlspecialchars($u->email,ENT_QUOTES,'UTF-8');$secret=htmlspecialchars($newSecret,ENT_QUOTES,'UTF-8'); $html='C132 MFA conta '.$id.'

MFA renovado — '.$name.'

Conta '.$id.' — '.$email.'

Entregar exclusivamente ao titular por canal privado. Adicionar no 2FAS Auth uma nova entrada para esta conta no portal ativo. A entrada anterior deixou de funcionar. Nunca enviar este QR/segredo na conversa ou por ligação pública.

'.$svg.'

Alternativa manual: '.$secret.'. TOTP, SHA-1, 6 dígitos, 30 segundos.

Depois: login no portal ativo com a password própria e o novo código, abrir o dashboard e confirmar com o responsável. MFA permanece obrigatório; os papéis e a password não mudaram.

'; file_put_contents($protectedDir.'/conta-'.$id.'-2fas-local.html',$html); $sessionsAfter=$db->table('sessions')->where('user_id',$id)->count();$tokensAfter=$db->getSchemaBuilder()->hasTable('personal_access_tokens')?$db->table('personal_access_tokens')->where('tokenable_type',App\Models\User::class)->where('tokenable_id',$id)->count():0;if($sessionsAfter||$tokensAfter||$u->remember_token!==null)throw new RuntimeException('Revocation incomplete'); $checks[]=['user_id'=>$id,'seed_rotated'=>true,'recovery_codes_rotated'=>true,'old_seed_code_rejected'=>true,'new_seed_code_accepted'=>true,'password_unchanged'=>true,'MFA_required_unchanged'=>true,'access_revision_incremented'=>true,'sessions_revoked'=>$sessionsBefore,'api_tokens_revoked'=>$tokensBefore,'remaining_authenticated_sessions'=>0,'remaining_api_tokens'=>0]; $users[]=['id'=>$id,'name'=>$u->name,'email'=>$u->email,'local_file'=>'conta-'.$id.'-2fas-local.html'];unset($oldSecret,$newSecret,$oldCode,$newCode,$svg,$uri,$secret,$html); } $allAfter=$db->table('users')->orderBy('id')->get()->map(fn($u)=>(array)$u)->keyBy('id')->all(); foreach($allBefore as$id=>$before){if(!in_array((int)$id,$ids,true)&&$before!==$allAfter[$id])throw new RuntimeException('Unaffected user changed');} if($grantsBefore!==$db->table('portal_role_assignments')->orderBy('id')->get()->toJson()||$pairBefore!==$db->table('portal_superuser_pair')->orderBy('id')->get()->toJson())throw new RuntimeException('Roles or pair changed'); $db->table('audit_events')->insert(['source_system'=>'C132-incident-response','entity_type'=>'security_incident','action'=>'C132_affected_MFA_rotated_and_sessions_revoked','data_classification'=>'restricted','actor_user_id'=>null,'correlation_id'=>$correlation,'after_data'=>json_encode(['authorization'=>'Explicit owner instruction in conversation; administrative incident response, no human account impersonated','case'=>'C132','affected_user_ids'=>$ids,'evidence'=>'Current TOTP seeds matched retained QR/secret responses','checks'=>$checks,'new_secret_values_in_audit'=>false,'incident_closed'=>false],JSON_THROW_ON_ERROR)]); $db->commit(); }catch(Throwable$e){$db->rollBack();throw$e;} file_put_contents($protectedDir.'/handoff-manifest-private.json',json_encode(['users'=>$users,'files_contain_secrets'=>true,'distribute_only_to_each_legitimate_holder'=>true,'public_URL'=>null],JSON_PRETTY_PRINT|JSON_THROW_ON_ERROR)); $result=['at'=>gmdate('c'),'result'=>'passed','mode'=>$mode,'target'=>$identity,'affected_ids'=>$ids,'checks'=>$checks,'roles_and_superuser_pair_unchanged'=>true,'unaffected_users_unchanged'=>true,'app_key_not_rotated'=>true,'MFA_not_disabled'=>true,'no_external_messages_sent'=>true,'secret_values_in_report'=>false,'secure_handoff_required'=>$mode==='--apply-active','backup_sha256'=>$backup['dump_sha256'],'audit_correlation_id'=>$correlation]; file_put_contents(__DIR__.'/'.($mode==='--qa'?'C132-rotation-QA.json':'C132-rotation-active.json'),json_encode($result,JSON_PRETTY_PRINT|JSON_THROW_ON_ERROR));echo json_encode($result,JSON_THROW_ON_ERROR);