diff --git a/AGENTS.md b/AGENTS.md index bf0b4252..c4008979 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -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. diff --git a/web/app/Controllers/AccountSecurityController.php b/web/app/Controllers/AccountSecurityController.php new file mode 100644 index 00000000..d8b946f3 --- /dev/null +++ b/web/app/Controllers/AccountSecurityController.php @@ -0,0 +1,123 @@ +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); + } +} diff --git a/web/app/Controllers/Admin/ConfigController.php b/web/app/Controllers/Admin/ConfigController.php index 506f0658..eab060d8 100644 --- a/web/app/Controllers/Admin/ConfigController.php +++ b/web/app/Controllers/Admin/ConfigController.php @@ -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; } diff --git a/web/app/Controllers/Admin/UserController.php b/web/app/Controllers/Admin/UserController.php index 4db1f5c7..7e24ba3f 100644 --- a/web/app/Controllers/Admin/UserController.php +++ b/web/app/Controllers/Admin/UserController.php @@ -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, ]; } diff --git a/web/app/Controllers/AuthController.php b/web/app/Controllers/AuthController.php index 27e32938..1d78157b 100644 --- a/web/app/Controllers/AuthController.php +++ b/web/app/Controllers/AuthController.php @@ -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(); } diff --git a/web/app/Controllers/UserController.php b/web/app/Controllers/UserController.php index 958bc366..01b4561b 100644 --- a/web/app/Controllers/UserController.php +++ b/web/app/Controllers/UserController.php @@ -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' => '请求已过期,请刷新页面后重试', + ]); } } diff --git a/web/app/Models/User.php b/web/app/Models/User.php index 0ae3bb4c..cf52d72f 100644 --- a/web/app/Models/User.php +++ b/web/app/Models/User.php @@ -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() diff --git a/web/app/Services/AccountSecurityService.php b/web/app/Services/AccountSecurityService.php new file mode 100644 index 00000000..c48f4afb --- /dev/null +++ b/web/app/Services/AccountSecurityService.php @@ -0,0 +1,203 @@ +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. + } + } +} diff --git a/web/app/Services/Payment/RechargeCreditService.php b/web/app/Services/Payment/RechargeCreditService.php index 6d090219..dbc34043 100644 --- a/web/app/Services/Payment/RechargeCreditService.php +++ b/web/app/Services/Payment/RechargeCreditService.php @@ -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(); diff --git a/web/app/Services/Payment/RechargeMethodsService.php b/web/app/Services/Payment/RechargeMethodsService.php new file mode 100644 index 00000000..7c9df7fa --- /dev/null +++ b/web/app/Services/Payment/RechargeMethodsService.php @@ -0,0 +1,57 @@ + '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); + } +} diff --git a/web/app/Services/ReferralConfig.php b/web/app/Services/ReferralConfig.php new file mode 100644 index 00000000..22b55063 --- /dev/null +++ b/web/app/Services/ReferralConfig.php @@ -0,0 +1,198 @@ + 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; + } +} diff --git a/web/app/Services/ReferralService.php b/web/app/Services/ReferralService.php new file mode 100644 index 00000000..851dc2ce --- /dev/null +++ b/web/app/Services/ReferralService.php @@ -0,0 +1,184 @@ +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); + } +} diff --git a/web/config/routes.php b/web/config/routes.php index 95035112..9b323f32 100644 --- a/web/config/routes.php +++ b/web/config/routes.php @@ -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'); diff --git a/web/public/cloud/account-drawer.js b/web/public/cloud/account-drawer.js new file mode 100644 index 00000000..e50d5751 --- /dev/null +++ b/web/public/cloud/account-drawer.js @@ -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(); +}); diff --git a/web/public/cloud/account.css b/web/public/cloud/account.css index c27cbacd..109d6954 100644 --- a/web/public/cloud/account.css +++ b/web/public/cloud/account.css @@ -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; } +} diff --git a/web/public/cloud/client.css b/web/public/cloud/client.css index 03ae0618..06e1b8da 100644 --- a/web/public/cloud/client.css +++ b/web/public/cloud/client.css @@ -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; } diff --git a/web/public/theme/venix/js/recharge.js b/web/public/theme/venix/js/recharge.js new file mode 100644 index 00000000..a41d9f05 --- /dev/null +++ b/web/public/theme/venix/js/recharge.js @@ -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 = "正在查询支付方式…"; + 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); + } +})(); diff --git a/web/public/theme/venix/js/user-home.js b/web/public/theme/venix/js/user-home.js index b08073e2..2a3971b8 100644 --- a/web/public/theme/venix/js/user-home.js +++ b/web/public/theme/venix/js/user-home.js @@ -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) { diff --git a/web/resources/email/auth/verify.tpl b/web/resources/email/auth/verify.tpl index 545b906a..23d28266 100644 --- a/web/resources/email/auth/verify.tpl +++ b/web/resources/email/auth/verify.tpl @@ -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'} -

{if !empty($scene) && $scene == 'login'}ACCOUNT SECURITY{elseif !empty($scene) && $scene == 'registration'}WELCOME TO THE CLOUD{else}EMAIL VERIFICATION{/if}

+

{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}

- {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}

- {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}

diff --git a/web/resources/views/venix/admin/config.tpl b/web/resources/views/venix/admin/config.tpl index 120dfda0..95e97bad 100644 --- a/web/resources/views/venix/admin/config.tpl +++ b/web/resources/views/venix/admin/config.tpl @@ -232,8 +232,8 @@
@@ -243,6 +243,24 @@
+
+ + +
按被邀请用户每次充值金额计算,范围 0–100%。
+
+
+ + +
被邀请用户注册超过此期限后,充值不再产生推广返利。
+
+
+ + +
关闭时保留历史返利记录,但新充值不生成返利。
+
+
+ + +
+
+ + +
+
+ {include file='user/layout_footer.tpl'} - {include file='user/layout_modal.tpl'} - {include file='user/layout_scripts.tpl'} diff --git a/web/resources/views/venix/user/invite.tpl b/web/resources/views/venix/user/invite.tpl index 1f6f1be0..866aca32 100644 --- a/web/resources/views/venix/user/invite.tpl +++ b/web/resources/views/venix/user/invite.tpl @@ -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'}
-

分销中心

-

邀请返利

+

推广中心

+

推广

购买云服务器 @@ -12,26 +12,26 @@
- 返利 {$user->aff_rate}% -

分享邀请链接,获得好友充值返利

-

每邀请一位用户注册,对方在两年内充值时,你会按当前返利比例获得佣金。邀请链接请勿发布到公共群组或公开平台。

+ 返利 {$referral_rate}% +

分享推广链接,获得好友消费返利

+

好友通过推广链接注册后,{$referral_days} 天内的符合条件充值会按当前比例计入返利。推广链接请勿发布到公共群组或公开平台。

{if $invite_enabled && $aff_method == 'code' && !$has_invite_code} - + {elseif $invite_enabled && $aff_method == 'code'} - + {/if}
@@ -50,7 +50,7 @@ ¥ {$user->inviteMoneyTotal()}
- 已邀请 + 已推广用户 {$user->invitedMemberTotal()} 人
@@ -64,7 +64,7 @@
返利比例 - {$user->aff_rate}% + {$referral_rate}%
- 已邀请 + 已推广用户 {$user->invitedMemberTotal()} 返利记录
- 邀请方式 - {if $aff_method == 'code'}邀请码{else}邀请链接{/if} + 推广方式 + {if $aff_method == 'code'}推广代码{else}推广链接{/if} {if $aff_method == 'code'}剩余 {$user->invite_num} 次{else}自动绑定{/if}
@@ -121,7 +121,7 @@

Records

-

返利记录

+

推广返利记录

@@ -129,7 +129,7 @@
暂无返利记录 - 好友完成充值后,返利记录会显示在这里。 + 好友完成符合条件的消费后,返利记录会显示在这里。
{else}
@@ -171,13 +171,13 @@

Tips

-

邀请说明

+

推广说明

-
邀请链接只建议发送给可信好友,避免发布到公开平台。
-
当前返利比例为 {$user->aff_rate}%,好友充值后会计入返利记录。
+
推广链接只建议发送给可信好友,避免发布到公开平台。
+
当前返利比例为 {$referral_rate}%,好友注册 {$referral_days} 天内的充值会计入返利记录。
返利余额可以转入账户余额;提现只支持 USDT。
diff --git a/web/resources/views/venix/user/layout_header.tpl b/web/resources/views/venix/user/layout_header.tpl index 7424b8d3..70f726d1 100644 --- a/web/resources/views/venix/user/layout_header.tpl +++ b/web/resources/views/venix/user/layout_header.tpl @@ -8,6 +8,7 @@ + {if $vu_page_title != ''}{$vu_page_title|escape:"html"} | {/if}{$config["appName"]|escape:"html"} @@ -15,7 +16,7 @@ - +
{include file='user/panel_sidebar.tpl' panel_active=$vu_active_key panel_cloud_page=0}
diff --git a/web/resources/views/venix/user/layout_scripts.tpl b/web/resources/views/venix/user/layout_scripts.tpl index 71caf440..69d4a132 100644 --- a/web/resources/views/venix/user/layout_scripts.tpl +++ b/web/resources/views/venix/user/layout_scripts.tpl @@ -3,7 +3,7 @@ {assign var=vu_has_ticket_page value=$vu_ticket_page|default:0} -{if $vu_active_key|default:'' == 'edit'}{/if} +{if $vu_active_key|default:'' == 'edit' || $vu_qrcode|default:false}{/if} {if $vu_has_shop_page}{/if} {if $vu_has_ticket_page}{/if} diff --git a/web/resources/views/venix/user/panel_sidebar.tpl b/web/resources/views/venix/user/panel_sidebar.tpl index 868edc80..9a2f0736 100644 --- a/web/resources/views/venix/user/panel_sidebar.tpl +++ b/web/resources/views/venix/user/panel_sidebar.tpl @@ -32,17 +32,8 @@ 账单信息 - - - 余额充值 - - - 邀请返利 - - - 账户设置 - {if !empty($ticket_navigation_enabled)} + 工单支持 diff --git a/web/resources/views/venix/user/panel_topbar.tpl b/web/resources/views/venix/user/panel_topbar.tpl index 51259db1..2359c844 100644 --- a/web/resources/views/venix/user/panel_topbar.tpl +++ b/web/resources/views/venix/user/panel_topbar.tpl @@ -3,7 +3,18 @@
- U{$user->user_name|default:'账户'|escape:"html"} +
+ + +
{if $panel_cloud_mode} {else} @@ -12,3 +23,4 @@
{include file='user/announcement_drawer.tpl'} +{include file='user/account_drawer.tpl'} diff --git a/web/resources/views/venix/user/pay_success.tpl b/web/resources/views/venix/user/pay_success.tpl index 81a9dc39..d6c59e17 100644 --- a/web/resources/views/venix/user/pay_success.tpl +++ b/web/resources/views/venix/user/pay_success.tpl @@ -5,7 +5,7 @@

充值结果

- {if $transaction_records_visible}充值记录{else}返回充值{/if} + 购买套餐
diff --git a/web/resources/views/venix/user/paytaro.tpl b/web/resources/views/venix/user/paytaro.tpl index 2149512c..e68b2fb0 100644 --- a/web/resources/views/venix/user/paytaro.tpl +++ b/web/resources/views/venix/user/paytaro.tpl @@ -1,483 +1,60 @@ {include file='user/layout_header.tpl' vu_title='账户充值' vu_active='code'} -
-
-

钱包

-

账户充值

-
-
- 购买套餐 - 返回实例 -
-
- -
-
- 余额充值 -

账户余额充值

-

请选择充值金额并完成扫码支付。支付成功后余额通常会自动入账,若长时间未到账请联系站内客服。

-
- +
+
+

账户充值

输入充值金额后,系统会自动筛选当前可用的支付方式。支付成功后余额将自动入账。

+
当前余额¥ {$user->money}去选套餐
+
+ +
+
+

选择充值方式

+ {if $recharge_restricted} +
充值服务暂时无法使用当前账户暂不满足充值条件,请稍后再试。
+ {else} +
+ +

先填写充值金额,系统会显示可用的支付方式。

+ + + {/if}
-
-
-
-
-
-

Recharge

-

在线充值

-
- -
- -
- {if $recharge_restricted} -
- - 充值服务暂时无法使用 - 请稍后再试。 -
- {else} - - {if $paytaro_enabled || $usdt_enabled || $yipay_alipay_enabled || $yipay_wxpay_enabled} -
- {if $paytaro_enabled} - - {/if} - {if $yipay_alipay_enabled} - - {/if} - {if $yipay_wxpay_enabled} - - {/if} - {if $usdt_enabled} - - {/if} -
- {else} -

当前暂无可用在线充值方式。

- {/if} - {/if} - -
- - {if !$transaction_records_restricted} -
-
-
-

History

-

充值记录

-
- -
-
-
- - - - - - - - - - - {if $codes->isEmpty()} - - - - {else} - {foreach $codes as $code} - {if $code->type!=-2} - - - - - - - - {/if} - {/foreach} - {/if} - -
充值代码类型内容状态时间
-
- - 暂无充值记录 - 完成第一笔充值后,记录会显示在这里。 -
-
-
- {$code->display_code|default:'--'|escape:'html'} - {if $code->display_code != ''} - - {/if} -
-
- {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} - - - {if $code->type==-1 || $code->type==10003 || $code->type==10004 || $code->type==10005 || $code->type==10006 || $code->type==10007} - ¥ {$code->number} - {/if} - - 成功{$code->usedatetime}
- - - - {/if} - - - +
+

充值说明

+
扫码或打开支付链接后请等待系统确认,避免重复创建订单。
请核对支付金额和收款网络,付款完成后余额会按订单金额入账。
{if !empty($ticket_navigation_enabled)}如遇到账延迟,请保留支付记录并提交工单。{else}如遇到账延迟,请保留支付记录并稍后重试。{/if}
+ + + {if !$transaction_records_restricted} +
+

充值记录

+
+ {if $codes->isEmpty()} + + {else} + {foreach $codes as $code} + {if $code->type!=-2} + + {/if} + {/foreach} + {/if} +
充值代码类型金额状态时间
暂无充值记录完成第一笔充值后,记录会显示在这里。
{$code->display_code|default:'--'|escape:'html'}{if $code->display_code != ''}{/if}
{if $code->type==-1 || $code->type==10003 || $code->type==10004 || $code->type==10005}余额充值{elseif $code->type==10006}USDT 充值{elseif $code->type==10007}在线充值{else}充值{/if}¥ {$code->number}成功{$code->usedatetime}
+
+ {/if} + {include file='user/layout_footer.tpl'} - {include file='user/layout_modal.tpl'} - {include file='user/layout_scripts.tpl' vu_qrcode=1} - + diff --git a/web/sql/referral_affiliate_code.sql b/web/sql/referral_affiliate_code.sql new file mode 100644 index 00000000..7fcc246f --- /dev/null +++ b/web/sql/referral_affiliate_code.sql @@ -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`); diff --git a/web/sql/ss.sql b/web/sql/ss.sql index beb63d53..fb85207b 100644 --- a/web/sql/ss.sql +++ b/web/sql/ss.sql @@ -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`); diff --git a/web/tests/AccountSecurityAndRechargeContractTest.php b/web/tests/AccountSecurityAndRechargeContractTest.php new file mode 100644 index 00000000..26233725 --- /dev/null +++ b/web/tests/AccountSecurityAndRechargeContractTest.php @@ -0,0 +1,60 @@ +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"; diff --git a/web/tests/ReferralConfigTest.php b/web/tests/ReferralConfigTest.php new file mode 100644 index 00000000..851d203b --- /dev/null +++ b/web/tests/ReferralConfigTest.php @@ -0,0 +1,81 @@ + '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"; diff --git a/web/tests/ReferralServiceTest.php b/web/tests/ReferralServiceTest.php new file mode 100644 index 00000000..ba0aaad5 --- /dev/null +++ b/web/tests/ReferralServiceTest.php @@ -0,0 +1,81 @@ +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";