Install independent osCommerce portal with central account linking

This commit is contained in:
Codex 2026-11-16 16:21:45 +00:00
commit 7ab013bd53
8 changed files with 266 additions and 6 deletions

View file

@ -0,0 +1,88 @@
<?php
namespace frontend\components;
use Yii;
final class DuneAccount {
private static function token(): string { return rtrim(strtr(base64_encode(random_bytes(32)), '+/', '-_'), '='); }
private static function cookie(string $name,string $value,int $expires):void { setcookie($name,$value,['expires'=>$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='<meta name="referrer" content="no-referrer"><script>parent.postMessage('.$js.','.json_encode($parent).');</script><p><a target="_top" href="'.htmlspecialchars($url,ENT_QUOTES).'">Continue with your DuneRealms account</a></p>';
$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=$identity['id'].'@accounts.dunerealms.invalid';
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_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($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']]);}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($identity['id'].'@accounts.dunerealms.invalid',$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/account/(login|create|password|password-forgotten)#',$path))self::start($app);
if(preg_match('#^/catalog/account/?$#',$path))self::redirect($app,'https://cp.dunerealms.com/');
if(preg_match('#^/catalog/checkout#',$path)&&!$identity)self::start($app,$path);
}
}

View file

@ -0,0 +1,14 @@
# Independent osCommerce shop
Host: https://shop.dunerealms.com/
Portal: /var/www/dunerealms-shop-portal/index.html
Application: /home/dunerealms/apps/oscommerce (official osCommerce V4 commit 48d31a36)
Database: dunerealms_oscommerce on the existing MySQL service. Azuriom and dunerealms_store are preserved.
The portal clones the existing public shop shell and embeds /catalog/. Header/footer assets stay central. The original /shop.html embed is unchanged.
Frontend account linking uses the existing API with a dedicated oscommerce SSO client and an opaque host-only cookie. Customer records map by central account UUID. One-time codes, browser-bound state, expiry and central-session revalidation are enforced. Native registration/password endpoints redirect to the central account. No API permission or role synchronization is performed; native osCommerce backend permissions remain authoritative.
PHP-FPM pool and TLS vhost are separate from Azuriom. Installer paths, .git, configuration, SQL and downloads are denied at the web server. No credentials belong in this directory.
Backend theme proposal: Tabler (https://tabler.io), MIT licensed. This requires an adapter; it has not been installed over the native backend.

View file

@ -0,0 +1,11 @@
:root{color-scheme:dark;--dune-ink:#0b2019;--dune-panel:#15352a;--dune-gold:#e7cc83;--dune-line:#8d7946;--dune-text:#eee6d3}
html,body{background:var(--dune-ink)!important;color:var(--dune-text)!important;font-family:Inter,Arial,sans-serif!important}
body{margin:0!important}.main-content{background:transparent!important;min-height:35vh;padding:28px 0!important}.main-width{max-width:1340px!important;margin:auto!important}
.dune-shop-header{position:relative;background:linear-gradient(120deg,#153e2ee8,#091b16f7);border-bottom:1px solid var(--dune-line);padding:24px 4vw 20px}
.dune-shop-header .wordmark{display:block;text-align:center;margin:auto auto 20px}.dune-shop-header .masthead-logo{width:360px;max-width:80vw;height:auto}
.dune-shop-header nav{display:flex;justify-content:center;flex-wrap:wrap;gap:8px}.dune-shop-header nav a{display:flex;gap:7px;align-items:center;border:1px solid #756b3b;border-radius:9px;padding:9px 12px;color:var(--dune-text)!important;text-decoration:none;background:#0b211bdc;font-size:13px}.dune-shop-header nav a:hover{background:#284c38;border-color:#e7cc83;box-shadow:0 0 15px #cda14c20}.dune-shop-header nav img{width:34px;height:34px;object-fit:contain}
.dune-shop-hero{max-width:1340px;margin:26px auto 0;display:flex;align-items:center;gap:26px;border:1px solid var(--dune-line);border-radius:18px;padding:30px 38px;background:radial-gradient(ellipse at 15% 25%,#315a3c99,transparent 60%),linear-gradient(125deg,#193b2c,#10271f);box-shadow:0 12px 30px #0003}.dune-shop-hero img{width:110px;height:110px;object-fit:contain;filter:drop-shadow(0 6px 12px #0008)}.dune-shop-hero p{margin:0;color:#bca15f;font-size:12px;letter-spacing:.16em;text-transform:uppercase}.dune-shop-hero h1{color:var(--dune-gold);font-size:38px;margin:8px 0}.dune-shop-hero small{color:#cbd8c9;font-size:15px}
.dune-shop-toolbar{max-width:1340px;margin:16px auto;display:flex;gap:12px;justify-content:flex-end;flex-wrap:wrap}.dune-shop-toolbar a,.dune-shop-link{border:1px solid var(--dune-line);border-radius:8px;background:#193a2d;color:var(--dune-gold)!important;padding:10px 16px;text-decoration:none;font-weight:600}
.main-content a{color:var(--dune-gold)}.main-content h1,.main-content h2,.main-content h3,.main-content h4{color:var(--dune-gold)!important}.main-content .item,.main-content .product-item,.main-content .product-listing-item,.main-content .w-block{background:var(--dune-panel)!important;border-color:#456247!important;border-radius:12px}.main-content input,.main-content select,.main-content textarea{background:#0b241c!important;color:#eee6d3!important;border:1px solid #63734e!important;border-radius:6px}.main-content .btn,.main-content button,.main-content input[type=submit]{background:linear-gradient(#254b35,#173829)!important;color:var(--dune-gold)!important;border:1px solid var(--dune-line)!important;border-radius:8px!important;box-shadow:0 3px 8px #0003}.main-content .btn:hover,.main-content button:hover{filter:brightness(1.15)}
.dune-shop-footer{margin-top:32px;padding:30px 4vw;border-top:1px solid #63734e;background:#091c16;text-align:center;color:#b8cbb6;font-size:13px}.dune-shop-footer a{color:var(--dune-gold);margin:0 10px}.dune-shop-footer p{margin:12px 0 0;font-size:12px}.dune-shop-footer strong{color:var(--dune-gold);font-size:17px}.dune-shop-powered{opacity:.65;font-size:11px!important}
@media(max-width:700px){.dune-shop-hero{margin:16px 12px 0;padding:20px;gap:16px}.dune-shop-hero img{width:70px;height:70px}.dune-shop-hero h1{font-size:28px}.dune-shop-toolbar{margin:16px 12px;justify-content:center}.main-content{padding:18px 12px!important}.dune-shop-header nav a{padding:7px;font-size:11px}.dune-shop-header nav img{width:26px;height:26px}}

View file

@ -0,0 +1,6 @@
server {
listen 80; listen [::]:80;
server_name shop.dunerealms.com;
location ^~ /.well-known/acme-challenge/ { root /var/www/dunerealms-acme; try_files $uri =404; }
location / { return 301 https://shop.dunerealms.com$request_uri; }
}

View file

@ -0,0 +1,44 @@
server {
listen 443 ssl; listen [::]:443 ssl; http2 on;
server_name shop.dunerealms.com;
ssl_certificate /etc/letsencrypt/live/dunerealms-shop/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/dunerealms-shop/privkey.pem;
ssl_protocols TLSv1.2 TLSv1.3;
root /home/dunerealms/apps/oscommerce;
index index.php;
client_max_body_size 20m;
add_header X-Content-Type-Options nosniff always;
add_header Referrer-Policy strict-origin-when-cross-origin always;
add_header Strict-Transport-Security "max-age=15552000" always;
add_header Content-Security-Policy "frame-ancestors 'self' https://www.dunerealms.com https://dunerealms.com https://cp.dunerealms.com" always;
location = / { root /var/www/dunerealms-shop-portal; try_files /index.html =404; default_type text/html; }
location = /catalog { return 308 /catalog/; }
location = /catalog/index.php {
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME /home/dunerealms/apps/oscommerce/index.php;
fastcgi_param SCRIPT_NAME /catalog/index.php;
fastcgi_param HTTPS on;
fastcgi_pass unix:/run/php/dunerealms-oscommerce.sock;
fastcgi_read_timeout 100s;
}
location ~ /(?:\.|lib/|sql/|includes/|install/|documents/|download/) { return 404; }
location ~ ^/(?:index|admin/index|dune-login)\.php$ {
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param HTTPS on;
fastcgi_pass unix:/run/php/dunerealms-oscommerce.sock;
fastcgi_read_timeout 100s;
}
location ~ \.(?:php|sql|ini|log|bak|conf)$ { return 404; }
location /catalog/ { alias /home/dunerealms/apps/oscommerce/; try_files $uri $uri/ @oscommerce_front; }
location @oscommerce_front {
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME /home/dunerealms/apps/oscommerce/index.php;
fastcgi_param SCRIPT_NAME /catalog/index.php;
fastcgi_param HTTPS on;
fastcgi_pass unix:/run/php/dunerealms-oscommerce.sock;
fastcgi_read_timeout 100s;
}
location /admin/ { try_files $uri $uri/ /admin/index.php?$query_string; }
location / { try_files $uri $uri/ /index.php?$query_string; }
}

View file

@ -0,0 +1,22 @@
[dunerealms-oscommerce]
user = dunerealms
group = dunerealms
listen = /run/php/dunerealms-oscommerce.sock
listen.owner = www-data
listen.group = www-data
listen.mode = 0660
pm = ondemand
pm.max_children = 3
pm.process_idle_timeout = 20s
pm.max_requests = 300
php_admin_value[memory_limit] = 512M
php_admin_value[upload_max_filesize] = 16M
php_admin_value[post_max_size] = 20M
php_admin_value[max_execution_time] = 90
php_admin_flag[display_errors] = off
php_admin_flag[log_errors] = on
php_admin_value[error_log] = /var/log/php8.5-oscommerce.log
php_admin_value[error_reporting] = 22527
php_admin_value[session.cookie_httponly] = 1
php_admin_value[session.cookie_secure] = 1
php_admin_value[session.cookie_samesite] = Lax

View file

@ -0,0 +1,24 @@
from pathlib import Path
import re,subprocess,urllib.request,urllib.parse
app=Path('/home/dunerealms/apps/oscommerce');target=Path('/var/www/dunerealms-shop-portal');target.mkdir(exist_ok=True)
html=urllib.request.urlopen('https://www.dunerealms.com/shop.html',timeout=30).read().decode()
html=re.sub(r'(<iframe\b[^>]*\bsrc=")[^"]+',r'\1https://shop.dunerealms.com/catalog/',html,count=1)
html=html.replace('src="/shop-embed.js"','src="https://shop.dunerealms.com/oscommerce-embed.js"')
def absolute(m):
attr,value=m.group(1),m.group(2)
if value.startswith(('#','data:','mailto:','tel:','javascript:')):return m.group(0)
if not re.match(r'^https?://',value):value=urllib.parse.urljoin('https://www.dunerealms.com/shop.html',value)
return attr+'="'+value+'"'
html=re.sub(r'\b(src|href)="([^"]*)"',absolute,html)
(target/'index.html').write_text(html)
layout=app/'lib/frontend/themes/basic/layouts/main.tpl'
original=subprocess.check_output(['runuser','-u','dunerealms','--','git','-C',str(app),'show','HEAD:lib/frontend/themes/basic/layouts/main.tpl'],text=True)
layout.write_text(original.replace('</head>','<link rel="stylesheet" href="/dune-oscommerce.css?v=2"><script src="/oscommerce-inner.js" defer></script>\n</head>'))
sql="""UPDATE dunerealms_oscommerce.platforms SET is_default=0,status=0 WHERE platform_id IN (1,7,8,9,10);
UPDATE dunerealms_oscommerce.platforms SET is_default=1,status=1,platform_name='DuneRealms Shop',platform_owner='DuneRealms',platform_url='shop.dunerealms.com/catalog',platform_url_secure='shop.dunerealms.com/catalog',ssl_enabled=2 WHERE platform_id=7;
UPDATE dunerealms_oscommerce.configuration SET configuration_value='DuneRealms Shop' WHERE configuration_key='STORE_NAME';
UPDATE dunerealms_oscommerce.products SET products_status=0;
"""
subprocess.run(['mysql'],input=sql,text=True,check=True,capture_output=True)
subprocess.run(['chown','dunerealms:dunerealms',str(layout)],check=True)
print('Published independent portal with central header/footer and osCommerce iframe; original shop page unchanged')

View file

@ -0,0 +1,14 @@
from pathlib import Path
import subprocess
app=Path('/home/dunerealms/apps/oscommerce')
sql="""CREATE TABLE IF NOT EXISTS dunerealms_oscommerce.dune_account_links(account_id CHAR(36) PRIMARY KEY,customer_id INT NOT NULL UNIQUE);
CREATE TABLE IF NOT EXISTS dunerealms_oscommerce.dune_sso_states(state_hash CHAR(64) PRIMARY KEY,nonce_hash CHAR(64) NOT NULL,next_path VARCHAR(2048) NOT NULL,expires_at BIGINT NOT NULL);
CREATE TABLE IF NOT EXISTS dunerealms_oscommerce.dune_sso_sessions(token_hash CHAR(64) PRIMARY KEY,account_id CHAR(36) NOT NULL,session_ref CHAR(64) NOT NULL,expires_at BIGINT NOT NULL);
"""
subprocess.run(['mysql'],input=sql,text=True,capture_output=True,check=True)
entry=app/'lib/frontend/web/index.php';s=entry.read_text()
if 'DuneAccount' not in s:s=s.replace('$application->run();',"require __DIR__.'/../components/DuneAccount.php';\n(new \\frontend\\components\\DuneAccount())->bootstrap($application);\n$application->run();")
entry.write_text(s)
(app/'dune-login.php').write_text("<?php\n$_SERVER['SCRIPT_NAME']='/catalog/index.php';\n$_SERVER['PHP_SELF']='/catalog/index.php';\nrequire __DIR__.'/index.php';\n")
subprocess.run(['chown','dunerealms:dunerealms',str(entry),str(app/'dune-login.php')],check=True)
print('Frontend account linking installed; backend roles and permissions unchanged')