feat: move account tools into user menu and add referral security flows

dev
admin 2 months ago
parent c5a7ca6d35
commit dd3dcedb8b

@ -2,6 +2,12 @@
- This repository is the independent Virt Cloud project. Work only inside this
checkout unless the user explicitly authorizes changes to another project.
- When a task depends on historical decisions, test results, or project
context, and the knowledge vault is available, first read
`/Users/admin/Documents/www/codex-knowledge/AGENTS.md`, then
`Memory/INDEX.md` and `Memory/CURRENT.md`; follow only the linked notes
relevant to the task. If the vault is unavailable, say so explicitly and do
not guess the old project state.
- The Git remote is `https://g.luoli.live/root/virt.git`.
- All subsequent changes, commits and pushes for this project must use the
`venix` branch. Do not commit or push them to `main` or force-push.

@ -0,0 +1,123 @@
<?php
namespace App\Controllers;
use App\Services\AccountSecurityService;
use App\Services\AdminCsrf;
use App\Services\Auth;
use App\Services\Payment\RechargeMethodsService;
use App\Services\UserFeatureRestrictionService;
use App\Utils\Hash;
/** Account drawer APIs which do not need to render a page. */
class AccountSecurityController extends BaseController
{
public function passwordVerifySend($request, $response, $args)
{
$csrf = $this->verifyCsrf($request, $response);
if ($csrf !== null) {
return $csrf;
}
$user = Auth::getUser();
$result = AccountSecurityService::sendPasswordEmailCode(
$user,
$request->getServerParam('REMOTE_ADDR', '')
);
return $this->json($response, [
'ret' => $result['ok'] ? 1 : 0,
'msg' => $result['msg'],
'retry_after' => $result['retry_after'],
], $result['ok'] ? 200 : 429);
}
public function updatePassword($request, $response, $args)
{
$csrf = $this->verifyCsrf($request, $response);
if ($csrf !== null) {
return $csrf;
}
$user = Auth::getUser();
$old = $request->getParam('oldpwd', '');
$password = $request->getParam('pwd', '');
$repeat = $request->getParam('repwd', '');
if (!is_string($old) || !is_string($password) || !is_string($repeat)) {
return $this->json($response, ['ret' => 0, 'msg' => '密码格式无效'], 422);
}
if (!Hash::checkPassword($user->pass, $old)) {
return $this->json($response, ['ret' => 0, 'msg' => '旧密码错误'], 422);
}
$error = Hash::newPasswordError($password);
if ($error !== null || $password !== $repeat) {
return $this->json($response, ['ret' => 0, 'msg' => $error ?? '两次密码不一致'], 422);
}
$factor = AccountSecurityService::consumePasswordFactor(
$user,
$request->getParam('emailcode', ''),
$request->getParam('gacode', ''),
$request->getServerParam('REMOTE_ADDR', '')
);
if ($factor === null) {
$hasTotp = AccountSecurityService::hasTotp($user);
return $this->json($response, [
'ret' => 0,
'need_security_verify' => 1,
'need_email_verify' => 1,
'need_ga_verify' => $hasTotp ? 1 : 0,
'msg' => $hasTotp ? '请使用邮箱验证码或谷歌验证器完成安全验证' : '请先获取邮箱验证码完成安全验证',
], 422);
}
try {
$user->updatePassword($password);
Auth::logout();
} catch (\Throwable $exception) {
error_log('Account password update failed: ' . get_class($exception));
return $this->json($response, ['ret' => 0, 'msg' => '密码修改失败,请稍后重试'], 500);
}
return $this->json($response, [
'ret' => 1,
'method' => $factor,
'msg' => '密码修改成功,请重新登录',
]);
}
public function rechargeOptions($request, $response, $args)
{
$user = Auth::getUser();
if (UserFeatureRestrictionService::isRechargeRestricted($user)) {
return $this->json($response, [
'ret' => 0,
'msg' => UserFeatureRestrictionService::RECHARGE_MESSAGE,
'methods' => [],
], 503);
}
return $this->json($response, [
'ret' => 1,
'methods' => RechargeMethodsService::forUser($user),
]);
}
private function json($response, array $data, $status = 200)
{
$response = $response->withStatus((int) $status)
->withHeader('Content-Type', 'application/json; charset=utf-8')
->withHeader('Cache-Control', 'no-store, private');
$response->getBody()->write(json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
return $response;
}
private function verifyCsrf($request, $response)
{
if (AdminCsrf::verify($request)) {
return null;
}
return $this->json($response, [
'ret' => 0,
'msg' => '请求已过期,请刷新页面后重试',
], 403);
}
}

@ -11,6 +11,7 @@ use App\Services\CaptchaConfig;
use App\Services\LoginSessionDurationService;
use App\Services\LoginSessionRevocationService;
use App\Services\RegistrationEmailWhitelist;
use App\Services\ReferralConfig;
use App\Services\RedisClient;
use App\Services\TrustedLoginDeviceService;
@ -37,6 +38,9 @@ class ConfigController extends AdminController
'cnreg' => 'false',
'aff_method' => 'affid',
'enable_invite_code' => 'false',
ReferralConfig::RATE_KEY => ReferralConfig::DEFAULT_RATE,
ReferralConfig::VALID_DAYS_KEY => ReferralConfig::DEFAULT_VALID_DAYS,
ReferralConfig::ENABLED_KEY => ReferralConfig::DEFAULT_ENABLED,
'language' => 'false',
'host_1' => '',
'host_2' => '',
@ -107,6 +111,19 @@ class ConfigController extends AdminController
$payload[$key] = CaptchaConfig::validatePositiveInt($payload[$key], $key);
}
}
if (array_key_exists(ReferralConfig::RATE_KEY, $payload)) {
$payload[ReferralConfig::RATE_KEY] = ReferralConfig::validateRate($payload[ReferralConfig::RATE_KEY]);
}
if (array_key_exists(ReferralConfig::VALID_DAYS_KEY, $payload)) {
$payload[ReferralConfig::VALID_DAYS_KEY] = (string) ReferralConfig::validateDays(
$payload[ReferralConfig::VALID_DAYS_KEY]
);
}
if (array_key_exists(ReferralConfig::ENABLED_KEY, $payload)) {
$payload[ReferralConfig::ENABLED_KEY] = ReferralConfig::validateBoolean(
$payload[ReferralConfig::ENABLED_KEY]
);
}
} catch (\InvalidArgumentException $exception) {
return $response->withJson([
'ret' => 0,
@ -152,7 +169,16 @@ class ConfigController extends AdminController
$keysToDelete[] = 'domain_site_configs';
}
if ($newValue === $current) {
// Referral settings have meaningful defaults even before their
// rows exist. Persist the first explicit save (including a
// value equal to that default) so administrators can opt into
// the global referral policy and mark the setting configured.
$isReferralKey = in_array($key, [
ReferralConfig::RATE_KEY,
ReferralConfig::VALID_DAYS_KEY,
ReferralConfig::ENABLED_KEY,
], true);
if ($newValue === $current && !($isReferralKey && !isset($configurations[$key]))) {
continue;
}
@ -168,6 +194,7 @@ class ConfigController extends AdminController
CaptchaConfig::clearCache();
$redisClient = new RedisClient();
$redisClient->deleteMultiple(array_unique($keysToDelete));
ReferralConfig::clearCache($redisClient);
}
if ($affectedRows > 0) {
@ -208,6 +235,12 @@ class ConfigController extends AdminController
$data[$key] = (string) TrustedLoginDeviceService::normalizeDays($value);
} elseif ($key === RegistrationEmailWhitelist::ENABLED_KEY) {
$data[$key] = RegistrationEmailWhitelist::normalizeEnabled($value);
} elseif ($key === ReferralConfig::RATE_KEY) {
$data[$key] = ReferralConfig::normalizeRate($value);
} elseif ($key === ReferralConfig::VALID_DAYS_KEY) {
$data[$key] = (string) ReferralConfig::normalizeDays($value);
} elseif ($key === ReferralConfig::ENABLED_KEY) {
$data[$key] = ReferralConfig::normalizeBoolean($value) ? 'true' : 'false';
} else {
$data[$key] = $value;
}

@ -24,9 +24,10 @@ class UserController extends AdminController
'op' => '操作', 'id' => 'ID', 'user_name' => '用户名', 'remark' => '备注',
'email' => '邮箱', 'money' => '余额', 'im_type' => '联络方式类型', 'im_value' => '联络方式详情',
'enable' => '是否启用', 'reg_date' => '注册时间', 'reg_ip' => '注册 IP', 'ref_by' => '邀请人 ID',
'ref_by_name' => '邀请人账户', 'aff_money' => '推广返利余额',
'trusted_login_device_count' => '可信设备数',
],
'default_show_column' => ['op', 'id', 'user_name', 'remark', 'email', 'enable'],
'default_show_column' => ['op', 'id', 'user_name', 'remark', 'email', 'ref_by_name', 'aff_money', 'enable'],
'ajax_url' => 'user/ajax',
];
@ -221,7 +222,7 @@ class UserController extends AdminController
$columnIndex = filter_var($first['column'] ?? null, FILTER_VALIDATE_INT);
$requested = $columnIndex !== false && is_array($columns) && isset($columns[$columnIndex]['data'])
? (string) $columns[$columnIndex]['data'] : 'id';
$sortable = ['id', 'money', 'im_type', 'enable', 'reg_date', 'ref_by'];
$sortable = ['id', 'money', 'im_type', 'enable', 'reg_date', 'ref_by', 'aff_money'];
if ($isSuperAdmin) {
$sortable = array_merge($sortable, ['user_name', 'remark', 'email', 'im_value', 'reg_ip']);
}
@ -248,6 +249,17 @@ class UserController extends AdminController
foreach ($users as $user) {
$ids[] = (int) $user->id;
}
$referrerNames = [];
$referrerIds = array_values(array_filter(array_map(function ($user) {
return (int) $user->ref_by;
}, $users), static function ($id) {
return $id > 0;
}));
if ($referrerIds !== []) {
foreach (User::whereIn('id', array_unique($referrerIds))->get() as $referrer) {
$referrerNames[(int) $referrer->id] = AdminDataMasker::account($referrer->user_name);
}
}
$deviceCounts = $this->trustedLoginDeviceCounts($ids);
$data = [];
foreach ($users as $user) {
@ -267,6 +279,8 @@ class UserController extends AdminController
'reg_date' => $user->reg_date,
'reg_ip' => AdminDataMasker::ip($user->reg_ip),
'ref_by' => (int) $user->ref_by,
'ref_by_name' => $referrerNames[(int) $user->ref_by] ?? '',
'aff_money' => number_format((float) ($user->aff_money ?? 0), 2, '.', ''),
'trusted_login_device_count' => $deviceCounts[$id] ?? 0,
];
}

@ -19,6 +19,7 @@ use App\Services\LoginSessionDurationService;
use App\Services\RegistrationEmailWhitelist;
use App\Services\RegistrationIpRestriction;
use App\Services\RedisClient;
use App\Services\ReferralService;
use App\Services\TrustedLoginDeviceService;
use App\Models\User;
use App\Models\LoginIp;
@ -75,7 +76,7 @@ class AuthController extends BaseController
return Configurations::where('name', 'aff_method')->value('value');
});
if (!in_array($this->aff_method, ['code', 'affid'], true)) {
$this->aff_method = 'code';
$this->aff_method = 'affid';
}
$this->enable_invite_code = $redis->get('enable_invite_code', 60, function () {
return Configurations::where('name', 'enable_invite_code')->value('value');
@ -689,15 +690,24 @@ class AuthController extends BaseController
public function register($request, $response, $next)
{
$query = $request->getQueryParams();
$code = isset($query['code']) && is_scalar($query['code']) ? trim((string) $query['code']) : '';
$affid = isset($query['aff']) && is_scalar($query['aff']) ? (int) $query['aff'] : (int) Cookie::get('affid');
if ($affid > 0) {
Cookie::set(['affid' => (string) $affid], time() + 86400 * 30);
$code = ReferralService::registrationCode($query, Cookie::get('aff_code'));
if ($code === '' && isset($query['code']) && is_scalar($query['code'])) {
// Preserve direct links issued before the eight-character `aff`
// format was introduced; registration still validates the stored
// legacy code inside the transaction.
$code = trim((string) $query['code']);
}
$legacyAffid = isset($query['aff']) && is_scalar($query['aff']) && ctype_digit((string) $query['aff'])
? (int) $query['aff'] : (int) Cookie::get('affid');
if ($code !== '') {
Cookie::set(['aff_code' => $code], time() + 86400 * 30);
} elseif ($legacyAffid > 0) {
Cookie::set(['affid' => (string) $legacyAffid], time() + 86400 * 30);
}
return $this->view()->assign('enable_invite_code', $this->enable_invite_code)
->assign('enable_email_verify', CaptchaConfig::get('enable_email_verify'))
->assign('code', $code)->assign('aff', max(0, $affid))->assign('aff_method', $this->aff_method)
->assign('code', $code)->assign('aff_code', $code)->assign('aff', max(0, $legacyAffid))->assign('aff_method', $this->aff_method)
->assign('invite_required', $this->aff_method === 'code')->assign('tos_reg', Config::get('tos_reg'))
->assign('captch_reg', CaptchaConfig::get('captch_reg'))
->assign('cdn', $this->cdn)->assign('backup_cdn', $this->backup_cdn)
@ -902,14 +912,28 @@ class AuthController extends BaseController
}
$refBy = 0;
$invitation = null;
if ($this->aff_method === 'code') {
$aff = trim($read('aff'));
$affCode = ReferralService::normalizeCode($aff);
if ($affCode === '') {
$affCode = ReferralService::normalizeCode($code);
}
if ($affCode !== '') {
$invitation = ReferralService::findInvitation($affCode, true);
if ($invitation === null) {
throw new \InvalidArgumentException('推广链接无效');
}
$refBy = (int) $invitation->user_id;
} elseif ($code !== '' && $this->aff_method === 'code') {
// Accept legacy, longer invite codes already issued by
// older installations while new links stay eight chars.
$invitation = InviteCode::where('code', $code)->lockForUpdate()->first();
if ($invitation === null) {
throw new \InvalidArgumentException('邀请码无效');
}
$refBy = (int) $invitation->user_id;
} elseif ($this->aff_method === 'affid') {
$aff = $read('aff');
} elseif ($this->aff_method === 'code') {
throw new \InvalidArgumentException('推广链接或邀请码无效');
} else {
if ($aff !== '' && (!ctype_digit($aff) || (int) $aff < 0)) {
throw new \InvalidArgumentException('邀请链接无效');
}
@ -920,7 +944,10 @@ class AuthController extends BaseController
if ($referrer === null || !$referrer->canInvite()) {
throw new \InvalidArgumentException('邀请服务暂不可用');
}
if ($invitation !== null) {
// New eight-character promotion links are reusable and do
// not consume the legacy invite quota. Older, longer
// `code` invitations retain their one-time quota rules.
if ($invitation !== null && $affCode === '') {
if ((int) $referrer->invite_num < 1) {
throw new \InvalidArgumentException('邀请次数不足');
}
@ -942,10 +969,7 @@ class AuthController extends BaseController
$user->theme = 'venix';
$user->save();
$newCode = new InviteCode();
$newCode->code = bin2hex(random_bytes(12));
$newCode->user_id = $user->id;
$newCode->save();
ReferralService::codeForUser($user);
if ($invitation !== null && (int) $invitation->user_id === 0) {
$invitation->delete();
}

@ -27,6 +27,10 @@ use App\Models\CheckoutApply;
use App\Services\Mail;
use App\Services\TicketTelegramNotifier;
use App\Services\RedisClient;
use App\Services\AdminCsrf;
use App\Services\AccountSecurityService;
use App\Services\ReferralService;
use App\Services\ReferralConfig;
use App\Services\Payment\UsdtConfig;
use App\Services\Payment\YipayConfig;
use App\Services\Payment\PaytaroConfig;
@ -69,6 +73,9 @@ class UserController extends BaseController
$this->aff_method = $redis->get('aff_method', 60, function () {
return Configurations::where('name', 'aff_method')->value('value');
});
if (!in_array($this->aff_method, ['code', 'affid'], true)) {
$this->aff_method = 'affid';
}
}
public function smarty()
@ -76,6 +83,7 @@ class UserController extends BaseController
$smarty = parent::smarty();
$smarty->assign('cdn', isset($this->cdn) ? $this->cdn : '');
$smarty->assign('backup_cdn', isset($this->backup_cdn) ? $this->backup_cdn : '');
$smarty->assign('account_csrf_token', AdminCsrf::token());
return $smarty;
}
@ -333,6 +341,10 @@ class UserController extends BaseController
public function enableGoogleAuthenticator($request, $response, $args)
{
$csrf = $this->verifyAccountCsrf($request, $response);
if ($csrf !== null) {
return $csrf;
}
$user = $this->user;
if ($this->hasGoogleAuthenticator($user)) {
return $this->echoJson($response, [
@ -370,6 +382,10 @@ class UserController extends BaseController
public function disableGoogleAuthenticator($request, $response, $args)
{
$csrf = $this->verifyAccountCsrf($request, $response);
if ($csrf !== null) {
return $csrf;
}
$user = $this->user;
if (!$this->hasGoogleAuthenticator($user)) {
return $this->echoJson($response, [
@ -398,6 +414,10 @@ class UserController extends BaseController
public function updateLoginVerifyMethod($request, $response, $args)
{
$csrf = $this->verifyAccountCsrf($request, $response);
if ($csrf !== null) {
return $csrf;
}
$method = trim((string) $request->getParam('method', 'email'));
if (!in_array($method, ['email', 'ga'], true)) {
return $this->echoJson($response, [
@ -437,23 +457,27 @@ class UserController extends BaseController
$inviteRestricted = UserFeatureRestrictionService::isInviteRestricted($user);
$inviteEnabled = $user->canInvite();
$inviteCode = null;
if ($this->aff_method === 'code') {
$inviteCode = InviteCode::where('user_id', $user->id)->orderBy('id')->first();
$invite_link = !$inviteEnabled || $inviteCode === null
? ''
: 'https://' . $_SERVER['HTTP_HOST'] . '/auth/register?code=' . $inviteCode->code;
} else {
$invite_link = $inviteEnabled ? $user->getAffLink() : '';
if ($inviteEnabled) {
$inviteCode = ReferralService::codeForUser($user);
}
$invite_link = $inviteEnabled ? $user->getAffLink() : '';
$paybacks = Payback::where("ref_by", $this->user->id)->orderBy("datetime", "desc")->paginate(10, ['*'], 'page', $pageNum);
$paybacks->setPath('/user/invite');
$referralValues = ReferralConfig::values();
$referralDays = ReferralConfig::normalizeDays(
$referralValues[ReferralConfig::VALID_DAYS_KEY] ?? ReferralConfig::DEFAULT_VALID_DAYS
);
return $this->view()->assign('paybacks', $paybacks)->assign('invite_link', $invite_link)->assign('invite_enabled', $inviteEnabled)->assign('invite_restricted', $inviteRestricted)->assign('has_invite_code', $inviteCode !== null)->assign('aff_method', $this->aff_method)->assign("cdn", $this->cdn)->assign("backup_cdn", $this->backup_cdn)->display('user/invite.tpl');
return $this->view()->assign('paybacks', $paybacks)->assign('invite_link', $invite_link)->assign('invite_enabled', $inviteEnabled)->assign('invite_restricted', $inviteRestricted)->assign('has_invite_code', $inviteCode !== null)->assign('aff_method', $this->aff_method)->assign('referral_rate', number_format(ReferralConfig::rateFor($user), 2, '.', ''))->assign('referral_days', $referralDays)->assign("cdn", $this->cdn)->assign("backup_cdn", $this->backup_cdn)->display('user/invite.tpl');
}
public function doAff($request, $response, $args)
{
$csrf = $this->verifyAccountCsrf($request, $response);
if ($csrf !== null) {
return $csrf;
}
$type = $request->getParam('type');
$amount = $request->getParam('amount');
$user = $this->user;
@ -519,6 +543,10 @@ class UserController extends BaseController
public function doInvite($request, $response, $args)
{
$csrf = $this->verifyAccountCsrf($request, $response);
if ($csrf !== null) {
return $csrf;
}
if (UserFeatureRestrictionService::isInviteRestricted($this->user)) {
return $this->echoJson($response, [
'ret' => 0,
@ -533,23 +561,11 @@ class UserController extends BaseController
]);
}
if ($this->aff_method === 'code') {
$existing = InviteCode::where('user_id', $this->user->id)->first();
if ($existing !== null) {
return $this->echoJson($response, [
'ret' => 1,
'msg' => '邀请码已经存在。',
]);
}
$code = new InviteCode();
$code->code = $this->newInviteCodeValue();
$code->user_id = $this->user->id;
$code->save();
if ($this->aff_method === 'code' || $this->aff_method === 'affid') {
ReferralService::codeForUser($this->user);
return $this->echoJson($response, [
'ret' => 1,
'msg' => '邀请码生成成功,剩余邀请次数不变。',
'msg' => '推广链接已生成,剩余邀请次数不变。',
]);
}
@ -576,6 +592,10 @@ class UserController extends BaseController
public function updatePassword($request, $response, $args)
{
$csrf = $this->verifyAccountCsrf($request, $response);
if ($csrf !== null) {
return $csrf;
}
$old = $request->getParam('oldpwd');
$password = $request->getParam('pwd');
if (!Hash::checkPassword($this->user->pass, $old)) {
@ -585,6 +605,22 @@ class UserController extends BaseController
if ($error !== null || $password !== $request->getParam('repwd')) {
return $this->echoJson($response, ['ret' => 0, 'msg' => $error ?? '两次密码不一致']);
}
$factor = AccountSecurityService::consumePasswordFactor(
$this->user,
$request->getParam('emailcode', ''),
$request->getParam('gacode', ''),
$request->getServerParam('REMOTE_ADDR', '')
);
if ($factor === null) {
$hasTotp = AccountSecurityService::hasTotp($this->user);
return $this->echoJson($response, [
'ret' => 0,
'need_security_verify' => 1,
'need_email_verify' => 1,
'need_ga_verify' => $hasTotp ? 1 : 0,
'msg' => $hasTotp ? '请使用邮箱验证码或谷歌验证器完成安全验证' : '请先获取邮箱验证码完成安全验证',
]);
}
$this->user->updatePassword($password);
Auth::logout();
@ -821,6 +857,10 @@ class UserController extends BaseController
public function doResetiv($request, $response, $args)
{
$csrf = $this->verifyAccountCsrf($request, $response);
if ($csrf !== null) {
return $csrf;
}
$user = Auth::getUser();
@ -838,18 +878,10 @@ class UserController extends BaseController
]);
}
if ($this->aff_method === "code") {
$code = InviteCode::where('user_id', $user->id)->orderBy('id')->first();
if ($code === null) {
$code = new InviteCode();
$code->user_id = $user->id;
}
$code->code = $this->newInviteCodeValue();
$code->save();
InviteCode::where('user_id', $user->id)->where('id', '<>', $code->id)->delete();
if ($this->aff_method === "code" || $this->aff_method === 'affid') {
ReferralService::rotateForUser($user);
$res['msg'] = "邀请码已重置,剩余邀请次数不变。";
$res['msg'] = "推广链接已重置,剩余邀请次数不变。";
$res['ret'] = 1;
return $this->echoJson($response, $res);
}
@ -861,11 +893,19 @@ class UserController extends BaseController
private function newInviteCodeValue()
{
do {
$value = Tools::genRandomChar(12);
} while (InviteCode::where('code', $value)->exists());
return ReferralService::generateCode();
}
private function verifyAccountCsrf($request, $response)
{
if (AdminCsrf::verify($request)) {
return null;
}
return $value;
return $this->echoJson($response, [
'ret' => 0,
'msg' => '请求已过期,请刷新页面后重试',
]);
}
}

@ -7,9 +7,8 @@ namespace App\Models;
*/
use App\Utils\Hash;
use App\Models\Configurations;
use App\Models\InviteCode;
use App\Services\RedisClient;
use App\Services\ReferralService;
use App\Services\UserFeatureRestrictionService;
use App\Services\UserDataDeletionService;
@ -47,33 +46,17 @@ class User extends Model
return '';
}
$uid = $this->attributes['id'];
$redis = new RedisClient();
$domain = $_SERVER['HTTP_HOST'];
$aff_method = $redis->get('aff_method', 60, function () {
return Configurations::where('name', 'aff_method')->value('value');
});
if ($aff_method === 'affid') {
return 'https://' . $domain . '/auth/register?aff=' . $uid;
$domain = trim((string) ($_SERVER['HTTP_HOST'] ?? ''));
if ($domain === '' || preg_match('/[\x00-\x20\x7F]/', $domain) === 1) {
return '';
}
if ($aff_method === 'code') {
$code = InviteCode::where('user_id', $uid)->first();
if ($code === null) {
do {
$value = bin2hex(random_bytes(6));
} while (InviteCode::where('code', $value)->exists());
$code = new InviteCode();
$code->code = $value;
$code->user_id = $uid;
$code->save();
}
return 'https://' . $domain . '/auth/register?code=' . $code->code;
$code = ReferralService::codeForUser($this);
if ($code === null || ReferralService::normalizeCode($code->code) === '') {
return '';
}
return '';
return 'https://' . $domain . '/auth/register?aff=' . rawurlencode((string) $code->code);
}
public function canInvite()

@ -0,0 +1,203 @@
<?php
namespace App\Services;
use App\Models\EmailVerify;
use App\Models\User;
use App\Utils\Totp;
/** Account security helpers shared by the account drawer and password API. */
class AccountSecurityService
{
private const SEND_COOLDOWN_SECONDS = 60;
private const ACTIVE_CODE_LIMIT = 3;
private const FACTOR_FAIL_LIMIT = 8;
private const FACTOR_FAIL_TTL = 600;
public static function hasTotp(User $user): bool
{
return (int) $user->ga_enable === 1
&& Totp::normalizeSecret($user->ga_token) !== '';
}
/** @return array{ok:bool,msg:string,retry_after:int} */
public static function sendPasswordEmailCode(User $user, $clientIp = ''): array
{
$email = strtolower(trim((string) $user->email));
if ($email === '' || filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
return ['ok' => false, 'msg' => '账户邮箱无效', 'retry_after' => 0];
}
if (Mail::isRecipientBlacklisted($email)) {
return ['ok' => false, 'msg' => '当前邮箱暂时无法接收验证邮件', 'retry_after' => 0];
}
$ip = is_scalar($clientIp) ? trim((string) $clientIp) : '';
$redis = new RedisClient();
// Scope the send gate to the authenticated account. Binding it to a
// client IP lets a requester evade the cooldown by rotating proxies.
$key = self::sendCooldownKey($user);
if (!self::acquireCooldown($redis, $key)) {
$retryAfter = self::ttl($redis, $key);
return ['ok' => false, 'msg' => '请求过于频繁,请稍后再试', 'retry_after' => $retryAfter];
}
$now = time();
$ttl = (int) CaptchaConfig::get('email_verify_ttl');
$active = EmailVerify::where('email', $email)
->where('code', 'like', 'password_change:%')
->where('expire_in', '>', $now)
->count();
if ((int) $active >= self::ACTIVE_CODE_LIMIT) {
return ['ok' => false, 'msg' => '验证码请求次数过多,请稍后再试', 'retry_after' => self::SEND_COOLDOWN_SECONDS];
}
$verification = new EmailVerify();
$verification->email = $email;
$verification->ip = $ip === '' ? '0.0.0.0' : $ip;
$plainCode = (string) random_int(100000, 999999);
$verification->code = 'password_change:' . $plainCode;
$verification->expire_in = $now + $ttl;
if (!$verification->save()) {
return ['ok' => false, 'msg' => '验证码发送失败,请稍后重试', 'retry_after' => 0];
}
try {
$sent = Mail::send(
$email,
Config::get('appName') . ' - 修改密码验证',
'auth/verify.tpl',
[
'code' => $plainCode,
'expire' => date('Y-m-d H:i:s', $verification->expire_in),
'language' => 'false',
'scene' => 'password_change',
],
[],
'修改密码验证'
);
} catch (\Throwable $exception) {
$sent = false;
}
if (!$sent) {
$verification->delete();
return ['ok' => false, 'msg' => '验证码发送失败,请稍后重试', 'retry_after' => 0];
}
return ['ok' => true, 'msg' => '验证码已发送,请检查邮箱', 'retry_after' => self::SEND_COOLDOWN_SECONDS];
}
/** Consume one accepted password-change factor. */
public static function consumePasswordFactor(User $user, $emailCode = '', $totpCode = '', $clientIp = ''): ?string
{
$redis = new RedisClient();
$failKey = self::factorFailKey($user);
if (self::factorFailures($redis, $failKey) >= self::FACTOR_FAIL_LIMIT) {
return null;
}
$emailCode = is_scalar($emailCode) ? trim((string) $emailCode) : '';
$totpCode = is_scalar($totpCode) ? trim((string) $totpCode) : '';
if (self::hasTotp($user)) {
if (Totp::verify($user->ga_token, $totpCode)) {
self::clearFactorFailures($redis, $failKey);
return 'totp';
}
}
if ($emailCode === '' || !preg_match('/^\d{6}$/D', $emailCode)
|| Mail::isRecipientBlacklisted($user->email)) {
self::recordFactorFailure($redis, $failKey);
return null;
}
$connection = (new EmailVerify())->getConnection();
$consumed = false;
$connection->transaction(function () use ($user, $emailCode, &$consumed) {
$verification = EmailVerify::where('email', strtolower(trim((string) $user->email)))
->where('code', 'password_change:' . $emailCode)
->where('expire_in', '>', time())
->lockForUpdate()
->first();
if ($verification !== null) {
$verification->delete();
$consumed = true;
}
}, 3);
if ($consumed) {
self::clearFactorFailures($redis, $failKey);
return 'email';
}
self::recordFactorFailure($redis, $failKey);
return null;
}
private static function sendCooldownKey(User $user): string
{
return 'account_password_verify_send:' . (int) $user->id;
}
private static function ttl(RedisClient $redis, string $key): int
{
try {
$ttl = $redis->getClient()->ttl($key);
return $ttl > 0 ? (int) $ttl : 0;
} catch (\Throwable $exception) {
return 0;
}
}
private static function acquireCooldown(RedisClient $redis, string $key): bool
{
try {
$result = $redis->getClient()->set(
$key,
'1',
'EX',
self::SEND_COOLDOWN_SECONDS,
'NX'
);
return $result === true || strtoupper((string) $result) === 'OK';
} catch (\Throwable $exception) {
// Redis is an abuse-control accelerator. The database active-code
// limit still bounds outstanding codes when it is unavailable.
return true;
}
}
private static function factorFailKey(User $user): string
{
return 'account_password_verify_fail:' . (int) $user->id;
}
private static function factorFailures(RedisClient $redis, string $key): int
{
try {
$value = $redis->getClient()->get($key);
return is_numeric($value) ? (int) $value : 0;
} catch (\Throwable $exception) {
return 0;
}
}
private static function recordFactorFailure(RedisClient $redis, string $key): void
{
try {
$client = $redis->getClient();
$value = (int) $client->incr($key);
if ($value === 1) {
$client->expire($key, self::FACTOR_FAIL_TTL);
}
} catch (\Throwable $exception) {
// Continue with database verification when Redis is unavailable.
}
}
private static function clearFactorFailures(RedisClient $redis, string $key): void
{
try {
$redis->del($key);
} catch (\Throwable $exception) {
// A stale failure counter only affects abuse throttling.
}
}
}

@ -6,6 +6,7 @@ use App\Models\Code;
use App\Models\Payback;
use App\Models\Paylist;
use App\Models\User;
use App\Services\ReferralConfig;
class RechargeCreditService
{
@ -57,7 +58,7 @@ class RechargeCreditService
private static function recordReferral(User $user, $amount)
{
if ((int) $user->ref_by <= 0 || strtotime('-2 year') >= strtotime((string) $user->reg_date)) {
if (!ReferralConfig::isEligible($user)) {
return;
}
@ -66,7 +67,10 @@ class RechargeCreditService
return;
}
$reward = round($amount * ((float) $referrer->aff_rate / 100), 2);
$reward = round($amount * (ReferralConfig::rateFor($referrer) / 100), 2);
if ($reward <= 0) {
return;
}
$referrer->aff_money = round((float) $referrer->aff_money + $reward, 2);
$referrer->save();

@ -0,0 +1,57 @@
<?php
namespace App\Services\Payment;
use App\Models\User;
/** Exposes only payment methods currently usable by a user. */
class RechargeMethodsService
{
public static function forUser(User $user): array
{
$methods = [];
if (PaytaroConfig::isUserVisible($user)) {
$values = PaytaroConfig::values();
$methods[] = self::method('paytaro', '支付宝', $values['paytaro_min_amount'], $values['paytaro_max_amount'], [
'provider' => 'paytaro',
]);
}
$yipayValues = YipayConfig::values();
foreach (YipayConfig::visibleMethods($user, $yipayValues) as $method) {
// visibleMethods reflects switches; runtimeForUser additionally
// validates credentials, callback URL and the selected method.
try {
YipayConfig::runtimeForUser($user, $method);
} catch (\Throwable $exception) {
continue;
}
$label = $method === 'wxpay' ? '微信支付' : '支付宝支付';
$methods[] = self::method('yipay_' . $method, $label, $yipayValues['yipay_min_amount'], $yipayValues['yipay_max_amount'], [
'provider' => 'yipay',
'method' => $method,
]);
}
if (UsdtConfig::isUserVisible($user)) {
$values = UsdtConfig::values();
$methods[] = self::method('usdt', 'USDT', $values['usdt_min_amount'], '9999999.99', [
'provider' => 'usdt',
'network' => 'tron',
]);
}
return $methods;
}
private static function method(string $id, string $label, $minimum, $maximum, array $extra = []): array
{
return array_merge([
'id' => $id,
'label' => $label,
'min_amount' => PaymentAmount::normalize($minimum),
'max_amount' => PaymentAmount::normalize($maximum),
], $extra);
}
}

@ -0,0 +1,198 @@
<?php
namespace App\Services;
use App\Models\Configurations;
/**
* Runtime settings for referral rewards.
*
* The values are kept in the administrator configuration table and cached in
* Redis. The configured flag is intentionally retained so installations
* upgraded from the old per-referrer `user.aff_rate` model keep their current
* behaviour until an administrator explicitly saves the new global rate.
*/
class ReferralConfig
{
public const RATE_KEY = 'referral_reward_rate';
public const VALID_DAYS_KEY = 'referral_reward_days';
public const ENABLED_KEY = 'referral_reward_enabled';
public const CACHE_KEY = 'referral:config';
public const CACHE_TTL_MINUTES = 5;
public const DEFAULT_RATE = '20';
public const DEFAULT_VALID_DAYS = '730';
public const DEFAULT_ENABLED = 'true';
private const DEFAULTS = [
self::RATE_KEY => self::DEFAULT_RATE,
self::VALID_DAYS_KEY => self::DEFAULT_VALID_DAYS,
self::ENABLED_KEY => self::DEFAULT_ENABLED,
];
/**
* @return array{referral_reward_rate: string, referral_reward_days: int,
* referral_reward_enabled: bool, rate_configured: bool,
* days_configured: bool, enabled_configured: bool}
*/
public static function values(): array
{
$raw = null;
try {
$redis = new RedisClient();
$cached = $redis->get(self::CACHE_KEY, self::CACHE_TTL_MINUTES, static function () {
return json_encode(self::loadRaw(), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
});
if (is_string($cached) && $cached !== '') {
$decoded = json_decode($cached, true);
if (is_array($decoded)) {
$raw = $decoded;
}
}
} catch (\Throwable $exception) {
// Redis is an optional acceleration layer. Database settings are
// still authoritative when it is unavailable during a request.
}
if (!is_array($raw)) {
$raw = self::loadRaw();
}
$rate = self::normalizeRate($raw[self::RATE_KEY] ?? self::DEFAULT_RATE);
$days = self::normalizeDays($raw[self::VALID_DAYS_KEY] ?? self::DEFAULT_VALID_DAYS);
$enabled = self::normalizeBoolean($raw[self::ENABLED_KEY] ?? self::DEFAULT_ENABLED);
return [
self::RATE_KEY => $rate,
self::VALID_DAYS_KEY => $days,
self::ENABLED_KEY => $enabled,
'rate_configured' => (bool) ($raw[self::RATE_KEY . '_configured'] ?? false),
'days_configured' => (bool) ($raw[self::VALID_DAYS_KEY . '_configured'] ?? false),
'enabled_configured' => (bool) ($raw[self::ENABLED_KEY . '_configured'] ?? false),
];
}
public static function clearCache(?RedisClient $redis = null): void
{
try {
($redis ?? new RedisClient())->del(self::CACHE_KEY);
} catch (\Throwable $exception) {
// A stale Redis cache must never prevent an administrator from
// saving a valid database configuration.
}
}
public static function normalizeRate($value): string
{
$value = trim((string) $value);
if (!preg_match('/^(?:\d{1,3})(?:\.\d{1,2})?$/D', $value)) {
return self::DEFAULT_RATE;
}
$number = (float) $value;
if (!is_finite($number) || $number < 0 || $number > 100) {
return self::DEFAULT_RATE;
}
return number_format($number, 2, '.', '');
}
public static function validateRate($value): string
{
$value = trim((string) $value);
if (!preg_match('/^(?:\d{1,3})(?:\.\d{1,2})?$/D', $value)
|| (float) $value < 0 || (float) $value > 100) {
throw new \InvalidArgumentException('推广返利比例必须是 0 至 100 之间的数字,最多两位小数');
}
return number_format((float) $value, 2, '.', '');
}
public static function normalizeDays($value): int
{
$value = trim((string) $value);
if (!preg_match('/^\d+$/D', $value)) {
return (int) self::DEFAULT_VALID_DAYS;
}
return max(1, min(3650, (int) $value));
}
public static function validateDays($value): int
{
$value = trim((string) $value);
if (!preg_match('/^\d+$/D', $value) || (int) $value < 1 || (int) $value > 3650) {
throw new \InvalidArgumentException('推广返利有效期必须是 1 至 3650 天');
}
return (int) $value;
}
public static function normalizeBoolean($value): bool
{
return in_array(strtolower(trim((string) $value)), ['1', 'true', 'yes', 'on'], true);
}
public static function validateBoolean($value): string
{
$value = strtolower(trim((string) $value));
if (!in_array($value, ['0', '1', 'true', 'false', 'yes', 'no', 'on', 'off'], true)) {
throw new \InvalidArgumentException('推广返利开关值无效');
}
return self::normalizeBoolean($value) ? 'true' : 'false';
}
public static function isEligible($user, ?int $now = null): bool
{
$values = self::values();
if (!$values[self::ENABLED_KEY] || (int) ($user->ref_by ?? 0) <= 0) {
return false;
}
$registeredAt = strtotime((string) ($user->reg_date ?? ''));
if ($registeredAt === false) {
return false;
}
$now = $now ?? time();
$age = $now - $registeredAt;
return $age >= 0 && $age <= $values[self::VALID_DAYS_KEY] * 86400;
}
public static function rateFor($referrer): float
{
$values = self::values();
if ($values['rate_configured']) {
return (float) $values[self::RATE_KEY];
}
// Existing installations may still rely on a per-referrer rate. The
// administrator can switch to the global rule by saving the setting.
$legacy = (float) ($referrer->aff_rate ?? 0);
return max(0.0, min(100.0, $legacy));
}
private static function loadRaw(): array
{
$raw = self::DEFAULTS;
foreach (array_keys(self::DEFAULTS) as $key) {
$raw[$key . '_configured'] = false;
}
try {
$rows = Configurations::whereIn('name', array_keys(self::DEFAULTS))->get()->keyBy('name');
foreach (array_keys(self::DEFAULTS) as $key) {
if (isset($rows[$key])) {
$raw[$key] = (string) $rows[$key]->value;
$raw[$key . '_configured'] = true;
}
}
} catch (\Throwable $exception) {
// Fresh bootstrap/tests may not have created the settings table.
}
return $raw;
}
}

@ -0,0 +1,184 @@
<?php
namespace App\Services;
use App\Models\InviteCode;
/**
* Referral-code rules shared by registration and the promotion drawer.
*/
class ReferralService
{
public const CODE_LENGTH = 8;
public const CODE_PATTERN = '/^[A-Za-z0-9]{8}$/D';
private const CODE_ALPHABET = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
public static function normalizeCode($value): string
{
$value = trim((string) $value);
return preg_match(self::CODE_PATTERN, $value) === 1 ? $value : '';
}
public static function generateCode(): string
{
// The generation lock serializes the check-and-select sequence. A
// caller that needs an atomic create/update should use codeForUser()
// or rotateForUser(); this method remains available for legacy code
// that only needs a fresh candidate value.
return self::withGenerationLock(static function (): string {
return self::generateCodeValue();
});
}
/**
* Return a user's existing eight-character code or create it atomically.
*
* The lock row is deliberately separate from ss_invite_code: legacy
* installations may contain duplicate/long codes, so adding a unique
* constraint to that table would make the migration destructive.
*/
public static function codeForUser($user): ?InviteCode
{
$userId = (int) ($user->id ?? 0);
if ($userId <= 0) {
return null;
}
return self::withGenerationLock(static function () use ($userId): InviteCode {
$existing = InviteCode::where('user_id', $userId)
->orderBy('id')
->get()
->first(static function ($code) {
return self::normalizeCode($code->code) !== '';
});
if ($existing !== null) {
return $existing;
}
$code = new InviteCode();
$code->code = self::generateCodeValue();
$code->user_id = $userId;
$code->save();
return $code;
});
}
/**
* Generate and persist a replacement code while holding the same lock.
* This is the safe replacement for legacy callers that used
* generateCode() followed by save() in separate statements.
*/
public static function rotateForUser($user): ?InviteCode
{
$userId = (int) ($user->id ?? 0);
if ($userId <= 0) {
return null;
}
return self::withGenerationLock(static function () use ($userId): InviteCode {
$code = InviteCode::where('user_id', $userId)->orderBy('id')->first();
if ($code === null) {
$code = new InviteCode();
$code->user_id = $userId;
}
$code->code = self::generateCodeValue();
$code->save();
// Keep the historical one-code-per-user behaviour without
// touching invitation rows belonging to other users.
InviteCode::where('user_id', $userId)
->where('id', '<>', $code->id)
->delete();
return $code;
});
}
private static function generateCodeValue(): string
{
$alphabetLength = strlen(self::CODE_ALPHABET);
for ($attempt = 0; $attempt < 32; $attempt++) {
$code = '';
for ($index = 0; $index < self::CODE_LENGTH; $index++) {
$code .= self::CODE_ALPHABET[random_int(0, $alphabetLength - 1)];
}
if (!InviteCode::where('code', $code)->exists()) {
return $code;
}
}
throw new \RuntimeException('无法生成唯一推广码');
}
private static function withGenerationLock(callable $callback)
{
$connection = (new InviteCode())->getConnection();
try {
return $connection->transaction(static function () use ($connection, $callback) {
$lock = $connection->table('referral_code_generation_locks')
->where('id', 1)
->lockForUpdate()
->first();
if ($lock === null) {
throw new \RuntimeException(
'推广码生成锁未初始化,请先导入 web/sql/referral_affiliate_code.sql'
);
}
return $callback();
});
} catch (\Throwable $exception) {
if ($exception instanceof \RuntimeException
&& str_starts_with($exception->getMessage(), '推广码生成锁未初始化')) {
throw $exception;
}
throw new \RuntimeException('推广码生成锁不可用,请先导入 web/sql/referral_affiliate_code.sql', 0, $exception);
}
}
public static function findInvitation($rawCode, $lock = false): ?InviteCode
{
$code = self::normalizeCode($rawCode);
if ($code === '') {
return null;
}
$query = InviteCode::where('code', $code);
if ($lock) {
$query->lockForUpdate();
}
// Existing installations may still have the old case-insensitive
// column collation until the optional SQL migration is applied. Read
// the candidate set and compare in PHP so mixed-case codes never
// resolve to the wrong inviter during that transition.
foreach ($query->get() as $invitation) {
if ((string) $invitation->code === $code) {
return $invitation;
}
}
return null;
}
public static function registrationCode($query, $cookie = ''): string
{
if (is_array($query)) {
$queryCode = $query['aff'] ?? '';
$normalized = self::normalizeCode($queryCode);
if ($normalized !== '') {
return $normalized;
}
// Keep accepting the historical `code` query parameter while all
// newly generated links use `aff`.
$normalized = self::normalizeCode($query['code'] ?? '');
if ($normalized !== '') {
return $normalized;
}
}
return self::normalizeCode($cookie);
}
}

@ -114,7 +114,12 @@ $app->group('/user', function () {
// Manual invite-code rotation is account functionality, not a proxy reset job.
$this->post('/resetiv', 'App\Controllers\UserController:doResetiv');
$this->get('/edit', 'App\Controllers\UserController:edit');
$this->post('/password', 'App\Controllers\UserController:updatePassword');
// Password changes require the current password plus either a one-time
// email code or an enabled Google Authenticator code.
$this->post('/password/verify/send', 'App\Controllers\AccountSecurityController:passwordVerifySend');
$this->post('/password', 'App\Controllers\AccountSecurityController:updatePassword');
$this->get('/recharge/options', 'App\Controllers\AccountSecurityController:rechargeOptions');
$this->get('/recharge/methods', 'App\Controllers\AccountSecurityController:rechargeOptions');
$this->post('/security/google-authenticator', 'App\Controllers\UserController:enableGoogleAuthenticator');
$this->delete('/security/google-authenticator', 'App\Controllers\UserController:disableGoogleAuthenticator');
$this->post('/security/verify-method', 'App\Controllers\UserController:updateLoginVerifyMethod');

@ -0,0 +1,99 @@
const drawer = document.getElementById('panel-account-drawer');
const frame = document.getElementById('panel-account-drawer-frame');
const closeButton = document.getElementById('panel-account-drawer-close');
const drawerTitle = document.getElementById('panel-account-drawer-title');
const drawerDescription = document.getElementById('panel-account-drawer-description');
const drawerFrameWrap = drawer && drawer.querySelector('.panel-account-drawer-frame-wrap');
const drawerRoutes = {
account: '/user/edit?drawer=1',
balance: '/user/code?drawer=1',
promotion: '/user/invite?drawer=1'
};
let lastTrigger = null;
let scrollTop = 0;
function setDrawerState(open) {
if (open) {
scrollTop = window.scrollY || document.documentElement.scrollTop || 0;
document.documentElement.style.setProperty('--panel-account-scroll-top', `-${scrollTop}px`);
} else {
document.documentElement.style.removeProperty('--panel-account-scroll-top');
}
document.documentElement.classList.toggle('panel-account-open', open);
if (drawerFrameWrap) drawerFrameWrap.setAttribute('aria-busy', open ? 'true' : 'false');
if (!open && scrollTop > 0) window.scrollTo(0, scrollTop);
}
function closeDrawer() {
if (!drawer) return;
if (drawer.open && typeof drawer.close === 'function') drawer.close();
else drawer.removeAttribute('open');
setDrawerState(false);
if (frame) frame.src = 'about:blank';
if (lastTrigger && typeof lastTrigger.focus === 'function') lastTrigger.focus();
lastTrigger = null;
}
function openDrawer(trigger) {
if (!drawer || !frame) return;
const kind = trigger.getAttribute('data-account-drawer-open') || '';
const route = drawerRoutes[kind];
if (!route) return;
lastTrigger = trigger;
if (drawerTitle) drawerTitle.textContent = trigger.getAttribute('data-drawer-title') || '账户中心';
if (drawerDescription) drawerDescription.textContent = trigger.getAttribute('data-drawer-description') || '';
frame.setAttribute('title', drawerTitle ? drawerTitle.textContent : '账户中心');
const menu = trigger.closest('details');
if (menu) menu.removeAttribute('open');
setDrawerState(true);
if (typeof drawer.showModal === 'function') {
if (!drawer.open) drawer.showModal();
} else {
drawer.setAttribute('open', 'open');
}
frame.src = route;
if (closeButton) closeButton.focus();
}
document.querySelectorAll('[data-account-drawer-open]').forEach((trigger) => {
trigger.addEventListener('click', () => openDrawer(trigger));
});
document.querySelectorAll('.panel-user-menu').forEach((menu) => {
const summary = menu.querySelector('summary');
if (summary) menu.addEventListener('toggle', () => summary.setAttribute('aria-expanded', menu.open ? 'true' : 'false'));
});
document.addEventListener('click', (event) => {
document.querySelectorAll('.panel-user-menu[open]').forEach((menu) => {
if (!menu.contains(event.target)) {
menu.removeAttribute('open');
const summary = menu.querySelector('summary');
if (summary) summary.setAttribute('aria-expanded', 'false');
}
});
});
if (frame) {
frame.addEventListener('load', () => {
if (drawer && drawer.open && drawerFrameWrap) drawerFrameWrap.setAttribute('aria-busy', 'false');
});
}
if (closeButton) closeButton.addEventListener('click', closeDrawer);
if (drawer) {
drawer.addEventListener('close', () => {
setDrawerState(false);
if (frame) frame.src = 'about:blank';
if (lastTrigger && typeof lastTrigger.focus === 'function') lastTrigger.focus();
lastTrigger = null;
});
drawer.addEventListener('click', (event) => {
if (event.target === drawer) closeDrawer();
});
}
document.addEventListener('keydown', (event) => {
if (event.key === 'Escape' && drawer && drawer.open) closeDrawer();
});

@ -346,6 +346,10 @@ body.vu-body :where(.vu-form-row, .vu-form-grid, .vu-invite-wallet-grid) {
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 16px;
}
body.vu-body .vu-password-factor-grid { display: grid; gap: 16px; }
body.vu-body .vu-password-code-row { display: flex; align-items: stretch; gap: 8px; }
body.vu-body .vu-password-code-row .vu-input { min-width: 0; flex: 1 1 auto; }
body.vu-body .vu-password-code-row .vu-btn { flex: 0 0 auto; min-width: 110px; }
body.vu-body :where(.vu-field, .vu-support-field) {
display: flex;
flex-direction: column;
@ -1279,3 +1283,198 @@ body.venix-auth .auth-modal-actions {
body.vu-body .vu-main { max-width: none; padding: 0; }
body.vu-body .vu-invoice-card { padding: 0; border: 0; box-shadow: none; }
}
/* Compact account and recharge surfaces used by the top-right account drawer. */
body.vu-body :where(.vu-account-workspace, .vu-recharge-workspace) {
width: 100%;
max-width: 1080px;
margin: 0 auto;
}
body.vu-body .vu-account-banner,
body.vu-body .vu-recharge-banner {
display: flex;
align-items: center;
justify-content: space-between;
gap: 28px;
margin-bottom: 20px;
padding: clamp(24px, 4vw, 37px);
color: #e8f2f6;
background: linear-gradient(130deg, #0f1f30 0%, #14394b 68%, #155367 100%);
border: 1px solid rgba(90, 216, 215, .16);
border-radius: 16px;
box-shadow: 0 18px 38px rgba(11, 34, 50, .15);
}
body.vu-body .vu-account-banner-copy,
body.vu-body .vu-recharge-banner-copy { min-width: 0; }
body.vu-body .vu-account-eyebrow {
display: block;
margin: 0 0 8px;
color: #54d8d5;
font-size: 10px;
font-weight: 850;
letter-spacing: .16em;
line-height: 1.4;
}
body.vu-body :where(.vu-account-banner h1, .vu-recharge-banner h1) {
margin: 0;
color: #f4fbfc;
font-size: clamp(25px, 4vw, 34px);
line-height: 1.2;
letter-spacing: -.7px;
}
body.vu-body :where(.vu-account-banner p, .vu-recharge-banner p) {
max-width: 670px;
margin: 12px 0 0;
color: #a7c0ca;
font-size: 13px;
line-height: 1.75;
}
body.vu-body .vu-account-banner-meta {
display: flex;
align-items: center;
flex: 0 0 auto;
gap: 11px;
min-width: 180px;
padding: 12px 14px;
background: rgba(4, 21, 34, .25);
border: 1px solid rgba(131, 231, 227, .17);
border-radius: 11px;
}
body.vu-body .vu-account-banner-meta > div { display: grid; gap: 4px; min-width: 0; }
body.vu-body .vu-account-banner-meta span:not(.vu-account-avatar) { color: #91b0bc; font-size: 11px; }
body.vu-body .vu-account-banner-meta strong { overflow-wrap: anywhere; color: #f2fbfc; font-size: 13px; }
body.vu-body .vu-account-avatar {
width: 38px;
height: 38px;
display: inline-flex;
align-items: center;
justify-content: center;
flex: 0 0 38px;
color: #57d5d3;
background: rgba(76, 213, 211, .14);
border-radius: 10px;
font-size: 20px;
}
body.vu-body .vu-security-stack { display: grid; gap: 18px; }
body.vu-body .vu-security-section,
body.vu-body .vu-recharge-card {
min-width: 0;
padding: clamp(20px, 3.2vw, 29px);
background: var(--vu-panel);
border: 1px solid var(--vu-border);
border-radius: 14px;
box-shadow: var(--vu-shadow);
}
body.vu-body .vu-security-section-head {
display: grid;
grid-template-columns: auto minmax(0, 1fr) auto;
align-items: start;
gap: 15px;
}
body.vu-body .vu-security-index {
width: 31px;
height: 31px;
display: inline-flex;
align-items: center;
justify-content: center;
color: var(--vu-brand-strong);
background: var(--vu-brand-soft);
border-radius: 9px;
font-size: 11px;
font-weight: 850;
}
body.vu-body .vu-security-section-head h2,
body.vu-body .vu-recharge-card-head h2 {
margin: 0;
color: var(--vu-text);
font-size: 20px;
line-height: 1.3;
letter-spacing: -.3px;
}
body.vu-body .vu-security-section-head p { margin: 7px 0 0; color: var(--vu-muted); font-size: 12px; line-height: 1.65; }
body.vu-body .vu-security-state {
display: inline-flex;
align-items: center;
gap: 6px;
padding: 7px 10px;
color: var(--vu-muted);
background: var(--vu-panel-soft);
border: 1px solid var(--vu-border);
border-radius: 99px;
font-size: 11px;
font-weight: 750;
white-space: nowrap;
}
body.vu-body .vu-security-state.is-active { color: var(--vu-success); background: var(--vu-success-soft); border-color: rgba(32, 135, 100, .12); }
body.vu-body .vu-security-state i { font-size: 16px; }
body.vu-body .vu-security-content { display: grid; gap: 17px; margin: 24px 0 0 46px; padding-top: 22px; border-top: 1px solid var(--vu-border); }
body.vu-body .vu-security-status-card,
body.vu-body .vu-factor-card {
display: flex;
align-items: flex-start;
gap: 11px;
min-width: 0;
padding: 14px;
background: var(--vu-panel-soft);
border: 1px solid var(--vu-border);
border-radius: 10px;
}
body.vu-body .vu-security-status-card > i,
body.vu-body .vu-factor-card-head > i { flex: 0 0 auto; color: var(--vu-brand); font-size: 20px; }
body.vu-body .vu-security-status-card > div,
body.vu-body .vu-factor-card-head > div { display: grid; gap: 4px; min-width: 0; }
body.vu-body .vu-security-status-card strong,
body.vu-body .vu-factor-card strong { color: var(--vu-text); font-size: 13px; }
body.vu-body .vu-security-status-card span,
body.vu-body .vu-factor-card span { color: var(--vu-muted); font-size: 12px; line-height: 1.55; }
body.vu-body .vu-security-status-card.is-muted { color: var(--vu-muted); }
body.vu-body .vu-security-form { max-width: 660px; }
body.vu-body .vu-security-form-danger { padding-top: 17px; border-top: 1px dashed var(--vu-border); }
body.vu-body .vu-ga-setup-compact { margin-top: 0; }
body.vu-body .vu-password-form { max-width: 820px; }
body.vu-body .vu-password-factor-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); }
body.vu-body .vu-password-factor-grid > :only-child { grid-column: 1 / -1; }
body.vu-body .vu-factor-card { display: grid; gap: 13px; }
body.vu-body .vu-factor-card-head { display: flex; align-items: flex-start; gap: 10px; }
body.vu-body .vu-factor-card .vu-input { min-width: 0; }
body.vu-body .vu-recharge-stack { display: grid; grid-template-columns: minmax(0, 1.3fr) minmax(270px, .7fr); align-items: start; gap: 18px; }
body.vu-body .vu-recharge-card-head { display: flex; align-items: flex-start; justify-content: space-between; gap: 16px; margin-bottom: 21px; }
body.vu-body .vu-recharge-card-icon { width: 42px; height: 42px; display: inline-flex; align-items: center; justify-content: center; flex: 0 0 42px; color: #fff; background: var(--vu-brand); border-radius: 11px; font-size: 21px; }
body.vu-body .vu-recharge-card-icon.is-soft { color: var(--vu-brand); background: var(--vu-brand-soft); }
body.vu-body .vu-recharge-balance { display: flex; flex: 0 0 auto; flex-direction: column; align-items: flex-start; gap: 8px; min-width: 160px; padding: 15px 17px; background: rgba(4, 21, 34, .25); border: 1px solid rgba(131, 231, 227, .17); border-radius: 11px; }
body.vu-body .vu-recharge-balance > span { color: #91b0bc; font-size: 11px; }
body.vu-body .vu-recharge-balance strong { color: #f3fbfc; font-size: 24px; letter-spacing: -.4px; }
body.vu-body .vu-recharge-balance .vu-btn { min-height: 34px; padding: 8px 11px; color: #9be8e7; background: rgba(75, 211, 210, .12); border-color: rgba(92, 218, 215, .15); box-shadow: none; font-size: 11px; }
body.vu-body .vu-recharge-form { max-width: 620px; }
body.vu-body .vu-amount-field { position: relative; }
body.vu-body .vu-amount-field > span { position: absolute; top: 50%; left: 14px; z-index: 1; color: var(--vu-brand-strong); font-size: 16px; font-weight: 850; transform: translateY(-50%); }
body.vu-body .vu-amount-field .vu-input { padding-left: 34px; font-size: 17px; font-weight: 700; }
body.vu-body .vu-recharge-methods { min-height: 42px; margin-top: 2px; }
body.vu-body .vu-recharge-method { display: inline-flex; align-items: center; justify-content: center; gap: 8px; min-height: 45px; padding: 10px 14px; color: var(--vu-text-soft); background: var(--vu-panel); border: 1px solid var(--vu-border-strong); border-radius: 10px; font-size: 12px; font-weight: 750; cursor: pointer; }
body.vu-body .vu-recharge-method:hover { color: var(--vu-brand-strong); background: var(--vu-brand-soft); border-color: #35b9c0; transform: translateY(-1px); }
body.vu-body .vu-recharge-method i { color: var(--vu-brand); font-size: 18px; }
body.vu-body .vu-method-loading { display: inline-flex; align-items: center; gap: 8px; color: var(--vu-muted); font-size: 12px; }
body.vu-body .vu-recharge-notes { min-height: 100%; }
body.vu-body .vu-recharge-tip-list { display: grid; gap: 10px; }
body.vu-body .vu-recharge-tip-list > div { display: flex; align-items: flex-start; gap: 10px; padding: 12px; color: var(--vu-text-soft); background: var(--vu-panel-soft); border-radius: 9px; font-size: 12px; line-height: 1.65; }
body.vu-body .vu-recharge-tip-list i { flex: 0 0 auto; color: var(--vu-brand); font-size: 18px; }
body.vu-body .vu-recharge-history { margin-top: 18px; }
@media (max-width: 760px) {
body.vu-body .vu-account-banner,
body.vu-body .vu-recharge-banner { align-items: flex-start; flex-direction: column; }
body.vu-body .vu-account-banner-meta,
body.vu-body .vu-recharge-balance { width: 100%; }
body.vu-body .vu-recharge-stack { grid-template-columns: 1fr; }
body.vu-body .vu-security-content { margin-left: 0; }
}
@media (max-width: 560px) {
body.vu-body .vu-security-section-head { grid-template-columns: auto minmax(0, 1fr); }
body.vu-body .vu-security-state { grid-column: 2; justify-self: start; }
body.vu-body .vu-password-factor-grid { grid-template-columns: 1fr; }
body.vu-body .vu-ga-setup-compact { grid-template-columns: 1fr; }
body.vu-body .vu-account-banner,
body.vu-body .vu-recharge-banner { padding: 22px 19px; }
}

@ -72,6 +72,54 @@ html.panel-announcements-open body { position: fixed; top: var(--panel-announcem
.panel-announcements-toolbar { padding: 12px 16px; }
.panel-announcements-scroll { padding-inline: 16px; }
}
/* User actions live under the top-right account menu. The drawers keep the
existing account, recharge and promotion flows available without making
those pages part of the primary navigation. */
.panel-user-menu { position: relative; z-index: 12; }
.panel-user-menu > summary { list-style: none; }
.panel-user-menu > summary::-webkit-details-marker { display: none; }
.panel-user-menu > summary { cursor: pointer; min-height: 34px; padding: 2px 7px; border-radius: 8px; }
.panel-user-menu > summary:hover,
.panel-user-menu[open] > summary { color: #117f88; background: #edf6f6; }
.panel-user-menu-chevron { color: #8294a3; font-size: 15px; transition: transform .15s ease; }
.panel-user-menu[open] .panel-user-menu-chevron { transform: rotate(180deg); color: #117f88; }
.panel-user-menu-options { position: absolute; top: calc(100% + 7px); right: 0; display: grid; gap: 3px; min-width: 178px; padding: 7px; border: 1px solid #dce7ed; border-radius: 10px; background: #fff; box-shadow: 0 14px 34px rgba(17,42,59,.15); }
.panel-user-menu-options button { display: flex; align-items: center; gap: 9px; width: 100%; min-height: 38px; padding: 8px 10px; border: 0; border-radius: 7px; background: transparent; color: #536b7e; font: inherit; font-size: 12px; font-weight: 700; text-align: left; }
.panel-user-menu-options button:hover,
.panel-user-menu-options button:focus-visible { background: #edf6f6; color: #117f88; outline: none; }
.panel-user-menu-options button i { width: 18px; color: #2b9da5; font-size: 17px; text-align: center; }
html.panel-account-open { overflow: hidden; overscroll-behavior: none; scroll-behavior: auto !important; }
html.panel-account-open body { position: fixed; top: var(--panel-account-scroll-top, 0px); left: 0; right: 0; width: 100%; overflow: hidden; }
.panel-account-drawer { position: fixed; inset: 0 0 0 auto; display: none; width: min(720px, 100%); max-width: 100%; height: 100vh; height: 100dvh; max-height: none; margin: 0; padding: 0; border: 0; border-radius: 0; background: #f4f7fb; color: #25384e; box-shadow: -14px 0 52px rgba(19,42,65,.18); overflow: hidden; }
.panel-account-drawer[open] { display: flex; flex-direction: column; }
.panel-account-drawer::backdrop { background: rgba(16,29,44,.46); }
.panel-account-drawer-header { display: flex; flex: 0 0 auto; align-items: flex-start; justify-content: space-between; gap: 14px; padding: 22px 24px 18px; border-bottom: 1px solid #e1e9ef; background: #fff; }
.panel-account-drawer-header > div { min-width: 0; }
.panel-account-drawer-kicker { margin: 0 0 4px; color: #159da9; font-size: 10px; font-weight: 800; letter-spacing: .14em; text-transform: uppercase; }
.panel-account-drawer-header h2 { margin: 0 0 6px; color: #25384e; font-size: 20px; line-height: 1.45; font-weight: 800; }
.panel-account-drawer-header p:last-child { margin: 0; color: #7a8c9d; font-size: 12px; line-height: 1.7; }
.panel-account-drawer-close.button { flex: 0 0 44px; width: 44px; height: 44px; min-height: 44px; padding: 0; font-size: 22px; }
.panel-account-drawer-frame-wrap { min-height: 0; flex: 1 1 auto; position: relative; background: #f4f7fb; }
.panel-account-drawer-frame-wrap[aria-busy="true"]::before { content: "正在加载…"; position: absolute; inset: 0; z-index: 1; display: grid; place-items: center; color: #7d91a0; font-size: 12px; pointer-events: none; }
.panel-account-drawer-frame-wrap[aria-busy="false"]::before { display: none; }
.panel-account-drawer-frame-wrap iframe { display: block; width: 100%; height: 100%; border: 0; background: #f4f7fb; }
body.vu-embedded { min-width: 320px; background: #f4f7fb; }
body.vu-embedded .dashboard { display: block; min-height: 100vh; }
body.vu-embedded .dashboard > .panel-sidebar,
body.vu-embedded .dashboard > .main-area > .panel-topbar { display: none; }
body.vu-embedded .dashboard > .main-area { min-height: 100vh; }
body.vu-embedded .dashboard > .main-area > .vu-main { max-width: none; padding: 0; }
body.vu-embedded .dashboard > .main-area > .vu-main > .vu-topbar { margin: 0; }
@media (max-width: 600px) {
.panel-user-menu-options { right: -5px; min-width: 170px; }
.panel-account-drawer { width: 100%; }
.panel-account-drawer-header { padding: 18px 16px 16px; }
}
@media (max-width: 520px) {
.panel-user-menu .topbar-user .avatar { display: inline-flex; }
.panel-user-menu .topbar-user > span:nth-child(2) { display: none; }
.panel-user-menu .topbar-user #current-username { display: block; max-width: 90px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
}
.admin-menu-options { max-height: min(70vh, 520px); overflow-y: auto; }
.admin-menu-options a { min-height: 34px; display: flex; align-items: center; padding: 7px 10px; border-radius: 7px; color: #536b7e; font-size: 12px; font-weight: 700; text-decoration: none; }
.admin-menu-options a:hover { background: #edf6f6; color: #117f88; }

@ -0,0 +1,380 @@
(function () {
"use strict";
var payTimer = null;
var methodRequestTimer = null;
var methodRequestId = 0;
var payDialog = document.getElementById("vuPayDialog");
var payTitle = document.getElementById("vuPayTitle");
var payInfo = document.getElementById("vuPayInfo");
var payOpen = document.getElementById("vuPayOpen");
var payOpenLabel = document.getElementById("vuPayOpenLabel");
var qrcodeBox = document.getElementById("qrcode");
var chainDetails = document.getElementById("vuPayChainDetails");
var payNetwork = document.getElementById("vuPayNetwork");
var payAmount = document.getElementById("vuPayAmount");
var payAddress = document.getElementById("vuPayAddress");
var payAddressCopy = document.getElementById("vuPayAddressCopy");
var currentBalance = document.getElementById("vuCurrentBalance");
var priceInput = document.getElementById("price");
var methodBox = document.getElementById("vuRechargeMethods");
var methodHint = document.getElementById("vuRechargeHint");
function qs(selector) {
return document.querySelector(selector);
}
function qsa(selector) {
return Array.prototype.slice.call(document.querySelectorAll(selector));
}
function topWindow() {
try {
return window.top || window;
} catch (error) {
return window;
}
}
function alertPay(message, type, title) {
if (window.VuModal && window.VuModal.alert) {
return window.VuModal.alert(message, type || "success", title);
}
window.alert(message);
return Promise.resolve();
}
function encoded(data) {
return new URLSearchParams(data || {}).toString();
}
function requestHeaders(headers) {
var next = Object.assign({}, headers || {});
next["X-Requested-With"] = "XMLHttpRequest";
var csrfField = qs("[data-csrf-token]");
var csrfToken = csrfField ? String(csrfField.getAttribute("data-csrf-token") || "") : "";
if (csrfToken) next["X-Admin-CSRF-Token"] = csrfToken;
return next;
}
function parseJson(response) {
return response.text().then(function (text) {
var data = {};
try {
data = text ? JSON.parse(text) : {};
} catch (error) {
data = {};
}
if (!response.ok) {
throw new Error(data.msg || data.errmsg || ("HTTP " + response.status));
}
return data;
});
}
function postForm(url, data) {
return fetch(url, {
method: "POST",
credentials: "same-origin",
headers: requestHeaders({
"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
"X-Requested-With": "XMLHttpRequest"
}),
body: encoded(data)
}).then(parseJson);
}
function getJson(url) {
return fetch(url, {
credentials: "same-origin",
headers: requestHeaders({ "X-Requested-With": "XMLHttpRequest" })
}).then(parseJson);
}
function amountInCents() {
if (!priceInput) return 0;
var raw = String(priceInput.value || "").trim();
if (!/^\d+(?:\.\d{1,2})?$/.test(raw)) return 0;
var amount = Number(raw);
if (!Number.isFinite(amount) || amount <= 0) return 0;
return Math.round(amount * 100);
}
function amountText() {
return (amountInCents() / 100).toFixed(2);
}
function methodCents(value) {
var amount = Number(value);
return Number.isFinite(amount) && amount >= 0 ? Math.round(amount * 100) : 0;
}
function setMethodHint(message, type) {
if (!methodHint) return;
methodHint.textContent = message || "";
methodHint.className = "vu-form-message" + (type ? " is-" + type : "");
}
function methodDefinition(method) {
var id = String(method && method.id || "");
var definitions = {
paytaro: { type: "paytaro", createUrl: "/user/paytaro/order", statusUrl: "/user/paytaro/status", icon: "mdi-qrcode-scan" },
yipay_alipay: { type: "yipay", method: "alipay", createUrl: "/user/yipay/order", statusUrl: "/user/yipay/status", icon: "mdi-credit-card-check-outline" },
yipay_wxpay: { type: "yipay", method: "wxpay", createUrl: "/user/yipay/order", statusUrl: "/user/yipay/status", icon: "mdi-wechat" },
usdt: { type: "usdt", createUrl: "/user/usdt/order", statusUrl: "/user/usdt/status", icon: "mdi-currency-usd" }
};
if (!Object.prototype.hasOwnProperty.call(definitions, id)) return null;
return Object.assign({}, definitions[id], { id: id, label: String(method.label || id) });
}
function renderMethods(methods) {
if (!methodBox) return;
methodBox.innerHTML = "";
var amount = amountInCents();
var available = (methods || []).filter(function (method) {
var definition = methodDefinition(method);
if (!definition) return false;
var minimum = methodCents(method.min_amount);
var maximum = methodCents(method.max_amount);
return amount >= minimum && (maximum === 0 || amount <= maximum);
});
if (!available.length) {
methodBox.hidden = true;
setMethodHint("当前金额没有符合条件的支付方式,请调整充值金额。", "warning");
return;
}
available.forEach(function (method) {
var definition = methodDefinition(method);
var button = document.createElement("button");
var icon = document.createElement("i");
var label = document.createElement("span");
button.className = "vu-recharge-method";
button.type = "button";
button.setAttribute("data-recharge-method", definition.id);
icon.className = "mdi " + definition.icon;
label.textContent = definition.label;
button.appendChild(icon);
button.appendChild(label);
button.addEventListener("click", function () {
createPay(definition);
});
methodBox.appendChild(button);
});
methodBox.hidden = false;
setMethodHint("选择支付方式继续,订单金额为 ¥ " + amountText() + "。", "success");
}
function loadMethods() {
if (!priceInput || !methodBox) return;
if (methodRequestTimer) window.clearTimeout(methodRequestTimer);
var amount = amountInCents();
if (!amount) {
methodBox.innerHTML = "";
methodBox.hidden = true;
setMethodHint("先填写充值金额,系统会显示可用的支付方式。", "");
return;
}
methodBox.hidden = false;
methodBox.innerHTML = "<span class=\"vu-method-loading\"><i class=\"mdi mdi-loading mdi-spin\"></i>正在查询支付方式…</span>";
setMethodHint("正在根据金额查询可用方式…", "");
methodRequestTimer = window.setTimeout(function () {
var requestId = ++methodRequestId;
getJson("/user/recharge/options?amount=" + encodeURIComponent((amount / 100).toFixed(2))).then(function (data) {
if (requestId !== methodRequestId) return;
if (Number(data.ret) !== 1) {
methodBox.hidden = true;
setMethodHint(data.msg || "充值方式暂时不可用。", "error");
return;
}
renderMethods(Array.isArray(data.methods) ? data.methods : []);
}).catch(function (error) {
if (requestId !== methodRequestId) return;
methodBox.hidden = true;
setMethodHint(error.message || "支付方式查询失败,请稍后重试。", "error");
});
}, 220);
}
function isMobileDevice() {
return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent || "");
}
function isPaytaroMobileDevice() {
if (isMobileDevice()) return true;
if (navigator.userAgentData && navigator.userAgentData.mobile) return true;
return Boolean(window.matchMedia && window.matchMedia("(pointer: coarse) and (hover: none)").matches);
}
function alipayAppUrl(payurl) {
return "alipays://platformapi/startapp?appId=20000067&url=" + encodeURIComponent(String(payurl || ""));
}
function paytaroMobileUrl(payurl) {
payurl = String(payurl || "");
try {
var url = new URL(payurl);
var host = String(url.hostname || "").toLowerCase();
if (host === "mclient.alipay.com" || url.searchParams.get("method") === "alipay.trade.wap.pay") return payurl;
} catch (error) {
return "";
}
return alipayAppUrl(payurl);
}
function renderPaymentQr(container, content, fallbackUrl) {
container.innerHTML = "";
try {
if (!window.QRCode) throw new Error("QRCode library unavailable");
var levels = window.QRCode.CorrectLevel || { L: 1, M: 0 };
new QRCode(container, { text: content, width: 220, height: 220, correctLevel: content.length > 1200 ? levels.L : levels.M });
if (!container.children.length) throw new Error("QRCode output missing");
return true;
} catch (error) {
container.innerHTML = "";
if (fallbackUrl) {
var link = document.createElement("a");
link.className = "vu-text-link";
link.href = fallbackUrl;
link.target = "_blank";
link.rel = "noopener";
link.textContent = "打开支付页面";
container.appendChild(link);
} else {
var code = document.createElement("code");
code.textContent = content;
container.appendChild(code);
}
return false;
}
}
function clearPaymentReturnParams() {
if (!window.history || !window.history.replaceState) return;
var url = new URL(window.location.href);
url.searchParams.delete("payment");
url.searchParams.delete("pid");
window.history.replaceState(null, "", url.pathname + (url.search ? url.search : "") + url.hash);
}
function closePayDialog() {
if (payTimer) {
window.clearInterval(payTimer);
payTimer = null;
}
if (!payDialog) return;
payDialog.classList.remove("is-open");
payDialog.setAttribute("aria-hidden", "true");
payDialog.setAttribute("hidden", "hidden");
document.body.classList.remove("vu-modal-lock");
}
function openPayDialog(data) {
if (!payDialog || !qrcodeBox || !payInfo || !payOpen) return false;
var isUsdt = data.payment_type === "usdt";
var qrContent = isUsdt ? String(data.receive_address || "") : String(data.url || "");
if (!qrContent) {
alertPay(isUsdt ? "系统没有返回有效收款地址。" : "支付网关没有返回有效支付链接。", "error", "创建订单失败");
return false;
}
if (payTitle) payTitle.textContent = isUsdt ? "USDT 扫码支付" : (data.payment_label || "扫码支付");
payInfo.textContent = isUsdt ? "请按下方网络和数量完成转账,支付数量必须完全一致。" : "订单金额:¥ " + data.amount + ",请扫码完成支付。";
var checkoutLinkEnabled = data.payment_type !== "paytaro" && (!isUsdt || (data.checkout_link_enabled === true && Boolean(data.url)));
payOpen.hidden = !checkoutLinkEnabled;
if (checkoutLinkEnabled) payOpen.setAttribute("href", data.url);
else payOpen.removeAttribute("href");
if (payOpenLabel) payOpenLabel.textContent = isUsdt ? "打开收银台" : "打开支付链接";
if (chainDetails) chainDetails.hidden = !isUsdt;
if (isUsdt) {
var network = String(data.network || "").toLowerCase();
var token = String(data.token || "USDT").toUpperCase();
if (payNetwork) payNetwork.textContent = network === "tron" && token === "USDT" ? "TRON (TRC20)" : network.toUpperCase();
if (payAmount) payAmount.textContent = data.actual_amount + " " + token;
if (payAddress) payAddress.textContent = qrContent;
if (payAddressCopy) payAddressCopy.setAttribute("data-copy", qrContent);
} else if (payAddressCopy) payAddressCopy.removeAttribute("data-copy");
renderPaymentQr(qrcodeBox, qrContent, isUsdt ? "" : data.url);
payDialog.removeAttribute("hidden");
payDialog.classList.add("is-open");
payDialog.setAttribute("aria-hidden", "false");
document.body.classList.add("vu-modal-lock");
return true;
}
function checkPayStatus(statusUrl) {
if (!statusUrl) return;
postForm(statusUrl, {}).then(function (data) {
if (String(data.result) === "1") {
closePayDialog();
if (currentBalance && data.balance !== null && typeof data.balance !== "undefined") currentBalance.textContent = "¥ " + data.balance;
alertPay("支付成功,余额已入账。", "success", "账户充值").then(function () {
clearPaymentReturnParams();
topWindow().location.reload();
});
return;
}
if (data.status === "expired" || data.status === "failed") {
closePayDialog();
alertPay(data.status === "expired" ? "订单已过期,请重新发起充值。" : "订单处理失败,请重新发起充值。", "error", "支付未完成");
}
}).catch(function () {
// A transient status request failure should not interrupt the payment poll.
});
}
function createPay(definition) {
var cents = amountInCents();
if (!definition || !cents) {
alertPay("请填写正确的充值金额。", "error", "金额错误");
return;
}
if (payTimer) {
window.clearInterval(payTimer);
payTimer = null;
}
qsa("[data-recharge-method]").forEach(function (button) { button.disabled = true; });
postForm(definition.createUrl, { price: (cents / 100).toFixed(2), type: definition.type, method: definition.method || "" }).then(function (data) {
qsa("[data-recharge-method]").forEach(function (button) { button.disabled = false; });
if (Number(data.code) !== 0) {
alertPay(data.errmsg || data.msg || "支付网关处理失败。", "error", "创建订单失败");
return;
}
data.payment_type = definition.type;
if (definition.type === "paytaro" && isPaytaroMobileDevice()) {
payTimer = window.setInterval(function () { checkPayStatus(data.status_url || definition.statusUrl); }, Number(data.poll_interval) || 3000);
var mobileUrl = paytaroMobileUrl(data.url);
if (!mobileUrl) {
openPayDialog(data);
return;
}
topWindow().location.assign(mobileUrl);
return;
}
if (definition.type !== "usdt" && isMobileDevice()) {
topWindow().location.href = data.url;
return;
}
if (!openPayDialog(data)) return;
payTimer = window.setInterval(function () { checkPayStatus(data.status_url || definition.statusUrl); }, Number(data.poll_interval) || 3000);
}).catch(function (error) {
qsa("[data-recharge-method]").forEach(function (button) { button.disabled = false; });
alertPay(error.message || "发生了错误。", "error", "请求失败");
});
}
if (priceInput) {
priceInput.addEventListener("input", loadMethods);
priceInput.addEventListener("change", loadMethods);
}
qsa("[data-pay-close]").forEach(function (item) { item.addEventListener("click", closePayDialog); });
var returnParams = new URLSearchParams(window.location.search);
if (returnParams.get("payment") === "yipay") {
checkPayStatus("/user/yipay/status");
payTimer = window.setInterval(function () { checkPayStatus("/user/yipay/status"); }, 3000);
} else if (returnParams.get("payment") === "paytaro") {
checkPayStatus("/user/paytaro/status");
payTimer = window.setInterval(function () { checkPayStatus("/user/paytaro/status"); }, 3000);
}
})();

@ -163,7 +163,15 @@
function parseResponse(response) {
if (!response.ok) {
throw new Error("HTTP " + response.status);
return response.text().then(function (text) {
var data = {};
try {
data = text ? JSON.parse(text) : {};
} catch (error) {
data = {};
}
throw new Error(data.msg || "HTTP " + response.status);
});
}
return response.text().then(function (text) {
if (!text) return { ret: 1, msg: "操作已提交" };
@ -176,10 +184,18 @@
}
function request(url, options) {
options = options || {};
var headers = Object.assign({ "X-Requested-With": "XMLHttpRequest" }, options.headers || {});
var csrfElement = qs("[data-csrf-token]");
var csrfToken = csrfElement ? csrfElement.getAttribute("data-csrf-token") : "";
if (!csrfToken) {
var csrfMeta = qs("meta[name='account-csrf-token']");
csrfToken = csrfMeta ? csrfMeta.getAttribute("content") : "";
}
if (csrfToken) headers["X-Admin-CSRF-Token"] = csrfToken;
return fetch(url, Object.assign({
credentials: "same-origin",
headers: { "X-Requested-With": "XMLHttpRequest" }
}, options || {})).then(parseResponse);
credentials: "same-origin"
}, options, { headers: headers })).then(parseResponse);
}
function post(url, data) {
@ -261,15 +277,47 @@
function bindEditActions() {
var passwordForm = qs("#vuPasswordForm");
if (passwordForm) {
var emailVerifyButton = qs("#pwd-send-email");
if (emailVerifyButton) {
emailVerifyButton.addEventListener("click", function () {
var original = emailVerifyButton.innerHTML;
var done = setBusy(emailVerifyButton, "发送中...");
post("/user/password/verify/send", {}).then(function (data) {
var seconds = Number(data.retry_after) || 60;
var until = Date.now() + seconds * 1000;
emailVerifyButton.disabled = true;
function tick() {
var left = Math.max(0, Math.ceil((until - Date.now()) / 1000));
if (left <= 0) {
emailVerifyButton.disabled = false;
emailVerifyButton.innerHTML = original;
return;
}
emailVerifyButton.textContent = "重新发送 (" + left + "s)";
window.setTimeout(tick, 1000);
}
done();
tick();
alertModal(data.msg || "验证码已发送", data.ret ? "success" : "error");
}).catch(function (error) {
alertModal(error.message, "error");
done();
});
});
}
passwordForm.addEventListener("submit", function (event) {
event.preventDefault();
var oldpwd = qs("#oldpwd");
var pwd = qs("#pwd");
var repwd = qs("#repwd");
var emailCode = qs("#pwd-emailcode");
var gaCode = qs("#pwd-gacode");
var button = qs("#pwd-update");
var oldValue = oldpwd ? oldpwd.value : "";
var pwdValue = pwd ? pwd.value : "";
var repwdValue = repwd ? repwd.value : "";
var emailCodeValue = emailCode ? emailCode.value.trim() : "";
var gaCodeValue = gaCode ? gaCode.value.trim() : "";
if (!oldValue || !pwdValue || !repwdValue) {
alertModal("请完整填写当前密码和新密码。", "error");
@ -279,16 +327,34 @@
alertModal("两次输入的新密码不一致。", "error");
return;
}
if (!emailCodeValue && !gaCodeValue) {
alertModal("请输入邮箱验证码或谷歌动态码。", "error");
return;
}
if (emailCodeValue && !/^\d{6}$/.test(emailCodeValue)) {
alertModal("邮箱验证码应为 6 位数字。", "error");
return;
}
if (gaCodeValue && !/^\d{6}$/.test(gaCodeValue)) {
alertModal("谷歌动态码应为 6 位数字。", "error");
return;
}
if (new TextEncoder().encode(pwdValue).length < 12 || new TextEncoder().encode(pwdValue).length > 72 || !/[A-Z]/.test(pwdValue) || !/[a-z]/.test(pwdValue) || !/[0-9]/.test(pwdValue) || !/[^A-Za-z0-9]/.test(pwdValue)) {
alertModal("密码需为 12–72 字节,包含大写、小写字母、数字和符号。", "error");
return;
}
var done = setBusy(button, "保存中...");
post("/user/password", { oldpwd: oldValue, pwd: pwdValue, repwd: repwdValue }).then(function (data) {
var payload = { oldpwd: oldValue, pwd: pwdValue, repwd: repwdValue };
if (emailCodeValue) payload.emailcode = emailCodeValue;
if (gaCodeValue) payload.gacode = gaCodeValue;
post("/user/password", payload).then(function (data) {
alertModal(data.msg || "密码已更新", data.ret ? "success" : "error").then(function () {
if (data.ret) {
passwordForm.reset();
var loginUrl = "/auth/login";
if (window.top && window.top !== window) window.top.location.href = loginUrl;
else window.location.href = loginUrl;
}
});
done();
@ -480,7 +546,7 @@
if (resetButton) {
resetButton.addEventListener("click", function () {
confirmModal("重置后旧邀请码会失效,剩余邀请次数不会改变。", "重置邀请码").then(function (ok) {
confirmModal("重置后旧推广链接会失效,剩余推广次数不会改变。", "重置推广链接").then(function (ok) {
if (!ok) return;
var done = setBusy(resetButton, "重置中...");
post("/user/resetiv").then(function (data) {

@ -1,17 +1,17 @@
{extends file='layout.tpl'}
{block name='email_title'}
{if $language == 'true'}{if !empty($scene) && $scene == 'login'}Login verification{else}Email verification{/if} | {$config["appName"]|escape:"html"}{else}{if !empty($scene) && $scene == 'login'}登录安全验证{else}注册邮箱验证{/if} | {$config["appName"]|escape:"html"}{/if}
{if $language == 'true'}{if !empty($scene) && $scene == 'login'}Login verification{elseif !empty($scene) && $scene == 'password_change'}Password change verification{else}Email verification{/if} | {$config["appName"]|escape:"html"}{else}{if !empty($scene) && $scene == 'login'}登录安全验证{elseif !empty($scene) && $scene == 'password_change'}修改密码验证{else}注册邮箱验证{/if} | {$config["appName"]|escape:"html"}{/if}
{/block}
{block name='preheader'}{if $language == 'true'}Your verification code is {$code|escape:"html"}.{else}您的验证码是 {$code|escape:"html"}。{/if}{/block}
{block name='content'}
<p style="margin:0 0 10px; color:#159da9; font-size:11px; line-height:16px; font-weight:800; letter-spacing:1.8px; text-transform:uppercase;">{if !empty($scene) && $scene == 'login'}ACCOUNT SECURITY{elseif !empty($scene) && $scene == 'registration'}WELCOME TO THE CLOUD{else}EMAIL VERIFICATION{/if}</p>
<p style="margin:0 0 10px; color:#159da9; font-size:11px; line-height:16px; font-weight:800; letter-spacing:1.8px; text-transform:uppercase;">{if !empty($scene) && $scene == 'login'}ACCOUNT SECURITY{elseif !empty($scene) && $scene == 'registration'}WELCOME TO THE CLOUD{elseif !empty($scene) && $scene == 'password_change'}ACCOUNT SECURITY{else}EMAIL VERIFICATION{/if}</p>
<h1 class="email-title" style="margin:0 0 14px; color:#15243a; font-size:30px; line-height:39px; font-weight:800; letter-spacing:-.6px;">
{if $language == 'true'}{if !empty($scene) && $scene == 'login'}Confirm your sign-in{else}Verify your email address{/if}{else}{if !empty($scene) && $scene == 'login'}确认本次登录{else}验证您的注册邮箱{/if}{/if}
{if $language == 'true'}{if !empty($scene) && $scene == 'login'}Confirm your sign-in{elseif !empty($scene) && $scene == 'password_change'}Confirm your password change{else}Verify your email address{/if}{else}{if !empty($scene) && $scene == 'login'}确认本次登录{elseif !empty($scene) && $scene == 'password_change'}确认修改密码{else}验证您的注册邮箱{/if}{/if}
</h1>
<p style="margin:0 0 25px; color:#53647a; font-size:14px; line-height:24px;">
{if $language == 'true'}{if !empty($scene) && $scene == 'login'}Enter the code below to complete the security check for your sign-in.{else}Enter the code below on the registration page to finish creating your account.{/if}{else}{if !empty($scene) && $scene == 'login'}请在登录页面输入下方验证码,完成本次安全验证。{else}请在注册页面输入下方验证码,完成邮箱验证并继续创建账户。{/if}{/if}
{if $language == 'true'}{if !empty($scene) && $scene == 'login'}Enter the code below to complete the security check for your sign-in.{elseif !empty($scene) && $scene == 'password_change'}Enter the code below on the account page to confirm your password change.{else}Enter the code below on the registration page to finish creating your account.{/if}{else}{if !empty($scene) && $scene == 'login'}请在登录页面输入下方验证码,完成本次安全验证。{elseif !empty($scene) && $scene == 'password_change'}请在账户设置页面输入下方验证码,确认修改密码。{else}请在注册页面输入下方验证码,完成邮箱验证并继续创建账户。{/if}{/if}
</p>
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="margin:0 0 22px;">

@ -232,8 +232,8 @@
<div class="col-md-6">
<label class="form-label" for="aff_method">注册返利方式</label>
<select class="form-select" id="aff_method" name="aff_method">
<option value="affid">邀请链接</option>
<option value="code">邀请码</option>
<option value="affid">推广链接(aff 8 位代码)</option>
<option value="code">兼容邀请码(必填)</option>
</select>
</div>
<div class="col-md-6">
@ -243,6 +243,24 @@
<option value="false">关闭</option>
</select>
</div>
<div class="col-md-4">
<label class="form-label" for="referral_reward_rate">推广返利比例(%)</label>
<input class="form-control" id="referral_reward_rate" name="referral_reward_rate" type="number" min="0" max="100" step="0.01" inputmode="decimal" value="20.00">
<div class="form-text">按被邀请用户每次充值金额计算,范围 0–100%。</div>
</div>
<div class="col-md-4">
<label class="form-label" for="referral_reward_days">注册后返利有效期(天)</label>
<input class="form-control" id="referral_reward_days" name="referral_reward_days" type="number" min="1" max="3650" step="1" inputmode="numeric" value="730">
<div class="form-text">被邀请用户注册超过此期限后,充值不再产生推广返利。</div>
</div>
<div class="col-md-4">
<label class="form-label" for="referral_reward_enabled">推广返利开关</label>
<select class="form-select" id="referral_reward_enabled" name="referral_reward_enabled">
<option value="true">开启</option>
<option value="false">关闭</option>
</select>
<div class="form-text">关闭时保留历史返利记录,但新充值不生成返利。</div>
</div>
<div class="col-md-6">
<label class="form-label" for="language">英文落地页</label>
<select class="form-select" id="language" name="language">

@ -28,7 +28,10 @@
<p class="admin-eyebrow mb-1">User</p>
<h5 class="card-title mb-2">{$edit_user->user_name|escape:"html"}</h5>
<p class="text-muted mb-3">{$edit_user->email|escape:"html"}</p>
<div class="admin-user-edit-summary"><div><span>账户余额</span><strong>¥ {$edit_user->money|escape:"html"}</strong></div></div>
<div class="admin-user-edit-summary">
<div><span>账户余额</span><strong>¥ {$edit_user->money|escape:"html"}</strong></div>
<div><span>推广返利余额</span><strong>¥ {$edit_user->aff_money|default:0|escape:"html"}</strong></div>
</div>
</div></div>
<div class="card">
<div class="card-body">
@ -82,6 +85,14 @@
<label class="form-label" for="ref_by">邀请人 ID</label>
<input class="form-control admin-mono" id="ref_by" type="text" value="{$edit_user->ref_by|escape:"html"}" readonly>
</div>
<div class="col-md-6">
<label class="form-label" for="ref_by_name">邀请人账户</label>
<input class="form-control" id="ref_by_name" type="text" value="{if $edit_user->ref_by_user()}{$edit_user->ref_by_user()->user_name|escape:"html"}{else}无{/if}" readonly>
</div>
<div class="col-md-6">
<label class="form-label" for="aff_money">推广返利余额</label>
<input class="form-control" id="aff_money" type="text" value="{$edit_user->aff_money|default:0|escape:"html"}" readonly>
</div>
<div class="col-md-6">
<div class="admin-user-edit-switches">
<label class="admin-user-edit-switch" for="enable">

@ -201,7 +201,7 @@
(function () {
var columns = [
'op', 'id', 'user_name', 'remark', 'email', 'money', 'im_type', 'im_value',
'enable', 'reg_date', 'reg_ip', 'ref_by'
'enable', 'reg_date', 'reg_ip', 'ref_by', 'ref_by_name', 'aff_money'
];
var rows = document.getElementById('userRows');
@ -247,7 +247,7 @@
var clearLoginDeviceTarget = null;
var clearLoginSessionTarget = null;
var searchTimer = null;
var columnStorageKey = 'venix-admin-user-visible-columns-v2';
var columnStorageKey = 'venix-admin-user-visible-columns-v3';
var sortKey = 'id';
var sortDir = 'desc';
@ -279,13 +279,15 @@
{key: 'reg_date', label: '注册时间', width: '170px'},
{key: 'reg_ip', label: '注册 IP', width: '140px'},
{key: 'ref_by', label: '邀请人', width: '90px'},
{key: 'ref_by_name', label: '邀请人账户', width: '140px', empty: '无'},
{key: 'aff_money', label: '推广返利余额', width: '130px', value: function (item) { return '<strong class="admin-user-money">¥ ' + escapeHtml(item.aff_money || '0.00') + '</strong>'; }},
{key: 'enable', label: '状态', width: '95px', value: function (item) {
var statusClass = isEnabled(item) ? 'is-enabled' : 'is-disabled';
return '<span class="admin-user-status ' + statusClass + '">' + escapeHtml(item.enable || '未知') + '</span>';
}}
];
var defaultVisibleColumns = ['actions','id','user_name','email','money','enable'];
var defaultVisibleColumns = ['actions','id','user_name','email','money','ref_by_name','aff_money','enable'];
var visibleColumnKeys = readVisibleColumns();
function escapeHtml(text) {
@ -372,6 +374,8 @@
reg_date: stripHtml(row.reg_date),
reg_ip: stripHtml(row.reg_ip),
ref_by: stripHtml(row.ref_by),
ref_by_name: stripHtml(row.ref_by_name),
aff_money: stripHtml(row.aff_money),
trusted_login_device_count: parseInt(row.trusted_login_device_count, 10) || 0
};
}

@ -92,6 +92,7 @@
var registerForm = document.getElementById('registerForm');
var registerButton = document.getElementById({if $tos_reg == 'true'}'registerBtn'{else}'reg'{/if});
var affCode = "{$aff_code|default:''|escape:'javascript'}";
var affid = Number("{$aff|escape:'javascript'}");
var emailButton = document.getElementById('email_verify');
var emailButtonText = {if $language == 'true'}'Send code'{else}'发送验证码'{/if};
@ -122,8 +123,8 @@
}
function register() {
if (!Number.isInteger(affid)) {
VenixAuth.showMessage(registerForm, 'error', 'Illegal invitation connection');
if (affCode === '' && !Number.isInteger(affid)) {
VenixAuth.showMessage(registerForm, 'error', '邀请链接无效');
return;
}
@ -143,7 +144,7 @@
VenixAuth.post('/auth/register', {
email: fieldValue('email'),
name: fieldValue('name'),
aff: affid,
aff: affCode || (Number.isInteger(affid) ? affid : ''),
passwd: fieldValue('passwd'),
repasswd: fieldValue('repasswd'),
captch: fieldValue('captch'),

@ -1,6 +1,6 @@
<section id="invoices-workspace">
<div class="page-heading"><div><span class="eyebrow">BILLING</span><h1>账单信息</h1><p>部署实例时先生成开通账单,支付完成后才开始创建;实例到期前 7 天会自动生成续费账单。实例到期后立即停用网络,到期满 3 天仍未续费,实例及系统盘将被永久删除。</p></div><button id="invoices-refresh" class="button button-outline" type="button">刷新</button></div>
<div class="invoice-balance-card"><span>当前账户余额</span><strong id="invoices-balance">{$cloud_invoice_balance|escape:"html"}</strong><a class="button button-outline small" href="/user/code">余额充值</a></div>
<div class="invoice-balance-card"><span>当前账户余额</span><strong id="invoices-balance">{$cloud_invoice_balance|escape:"html"}</strong><button class="button button-outline small" type="button" data-account-drawer-open="balance" data-drawer-title="余额充值" data-drawer-description="选择充值金额和可用支付方式">余额充值</button></div>
<div id="invoices-list" class="inventory-panel cloud-orders cloud-invoices" aria-live="polite">
{if empty($cloud_invoice_rows)}
<p class="muted">暂无账单。部署实例后会先生成开通账单;续费账单会在实例到期前 7 天自动生成。</p>

@ -1,2 +1,2 @@
{* Shared Venix CSS/JS cache key. Increment whenever a shared browser asset changes. *}
{assign var=venix_asset_version value='2026093011' scope='global'}
{assign var=venix_asset_version value='2026093013' scope='global'}

@ -0,0 +1,14 @@
<dialog class="panel-account-drawer" id="panel-account-drawer" aria-labelledby="panel-account-drawer-title" aria-describedby="panel-account-drawer-description">
<header class="panel-account-drawer-header">
<div>
<p class="panel-account-drawer-kicker">账户中心</p>
<h2 id="panel-account-drawer-title">账户设置</h2>
<p id="panel-account-drawer-description">管理双重认证和登录密码。</p>
</div>
<button class="button button-ghost panel-account-drawer-close" id="panel-account-drawer-close" type="button" aria-label="关闭账户抽屉"><i class="mdi mdi-close" aria-hidden="true"></i></button>
</header>
<div class="panel-account-drawer-frame-wrap" aria-busy="false">
<iframe id="panel-account-drawer-frame" title="账户设置" src="about:blank" loading="lazy"></iframe>
</div>
</dialog>
<script type="module" src="/cloud/account-drawer.js?v={$venix_asset_version|escape:'html'}"></script>

@ -1,146 +1,79 @@
{include file='user/layout_header.tpl' vu_title='资料编辑' vu_active='edit'}
<header class="vu-topbar">
<div>
<p class="vu-kicker">账户</p>
<h1>账户设置</h1>
</div>
<div class="vu-top-actions">
<a class="vu-btn" href="/user/cloud/instances"><i class="mdi mdi-arrow-left"></i><span>返回实例</span></a>
</div>
</header>
<section class="vu-edit-hero">
<article class="vu-edit-hero-main">
<span class="vu-status is-live">{$user->user_name|escape:"html"}</span>
<h2>管理账户登录安全</h2>
<p>这些设置会影响账号登录安全。默认使用邮箱验证,绑定谷歌验证器后可手动切换。</p>
</article>
<aside class="vu-edit-summary"><div><span>登录验证</span><strong>{if $login_verify_method == 'ga'}谷歌验证器{else}邮箱验证{/if}</strong></div></aside>
</section>
<section class="vu-edit-layout">
<div class="vu-edit-main">
<article class="vu-card vu-setting-card">
<div class="vu-card-head">
<div>
<p class="vu-kicker">Password</p>
<h2>修改登录密码</h2>
</div>
<i class="mdi mdi-lock-reset vu-card-icon"></i>
</div>
<form class="vu-form" id="vuPasswordForm" autocomplete="off">
<label class="vu-field" for="oldpwd">
<span>当前密码</span>
<input id="oldpwd" class="vu-input" type="password" autocomplete="current-password">
</label>
<div class="vu-form-grid">
<label class="vu-field" for="pwd">
<span>新密码</span>
<input id="pwd" class="vu-input" type="password" autocomplete="new-password">
</label>
<label class="vu-field" for="repwd">
<span>重复新密码</span>
<input id="repwd" class="vu-input" type="password" autocomplete="new-password">
</label>
</div>
<p class="vu-form-message">密码至少 12 位,包含大写、小写字母、数字和符号。</p>
<div class="vu-form-actions">
<button class="vu-btn" id="pwd-update" type="submit"><i class="mdi mdi-content-save-outline"></i><span>保存密码</span></button>
</div>
</form>
</article>
<article class="vu-card vu-setting-card vu-ga-card">
<div class="vu-card-head">
<div>
<p class="vu-kicker">Authenticator</p>
<h2>谷歌验证器</h2>
</div>
<i class="mdi mdi-two-factor-authentication vu-card-icon"></i>
</div>
{if $ga_enabled}
<div class="vu-current-line">
<div>
<span>绑定状态</span>
<strong>已开启</strong>
</div>
<span class="vu-status is-live">保护中</span>
</div>
{include file='user/layout_header.tpl' vu_title='账户设置' vu_active='edit'}
<section class="vu-account-workspace" aria-labelledby="vuAccountTitle">
<header class="vu-account-banner">
<div class="vu-account-banner-copy">
<span class="vu-account-eyebrow">ACCOUNT SECURITY</span>
<h1 id="vuAccountTitle">账户安全</h1>
<p>集中管理登录验证和密码。敏感操作会要求额外的邮箱验证码或动态码。</p>
</div>
<div class="vu-account-banner-meta">
<span class="vu-account-avatar" aria-hidden="true"><i class="mdi mdi-shield-lock-outline"></i></span>
<div><span>当前账户</span><strong>{$user->user_name|escape:'html'}</strong></div>
</div>
</header>
<form class="vu-form vu-security-method-form" id="vuSecurityMethodForm" autocomplete="off">
<label class="vu-field" for="login_verify_method">
<span>登录安全认证</span>
<select id="login_verify_method" class="vu-input">
<option value="email" {if $login_verify_method != 'ga'}selected{/if}>邮箱验证码</option>
<option value="ga" {if $login_verify_method == 'ga'}selected{/if}>谷歌验证器</option>
</select>
</label>
<p class="vu-form-message">默认是邮箱验证;切换为谷歌验证器后,登录时需要输入 App 中的 6 位动态码。</p>
<div class="vu-form-actions">
<button class="vu-btn" id="verify-method-update" type="submit"><i class="mdi mdi-content-save-outline"></i><span>保存验证方式</span></button>
</div>
</form>
<div class="vu-security-stack">
<section class="vu-security-section" aria-labelledby="vuTwoFactorTitle">
<div class="vu-security-section-head">
<span class="vu-security-index">01</span>
<div><span class="vu-account-eyebrow">TWO-FACTOR AUTHENTICATION</span><h2 id="vuTwoFactorTitle">双重认证</h2><p>绑定验证器后,登录及重要账户操作可以使用 6 位动态码保护。</p></div>
<span class="vu-security-state {if $ga_enabled}is-active{else}is-muted{/if}"><i class="mdi {if $ga_enabled}mdi-check-circle-outline{else}mdi-circle-outline{/if}"></i>{if $ga_enabled}已开启{else}未绑定{/if}</span>
</div>
<form class="vu-form vu-ga-disable-form" id="vuGaDisableForm" autocomplete="off">
<label class="vu-field" for="ga_disable_code">
<span>解绑验证</span>
<input id="ga_disable_code" class="vu-input" type="text" inputmode="numeric" autocomplete="one-time-code" maxlength="6" placeholder="输入当前 6 位动态码">
</label>
<div class="vu-form-actions">
<button class="vu-btn vu-btn-ghost" id="ga-disable" type="submit"><i class="mdi mdi-link-variant-off"></i><span>解绑谷歌验证器</span></button>
</div>
</form>
{else}
<div class="vu-ga-setup">
<div class="vu-ga-qr" data-qr-text="{$ga_otpauth_uri|escape:'html'}" aria-label="谷歌验证器二维码"></div>
<div class="vu-ga-setup-body">
<p class="vu-form-message">使用 Google Authenticator、Microsoft Authenticator 或其他兼容 App 扫描二维码;不能扫码时可手动输入下方密钥。</p>
<div class="vu-code-row vu-ga-secret">
<code>{$ga_setup_secret|escape:'html'}</code>
<button class="vu-icon-btn" type="button" data-copy="{$ga_setup_secret|escape:'html'}" aria-label="复制谷歌验证器密钥"><i class="mdi mdi-content-copy"></i></button>
</div>
<form class="vu-form" id="vuGaEnableForm" autocomplete="off">
<input type="hidden" id="ga_secret" value="{$ga_setup_secret|escape:'html'}">
<label class="vu-field" for="ga_code">
<span>动态验证码</span>
<input id="ga_code" class="vu-input" type="text" inputmode="numeric" autocomplete="one-time-code" maxlength="6" placeholder="输入 App 中的 6 位验证码">
</label>
<div class="vu-form-actions">
<button class="vu-btn" id="ga-enable" type="submit"><i class="mdi mdi-shield-key-outline"></i><span>绑定谷歌验证器</span></button>
</div>
</form>
</div>
{if $ga_enabled}
<div class="vu-security-content">
<div class="vu-security-status-card"><i class="mdi mdi-cellphone-key"></i><div><strong>谷歌验证器已绑定</strong><span>可以在登录时使用验证器动态码,也可以在下方切换默认验证方式。</span></div></div>
<form class="vu-form vu-security-form" id="vuSecurityMethodForm" data-csrf-token="{$account_csrf_token|default:''|escape:'html'}" autocomplete="off">
<label class="vu-field" for="login_verify_method"><span>默认登录验证方式</span><select id="login_verify_method" class="vu-input"><option value="email" {if $login_verify_method != 'ga'}selected{/if}>邮箱验证码</option><option value="ga" {if $login_verify_method == 'ga'}selected{/if}>谷歌验证器动态码</option></select></label>
<p class="vu-form-message">切换后下次登录生效;密码修改仍然需要额外的安全验证。</p>
<div class="vu-form-actions"><button class="vu-btn" id="verify-method-update" type="submit"><i class="mdi mdi-content-save-outline"></i><span>保存验证方式</span></button></div>
</form>
<form class="vu-form vu-security-form vu-security-form-danger" id="vuGaDisableForm" data-csrf-token="{$account_csrf_token|default:''|escape:'html'}" autocomplete="off">
<label class="vu-field" for="ga_disable_code"><span>解绑验证器</span><input id="ga_disable_code" class="vu-input" type="text" inputmode="numeric" autocomplete="one-time-code" maxlength="6" placeholder="输入当前 6 位动态码"></label>
<div class="vu-form-actions"><button class="vu-btn vu-btn-ghost" id="ga-disable" type="submit"><i class="mdi mdi-link-variant-off"></i><span>解绑谷歌验证器</span></button></div>
</form>
</div>
{else}
<div class="vu-security-content">
<div class="vu-ga-setup vu-ga-setup-compact">
<div class="vu-ga-qr" data-qr-text="{$ga_otpauth_uri|escape:'html'}" aria-label="谷歌验证器二维码"></div>
<div class="vu-ga-setup-body">
<div class="vu-security-status-card is-muted"><i class="mdi mdi-qrcode-scan"></i><div><strong>扫描二维码完成绑定</strong><span>支持 Google Authenticator、Microsoft Authenticator 等兼容应用。</span></div></div>
<div class="vu-code-row vu-ga-secret"><code>{$ga_setup_secret|escape:'html'}</code><button class="vu-icon-btn" type="button" data-copy="{$ga_setup_secret|escape:'html'}" aria-label="复制谷歌验证器密钥"><i class="mdi mdi-content-copy"></i></button></div>
<form class="vu-form vu-security-form" id="vuGaEnableForm" data-csrf-token="{$account_csrf_token|default:''|escape:'html'}" autocomplete="off">
<input type="hidden" id="ga_secret" value="{$ga_setup_secret|escape:'html'}">
<label class="vu-field" for="ga_code"><span>动态验证码</span><input id="ga_code" class="vu-input" type="text" inputmode="numeric" autocomplete="one-time-code" maxlength="6" placeholder="输入 App 中的 6 位验证码"></label>
<div class="vu-form-actions"><button class="vu-btn" id="ga-enable" type="submit"><i class="mdi mdi-shield-key-outline"></i><span>绑定谷歌验证器</span></button></div>
</form>
</div>
{/if}
</article>
</div>
</div>
{/if}
</section>
<aside class="vu-edit-side">
<article class="vu-card vu-setting-card">
<div class="vu-card-head">
<div>
<p class="vu-kicker">Security</p>
<h2>安全建议</h2>
</div>
<i class="mdi mdi-shield-check-outline vu-card-icon"></i>
</div>
<div class="vu-profile-tips">
<div><i class="mdi mdi-lock-outline"></i><span>定期更新登录密码,避免与其他网站重复使用。</span></div>
<div><i class="mdi mdi-email-check-outline"></i><span>邮箱验证码仍是默认登录安全验证方式。</span></div>
<div><i class="mdi mdi-cellphone-key"></i><span>绑定谷歌验证器后,可以手动切换登录验证方式。</span></div>
<section class="vu-security-section" aria-labelledby="vuPasswordTitle">
<div class="vu-security-section-head">
<span class="vu-security-index">02</span>
<div><span class="vu-account-eyebrow">PASSWORD</span><h2 id="vuPasswordTitle">修改密码</h2><p>更新后当前登录会立即失效,请使用新密码重新登录。</p></div>
<span class="vu-security-state is-muted"><i class="mdi mdi-lock-outline"></i>高强度密码</span>
</div>
<div class="vu-security-content">
<form class="vu-form vu-password-form" id="vuPasswordForm" data-csrf-token="{$account_csrf_token|default:''|escape:'html'}" autocomplete="off">
<label class="vu-field" for="oldpwd"><span>当前密码</span><input id="oldpwd" class="vu-input" type="password" autocomplete="current-password" placeholder="输入当前密码"></label>
<div class="vu-form-grid"><label class="vu-field" for="pwd"><span>新密码</span><input id="pwd" class="vu-input" type="password" autocomplete="new-password" placeholder="12–72 字节,含大小写、数字和符号"></label><label class="vu-field" for="repwd"><span>确认新密码</span><input id="repwd" class="vu-input" type="password" autocomplete="new-password" placeholder="再次输入新密码"></label></div>
<p class="vu-form-message">请至少填写一种安全验证方式。已绑定验证器时,可直接使用动态码。</p>
<div class="vu-password-factor-grid">
<div class="vu-factor-card"><div class="vu-factor-card-head"><i class="mdi mdi-email-check-outline"></i><div><strong>邮箱验证码</strong><span>向账户邮箱发送一次性验证码</span></div></div><div class="vu-password-code-row"><input id="pwd-emailcode" class="vu-input" type="text" inputmode="numeric" autocomplete="one-time-code" maxlength="6" placeholder="6 位验证码"><button class="vu-btn vu-btn-soft" id="pwd-send-email" type="button">获取验证码</button></div></div>
{if $ga_enabled}<div class="vu-factor-card"><div class="vu-factor-card-head"><i class="mdi mdi-cellphone-key"></i><div><strong>谷歌动态码</strong><span>使用验证器 App 中的当前验证码</span></div></div><input id="pwd-gacode" class="vu-input" type="text" inputmode="numeric" autocomplete="one-time-code" maxlength="6" placeholder="6 位动态码"></div>{/if}
</div>
</article>
</aside>
<div class="vu-form-actions"><button class="vu-btn" id="pwd-update" type="submit"><i class="mdi mdi-lock-reset"></i><span>保存新密码</span></button></div>
</form>
</div>
</section>
</div>
</section>
{include file='user/layout_footer.tpl'}
{include file='user/layout_modal.tpl'}
{include file='user/layout_scripts.tpl'}
</body>
</html>

@ -1,8 +1,8 @@
{include file='user/layout_header.tpl' vu_title='邀请返利' vu_active='invite'}
{include file='user/layout_header.tpl' vu_title='推广' vu_active='invite'}
<header class="vu-topbar">
<div>
<p class="vu-kicker">分销中心</p>
<h1>邀请返利</h1>
<p class="vu-kicker">推广中心</p>
<h1>推广</h1>
</div>
<div class="vu-top-actions">
<a class="vu-btn vu-btn-ghost" href="/user/cloud/deploy"><i class="mdi mdi-cart-outline"></i><span>购买云服务器</span></a>
@ -12,26 +12,26 @@
<section class="vu-invite-hero">
<article class="vu-invite-hero-main">
<span class="vu-status is-live">返利 {$user->aff_rate}%</span>
<h2>分享邀请链接,获得好友充值返利</h2>
<p>每邀请一位用户注册,对方在两年内充值时,你会按当前返利比例获得佣金。邀请链接请勿发布到公共群组或公开平台。</p>
<span class="vu-status is-live">返利 {$referral_rate}%</span>
<h2>分享推广链接,获得好友消费返利</h2>
<p>好友通过推广链接注册后,{$referral_days} 天内的符合条件充值会按当前比例计入返利。推广链接请勿发布到公共群组或公开平台。</p>
<div class="vu-code-row vu-invite-link">
{if $invite_restricted}
<code>邀请服务暂时无法使用,请稍后再试。</code>
<code>推广服务暂时无法使用,请稍后再试。</code>
{elseif !$invite_enabled}
<code>邀请功能暂不可用</code>
<code>推广功能暂不可用</code>
{elseif $invite_link != ''}
<code id="aff_link">{$invite_link|escape:"html"}</code>
<button class="vu-icon-btn" data-copy="{$invite_link|escape:"html"}" aria-label="复制邀请链接"><i class="mdi mdi-content-copy"></i></button>
<button class="vu-icon-btn" data-copy="{$invite_link|escape:"html"}" aria-label="复制推广链接"><i class="mdi mdi-content-copy"></i></button>
{else}
<code>尚未生成邀请码</code>
<code>尚未生成推广链接</code>
{/if}
</div>
<div class="vu-invite-actions">
{if $invite_enabled && $aff_method == 'code' && !$has_invite_code}
<button class="vu-btn vu-btn-soft" id="invite" type="button"><i class="mdi mdi-ticket-confirmation-outline"></i><span>生成邀请码</span></button>
<button class="vu-btn vu-btn-soft" id="invite" type="button"><i class="mdi mdi-ticket-confirmation-outline"></i><span>生成推广链接</span></button>
{elseif $invite_enabled && $aff_method == 'code'}
<button class="vu-btn vu-btn-ghost" id="resetiv" type="button"><i class="mdi mdi-refresh"></i><span>重置邀请码</span></button>
<button class="vu-btn vu-btn-ghost" id="resetiv" type="button"><i class="mdi mdi-refresh"></i><span>重置推广链接</span></button>
{/if}
</div>
</article>
@ -50,7 +50,7 @@
<b>¥ {$user->inviteMoneyTotal()}</b>
</div>
<div>
<small>已邀请</small>
<small>已推广用户</small>
<b>{$user->invitedMemberTotal()} 人</b>
</div>
</div>
@ -64,7 +64,7 @@
<section class="vu-stat-grid vu-invite-stats">
<article class="vu-stat">
<span>返利比例</span>
<strong>{$user->aff_rate}%</strong>
<strong>{$referral_rate}%</strong>
<button class="panel-announcements-link" type="button" data-announcements-open aria-haspopup="dialog" aria-controls="panel-announcements-drawer" aria-expanded="false">查看规则</button>
</article>
<article class="vu-stat">
@ -73,13 +73,13 @@
<a href="#invite-wallet">处理返利</a>
</article>
<article class="vu-stat">
<span>已邀请</span>
<span>已推广用户</span>
<strong>{$user->invitedMemberTotal()}</strong>
<a href="#invite-records">返利记录</a>
</article>
<article class="vu-stat">
<span>邀请方式</span>
<strong>{if $aff_method == 'code'}邀请码{else}邀请链接{/if}</strong>
<span>推广方式</span>
<strong>{if $aff_method == 'code'}推广代码{else}推广链接{/if}</strong>
{if $aff_method == 'code'}<a href="javascript:void(0)">剩余 {$user->invite_num} 次</a>{else}<a href="javascript:void(0)">自动绑定</a>{/if}
</article>
</section>
@ -121,7 +121,7 @@
<div class="vu-card-head">
<div>
<p class="vu-kicker">Records</p>
<h2>返利记录</h2>
<h2>推广返利记录</h2>
</div>
<i class="mdi mdi-receipt-text-clock-outline vu-card-icon"></i>
</div>
@ -129,7 +129,7 @@
<div class="vu-empty-state">
<i class="mdi mdi-account-cash-outline"></i>
<strong>暂无返利记录</strong>
<span>好友完成充值后,返利记录会显示在这里。</span>
<span>好友完成符合条件的消费后,返利记录会显示在这里。</span>
</div>
{else}
<div class="vu-table-wrap">
@ -171,13 +171,13 @@
<div class="vu-card-head">
<div>
<p class="vu-kicker">Tips</p>
<h2>邀请说明</h2>
<h2>推广说明</h2>
</div>
<i class="mdi mdi-information-outline vu-card-icon"></i>
</div>
<div class="vu-profile-tips">
<div><i class="mdi mdi-link-variant"></i><span>邀请链接只建议发送给可信好友,避免发布到公开平台。</span></div>
<div><i class="mdi mdi-percent-outline"></i><span>当前返利比例为 {$user->aff_rate}%,好友充值后会计入返利记录。</span></div>
<div><i class="mdi mdi-link-variant"></i><span>推广链接只建议发送给可信好友,避免发布到公开平台。</span></div>
<div><i class="mdi mdi-percent-outline"></i><span>当前返利比例为 {$referral_rate}%,好友注册 {$referral_days} 天内的充值会计入返利记录。</span></div>
<div><i class="mdi mdi-cash-check"></i><span>返利余额可以转入账户余额;提现只支持 USDT。</span></div>
</div>
</article>

@ -8,6 +8,7 @@
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="theme-color" content="#f4f7fb">
<meta name="account-csrf-token" content="{$account_csrf_token|default:''|escape:'html'}">
<title>{if $vu_page_title != ''}{$vu_page_title|escape:"html"} | {/if}{$config["appName"]|escape:"html"}</title>
<link rel="shortcut icon" href="/theme/venix/images/favicon.ico" type="image/x-icon">
<link href="{$cdn}/theme/venix/css/icons.min.css?v={$vu_asset_version}" rel="stylesheet">
@ -15,7 +16,7 @@
<link href="/cloud/client.css?v={$vu_asset_version}" rel="stylesheet">
<link href="/cloud/account.css?v={$vu_asset_version}" rel="stylesheet">
</head>
<body class="vu-body">
<body class="vu-body{if !empty($smarty.get.drawer)} vu-embedded{/if}">
<div class="dashboard user-dashboard">
{include file='user/panel_sidebar.tpl' panel_active=$vu_active_key panel_cloud_page=0}
<div class="main-area">

@ -3,7 +3,7 @@
{assign var=vu_has_ticket_page value=$vu_ticket_page|default:0}
<script>window.VU_HOME = { jumpDelay: {$config['jump_delay']|default:1000}, pageTitle: '{$config["appName"]|escape:"javascript"}' };</script>
{if $vu_active_key|default:'' == 'edit'}<script src="{$cdn}/theme/venix/js/qrcode.min.js?v={$vu_asset_version}"></script>{/if}
{if $vu_active_key|default:'' == 'edit' || $vu_qrcode|default:false}<script src="{$cdn}/theme/venix/js/qrcode.min.js?v={$vu_asset_version}"></script>{/if}
<script src="/theme/venix/js/user-home.js?v={$vu_asset_version}"></script>
{if $vu_has_shop_page}<script src="{$cdn}/theme/venix/js/shop-page.js?v={$vu_asset_version}"></script>{/if}
{if $vu_has_ticket_page}<script src="{$cdn}/theme/venix/js/ticket-page.js?v={$vu_asset_version}"></script>{/if}

@ -32,17 +32,8 @@
<i class="mdi mdi-file-document-outline nav-icon" aria-hidden="true"></i><span>账单信息</span>
</a>
<div class="sidebar-section-label">账户与支持</div>
<a class="sidebar-link{if $panel_active_key == 'code'} active{/if}" href="/user/code">
<i class="mdi mdi-wallet-plus-outline nav-icon" aria-hidden="true"></i><span>余额充值</span>
</a>
<a class="sidebar-link{if $panel_active_key == 'invite'} active{/if}" href="/user/invite">
<i class="mdi mdi-account-multiple-plus-outline nav-icon" aria-hidden="true"></i><span>邀请返利</span>
</a>
<a class="sidebar-link{if $panel_active_key == 'edit'} active{/if}" href="/user/edit">
<i class="mdi mdi-shield-account-outline nav-icon" aria-hidden="true"></i><span>账户设置</span>
</a>
{if !empty($ticket_navigation_enabled)}
<div class="sidebar-section-label">支持</div>
<a class="sidebar-link{if $panel_active_key == 'ticket'} active{/if}" href="/user/ticket">
<i class="mdi mdi-lifebuoy nav-icon" aria-hidden="true"></i><span>工单支持</span>
</a>

@ -3,7 +3,18 @@
<div class="breadcrumb">用户中心 <span>/</span><strong{if $panel_cloud_mode} id="breadcrumb-current"{/if}>{$panel_title|default:'账户'|escape:"html"}</strong></div>
<div class="topbar-right">
<button class="button button-ghost panel-announcements-trigger" type="button" data-announcements-open aria-haspopup="dialog" aria-controls="panel-announcements-drawer" aria-expanded="false" aria-label="查看公告与维护信息" title="公告与维护信息"><i class="mdi mdi-bullhorn-outline" aria-hidden="true"></i></button>
<span class="topbar-user"><span class="avatar">U</span><span{if $panel_cloud_mode} id="current-username"{/if}>{$user->user_name|default:'账户'|escape:"html"}</span></span>
<details class="panel-user-menu">
<summary class="topbar-user" aria-label="打开账户菜单" aria-haspopup="menu" aria-expanded="false">
<span class="avatar">U</span>
<span{if $panel_cloud_mode} id="current-username"{/if}>{$user->user_name|default:'账户'|escape:"html"}</span>
<i class="mdi mdi-chevron-down panel-user-menu-chevron" aria-hidden="true"></i>
</summary>
<div class="panel-user-menu-options" role="menu" aria-label="账户菜单">
<button type="button" role="menuitem" data-account-drawer-open="account" data-drawer-title="账户设置" data-drawer-description="管理双重认证和登录密码"><i class="mdi mdi-shield-account-outline" aria-hidden="true"></i><span>账户设置</span></button>
<button type="button" role="menuitem" data-account-drawer-open="balance" data-drawer-title="余额充值" data-drawer-description="选择充值金额和可用支付方式"><i class="mdi mdi-wallet-plus-outline" aria-hidden="true"></i><span>余额充值</span></button>
<button type="button" role="menuitem" data-account-drawer-open="promotion" data-drawer-title="推广" data-drawer-description="分享邀请链接并查看推广返利"><i class="mdi mdi-account-multiple-plus-outline" aria-hidden="true"></i><span>推广</span></button>
</div>
</details>
{if $panel_cloud_mode}
<button id="logout-button" class="button button-ghost small" type="button">退出登录</button>
{else}
@ -12,3 +23,4 @@
</div>
</header>
{include file='user/announcement_drawer.tpl'}
{include file='user/account_drawer.tpl'}

@ -5,7 +5,7 @@
<h1>充值结果</h1>
</div>
<div class="vu-top-actions">
<a class="vu-btn vu-btn-ghost" href="/user/code"><i class="mdi mdi-wallet-outline"></i><span>{if $transaction_records_visible}充值记录{else}返回充值{/if}</span></a>
<button class="vu-btn vu-btn-ghost" type="button" data-account-drawer-open="balance" data-drawer-title="余额充值" data-drawer-description="选择充值金额和可用支付方式"><i class="mdi mdi-wallet-outline"></i><span>{if $transaction_records_visible}充值记录{else}返回充值{/if}</span></button>
<a class="vu-btn" href="/user/cloud/deploy"><i class="mdi mdi-cart-outline"></i><span>购买套餐</span></a>
</div>
</header>

@ -1,483 +1,60 @@
{include file='user/layout_header.tpl' vu_title='账户充值' vu_active='code'}
<header class="vu-topbar">
<div>
<p class="vu-kicker">钱包</p>
<h1>账户充值</h1>
</div>
<div class="vu-top-actions">
<a class="vu-btn vu-btn-ghost" href="/user/cloud/deploy"><i class="mdi mdi-cart-outline"></i><span>购买套餐</span></a>
<a class="vu-btn" href="/user/cloud/instances"><i class="mdi mdi-arrow-left"></i><span>返回实例</span></a>
</div>
</header>
<section class="vu-pay-hero">
<article class="vu-pay-hero-main">
<span class="vu-status is-live">余额充值</span>
<h2>账户余额充值</h2>
<p>请选择充值金额并完成扫码支付。支付成功后余额通常会自动入账,若长时间未到账请联系站内客服。</p>
</article>
<aside class="vu-pay-balance">
<span>当前余额</span>
<strong id="vuCurrentBalance">¥ {$user->money}</strong>
<a class="vu-btn vu-btn-soft" href="/user/cloud/deploy"><i class="mdi mdi-package-variant-closed"></i><span>去选套餐</span></a>
</aside>
<section class="vu-recharge-workspace" aria-labelledby="vuRechargeTitle">
<header class="vu-recharge-banner">
<div class="vu-recharge-banner-copy"><span class="vu-account-eyebrow">WALLET</span><h1 id="vuRechargeTitle">账户充值</h1><p>输入充值金额后,系统会自动筛选当前可用的支付方式。支付成功后余额将自动入账。</p></div>
<div class="vu-recharge-balance"><span>当前余额</span><strong id="vuCurrentBalance">¥ {$user->money}</strong><a href="/user/cloud/deploy" target="_top" class="vu-btn vu-btn-soft"><i class="mdi mdi-package-variant-closed"></i><span>去选套餐</span></a></div>
</header>
<div class="vu-recharge-stack">
<section class="vu-recharge-card" aria-labelledby="vuRechargeFormTitle">
<div class="vu-recharge-card-head"><div><span class="vu-account-eyebrow">RECHARGE</span><h2 id="vuRechargeFormTitle">选择充值方式</h2></div><span class="vu-recharge-card-icon"><i class="mdi mdi-credit-card-plus-outline"></i></span></div>
{if $recharge_restricted}
<div class="vu-empty-state vu-recharge-empty"><i class="mdi mdi-clock-alert-outline"></i><strong>充值服务暂时无法使用</strong><span>当前账户暂不满足充值条件,请稍后再试。</span></div>
{else}
<form class="vu-form vu-recharge-form" id="vuPayForm" data-csrf-token="{$account_csrf_token|default:''|escape:'html'}" autocomplete="off">
<label class="vu-field" for="price"><span>充值金额</span><div class="vu-amount-field"><span>¥</span><input class="vu-input" id="price" name="price" type="number" min="0.01" step="0.01" inputmode="decimal" placeholder="请输入充值金额" aria-describedby="vuRechargeHint"></div></label>
<p class="vu-form-message" id="vuRechargeHint">先填写充值金额,系统会显示可用的支付方式。</p>
<div class="vu-pay-methods vu-recharge-methods" id="vuRechargeMethods" hidden aria-live="polite"></div>
</form>
{/if}
</section>
<section class="vu-pay-layout">
<div class="vu-pay-main">
<article class="vu-card vu-pay-card">
<div class="vu-card-head">
<div>
<p class="vu-kicker">Recharge</p>
<h2>在线充值</h2>
</div>
<i class="mdi mdi-credit-card-plus-outline vu-card-icon"></i>
</div>
<form class="vu-form" id="vuPayForm">
{if $recharge_restricted}
<div class="vu-empty-state">
<i class="mdi mdi-clock-alert-outline"></i>
<strong>充值服务暂时无法使用</strong>
<span>请稍后再试。</span>
</div>
{else}
<label class="vu-field" for="price">
<span>充值金额</span>
<input class="vu-input" id="price" name="price" type="number" min="0.01" step="0.01" inputmode="decimal" placeholder="请输入充值金额">
</label>
{if $paytaro_enabled || $usdt_enabled || $yipay_alipay_enabled || $yipay_wxpay_enabled}
<div class="vu-pay-methods">
{if $paytaro_enabled}
<button class="vu-btn" id="pay-paytaro" type="button" data-pay-type="paytaro" data-create-url="/user/paytaro/order" data-status-url="/user/paytaro/status"><i class="mdi mdi-qrcode-scan"></i><span>支付宝</span></button>
{/if}
{if $yipay_alipay_enabled}
<button class="vu-btn" id="pay-yipay-alipay" type="button" data-pay-type="yipay" data-pay-method="alipay" data-create-url="/user/yipay/order" data-status-url="/user/yipay/status"><i class="mdi mdi-credit-card-check"></i><span>支付宝充值</span></button>
{/if}
{if $yipay_wxpay_enabled}
<button class="vu-btn vu-btn-soft" id="pay-yipay-wxpay" type="button" data-pay-type="yipay" data-pay-method="wxpay" data-create-url="/user/yipay/order" data-status-url="/user/yipay/status"><i class="mdi mdi-wechat"></i><span>微信支付</span></button>
{/if}
{if $usdt_enabled}
<button class="vu-btn vu-btn-soft" id="pay-usdt" type="button" data-pay-type="usdt" data-create-url="/user/usdt/order" data-status-url="/user/usdt/status"><i class="mdi mdi-currency-usd"></i><span>USDT 充值</span></button>
{/if}
</div>
{else}
<p class="vu-form-message">当前暂无可用在线充值方式。</p>
{/if}
{/if}
</form>
</article>
{if !$transaction_records_restricted}
<article class="vu-card vu-pay-card">
<div class="vu-card-head">
<div>
<p class="vu-kicker">History</p>
<h2>充值记录</h2>
</div>
<i class="mdi mdi-receipt-text-clock-outline vu-card-icon"></i>
</div>
<div class="vu-table-wrap">
<table class="vu-data-table vu-pay-table">
<thead>
<tr>
<th>充值代码</th>
<th>类型</th>
<th>内容</th>
<th>状态</th>
<th>时间</th>
</tr>
</thead>
<tbody>
{if $codes->isEmpty()}
<tr>
<td colspan="5">
<div class="vu-empty-state">
<i class="mdi mdi-receipt-text-remove-outline"></i>
<strong>暂无充值记录</strong>
<span>完成第一笔充值后,记录会显示在这里。</span>
</div>
</td>
</tr>
{else}
{foreach $codes as $code}
{if $code->type!=-2}
<tr>
<td>
<div class="vu-pay-code">
<code>{$code->display_code|default:'--'|escape:'html'}</code>
{if $code->display_code != ''}
<button class="vu-icon-btn" type="button" data-copy="{$code->display_code|escape:'html'}" aria-label="复制充值代码">
<i class="mdi mdi-content-copy"></i>
</button>
{/if}
</div>
</td>
<td>
{if $code->type==-1}余额充值{/if}
{if $code->type==10003}账户充值{/if}
{if $code->type==10004}金额充值{/if}
{if $code->type==10005}余额充值{/if}
{if $code->type==10006}USDT 充值{/if}
{if $code->type==10007}在线充值{/if}
</td>
<td>
<strong>
{if $code->type==-1 || $code->type==10003 || $code->type==10004 || $code->type==10005 || $code->type==10006 || $code->type==10007}
¥ {$code->number}
{/if}
</strong>
</td>
<td><span class="vu-pill">成功</span></td>
<td>{$code->usedatetime}</td>
</tr>
{/if}
{/foreach}
{/if}
</tbody>
</table>
</div>
<div class="vu-table-footer">
<span>共 {$codes->total()} 条充值记录</span>
<div class="vu-pagination-wrap">{$codes->links()}</div>
</div>
</article>
{/if}
</div>
<aside class="vu-pay-side">
<article class="vu-card vu-pay-card">
<div class="vu-card-head">
<div>
<p class="vu-kicker">Tips</p>
<h2>充值说明</h2>
</div>
<i class="mdi mdi-information-outline vu-card-icon"></i>
</div>
<div class="vu-profile-tips">
<div><i class="mdi mdi-timer-sand"></i><span>扫码支付后请等待页面自动确认,避免重复发起订单。</span></div>
<div><i class="mdi mdi-shield-check-outline"></i><span>请核对支付金额,付款完成后余额会按订单金额入账。</span></div>
<div><i class="mdi mdi-lifebuoy"></i><span>{if !empty($ticket_navigation_enabled)}如遇到账延迟,请保留支付记录并提交工单。{else}如遇到账延迟,请保留支付记录并稍后重试。{/if}</span></div>
</div>
</article>
</aside>
<section class="vu-recharge-card vu-recharge-notes" aria-labelledby="vuRechargeNotesTitle">
<div class="vu-recharge-card-head"><div><span class="vu-account-eyebrow">HOW IT WORKS</span><h2 id="vuRechargeNotesTitle">充值说明</h2></div><span class="vu-recharge-card-icon is-soft"><i class="mdi mdi-information-outline"></i></span></div>
<div class="vu-recharge-tip-list"><div><i class="mdi mdi-timer-sand"></i><span>扫码或打开支付链接后请等待系统确认,避免重复创建订单。</span></div><div><i class="mdi mdi-shield-check-outline"></i><span>请核对支付金额和收款网络,付款完成后余额会按订单金额入账。</span></div><div><i class="mdi mdi-lifebuoy"></i><span>{if !empty($ticket_navigation_enabled)}如遇到账延迟,请保留支付记录并提交工单。{else}如遇到账延迟,请保留支付记录并稍后重试。{/if}</span></div></div>
</section>
</div>
{if !$transaction_records_restricted}
<section class="vu-recharge-card vu-recharge-history" aria-labelledby="vuRechargeHistoryTitle">
<div class="vu-recharge-card-head"><div><span class="vu-account-eyebrow">HISTORY</span><h2 id="vuRechargeHistoryTitle">充值记录</h2></div><span class="vu-recharge-card-icon is-soft"><i class="mdi mdi-receipt-text-clock-outline"></i></span></div>
<div class="vu-table-wrap"><table class="vu-data-table vu-pay-table"><thead><tr><th>充值代码</th><th>类型</th><th>金额</th><th>状态</th><th>时间</th></tr></thead><tbody>
{if $codes->isEmpty()}
<tr><td colspan="5"><div class="vu-empty-state"><i class="mdi mdi-receipt-text-remove-outline"></i><strong>暂无充值记录</strong><span>完成第一笔充值后,记录会显示在这里。</span></div></td></tr>
{else}
{foreach $codes as $code}
{if $code->type!=-2}
<tr><td><div class="vu-pay-code"><code>{$code->display_code|default:'--'|escape:'html'}</code>{if $code->display_code != ''}<button class="vu-icon-btn" type="button" data-copy="{$code->display_code|escape:'html'}" aria-label="复制充值代码"><i class="mdi mdi-content-copy"></i></button>{/if}</div></td><td>{if $code->type==-1 || $code->type==10003 || $code->type==10004 || $code->type==10005}余额充值{elseif $code->type==10006}USDT 充值{elseif $code->type==10007}在线充值{else}充值{/if}</td><td><strong>¥ {$code->number}</strong></td><td><span class="vu-pill">成功</span></td><td>{$code->usedatetime}</td></tr>
{/if}
{/foreach}
{/if}
</tbody></table></div><div class="vu-table-footer"><span>共 {$codes->total()} 条充值记录</span><div class="vu-pagination-wrap">{$codes->links()}</div></div>
</section>
{/if}
</section>
{include file='user/layout_footer.tpl'}
<div class="vu-pay-dialog" id="vuPayDialog" aria-hidden="true" hidden>
<div class="vu-pay-dialog-backdrop" data-pay-close></div>
<div class="vu-pay-dialog-panel" role="dialog" aria-modal="true" aria-labelledby="vuPayTitle">
<button class="vu-modal-close" type="button" data-pay-close aria-label="关闭"><i class="mdi mdi-close"></i></button>
<div class="vu-modal-mark"><i class="mdi mdi-qrcode-scan"></i></div>
<h2 id="vuPayTitle">扫码支付</h2>
<p id="vuPayInfo">请使用对应客户端完成支付。</p>
<div class="vu-pay-qrcode" id="qrcode"></div>
<div class="vu-pay-chain-details" id="vuPayChainDetails" hidden>
<div class="vu-pay-chain-summary">
<span><small>支付网络</small><strong id="vuPayNetwork">--</strong></span>
<span><small>应付数量</small><strong id="vuPayAmount">--</strong></span>
</div>
<div class="vu-pay-address">
<small>USDT 收款地址</small>
<div>
<code id="vuPayAddress">--</code>
<button class="vu-icon-btn" id="vuPayAddressCopy" type="button" aria-label="复制 USDT 收款地址"><i class="mdi mdi-content-copy"></i></button>
</div>
</div>
</div>
<div class="vu-modal-mark"><i class="mdi mdi-qrcode-scan"></i></div><h2 id="vuPayTitle">扫码支付</h2><p id="vuPayInfo">请使用对应客户端完成支付。</p><div class="vu-pay-qrcode" id="qrcode"></div>
<div class="vu-pay-chain-details" id="vuPayChainDetails" hidden><div class="vu-pay-chain-summary"><span><small>支付网络</small><strong id="vuPayNetwork">--</strong></span><span><small>应付数量</small><strong id="vuPayAmount">--</strong></span></div><div class="vu-pay-address"><small>USDT 收款地址</small><div><code id="vuPayAddress">--</code><button class="vu-icon-btn" id="vuPayAddressCopy" type="button" aria-label="复制 USDT 收款地址"><i class="mdi mdi-content-copy"></i></button></div></div></div>
<a class="vu-btn vu-btn-soft" id="vuPayOpen" href="#" target="_blank" rel="noopener"><i class="mdi mdi-open-in-new"></i><span id="vuPayOpenLabel">打开支付链接</span></a>
</div>
</div>
{include file='user/layout_modal.tpl'}
{include file='user/layout_scripts.tpl' vu_qrcode=1}
<script>
(function () {
"use strict";
var payTimer = null;
var payDialog = document.getElementById("vuPayDialog");
var payTitle = document.getElementById("vuPayTitle");
var payInfo = document.getElementById("vuPayInfo");
var payOpen = document.getElementById("vuPayOpen");
var payOpenLabel = document.getElementById("vuPayOpenLabel");
var qrcodeBox = document.getElementById("qrcode");
var chainDetails = document.getElementById("vuPayChainDetails");
var payNetwork = document.getElementById("vuPayNetwork");
var payAmount = document.getElementById("vuPayAmount");
var payAddress = document.getElementById("vuPayAddress");
var payAddressCopy = document.getElementById("vuPayAddressCopy");
var currentBalance = document.getElementById("vuCurrentBalance");
function qs(selector) {
return document.querySelector(selector);
}
function qsa(selector) {
return Array.prototype.slice.call(document.querySelectorAll(selector));
}
function alertPay(message, type, title) {
if (window.VuModal && window.VuModal.alert) {
return window.VuModal.alert(message, type || "success", title);
}
window.alert(message);
return Promise.resolve();
}
function clearPaymentReturnParams() {
if (!window.history || !window.history.replaceState) return;
var url = new URL(window.location.href);
url.searchParams.delete("payment");
url.searchParams.delete("pid");
window.history.replaceState(null, "", url.pathname + (url.search ? url.search : "") + url.hash);
}
function encoded(data) {
return new URLSearchParams(data || {}).toString();
}
function postForm(url, data) {
return fetch(url, {
method: "POST",
credentials: "same-origin",
headers: {
"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
"X-Requested-With": "XMLHttpRequest"
},
body: encoded(data)
}).then(function (response) {
return response.json().then(function (data) {
if (!response.ok) throw new Error(data.msg || ("HTTP " + response.status));
return data;
});
});
}
function isMobileDevice() {
return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent || "");
}
function isPaytaroMobileDevice() {
if (isMobileDevice()) return true;
if (navigator.userAgentData && navigator.userAgentData.mobile) return true;
return Boolean(window.matchMedia && window.matchMedia("(pointer: coarse) and (hover: none)").matches);
}
function alipayAppUrl(payurl) {
return "alipays://platformapi/startapp?appId=20000067&url=" + encodeURIComponent(String(payurl || ""));
}
function paytaroMobileUrl(payurl) {
payurl = String(payurl || "");
try {
var url = new URL(payurl);
var host = String(url.hostname || "").toLowerCase();
if (host === "mclient.alipay.com" || url.searchParams.get("method") === "alipay.trade.wap.pay") {
return payurl;
}
} catch (error) {
return "";
}
return alipayAppUrl(payurl);
}
function renderPaymentQr(container, content, fallbackUrl) {
container.innerHTML = "";
try {
if (!window.QRCode) throw new Error("QRCode library unavailable");
var levels = window.QRCode.CorrectLevel || { L: 1, M: 0 };
new QRCode(container, {
text: content,
width: 220,
height: 220,
correctLevel: content.length > 1200 ? levels.L : levels.M
});
if (!container.children.length) throw new Error("QRCode output missing");
return true;
} catch (error) {
container.innerHTML = "";
if (fallbackUrl) {
var link = document.createElement("a");
link.className = "vu-text-link";
link.href = fallbackUrl;
link.target = "_blank";
link.rel = "noopener";
link.textContent = "打开支付宝支付";
container.appendChild(link);
} else {
var code = document.createElement("code");
code.textContent = content;
container.appendChild(code);
}
return false;
}
}
function closePayDialog() {
if (payTimer) {
clearInterval(payTimer);
payTimer = null;
}
if (!payDialog) return;
payDialog.classList.remove("is-open");
payDialog.setAttribute("aria-hidden", "true");
payDialog.setAttribute("hidden", "hidden");
document.body.classList.remove("vu-modal-lock");
}
function openPayDialog(data) {
if (!payDialog || !qrcodeBox || !payInfo || !payOpen) return false;
var isUsdt = data.payment_type === "usdt";
var qrContent = isUsdt ? String(data.receive_address || "") : String(data.url || "");
if (!qrContent) {
alertPay(isUsdt ? "系统没有返回有效收款地址。" : "支付网关没有返回有效支付链接。", "error", "创建订单失败");
return false;
}
if (payTitle) payTitle.textContent = isUsdt ? "USDT 扫码支付" : (data.payment_label || "扫码支付");
payInfo.textContent = isUsdt
? "请按下方网络和数量完成转账,支付数量必须完全一致。"
: "订单金额:¥ " + data.amount + ",请扫码完成支付。";
var checkoutLinkEnabled = data.payment_type !== "paytaro"
&& (!isUsdt || (data.checkout_link_enabled === true && Boolean(data.url)));
payOpen.hidden = !checkoutLinkEnabled;
if (checkoutLinkEnabled) {
payOpen.setAttribute("href", data.url);
} else {
payOpen.removeAttribute("href");
}
if (payOpenLabel) payOpenLabel.textContent = isUsdt ? "打开收银台" : "打开支付链接";
if (chainDetails) chainDetails.hidden = !isUsdt;
if (isUsdt) {
var network = String(data.network || "").toLowerCase();
var token = String(data.token || "USDT").toUpperCase();
if (payNetwork) payNetwork.textContent = network === "tron" && token === "USDT" ? "TRON (TRC20)" : network.toUpperCase();
if (payAmount) payAmount.textContent = data.actual_amount + " " + String(data.token || "USDT").toUpperCase();
if (payAddress) payAddress.textContent = qrContent;
if (payAddressCopy) payAddressCopy.setAttribute("data-copy", qrContent);
} else if (payAddressCopy) {
payAddressCopy.removeAttribute("data-copy");
}
renderPaymentQr(qrcodeBox, qrContent, isUsdt ? "" : data.url);
payDialog.removeAttribute("hidden");
payDialog.classList.add("is-open");
payDialog.setAttribute("aria-hidden", "false");
document.body.classList.add("vu-modal-lock");
return true;
}
function checkPayStatus(statusUrl) {
postForm(statusUrl, {}).then(function (data) {
if (String(data.result) === "1") {
closePayDialog();
if (currentBalance && data.balance !== null && typeof data.balance !== "undefined") {
currentBalance.textContent = "¥ " + data.balance;
}
alertPay("支付成功,余额已入账。", "success", "账户充值").then(function () {
clearPaymentReturnParams();
window.location.reload();
});
return;
}
if (data.status === "expired" || data.status === "failed") {
closePayDialog();
alertPay(data.status === "expired" ? "订单已过期,请重新发起充值。" : "订单处理失败,请重新发起充值。", "error", "支付未完成");
}
}).catch(function () {
return;
});
}
function createPay(button) {
var input = qs("#price");
var price = input ? parseFloat(input.value) : 0;
var type = button.getAttribute("data-pay-type");
var method = button.getAttribute("data-pay-method") || "";
var createUrl = button.getAttribute("data-create-url");
var statusUrl = button.getAttribute("data-status-url");
if (payTimer) {
clearInterval(payTimer);
payTimer = null;
}
if (Number.isNaN(price) || price <= 0) {
alertPay("请填写正确的充值金额。", "error", "金额错误");
return;
}
qsa("[data-pay-type]").forEach(function (button) {
button.disabled = true;
});
postForm(createUrl, { price: price, type: type, method: method }).then(function (data) {
qsa("[data-pay-type]").forEach(function (button) {
button.disabled = false;
});
if (Number(data.code) !== 0) {
alertPay(data.errmsg || data.msg || "支付网关处理失败。", "error", "创建订单失败");
return;
}
data.payment_type = type;
if (type === "paytaro" && isPaytaroMobileDevice()) {
payTimer = window.setInterval(function () {
checkPayStatus(data.status_url || statusUrl);
}, Number(data.poll_interval) || 1000);
var mobileUrl = paytaroMobileUrl(data.url);
if (!mobileUrl) {
openPayDialog(data);
return;
}
window.location.assign(mobileUrl);
return;
}
if (type !== "usdt" && isMobileDevice()) {
window.location.href = data.url;
return;
}
if (!openPayDialog(data)) return;
payTimer = window.setInterval(function () {
checkPayStatus(data.status_url || statusUrl);
}, Number(data.poll_interval) || 1000);
}).catch(function (error) {
qsa("[data-pay-type]").forEach(function (button) {
button.disabled = false;
});
alertPay(error.message || "发生了错误。", "error", "请求失败");
});
}
qsa("[data-pay-type]").forEach(function (button) {
button.addEventListener("click", function () {
createPay(button);
});
});
qsa("[data-pay-close]").forEach(function (item) {
item.addEventListener("click", closePayDialog);
});
var returnParams = new URLSearchParams(window.location.search);
if (returnParams.get("payment") === "yipay") {
checkPayStatus("/user/yipay/status");
payTimer = window.setInterval(function () {
checkPayStatus("/user/yipay/status");
}, 3000);
} else if (returnParams.get("payment") === "paytaro") {
checkPayStatus("/user/paytaro/status");
payTimer = window.setInterval(function () {
checkPayStatus("/user/paytaro/status");
}, 3000);
}
})();
</script>
<script src="/theme/venix/js/recharge.js?v={$vu_asset_version}"></script>
</body>
</html>

@ -0,0 +1,13 @@
-- Import once for existing installations before enabling promotion links.
-- New promotion links use an eight-character case-sensitive code in
-- ss_invite_code.code; the index keeps registration lookups bounded.
CREATE TABLE IF NOT EXISTS `referral_code_generation_locks` (
`id` tinyint unsigned NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;
INSERT IGNORE INTO `referral_code_generation_locks` (`id`) VALUES (1);
ALTER TABLE `ss_invite_code`
MODIFY `code` varchar(128) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL,
ADD KEY IF NOT EXISTS `idx_ss_invite_code_code` (`code`);

@ -234,12 +234,19 @@ CREATE TABLE `shop` (
CREATE TABLE `ss_invite_code` (
`id` int(11) NOT NULL,
`code` varchar(128) NOT NULL,
`code` varchar(128) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL,
`user_id` int(11) NOT NULL,
`created_at` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
`updated_at` timestamp NOT NULL DEFAULT '2016-06-01 00:00:00'
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
CREATE TABLE `referral_code_generation_locks` (
`id` tinyint unsigned NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;
INSERT INTO `referral_code_generation_locks` (`id`) VALUES (1);
CREATE TABLE `ss_password_reset` (
`id` int(11) NOT NULL,
`email` varchar(254) NOT NULL,
@ -437,7 +444,8 @@ ALTER TABLE `shop`
ALTER TABLE `ss_invite_code`
ADD PRIMARY KEY (`id`),
ADD KEY `user_id` (`user_id`);
ADD KEY `user_id` (`user_id`),
ADD KEY `idx_ss_invite_code_code` (`code`);
ALTER TABLE `ss_password_reset`
ADD PRIMARY KEY (`id`);

@ -0,0 +1,60 @@
<?php
require dirname(__DIR__) . '/vendor/autoload.php';
$System_Config = [];
use App\Models\User;
use App\Services\AccountSecurityService;
use App\Services\Payment\RechargeMethodsService;
use App\Utils\Totp;
$assert = static function ($condition, $message) {
if (!$condition) {
throw new RuntimeException($message);
}
};
$user = new User();
$user->ga_enable = 1;
$user->ga_token = Totp::generateSecret();
$assert(AccountSecurityService::hasTotp($user), 'Enabled TOTP was not detected.');
$user->ga_enable = 0;
$assert(!AccountSecurityService::hasTotp($user), 'Disabled TOTP was reported as enabled.');
$assert(AccountSecurityService::consumePasswordFactor($user, '', '') === null,
'An empty password factor was accepted.');
$routes = file_get_contents(dirname(__DIR__) . '/config/routes.php');
foreach ([
"'/password/verify/send'",
"'/password'",
"'/recharge/options'",
'AccountSecurityController:passwordVerifySend',
'AccountSecurityController:updatePassword',
'AccountSecurityController:rechargeOptions',
] as $needle) {
$assert(strpos($routes, $needle) !== false, 'Missing account API route: ' . $needle);
}
$controller = file_get_contents(dirname(__DIR__) . '/app/Controllers/AccountSecurityController.php');
foreach (['oldpwd', 'emailcode', 'gacode', 'need_security_verify', 'AdminCsrf::verify'] as $needle) {
$assert(strpos($controller, $needle) !== false, 'Password API dropped security field: ' . $needle);
}
$security = file_get_contents(dirname(__DIR__) . '/app/Services/AccountSecurityService.php');
foreach ([
"'password_change:' . $plainCode",
"'password_change:' . $emailCode",
"->where('code', 'like', 'password_change:%')",
'is_scalar($emailCode)',
'is_scalar($totpCode)',
'->incr($key)',
'->getClient()->set(',
] as $needle) {
$assert(strpos($security, $needle) !== false, 'Password factor hardening is missing: ' . $needle);
}
$methods = RechargeMethodsService::class;
$assert(method_exists($methods, 'forUser'), 'Recharge method discovery service is missing.');
echo "Account security and recharge API contract checks passed.\n";

@ -0,0 +1,81 @@
<?php
require dirname(__DIR__) . '/vendor/autoload.php';
use App\Services\ReferralConfig;
use Illuminate\Database\Capsule\Manager as Capsule;
use Illuminate\Database\Schema\Blueprint;
$assert = static function ($condition, string $message): void {
if (!$condition) {
throw new RuntimeException($message);
}
};
// Force Redis connection attempts to fail fast; the service must fall back to
// the authoritative configuration table when Redis is unavailable.
$System_Config = ['redis_host' => '127.0.0.1', 'redis_port' => 1];
$capsule = new Capsule();
$capsule->addConnection(['driver' => 'sqlite', 'database' => ':memory:'], 'default');
$capsule->setAsGlobal();
$capsule->bootEloquent();
$schema = $capsule->schema('default');
$schema->create('configurations', static function (Blueprint $table): void {
$table->increments('id');
$table->string('name');
$table->text('value')->nullable();
});
ReferralConfig::clearCache();
$defaults = ReferralConfig::values();
$assert($defaults[ReferralConfig::RATE_KEY] === '20.00', 'Default referral rate changed unexpectedly.');
$assert($defaults[ReferralConfig::VALID_DAYS_KEY] === 730, 'Default referral validity changed unexpectedly.');
$assert($defaults[ReferralConfig::ENABLED_KEY] === true, 'Default referral switch should be enabled.');
$assert($defaults['rate_configured'] === false, 'Missing rate row was marked configured.');
Capsule::table('configurations')->insert([
['name' => ReferralConfig::RATE_KEY, 'value' => '12.5'],
['name' => ReferralConfig::VALID_DAYS_KEY, 'value' => '30'],
['name' => ReferralConfig::ENABLED_KEY, 'value' => 'false'],
]);
ReferralConfig::clearCache();
$configured = ReferralConfig::values();
$assert($configured[ReferralConfig::RATE_KEY] === '12.50' && $configured['rate_configured'], 'Configured rate was not loaded.');
$assert($configured[ReferralConfig::VALID_DAYS_KEY] === 30 && $configured['days_configured'], 'Configured validity was not loaded.');
$assert($configured[ReferralConfig::ENABLED_KEY] === false && $configured['enabled_configured'], 'Configured switch was not loaded.');
$now = 1700000000;
$eligible = (object) ['ref_by' => 9, 'reg_date' => date('Y-m-d H:i:s', $now - 29 * 86400)];
$expired = (object) ['ref_by' => 9, 'reg_date' => date('Y-m-d H:i:s', $now - 31 * 86400)];
$assert(!ReferralConfig::isEligible($eligible, $now), 'Disabled referral configuration still paid rewards.');
$assert(ReferralConfig::rateFor((object) ['aff_rate' => 7.5]) === 12.5, 'Configured global rate did not override legacy per-user rate.');
Capsule::table('configurations')->where('name', ReferralConfig::ENABLED_KEY)->update(['value' => 'true']);
ReferralConfig::clearCache();
$assert(ReferralConfig::isEligible($eligible, $now), 'An in-window referred user was rejected.');
$assert(!ReferralConfig::isEligible($expired, $now), 'An expired referral remained eligible.');
$assert(!ReferralConfig::isEligible((object) ['ref_by' => 0, 'reg_date' => date('Y-m-d H:i:s', $now)], $now), 'A user without an inviter was eligible.');
Capsule::table('configurations')->where('name', ReferralConfig::RATE_KEY)->delete();
ReferralConfig::clearCache();
$assert(ReferralConfig::rateFor((object) ['aff_rate' => 7.5]) === 7.5, 'Legacy per-referrer rate was not preserved before global configuration.');
foreach ([['0', '0.00'], ['100', '100.00'], ['12.5', '12.50']] as [$input, $expected]) {
$assert(ReferralConfig::validateRate($input) === $expected, 'Valid referral rate was rejected.');
}
foreach (['-1', '100.01', '1.234', 'abc'] as $invalid) {
try {
ReferralConfig::validateRate($invalid);
throw new RuntimeException('Invalid referral rate was accepted: ' . $invalid);
} catch (InvalidArgumentException $exception) {
// Expected.
}
}
// Regression guard for ConfigController's first-save/default-row path.
$controller = file_get_contents(dirname(__DIR__) . '/app/Controllers/Admin/ConfigController.php');
$assert(str_contains($controller, '$isReferralKey')
&& str_contains($controller, '!($isReferralKey && !isset($configurations[$key]))'),
'ConfigController does not persist an explicitly saved referral default.');
echo "Referral config checks passed.\n";

@ -0,0 +1,81 @@
<?php
require dirname(__DIR__) . '/vendor/autoload.php';
use App\Services\ReferralService;
use Illuminate\Database\Capsule\Manager as Capsule;
use Illuminate\Database\Schema\Blueprint;
$assert = static function ($condition, string $message): void {
if (!$condition) {
throw new RuntimeException($message);
}
};
// Keep this regression test self-contained: no Redis or production database
// is needed to exercise the code/lock invariants.
$capsule = new Capsule();
$capsule->addConnection(['driver' => 'sqlite', 'database' => ':memory:'], 'default');
$capsule->setAsGlobal();
$capsule->bootEloquent();
$schema = $capsule->schema('default');
$schema->create('ss_invite_code', static function (Blueprint $table): void {
$table->increments('id');
$table->string('code', 128);
$table->integer('user_id');
});
$schema->create('referral_code_generation_locks', static function (Blueprint $table): void {
$table->unsignedTinyInteger('id')->primary();
});
Capsule::table('referral_code_generation_locks')->insert(['id' => 1]);
Capsule::table('ss_invite_code')->insert([
['id' => 1, 'code' => 'Ab3dE9x0', 'user_id' => 1],
['id' => 2, 'code' => 'aB3dE9x0', 'user_id' => 2],
['id' => 3, 'code' => 'legacy-long-code', 'user_id' => 3],
]);
$assert(ReferralService::normalizeCode('Ab3dE9x0') === 'Ab3dE9x0', 'Valid mixed-case code was rejected.');
$assert(ReferralService::normalizeCode(' Ab3dE9x0 ') === 'Ab3dE9x0', 'Whitespace was not trimmed.');
$assert(ReferralService::normalizeCode('Ab3dE9x') === '', 'Short code was accepted.');
$assert(ReferralService::normalizeCode('Ab3dE9x!') === '', 'Non-alphanumeric code was accepted.');
$assert(ReferralService::findInvitation('Ab3dE9x0')->user_id === 1, 'Exact mixed-case lookup chose the wrong inviter.');
$assert(ReferralService::findInvitation('aB3dE9x0')->user_id === 2, 'Case-sensitive lookup did not preserve the code owner.');
$assert(ReferralService::findInvitation('AB3DE9X0') === null, 'A differently cased code resolved unexpectedly.');
$assert(ReferralService::findInvitation('legacy-long-code') === null, 'Legacy long code was accepted by the new lookup.');
// Query-string links win over a stale cookie; `code` remains a compatibility
// alias, and a valid cookie is used only when neither query key is valid.
$assert(ReferralService::registrationCode(['aff' => 'Ab3dE9x0'], 'aB3dE9x0') === 'Ab3dE9x0', 'aff did not win over cookie.');
$assert(ReferralService::registrationCode(['aff' => 'invalid', 'code' => 'aB3dE9x0'], 'Ab3dE9x0') === 'aB3dE9x0', 'Legacy code query alias was not accepted.');
$assert(ReferralService::registrationCode([], 'aB3dE9x0') === 'aB3dE9x0', 'Valid cookie was not used as fallback.');
$assert(ReferralService::registrationCode(['aff' => 'invalid', 'code' => 'invalid'], 'invalid') === '', 'Invalid referral values were accepted.');
$first = ReferralService::codeForUser((object) ['id' => 4]);
$again = ReferralService::codeForUser((object) ['id' => 4]);
$other = ReferralService::codeForUser((object) ['id' => 5]);
$assert($first !== null && $again !== null && $other !== null, 'Code generation returned no model.');
$assert($first->code === $again->code, 'Repeated codeForUser calls generated duplicate rows.');
$assert($first->code !== $other->code, 'Different users received the same generated code.');
$assert(ReferralService::normalizeCode($first->code) === $first->code, 'Generated code does not match the eight-character contract.');
$assert(Capsule::table('ss_invite_code')->where('code', $first->code)->count() === 1, 'Generated code was not persisted once.');
$candidate = ReferralService::generateCode();
$assert(ReferralService::normalizeCode($candidate) === $candidate
&& Capsule::table('ss_invite_code')->where('code', $candidate)->count() === 0,
'The locked candidate generator returned an invalid or already-used code.');
Capsule::table('referral_code_generation_locks')->delete();
try {
ReferralService::codeForUser((object) ['id' => 6]);
throw new RuntimeException('Missing referral generation lock was not rejected.');
} catch (RuntimeException $exception) {
$assert(str_contains($exception->getMessage(), 'referral_affiliate_code.sql'), 'Missing lock error was not actionable.');
}
Capsule::table('referral_code_generation_locks')->insert(['id' => 1]);
$rotated = ReferralService::rotateForUser((object) ['id' => 4]);
$assert($rotated !== null && $rotated->code !== $first->code, 'Code rotation did not issue a replacement.');
$assert(Capsule::table('ss_invite_code')->where('user_id', 4)->count() === 1, 'Code rotation left multiple rows for one user.');
$assert(Capsule::table('ss_invite_code')->where('code', $first->code)->count() === 0, 'Rotated code remained active.');
echo "Referral service checks passed.\n";
Loading…
Cancel
Save