Files
dpl/scripts/fuc-xb-acceptance/mail.php
T

77 lines
7.5 KiB
PHP

<?php
declare(strict_types=1);
umask(0077);error_reporting(E_ALL);ini_set('display_errors','0');
$root='/var/www/wwwroot/fuc-xb-test/current';
$private='/var/www/wwwroot/fuc-xb-test/private/live-acceptance-20261104';
if(!is_dir($private))throw new RuntimeException('Preflight directory missing');
$out=$private.'/mail-result.json';
if(is_file($out))throw new RuntimeException('Refuse second delivery; inspect receipt');
function legacyMailConfig(): array {
$cwd=getcwd();chdir('/www/wwwroot/fuuuu.cloud');require 'config/.config.php';
$dsn=!empty($_ENV['db_socket'])?'mysql:unix_socket='.$_ENV['db_socket']:'mysql:host='.$_ENV['db_host'].';port='.$_ENV['db_port'];
$p=new PDO($dsn.';dbname='.$_ENV['db_database'].';charset=utf8mb4',$_ENV['db_username'],$_ENV['db_password'],[PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION,PDO::ATTR_DEFAULT_FETCH_MODE=>PDO::FETCH_ASSOC]);
$p->exec('SET TRANSACTION READ ONLY');$p->beginTransaction();
$s=$p->query("SELECT item,value FROM config WHERE item IN ('smtp_host','smtp_port','smtp_username','smtp_password','smtp_sender','smtp_ssl')")->fetchAll(PDO::FETCH_KEY_PAIR);
$v=$p->query("SELECT apikey,auther FROM mail_must WHERE client='resend' AND status=1 LIMIT 1")->fetch();
$p->rollBack();chdir($cwd);
if(($s['smtp_host']??'')!=='mail.privateemail.com'||($s['smtp_sender']??'')!=='[email protected]'||empty($s['smtp_password'])||empty($v['apikey']))throw new RuntimeException('Registered FUC transports changed');
return ['smtp'=>$s,'resend'=>$v];
}
$legacy=legacyMailConfig();
putenv('XB_INSTANCE=fuc-xb-test');$_SERVER['XB_INSTANCE']=$_ENV['XB_INSTANCE']='fuc-xb-test';
require $root.'/vendor/autoload.php';$app=require $root.'/bootstrap/app.php';$app->make(Illuminate\Contracts\Console\Kernel::class)->bootstrap();
use Illuminate\Support\Facades\{DB,Cache};
use App\Models\MailMessage;
if(DB::connection()->getDatabaseName()!=='fuc_xb_test')throw new RuntimeException('Wrong database');
// Isolate settings cache too: never publish uncommitted secrets/settings to shared Redis.
config(['cache.stores.redis'=>['driver'=>'array'],'cache.default'=>'redis']);
Cache::purge('redis');$app->forgetInstance(App\Support\Setting::class);
$recipient='[email protected]';$key='fuc-xb-live-mail-20261104';
if(MailMessage::count()!==0)throw new RuntimeException('Unexpected existing mail; stop before sending');
$result=['recipient'=>$recipient,'sender'=>'[email protected]','real_deliveries'=>[],'simulated'=>false,'native_http_kernel'=>true,'production_site_changed'=>false];
$baseline=['users'=>App\Models\User::count(),'orders'=>App\Models\Order::count(),'balance'=>(int)App\Models\User::sum('balance'),'settings_hash'=>hash('sha256',DB::table('v2_settings')->orderBy('id')->get()->toJson())];
$db=DB::connection();$db->beginTransaction();
try {
$flow=array_replace((array)admin_setting('mail_flow',[]),['enabled'=>true,'resend_enabled'=>true,'resend_key'=>$legacy['resend']['apikey'],'resend_from'=>$legacy['resend']['auther'],'reply_to'=>'[email protected]','inbound_enabled'=>false,'auto_reply_enabled'=>false,'report_enabled'=>false,'logo_path'=>'','daily_limit'=>100,'monthly_limit'=>3000]);
// Uncommitted settings remain invisible to other PHP/FPM requests.
app(App\Support\Setting::class)->save(['mail_flow'=>$flow,'automatic_mail_policy'=>['level'=>3,'since'=>null]]);
config(['queue.default'=>'sync','mail.driver'=>'smtp','mail.host'=>$legacy['smtp']['smtp_host'],'mail.port'=>(int)$legacy['smtp']['smtp_port'],'mail.username'=>$legacy['smtp']['smtp_username'],'mail.password'=>$legacy['smtp']['smtp_password'],'mail.encryption'=>'ssl','mail.from.address'=>'[email protected]','mail.from.name'=>'FUC-XB_TEST','mailflow.logo_path'=>'']);
$r=Illuminate\Http\Request::create('https://fuc-xb-test.gemcook.net/api/v1/passport/comm/sendEmailVerify','POST',['email'=>$recipient],[],[],['HTTP_ACCEPT'=>'application/json','REMOTE_ADDR'=>'127.0.0.1']);
app()->instance('request',$r);$response=app(Illuminate\Contracts\Http\Kernel::class)->handle($r);
if($response->getStatusCode()!==200)throw new RuntimeException('Native verification request failed');
$first=MailMessage::where('email',$recipient)->where('purpose','verification')->firstOrFail();
if(!in_array($first->status,['submitted','delivered'],true)||!in_array($first->channel,['resend','conventional'],true))throw new RuntimeException('Verification not submitted');
$code=Cache::get(App\Utils\CacheKey::get('EMAIL_VERIFY_CODE',$recipient));
if(!preg_match('/^\d{6}$/',(string)$code))throw new RuntimeException('Verification cache contract failed');
$result['verification_http_status']=200;$result['verification_code_cached_in_isolated_process']=true;
$before=$first->attempts;
(new App\Jobs\SendEmailJob(['email'=>$recipient,'subject'=>'FUC-XB verification idempotency check','template_name'=>'verify','purpose'=>'verification','message_key'=>$first->message_key,'template_value'=>['name'=>'FUC-XB_TEST','code'=>$code,'url'=>'https://fuc-xb-test.tomtojapan.online']]))->handle();
$first->refresh();if($first->attempts!==$before)throw new RuntimeException('Mail duplicate submitted again');
$result['same_message_key_does_not_resend']=true;
$second=App\Services\MailService::sendEmail(['email'=>$recipient,'subject'=>'[FUC-XB隔离验收 20261104] 通知邮件','template_name'=>'notify','purpose'=>'admin_test','message_key'=>$key.'-notification','template_value'=>['name'=>'FUC-XB_TEST','content'=>'隔离测试站真实通知邮件,仅用于验收。不涉及正式切换、扣款或原用户通知。','url'=>'https://fuc-xb-test.tomtojapan.online']]);
if(!in_array($second['status']??null,['submitted','delivered'],true))throw new RuntimeException('Notification not submitted');
foreach(MailMessage::where('email',$recipient)->get()as$m){
$event=null;
if($m->channel==='resend'){
try{$detail=app(App\Services\MailFlow\ResendClient::class)->retrieve($m->provider_id);$event=$detail['last_event']??null;}catch(Throwable){$event='provider_status_unavailable';}
}
$result['real_deliveries'][]=['purpose'=>$m->purpose,'channel'=>$m->channel,'status'=>$m->status,'provider_event'=>$event,'fallback_reason'=>$m->fallback_reason,'attempts'=>$m->attempts,'provider_id'=>$m->provider_id];
}
$result['both_messages_submitted']=count($result['real_deliveries'])===2;
file_put_contents($out,json_encode($result,JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT));chmod($out,0600);
} catch(Throwable $e) {
$result['failed']=get_class($e);$result['failure_stage']=$e->getMessage();
file_put_contents($out,json_encode($result,JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT));chmod($out,0600);
throw $e;
} finally {
while($db->transactionLevel()>0)$db->rollBack();
Cache::store('redis')->forget(App\Support\Setting::CACHE_KEY);
Cache::forget(App\Utils\CacheKey::get('EMAIL_VERIFY_CODE',$recipient));
Cache::forget(App\Utils\CacheKey::get('LAST_SEND_EMAIL_VERIFY_TIMESTAMP',$recipient));
Cache::forget('mailflow:resend:usage');
}
$after=['users'=>App\Models\User::count(),'orders'=>App\Models\Order::count(),'balance'=>(int)App\Models\User::sum('balance'),'settings_hash'=>hash('sha256',DB::table('v2_settings')->orderBy('id')->get()->toJson())];
$result['temporary_settings_and_database_rows_rolled_back']=$baseline===$after&&MailMessage::count()===0;
$result['verification_code_cleared']=true;$result['passed']=($result['both_messages_submitted']??false)&&$result['temporary_settings_and_database_rows_rolled_back'];
file_put_contents($out,json_encode($result,JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT));echo json_encode($result,JSON_UNESCAPED_UNICODE).PHP_EOL;