From 553be20f69b0fd10c51a15b1b9ac363a1a052447 Mon Sep 17 00:00:00 2001 From: Dev Date: Wed, 25 Nov 2026 00:46:06 +0100 Subject: [PATCH 1/2] Connect native shop presentation to completed HTML responses --- website/ops/oscommerce/DuneAccount.php | 207 +++++++++--------- .../oscommerce/test-shop-design-bootstrap.php | 41 ++++ website/ops/publish-realm-design.py | 13 ++ website/ops/test_native_shop_design.py | 10 + 4 files changed, 172 insertions(+), 99 deletions(-) create mode 100644 website/ops/oscommerce/test-shop-design-bootstrap.php create mode 100644 website/ops/test_native_shop_design.py diff --git a/website/ops/oscommerce/DuneAccount.php b/website/ops/oscommerce/DuneAccount.php index 7a90f7da..53a96505 100644 --- a/website/ops/oscommerce/DuneAccount.php +++ b/website/ops/oscommerce/DuneAccount.php @@ -1,99 +1,108 @@ -$expires,'path'=>'/','secure'=>true,'httponly'=>true,'samesite'=>'Lax']); } - private static function api(string $operation,array $payload):array { - $config=json_decode(file_get_contents('/home/dunerealms/.config/integrations.json'),true,8,JSON_THROW_ON_ERROR); - $curl=curl_init('http://127.0.0.1:3003/internal/integrations/'.$operation); - curl_setopt_array($curl,[CURLOPT_POST=>true,CURLOPT_POSTFIELDS=>json_encode($payload),CURLOPT_HTTPHEADER=>['Content-Type: application/json','Authorization: Bearer '.$config['secret']],CURLOPT_RETURNTRANSFER=>true,CURLOPT_TIMEOUT=>6]); - $body=curl_exec($curl);$status=curl_getinfo($curl,CURLINFO_HTTP_CODE);curl_close($curl); - if($status!==200) throw new \yii\web\HttpException($status===401?401:503,'DuneRealms sign-in is unavailable. Please sign in again.'); - return json_decode($body,true,32,JSON_THROW_ON_ERROR); - } - public function bootstrap($app):void { $app->on(\yii\base\Application::EVENT_BEFORE_REQUEST,fn()=>self::handle($app)); } - private static function redirect($app,string $url):never { $app->response->redirect($url,303)->send();$app->end();exit; } - private static function start($app,string $next='/catalog/'):never { - $state=self::token();$nonce=self::token(); - $app->db->createCommand()->delete('dune_sso_states','expires_at < :now',[':now'=>time()])->execute(); - $app->db->createCommand()->insert('dune_sso_states',['state_hash'=>hash('sha256',$state),'nonce_hash'=>hash('sha256',$nonce),'next_path'=>$next,'expires_at'=>time()+300])->execute(); - self::cookie('__Host-dune_osc_state',$nonce,time()+300); - $url='https://cp.dunerealms.com/sso/authorize?client=oscommerce&state='.rawurlencode($state); - if(($_SERVER['HTTP_SEC_FETCH_DEST']??'')==='iframe'){ - $js=json_encode(['type'=>'dune-shop-signin','url'=>$url],JSON_HEX_TAG|JSON_HEX_AMP); - $app->response->format=\yii\web\Response::FORMAT_HTML; - $parent='https://shop.dunerealms.com';$ref=parse_url($_SERVER['HTTP_REFERER']??''); - if(($ref['scheme']??'')==='https'&&in_array($ref['host']??'',['www.dunerealms.com','dunerealms.com','cp.dunerealms.com','shop.dunerealms.com'],true))$parent='https://'.$ref['host']; - $app->response->content='

Continue with your DuneRealms account

'; - $app->response->send();$app->end();exit; - } - self::redirect($app,$url); - } - private static function synchronize($app,array $identity):int { - if(!preg_match('/^[a-f0-9-]{36}$/i',$identity['id']??'')||!preg_match('/^[a-f0-9]{64}$/',$identity['sessionRef']??''))throw new \yii\web\ForbiddenHttpException('Invalid account identity'); - $db=$app->db;$transaction=$db->beginTransaction(); - try{ - $id=$db->createCommand('SELECT customer_id FROM dune_account_links WHERE account_id=:id FOR UPDATE',[':id'=>$identity['id']])->queryScalar(); - $email=self::email($identity); - $collision=$db->createCommand('SELECT customers_id FROM customers WHERE customers_email_address=:email AND customers_id<>:id',[':email'=>$email,':id'=>(int)$id])->queryScalar(); - if($collision)throw new \yii\web\HttpException(409,'This email is linked to another shop customer. Please contact support to link the accounts.'); - if(!$id){ - $db->createCommand("SET SESSION sql_mode=''")->execute(); - $db->createCommand()->insert('customers',['customers_firstname'=>mb_substr($identity['username']??'Player',0,32),'customers_lastname'=>'','customers_email_address'=>$email,'customers_password'=>password_hash(bin2hex(random_bytes(32)),PASSWORD_BCRYPT),'customers_status'=>1,'platform_id'=>\common\classes\platform::currentId()])->execute(); - $id=(int)$db->getLastInsertID(); - $db->createCommand()->insert('dune_account_links',['account_id'=>$identity['id'],'customer_id'=>$id])->execute(); - $db->createCommand()->insert('customers_info',['customers_info_id'=>$id,'customers_info_date_account_created'=>gmdate('Y-m-d H:i:s')])->execute(); - } - $db->createCommand()->update('customers',['customers_firstname'=>mb_substr($identity['username']??'Player',0,32),'customers_email_address'=>$email],['customers_id'=>$id])->execute(); - $transaction->commit();return (int)$id; - }catch(\Throwable $e){$transaction->rollBack();throw $e;} - } - private static function handle($app):void { - $app->response->headers->set('Referrer-Policy','no-referrer'); - $path=parse_url($_SERVER['REQUEST_URI']??'/',PHP_URL_PATH); - if(empty($_GET['action'])&&preg_match('#^/catalog/(?:[A-Z]{3}/)?$#',$path)){ - $currency=$_GET['currency']??'EUR'; - if(!is_string($currency)||!in_array($currency,['EUR','GBP','USD'],true))$currency='EUR'; - self::redirect($app,'/catalog/dune-shop?currency='.$currency); - } - if($path==='/dune-login.php'){ - if(!isset($_GET['code']))self::start($app); - $state=$_GET['state']??'';$nonce=$_COOKIE['__Host-dune_osc_state']??''; - if(!is_string($state)||!is_string($nonce)||!preg_match('/^[A-Za-z0-9_-]{43}$/',$state)||!preg_match('/^[A-Za-z0-9_-]{43}$/',$nonce))throw new \yii\web\ForbiddenHttpException('Invalid sign-in state'); - $row=$app->db->createCommand('SELECT * FROM dune_sso_states WHERE state_hash=:state AND nonce_hash=:nonce AND expires_at>=:now',[':state'=>hash('sha256',$state),':nonce'=>hash('sha256',$nonce),':now'=>time()])->queryOne(); - if(!$row)throw new \yii\web\ForbiddenHttpException('Expired or already used sign-in state'); - $removed=$app->db->createCommand()->delete('dune_sso_states',['state_hash'=>$row['state_hash'],'nonce_hash'=>$row['nonce_hash']])->execute(); - if($removed!==1)throw new \yii\web\ForbiddenHttpException('Sign-in already used'); - $identity=self::api('redeem',['client'=>'oscommerce','code'=>$_GET['code']]); - $id=self::synchronize($app,$identity);$token=self::token(); - $app->db->createCommand()->insert('dune_sso_sessions',['token_hash'=>hash('sha256',$token),'account_id'=>$identity['id'],'session_ref'=>$identity['sessionRef'],'expires_at'=>time()+43200])->execute(); - self::cookie('__Host-dune_oscommerce',$token,time()+43200);self::cookie('__Host-dune_osc_state','',time()-3600); - self::redirect($app,'https://shop.dunerealms.com/'); - } - $token=$_COOKIE['__Host-dune_oscommerce']??'';$identity=null; - if(is_string($token)&&preg_match('/^[A-Za-z0-9_-]{43}$/',$token)){ - $row=$app->db->createCommand('SELECT account_id,session_ref FROM dune_sso_sessions WHERE token_hash=:token AND expires_at>:now',[':token'=>hash('sha256',$token),':now'=>time()])->queryOne(); - if($row){ - try{$identity=self::api('identity',['sessionRef'=>$row['session_ref'],'client'=>'oscommerce']);}catch(\yii\web\HttpException $e){if($e->statusCode!==401)throw $e;} - if(($identity['id']??null)!==$row['account_id'])$identity=null; - } - } - if($identity){ - $id=self::synchronize($app,$identity); - if((int)$app->user->id!==$id){ - if(!$app->user->isGuest){$app->user->logout(false);global $cart;if(is_object($cart)&&is_callable([$cart,'reset']))$cart->reset();} - $app->session->regenerateID(true); - $customer=new \common\components\Customer(\common\components\Customer::LOGIN_WITHOUT_CHECK); - if(!$customer->loginCustomer(self::email($identity),$id))throw new \yii\web\ForbiddenHttpException('Account link failed'); - } - }elseif(!$app->user->isGuest){$app->user->logout(false);self::cookie('__Host-dune_oscommerce','',time()-3600);} - if(preg_match('#^/catalog/(?:[A-Z]{3}/)?account/(login|create|password|password-forgotten)#',$path))self::start($app); - if(preg_match('#^/catalog/(?:[A-Z]{3}/)?account/?$#',$path))self::redirect($app,'https://cp.dunerealms.com/'); - if(preg_match('#^/catalog/(?:[A-Z]{3}/)?checkout#',$path)&&!$identity)self::start($app,$path); - } -} +$expires,'path'=>'/','secure'=>true,'httponly'=>true,'samesite'=>'Lax']); } + private static function api(string $operation,array $payload):array { + $config=json_decode(file_get_contents('/home/dunerealms/.config/integrations.json'),true,8,JSON_THROW_ON_ERROR); + $curl=curl_init('http://127.0.0.1:3003/internal/integrations/'.$operation); + curl_setopt_array($curl,[CURLOPT_POST=>true,CURLOPT_POSTFIELDS=>json_encode($payload),CURLOPT_HTTPHEADER=>['Content-Type: application/json','Authorization: Bearer '.$config['secret']],CURLOPT_RETURNTRANSFER=>true,CURLOPT_TIMEOUT=>6]); + $body=curl_exec($curl);$status=curl_getinfo($curl,CURLINFO_HTTP_CODE);curl_close($curl); + if($status!==200) throw new \yii\web\HttpException($status===401?401:503,'DuneRealms sign-in is unavailable. Please sign in again.'); + return json_decode($body,true,32,JSON_THROW_ON_ERROR); + } + // DUNE SHOP DESIGN BOOTSTRAP START + public function bootstrap($app):void { + $app->on(\yii\base\Application::EVENT_BEFORE_REQUEST,fn()=>self::handle($app)); + $app->response->on(\yii\web\Response::EVENT_AFTER_PREPARE,static function($event):void { + $response=$event->sender;$path=parse_url($_SERVER['REQUEST_URI']??'/',PHP_URL_PATH); + if(!is_string($path)||!str_starts_with($path,'/catalog/')||$response->statusCode<200||$response->statusCode>=300||$response->format!==\yii\web\Response::FORMAT_HTML||!is_string($response->content)||stripos($response->content,'content,'/oscommerce-inner.js'))return; + $response->content=preg_replace('~~i','',$response->content,1); + }); + } + // DUNE SHOP DESIGN BOOTSTRAP END + private static function redirect($app,string $url):never { $app->response->redirect($url,303)->send();$app->end();exit; } + private static function start($app,string $next='/catalog/'):never { + $state=self::token();$nonce=self::token(); + $app->db->createCommand()->delete('dune_sso_states','expires_at < :now',[':now'=>time()])->execute(); + $app->db->createCommand()->insert('dune_sso_states',['state_hash'=>hash('sha256',$state),'nonce_hash'=>hash('sha256',$nonce),'next_path'=>$next,'expires_at'=>time()+300])->execute(); + self::cookie('__Host-dune_osc_state',$nonce,time()+300); + $url='https://cp.dunerealms.com/sso/authorize?client=oscommerce&state='.rawurlencode($state); + if(($_SERVER['HTTP_SEC_FETCH_DEST']??'')==='iframe'){ + $js=json_encode(['type'=>'dune-shop-signin','url'=>$url],JSON_HEX_TAG|JSON_HEX_AMP); + $app->response->format=\yii\web\Response::FORMAT_HTML; + $parent='https://shop.dunerealms.com';$ref=parse_url($_SERVER['HTTP_REFERER']??''); + if(($ref['scheme']??'')==='https'&&in_array($ref['host']??'',['www.dunerealms.com','dunerealms.com','cp.dunerealms.com','shop.dunerealms.com'],true))$parent='https://'.$ref['host']; + $app->response->content='

Continue with your DuneRealms account

'; + $app->response->send();$app->end();exit; + } + self::redirect($app,$url); + } + private static function synchronize($app,array $identity):int { + if(!preg_match('/^[a-f0-9-]{36}$/i',$identity['id']??'')||!preg_match('/^[a-f0-9]{64}$/',$identity['sessionRef']??''))throw new \yii\web\ForbiddenHttpException('Invalid account identity'); + $db=$app->db;$transaction=$db->beginTransaction(); + try{ + $id=$db->createCommand('SELECT customer_id FROM dune_account_links WHERE account_id=:id FOR UPDATE',[':id'=>$identity['id']])->queryScalar(); + $email=self::email($identity); + $collision=$db->createCommand('SELECT customers_id FROM customers WHERE customers_email_address=:email AND customers_id<>:id',[':email'=>$email,':id'=>(int)$id])->queryScalar(); + if($collision)throw new \yii\web\HttpException(409,'This email is linked to another shop customer. Please contact support to link the accounts.'); + if(!$id){ + $db->createCommand("SET SESSION sql_mode=''")->execute(); + $db->createCommand()->insert('customers',['customers_firstname'=>mb_substr($identity['username']??'Player',0,32),'customers_lastname'=>'','customers_email_address'=>$email,'customers_password'=>password_hash(bin2hex(random_bytes(32)),PASSWORD_BCRYPT),'customers_status'=>1,'platform_id'=>\common\classes\platform::currentId()])->execute(); + $id=(int)$db->getLastInsertID(); + $db->createCommand()->insert('dune_account_links',['account_id'=>$identity['id'],'customer_id'=>$id])->execute(); + $db->createCommand()->insert('customers_info',['customers_info_id'=>$id,'customers_info_date_account_created'=>gmdate('Y-m-d H:i:s')])->execute(); + } + $db->createCommand()->update('customers',['customers_firstname'=>mb_substr($identity['username']??'Player',0,32),'customers_email_address'=>$email],['customers_id'=>$id])->execute(); + $transaction->commit();return (int)$id; + }catch(\Throwable $e){$transaction->rollBack();throw $e;} + } + private static function handle($app):void { + $app->response->headers->set('Referrer-Policy','no-referrer'); + $path=parse_url($_SERVER['REQUEST_URI']??'/',PHP_URL_PATH); + if(empty($_GET['action'])&&preg_match('#^/catalog/(?:[A-Z]{3}/)?$#',$path)){ + $currency=$_GET['currency']??'EUR'; + if(!is_string($currency)||!in_array($currency,['EUR','GBP','USD'],true))$currency='EUR'; + self::redirect($app,'/catalog/dune-shop?currency='.$currency); + } + if($path==='/dune-login.php'){ + if(!isset($_GET['code']))self::start($app); + $state=$_GET['state']??'';$nonce=$_COOKIE['__Host-dune_osc_state']??''; + if(!is_string($state)||!is_string($nonce)||!preg_match('/^[A-Za-z0-9_-]{43}$/',$state)||!preg_match('/^[A-Za-z0-9_-]{43}$/',$nonce))throw new \yii\web\ForbiddenHttpException('Invalid sign-in state'); + $row=$app->db->createCommand('SELECT * FROM dune_sso_states WHERE state_hash=:state AND nonce_hash=:nonce AND expires_at>=:now',[':state'=>hash('sha256',$state),':nonce'=>hash('sha256',$nonce),':now'=>time()])->queryOne(); + if(!$row)throw new \yii\web\ForbiddenHttpException('Expired or already used sign-in state'); + $removed=$app->db->createCommand()->delete('dune_sso_states',['state_hash'=>$row['state_hash'],'nonce_hash'=>$row['nonce_hash']])->execute(); + if($removed!==1)throw new \yii\web\ForbiddenHttpException('Sign-in already used'); + $identity=self::api('redeem',['client'=>'oscommerce','code'=>$_GET['code']]); + $id=self::synchronize($app,$identity);$token=self::token(); + $app->db->createCommand()->insert('dune_sso_sessions',['token_hash'=>hash('sha256',$token),'account_id'=>$identity['id'],'session_ref'=>$identity['sessionRef'],'expires_at'=>time()+43200])->execute(); + self::cookie('__Host-dune_oscommerce',$token,time()+43200);self::cookie('__Host-dune_osc_state','',time()-3600); + self::redirect($app,'https://shop.dunerealms.com/'); + } + $token=$_COOKIE['__Host-dune_oscommerce']??'';$identity=null; + if(is_string($token)&&preg_match('/^[A-Za-z0-9_-]{43}$/',$token)){ + $row=$app->db->createCommand('SELECT account_id,session_ref FROM dune_sso_sessions WHERE token_hash=:token AND expires_at>:now',[':token'=>hash('sha256',$token),':now'=>time()])->queryOne(); + if($row){ + try{$identity=self::api('identity',['sessionRef'=>$row['session_ref'],'client'=>'oscommerce']);}catch(\yii\web\HttpException $e){if($e->statusCode!==401)throw $e;} + if(($identity['id']??null)!==$row['account_id'])$identity=null; + } + } + if($identity){ + $id=self::synchronize($app,$identity); + if((int)$app->user->id!==$id){ + if(!$app->user->isGuest){$app->user->logout(false);global $cart;if(is_object($cart)&&is_callable([$cart,'reset']))$cart->reset();} + $app->session->regenerateID(true); + $customer=new \common\components\Customer(\common\components\Customer::LOGIN_WITHOUT_CHECK); + if(!$customer->loginCustomer(self::email($identity),$id))throw new \yii\web\ForbiddenHttpException('Account link failed'); + } + }elseif(!$app->user->isGuest){$app->user->logout(false);self::cookie('__Host-dune_oscommerce','',time()-3600);} + if(preg_match('#^/catalog/(?:[A-Z]{3}/)?account/(login|create|password|password-forgotten)#',$path))self::start($app); + if(preg_match('#^/catalog/(?:[A-Z]{3}/)?account/?$#',$path))self::redirect($app,'https://cp.dunerealms.com/'); + if(preg_match('#^/catalog/(?:[A-Z]{3}/)?checkout#',$path)&&!$identity)self::start($app,$path); + } +} diff --git a/website/ops/oscommerce/test-shop-design-bootstrap.php b/website/ops/oscommerce/test-shop-design-bootstrap.php new file mode 100644 index 00000000..f757e1a8 --- /dev/null +++ b/website/ops/oscommerce/test-shop-design-bootstrap.php @@ -0,0 +1,41 @@ +handler=$handler; } + } +} +namespace { + require $argv[1]??__DIR__.'/DuneAccount.php'; + $app=new class { + public $response;public $authenticationHooks=0; + public function __construct(){ $this->response=new \yii\web\Response(); } + public function on($event,$handler):void { if($event!==\yii\base\Application::EVENT_BEFORE_REQUEST||!is_callable($handler))throw new \RuntimeException('Authentication hook changed');$this->authenticationHooks++; } + }; + (new \frontend\components\DuneAccount())->bootstrap($app); + if($app->authenticationHooks!==1)throw new \RuntimeException('Authentication hook missing'); + $cases=[ + ['/catalog/dune-shop',200,'html','Shop',true], + ['/catalog/product?products_id=1',200,'html','Product',true], + ['/catalog/shopping-cart',200,'html','Cart',true], + ['/catalog/checkout',200,'html','Checkout',true], + ['/catalog/dune-shop',200,'html','',false], + ['/catalog/dune-shop/sales-feed',200,'json','{"items":[]}',false], + ['/catalog/account',303,'html','Redirect',false], + ['/catalog/product',500,'html','Error',false], + ['/catalog/product',200,'html','
Partial response
',false], + ['/catalog/download',200,'raw','Raw download',false], + ['/admin/',200,'html','Admin',false], + ['/dune-login.php',200,'html','Identity handoff',false], + ]; + foreach($cases as [$path,$status,$format,$content,$decorate]){ + $_SERVER['REQUEST_URI']=$path;$r=$app->response;$r->statusCode=$status;$r->format=$format;$r->content=$content; + ($r->handler)((object)['sender'=>$r]); + if($decorate){if(substr_count($r->content,'src="/oscommerce-inner.js?v=realm-design-1"')!==1||!str_contains($r->content,' defer>'))throw new \RuntimeException('Missing single presentation bridge: '.$path);} + elseif($r->content!==$content)throw new \RuntimeException('Non-page response changed: '.$path); + if($r->statusCode!==$status||$r->format!==$format)throw new \RuntimeException('Response contract changed'); + } + echo count($cases)." native response cases passed; authentication hook retained\n"; +} diff --git a/website/ops/publish-realm-design.py b/website/ops/publish-realm-design.py index 8050b889..3c235b1a 100644 --- a/website/ops/publish-realm-design.py +++ b/website/ops/publish-realm-design.py @@ -44,6 +44,19 @@ shop_inner=(shop_app/'oscommerce-inner.js').resolve(strict=True);assert shop_inn # Keep the native resizing/checkout bridge and apply the same design inside it. changes['shop-native/oscommerce-inner.js']=append(shop_inner.read_text(),script) targets['shop-native/oscommerce-inner.js']=shop_inner +account=(shop_app/'lib/frontend/components/DuneAccount.php').resolve(strict=True);assert account.is_relative_to(shop_app) +original_account=account.read_text();source_account=(release/'ops/oscommerce/DuneAccount.php').read_text() +bootstrap_pattern=r' // DUNE SHOP DESIGN BOOTSTRAP START[\s\S]*? // DUNE SHOP DESIGN BOOTSTRAP END' +bootstrap=re.search(bootstrap_pattern,source_account).group(0) +if 'DUNE SHOP DESIGN BOOTSTRAP START' in original_account: + assert len(re.findall(bootstrap_pattern,original_account))==1 + account_content=re.sub(bootstrap_pattern,lambda _:bootstrap,original_account,count=1) +else: + old_bootstrap=' public function bootstrap($app):void { $app->on(\\yii\\base\\Application::EVENT_BEFORE_REQUEST,fn()=>self::handle($app)); }' + assert original_account.count(old_bootstrap)==1 + account_content=original_account.replace(old_bootstrap,bootstrap,1) + assert account_content.replace(bootstrap,old_bootstrap,1)==original_account +changes['shop-native/DuneAccount.php']=account_content;targets['shop-native/DuneAccount.php']=account for kind,document in [('clans','clan-center-index.html'),('corp','company-center-index.html')]: root=pathlib.Path('/var/www/dunerealms-'+kind).resolve(strict=True) name=kind+'-portal/index.html';changes[name]=(release/'ops'/document).read_text();targets[name]=(root/'index.html').resolve(strict=True) diff --git a/website/ops/test_native_shop_design.py b/website/ops/test_native_shop_design.py new file mode 100644 index 00000000..304f53d8 --- /dev/null +++ b/website/ops/test_native_shop_design.py @@ -0,0 +1,10 @@ +import pathlib,shutil,subprocess,unittest + +class NativeShopDesign(unittest.TestCase): + @unittest.skipUnless(shutil.which('php'),'PHP is checked on the native shop host') + def test_response_hook_preserves_non_page_responses(self): + root=pathlib.Path(__file__).resolve().parent/'oscommerce' + result=subprocess.run(['php',str(root/'test-shop-design-bootstrap.php'),str(root/'DuneAccount.php')],capture_output=True,text=True,check=True) + self.assertIn('12 native response cases passed',result.stdout) + +if __name__=='__main__':unittest.main() From dc9d42c0a369f0781f17e444d3b82a9bffba5184 Mon Sep 17 00:00:00 2001 From: Dev Date: Wed, 25 Nov 2026 00:46:35 +0100 Subject: [PATCH 2/2] Keep the native shop change in the repository line format --- website/ops/oscommerce/DuneAccount.php | 216 ++++++++++++------------- 1 file changed, 108 insertions(+), 108 deletions(-) diff --git a/website/ops/oscommerce/DuneAccount.php b/website/ops/oscommerce/DuneAccount.php index 53a96505..d49ca00e 100644 --- a/website/ops/oscommerce/DuneAccount.php +++ b/website/ops/oscommerce/DuneAccount.php @@ -1,108 +1,108 @@ -$expires,'path'=>'/','secure'=>true,'httponly'=>true,'samesite'=>'Lax']); } - private static function api(string $operation,array $payload):array { - $config=json_decode(file_get_contents('/home/dunerealms/.config/integrations.json'),true,8,JSON_THROW_ON_ERROR); - $curl=curl_init('http://127.0.0.1:3003/internal/integrations/'.$operation); - curl_setopt_array($curl,[CURLOPT_POST=>true,CURLOPT_POSTFIELDS=>json_encode($payload),CURLOPT_HTTPHEADER=>['Content-Type: application/json','Authorization: Bearer '.$config['secret']],CURLOPT_RETURNTRANSFER=>true,CURLOPT_TIMEOUT=>6]); - $body=curl_exec($curl);$status=curl_getinfo($curl,CURLINFO_HTTP_CODE);curl_close($curl); - if($status!==200) throw new \yii\web\HttpException($status===401?401:503,'DuneRealms sign-in is unavailable. Please sign in again.'); - return json_decode($body,true,32,JSON_THROW_ON_ERROR); - } - // DUNE SHOP DESIGN BOOTSTRAP START - public function bootstrap($app):void { - $app->on(\yii\base\Application::EVENT_BEFORE_REQUEST,fn()=>self::handle($app)); - $app->response->on(\yii\web\Response::EVENT_AFTER_PREPARE,static function($event):void { - $response=$event->sender;$path=parse_url($_SERVER['REQUEST_URI']??'/',PHP_URL_PATH); - if(!is_string($path)||!str_starts_with($path,'/catalog/')||$response->statusCode<200||$response->statusCode>=300||$response->format!==\yii\web\Response::FORMAT_HTML||!is_string($response->content)||stripos($response->content,'content,'/oscommerce-inner.js'))return; - $response->content=preg_replace('~~i','',$response->content,1); - }); - } - // DUNE SHOP DESIGN BOOTSTRAP END - private static function redirect($app,string $url):never { $app->response->redirect($url,303)->send();$app->end();exit; } - private static function start($app,string $next='/catalog/'):never { - $state=self::token();$nonce=self::token(); - $app->db->createCommand()->delete('dune_sso_states','expires_at < :now',[':now'=>time()])->execute(); - $app->db->createCommand()->insert('dune_sso_states',['state_hash'=>hash('sha256',$state),'nonce_hash'=>hash('sha256',$nonce),'next_path'=>$next,'expires_at'=>time()+300])->execute(); - self::cookie('__Host-dune_osc_state',$nonce,time()+300); - $url='https://cp.dunerealms.com/sso/authorize?client=oscommerce&state='.rawurlencode($state); - if(($_SERVER['HTTP_SEC_FETCH_DEST']??'')==='iframe'){ - $js=json_encode(['type'=>'dune-shop-signin','url'=>$url],JSON_HEX_TAG|JSON_HEX_AMP); - $app->response->format=\yii\web\Response::FORMAT_HTML; - $parent='https://shop.dunerealms.com';$ref=parse_url($_SERVER['HTTP_REFERER']??''); - if(($ref['scheme']??'')==='https'&&in_array($ref['host']??'',['www.dunerealms.com','dunerealms.com','cp.dunerealms.com','shop.dunerealms.com'],true))$parent='https://'.$ref['host']; - $app->response->content='

Continue with your DuneRealms account

'; - $app->response->send();$app->end();exit; - } - self::redirect($app,$url); - } - private static function synchronize($app,array $identity):int { - if(!preg_match('/^[a-f0-9-]{36}$/i',$identity['id']??'')||!preg_match('/^[a-f0-9]{64}$/',$identity['sessionRef']??''))throw new \yii\web\ForbiddenHttpException('Invalid account identity'); - $db=$app->db;$transaction=$db->beginTransaction(); - try{ - $id=$db->createCommand('SELECT customer_id FROM dune_account_links WHERE account_id=:id FOR UPDATE',[':id'=>$identity['id']])->queryScalar(); - $email=self::email($identity); - $collision=$db->createCommand('SELECT customers_id FROM customers WHERE customers_email_address=:email AND customers_id<>:id',[':email'=>$email,':id'=>(int)$id])->queryScalar(); - if($collision)throw new \yii\web\HttpException(409,'This email is linked to another shop customer. Please contact support to link the accounts.'); - if(!$id){ - $db->createCommand("SET SESSION sql_mode=''")->execute(); - $db->createCommand()->insert('customers',['customers_firstname'=>mb_substr($identity['username']??'Player',0,32),'customers_lastname'=>'','customers_email_address'=>$email,'customers_password'=>password_hash(bin2hex(random_bytes(32)),PASSWORD_BCRYPT),'customers_status'=>1,'platform_id'=>\common\classes\platform::currentId()])->execute(); - $id=(int)$db->getLastInsertID(); - $db->createCommand()->insert('dune_account_links',['account_id'=>$identity['id'],'customer_id'=>$id])->execute(); - $db->createCommand()->insert('customers_info',['customers_info_id'=>$id,'customers_info_date_account_created'=>gmdate('Y-m-d H:i:s')])->execute(); - } - $db->createCommand()->update('customers',['customers_firstname'=>mb_substr($identity['username']??'Player',0,32),'customers_email_address'=>$email],['customers_id'=>$id])->execute(); - $transaction->commit();return (int)$id; - }catch(\Throwable $e){$transaction->rollBack();throw $e;} - } - private static function handle($app):void { - $app->response->headers->set('Referrer-Policy','no-referrer'); - $path=parse_url($_SERVER['REQUEST_URI']??'/',PHP_URL_PATH); - if(empty($_GET['action'])&&preg_match('#^/catalog/(?:[A-Z]{3}/)?$#',$path)){ - $currency=$_GET['currency']??'EUR'; - if(!is_string($currency)||!in_array($currency,['EUR','GBP','USD'],true))$currency='EUR'; - self::redirect($app,'/catalog/dune-shop?currency='.$currency); - } - if($path==='/dune-login.php'){ - if(!isset($_GET['code']))self::start($app); - $state=$_GET['state']??'';$nonce=$_COOKIE['__Host-dune_osc_state']??''; - if(!is_string($state)||!is_string($nonce)||!preg_match('/^[A-Za-z0-9_-]{43}$/',$state)||!preg_match('/^[A-Za-z0-9_-]{43}$/',$nonce))throw new \yii\web\ForbiddenHttpException('Invalid sign-in state'); - $row=$app->db->createCommand('SELECT * FROM dune_sso_states WHERE state_hash=:state AND nonce_hash=:nonce AND expires_at>=:now',[':state'=>hash('sha256',$state),':nonce'=>hash('sha256',$nonce),':now'=>time()])->queryOne(); - if(!$row)throw new \yii\web\ForbiddenHttpException('Expired or already used sign-in state'); - $removed=$app->db->createCommand()->delete('dune_sso_states',['state_hash'=>$row['state_hash'],'nonce_hash'=>$row['nonce_hash']])->execute(); - if($removed!==1)throw new \yii\web\ForbiddenHttpException('Sign-in already used'); - $identity=self::api('redeem',['client'=>'oscommerce','code'=>$_GET['code']]); - $id=self::synchronize($app,$identity);$token=self::token(); - $app->db->createCommand()->insert('dune_sso_sessions',['token_hash'=>hash('sha256',$token),'account_id'=>$identity['id'],'session_ref'=>$identity['sessionRef'],'expires_at'=>time()+43200])->execute(); - self::cookie('__Host-dune_oscommerce',$token,time()+43200);self::cookie('__Host-dune_osc_state','',time()-3600); - self::redirect($app,'https://shop.dunerealms.com/'); - } - $token=$_COOKIE['__Host-dune_oscommerce']??'';$identity=null; - if(is_string($token)&&preg_match('/^[A-Za-z0-9_-]{43}$/',$token)){ - $row=$app->db->createCommand('SELECT account_id,session_ref FROM dune_sso_sessions WHERE token_hash=:token AND expires_at>:now',[':token'=>hash('sha256',$token),':now'=>time()])->queryOne(); - if($row){ - try{$identity=self::api('identity',['sessionRef'=>$row['session_ref'],'client'=>'oscommerce']);}catch(\yii\web\HttpException $e){if($e->statusCode!==401)throw $e;} - if(($identity['id']??null)!==$row['account_id'])$identity=null; - } - } - if($identity){ - $id=self::synchronize($app,$identity); - if((int)$app->user->id!==$id){ - if(!$app->user->isGuest){$app->user->logout(false);global $cart;if(is_object($cart)&&is_callable([$cart,'reset']))$cart->reset();} - $app->session->regenerateID(true); - $customer=new \common\components\Customer(\common\components\Customer::LOGIN_WITHOUT_CHECK); - if(!$customer->loginCustomer(self::email($identity),$id))throw new \yii\web\ForbiddenHttpException('Account link failed'); - } - }elseif(!$app->user->isGuest){$app->user->logout(false);self::cookie('__Host-dune_oscommerce','',time()-3600);} - if(preg_match('#^/catalog/(?:[A-Z]{3}/)?account/(login|create|password|password-forgotten)#',$path))self::start($app); - if(preg_match('#^/catalog/(?:[A-Z]{3}/)?account/?$#',$path))self::redirect($app,'https://cp.dunerealms.com/'); - if(preg_match('#^/catalog/(?:[A-Z]{3}/)?checkout#',$path)&&!$identity)self::start($app,$path); - } -} +$expires,'path'=>'/','secure'=>true,'httponly'=>true,'samesite'=>'Lax']); } + private static function api(string $operation,array $payload):array { + $config=json_decode(file_get_contents('/home/dunerealms/.config/integrations.json'),true,8,JSON_THROW_ON_ERROR); + $curl=curl_init('http://127.0.0.1:3003/internal/integrations/'.$operation); + curl_setopt_array($curl,[CURLOPT_POST=>true,CURLOPT_POSTFIELDS=>json_encode($payload),CURLOPT_HTTPHEADER=>['Content-Type: application/json','Authorization: Bearer '.$config['secret']],CURLOPT_RETURNTRANSFER=>true,CURLOPT_TIMEOUT=>6]); + $body=curl_exec($curl);$status=curl_getinfo($curl,CURLINFO_HTTP_CODE);curl_close($curl); + if($status!==200) throw new \yii\web\HttpException($status===401?401:503,'DuneRealms sign-in is unavailable. Please sign in again.'); + return json_decode($body,true,32,JSON_THROW_ON_ERROR); + } + // DUNE SHOP DESIGN BOOTSTRAP START + public function bootstrap($app):void { + $app->on(\yii\base\Application::EVENT_BEFORE_REQUEST,fn()=>self::handle($app)); + $app->response->on(\yii\web\Response::EVENT_AFTER_PREPARE,static function($event):void { + $response=$event->sender;$path=parse_url($_SERVER['REQUEST_URI']??'/',PHP_URL_PATH); + if(!is_string($path)||!str_starts_with($path,'/catalog/')||$response->statusCode<200||$response->statusCode>=300||$response->format!==\yii\web\Response::FORMAT_HTML||!is_string($response->content)||stripos($response->content,'content,'/oscommerce-inner.js'))return; + $response->content=preg_replace('~~i','',$response->content,1); + }); + } + // DUNE SHOP DESIGN BOOTSTRAP END + private static function redirect($app,string $url):never { $app->response->redirect($url,303)->send();$app->end();exit; } + private static function start($app,string $next='/catalog/'):never { + $state=self::token();$nonce=self::token(); + $app->db->createCommand()->delete('dune_sso_states','expires_at < :now',[':now'=>time()])->execute(); + $app->db->createCommand()->insert('dune_sso_states',['state_hash'=>hash('sha256',$state),'nonce_hash'=>hash('sha256',$nonce),'next_path'=>$next,'expires_at'=>time()+300])->execute(); + self::cookie('__Host-dune_osc_state',$nonce,time()+300); + $url='https://cp.dunerealms.com/sso/authorize?client=oscommerce&state='.rawurlencode($state); + if(($_SERVER['HTTP_SEC_FETCH_DEST']??'')==='iframe'){ + $js=json_encode(['type'=>'dune-shop-signin','url'=>$url],JSON_HEX_TAG|JSON_HEX_AMP); + $app->response->format=\yii\web\Response::FORMAT_HTML; + $parent='https://shop.dunerealms.com';$ref=parse_url($_SERVER['HTTP_REFERER']??''); + if(($ref['scheme']??'')==='https'&&in_array($ref['host']??'',['www.dunerealms.com','dunerealms.com','cp.dunerealms.com','shop.dunerealms.com'],true))$parent='https://'.$ref['host']; + $app->response->content='

Continue with your DuneRealms account

'; + $app->response->send();$app->end();exit; + } + self::redirect($app,$url); + } + private static function synchronize($app,array $identity):int { + if(!preg_match('/^[a-f0-9-]{36}$/i',$identity['id']??'')||!preg_match('/^[a-f0-9]{64}$/',$identity['sessionRef']??''))throw new \yii\web\ForbiddenHttpException('Invalid account identity'); + $db=$app->db;$transaction=$db->beginTransaction(); + try{ + $id=$db->createCommand('SELECT customer_id FROM dune_account_links WHERE account_id=:id FOR UPDATE',[':id'=>$identity['id']])->queryScalar(); + $email=self::email($identity); + $collision=$db->createCommand('SELECT customers_id FROM customers WHERE customers_email_address=:email AND customers_id<>:id',[':email'=>$email,':id'=>(int)$id])->queryScalar(); + if($collision)throw new \yii\web\HttpException(409,'This email is linked to another shop customer. Please contact support to link the accounts.'); + if(!$id){ + $db->createCommand("SET SESSION sql_mode=''")->execute(); + $db->createCommand()->insert('customers',['customers_firstname'=>mb_substr($identity['username']??'Player',0,32),'customers_lastname'=>'','customers_email_address'=>$email,'customers_password'=>password_hash(bin2hex(random_bytes(32)),PASSWORD_BCRYPT),'customers_status'=>1,'platform_id'=>\common\classes\platform::currentId()])->execute(); + $id=(int)$db->getLastInsertID(); + $db->createCommand()->insert('dune_account_links',['account_id'=>$identity['id'],'customer_id'=>$id])->execute(); + $db->createCommand()->insert('customers_info',['customers_info_id'=>$id,'customers_info_date_account_created'=>gmdate('Y-m-d H:i:s')])->execute(); + } + $db->createCommand()->update('customers',['customers_firstname'=>mb_substr($identity['username']??'Player',0,32),'customers_email_address'=>$email],['customers_id'=>$id])->execute(); + $transaction->commit();return (int)$id; + }catch(\Throwable $e){$transaction->rollBack();throw $e;} + } + private static function handle($app):void { + $app->response->headers->set('Referrer-Policy','no-referrer'); + $path=parse_url($_SERVER['REQUEST_URI']??'/',PHP_URL_PATH); + if(empty($_GET['action'])&&preg_match('#^/catalog/(?:[A-Z]{3}/)?$#',$path)){ + $currency=$_GET['currency']??'EUR'; + if(!is_string($currency)||!in_array($currency,['EUR','GBP','USD'],true))$currency='EUR'; + self::redirect($app,'/catalog/dune-shop?currency='.$currency); + } + if($path==='/dune-login.php'){ + if(!isset($_GET['code']))self::start($app); + $state=$_GET['state']??'';$nonce=$_COOKIE['__Host-dune_osc_state']??''; + if(!is_string($state)||!is_string($nonce)||!preg_match('/^[A-Za-z0-9_-]{43}$/',$state)||!preg_match('/^[A-Za-z0-9_-]{43}$/',$nonce))throw new \yii\web\ForbiddenHttpException('Invalid sign-in state'); + $row=$app->db->createCommand('SELECT * FROM dune_sso_states WHERE state_hash=:state AND nonce_hash=:nonce AND expires_at>=:now',[':state'=>hash('sha256',$state),':nonce'=>hash('sha256',$nonce),':now'=>time()])->queryOne(); + if(!$row)throw new \yii\web\ForbiddenHttpException('Expired or already used sign-in state'); + $removed=$app->db->createCommand()->delete('dune_sso_states',['state_hash'=>$row['state_hash'],'nonce_hash'=>$row['nonce_hash']])->execute(); + if($removed!==1)throw new \yii\web\ForbiddenHttpException('Sign-in already used'); + $identity=self::api('redeem',['client'=>'oscommerce','code'=>$_GET['code']]); + $id=self::synchronize($app,$identity);$token=self::token(); + $app->db->createCommand()->insert('dune_sso_sessions',['token_hash'=>hash('sha256',$token),'account_id'=>$identity['id'],'session_ref'=>$identity['sessionRef'],'expires_at'=>time()+43200])->execute(); + self::cookie('__Host-dune_oscommerce',$token,time()+43200);self::cookie('__Host-dune_osc_state','',time()-3600); + self::redirect($app,'https://shop.dunerealms.com/'); + } + $token=$_COOKIE['__Host-dune_oscommerce']??'';$identity=null; + if(is_string($token)&&preg_match('/^[A-Za-z0-9_-]{43}$/',$token)){ + $row=$app->db->createCommand('SELECT account_id,session_ref FROM dune_sso_sessions WHERE token_hash=:token AND expires_at>:now',[':token'=>hash('sha256',$token),':now'=>time()])->queryOne(); + if($row){ + try{$identity=self::api('identity',['sessionRef'=>$row['session_ref'],'client'=>'oscommerce']);}catch(\yii\web\HttpException $e){if($e->statusCode!==401)throw $e;} + if(($identity['id']??null)!==$row['account_id'])$identity=null; + } + } + if($identity){ + $id=self::synchronize($app,$identity); + if((int)$app->user->id!==$id){ + if(!$app->user->isGuest){$app->user->logout(false);global $cart;if(is_object($cart)&&is_callable([$cart,'reset']))$cart->reset();} + $app->session->regenerateID(true); + $customer=new \common\components\Customer(\common\components\Customer::LOGIN_WITHOUT_CHECK); + if(!$customer->loginCustomer(self::email($identity),$id))throw new \yii\web\ForbiddenHttpException('Account link failed'); + } + }elseif(!$app->user->isGuest){$app->user->logout(false);self::cookie('__Host-dune_oscommerce','',time()-3600);} + if(preg_match('#^/catalog/(?:[A-Z]{3}/)?account/(login|create|password|password-forgotten)#',$path))self::start($app); + if(preg_match('#^/catalog/(?:[A-Z]{3}/)?account/?$#',$path))self::redirect($app,'https://cp.dunerealms.com/'); + if(preg_match('#^/catalog/(?:[A-Z]{3}/)?checkout#',$path)&&!$identity)self::start($app,$path); + } +}