Files
Investidor-V2/outputs/investmoz-staff-preparation-20261012/prepare-accounts.php
T
nala 287e991486
tests / ci (push) Waiting to run
oportunidades 7
2026-10-13 11:40:29 +02:00

88 lines
11 KiB
PHP

<?php
// One-off, owner-authorized preparation. Reuses Fortify; not a new portal endpoint.
ini_set('zend.exception_ignore_args','1');
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Password;
use Illuminate\Support\Str;
use App\Models\User;
try {
$root=dirname(__DIR__,2);$mode=$argv[1]??'';
if(!in_array($mode,['--qa','--apply-active-staff'],true))throw new RuntimeException('Explicit mode required');
$qa=$mode==='--qa';
$plan=json_decode(file_get_contents($root.'/storage/app/private/investmoz-v2/portal-audit/internal-designation-plan.json'),true,512,JSON_THROW_ON_ERROR);
$source=$qa?$plan['source']:$root;
require $source.($qa?'/qa-autoload.php':'/vendor/autoload.php');$app=require $source.'/bootstrap/app.php';
(new Illuminate\Foundation\Bootstrap\LoadEnvironmentVariables)->bootstrap($app);
(new Illuminate\Foundation\Bootstrap\LoadConfiguration)->bootstrap($app);
$c=config('database.connections.'.config('database.default'));
$expectedDb=$qa?$plan['target']['database']:'investemoz';$expectedPort=$qa?55441:5432;
if($c['driver']!=='pgsql'||!empty($c['url'])||!in_array($c['host'],['127.0.0.1','localhost'],true)||(int)$c['port']!==$expectedPort||$c['database']!==$expectedDb)throw new RuntimeException('Connection guard refused');
$beforeEnv=hash_file('sha256',$source.'/.env');$beforeBuild=hash_file('sha256',$source.'/public/build/manifest.json');
if(!$qa){
$qaProof=json_decode(file_get_contents(__DIR__.'/qa-result.json'),true,512,JSON_THROW_ON_ERROR);
if(($qaProof['result']??'')!=='prepared_pending_personal_validation'||count($qaProof['accounts'])!==3||!$qaProof['idempotency_verified'])throw new RuntimeException('QA preparation not demonstrated');
$backup=json_decode(file_get_contents($root.'/storage/app/private/investmoz-v2/portal-audit/internal-designation-target-backup.json'),true,512,JSON_THROW_ON_ERROR);
if(!$backup['restore_verified']||!$backup['files_verified']||strtotime($backup['valid_until'])<time()||$backup['target']['database']!=='investemoz'||(int)$backup['target']['port']!==5432||$backup['active_manifest_sha256']!==$beforeBuild||$backup['active_files_manifest']['runtime/.env']!==$beforeEnv)throw new RuntimeException('Current backup/restore refused');
if(hash_file('sha256',$backup['dump_path'])!==$backup['dump_sha256'])throw new RuntimeException('Backup bytes mismatch');
}
$app->make(Illuminate\Contracts\Console\Kernel::class)->bootstrap();
if((int)DB::selectOne('SELECT inet_server_port() AS port')->port!==$expectedPort||DB::selectOne('SELECT current_database() AS db')->db!==$expectedDb)throw new RuntimeException('Actual target refused');
if(!$qa&&(!config('portal.organization_country_enabled')||!config('portal.profile_administration_enabled')||config('portal.profile_access_enabled')))throw new RuntimeException('Active containment differs');
$private=$source.'/storage/app/private/staff-validation-20261012';if(!is_dir($private))mkdir($private,0700,true);
$receipt=$private.'/preparation.json';
if(is_file($receipt)){
$old=json_decode(file_get_contents($receipt),true,512,JSON_THROW_ON_ERROR);
foreach($old['accounts']as$a){$u=User::findOrFail($a['id']);if(strtolower($u->email)!==$a['email'])throw new RuntimeException('Existing receipt identity mismatch');}
$old['idempotency_verified']=true;$old['repeat_created_accounts']=0;
file_put_contents($receipt,json_encode($old,JSON_PRETTY_PRINT|JSON_THROW_ON_ERROR));
file_put_contents(__DIR__.($qa?'/qa-result.json':'/result.json'),json_encode($old,JSON_PRETTY_PRINT|JSON_THROW_ON_ERROR));
echo json_encode(['result'=>'existing_preparation_recovered','accounts'=>count($old['accounts']),'created'=>0,'target'=>$expectedDb.':'.$expectedPort],JSON_THROW_ON_ERROR);exit;
}
$staff=[
['key'=>'aurora','name'=>$qa?'Synthetic staff preparation Aurora QA':'Aurora Chachuaio','email'=>$qa?'staff-aurora-qa@example.invalid':'aurora.chachuaio@tempo.co.mz','role'=>'promoter','scope'=>'Operação interna do portal pela Tempo Lda; promotor real e autorização de divulgação separados em cada oportunidade.'],
['key'=>'palmira','name'=>$qa?'Synthetic staff preparation Palmira QA':'Palmira Uamusse','email'=>$qa?'staff-palmira-qa@example.invalid':'palmira.matsinhe@tempo.co.mz','role'=>'validator','scope'=>'Seis categorias base; revisão de todas as organizações, preservando independência e conflito de interesse.'],
['key'=>'mario','name'=>$qa?'Synthetic staff preparation Mario QA':'Mario Melembe','email'=>$qa?'staff-mario-qa@example.invalid':'mario.melembe@tempo.co.mz','role'=>'publisher','scope'=>'Seis categorias base; publicação de todas as organizações no catálogo público após aprovação independente e autorização de divulgação.']
];
$types=App\Services\OpportunityCanonicalContract::BASE_CATEGORIES;
$jobsBefore=DB::table('jobs')->count();$grantsBefore=DB::table('portal_role_assignments')->count();$orgsBefore=DB::table('organizations')->count();
$oldUsers=DB::table('users')->orderBy('id')->get(['id','password','email_verified_at','two_factor_secret','two_factor_confirmed_at','portal_access_revision'])->keyBy('id')->all();
$local=[];$accounts=[];$operation=(string)Str::uuid();$created=0;
DB::transaction(function()use($staff,$qa,$types,$private,$operation,&$local,&$accounts,&$created){
DB::select('SELECT pg_advisory_xact_lock(121026,1)');
foreach($staff as$s){
$matches=User::whereRaw('lower(email)=?',[$s['email']])->get();
if($matches->count()>1)throw new RuntimeException('Ambiguous existing account');
$user=$matches->first();$new=$user===null;
if($new){
// No Registered notification event: no email is sent on another person's behalf.
// Bootstrap credential is CSPRNG and is discarded, not provided to staff.
$bootstrap='T1!'.bin2hex(random_bytes(32));
$user=app(Laravel\Fortify\Contracts\CreatesNewUsers::class)->create(['name'=>$s['name'],'email'=>$s['email'],'password'=>$bootstrap,'password_confirmation'=>$bootstrap]);
if(!password_verify($bootstrap,$user->password))throw new RuntimeException('Password hashing failed');
unset($bootstrap);$created++;
$token=Password::broker()->createToken($user);
if(!Password::broker()->tokenExists($user,$token))throw new RuntimeException('Reset token refused');
$local[$s['key']]=['email'=>$s['email'],'url'=>rtrim(config('app.url'),'/').'/reset-password/'.rawurlencode($token).'?email='.rawurlencode($s['email']),'expires_at'=>gmdate('c',time()+60*(int)config('auth.passwords.users.expire'))];
unset($token);
}
$a=['id'=>$user->id,'name'=>$user->name,'email'=>$s['email'],'created'=>$new,'intended_role'=>$s['role'],'scope'=>$s['scope'],'categories'=>$types,'contact_verified'=>$user->email_verified_at!==null,'MFA_confirmed'=>$user->two_factor_confirmed_at!==null,'role_assigned'=>false];
DB::table('audit_events')->insert(['source_system'=>'portal-owner-staff-preparation','entity_type'=>'authorization','actor_user_id'=>null,'action'=>'staff_account_prepared','data_classification'=>'restricted','correlation_id'=>$operation,
'after_data'=>json_encode(['operation_id'=>$operation,'user_id'=>$user->id,'name'=>$user->name,'email'=>$s['email'],'intended_role'=>$s['role'],'categories'=>$types,'scope'=>$s['scope'],'employer'=>['name'=>'Tempo Lda','nuit'=>'400993114'],'authorization'=>'Explicit owner instruction in Codex session 2026-10-12: create Aurora, Mario and Palmira entries for validation','execution'=>'Fortify creation action through local operator command; no authenticated portal actor is claimed','contact_validation'=>'pending person','MFA'=>'pending person','operational_assignment'=>'pending authenticated administration','qa'=>$qa],JSON_THROW_ON_ERROR)]);
$accounts[]=$a;
}
});
// Confidential links are stored locally only, outside public storage and evidence.
$esc=fn($v)=>htmlspecialchars($v,ENT_QUOTES|ENT_SUBSTITUTE,'UTF-8');
foreach($local as$key=>$l){
$u=array_values(array_filter($accounts,fn($a)=>$a['email']===$l['email']))[0];
$html='<!doctype html><html lang="pt"><meta charset="utf-8"><title>Entrada pessoal — '.$esc($u['name']).'</title><body><h1>'.$esc($u['name']).'</h1><p>Conta '.$u['id'].' — '.$esc($u['email']).'</p><p>Este ficheiro é confidencial e destinado apenas ao titular. Não publicar nem copiar o endereço para a conversa.</p><ol><li>Abra uma janela privada, sem a sessão de outro utilizador.</li><li>Copie o endereço abaixo para essa janela e defina a sua própria palavra-passe.</li><li>Entre com o seu email e peça a confirmação do contacto no ecrã de verificação.</li><li>Configure e confirme o seu autenticador em /settings/security.</li></ol><p><a href="'.$esc($l['url']).'">Definir a minha palavra-passe</a></p><p style="overflow-wrap:anywhere">'.$esc($l['url']).'</p><p>Expira em '.$esc($l['expires_at']).' (UTC). Após expirar, use a opção Esqueci a palavra-passe do portal.</p><p>O endereço portal-investidor.test é local. A validação deve decorrer numa máquina onde o endereço e o certificado do portal já funcionem.</p><p>Papel previsto: '.$esc($u['intended_role']).'. Ainda não atribuído.</p></body></html>';
file_put_contents($private.'/'.$key.'-entrada-local.html',$html);
}
foreach($oldUsers as$id=>$old){$now=DB::table('users')->where('id',$id)->first(['id','password','email_verified_at','two_factor_secret','two_factor_confirmed_at','portal_access_revision']);if((array)$old!==(array)$now)throw new RuntimeException('An existing identity changed');}
if(DB::table('jobs')->count()!==$jobsBefore||DB::table('portal_role_assignments')->count()!==$grantsBefore||DB::table('organizations')->count()!==$orgsBefore||hash_file('sha256',$source.'/.env')!==$beforeEnv||hash_file('sha256',$source.'/public/build/manifest.json')!==$beforeBuild)throw new RuntimeException('Scope changed');
$result=['at'=>gmdate('c'),'result'=>'prepared_pending_personal_validation','target'=>$expectedDb.':'.$expectedPort,'qa'=>$qa,'operation_id'=>$operation,'created_accounts'=>$created,'accounts'=>$accounts,'idempotency_verified'=>false,'existing_accounts_preserved'=>count($oldUsers),'emails_sent'=>0,'operational_grants_created'=>0,'organizations_created'=>0,'MFA_or_email_validation_fabricated'=>false,'COUNTRY02_preserved'=>true,'workflow_enabled'=>config('portal.profile_access_enabled'),'product_code_changed'=>false,'configuration_changed'=>false,'entry_files_private'=>true];
file_put_contents($receipt,json_encode($result,JSON_PRETTY_PRINT|JSON_THROW_ON_ERROR));
file_put_contents(__DIR__.($qa?'/qa-result.json':'/result.json'),json_encode($result,JSON_PRETTY_PRINT|JSON_THROW_ON_ERROR));
echo json_encode(['result'=>$result['result'],'target'=>$result['target'],'created_accounts'=>$created,'accounts'=>array_map(fn($a)=>['id'=>$a['id'],'email'=>$a['email'],'role'=>'pending '.$a['intended_role']],$accounts),'emails_sent'=>0,'operational_grants_created'=>0],JSON_THROW_ON_ERROR);
}catch(Throwable $e){echo json_encode(['result'=>'stopped','type'=>$e::class,'line'=>$e->getLine()],JSON_THROW_ON_ERROR);exit(1);}