Compare commits

..
Author SHA1 Message Date
Codex af8c292446 feat(fuc): prepare independent public address navigation 2026-11-08 18:58:41 +08:00
hellcat 1b83aabc68 fix(fuc): isolate page failures and preserve checkout state 2026-11-08 18:11:32 +08:00
hellcat b88b88dd84 fix(fuc): keep public support clear of the fixed header 2026-11-08 17:32:11 +08:00
Codex e1c8c3e636 fix(fuc): keep mobile support above navigation 2026-11-08 17:25:32 +08:00
Codex 998225ae04 fix(fuc): stabilize support widget layers 2026-11-08 15:46:14 +08:00
hellcat ff39564d44 fix(fuc): remove unsupported daily check-in button 2026-11-07 19:25:36 +08:00
Codex 9971b6fab5 Prepare FUC-XB web support integration 2026-11-07 17:53:47 +08:00
hellcat 7b46eed243 fix(fuc): restore original Cool theme logo 2026-11-07 17:48:50 +08:00
hellcat 2c92a857e8 Fix FUC mobile scrolling and Safari form viewport behavior 2026-11-07 16:06:52 +08:00
Codex d552b8a592 Sort user-facing nodes by region across XB instances 2026-11-07 03:24:01 +00:00
Codex a11df4fe56 Restore order hover and hide closed-ticket actions 2026-11-06 20:19:12 +08:00
Codex 42813c30cb Polish FUC order list spacing and show total pages 2026-11-06 20:05:40 +08:00
Codex 0f78c664ff Label unpaid FUC order actions as continue payment 2026-11-06 19:42:09 +08:00
Codex 30b36f01c6 Remove the pending order banner from FUC 2026-11-06 19:39:00 +08:00
Codex 66ded03d80 Open the cashier directly and refine FUC order controls 2026-11-06 19:29:23 +08:00
Codex c5513e18b9 Release FUC dashboard, orders, and checkout improvements 2026-11-06 18:26:40 +08:00
hellcat a50fc3f77d fix(fuc): use regular weight for dashboard notices 2026-11-06 16:34:50 +08:00
hellcat 9c6ef63a81 Use the current official sing-box App Store listing 2026-11-05 21:32:35 +08:00
hellcat ac797a3b1f Restore FUC client guides and package links 2026-11-05 21:30:44 +08:00
hellcat d8057f06e0 fix(fuc): keep dashboard-only notices out of the site list 2026-11-05 21:07:02 +08:00
hellcat 21a6bcff34 test(fuc-xb): formal-import-guard acceptance\n 2026-11-05 17:20:22 +08:00
hellcat 5a55fae630 test(fuc-xb): cutover-backup-notices acceptance\n 2026-11-05 16:55:04 +08:00
hellcat 29752628df test(fuc-xb): theme-hide-vip-progress-129 acceptance\n 2026-11-05 16:29:35 +08:00
hellcat b91e4b82e2 test(fuc-xb): theme-scroll-header-128 acceptance\n 2026-11-05 16:20:36 +08:00
hellcat 824d0f4167 test(fuc-xb): theme-plan-label-127 acceptance\n 2026-11-05 16:14:30 +08:00
hellcat 6f6abdfc05 test(fuc-xb): theme-calendar-126 acceptance\n 2026-11-05 12:47:42 +08:00
hellcat 3beacbd172 test(fuc-xb): launch-native-worker-mail acceptance\n 2026-11-05 12:16:18 +08:00
hellcat 3ddbf98057 test(fuc-xb): launch-execution-guard acceptance\n 2026-11-05 12:02:43 +08:00
hellcat ed4ec7fd71 test(fuc-xb): launch-worker-client-guards acceptance\n 2026-11-05 12:00:51 +08:00
hellcat 7e9d65ccae test(fuc-xb): launch-client-matrix acceptance\n 2026-11-05 11:49:25 +08:00
hellcat 4065f1d755 test(fuc-xb): launch-queue-relay acceptance\n 2026-11-05 11:45:55 +08:00
hellcat ab3d13bc69 test(fuc-xb): launch-node-recovery acceptance\n 2026-11-05 11:21:43 +08:00
hellcat 7919a9f33f test(fuc-xb): launch-runtime-preparation acceptance\n 2026-11-05 11:09:52 +08:00
hellcat fb5d6a90d4 test(fuc-xb): launch-gate-v2 acceptance\n 2026-11-05 10:53:59 +08:00
hellcat 0744b9ac99 test(fuc-xb): complete fresh migration and native V2 reacceptance 2026-11-05 10:26:42 +08:00
hellcat 8afb1d44fb test(fuc-xb): refresh-v2-group-model acceptance\n 2026-11-05 10:08:40 +08:00
hellcat 6a7e941c8a test(fuc-xb): refresh-v2-node acceptance\n 2026-11-05 10:05:39 +08:00
hellcat 6e09553f91 test(fuc-xb): refresh-v2-reset-log acceptance\n 2026-11-05 10:00:55 +08:00
hellcat 3e9e6606fc test(fuc-xb): refresh-v2-tools acceptance\n 2026-11-05 09:57:34 +08:00
hellcat f584444183 test(fuc-xb): record external acceptance failures and cleanup 2026-11-04 19:38:59 +08:00
hellcat 4ab037711f test(fuc-xb): upload-content-type acceptance\n 2026-11-04 19:09:52 +08:00
hellcat 89bbc2a211 test(fuc-xb): template acceptance\n 2026-11-04 19:06:08 +08:00
hellcat ce2a2ad578 test(fuc-xb): cashier acceptance\n 2026-11-04 19:03:24 +08:00
hellcat c0e86a7deb test(fuc-xb): client acceptance\n 2026-11-04 19:02:26 +08:00
hellcat 5a75c839b9 test(fuc-xb): payment-uuid acceptance\n 2026-11-04 18:53:12 +08:00
hellcat 08100a207f test(fuc-xb): node acceptance\n 2026-11-04 18:52:01 +08:00
hellcat 435fe9dc8d test(fuc-xb): payment acceptance\n 2026-11-04 18:46:32 +08:00
hellcat 7b1d04547e test(fuc-xb): add bounded real-mail acceptance harness 2026-11-04 18:36:34 +08:00
hellcat 6c7e7c8318 docs(fuc-xb): record isolated staging final acceptance and cleanup 2026-11-04 18:07:21 +08:00
hellcat 28ccc0e964 fix(fuc): avoid misleading preview totals and legacy document overlap
Leave final VIP, coupon, surplus and wallet settlement to the native order. Keep document metadata on its own line within the approved usable legacy layout. Bump Fuc to 0.12.4.
2026-11-04 17:35:57 +08:00
hellcat 2022184583 fix(fuc): preserve loaded styles during native page transitions
Keep common LINK nodes attached, load ordered mode styles and overrides before committing the next page, and avoid reparenting dark/bridge styles. Bump Fuc to 0.12.3.
2026-11-04 17:08:58 +08:00
hellcat f236c58935 fix(fuc): show wallet-funded order amounts and settlement breakdown
Display native package consideration including consumed old-plan credit instead of online-only remainder. Clarify zero online payment without changing XB checkout or financial logic. Bump Fuc to 0.12.2.
2026-11-04 16:51:35 +08:00
hellcat 7446b045a3 fix(fuc): restore original palettes and fixed landing colors
Remove seasonal styles and selectors, migrate retired browser preferences, and retain the original purple/green options and dark-mode controls. Preserve VIP and other theme features. Authorized for the independent FUC-XB test instance only.
2026-11-04 15:48:58 +08:00
hellcat 0501711267 feat(fuc-xb): prepare isolated staging theme and VIP auto upgrades
Port the Fuc 0.12.0 frontend and default-off VIP plugin. Include the previously approved password-reset token revocation. Deploy only to an independent FUC-XB test instance; no production cutover.
2026-11-04 13:44:33 +08:00
hellcat 3633ba32a6 docs(nodes): record HN and DPL country-based UDP protocol allocation
Docker Build and Publish / build (push) Has been cancelled
2026-11-03 19:32:30 +08:00
hellcat 299f8f2d5a docs(dpl): record single-node Hysteria2 UDP cutover
Docker Build and Publish / build (push) Waiting to run
2026-11-03 13:56:39 +08:00
hellcat d8022bb840 docs(hn): record single-node Hysteria2 UDP cutover
Docker Build and Publish / build (push) Waiting to run
2026-11-03 13:31:23 +08:00
hellcat 8642c1be7f docs(hn): record full mail theme activation and real inbox acceptance
Docker Build and Publish / build (push) Has been cancelled
2026-11-01 19:32:39 +08:00
hellcat 2a82819ce8 feat(hn): cover all transactional mail and incoming auto replies
Docker Build and Publish / build (push) Waiting to run
2026-11-01 18:39:44 +08:00
hellcat 97da1ae43a design(hn): add branded transactional email previews 2026-11-01 18:28:40 +08:00
hellcat 8c1a01ab3b docs(payments): record cashier fix rollout and WeChat recovery
Docker Build and Publish / build (push) Waiting to run
2026-11-01 16:40:46 +08:00
hellcat 296e063e3c fix(payments): accept HTML cashiers and recognize WeChat HTTPS QR links
Docker Build and Publish / build (push) Waiting to run
2026-11-01 16:31:14 +08:00
hellcat f825c30038 docs(orders): record payment reporting rollout and real daily receipts 2026-11-01 13:59:51 +08:00
hellcat 91b5e1251f feat(orders): add asynchronous payment logs and 08:00 daily reports 2026-11-01 13:51:09 +08:00
hellcat 99bb100b45 docs(mail): record TeleHub rollout and legacy report protection 2026-10-31 19:55:42 +08:00
hellcat 18913a11ef docs(payment): verify and restore HN Alipay after approved unpaid probe
Docker Build and Publish / build (push) Waiting to run
2026-10-31 19:53:46 +08:00
hellcat 893da7c56b Merge branch 'master' into codex/payment-health 2026-10-31 19:51:34 +08:00
hellcat 1d5bc332b3 docs(payment): record QR fix deployment and unpaid verification limits 2026-10-31 19:51:22 +08:00
hellcat 2b362b48ee docs(payment): record QR fix deployment and unpaid verification limits 2026-10-31 19:49:33 +08:00
hellcat ee9b1446f6 feat(mail): route DPL and HN mail usage reports through TeleHub 2026-10-31 19:45:37 +08:00
hellcat eb85f2a1a9 fix(payment): recognize bounded large cashier QR and clarify channel alerts
Docker Build and Publish / build (push) Waiting to run
2026-10-31 19:43:17 +08:00
hellcat 7e297b47a3 docs(xb): record unified production release and registration delivery 2026-10-31 19:17:10 +08:00
hellcat fce30f6b4c fix(themes): reuse immutable assets when selecting a published theme 2026-10-31 19:14:31 +08:00
hellcat 1ded40226b feat(xb): unify DPL and HN backend, themes and registration reports 2026-10-31 18:58:37 +08:00
hellcat eb630d2caf docs(nodes): record shared gembox SNI migration
Docker Build and Publish / build (push) Waiting to run
2026-10-31 12:43:23 +08:00
hellcat ac89f9719b Merge dynamic cashier public-address validation
Docker Build and Publish / build (push) Waiting to run
2026-10-30 17:17:54 +08:00
hellcat b530df2de8 fix(xb): reject shared and multicast cashier addresses 2026-10-30 17:17:40 +08:00
hellcat 97e6e86d70 Merge dynamic cashier deployment acceptance
Docker Build and Publish / build (push) Waiting to run
2026-10-30 17:16:06 +08:00
hellcat 4e319098c1 docs: verify dynamic cashier policy deployment 2026-10-30 17:15:49 +08:00
hellcat ad0f04b1d4 Merge dynamic payment cashier handoff fix
Docker Build and Publish / build (push) Waiting to run
2026-10-30 17:12:46 +08:00
hellcat 108fbfa798 fix(xb): follow dynamic cashier handoffs from trusted gateways 2026-10-30 17:12:32 +08:00
hellcat 4c14117bdc Merge payment health production acceptance
Docker Build and Publish / build (push) Waiting to run
2026-10-30 17:02:00 +08:00
hellcat 4dbbd165d1 docs: record payment monitoring production acceptance 2026-10-30 17:01:32 +08:00
hellcat 625b682011 Merge commit '278baa4796f004d77ae03945d49072f4b395aeb9'
Docker Build and Publish / build (push) Waiting to run
2026-10-30 16:39:22 +08:00
hellcat 278baa4796 feat(xb): monitor and manage payment cashiers every six hours 2026-10-30 16:38:30 +08:00
hellcat 9ecb820a16 docs(hn): record shared node rollout and dependency-based acceptance
Docker Build and Publish / build (push) Has been cancelled
2026-10-28 20:15:04 +08:00
hellcat f5ac35730d docs: record verified HN distinct-port shared-node pilot
Docker Build and Publish / build (push) Waiting to run
2026-10-28 13:23:22 +08:00
hellcat eb283d3394 docs: prepare distinct-port HN pilot and record cutover approval boundary 2026-10-28 12:26:12 +08:00
hellcat 7c71192cfb docs: record isolated HN shared-port feasibility failure 2026-10-28 12:09:09 +08:00
hellcat a49881f620 docs: record remaining eligible node onboarding and tool safeguards 2026-10-21 15:39:15 +08:00
hellcat 82902e7ab6 docs: record HK04 to HK06 node onboarding and acceptance 2026-10-20 19:24:57 +08:00
hellcat 66f3044982 fix: preserve actual per-host service configuration in node batches 2026-10-20 18:33:04 +08:00
hellcat 4661c99706 docs: record three Hong Kong nodes and server-side acceptance 2026-10-20 18:19:55 +08:00
hellcat 4397e1958b docs: record sg05 onboarding and server-side provider workflow 2026-10-20 17:46:29 +08:00
hellcat 9d153c7409 docs: prefer server-side operations throughout node maintenance 2026-10-20 17:29:00 +08:00
hellcat 852b38c25d docs: use server-side node onboarding without DPL page acceptance 2026-10-20 17:11:51 +08:00
hellcat 155ee10370 docs: record three Singapore nodes and scoped acceptance 2026-10-20 17:04:00 +08:00
hellcat d331f45b0e feat(nodes): exclude small XrayR hosts and use registered credential fields 2026-10-20 16:24:46 +08:00
hellcat 4d667f37b2 feat(nodes): scope final acceptance to reviewed change impact 2026-10-20 16:07:49 +08:00
hellcat d085e211b3 fix(nodes): validate renewal hooks and record five-node acceptance 2026-10-18 20:13:33 +08:00
hellcat 6b0ac99d19 fix(nodes): restrict Certbot loader to current mounted core revision
Docker Build and Publish / build (push) Has been cancelled
2026-10-17 17:50:02 +08:00
hellcat 44d1c79bef fix(nodes): restore installed Certbot AppArmor profiles on legacy hosts
Docker Build and Publish / build (push) Waiting to run
2026-10-17 17:49:19 +08:00
hellcat ac9f249961 fix(nodes): validate QA scripts and normalized formal snapshots
Docker Build and Publish / build (push) Waiting to run
2026-10-17 17:22:47 +08:00
hellcat e26b5bc6ca fix: finalize acceptance identity and raw QA review evidence
Docker Build and Publish / build (push) Waiting to run
2026-10-17 15:32:03 +08:00
hellcat 5c9157f5d7 feat: add reusable jump-host node onboarding runtime
Docker Build and Publish / build (push) Waiting to run
2026-10-17 15:22:30 +08:00
hellcat 1de59971f6 docs: record three-node Japan batch acceptance and recovery
Docker Build and Publish / build (push) Waiting to run
2026-10-17 09:11:53 +08:00
hellcat 6af676421b Add append-only batch node onboarding and recovery checks
Docker Build and Publish / build (push) Waiting to run
2026-10-17 08:29:05 +08:00
hellcat 522666c339 Define node numbering independently from VPS identifiers 2026-10-16 17:48:29 +08:00
hellcat 910d3cfe01 Document verified Japan node onboarding and administrator access 2026-10-16 17:27:20 +08:00
hellcat 76d9e8d77a Document weiwei proxy deployment and acceptance scope 2026-10-16 16:34:01 +08:00
hellcat 54c5a5ddd9 Add weiwei relay administration reverse proxy 2026-10-16 16:28:41 +08:00
hellcat 26f84bda60 Document accepted gateway domains, proxy boundaries and SSH verification 2026-10-14 10:20:51 +08:00
hellcat 4ad89b196c Keep proxy failure telemetry without sensitive request URLs 2026-10-13 21:08:35 +08:00
hellcat 936a7b3ddf Accept current Cloudflare token lengths with safe characters 2026-10-13 20:47:45 +08:00
hellcat 9880081af7 Limit proxy body rewriting to URLs and guard legacy certificate repair 2026-10-13 20:30:22 +08:00
hellcat 1b8472112c Allow Nginx traversal only to isolated ACME webroot 2026-10-13 20:00:56 +08:00
hellcat 67f1c93e02 Add isolated gateway admin and white proxy provisioning 2026-10-13 19:53:10 +08:00
hellcat 99f9b9ec92 Document verified Cloudflare tuning for both subscription gateways 2026-10-11 19:16:48 +08:00
hellcat 7e8fbf60bd Record user waiver of local node test and Cloudflare follow-up 2026-10-11 17:38:58 +08:00
hellcat 84b334a72d Record unresolved local relay TLS path and diagnostic boundary 2026-10-11 17:32:39 +08:00
hellcat 50eecb91fa Document live AnyTLS onboarding and pending Cloudflare verification 2026-10-11 17:21:48 +08:00
hellcat 3b72c3e3c1 Fix modern DNS startup and parameterize node provisioning 2026-10-11 16:58:11 +08:00
hellcat 12d9f2b47c ops: complete subscription template and node activation workflow 2026-10-11 16:45:16 +08:00
hellcat 1537ebf65c ops: verify AnyTLS relay and allow validated certificate chains 2026-10-11 16:32:29 +08:00
hellcat 52ab8d0885 ops: extend Cloudflare IP synchronization to original gateway 2026-10-11 16:27:09 +08:00
hellcat 16f1a5366b ops: synchronize Cloudflare trust ranges for DPL vhost 2026-10-11 16:21:59 +08:00
hellcat 23ae4068a8 ops: isolate gateway certificate renewal and preserve client IP 2026-10-11 16:18:24 +08:00
hellcat e7ec154f75 ops: version isolated subscription gateway configuration 2026-10-11 16:06:44 +08:00
hellcat 9a523b625c fix: assign onboarding group through model properties 2026-10-11 15:59:52 +08:00
hellcat dfdfbf2562 ops: add isolated AnyTLS node onboarding workflow 2026-10-11 15:55:45 +08:00
hellcat e00c8d1e19 docs: record plan description production acceptance 2026-10-11 14:01:47 +08:00
hellcat bc30ad38c9 docs: record plan description rules and local preview 2026-10-11 13:58:30 +08:00
hellcat 6aec36e786 docs: record verified Telegram ticket reply and email delivery 2026-10-11 13:03:22 +08:00
hellcat ee40fcf7c2 docs: record original reply classification restored in production 2026-10-11 13:00:50 +08:00
hellcat 8ccc38908b fix: preserve original Telegram reply classification as requested 2026-10-11 13:00:10 +08:00
hellcat 85246d26a6 docs: record deployed Telegram reply diagnostics and pending real acceptance 2026-10-11 12:59:10 +08:00
hellcat 5b643135e1 fix: classify Telegram ticket replies by message id and record safe routing diagnostics 2026-10-11 12:58:21 +08:00
hellcat 7622b49cb3 Clarify administrator email reports use a default-off switch when present 2026-10-11 12:05:02 +08:00
hellcat d828cf558b Document Telegram-only administrator operational notifications 2026-10-11 12:04:22 +08:00
hellcat 8aca507c0e Record Telegram ticket deployment and remaining administrator setup 2026-10-11 12:00:23 +08:00
hellcat 6c9422d055 Add authenticated Telegram ticket replies and notification tracking 2026-10-11 11:58:19 +08:00
hellcat 9f8f297a5d docs: record completed non-payment acceptance 2026-10-11 11:09:50 +08:00
hellcat 7a123f8e97 test: verify EPay callback flow without real payments 2026-10-11 11:08:36 +08:00
hellcat a1f4019add docs: record EPay deployment and merchant API verification 2026-10-11 11:03:37 +08:00
hellcat 6045748772 fix: validate EPay successful payment callbacks 2026-10-11 11:01:57 +08:00
hellcat 16a8d769e1 docs: record production payment configuration sync 2026-10-11 10:49:27 +08:00
hellcat 30645f96d5 docs: move maintenance guides to docs and add project agent entry 2026-10-11 10:34:09 +08:00
hellcat 430ddbe9b6 docs: establish AI maintenance guide and operational handoff 2026-10-11 10:26:58 +08:00
hellcat 13117587c8 refactor(admin): split mail settings into dedicated tabs 2026-10-11 09:51:27 +08:00
hellcat 966a8b2c32 feat(admin): integrate mail flow controls into email settings page 2026-10-11 09:48:58 +08:00
hellcat d51fb5e398 fix(admin): show mail flow settings on email configuration page 2026-10-10 19:28:39 +08:00
hellcat ad42a0e1e7 feat(mail): add Resend delivery, inbox replies and notification tiers 2026-10-10 18:53:35 +08:00
hellcat 208536e1cb style(mail): apply tutorial design to default email templates 2026-10-09 18:46:25 +08:00
hellcat cd117604a3 feat: add branded tutorials and display-only plan device settings 2026-10-08 18:01:02 +08:00
xboard 4f48e61a2c fix(order): prevent duplicate refunds and redemptions
Refs #1021
2026-08-30 04:50:34 +08:00
asukassa 9d125527cb fix: reindex device IP array before JSON encoding (#1045) 2026-08-30 01:07:37 +08:00
JW-3154andXboard e074bef702 fix(Shadowrocket.php): add missing bandwidth params for Hysteria2 (#1031)
* fix(Shadowrocket): add missing bandwidth params for Hysteria2

Fixes a critical issue where Hysteria 2 silently downgrades to non-Brutal congestion control (BBR/Reno) on Shadowrocket clients.

* Refactor bandwidth parameters assignment

Update bandwidth parameters to only include positive values.

---------

Co-authored-by: Xboard <[email protected]>
2026-08-30 00:55:14 +08:00
muyichunandmuyichun 7cfe061469 fix: correct Alipay F2F request timestamp (#1024)
Co-authored-by: muyichun <[email protected]>
2026-08-30 00:42:46 +08:00
yootus c9ef5768e0 fix(order): calculate invitation commission after balance deduction (#1020)
Calculate invitation commission from the amount remaining after balance deductions, preventing duplicate commission on internally credited payments.
2026-08-30 00:39:20 +08:00
JW-3154 60ba57142b fix (General.php): VLESS parsing issue (#1017)
Replace urlencode with rawurlencode to prevent spaces from being improperly converted to '+' in node names (e.g., 'HKG 01' becoming 'HKG+01'). 

A tiny one-line change that significantly improves the UX.
2026-08-07 21:44:44 +08:00
xboard 8ecb762d77 fix(admin): keep ticket detail open after reply, etc. 2026-06-18 00:56:23 +08:00
JW-3154 6141430a88 Fix TUIC congestion control at Shadowrocket.php (#968)
Fixes an issue where the TUIC congestion_control parameter was not being passed to clients on Shadowrocket. This PR adds the missing parameter to the URL query string, fetching it from $protocol_settings with a default and safe fallback to 'cubic', ensuring panel configurations are properly respected by the client.
2026-06-06 11:11:01 +08:00
34bb1fdbcf Rename v2_order.refund_amount to surplus_credit (#967)
The old name was misleading — this column tracks surplus credit returned
to the user's internal balance during plan upgrades, not a payment
gateway refund. The new name aligns with the existing surplus_amount
and surplus_order_ids naming convention.

Co-authored-by: socksprox <[email protected]>
Co-authored-by: Cursor <[email protected]>
2026-06-02 11:49:58 +08:00
xboard 8f66a9af94 feat: add admin user plugin hooks
Added hooks:

- admin.user.fetch.query

- admin.user.transform

- admin.user.detail

- admin.user.update.rules

- admin.user.update.messages

- admin.user.update.params

- admin.user.update.before

- admin.user.update.after

- admin.user.secret.reset

- admin.user.destroy.before

- admin.user.destroy.after
2026-05-26 02:23:23 +08:00
xboard 4e9dfd6018 fix(security): harden registration email code validation 2026-05-22 22:05:33 +08:00
xboard 1eb085d4c0 fix(security): harden password reset email code validation 2026-05-22 21:52:34 +08:00
socksproxandsocksprox f2ac5db4bd feat(sing-box): include/exclude outbound tags with safe regex and fallback (#916)
- Add optional include/exclude patterns on selector/urltest outbounds (stripped before client)
- Safe preg_match: bare patterns use ~ delimiter with escape; delimited regex supported; invalid patterns logged, no throw
- Add fallback when filtering yields empty outbounds (string or ordered list: exact tag or pattern)
- Prevents broken routing when dynamic node sets match no filter

Made-with: Cursor

Co-authored-by: socksprox <[email protected]>
2026-05-03 10:06:30 +08:00
socksproxandsocksprox 689dc5ffa8 Fix redis ownership (#927)
Co-authored-by: socksprox <[email protected]>
2026-05-03 09:38:53 +08:00
Xboard d22a12cb34 Update Docker commands for V2board Dev migration 2026-04-30 00:49:52 +08:00
Xboard 449ccc3a1a Fix service names in v2board migration steps
Updated commands for database wipe and migration in v2board migration guide.
2026-04-30 00:49:37 +08:00
Xboard 42e5dac982 Update docker commands for migration to use xboard 2026-04-30 00:49:19 +08:00
Xboard e2e489e85e Modify upgrade command for older compose.yaml
Updated command for upgrading using older compose.yaml.
2026-04-25 20:43:35 +08:00
xboard 3b0b42c51d refactor(middleware): split V2 server middleware to drop node_type 2026-04-23 19:24:34 +08:00
xboard cf26ab3210 docs(upgrade): note pre-2026-04-19 compose upgrade command 2026-04-23 12:23:08 +08:00
xboard 382efe5aa5 fix(caddy): preserve X-Forwarded-For chain so Laravel TrustProxies resolves real client IP 2026-04-23 11:39:58 +08:00
xboard 0fa4b4e0fc fix(security): prevent payment gateway credentials leakage via OrderResource 2026-04-23 10:26:35 +08:00
xboard b8944e2341 fix(docker): re-apply www ownership to /www at entrypoint 2026-04-20 01:39:24 +08:00
xboard a7c7120d8a chore(docker): all-in-one redis no longer listens on TCP 2026-04-20 01:14:52 +08:00
xboard 0598351c10 fix: backfill utls for legacy vless reality nodes 2026-04-20 00:08:00 +08:00
Xboard f714767205 Update installation instructions for aapanel-docker 2026-04-19 23:33:32 +08:00
xboardandCopilot 66861500c3 fix(deploy): make install/update redis-independent and clean stale octane state
Co-authored-by: Copilot <[email protected]>
2026-04-19 23:23:27 +08:00
xboard 8379f1d1cd docs: update readme 2026-04-19 21:57:56 +08:00
xboard 3f82b00972 refactor: all-in-one docker deployment with auto-tuned resources and per-mode compose templates 2026-04-19 21:18:15 +08:00
xboard 135164056a fix: restore stripped protocol_settings fields for tuic/mieru/vmess 2026-04-19 00:45:47 +08:00
xboard a9cae6dc19 refactor: core plugins to plugins-core 2026-04-18 23:31:59 +08:00
xboard 4431641197 fix: unify Trojan server_name/allow_insecure to tls_settings across all protocols 2026-04-18 21:00:21 +08:00
xboard e0f41257db feat(admin): batch node-machine binding & frontend update 2026-04-18 19:38:31 +08:00
xboard 6be8137ed5 fix: commit composer.lock for reproducible Docker builds 2026-04-18 16:56:41 +08:00
xboard 8131bf4748 fix: ticket reply_status semantics, N+1 query, and admin reply auto-reopen 2026-04-18 16:40:21 +08:00
xboard 775590dc21 fix: Shadowrocket Trojan whitelist bug and xhttp support 2026-04-18 16:07:22 +08:00
xboard d406e440a7 feat: email template management with DB override, modern mail redesign 2026-04-18 15:41:23 +08:00
xboard a7fae4cc6d fix: batchUpdate use model instance to trigger observer 2026-04-18 04:26:25 +08:00
xboard f5ff15e415 fix: dedup device IPs, reset stale online_count on disconnect and scheduled cleanup (#886) 2026-04-18 02:57:55 +08:00
xboard 7652882fe5 feat: add xhttp subscriptions, network monitoring, chart legend toggle and ticket sender labels 2026-04-18 02:02:06 +08:00
xboard 8e35be3097 fix(plugin): improve plugin install and uninstall migration handling 2026-04-17 23:11:03 +08:00
xboard b9f3bc29dc fix: support both GET and POST for handshake endpoint (backward compatibility) 2026-04-17 20:59:48 +08:00
Xboard 2671cd3f2d Update installer URL to use 'dev' branch 2026-04-17 12:54:22 +08:00
xboard 83b43e8664 feat: show install command on machine creation 2026-04-17 06:47:05 +08:00
xboard 6796b70179 feat: machine mode, ECH subscriptions, batch ops & security hardening 2026-04-17 03:02:53 +08:00
yootus 299a69cd51 QuantumultX下发Anytls节点 (#880)
QuantumultX最新版本支持Anytls了,做适配
2026-04-16 19:31:24 +08:00
xboard a0f6b324a4 fix: reset traffic stats when copying server nodes 2026-04-11 20:24:43 +08:00
Valentin Lobstein cf5cece77f Fix: CVE-2026-39912 - Magic link token leak in loginWithMailLink (#873)
The loginWithMailLink endpoint returns the magic login link in the
HTTP response body, allowing unauthenticated account takeover.

The fix returns true instead of the link. The email delivery is
the authentication factor.

Bug inherited from V2Board commit 9b707aaf (2022-06-27).
2026-04-10 02:44:20 +08:00
xboard 9c03a344f9 fix(update): avoid duplicate safe.directory entries for repo and admin submodule 2026-04-09 20:31:19 +08:00
xboard 5f0af1290c docs: add donation section 2026-04-09 00:21:28 +08:00
xboard f7118ab0bd fix: stop sending VLESS decryption when encryption is disabled 2026-04-08 11:05:55 +08:00
yootus 7af8d3be47 Loon和Surfboard适配anytls (#854)
* Loon适配anytls

* Surfboard适配anytls

Surfboard适配anytls
2026-04-02 15:47:41 +08:00
NFamou 06ff341290 Merge pull request #856 from NFamou/master
支持Surfboard下发SS2022
2026-04-02 15:46:55 +08:00
xboard 8e83143721 updata admin asset 2026-04-02 05:51:16 +08:00
Xboard 076370c3d3 Merge pull request #841 from cedar2025/revert-755-feat/server-id-stat-user
Revert "feat: Track user traffic per node (server_id)"
2026-03-30 18:18:35 +08:00
Xboard f0af3b6832 Revert "feat: Track user traffic per node (server_id)" 2026-03-30 18:17:27 +08:00
xboard 8ebc9e76d0 Remove duplicate doc files 2026-03-30 18:04:41 +08:00
xboard de7701066c fix: remove 2026_03_28_050000_lowercase_existing_emails.php 2026-03-30 17:59:39 +08:00
xboard 209e862374 feat: add Vless Encryption support 2026-03-30 17:03:37 +08:00
Xboard 0ea23b24c9 Merge pull request #755 from socksprox/feat/server-id-stat-user
feat: Track user traffic per node (server_id)
2026-03-30 13:55:11 +08:00
Xboard df4e143cf5 Merge pull request #689 from socksprox/fix-user-generation-multiple-prefix
Fix user generation with email_prefix to support multiple users
2026-03-30 13:32:46 +08:00
Xboard da3fa92e6d Merge pull request #786 from lithromantic/master
Add sha256salt hashing option in password verification
2026-03-30 13:05:39 +08:00
xboard 22a5b2b03c update 2026_03_28_161536_add_traffic_fields_to_servers.php 2026-03-30 02:58:09 +08:00
xboard 1e7fa93f99 feat: node traffic limit & batch operations
- Traffic monitoring with transfer_enable limit
- Batch delete nodes
- Reset traffic (single/batch)
2026-03-30 02:50:56 +08:00
xboard dbfb2f1376 fix: escape Telegram Markdown special characters 2026-03-30 01:46:56 +08:00
xboard 7cd1fb185b Revert "fix: escape Telegram Markdown special characters (fix #450)"
This reverts commit e10ec47140.
2026-03-29 17:48:49 +08:00
lithromantic cafc6902d6 Merge branch 'cedar2025:master' into master 2026-03-29 00:00:34 +01:00
Xboard ed6ffbd878 Merge pull request #832 from Dlphine/fix/raw-array-access-data-get
fix: replace raw array access with data_get() to prevent Undefined array key
2026-03-28 17:38:44 +08:00
xboard 457dfeb0e9 fix: use getHost() for proper host comparison in safe mode 2026-03-28 15:52:25 +08:00
xboard e10ec47140 fix: escape Telegram Markdown special characters (fix #450) 2026-03-28 09:10:54 +08:00
xboard a8aee3e992 feat: revoke other sessions when changing password (fix #414) 2026-03-28 08:31:24 +08:00
xboard a2ffaf2ac8 fix: add ru-RU.json 2026-03-28 07:44:43 +08:00
xboard b19ae5c581 fix: iOS Safari autofill not filling email field (Fixes #330) 2026-03-28 07:41:57 +08:00
xboard 7af0764031 feat: implement email case-insensitive queries (fix #318) 2026-03-28 07:09:21 +08:00
Dlphine 62981bc2e8 fix: replace raw array access with data_get() to prevent Undefined array key
- Migrate $protocol_settings['key'] to data_get($protocol_settings, 'key') across General, SingBox, Shadowrocket, Surfboard, QuantumultX
- Prevents PHP 8 Undefined array key fatal errors when optional protocol_settings fields are missing
- Same class of bug that caused #735
2026-03-27 13:51:28 +08:00
xboard 3659d9f784 feat: add Russian language support and remove v2board theme 2026-03-26 23:35:30 +08:00
xboard c8ef04d55f fix: use ServerService::getServer() for node lookup in WebSocket 2026-03-26 03:51:58 +08:00
xboard b9276470eb fix: resolve device sync issues and refactor WebSocket server 2026-03-26 03:33:01 +08:00
xboard b487d6c561 refactor: restructure device limit system 2026-03-25 17:50:16 +08:00
xboard d179f49bbb feat: ws notify nodes when user traffic is exhausted 2026-03-25 01:44:55 +08:00
xboard 8b776b1ea1 feat: Trojan Reality support and protocol distribution optimizations 2026-03-23 14:56:41 +08:00
xboard 8c8c55e2bc update admin assets submodule 2026-03-23 11:00:31 +08:00
xboard f289e48cc5 fix: intval u/d to avoid bigint overflow (#821) 2026-03-22 19:13:07 +08:00
Xboard 75d3b254be Merge pull request #789 from socksprox/feat/or-filter-logic
feat: Add OR logic support to user fetch API filters
2026-03-21 07:49:03 +08:00
xboard 8137a11008 feat: Add admin bulk-mail placeholder variables and template rendering 2026-03-19 05:02:16 +08:00
xboard 63f5080006 fix(runtime): force app_url/force_https per-request via middlewar 2026-03-19 04:22:17 +08:00
xboard 656539963f fix(compose): use named volume for redis socket 2026-03-17 22:50:29 +08:00
xboard 4628a3bc62 fix(admin): fix giftcard form validation and template creation issues 2026-03-17 18:35:21 +08:00
xboard 64f78599e9 fix(admin): fix node manage tooltip error 2026-03-17 14:13:48 +08:00
Xboard e6a2b9facc Add port mapping for 1panel service 2026-03-17 13:16:43 +08:00
xboard 287302729f fix: fix brutal-opts configure for clashMeta 2026-03-17 12:26:10 +08:00
xboard da84eec1b8 fix(admin): resolve translation key issues 2026-03-17 11:44:17 +08:00
xboard 57a81046ff fix:Fix DynamicForm default value sync, payment unit conversion, advanced config tabs, AnyTLS translation, and UI overlap issues. Fixed #807 2026-03-17 03:21:27 +08:00
Xboard bb91062911 Add ws-server service configuration to 1panel.md 2026-03-17 02:36:21 +08:00
xboard 6b1256d88f fix(admin): fix order assign 2026-03-17 00:54:26 +08:00
xboard 2e4bfe08df feat: Refactor uTLS & Multiplex Support, Node Status Push Optimization
- Server/ServerSave/Server.php: Unified utls and multiplex schema, validation, and defaults for vmess/vless/trojan/mieru protocols, enabling more flexible protocol configuration.
- Protocols (SingBox/ClashMeta/Shadowrocket/Stash/General): All protocol generators now support utls (client-fingerprint/fp) and multiplex options. Removed getRandFingerprint, replaced with getTlsFingerprint supporting random/custom fingerprints.
- Helper.php: Refactored TLS fingerprint utility to support object/string/random input.
- ServerService: Abstracted updateMetrics method to unify HTTP/WS node status caching logic.
- NodeWebSocketServer: Improved node connection, status push, and full sync logic; adjusted log levels; clarified push logic.
- ServerController: Reused ServerService for node metrics handling, reducing code duplication.
- Docs: Improved aapanel installation docs, added fix for empty admin dashboard.
2026-03-16 23:09:56 +08:00
Xboard 18b06287a7 Fix environment variable declaration in Dockerfile. #806 2026-03-16 20:28:18 +08:00
xboard d6986a4493 fix: correct node_sync queue assignment in horizon 2026-03-16 02:28:28 +08:00
xboard edbe7ce99c update admin assets 2026-03-15 15:46:44 +08:00
xboard 178488425b fix(admin): fix 2026-03-15 14:10:05 +08:00
xboard 2bc4c98be6 feat(ClashMeta): enhance Shadowsocks plugin support 2026-03-15 11:36:43 +08:00
xboard 3e8284cf70 refactor: rename ws-server command and update configuration 2026-03-15 10:57:21 +08:00
xboard dbcf90927b fix(ws): enabel unix socket support for redis connection 2026-03-15 10:47:31 +08:00
xboard 56fc085daf ci: remove image signing 2026-03-15 10:28:49 +08:00
xboard ff30088f8a fix: missing ws-server core and update routine 2026-03-15 10:20:42 +08:00
xboard d92c32fab5 feat: introduce WebSocket sync for XBoard nodes
- Implement Workerman-based `xboard:ws-server` for real-time node synchronization.
- Support custom routes, outbounds, and certificate configurations via JSON.
- Optimize scheduled tasks with `lazyById` to minimize memory footprint.
- Enhance reactivity using Observers for `Plan`, `Server`, and `ServerRoute`.
- Expand protocol support for `httpupgrade`, `h2`, and `mieru`.
2026-03-15 09:49:11 +08:00
xboard 8066af5bf8 refactor: rewrite default clash rules with KEYWORD-based routing 2026-03-12 13:11:04 +08:00
xboard 90a5065162 refactor: rewrite restoreProtectedPlugins to use file copy instead of git
- Dockerfile: backup plugins/ to /opt/default-plugins/ at build time
- Replace exec/git-based restore with pure PHP File::copyDirectory()
- Only restore plugins defined in Plugin::PROTECTED_PLUGINS
- Delete target directory before copy to prevent stale files
- Remove function_exists('exec') guard (no longer needed)
2026-03-11 08:30:12 +08:00
xboard b4b2d44223 fix: configure SQLite WAL mode and busy_timeout to prevent database locked errors
- Enable WAL journal mode for concurrent read/write support
- Set busy_timeout to 30s to wait on locks instead of failing immediately
- Set synchronous to normal for better write performance

Fixes #770
2026-03-11 07:56:27 +08:00
xboard 662e1343d2 feat: add configurable ticket_must_wait_reply setting 2026-03-11 07:31:09 +08:00
xboard 627281f9e6 perf: fix getTrafficRank slow query with index and batch loading 2026-03-11 07:01:19 +08:00
xboard 76edd15186 refactor: replace database logging with file logging and admin audit log 2026-03-11 06:50:07 +08:00
xboard 2b2a51e73b refactor: move subscribe templates to dedicated database table 2026-03-11 05:47:29 +08:00
xboard 0a662cb456 Use submodule for admin assets 2026-03-11 04:52:06 +08:00
xboard ac8283a7bf feat(config): support custom telegram webhook url 2026-03-11 02:50:33 +08:00
xboard e355f2b61a fix(register): handle invalid invite code as API error (#792) 2026-03-11 02:09:25 +08:00
xboard b20d12d510 feat(surge): add SS2022, SOCKS5, HTTP support 2026-03-09 07:32:51 +08:00
xboard 48fd340b0b fix: apply device_limit from plan when assigning via gift card (#630) 2026-03-09 06:51:10 +08:00
xboard 6f860c784a fix: return dynamic rate instead of base rate in user server list (#709) 2026-03-09 06:47:30 +08:00
xboard cadfefbbdd fix: always set uTLS fingerprint for TLS connections in General protocol (#673) 2026-03-09 06:45:28 +08:00
xboard 7ecd549042 fix: validate random_int parameters in Helper::randomPort to prevent min > max error 2026-03-09 06:32:10 +08:00
xboard 6db54d904b fix(stash): correct TCP/HTTP network type handling in node generation 2026-03-09 05:39:51 +08:00
Xboard 928e051415 Merge pull request #681 from superabbite1/master
Update General.php v2rayN新增tuic协议订阅,vless+ws+tls协议新增fingerprint指纹参数
2026-03-09 05:04:50 +08:00
Xboard 215502070b Merge pull request #703 from kuizw9/master
Fix General.php for support AnyTLS and Shadowrocket.php for support Socks Node Name Display
2026-03-09 05:02:07 +08:00
Xboard 4c1019959b Merge pull request #655 from JxQg/jxq_dev
Feat: Support VLESS node output for Loon protocol, improve buildVless method template
2026-03-09 04:59:20 +08:00
Xboard 8d5ead43ac Merge pull request #734 from kelly5454/master
fix: Type error when redeeming gift card
2026-03-09 04:56:14 +08:00
xboard 7f5c5d761a chore: optimize default.clash.yaml template 2026-03-09 03:51:54 +08:00
xboard 8d25dd643a feat: add AnyTLS protocol support for Surge 2026-03-09 02:37:32 +08:00
socksprox fbc85f298b Make querying users better with "or" statements 2026-01-28 01:27:21 +01:00
lithromantic 8a93d3f1a4 Add sha256salt hashing option in password verification 2026-01-18 00:04:00 +01:00
xboard 4b7e3e7300 fix: read plugin enabled from DB for consistency 2026-01-02 18:30:21 +08:00
xboard aa8cbeac0a fix(admin): guard unknown order status 2025-12-18 00:57:59 +08:00
socksprox acee3a2241 do not return strings, but int 2025-11-29 17:05:07 +01:00
socksprox c592543394 again: update api combining times 2025-11-29 17:05:07 +01:00
socksprox 5ce07d7091 Revert "Combine data with node_id in api output, so its all still "one day", and fits vanilla xboard behaviour"
This reverts commit de39230cbe111bbf793f11bcf5046ef717c67f87.

The api change caused issues
2025-11-29 17:05:07 +01:00
socksprox 47f235dffa Combine data with node_id in api output, so its all still "one day", and fits vanilla xboard behaviour 2025-11-29 14:07:10 +01:00
socksprox 2d7f70d5fb fix: do not merge traffic from different nodes 2025-11-29 13:47:21 +01:00
socksprox d046028bac User traffic can now be viewed by node 2025-11-29 13:47:15 +01:00
kuizw9 26bc181608 Merge branch 'cedar2025:master' into master 2025-11-23 14:55:14 +08:00
xboard 7801a0fb19 feat: add v2node support 2025-11-22 20:33:38 +08:00
xboard af431d178e fix: preserve theme config when upgrading theme 2025-11-07 19:25:40 +08:00
kelly5454 e26677813c fix: exchange gift card type error 2025-10-30 21:08:39 +08:00
xboard 4d27cdccc1 feat(admin): add Custom ID/Original ID display with copy actions 2025-10-20 21:46:26 +08:00
xboard fc685ae9b5 feat(plugin): auto-decode JSON config values by type in PluginManager 2025-10-20 18:56:44 +08:00
xboard b16a288c55 fix(telegram): correct traffic usage description in notification 2025-10-08 10:26:26 +08:00
KuizW9 23c3ebcf4b Update General.php
Add AnyTLS to General Client
2025-10-05 22:34:36 +08:00
KuizW9 dad248a9f8 Merge branch 'cedar2025:master' into master 2025-10-05 22:32:48 +08:00
xboard a47f145c90 feat(telegram plugin): improve Telegram notification formatting 2025-09-27 16:53:17 +08:00
KuizW9 2c38d30a94 Merge branch 'cedar2025:master' into master 2025-09-27 08:52:25 +08:00
xboard 245ddc56e7 fix: avoid getCurrentCommit on cache hit 2025-09-26 19:04:17 +08:00
xboard 9ef40d4918 allow free plans 2025-09-24 22:19:04 +08:00
KuizW9 160db350da Update Shadowrocket.php 2025-09-24 19:14:34 +08:00
xboard 17b671c87e fix(jobs): resolve PostgreSQL issue in StatServerJob and StatUserJob 2025-09-23 18:57:44 +08:00
xboard 8176afb073 fix(plugin): remove stale plugin records when files missing; adjust logging 2025-09-23 14:59:22 +08:00
xboard c9fbd24c58 fix: remove smogate 2025-09-22 22:52:11 +08:00
xboard 7f96171128 Remove Smogate plugin 2025-09-22 18:47:25 +08:00
xboard 221784367e feat(knowledge): add KnowledgeResource with plugin hooks
- Add KnowledgeResource with user.knowledge.resource hook
- Unify processKnowledgeContent for both single and list items
- Remove isListItem parameter for cleaner architecture
2025-09-20 13:36:10 +08:00
xboard 34a9ed0fce feat(plugin): add user.subscribe.response hook 2025-09-17 00:02:59 +08:00
xboard 471ec94ae3 fix 2025-09-16 18:44:44 +08:00
socksprox 3e0deed576 Make that user batch generation works again 2025-09-15 15:43:43 +02:00
xboard 895f940849 refactor(online-status): consolidate updates and add cleanup command 2025-09-15 20:32:22 +08:00
xboard ebea3e8b8c feat(middleware): Add transaction state guard for Octane 2025-09-15 16:15:39 +08:00
xboard cf99d4372e refactor(Jobs): Optimize traffic statistics jobs with upsert 2025-09-15 09:56:36 +08:00
xboard 28f11e30af fix(server): Correct node_info retrieval method 2025-09-15 09:21:20 +08:00
xboard 190f81c12c fix: resolve vmess http-opts headers null issue in subscription generation 2025-09-12 10:45:31 +08:00
superabbite1 5521746509 Update Shadowrocket.php
新增Vless+ws+tls协议 Fingerprint指纹参数
2025-09-09 16:43:42 +08:00
superabbite1 4fa311dc87 Update ClashMeta.php
新增vless+ws+tls协议Fingerprint指纹参数
2025-09-09 16:42:11 +08:00
superabbite1 857c6c5a83 Update General.php
vless+ws+tls协议新增fingerprint指纹参数;v2rayN新增tuic协议订阅
2025-09-09 11:35:44 +08:00
xboard d426eef1cd fix(epay): allow custom payment types via string input
- Replace select dropdown with string input for `type`
2025-09-05 16:16:30 +08:00
xboard 058a5c789b feat(shadowrocket): support VLESS transports httpupgrade/xhttp/kcp
- Add parsing for httpupgrade, xhttp, and kcp in Shadowrocket VLESS builder
- Ensure correct obfs/path/host/mode mapping for Shadowrocket compatibility
2025-09-05 15:22:46 +08:00
xboard 50defe9d73 fix: remove dependency on job_batches table for batch email sending 2025-09-02 23:54:21 +08:00
xboard ff120ac53f fix: prevent null pointer exception in knowledge fetch 2025-09-01 21:15:40 +08:00
xboard 989b471bec feat: add force traffic reset to update script 2025-08-31 20:50:34 +08:00
xboard 5eb2429332 feat: add force option to reset traffic command 2025-08-31 20:38:09 +08:00
xboard 371fd791ac fix: improve date calculation for month-end reset schedules 2025-08-31 20:30:02 +08:00
Xboard 5b649ac14f Merge pull request #658 from xcxnig/patch-2
fix(order): correct renewal handling for onetime plan
2025-08-30 03:15:06 +08:00
Miku 69637949ce fix(order): correct renewal handling for onetime plan
fixes onetime plan renewal logic
2025-08-29 23:24:48 +08:00
xboard 46fef609dd fix: correct getAvailableUsers call to use (Server) 2025-08-29 20:50:55 +08:00
xboard 4f7f3d7168 feat: optimize server.user.get hook definition 2025-08-29 19:21:49 +08:00
Xboard 1edc401ca0 Rename docker-compose.yml to compose.yaml 2025-08-29 01:55:34 +08:00
JxQggg 03c61bfe38 feat(protocols): support VLESS node output, improve buildVless method template
- Added Server::TYPE_VLESS to Loon::$allowedProtocols
- handle() method now supports VLESS node output
- buildVless() method supports all mainstream VLESS parameter templates, including reality/xtls-rprx-vision
2025-08-26 12:27:38 +08:00
xboard 19caedb730 fix(subscribe): fix vmess+tcp+http subscription in general and singbox 2025-08-24 18:39:00 +08:00
xboard e07694a694 fix(subscribe): fix vmess+tcp+http subscription in Clash and Clash Meta 2025-08-24 18:07:36 +08:00
xboard 7eb8565c6d fix(payment): add AlipayF2F libraty file 2025-08-24 17:04:16 +08:00
xboard c13daf4bfd fix: handle disable exec funtion in install script 2025-08-23 19:32:32 +08:00
xboard 72ead1cf8f fix: support resources/views directory for plugin views 2025-08-23 15:26:09 +08:00
xboard 3fbf178630 feat(admin): add user details dialog and fix editor resize bug 2025-08-23 15:12:30 +08:00
Xboard e64afe75bc Merge pull request #603 from OfficialKatana/patch-3
Add missing extension
2025-08-23 11:28:46 +08:00
xboard 802c151c40 refactor(singbox): use data_get for array access 2025-08-23 11:19:37 +08:00
xboard 20474add2e docs: add plugin development document 2025-08-23 00:25:09 +08:00
xboard 2412b266b7 fix: optimize batch email performance and fix gift card issues
- Add chunking and batching for admin email sending
- Fix gift card pagination and add per_page limits
- Update frontend prompts and complete language packs
2025-08-23 00:11:45 +08:00
xboard 10e36bd11f fix(tickets): prevent ApiException logging in ticket creation API 2025-08-21 19:13:14 +08:00
xboard 95c5a6e94c fix(auth): handle null redirect in quick login url 2025-08-21 18:57:19 +08:00
Xboard cf22f6379d Merge pull request #595 from swcoffee/master
fix: missing field 'version' when distributing tuic protocol in stash
2025-08-21 18:10:04 +08:00
Xboard 0b3263756d Merge pull request #638 from zytakeshi/fix/singbox-sni-domain-issue
fix: correct SNI domain configuration paths in SingBox protocol
2025-08-21 18:07:53 +08:00
xboard c8f8667f82 fix: fix return type in transferToGB method 2025-08-20 04:13:52 +08:00
zytakeshi 7f439c4cde Update SingBox.php
fix Vmess
2025-08-16 03:21:17 +09:00
Takeshi Matsumoto c7483a67d2 fix: correct VMess TCP transport configuration in SingBox protocol
- Only add HTTP transport when network_settings.header.type is not 'none'
- Use pure TCP (null transport) when header type is 'none' or unset
- Align with General protocol implementation and VMess specification

This prevents unnecessary HTTP transport layer when using pure TCP.
2025-08-16 03:08:56 +09:00
Takeshi Matsumoto ca8f904121 fix: correct SNI domain configuration paths in SingBox protocol
- Fix Trojan protocol to use 'server_name' instead of 'tls_settings.server_name'
- Fix Hysteria protocol to use 'tls.server_name' instead of 'tls_settings.server_name'
- Align with Server model configuration and General protocol implementation
- Resolves missing SNI domains in sing-box configuration generation

This fixes the inconsistency where SNI domains were missing for certain
protocols while working correctly in General protocol handler.
2025-08-16 02:44:17 +09:00
xboard f53c064f76 fix: fix Alipay face-to-face payment form display issues 2025-08-08 03:17:05 +08:00
xboard adc8b61359 fix: fix user expiration date display and update issues
- Fix 1970 year display for unlimited validity users
- Resolve SQL error in user update endpoint
- Closes #625
2025-08-08 03:04:44 +08:00
xboard 43d5bb11cc fix: resolve Telegram ticket notification issue 2025-08-08 02:53:44 +08:00
Xboard 498ba709fa Merge pull request #612 from xcxnig/patch-1
fix(stash): fix Flow network and SNI issues
2025-08-08 02:44:58 +08:00
Miku 859ad0b529 fix(stash): fix Flow network and SNI issues 2025-08-02 02:07:29 +08:00
Katana 56bba44281 Add missing extension
Fix: Call to undefined function Illuminate\Support\mb_split()
2025-07-30 16:52:01 +08:00
xboard fe4f8d5875 fix: change user default_at to 0 2025-07-27 08:11:42 +08:00
xboard 8b019057f5 fix: correct errors in database migration file 2025-07-27 08:00:49 +08:00
xboard 06cffa32b4 feat: add plugin migrations and fix plan management bugs
- Plugin database migration support
- Fix empty prices error in plan management
- Plugin update functionality
- Custom shadowsocks encryption algorithms
2025-07-27 00:19:14 +08:00
xboard 5b8cf681f9 feat: enhance plugin management
- Add command support for plugin management
- Optimize plugin management page layout
- Add email copy functionality for users
- Convert payment methods and Telegram Bot to plugin system
2025-07-26 18:49:58 +08:00
swcoffee bd47a06863 fix: missing field 'version' when distributing tuic protocol in stash
stash下发tuic协议时缺少version字段,会导致订阅无法使用
2025-07-26 13:46:54 +08:00
xboard dc5a6326a4 update composer.yaml 2025-07-23 16:47:48 +08:00
xboard 44486adb46 fix: announcement sorting issue 2025-07-22 04:28:39 +08:00
xboard d9b290b0f4 fix: make subscribe url cofig changes take effect immediately under octane 2025-07-22 03:25:13 +08:00
xboard 5f3b92adde fix(theme): qx import issue and long title display 2025-07-22 02:01:46 +08:00
xboard 89ed4a54d9 fix: sub link types not working 2025-07-22 01:33:59 +08:00
xboard abd549c3e2 fix: correct return_url generation for payment in frontend-backend separated deployment 2025-07-21 23:54:00 +08:00
xboard a0e09f1c3a fix: align user action buttons, add json/yaml support for plugin config, improve formatTrafficSize, show processed commission
- Aligned user action buttons in dropdown for consistent UI.
- Added JSON and YAML support in plugin config form with Monaco Editor and resizable height.
- Improved formatTrafficSize to handle large numbers and prevent undefined units.
- Order detail now shows commission info when commission_status is 1 or 2.
2025-07-21 23:52:07 +08:00
xboard dcd1d64bbd feat: add multiple hooks, pligun schedule support ,add hook:list artisan command 2025-07-21 13:29:17 +08:00
xboard b3a69bcd60 fix: gift card redemption limits validation 2025-07-21 09:28:00 +08:00
xboard 1493fe18eb fix: resolve issue where dynamic rate cannot be disabled 2025-07-21 08:29:14 +08:00
xboard 05e8feedfb fix: resolve theme refresh issue after updates 2025-07-21 08:27:41 +08:00
xboard 9cc512eb8d fix: resolve traffic reset time generation and refactor reset logic
- Add fix-null mode to ResetTraffic command
- Refactor reset logic for better separation of concerns
- Update migration to reuse fix functionality
2025-07-19 14:22:01 +08:00
xboard b1f15995b6 refactor: rename hook form traffic.before_process to traffic.process.before 2025-07-18 23:39:19 +08:00
xboard 7fc913e853 refactor: refactor subscription delivery logic, change payment return_url to origin_url concatenation
- Unify protocol filter configuration to client.type.field (dot-path, three-segment) format, support strict whitelist mode
- Refactor AbstractProtocol and all protocol classes for more flexible and maintainable subscription delivery
- Change payment callback logic: use origin_url concatenation instead of return_url for more accurate redirects
2025-07-18 15:42:58 +08:00
xboard f2fbcc86d8 feat(hook): add order.create.after, order.open.before, order.open.after, and protocol.servers.filtered hooks 2025-07-17 12:34:31 +08:00
xboard 480e6162cb feat: consider remaining traffic in surplus calculation when resetting traffic on plan change 2025-07-17 12:13:03 +08:00
xboard ac77a73098 refactor: optimize surplus value calculation for plan deduction 2025-07-17 11:32:34 +08:00
xboard cd6b07e655 style(theme): announcement carousel content and set full-width background 2025-07-16 11:03:07 +08:00
xboard b2c02e0fab feat(plugin hook): add client.subscribe.unavailable hook 2025-07-16 00:08:30 +08:00
xboard 305108061e fix: fix Redis RDB snapshot permission error 2025-07-15 23:09:38 +08:00
xboard 36f0704360 fix: theme switch service 2025-07-15 20:50:04 +08:00
Xboard 48d9568f3d Merge pull request #558 from Hei-XiaoHu/update-memory-limit
Increase Horizon memory_limit to prevent container memory exhaustion
2025-07-15 03:23:55 +08:00
xboard 170923bad5 chore: code style and type declaration improvements 2025-07-15 02:55:58 +08:00
xboard 5a86c46ab9 feat: improve traffic reset precision and admin features
- Increase traffic reset granularity to seconds
- Add next reset time display in admin pane
2025-07-15 02:18:33 +08:00
xboard 6ac0cc7ce5 feat: support theme update and various improvements
- Add support for updating themes if a newer version is uploaded
- Hide config button for plugins without configuration items
- Auto refresh theme cache after panel update
- Fix issue where user used traffic cannot be set as a decimal
- Fix subscription issue for shadowrocket in v2board theme
2025-07-15 01:26:14 +08:00
xboard 342dc9df5a fix(admin): handle null rate_time_ranges when editing server nodes to prevent 500 error 2025-07-14 10:19:08 +08:00
xboard da9b62b1d6 fix(i18n): correct traffic unit display for gift card template rewards 2025-07-14 00:39:54 +08:00
xboard c80dd82558 feat: multiple improvements and bug fixes
- Add gift card redemption feature
- Resolve custom range selection issue in overview
- Allow log page size to be modified
- Add subscription path change notification
- Improve dynamic node rate feature
- Support markdown documentation display for plugins
- Reduce power reset service logging
- Fix backend version number not updating after update
2025-07-14 00:33:04 +08:00
xboard 939d1c2b65 fix(register): handle invalid invite code gracefully
Fix an issue where entering a non-existent invite code during registration would result in an unclear HTTP code 0 error. Now, the system properly validates the invite code and returns a clear error response if the code does not exist.
2025-07-13 21:19:33 +08:00
xboard c95448b4b0 feat: add plugin update support + fix bugs 2025-07-13 08:53:00 +08:00
xboard a7192493bb fix(plugin): auto-remove plugin record if class file is missing 2025-07-12 21:54:12 +08:00
xboard 413e24c7bd remove redundant and unused payment methods 2025-07-12 03:43:39 +08:00
xboard 613c769e42 feat: Add client.subscribe.servers hook for plugin-based server extension
- Add HookManager::filter('client.subscribe.servers') hook in ClientController::subscribe()
- Allow plugins to inject custom servers into subscription responses
- Update protocol classes to support extended server configurations
- Enable dynamic server list modification before protocol processing
2025-07-11 21:19:23 +08:00
xboard 4615719f39 fix(subscribe): Disable anytls protocol for Stash client 2025-07-11 08:48:02 +08:00
xboard 306d94a817 feat: update plugin/config api 2025-07-09 18:07:38 +08:00
xboard ebd0d3c632 fix: Subscription filter not working when using types=all parameter 2025-07-07 03:14:21 +08:00
xboard 90cfaf3457 Fix: Handle raw DB expressions in user filter
A TypeError occurred when filtering the user list by the `total_used` computed attribute. The `applyQueryCondition` method expected a string for the field name, but received an `Illuminate\Database\Query\Expression` object from `DB::raw`.

This commit updates the `buildFilterQuery` method to check if the query field is an `Expression` instance. If so, it now uses `whereRaw` to apply the filter, preventing the type error and enabling filtering on computed fields. For standard string fields, it continues to use the original `applyQueryCondition` logic.Fix: Handle raw DB expressions in user filter

A TypeError occurred when filtering the user list by the `total_used` computed attribute. The `applyQueryCondition` method expected a string for the field name, but received an `Illuminate\Database\Query\Expression` object from `DB::raw`.

This commit updates the `buildFilterQuery` method to check if the query field is an `Expression` instance. If so, it now uses `whereRaw` to apply the filter, preventing the type error and enabling filtering on computed fields. For standard string fields, it continues to use the original `applyQueryCondition` logic.Fix: Handle raw DB expressions in user filter

A TypeError occurred when filtering the user list by the `total_used` computed attribute. The `applyQueryCondition` method expected a string for the field name, but received an `Illuminate\Database\Query\Expression` object from `DB::raw`.

This commit updates the `buildFilterQuery` method to check if the query field is an `Expression` instance. If so, it now uses `whereRaw` to apply the filter, preventing the type error and enabling filtering on computed fields. For standard string fields, it continues to use the original `applyQueryCondition` logic.Fix: Handle raw DB expressions in user filter

A TypeError occurred when filtering the user list by the `total_used` computed attribute. The `applyQueryCondition` method expected a string for the field name, but received an `Illuminate\Database\Query\Expression` object from `DB::raw`.

This commit updates the `buildFilterQuery` method to check if the query field is an `Expression` instance. If so, it now uses `whereRaw` to apply the filter, preventing the type error and enabling filtering on computed fields. For standard string fields, it continues to use the original `applyQueryCondition` logic.Fix: Handle raw DB expressions in user filter

A TypeError occurred when filtering the user list by the `total_used` computed attribute. The `applyQueryCondition` method expected a string for the field name, but received an `Illuminate\Database\Query\Expression` object from `DB::raw`.

This commit updates the `buildFilterQuery` method to check if the query field is an `Expression` instance. If so, it now uses `whereRaw` to apply the filter, preventing the type error and enabling filtering on computed fields. For standard string fields, it continues to use the original `applyQueryCondition` logic.Fix: Handle raw DB expressions in user filter

A TypeError occurred when filtering the user list by the `total_used` computed attribute. The `applyQueryCondition` method expected a string for the field name, but received an `Illuminate\Database\Query\Expression` object from `DB::raw`.

This commit updates the `buildFilterQuery` method to check if the query field is an `Expression` instance. If so, it now uses `whereRaw` to apply the filter, preventing the type error and enabling filtering on computed fields. For standard string fields, it continues to use the original `applyQueryCondition` logic.Fix: Handle raw DB expressions in user filter

A TypeError occurred when filtering the user list by the `total_used` computed attribute. The `applyQueryCondition` method expected a string for the field name, but received an `Illuminate\Database\Query\Expression` object from `DB::raw`.

This commit updates the `buildFilterQuery` method to check if the query field is an `Expression` instance. If so, it now uses `whereRaw` to apply the filter, preventing the type error and enabling filtering on computed fields. For standard string fields, it continues to use the original `applyQueryCondition` logic.Fix: Handle raw DB expressions in user filter

A TypeError occurred when filtering the user list by the `total_used` computed attribute. The `applyQueryCondition` method expected a string for the field name, but received an `Illuminate\Database\Query\Expression` object from `DB::raw`.

This commit updates the `buildFilterQuery` method to check if the query field is an `Expression` instance. If so, it now uses `whereRaw` to apply the filter, preventing the type error and enabling filtering on computed fields. For standard string fields, it continues to use the original `applyQueryCondition` logic.Fix: Handle raw DB expressions in user filter

A TypeError occurred when filtering the user list by the `total_used` computed attribute. The `applyQueryCondition` method expected a string for the field name, but received an `Illuminate\Database\Query\Expression` object from `DB::raw`.

This commit updates the `buildFilterQuery` method to check if the query field is an `Expression` instance. If so, it now uses `whereRaw` to apply the filter, preventing the type error and enabling filtering on computed fields. For standard string fields, it continues to use the original `applyQueryCondition` logic.
2025-07-05 12:35:12 +08:00
xboard 2d1d8e1916 fix(setting): Resolve admin_setting helper incompatibility with Octane
Updated the `admin_setting` and `admin_settings_batch` helpers to retrieve the `Setting` instance from the service container. This fixes a fatal error and ensures correct behavior in a Laravel Octane environment by preventing the use of stale, shared static instances.
2025-07-04 22:16:19 +08:00
Xiaohu Hei a3e384c2db Increase Horizon memory_limit configuration from 32MB to 64MB to support higher workload 2025-07-02 02:12:47 +08:00
xboard 03a55bdd77 feat: add tags to plans, refactor order service, adn fix ticket lock 2025-07-01 11:14:18 +08:00
xboard 0863277424 feat: add PostgreSQL support and refactor database configuration in install command 2025-07-01 03:09:53 +08:00
xboard 40290b6496 feat: add socks protocol support for shadowrocket client 2025-07-01 00:49:55 +08:00
xboard aebd746060 feat: plugin controller config system with guest_comm_config hook integration
- Add HasPluginConfig trait and PluginController base class
- Integrate guest_comm_config hook in CommController for plugin frontend config injection
- Add user creation functionality to UserService and fix null value handling
- Enhance AbstractPlugin.getConfig() with key parameter support
- Multiple service layer optimizations and architecture improvements
2025-06-29 01:42:48 +08:00
xboard c414143997 docs: update issue template 2025-06-28 18:16:10 +08:00
xboard 669eef6569 eat: add reCAPTCHA v3 and Cloudflare Turnstile verification support
- Implement reCAPTCHA v3 with score-based validation
- Add Cloudflare Turnstile as captcha alternative
- Create reusable CaptchaService for unified validation
- Support switching between recaptcha, recaptcha-v3, and turnstile
- Maintain backward compatibility with existing configurations
2025-06-28 18:01:59 +08:00
xboard 8b9113e0cc docs: update docs 2025-06-28 15:54:44 +08:00
xboard bd118bb526 fix: admin export subscription link issue 2025-06-24 22:55:34 +08:00
xboard f7c373bae7 remove: disable traffic package stacking feature 2025-06-24 02:00:12 +08:00
xboard c7ea9f6809 feat(admin): enhance i18n support
Fix system monitor button i18n syntax, complete coupon form i18n
2025-06-23 11:55:17 +08:00
xboard cf30a26e43 feat(admin): optimize user traffic management features
- Improve traffic reset dialog interactions
- Enhance traffic reset logs display
2025-06-22 18:04:29 +08:00
xboard 449c30d64e fix: resolve known issues and improve code standards
- Fix known bugs in user, plan, and server modules
- Standardize code formatting and structure
- Optimize database queries and model relationships
- Improve request validation and error handling
- Update admin controllers for better consistency
2025-06-22 17:38:17 +08:00
Xboard 7f850da9ad Update README.md 2025-06-22 01:22:04 +08:00
xboard 8f07e03b6e feat: enhance plan validation, traffic system and email verification
- feat: add plan price validation
- feat: make traffic packages stackable
- feat: add commission and invite info to admin order details
- feat: apply email whitelist to verification code API
- fix: subscription link copy compatibility for non-HTTPS
- fix: resolve route editing 500 error in certain cases
- refactor: restructure traffic reset logic
2025-06-22 01:18:38 +08:00
Xboard 77d1a51fd8 Merge pull request #427 from OfficialKatana/patch-1
更换可用的DoH服务器
2025-06-22 00:05:52 +08:00
xboard dd098c2c78 fix: getSystemStatus api 2025-06-21 16:01:51 +08:00
xboard ad6e51c6ed feat: enhance plan user statistics with active user count display 2025-06-21 13:20:57 +08:00
xboard 06d0f80960 feat: optimize settings management and admin functionality
- Add system log cleanup functionality with batch processing
- Optimize v2_settings table performance by unifying value storage
- Add comprehensive client support list for one-click subscription
- Fix QR code subscription links for specific node types
- Fix route addition issues in admin management panel
- Enhance admin system controller with log management APIs
2025-06-21 12:11:27 +08:00
xboard 1d3d4b1239 fix(admin): fix shadowsocks plugin issue - save empty string instead of 'none' when plugin is set to none 2025-05-25 08:43:00 +08:00
xboard f9600d5412 fix(clash-meta): support custom SNI configuration for anytls protocol 2025-05-25 00:20:13 +08:00
xboard 6e983cc3b4 fix(admin): optimize mail encryption selector and null value handling 2025-05-24 22:58:46 +08:00
xboard 49bcc9696b refactor: comment out update-check routes and refactor findUserByBearerToken, calcResetDayByMonthFirstDay, calcResetDayByExpireDay 2025-05-24 20:47:27 +08:00
xboard c94a3d0500 fix: add missing files from previous commit 2025-05-24 20:19:54 +08:00
xboard 8880fd468d refactor: optimize mail reminder system - fix memory overflow, improve performance 20-30x, streamline code 2025-05-24 20:08:21 +08:00
Xboard d4b5c2e48a Update composer.json 2025-05-24 18:11:11 +08:00
xboard 887cc52788 feat: upgrade Laravel framework from 11.x to 12.15.0 with enhanced dependencies and performance optimizations 2025-05-24 16:28:49 +08:00
Xboard 299e15ed70 Update 1panel.md 2025-05-24 14:17:22 +08:00
xboard 0f657ad67e fix: restrict anytls delivery to compatible stash client versions 2025-05-24 14:13:44 +08:00
xboard 66f9b58393 refactor: use request attributes instead of merge for middleware data transfer
- Replace request->merge() with request->attributes->set() in Server middleware to avoid polluting user input
- Add getNodeInfo() helper method in UniProxyController for cleaner node info access
- Update all node_info references to use the new attribute-based approach
2025-05-24 13:54:57 +08:00
xboard b271238094 fix: improve node filtering by client base_version, set subscription content-type, and add hop_interval support for hysteria2
- Refactor node filtering logic to correctly handle client base_version requirements.
- Set appropriate Content-Type header for subscription responses.
- Add support for hop_interval configuration in hysteria2 node delivery.
2025-05-24 13:45:32 +08:00
xboard 64e68d7d65 feat: Add node load submission and display functionality
- Implemented node load status submission in UniProxyController with dynamic cache expiration based on server push interval.
- Added log filtering capability in the admin panel for better log management and analysis.
2025-05-24 12:31:18 +08:00
xboard 819d57dfe6 fix: resolve AnyTLS padding scheme modification issue 2025-05-23 20:47:17 +08:00
xboard af420ea83a feat: add AnyTLS support and improve system functionality
- Add AnyTLS protocol support
- Add system logs viewing in admin panel
- Refactor client subscription delivery code
- Refactor hook mechanism
- Add plugin support for Shadowsocks protocol
- Add CSV export option for batch user creation
- Fix mobile admin login page width display issue
2025-05-22 17:58:22 +08:00
Xboard 672cd3860f Merge pull request #504 from Fearless743/master
add anytls support
2025-05-21 10:13:28 +08:00
Fearless 0f672571b7 add anytls support 2025-05-19 09:25:52 +08:00
xboard 497fe59986 fix: correct obfs host parameter in subscription delivery for clash/clash-meta/shadowsocks/stash 2025-05-18 03:58:14 +08:00
xboard 4811b38eb3 fix: add missing i18n fields in admin and fix Surge template issue 2025-05-16 23:18:30 +08:00
xboard 333f131ec8 chore: update docker-publish.yaml and Dockerfile 2025-05-16 22:43:00 +08:00
xboard 16cca9c12d feat(protocols): add support for ss obfs, ss2022, and vless reality
- Clash and Clash Meta: Added support for Shadowsocks (SS) with obfs.
- Loon: Added support for SS2022 and obfs.
- Stash: Added support for SS2022, obfs, and VLESS Reality.
2025-05-16 06:43:58 +08:00
xboard 5b02d3d155 fix(admin): remove one-click update feature and fix fuzzy order search in user management
- Removed the one-click update functionality from the admin panel.
- Fixed the issue where order search in user management used fuzzy matching; now uses precise matching.
2025-05-16 05:48:37 +08:00
xboard ee93a7315b chore(redis): disable persistence configuration 2025-05-16 05:16:23 +08:00
xboard 75c6d854b4 feat(admin): optimize subscription template configuration and add Surfboard subscription template
- Improved the code structure for subscription template configuration.
- Added a new feature in the admin panel to configure Surfboard subscription templates.
2025-05-16 05:13:49 +08:00
Xboard 328ed66a6a Merge pull request #497 from ztbh/master
Fix the bug of sub-node ss password mismatch
2025-05-16 00:18:00 +08:00
xboard 708674d56e fix(admin): correct language pack errors in admin panel 2025-05-15 22:19:25 +08:00
ztb 66c5c03203 Fix the bug of sub-node ss password mismatch 2025-05-13 21:55:18 +08:00
xboard 42f9eda8aa fix(admin): correct ticket message bubble alignment in admin panel 2025-05-11 17:44:18 +08:00
xboard 3cb4bcf64a fix(singbox): resolve port type casting and add port hopping support 2025-05-10 17:10:41 +08:00
xboard 53e09f98d7 fix(node): resolve port type validation error 2025-05-09 19:53:59 +08:00
xboard 7b45351f99 fix(admin): Fix order assignment issue in admin panel 2025-05-08 22:14:56 +08:00
xboard 61d8c0ed66 fix(stash): resolve incorrect ports deployment 2025-05-08 21:30:47 +08:00
Xboard 3674896780 Merge pull request #484 from cedar2025/new-dev
fix: resolve PHPStan static analysis warnings
2025-05-08 17:17:41 +08:00
xboard 4845ff0739 fix: resolve PHPStan static analysis warnings 2025-05-07 19:48:19 +08:00
xboard ea424ad0a8 Revert "fix: resolve PHPStan static analysis warnings"
This reverts commit b885e644a8.
2025-04-14 21:23:08 +08:00
xboard b885e644a8 fix: resolve PHPStan static analysis warnings 2025-04-14 02:12:42 +08:00
Xboard 9e2f46c688 Merge pull request #438 from NekoCareLab/master
Fixed: IPv6 is not properly processed
2025-03-19 22:49:10 +08:00
NekoCareLab e2bb019551 Fixed: IPv6 is not properly processed 2025-03-16 14:23:58 +08:00
Xboard 2cebc65be8 Merge pull request #417 from NekoCareLab/master
Fixed: Vless GRPC subscription
2025-03-07 12:26:24 +08:00
Katana 604036ae6e Add DoH fallback servers 2025-03-04 15:28:32 +08:00
NekoCareLab 3ec93f9971 Fixed: Vless GRPC subscription 2025-03-01 19:29:21 +08:00
xboard 7d5ef44e9f Fix: Handle null content in PlanResource::formatContent method
- Fix deprecated warning when passing null to str_replace() function\n- Use null coalescing operator to provide empty string as default value\n- Comply with PHP 8.2+ type requirements
2025-02-25 19:14:19 +08:00
xboard bea2c5ed03 chore: update docker-publish 2025-02-23 16:53:42 +08:00
xboard b910235eb7 fix: ensure string type safety in Helper::getSubscribeUrl 2025-02-23 16:27:03 +08:00
xboard bcdb8ff497 feat(admin): add XHTTP and HTTP Upgrade protocol network templates 2025-02-23 02:04:35 +08:00
xboard 86295d229b fix: Remove forced direct IP rule for nodes 2025-02-23 00:33:03 +08:00
xboard 2da7cfcfd7 fix: Correct email dispatching in user management 2025-02-23 00:27:22 +08:00
xboard e52895d2aa feat: Add TUIC protocol support and fix user filtering/export issues 2025-02-23 00:13:04 +08:00
xboard c3bfe62ca9 fix(subscribe): correct vmess websocket cofiguration for Surge compatibility 2025-02-22 21:37:38 +08:00
xboard d4ef15967c fix(subscribe): correct vmess websocket cofiguration for Surfboard compatibility 2025-02-22 21:12:59 +08:00
Xboard b4b5451861 Update aapanel.md 2025-02-22 17:39:05 +08:00
xboard c85fee9232 fix(setting): change cache driver from octane to redis in Setting class 2025-02-17 17:01:08 +08:00
xboard a62295ea82 update stash.php 2025-02-16 18:15:20 +08:00
xboard 58a9303e5f feat(admin): Add subscription template configuration and fix minor issues 2025-02-16 18:05:03 +08:00
xboard 410c8b5539 update compose.sample.yaml 2025-02-16 10:19:26 +08:00
xboard b3f1a9e546 update aapanel.md 2025-02-16 10:16:26 +08:00
xboard 45d4fadbba update dockerfile 2025-02-10 00:46:00 +08:00
xboard 3dc20847ca fix(plugin): correct knows bugs 2025-02-10 00:32:17 +08:00
xboard 170de2638b fix(plugin): correct knows bugs 2025-02-10 00:01:51 +08:00
xboard d1d397eed0 fix(plugin): correct knows bugs 2025-02-09 23:54:28 +08:00
xboard 1131044d58 fix(plugin): correct knows issues 2025-02-09 23:45:23 +08:00
xboard d01c1b476f fix(plugin): correct knows bugs 2025-02-09 23:36:19 +08:00
xboard 4092a49117 chore: update dockerfile 2025-02-09 23:10:28 +08:00
xboard bd9c2a32d7 chore(plugin): Refactor plugin architecture and improve code quality 2025-02-09 22:38:09 +08:00
xboard bba20216fe fix(update): fix version fetch logic 2025-02-09 14:24:49 +08:00
xboard fe39779a53 fix(update): fix version comparison logic 2025-02-09 14:05:25 +08:00
xboard 2d799c0218 feat: add one-click update feature to admin panel 2025-02-09 13:43:09 +08:00
xboard 0e65a45661 feat: enhance user management and system optimization
New Features:
- Add bulk ban and email notification in user management
- Add CSV export for batch coupon generation
- Optimize subscription description template

Bug Fixes:
- Fix knowledge base pagination issue
- Fix permission group filtering in node management
- Fix unauthorized order placement for free subscription periods
2025-02-09 11:06:08 +08:00
xboard ec67740528 fix: coupon period limit 2025-02-07 22:55:45 +08:00
xboard 4a73b3afc0 fix: coupon period limit 2025-02-07 22:39:31 +08:00
xboard 7c7dd79d99 update docker-publish.yml 2025-02-07 20:11:08 +08:00
xboard 1a8fcdd0eb update dockerfile 2025-02-07 19:58:42 +08:00
xboard 99a05cd956 fix: subscribe.url hook 2025-02-07 13:06:01 +08:00
xboard 1e7469a0ac chore: update dockerfile 2025-02-06 19:04:38 +08:00
xboard 3c31c13038 feat(plugin): add subscribe.url hook 2025-02-06 18:18:02 +08:00
xboard 85d3e0a22c feat: add traffic.before_process hook 2025-02-06 17:48:17 +08:00
Xboard 2af70545ad Update aapanel.md 2025-02-05 03:41:26 +08:00
xboard 8a5a1f60f5 fix(xboard theme): add root path redirection to dashboard 2025-01-26 12:50:40 +08:00
xboard 97fbdc01c0 feat: suppress InterceptResponseException logging to reduce noise 2025-01-26 11:59:32 +08:00
xboard 8cac0aee06 fix(ticket): correct knows issues 2025-01-26 11:42:30 +08:00
xboard 546fc0773f fix(plugin): remove redundant code 2025-01-26 11:41:53 +08:00
Xboard 4fc33ab334 Merge pull request #349 from ogbeh/patch-1
Update aapanel-docker.md
2025-01-26 04:28:24 +08:00
xboard 6458dc0b70 refactor: move plugin initialization to middleware for Swoole compatibility 2025-01-26 04:22:47 +08:00
xboard 2b29278e58 update composer.yaml 2025-01-26 04:03:34 +08:00
xboard cb151cd612 feat: add plugin upload functionality and optimize plugin logic 2025-01-26 03:58:28 +08:00
xboard 29f838ee93 refactor: enhance plugin mechanism for better extensibility 2025-01-26 02:31:57 +08:00
xboard 421f50ce93 fix: optimize stat jobs to prevent SQLite lock issues 2025-01-26 01:07:42 +08:00
xboard 271e1cfeeb update issue template 2025-01-26 00:54:51 +08:00
xboard 50ea3bd667 fix: resolve deprecation warnings across the application 2025-01-26 00:44:58 +08:00
xboard f65f1ae817 refactor: optimize ticket management system 2025-01-25 17:46:10 +08:00
xboard 9ed588bd93 feat: add user deletion functionality and fix known issues 2025-01-25 16:57:17 +08:00
Samuel Ogbeh 74fe66b6ab Update aapanel-docker.md
Update site config to solve the issue of admin panel not loading
2025-01-24 14:32:30 +01:00
xboard 66f91908ce feat(coupon): enhance theme compatibility by converting plan IDs to strings 2025-01-24 02:26:22 +08:00
xboard e9d41441cc fix(coupon): correct knows issues 2025-01-23 16:14:18 +08:00
xboard 1733b23784 fix(coupon): correct knows issues 2025-01-23 14:48:12 +08:00
xboard d117960abb update docs 2025-01-22 21:01:18 +08:00
Xboard 76aafe8d4e Update 1panel.md 2025-01-21 22:12:28 +08:00
Xboard 9e76f90f56 Update compose.sample.yaml 2025-01-21 22:11:22 +08:00
Xboard affd1c5a47 Update docker-publish.yml 2025-01-21 22:04:08 +08:00
xboard 884f521d78 update md 2025-01-21 19:35:49 +08:00
xboard 0f6faae83d update readme 2025-01-21 16:18:00 +08:00
xboard a9516400c6 feat: new xboard 2025-01-21 14:57:54 +08:00
Xboard 4826ee72e3 fix: resolve hy2 speed limit dispatch issue in Singbox client 2024-12-09 18:45:12 +08:00
xboard fed0972283 pref: Enhance TrafficFetch Performance and Optimize Code Structure 2024-11-29 19:22:12 +08:00
Xboard 19b2cd968a Update composer.json 2024-11-17 17:02:07 +08:00
xboard 662711c0b7 Revert "chore: update composer.json"
This reverts commit 8c0c4e1cc5.
2024-11-15 15:10:05 +08:00
xboard 68ffe0f1cf feat: add support for hysteria2 in V2rayNG 2024-11-09 22:16:05 +08:00
xboard e38bd1c101 feat: add support for hysteria2 in Passwall and SSRPLUS 2024-11-09 21:37:15 +08:00
xboard b55e4a58f5 refactor: subscription URL retrieval logic 2024-11-09 06:35:37 +08:00
Xboard 1b52b1c9dd Update aapanel+docker安装指南.md 2024-11-09 04:13:45 +08:00
Xboard 514c2dd613 Update docker-compose安装指南.md 2024-11-09 04:01:39 +08:00
Xboard c512de8c2f feat: add appname display in hiddify
add profile-title header to sing-box subscribe
2024-11-08 17:26:31 +08:00
Xboard 6ed825c714 chore: add persistence configuration to redis 2024-11-08 06:32:48 +08:00
xboard 8c0c4e1cc5 chore: update composer.json 2024-11-05 11:56:02 +08:00
Xboard 78e43ed18c 合并来自greatbody/dev的拉取请求#215
feat: Support configure environment variable to skip interactive configurat…
2024-11-02 14:30:54 +08:00
Xboard 0f71824048 Merge pull request #238 from mercury7720/dev
[feat]: add v2rayNG hysteria2 support
2024-11-02 14:25:51 +08:00
Linux 6c14a93ed7 Payment: add type configuration to Epay payment 2024-10-20 12:37:16 +08:00
Linux 29354a7471 fix: Hide online user count display for child nodes without independent online users 2024-10-20 12:03:21 +08:00
Linux be5e714741 docs: update 2024-10-19 23:17:22 +08:00
George 6cf1df9fd0 Merge remote-tracking branch 'upstream/dev' into feature/v2rayng-hysteria2 2024-10-10 11:18:20 +08:00
Linux fc3a269fbe fix: 修复用户端不显示当日流量的问题 2024-10-09 22:55:26 +08:00
George a1d88130c3 [feat]: add v2rayNG hysteria2 support 2024-10-09 15:17:45 +08:00
xboard 3cfc5fc6c2 fix: 修复流量明细显示所有记录的BUG 2024-10-07 09:55:19 +08:00
Xboard 67eb96a235 Merge pull request #227 from mercury7720/dev
[fix]: Loon Hysteria2 node cannot get SNI
2024-10-07 05:48:29 +08:00
xboard adaed5038b fix: 修复vless节点的tls_insecure在meta中下发生效的问题 2024-10-07 02:47:54 +08:00
xboard b2d3d03217 fix: 修复节点密钥未校验是否为空的问题 2024-10-07 00:27:11 +08:00
George c5ef9b9052 [fix]: Loon Hysteria2 node cannot get SNI 2024-09-29 11:28:18 +08:00
greatbody b02175bdf1 Enable mannual trigger of pipeline. 2024-09-06 10:08:17 +08:00
greatbody e42c960efc Support configure environment variable to skip interactive configuration, which is require when we want to setup by script. 2024-09-06 10:02:45 +08:00
xboard 60cb7c2b3b fix: [Xboard主题] 修复扫描二维码订阅中二维码显示位置歪了的问题 2024-08-27 13:55:20 +08:00
xboard 9894f0cd8d update docker-publish.yml 2024-07-29 13:09:25 +08:00
xboard 881101b84a fix: [Xboard主题] 修复订单金额计算的问题 2024-07-24 00:25:37 +08:00
Xboard 5ffc1387ef Merge pull request #180 from ishkong/patch-1
feat: 支持部分客户端订阅获取shadowsocks中obfs部分参数
2024-07-21 17:48:17 +08:00
ishkong a86e9174a2 feat: Support V2RayNG to get obfs parameters in shadowsocks. 2024-07-21 17:29:12 +08:00
ishkong f352be2acd feat: Support shadowrocket to get obfs parameters in shadowsocks. 2024-07-21 14:01:03 +08:00
ishkong 4d1a1eb037 feat: Support Shadowsocks obfs config 2024-07-21 13:58:22 +08:00
xboard 5acfdbcae3 fix:【Xboard主题】 修复订单金额计算在分配订单情况下显示有误的问题, 修改部分弹窗的按钮颜色与主题色一致 2024-07-20 02:53:06 +08:00
xboard 7ccb7c7f94 fix: 修复上一个commit造成的bug 2024-07-19 07:04:02 +08:00
xboard 77e329370e feat: Singbox、clash订阅增加绕过服务器地址规则
1、优化订阅下发代码
2、singbox、clash、meta订阅下发增加绕过服务器地址规则,防止重复代理
2024-07-19 06:29:35 +08:00
xboard 63af670fc2 update default.sing-box.json 2024-07-19 02:33:27 +08:00
xboard e6547d1276 fix: Fix OrderHandleJob to prevent Lock wait timeout. 2024-07-19 02:30:51 +08:00
Xboard edbb6dd6a5 Update aapanel+docker安装指南.md 2024-07-16 02:25:49 +08:00
xboard cdd64ede58 fix:[Xboard主题] 修复支付弹窗二维码溢出盒子的问题 2024-07-04 13:36:25 +08:00
xboard bb90dc72c3 xboard主题: 公告增加自动轮播 2024-06-14 01:43:55 +08:00
xboard 11a30a6d4e fix: 修复0ca9a24 导致的订单tg通知失败的问题 2024-06-14 00:05:20 +08:00
xboard c6b8b1b664 update default.sing-box.json
migrate singbox configuration to v1.9.0
2024-06-10 12:27:13 +08:00
Xboard 0a2885903c Merge pull request #145 from riolurs/patch-1
feat: Add additional payment information to Telegram notifications.
2024-06-08 21:41:32 +08:00
riolu.rs b637b298c9 详细支付信息 2024-06-08 17:51:38 +08:00
xboard 0ca9a24cc3 update feature-request---功能请求.md 2024-06-02 22:23:39 +08:00
xboard fb4dd9c77d fix: 修复支付完成后的返回URL可能不为来源站点的问题 2024-06-02 22:22:57 +08:00
Xboard d160e02601 Update aapanel安装指南.md 2024-06-02 13:56:57 +08:00
xboard b6eb9a9fe3 fix: 修复今日节点实时流量排行超过15个排序变乱的问题 2024-05-31 14:39:16 +08:00
xboard 6295f98cad fix: 修复初始化安装时清理缓存报错的问题
修改aapanel 安装文档增加inotify 扩展说明
修改webman.php 自动检测是否安装inotify扩展,如果安装则自动拉取热重载监控
2024-05-29 00:56:00 +08:00
xboard 891d00c5a4 fix: 修复ss2022订阅下发密码错误的问题 2024-05-24 22:45:27 +08:00
xboard 0c04c97ab5 perf: 优化安装体验 2024-05-24 13:06:25 +08:00
xboard e638b4d9dc hy2: 不带版本号的客户端默认下发hy2节点 2024-05-23 16:42:57 +08:00
xboard aa8f648179 feat: workerman 增加热重载 2024-05-23 11:40:52 +08:00
xboard 23d17f362a log: 修改日志导出结果路径提示为绝对路径 2024-05-20 10:22:31 +08:00
xboard 6eb9d9fdd7 update docs 2024-05-18 00:23:00 +08:00
xboard 01170cfa0c to: 追加sing-box下发忘记提交的代码 2024-05-15 01:06:41 +08:00
xboard b0c23cdd6d fix: 修复上一个commit导致的shadowrocket的hy2节点订阅下发失败的问题 2024-05-15 01:05:27 +08:00
xboard 35a2811a0a feat: 增加surge的hy2下发、添加clash meta、shadowrocket、stash订阅hy2端口跳跃的下发 2024-05-14 21:57:36 +08:00
xboard a3abb62728 chore: 优化docker环境下的启动速度,增加webman进程自动重启来释放内存 2024-05-14 18:10:15 +08:00
xboard deee5d85f6 fix: 修复Surge surfboard订阅中的剩余流量显示错误的问题 2024-05-03 15:04:23 +08:00
xboard d33af355db update docs 2024-05-03 03:36:29 +08:00
xboard 52442cc167 chore: 修复docker 环境当中,因为缺少patch导致打patch失败的问题 2024-05-03 03:35:47 +08:00
xboard b12ce755ea fix: 修复订阅过滤功能在某些情况下报错的问题 2024-04-30 11:02:21 +08:00
xboard cb14007719 to: 追加上个commit 缺少提交的文件 2024-04-27 21:22:45 +08:00
xboard 7faa7ccdf0 perf: 优化流量消费相关代码性能,解决流量纪录与已用流量有概率不一致的问题 2024-04-27 17:06:57 +08:00
xboard bd9873e5ad fix:[Xboard主题] 修复重置密码页面不显示邮箱白名单后缀的问题 2024-04-24 22:45:03 +08:00
xboard bb24d43974 fix:[Xboard主题]修复重构导致的注册邮箱白名单不显示的问题 2024-04-21 20:09:14 +08:00
xboard 0318d68842 update docs 2024-04-21 02:17:19 +08:00
xboard 4cb9922f6e [Xboard主题]: 当订阅停售且用户续费订阅时跳转到订阅列表页 2024-04-21 01:51:05 +08:00
xboard 766dcb8219 refactor:[Xboard主题] 重构登陆、注册、忘记密码页面
修复用户注册时第二次提交recaptcha不弹出的问题
修改Info弹窗颜色为主题色
2024-04-21 01:39:53 +08:00
xboard a8bfe853e2 update docs 2024-04-20 20:27:45 +08:00
xboard e4886a85e7 fix: 修复当 server_token 为长数字时,后台会转化成科学计数法,后端验证失败 2024-04-18 01:27:52 +08:00
xboard 802d0acc17 chore: 优化docker 容器启动速度 2024-04-15 03:19:48 +08:00
xboard cf69157a08 docs: 增加1panel部署文档 2024-04-15 02:41:03 +08:00
xboard ad9d7405d0 fix: 修复节点密钥包含特殊字符时校验失败的问题 2024-04-15 00:01:14 +08:00
xboard 6c4c41e109 chore: 在 Docker 启动时自动修改项目目录权限 2024-04-13 04:10:47 +08:00
xboard 9fe10dbc46 fix: 修复无法读取未携带Content-Type的请求头的节点后端上报的数据的问题 2024-04-13 03:23:30 +08:00
xboard 47ca6e9780 fix: 修复更新后导致节点后端交互api不可用的问题 2024-04-12 17:34:06 +08:00
xboard 7816e12a38 chore: 修复docker环境该用非root运行时全挂载和sqlite部署报错并减少layers 2024-04-12 16:37:21 +08:00
xboard 490482dd7b chore: docker环境修改php为非root运行 2024-04-11 20:37:46 +08:00
xboard a7fa79f88a fix: 修复安装Command 2024-04-10 19:09:16 +08:00
xboard 18ec8ee813 refactor: 重构规范部分代码、邮件队列增加失败重试、去除多个支付方式、更新依赖 2024-04-10 00:51:03 +08:00
Xboard 880e5eb29d Update webman.php 2024-04-09 22:52:10 +08:00
xboard f49a362810 chore: 增加通过环境变量WEBMAN_WORKERS修改Webman的worker数的功能 2024-04-07 22:23:34 +08:00
xboard f715164af0 fix: 修复早期安装用户更新后访问首页会报theme_color不存在的问题 2024-04-05 06:51:59 +08:00
xboard 511de2b4f4 fix: 修复Xboard切换主题色不生效的问题 2024-04-04 18:04:21 +08:00
xboard e4959e966c fix:[Xboard主题] 修复支付手续费部分情况下计算与实际不符的问题与支付图标布局的问题 2024-04-04 17:01:47 +08:00
xboard 50aebcb2cc chore: docker构造环境增加bcmath扩展 2024-04-03 11:00:39 +08:00
xboard 75ff25048f fix: 调整支付通道百分比手续费可为0 2024-04-03 10:33:40 +08:00
xboard 5f0b9edb6c feat: 更改v2_payment表icon字段为text类型,增加图标对base64输入的支持 2024-04-03 07:29:24 +08:00
xboard 7dd24d4dbb fix:[Xboard主题] 进行了各种改进和修复
1、去除未使用的图片
2、修改Google验证码reCaptcha地址为www.recaptcha.net
3、修复部分页面返回最顶部按钮被挡住的问题
4、补全部分缺失的语言包
5、修复部分分辨率下侧边栏菜单切换后不会自动收起的问题
6、修复暗黑模式下登陆注册忘记密码页面为白色背景的问题
7、调整手机端弹窗增加与屏幕边界的间隙
8、当有未完成订单的情况下,增加首页重置流量的弹窗提示
9、修复节点列表在手机端上显示不协调的问题
10、去除工单ID的显示
2024-04-02 14:45:54 +08:00
Xboard 96d34ff37d Update docker-publish.yml 2024-03-20 19:41:45 +08:00
xboard bbfbdf9737 update: docker-publish.yml 2024-03-20 19:29:16 +08:00
xboard 955f85dd7b docs: update docs 2024-03-20 18:47:28 +08:00
xboard 44228802c4 fix:【Xboard主题】修复语言包与路由跳转相关的问题
修复token2Login在已登陆情况下无法跳转参数指定路由的问题
    修复登陆成功后无法跳转指定页面的问题
    修复前端语言与后台返回语言不通不的问题
    调整邀请码列表样式(增加边框)
2024-03-20 02:24:42 +08:00
xboard e07b14e9aa docs: update docs 2024-03-13 05:23:35 +08:00
xboard d5569e08b2 chore: docker添加ipv6的监听 2024-03-09 05:56:58 +08:00
xboard 79904f11d0 feat: [Xboard主题]增加token2Login 2024-03-07 23:39:26 +08:00
xboard 384ab2eb2e fix:[Xboard主题] 修复当支付金额为0时固定手续费显示不为0的问题、修复谷歌人机认证无效的问题 2024-03-07 04:36:42 +08:00
xboard d73f0decec docs: update docs 2024-02-28 18:34:27 +08:00
xboard 17588a2cf2 fix: 修复shadowrocket grpc协议sni下发错误的问题 2024-01-24 20:26:58 +08:00
xboard bfc3609a0a update README.md 2024-01-22 08:44:59 +08:00
xboard 9d945702ac docs: 删除多余的readme.md 2024-01-22 08:40:53 +08:00
Xboard 3b4a064722 Merge pull request #58 from rebecca554owen/dev
delete apanel docs
2024-01-18 23:36:12 +08:00
rebecca554owen bbb43ca31e Update README.md 2024-01-18 21:19:05 +08:00
rebecca554owen 88a6570a1b Delete docs 2024-01-18 21:18:28 +08:00
xboard 45b915b70f fix: 修复vless 使用Tls时sni不下发的问题 2024-01-17 17:54:33 +08:00
xboard a9bf3ce08c fix: 修复vless节点使用tls时订阅抱错的问题 2024-01-16 17:02:42 +08:00
xboard ff7fe43ff3 perf:[Xboard主题] 一些样式调整
1、个人中心绑定TG按钮增加已经绑定判断、
    2、侧边栏菜单增加自动收起手机端自动切换为抽屉调整邀请页面佣金和邀请码布局
    3、修改订阅列表为左对齐
2024-01-15 05:51:16 +08:00
xboard e6f6a1cb52 fix: 修复一些主题用户获取节点为空的问题,取消节点API未找到节点的日志记录 2024-01-15 04:25:25 +08:00
xboard 3a518c5de5 fix: 修复一些主题节点状态显示有误的问题 2024-01-13 17:55:28 +08:00
Xboard f8c1506841 Merge pull request #55 from ishkong/patch-2
feat: 增加v2rayN自动下发Hysteria2节点
2024-01-13 17:46:30 +08:00
Xboard 781cc056c2 Merge pull request #52 from ishkong/patch-1
feat: 为v2rayn的订阅添加hysteria2支持
2024-01-13 17:46:08 +08:00
ishkong 2618bc256c Update V2rayN.php 2024-01-13 17:25:11 +08:00
ishkong efa3234fd7 feat: 增加v2rayN自动下发Hysteria2节点 2024-01-13 17:16:22 +08:00
Xboard 87f049b166 Merge pull request #54 from sakurauidev/ResetTraffic
将周期重置流量只重置已使用流量修改为重置已使用流量的同时重置当总流量为当前订阅所设置的流量
2024-01-13 12:11:14 +08:00
ventle233 2491a522e0 将重置流量只重置已使用流量修改为重置已使用流量的同时重置当总流量为当前订阅所设置的流量 2024-01-13 02:10:15 +08:00
xboard 4b0935d58a fix: [Xboard主题] 修改谷歌recaptcha为中国可以访问地址,解决中国用户无法打开进行人机认证的问题 2024-01-12 21:16:42 +08:00
ishkong c80fe75b3e 为v2rayn的订阅添加hysteria2支持 2024-01-11 22:15:43 +08:00
xboard 3382b719e2 docs: update aapanel安装指南.md 2024-01-11 21:47:38 +08:00
xboard 4bedb16fd4 to: 增加支付回调错误日志记录 2024-01-11 01:16:10 +08:00
xboard 54bae44418 style: 去除v2board 字段css 改为xborad 尝试解决被墙问题 2024-01-11 00:22:29 +08:00
xboard 9d5f4f1dfd fix: [用户前端]修复更改订阅提示框显示条件有误的问题 2024-01-11 00:11:54 +08:00
xboard 5f1956094d fix: 修复升级后不选择主题色会导致500错误的问题 2024-01-10 20:00:13 +08:00
xboard 2a48c72c5d feat: [用户前端] 修复部分BUG、增加主题色、增加注册用户协议显示等 2024-01-10 18:59:59 +08:00
xboard 64f2634878 chore: nginx增加html文件访问支持 2024-01-06 14:54:39 +08:00
xboard 5c3d15e1a4 feat: 增加Command (php artisan log:export)导出日志命令 2024-01-01 04:52:49 +08:00
xboard ea3641b48c feat: 增加邮件Mailgun支持 2024-01-01 04:40:23 +08:00
xboard 827bda72b3 fix: 修复邮箱配置无法从环境变量读取的问题 2024-01-01 01:06:07 +08:00
Xboard 7aae14a6b9 Merge pull request #35 from rebecca554owen/dev
v2baord迁移教程有误,重新修改。
2023-12-24 21:28:58 +08:00
rebecca554owen 2185904792 Update 从aapanel迁移到1panel教程.md 2023-12-19 23:18:20 +08:00
rebecca554owen 76ec9af168 Update 从aapanel迁移到1panel教程.md 2023-12-19 23:17:17 +08:00
rebecca554owen 305fece8ca Update 从aapanel迁移到1panel教程.md 2023-12-19 23:03:54 +08:00
xboard b90da0002a perf: 优化初始化安装流程,增加mysql和Redis配置校验 2023-12-18 17:42:59 +08:00
xboard 291a374ba2 feat: 增加Vmess tcp http下发支持 2023-12-18 09:40:35 +08:00
xboard 53ac59f49c fix:[用户前端] 修复扫描二维码订阅地址错误的问题 2023-12-17 21:56:05 +08:00
Xboard ee7402cf69 Merge pull request #30 from rebecca554owen/dev
更新1paenl教程,删除多开教程,更新docker生成,方便fork分支用户自行修改以及测试。
2023-12-16 20:10:00 +08:00
rebecca554owen 8e8121d175 多开Xboard教程存在Redis共用处理问题,先删除。 2023-12-16 18:09:19 +08:00
rebecca554owen db799a1ad9 更新教程适用于新安装,v2board/xboard用户迁移。 2023-12-16 18:08:33 +08:00
rebecca554owen a10a68e060 修改生成镜像为仓库拥有者。 2023-12-16 18:07:32 +08:00
xboard 3e5861b1ee fix: 修复v2ray、Trojan旧版接口获取用户列表失败的问题 2023-12-16 08:05:09 +08:00
xboard 211b541819 fix: 修复节点状态列表接口报错的问题 2023-12-15 22:46:09 +08:00
xboard 4f6ddd8b7d fix: 修复Xboard主题扫描二维码不显示节点类型的问题 2023-12-14 22:29:37 +08:00
xboard 4973a390ef fix: 修复多处可能出现的事务安全问题 2023-12-14 13:07:57 +08:00
xboard 1c3879e292 perf: 优化数据库备份Command逻辑 2023-12-13 09:28:01 +08:00
xboard bfe979f953 fix: 修复创建工单中的事务安全 2023-12-13 03:00:43 +08:00
xboard 8eda977efb feat: 增加Loon自动下发Hysteria2节点 2023-12-13 00:08:39 +08:00
xboard 7af7ee047c fix:[用户前端] 修复markdown-body类中暗黑模式不生效的问题 2023-12-12 22:18:24 +08:00
xboard b345f02951 perf: 优化节点后端获取用户用户列表接口响应速度,降低CPU使用资源 2023-12-12 21:49:16 +08:00
xboard 8d09d04a23 fix: 修复1.8 版本sing-box订阅失败的问题 2023-12-12 09:25:58 +08:00
xboard 48ed3dc17f feat: [用户前端]增加crisp识别用户email、套餐详情支持 2023-12-12 08:25:26 +08:00
xboard b4cfcad0cb refactor: 规范工单接口代码规范 2023-12-12 06:22:18 +08:00
xboard 6d16e9b36a feat: filter支持匹配节点标签 2023-12-10 18:09:58 +08:00
xboard 1c68f4564a refactor: 规范部分API接口响应格式 2023-12-10 17:53:31 +08:00
xboard b598700282 fix: [用户前端]修复工单聊天窗口没有自动将聊天记录拉到最下面的问题、修复续费订阅会显示弹窗的 问题、补充部分i18n语言包 2023-12-10 17:27:28 +08:00
xboard 10288039cb fix: 修复安装Command不清除缓存的问题 2023-12-10 11:51:56 +08:00
xboard 53b02859f4 perf:[用户前端] 补全i18n、优化登录注册交互逻辑、修复佣金提现对话框取消按钮无效的问题 2023-12-09 10:41:50 +08:00
xboard af513acd79 feat: 个人中心页面增加绑定机器人、立即进入群聊卡片 2023-12-08 23:00:23 +08:00
xboard 02b06d813c docs: update aapanel+docker安装指南.md 2023-12-08 20:33:10 +08:00
xboard eae225278e feat: 增加订阅地址支持[*-*]表达式 2023-12-08 20:16:24 +08:00
xboard 1bae745eea docs: 修复错别字 2023-12-08 16:04:11 +08:00
xboard b3533a2577 to: 工单增强消息调整 2023-12-08 15:51:29 +08:00
xboard 512b29ceec feat: 工单Bot增强 2023-12-08 15:43:17 +08:00
xboard 5c86010e29 update: composer.json 2023-12-08 10:11:37 +08:00
xboard 1fc7b50bbf perf: 优化初始化安装流程 2023-12-08 08:53:19 +08:00
xboard 9b4b2c98e1 update: composer.json 2023-12-07 23:12:32 +08:00
xboard 1bffc660c5 fix: telegram机器人setwebhook接口url设置为站点网址,防止一些反向代理配置导致绑定机器人失败的问题 2023-12-07 23:12:05 +08:00
xboard d66f4e22d2 perf:[用户前端] 优化一键订阅列表 2023-12-07 21:46:11 +08:00
xboard 26d2bf78d5 fix: [用户前端]修复ipad会被识别为mac的问题 2023-12-07 20:44:51 +08:00
xboard d32163d3fe fix: 修复邀请信息获取接口返回数据格式错误的问题 2023-12-07 09:52:23 +08:00
xboard 6b0554a263 feat:[用户前端]添加订单二维码结账方式的支持、知识库增加copy和jump两个事件的支持 2023-12-07 06:09:41 +08:00
xboard 4038fd3408 fix: 修复创建Hy节点时obfs默认关闭却不提交到后端的问题、优化Vless Reality节点创建字段提示 2023-12-07 04:45:39 +08:00
xboard cb2b684bca fix: 修复后台发送测试邮件返回状态不正确的问题 2023-12-07 04:19:30 +08:00
xboard 8f049f72f8 refactor: 规范状态码、抛出异常的使用 2023-12-07 04:01:32 +08:00
xboard bfb8bf2201 Log: 给流量消费队列当中保存失败的用户增加错误日志 2023-12-06 19:11:29 +08:00
xboard a3356f695c fix: 规范数据库事物的使用,解决在swoole环境下可能会出现事物一直不被提交的问题 2023-12-06 19:00:26 +08:00
xboard 6b209d8c58 fix: 优化流量消费队列,防止记录长时间被锁住 2023-12-04 23:16:18 +08:00
xboard 7639f87334 fix: 修复潮汐app Trojan协议的问题 2023-12-04 22:52:11 +08:00
xboard c721860240 fix:[用户前端] 修复订阅详情为数字时的异常渲染 2023-12-04 20:42:34 +08:00
xboard 779c3fa984 refactor: 规范Expection处理 2023-12-04 20:40:49 +08:00
xboard 6e293f9a36 在 Docker 环境中读取 INSTALL 环境变量判断是否已经安装 2023-12-04 20:30:38 +08:00
xboard f814fc97e7 fix: 修复hiddify无法自动下发hy2节点的问题 2023-12-03 22:17:33 +08:00
xboard c7d1fb4631 fix: 修复SingBox下发带混淆的hysteria失败的问题 2023-12-03 19:21:05 +08:00
xboard 77c47eee2e feat: [用户前端]订阅介绍支持潮汐客户端的写法 2023-12-03 18:37:32 +08:00
xboard 99ea11c3bb fix: 修复tg机器人无法回复工单的问题 2023-12-03 09:43:38 +08:00
xboard fbee6551c5 style:[用户前端] Markdown使用github样式预设 2023-12-03 07:16:53 +08:00
xboard b743ca475b fix:[用户前端] 修复订阅介绍为空时订阅不显示的问题,修复公告中图片宽度会超出边界的问题 2023-12-03 00:19:19 +08:00
xboard 157c29392d feat:[用户前端] 提高复制功能兼容性、订阅描述增加md支持、增加使用文档预设样式 2023-12-02 22:04:48 +08:00
xboard 73b5888cea refactor: CORS中间件改用\Illuminate\Http\Middleware\HandleCors 2023-12-01 00:36:09 +08:00
xboard ad969fc60d debug:[用户前端]删除测试代码 2023-12-01 00:23:58 +08:00
xboard f2dafbed95 style:[用户前端] 将一键订阅的软件图标内联到网页当中,加快图标的加载速度 2023-12-01 00:18:39 +08:00
xboard 06e928dca6 fix:[用户前端] 修复前端显示三级分销比率错误的问题 2023-11-29 04:50:53 +08:00
xboard f65cf8852d fix:[用户前端] 修复个人中心流量邮件提醒关闭无效的问题 2023-11-28 23:17:04 +08:00
xboard 13d2878823 fix:[用户前端] 修复手机端菜单栏被数据表格覆盖的问题 2023-11-28 21:57:27 +08:00
xboard 4d79590c38 i18n:[用户前端] 更新语言包 2023-11-28 21:39:16 +08:00
xboard 0ad7a55ec6 feat:[用户前端] 增加提现推广用户按钮,修正三级分销当中佣金比例显示问题 2023-11-28 21:31:32 +08:00
xboard 3028d3ead0 fix:[用户前端] 修复长期套餐用户不显示重置已用流量按钮的问题,补全 重置按钮语言包 2023-11-28 20:29:56 +08:00
xboard c7d8483fed style:[用户前端] 增加首页增加重置流量按钮、知识库增加img、video标签最大宽度的为100%的限制、首页增加流量告急警告、修改手机端菜单栏关闭样式 2023-11-28 19:28:20 +08:00
xboard 973852e803 fix: [用户前端]修复google reCaptcha 超时导致错误的问题、补全部分语言包 2023-11-27 16:19:48 +08:00
xboard 099036e1d8 feat:[用户前端] 增加多语言支持,修复菜单栏存在的BUG, 启用静态gzip以节省CPU资源 2023-11-27 00:23:25 +08:00
xboard be7657685f docs: 增加修改代码需要重启的注意事项 2023-11-26 11:56:44 +08:00
xboard b767f33a9d chore: 增加docker-compose 模版的自动启动的配置 2023-11-26 11:50:56 +08:00
xboard 9437c4bfc5 to: 添加前端静态资源请求版本号,防止更新导致的缓存 2023-11-25 10:24:14 +08:00
xboard a8a03e76c6 chore: 修改Docker环境安装过程中默认的数据库地址为127.0.0.1 2023-11-24 17:03:48 +08:00
xboard fc35db9ac4 style:[用户前端] 订阅列表修改为点击可片即可进入订阅详情 2023-11-24 13:40:26 +08:00
xboard fa476ed31d fix:[用户前端] 修复注册页面选择邮箱后缀在手机端被缩略的问题 2023-11-24 11:53:35 +08:00
xboard 7b36c07630 chore: Docker镜像增加git软件包、修正aapanel+ docker 更新步骤 2023-11-24 11:24:15 +08:00
xboard d51298d4f4 docs: update docker-compose安装指南 2023-11-24 10:50:29 +08:00
xboard f2b57a378b fix:[用户前端] 修复确认中的永久与累计获得的佣金显示单位不正确的问题 2023-11-24 09:29:37 +08:00
xboard 4a0bfd3f16 feat: 新增hiddify自动下发hy2 2023-11-24 00:02:33 +08:00
xboard 3e537cf544 fix: 修复用户订阅到期提醒、流量告急提醒的默认设置修改无效的问题 2023-11-23 23:59:08 +08:00
xboard a396d60a6c fix: 修复迁移配置文件时配置为数组时的错误 2023-11-23 18:35:18 +08:00
xboard 5cb37ed3e5 feat: 增加用户流量告急提醒和订阅到期提醒的默认设置 2023-11-23 18:31:15 +08:00
xboard c36a4a4ce9 fix: 修复admin_setting可能出现的问题 2023-11-23 18:02:50 +08:00
xboard f4964f4561 fix: 修复自动备份command 的问题,增加备份后自动压缩为.gz节省空间 2023-11-23 17:55:58 +08:00
xboard a32adf1d28 feat: 添加cmfa、nekoray、verge、clashx meta 自动下发Hy2 2023-11-23 15:11:22 +08:00
xboard e0770798eb docs: update aapanel+docker安装指南.md 2023-11-23 14:05:38 +08:00
xboard 687ba3b18f feat: 增加 新增、修改Vless、Hysteria节点表单的字段的必填提示 2023-11-23 13:37:41 +08:00
xboard 02003e4c7a refactor: 优化安装命令的代码 2023-11-23 13:32:39 +08:00
xboard cc6aa801ed chore: 增加docker-compose.sample.yaml 模版 2023-11-23 13:29:30 +08:00
xboard 33e2d7b211 chore: 删除docker-compose.yaml 增加docker-compose.yaml模版 2023-11-23 13:28:38 +08:00
xboard 657f24511b update readme.md 2023-11-23 11:49:50 +08:00
xboard c76cabecc6 docs: 补充迁移文档中缺少的步骤 2023-11-23 11:48:21 +08:00
xboard 536fbc5949 Merge branch 'dev' of github.com:cedar2025/v2board into dev 2023-11-23 11:13:28 +08:00
xboard db588b6408 docs: 修正aapanel安装指南中的错误 2023-11-23 11:12:33 +08:00
xboard 6cea64d4b5 style:[用户前端] 取消头像显示 2023-11-23 00:13:18 +08:00
xboard 01f3364889 docs: update aapanel+docker安装指南.md 2023-11-23 00:12:48 +08:00
Xboard 5c8d9da490 Merge pull request #7 from rebecca554owen/patch-1
修改单词拼写错误。
2023-11-22 23:25:27 +08:00
xboard 59b458c593 fix: 修复知识库 access start 在webman中重新定义的问题 2023-11-22 21:33:19 +08:00
rebecca554owen 4c29096e70 Update 从aapanel迁移到1panel教程.md 2023-11-22 19:38:56 +08:00
Xboard 8dc63989d8 Merge pull request #6 from rebecca554owen/dev
内置Redis后修改教程。
2023-11-22 19:35:03 +08:00
rebecca554owen e88d2a84da Update 从aapanel迁移到1panel教程.md 2023-11-22 19:33:01 +08:00
rebecca554owen 0f79848afd Update 多开Xboard教程.md 2023-11-22 19:32:26 +08:00
rebecca554owen f9f2f6a88e Merge branch 'cedar2025:dev' into dev 2023-11-22 19:31:45 +08:00
rebecca554owen 1946ef12b4 Update 从aapanel迁移到1panel教程.md 2023-11-22 18:58:26 +08:00
xboard ff50b642fb docs: 修正aapanel安装指南当中配置php.ini的命令 2023-11-22 18:52:58 +08:00
rebecca554owen 9ed2855cda Update 从aapanel迁移到1panel教程.md 2023-11-22 18:48:01 +08:00
rebecca554owen 3f682cb78a Update 从aapanel迁移到1panel教程.md 2023-11-22 18:42:52 +08:00
Xboard d829194774 Update aapanel安装指南.md 2023-11-22 18:33:37 +08:00
xboard 952e196885 to: 增加迁移迁移配置文件前清除缓存 2023-11-22 18:32:29 +08:00
xboard d61c2d2f46 docs: 更新文档,增加迁移迁移配置文件前清除缓存 2023-11-22 18:26:19 +08:00
Xboard 2edb19943b Update 从aapanel迁移到1panel教程.md 2023-11-22 18:16:47 +08:00
xboard df8ee539fa docs: 补充aapanel + docker部署教程 2023-11-22 15:52:07 +08:00
xboard 7a64bde28a fix: 安装步骤当中修复错误的redis unix地址 2023-11-22 14:36:23 +08:00
Xboard 263b455806 Merge pull request #5 from rebecca554owen/dev
修正教程错误
2023-11-22 14:13:11 +08:00
xboard 88bc34ba8c docs: 优化部署、迁移文档、docker增加redis支持
1、优化部署、迁移
2、自动备份命令增加手动备份功能
3、docker部署集成redis
2023-11-22 14:01:58 +08:00
rebecca554owen 082f9e8ad7 多开Xboard建多个站点
多开Redis容器以便于多开Xboard容器
2023-11-22 13:37:33 +08:00
rebecca554owen 5983d0bb57 Update 从aapanel迁移到1panel教程.md 2023-11-22 13:09:33 +08:00
rebecca554owen 1aa99919a2 Add files via upload 2023-11-22 13:05:07 +08:00
xboard b953f4e661 style:[用户前端] 修复公告背景图显示不正常的问题 2023-11-22 07:50:12 +08:00
xboard 9da5de3633 style: 修改后台Hysteri节点颜色为蓝色 2023-11-21 19:25:30 +08:00
xboard 47badf98be chore: docker 环境增加json、ico文件访问支持 2023-11-21 19:15:32 +08:00
xboard 937351a489 style:[用户前端] 知识库添加Markdown支持 2023-11-21 16:59:55 +08:00
xboard 5da7bac12a perf: 优化用户流量消费队列(上万用户流量信息数秒即可处理完成 2023-11-21 15:59:06 +08:00
xboard def4fdc75c style:[用户前端] 修复手机浏览器登录、注册、找回密码 点显示密码按钮无反应 2023-11-21 08:09:35 +08:00
xboard 9778b8a7a9 style:[用户前端] 修复登录、注册、找回密码页面LOGO不居中的问题 2023-11-21 07:58:21 +08:00
xboard d3142cebfa style:[用户前端] 修复注册、登录、找回密码界面LOGO过大溢出的问题 2023-11-21 07:53:57 +08:00
xboard 9ec03ba742 fix: [用户前端]修复仪表盘页公告不显示背景的问题 2023-11-20 22:38:23 +08:00
xboard af0b6854c3 style: [用户界面]手机端增加侧边栏关闭按钮 2023-11-20 22:04:35 +08:00
xboard 8f3c69a7ef style: [用户前端]公告支持Markdown渲染的同时增加HTML渲染,优化登录、注册、找回密码页面显示效果 2023-11-20 20:54:43 +08:00
xboard 6e371a550d docs:增加laravels测试数据 2023-11-20 18:37:44 +08:00
xboard aef9677a30 docs: 增加性能测试、页面展示 2023-11-20 18:06:42 +08:00
Xboard 1585098392 Update readme.md 2023-11-20 14:01:47 +08:00
xboard da011db721 fix: 修复mysql5.7和sqlite环境下无法上报流量的问题 2023-11-20 13:53:11 +08:00
xboard 04f620966a docs: update readme 2023-11-20 12:40:42 +08:00
xboard 21b86002ba docs: 更新迁移引导 2023-11-20 11:56:38 +08:00
xboard 83f0bdfb97 feat: php artisan reset:password重置密码增加可自定义密码 2023-11-20 09:38:14 +08:00
xboard 7e3771f12c refactor: 规范MysqlLogger代码 2023-11-20 09:37:22 +08:00
xboard e9a2634649 style(clahs): 恢复默认原版clash模版 2023-11-20 09:36:21 +08:00
xboard cfb118e6ec style: 公告修改为markdown格式显示 2023-11-19 22:07:10 +08:00
xboard 04b9990ab6 fix: [用户前端]修复查看教程不动态显示站点名称 2023-11-19 21:37:55 +08:00
xboard 7c89e2d9de fix: 修复sqlite执行数据库字段修改迁移出错的问题 2023-11-19 21:04:52 +08:00
xboard 69be37e77d fix: 修改v2_setting的value为text类型,防止过长的配置抱错 2023-11-19 20:51:52 +08:00
xboard 71b3e3fbe0 style: [用户前端]优化手机端体验 2023-11-19 20:42:39 +08:00
xboard 5a6f503f94 fix: [用户前端]修复主页订阅过期用户点击续费订阅无效的问题 2023-11-19 15:27:03 +08:00
xboard 8bd883ab59 docs: 修改文档目录 2023-11-19 15:18:32 +08:00
xboard 494ea58ad8 feat: [用户前端]补全可选订阅类型 2023-11-19 14:15:52 +08:00
xboard 432940c410 fix: 修复使用邀请链接注册不会自动填写邀请码的问题、修复webman环境下节点不可排序的问题 2023-11-19 12:48:37 +08:00
xboard 72ea53aa15 feat: 兼容V2bx 的Hysteria2 2023-11-19 09:54:40 +08:00
xboard 608ac4271d fix: 修复soga后端、Tidalab、等一些后端对接获取配置失败的问题
修复添加了服务后端中间件统一鉴权导致了一些后端鉴权不通过的问题
2023-11-19 04:03:09 +08:00
xboard a258f96ae3 feat: 添加·定时自动备份并上传到谷歌云存储·的功能 2023-11-18 19:54:16 +08:00
xboard ff19af3115 feat: 增加Xboard主题自定义页脚HTML支持 2023-11-18 16:58:01 +08:00
xboard ce62e6ea36 fix: 修复Vless Grpc ws不可用的问题 2023-11-18 15:31:10 +08:00
xboard f9bc84cda2 update: updata.sh 2023-11-18 14:44:44 +08:00
xboard 12bf2521c8 fix: [用户前端]修复订单折扣金额不计算的问题 2023-11-18 12:26:34 +08:00
xboard f91ccb82c8 fix: [用户前端]修复开启邮箱后缀白名单后用户注册的问题 2023-11-18 10:59:19 +08:00
xboard 21ade0f0e5 fix: 去除默认clash订阅中的 quic协议的dns防止clash客户端不可用 2023-11-18 09:56:33 +08:00
xboard 77b9594c35 to: 添加alive空接口 2023-11-18 09:10:55 +08:00
xboard 4185ead8b0 style: [用户前端]优化流量明细页面显示效果,docker环境支持wasm文件支持 2023-11-18 03:29:46 +08:00
xboard 601e46a460 fix: [用户前端] 流量明细记录时间精度修改为天 2023-11-17 16:37:09 +08:00
xboard d57386ccbd fix: 修复vless的 ws、grpc订阅问题 2023-11-17 16:34:16 +08:00
xboard 33c69f0497 fix: [用户前端]修复暗黑模式下的登录页面背景颜色显示问题 2023-11-17 15:37:04 +08:00
xboard dc0ac0fc46 fix: 修复meta 的vless grpc订阅下发错误 2023-11-17 15:11:52 +08:00
xboard 4ab8a9cb3c Initial commit 2023-11-17 14:44:01 +08:00
1883 changed files with 239584 additions and 0 deletions

No files matched your search

+3
View File
@@ -0,0 +1,3 @@
*
!.gitignore
!redis
+2
View File
@@ -0,0 +1,2 @@
*
!.gitignore
+35
View File
@@ -0,0 +1,35 @@
# Xboard protocol fusion entrypoint.
#
# Caddy listens on a single public port and dispatches HTTP traffic to Octane
# while transparently upgrading WebSocket requests to the ws-server worker.
# This lets every external reverse proxy (nginx, Cloudflare, the user's own
# Caddy, ...) treat the panel as a single upstream and avoids exposing the
# 8076 WebSocket port directly.
{
admin off
auto_https off
persist_config off
log {
output stdout
format console
}
servers {
trusted_proxies static 0.0.0.0/0 ::/0
}
}
:{$CADDY_LISTEN_PORT:7001} {
@ws path /ws
reverse_proxy @ws 127.0.0.1:{$WS_PORT:8076}
reverse_proxy 127.0.0.1:{$OCTANE_INTERNAL_PORT:7002} {
header_up Host {host}
# X-Forwarded-For is auto-appended with our remote_addr by Caddy
# (enabled by the global trusted_proxies above), so Octane receives the
# full proxy chain and Laravel's TrustProxies middleware resolves the
# real client IP using its own trust list. We additionally surface the
# directly-connected peer as X-Real-IP for downstream consumers (logs,
# admin tools) that read it directly without TrustProxies.
header_up X-Real-IP {remote_host}
}
}
+25
View File
@@ -0,0 +1,25 @@
# Caddy config used by compose.split.yaml — the embedded image's Caddy is
# disabled in this mode and a dedicated Caddy container fronts independent
# web and ws-server containers reachable via the compose network.
{
admin off
auto_https off
persist_config off
log {
output stdout
format console
}
servers {
trusted_proxies static 0.0.0.0/0 ::/0
}
}
:7001 {
@ws path /ws
reverse_proxy @ws ws-server:8076
reverse_proxy web:7001 {
header_up Host {host}
header_up X-Real-IP {remote_host}
}
}
+152
View File
@@ -0,0 +1,152 @@
#!/bin/sh
set -e
# Resolve the binding scheme based on whether the embedded Caddy is enabled.
#
# When ENABLE_CADDY=true (default), Caddy owns the public port (7001) and
# dispatches traffic internally; Octane and ws-server bind to localhost only
# so they cannot be reached from outside the container.
#
# When ENABLE_CADDY=false (e.g. an external reverse proxy or split mode),
# Octane takes the public port directly to keep behaviour identical to the
# pre-Caddy releases.
if [ "${ENABLE_CADDY}" = "true" ]; then
: "${OCTANE_HOST:=127.0.0.1}"
: "${OCTANE_PORT:=7002}"
: "${WS_HOST:=127.0.0.1}"
: "${WS_PORT:=8076}"
: "${CADDY_LISTEN_PORT:=7001}"
else
: "${OCTANE_HOST:=0.0.0.0}"
: "${OCTANE_PORT:=7001}"
: "${WS_HOST:=0.0.0.0}"
: "${WS_PORT:=8076}"
fi
export OCTANE_HOST OCTANE_PORT WS_HOST WS_PORT CADDY_LISTEN_PORT
export OCTANE_INTERNAL_PORT="${OCTANE_PORT}"
# ---------------------------------------------------------------------------
# Auto-tune worker counts based on the host (CPU + memory).
#
# Heuristic: each PHP worker (Octane/Horizon) costs ~80 MiB. After reserving
# ~300 MiB for the always-on processes (caddy/redis/ws-server/masters), divide
# the remaining budget across roles. Any user-set ENV wins.
# ---------------------------------------------------------------------------
detect_cpus() {
if [ -r /sys/fs/cgroup/cpu.max ]; then
# cgroup v2: "<quota> <period>" or "max <period>"
read -r q p < /sys/fs/cgroup/cpu.max 2>/dev/null
if [ "$q" != "max" ] && [ -n "$q" ] && [ -n "$p" ] && [ "$p" -gt 0 ]; then
echo $(( (q + p - 1) / p ))
return
fi
fi
nproc 2>/dev/null || echo 1
}
detect_mem_mib() {
if [ -r /sys/fs/cgroup/memory.max ]; then
m=$(cat /sys/fs/cgroup/memory.max 2>/dev/null)
if [ "$m" != "max" ] && [ -n "$m" ]; then
echo $(( m / 1024 / 1024 ))
return
fi
fi
# No cgroup limit: avoid over-provisioning on big hosts. Cap the assumed
# budget to MEM_FALLBACK_MIB (default 1024) unless the user opts out by
# setting it explicitly. Use whichever is smaller of MemAvailable and cap.
avail=$(awk '/MemAvailable/ {print int($2/1024)}' /proc/meminfo 2>/dev/null || echo 1024)
cap=${MEM_FALLBACK_MIB:-1024}
[ "$avail" -lt "$cap" ] && echo "$avail" || echo "$cap"
}
CPUS=$(detect_cpus)
MEM_MIB=$(detect_mem_mib)
# Resource profile presets. RESOURCE_PROFILE selects ratios for the budget split:
# minimal - smallest possible footprint (~250-350 MiB), single octane worker,
# horizon capped to 1/1/1. Suitable for VPS with <=512 MiB RAM.
# balanced - default; ~80 MiB per worker, octane gets 25% of slots.
# performance - larger reserves for opcache/caches, more aggressive horizon caps.
# auto - same as balanced.
: "${RESOURCE_PROFILE:=auto}"
case "$RESOURCE_PROFILE" in
minimal) RESERVED_MIB=200; SLOT_MIB=100; OCT_NUM=1; OCT_DEN=1; OCT_FORCE=1; auto_horizon_mem=128; auto_octane_gc=64 ;;
performance) RESERVED_MIB=400; SLOT_MIB=70; OCT_NUM=1; OCT_DEN=3; OCT_FORCE=0; auto_horizon_mem=384; auto_octane_gc=256 ;;
balanced|auto|*) RESERVED_MIB=300; SLOT_MIB=80; OCT_NUM=1; OCT_DEN=4; OCT_FORCE=0; auto_horizon_mem=256; auto_octane_gc=128 ;;
esac
BUDGET=$(( MEM_MIB - RESERVED_MIB ))
[ "$BUDGET" -lt "$SLOT_MIB" ] && BUDGET=$SLOT_MIB
SLOTS=$(( BUDGET / SLOT_MIB ))
clamp() { v=$1; lo=$2; hi=$3; [ "$v" -lt "$lo" ] && v=$lo; [ "$v" -gt "$hi" ] && v=$hi; echo "$v"; }
if [ "$OCT_FORCE" = "1" ]; then
auto_octane=1
auto_dp=1; auto_biz=1; auto_notif=1
else
auto_octane=$(clamp $(( (SLOTS * OCT_NUM) / OCT_DEN )) 1 "$CPUS")
remaining=$(( SLOTS - auto_octane - 2 ))
[ "$remaining" -lt 3 ] && remaining=3
auto_dp=$(clamp $(( remaining / 2 )) 1 $(( CPUS * 2 )))
auto_biz=$(clamp $(( remaining / 4 )) 1 "$CPUS")
auto_notif=$(clamp $(( remaining / 4 )) 1 "$CPUS")
fi
# User-set ENV always wins.
: "${OCTANE_WORKERS:=$auto_octane}"
: "${OCTANE_TASK_WORKERS:=1}"
: "${OCTANE_MAX_REQUESTS:=500}"
: "${OCTANE_GARBAGE_MB:=$auto_octane_gc}"
: "${OCTANE_MAX_EXECUTION_TIME:=60}"
: "${HORIZON_DATA_PIPELINE_MAX:=$auto_dp}"
: "${HORIZON_BUSINESS_MAX:=$auto_biz}"
: "${HORIZON_NOTIFICATION_MAX:=$auto_notif}"
: "${HORIZON_WORKER_MEMORY_MB:=$auto_horizon_mem}"
: "${HORIZON_WORKER_MAX_TIME:=0}"
: "${HORIZON_WORKER_MAX_JOBS:=0}"
export OCTANE_WORKERS OCTANE_TASK_WORKERS OCTANE_MAX_REQUESTS \
OCTANE_GARBAGE_MB OCTANE_MAX_EXECUTION_TIME \
HORIZON_DATA_PIPELINE_MAX HORIZON_BUSINESS_MAX HORIZON_NOTIFICATION_MAX \
HORIZON_WORKER_MEMORY_MB HORIZON_WORKER_MAX_TIME HORIZON_WORKER_MAX_JOBS \
RESOURCE_PROFILE
echo "[entrypoint] Auto-tune (profile=${RESOURCE_PROFILE}): cpus=${CPUS} mem=${MEM_MIB}MiB slots=${SLOTS} -> octane=${OCTANE_WORKERS} horizon(dp/biz/notif)=${HORIZON_DATA_PIPELINE_MAX}/${HORIZON_BUSINESS_MAX}/${HORIZON_NOTIFICATION_MAX} horizon_worker_mem=${HORIZON_WORKER_MEMORY_MB}MB"
echo "[entrypoint] Horizon supervisors use balance=auto with minProcesses=1, so they scale up to the cap on demand and back down when idle."
redis_reachable() {
local host port
host=$(grep -E '^REDIS_HOST=' /www/.env 2>/dev/null | tail -1 | cut -d= -f2- | tr -d '"' | tr -d "'")
port=$(grep -E '^REDIS_PORT=' /www/.env 2>/dev/null | tail -1 | cut -d= -f2- | tr -d '"' | tr -d "'")
command -v redis-cli >/dev/null 2>&1 || return 1
[ -n "$host" ] || return 1
case "$host" in
/*) [ -S "$host" ] && redis-cli -s "$host" ping 2>/dev/null | grep -q PONG ;;
*) redis-cli -h "$host" -p "${port:-6379}" ping 2>/dev/null | grep -q PONG ;;
esac
}
if [ ! -s /www/.env ] || ! grep -qE '^INSTALLED=(1|true)$' /www/.env || echo " $* " | grep -q ' xboard:install '; then
echo "[entrypoint] Skipping xboard:update (not yet installed or running xboard:install)."
else
if redis_reachable; then
echo "[entrypoint] Running xboard:update (redis reachable, real drivers)..."
php /www/artisan xboard:update --no-interaction || \
echo "[entrypoint] WARNING: xboard:update failed; continuing so supervisor can boot anyway." >&2
else
echo "[entrypoint] Running xboard:update (redis not yet up, using array/sync drivers)..."
CACHE_DRIVER=array QUEUE_CONNECTION=sync SESSION_DRIVER=array \
php /www/artisan xboard:update --no-interaction || \
echo "[entrypoint] WARNING: xboard:update failed; continuing so supervisor can boot anyway." >&2
fi
fi
echo "[entrypoint] Starting services (caddy=${ENABLE_CADDY} web=${ENABLE_WEB} horizon=${ENABLE_HORIZON} ws=${ENABLE_WS_SERVER})..."
# Drop stale Octane/WorkerMan state files so the new master does not signal
# PIDs left over from a previous container run (causes Swoole kill EPERM).
rm -f /www/storage/logs/octane-server-state.json /www/storage/logs/xboard-ws-server.pid 2>/dev/null || true
chown -R www:www /www 2>/dev/null || true
chown redis:redis /data 2>/dev/null || true
exec "$@"
+17
View File
@@ -0,0 +1,17 @@
; Slim PHP defaults for the all-in-one container.
; Tunables are overridable via Docker ENV (PHP_MEMORY_LIMIT, etc.) if needed.
memory_limit = 256M
[opcache]
opcache.enable = 1
opcache.enable_cli = 0
opcache.memory_consumption = 96
opcache.interned_strings_buffer = 16
opcache.max_accelerated_files = 10000
opcache.validate_timestamps = 0
opcache.revalidate_freq = 0
opcache.fast_shutdown = 1
[swoole]
swoole.use_shortname = Off
+99
View File
@@ -0,0 +1,99 @@
[supervisord]
nodaemon=true
user=root
logfile=/dev/stdout
logfile_maxbytes=0
pidfil=/www/storage/logs/supervisor/supervisord.pid
loglevel=info
[program:octane]
process_name=%(program_name)s_%(process_num)02d
command=php /www/artisan octane:start --host=%(ENV_OCTANE_HOST)s --port=%(ENV_OCTANE_PORT)s --workers=%(ENV_OCTANE_WORKERS)s --task-workers=%(ENV_OCTANE_TASK_WORKERS)s --max-requests=%(ENV_OCTANE_MAX_REQUESTS)s
autostart=%(ENV_ENABLE_WEB)s
autorestart=true
user=www
redirect_stderr=true
stdout_logfile=/dev/stdout
stdout_logfile_maxbytes=0
stdout_logfile_backups=0
numprocs=1
stopwaitsecs=10
stopsignal=QUIT
stopasgroup=true
killasgroup=true
priority=100
[program:horizon]
process_name=%(program_name)s_%(process_num)02d
command=php /www/artisan horizon
autostart=%(ENV_ENABLE_HORIZON)s
autorestart=true
user=www
redirect_stderr=true
stdout_logfile=/dev/stdout
stdout_logfile_maxbytes=0
stdout_logfile_backups=0
numprocs=1
stopwaitsecs=3
stopsignal=SIGINT
stopasgroup=true
killasgroup=true
priority=200
[program:redis]
process_name=%(program_name)s_%(process_num)02d
command=redis-server --dir /data
--dbfilename dump.rdb
--save 900 1
--save 300 10
--save 60 10000
--port 0
--unixsocket /data/redis.sock
--unixsocketperm 777
autostart=%(ENV_ENABLE_REDIS)s
autorestart=true
user=redis
redirect_stderr=true
stdout_logfile=/dev/stdout
stdout_logfile_maxbytes=0
stdout_logfile_backups=0
numprocs=1
stopwaitsecs=3
stopsignal=TERM
stopasgroup=true
killasgroup=true
priority=300
[program:ws-server]
process_name=%(program_name)s_%(process_num)02d
command=php /www/artisan ws-server start --host=%(ENV_WS_HOST)s --port=%(ENV_WS_PORT)s
autostart=%(ENV_ENABLE_WS_SERVER)s
autorestart=true
user=www
redirect_stderr=true
stdout_logfile=/dev/stdout
stdout_logfile_maxbytes=0
stdout_logfile_backups=0
numprocs=1
stopwaitsecs=5
stopsignal=SIGINT
stopasgroup=true
killasgroup=true
priority=400
[program:caddy]
process_name=%(program_name)s_%(process_num)02d
command=caddy run --config /etc/caddy/Caddyfile --adapter caddyfile
autostart=%(ENV_ENABLE_CADDY)s
autorestart=true
user=root
redirect_stderr=true
stdout_logfile=/dev/stdout
stdout_logfile_maxbytes=0
stdout_logfile_backups=0
numprocs=1
stopwaitsecs=5
stopsignal=TERM
stopasgroup=true
killasgroup=true
priority=500
+26
View File
@@ -0,0 +1,26 @@
/node_modules
/config/v2board.php
/public/hot
/public/storage
/public/env.example.js
/storage/*.key
/vendor
.env
.env.backup
.phpunit.result.cache
.idea
.lock
Homestead.json
Homestead.yaml
npm-debug.log
yarn-error.log
composer.phar
composer.lock
yarn.lock
docker-compose.yml
.DS_Store
/docker
storage/laravels.conf
storage/laravels.pid
storage/laravels-timer-process.pid
/frontend
Executable
+15
View File
@@ -0,0 +1,15 @@
root = true
[*]
charset = utf-8
end_of_line = lf
insert_final_newline = true
indent_style = space
indent_size = 4
trim_trailing_whitespace = true
[*.md]
trim_trailing_whitespace = false
[*.{yml,yaml}]
indent_size = 2
Executable
+42
View File
@@ -0,0 +1,42 @@
APP_NAME=XBoard
APP_FULL_NAME="Deep Link"
APP_ENV=production
APP_KEY=base64:PZXk5vTuTinfeEVG5FpYv2l6WEhLsyvGpiWK7IgJJ60=
APP_DEBUG=false
APP_URL=http://localhost
LOG_CHANNEL=stack
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=xboard
DB_USERNAME=root
DB_PASSWORD=
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379
BROADCAST_DRIVER=log
CACHE_DRIVER=redis
QUEUE_CONNECTION=redis
MAIL_DRIVER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null
MAIL_FROM_ADDRESS=null
MAIL_FROM_NAME=null
MAILGUN_DOMAIN=
MAILGUN_SECRET=
# google cloud storage
ENABLE_AUTO_BACKUP_AND_UPDATE=false
GOOGLE_CLOUD_KEY_FILE=config/googleCloudStorageKey.json
GOOGLE_CLOUD_STORAGE_BUCKET=
# Prevent reinstallation
INSTALLED=false
Executable
+5
View File
@@ -0,0 +1,5 @@
* text=auto
*.css linguist-vendored
*.scss linguist-vendored
*.js linguist-vendored
CHANGELOG.md export-ignore
+39
View File
@@ -0,0 +1,39 @@
---
name: 🐛 问题反馈 | Bug Report
about: 提交使用过程中遇到的问题 | Report an issue
title: "Bug Report:"
labels: '🐛 bug'
assignees: ''
---
<!-- 🔴 请注意:XrayR等非XBoard问题请前往相应项目提问 -->
<!-- 🔴 Note: For XrayR and other non-XBoard issues, please report to their respective projects -->
> ⚠️ 请务必按照模板填写完整信息,没有详细描述的issue可能会被忽略或关闭
> ⚠️ Please follow the template to provide complete information, issues without detailed description may be ignored or closed
**基本信息 | Basic Info**
```yaml
XBoard版本 | Version:
部署方式 | Deployment: [Docker/手动部署]
PHP版本 | Version:
数据库 | Database:
```
**问题描述 | Description**
<!-- 简要描述你遇到的问题 -->
**复现步骤 | Steps**
<!-- 如何复现这个问题? -->
1.
2.
**相关截图 | Screenshots**
<!-- 拖拽图片到这里(请注意隐藏敏感信息)-->
**日志信息 | Logs**
<!-- storage/logs 目录下的日志 -->
```log
// 粘贴日志内容到这里
```
+28
View File
@@ -0,0 +1,28 @@
---
name: ✨ 功能请求 | Feature Request
about: 提交新功能建议或改进意见 | Suggest an idea
title: "Feature Request:"
labels: '✨ enhancement'
assignees: ''
---
> ⚠️ 请务必按照模板详细描述你的需求,没有详细描述的issue可能会被忽略或关闭
> ⚠️ Please follow the template to describe your request in detail, issues without detailed description may be ignored or closed
**需求描述 | Description**
<!-- 描述你希望添加的功能或改进建议 -->
**使用场景 | Use Case**
<!-- 描述这个功能会在什么场景下使用,解决什么问题 -->
**功能建议 | Suggestion**
<!-- 你期望这个功能是什么样的?可以描述一下具体实现方式 -->
```yaml
功能形式 | Type: [新功能/功能优化/界面改进]
预期效果 | Expected:
```
**补充说明 | Additional**
<!-- 其他补充说明或者参考示例 -->
+100
View File
@@ -0,0 +1,100 @@
name: Docker Build and Publish
on:
push:
branches: ["master", "new-dev"]
workflow_dispatch:
env:
REGISTRY: ghcr.io
IMAGE_NAME: ${{ github.repository }}
jobs:
build:
runs-on: ubuntu-latest
permissions:
contents: read
packages: write
id-token: write
steps:
- name: Checkout code
uses: actions/checkout@v4
with:
fetch-depth: 1
- name: Set up QEMU
uses: docker/setup-qemu-action@v3
with:
platforms: 'arm64,amd64'
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
with:
platforms: linux/amd64,linux/arm64
driver-opts: |
image=moby/buildkit:v0.20.0
network=host
- name: Free Disk Space
run: |
sudo rm -rf /usr/share/dotnet
sudo rm -rf /usr/local/lib/android
sudo rm -rf /opt/ghc
sudo rm -rf /opt/hostedtoolcache/CodeQL
sudo docker image prune -af
- name: Login to registry
uses: docker/login-action@v3
with:
registry: ${{ env.REGISTRY }}
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Extract metadata
id: meta
uses: docker/metadata-action@v5
with:
images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
tags: |
type=ref,event=branch
type=sha,format=short,prefix=,enable=true
type=raw,value=new,enable=${{ github.ref == 'refs/heads/master' }}
type=raw,value=latest,enable=${{ github.ref == 'refs/heads/master' }}
type=raw,value=${{ steps.get_version.outputs.version }}
labels: |
org.opencontainers.image.source=${{ github.server_url }}/${{ github.repository }}
org.opencontainers.image.revision=${{ github.sha }}
- name: Get version
id: get_version
run: echo "version=$(git describe --tags --always)" >> $GITHUB_OUTPUT
- name: Update version in app.php
run: |
VERSION=$(date '+%Y%m%d')-$(git rev-parse --short HEAD)
sed -i "s/'version' => '.*'/'version' => '$VERSION'/g" config/app.php
echo "Updated version to: $VERSION"
- name: Build and push
id: build-and-push
uses: docker/build-push-action@v5
with:
context: .
push: true
platforms: linux/amd64,linux/arm64
cache-from: type=gha
cache-to: type=gha,mode=max
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
build-args: |
BUILDKIT_INLINE_CACHE=1
BUILDKIT_MULTI_PLATFORM=1
CACHEBUST=${{ github.sha }}
REPO_URL=https://github.com/${{ github.repository }}
BRANCH_NAME=${{ github.ref_name }}
provenance: false
outputs: type=registry,push=true
allow: |
network.host
Executable
+50
View File
@@ -0,0 +1,50 @@
/node_modules
/config/v2board.php
/config/googleCloudStorageKey.json
/public/hot
/public/storage
/public/env.example.js
*.user.ini
/storage/*.key
/vendor
.env
.env.backup
.phpunit.result.cache
.idea
Homestead.json
Homestead.yaml
npm-debug.log
yarn-error.log
composer.phar
yarn.lock
docker-compose.yml
.DS_Store
/docker
storage/laravels.conf
storage/laravels.pid
storage/update_pending
storage/laravels-timer-process.pid
cli-php.ini
frontend
docker-compose.yaml
bun.lockb
compose.yaml
compose.host.yaml
compose.split.yaml
.scribe
# Generated tutorial previews and publication exports
# Local Vite dev-server opt-in (never publish)
/storage/framework/stellar-vite.hot
# Separate frontend repository (commit it independently)
/theme/Stellar/source/
# Local reports, backups, screenshots and private operational records
/codex/output/
/deliverables/
# Local native-client build products
/macos-client/build/
/macos-client/.build/
/macos-client/.swiftpm/
/storage/app/private/
+3
View File
@@ -0,0 +1,3 @@
[submodule "public/assets/admin"]
path = public/assets/admin
url = https://github.com/cedar2025/xboard-admin-dist.git
+30
View File
@@ -0,0 +1,30 @@
# XB / 衍生项目维护
当前统一架构必读:[共用后端与主题](docs/maintenance/UNIFIED_BACKEND.md)。本地DPL/HN只维护当前XB后端;所有主题源在theme/,HN环境/数据在instances/hn/。原HN独立工作树已退出运行,禁止继续作为活动后端开发。
处理XB及任何衍生项目,必须先读[XB AI工作规则](docs/maintenance/AI_WORK_RULES.md);涉及XB核心修改须在写入前取得用户针对该具体变更的明确批准。
先读 [GemDocs AI版 项目总览](/Users/hellcat/Documents/GemDocs/AI版/项目总览.md) 与首次会话的 [持续维护协议](/Users/hellcat/Documents/GemDocs/AI版/00-协作规范/维护协议.md),再阅读 [维护入口](docs/maintenance/README.md),再按任务范围阅读架构、业务约束、发布恢复与验收状态。用户最新明确要求优先;文档中的历史状态必须按当前代码和运行环境复核。
- 保留用户及其他任务既有修改,提交只包含本次范围;不要重置或清理无关文件。
- 默认 Git 发布:提交、推送,再让服务器更新到明确版本并验证;未经明确要求不得打包覆盖。
- 前台 theme/Stellar/source/ 是独立仓库;后台资源是锁定版本的 Git 子模块,不能混入后端提交或直接改第三方构建产物。
- 修改功能时同步相应维护说明与验收状态。原有业务约束见 docs/maintenance/BUSINESS_RULES.md。
- 文档放 docs/maintenance/;任务截图、日志与临时脚本放 codex/output/;密钥和私密配置不提交 Git。
- 本地开发优先 dev/热更新;构建用于发布或构建验证。相关检查与命令见 docs/maintenance/ARCHITECTURE.md。
- 后台界面功能变更仍实际验证显示、切换、保存与权限;HTTP 200 不代表界面可用。节点接入按用户2026-10-20长期要求,不再默认登录DPL或进行DPL页面验收;经白色机使用服务器侧正式脚本、应用模型/事务操作并回读线上数据,仍须完成订阅、联网/上报、权限、QA清理和旧资源回归。执行范围唯一入口见[服务器侧接入](docs/maintenance/NODE_BATCH_RUNTIME.md#服务器侧接入与验收)。测试、提交、发布和真实验收分别报告,未执行的步骤不能写成完成。
- 节点维护全流程(候选盘点、查重、DNS/中转配置、部署、验收和回退)优先在服务器侧完成,默认不打开线上网站;优先使用经白色机的SSH、已登记凭据及服务接口。第三方缺少可用接口或凭据且确需网页时,先说明具体缺口,仅按现有访问规则处理必要范围;不为补页面验收打开网站,不绕过强制验证。 具体流程见[服务器侧接入](docs/maintenance/NODE_BATCH_RUNTIME.md#服务器侧接入与验收)。
## 批量节点接入:默认启动一个子助手
后续新批次默认使用 [正式适配器入口](docs/maintenance/NODE_BATCH_RUNTIME.md),由 `configure-site.py` 固定计划,再由 `batch.py` 的 `ssh-site-v1` 运行;动态读取验收账号应得节点集合,不固定节点数量。没有有效验收账号时自动创建本任务受限测试用户并负责禁用收尾;SSH始终经已登记白色机。具体实现、证据续跑和原服务调查边界见该专题;旧冻结计划及其处理脚本不改摘要迁就新实现。仅维护脚本/文档不触发真实接入或线上创建测试用户。
用户要求执行批量节点接入(明确说批量,或同批接入两个及以上节点)时,主协调者必须默认启动一个子助手,无需再次询问是否使用助手:核查验收助手负责候选服务器、端口、中转与已有资源冲突核查,并独立审查脚本、测试并发/查重/恢复及执行接入验收。主协调者负责统一参数、展示编号、端口、唯一账本及生产写入。完整分工、执行关卡与消耗控制见 [批量接入协作流程](docs/maintenance/NODE_BATCH.md#多智能体协作流程)。
这项授权针对当前任务的子助手,不自动新建或分叉普通聊天,也不授权向已有聊天发消息。仅讨论方案、维护脚本/文档或单节点任务不自动触发。若子助手工具不可用、并发名额不足或助手失败,说明具体缺口并恢复/等待;未经用户明确允许,不静默省略角色或跳过验收。当前批次已有对应助手时复用,不重复启动。具体线上变更仍以用户本次接入授权为限;项目规则不启动无人值守接入。
- 新增候选按[容量筛选](docs/maintenance/NODE_BATCH_RUNTIME.md#候选容量筛选):物理内存小于1GB且已安装XrayR则排除,不以停服务绕过,不追溯停用已接入节点。
- 接入所需邮箱验证码,按用户2026-10-20长期授权,先用已登记的对应邮箱自行登录并只读取本次验证邮件;凭据仍走GemDocs统一字段入口,不改账号安全设置、不读取无关邮件。只有资料缺失、认证失败或必须人工完成的验证才请求用户协助;账号切换及网站访问边界继续适用。
本文件提供维护入口,不扩大当前任务授权,也不启动无人值守自动维护。
+52
View File
@@ -0,0 +1,52 @@
FROM phpswoole/swoole:php8.2-alpine
COPY --from=mlocati/php-extension-installer /usr/bin/install-php-extensions /usr/local/bin/
# Install PHP extensions one by one with lower optimization level for ARM64 compatibility
RUN CFLAGS="-O0" install-php-extensions pcntl && \
CFLAGS="-O0 -g0" install-php-extensions bcmath && \
install-php-extensions zip && \
install-php-extensions redis && \
apk --no-cache add shadow sqlite mysql-client mysql-dev mariadb-connector-c git patch supervisor redis caddy && \
addgroup -S -g 1000 www && adduser -S -G www -u 1000 www && \
(getent group redis || addgroup -S redis) && \
(getent passwd redis || adduser -S -G redis -H -h /data redis)
WORKDIR /www
COPY .docker /
# Add build arguments
ARG CACHEBUST=1
ARG REPO_URL=https://github.com/cedar2025/Xboard
ARG BRANCH_NAME=master
RUN echo "Attempting to clone branch: ${BRANCH_NAME} from ${REPO_URL} with CACHEBUST: ${CACHEBUST}" && \
rm -rf ./* && \
rm -rf .git && \
git config --global --add safe.directory /www && \
git clone --depth 1 --branch ${BRANCH_NAME} ${REPO_URL} . && \
git submodule update --init --recursive --force
COPY .docker/supervisor/supervisord.conf /etc/supervisor/conf.d/supervisord.conf
COPY .docker/caddy/Caddyfile /etc/caddy/Caddyfile
COPY .docker/php/zz-xboard.ini /usr/local/etc/php/conf.d/zz-xboard.ini
RUN composer install --no-cache --no-dev --no-security-blocking \
&& php artisan storage:link \
&& chown -R www:www /www \
&& chmod -R 775 /www \
&& mkdir -p /data \
&& chown redis:redis /data
ENV ENABLE_WEB=true \
ENABLE_HORIZON=true \
ENABLE_REDIS=true \
ENABLE_WS_SERVER=true \
ENABLE_CADDY=true
EXPOSE 7001
COPY .docker/entrypoint.sh /entrypoint.sh
RUN chmod +x /entrypoint.sh
ENTRYPOINT ["/entrypoint.sh"]
CMD ["/usr/bin/supervisord", "-c", "/etc/supervisor/conf.d/supervisord.conf"]
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2019 Tokumeikoi
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+112
View File
@@ -0,0 +1,112 @@
## dpl 项目维护
AI 接手入口见 [AGENTS.md](AGENTS.md),维护说明见 [docs/maintenance](docs/maintenance/README.md)。任务日志与截图仍保存在不纳入 Git 的 codex/output/。
---
# Xboard
<div align="center">
[![Telegram](https://img.shields.io/badge/Telegram-Channel-blue)](https://t.me/XboardOfficial)
![PHP](https://img.shields.io/badge/PHP-8.2+-green.svg)
![MySQL](https://img.shields.io/badge/MySQL-5.7+-blue.svg)
[![License](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)
</div>
## 📖 Introduction
Xboard is a modern panel system built on Laravel 11, focusing on providing a clean and efficient user experience.
## ✨ Features
- 🚀 Built with Laravel 12 + Octane for significant performance gains
- 🎨 Redesigned admin interface (React + Shadcn UI)
- 📱 Modern user frontend (Vue3 + TypeScript)
- 🐳 Ready-to-use Docker deployment solution
- 🎯 Optimized system architecture for better maintainability
## 🚀 Quick Start
```bash
git clone -b compose --depth 1 https://github.com/cedar2025/Xboard && \
cd Xboard && \
docker compose run -it --rm \
-e ENABLE_SQLITE=true \
-e ENABLE_REDIS=true \
-e ADMIN_ACCOUNT=[email protected] \
xboard php artisan xboard:install && \
docker compose up -d
```
> After installation, visit: http://SERVER_IP:7001
> ⚠️ Make sure to save the admin credentials shown during installation
## 📖 Documentation
### 🔄 Upgrade Notice
> 🚨 **Important:** This version involves significant changes. Please strictly follow the upgrade documentation and backup your database before upgrading. Note that upgrading and migration are different processes, do not confuse them.
### Development Guides
- [Plugin Development Guide](./docs/en/development/plugin-development-guide.md) - Complete guide for developing XBoard plugins
### Deployment Guides
- [Deploy with 1Panel](./docs/en/installation/1panel.md)
- [Deploy with Docker Compose](./docs/en/installation/docker-compose.md)
- [Deploy with aaPanel](./docs/en/installation/aapanel.md)
- [Deploy with aaPanel + Docker](./docs/en/installation/aapanel-docker.md) (Recommended)
### Migration Guides
- [Migrate from v2board dev](./docs/en/migration/v2board-dev.md)
- [Migrate from v2board 1.7.4](./docs/en/migration/v2board-1.7.4.md)
- [Migrate from v2board 1.7.3](./docs/en/migration/v2board-1.7.3.md)
## 🛠️ Tech Stack
- Backend: Laravel 11 + Octane
- Admin Panel: React + Shadcn UI + TailwindCSS
- User Frontend: Vue3 + TypeScript + NaiveUI
- Deployment: Docker + Docker Compose
- Caching: Redis + Octane Cache
## 📷 Preview
![Admin Preview](./docs/images/admin.png)
![User Preview](./docs/images/user.png)
## ⚠️ Disclaimer
This project is for learning and communication purposes only. Users are responsible for any consequences of using this project.
## ❤️ Support The Project
If this project has helped you, donations are appreciated. They help support ongoing maintenance and would make me very happy.
TRC20: `TLypStEWsVrj6Wz9mCxbXffqgt5yz3Y4XB`
## 🌟 Maintenance Notice
This project is currently under light maintenance. We will:
- Fix critical bugs and security issues
- Review and merge important pull requests
- Provide necessary updates for compatibility
However, new feature development may be limited.
## 🔔 Important Notes
1. Restart required after modifying admin path:
```bash
docker compose restart
```
2. For aaPanel installations, restart the Octane daemon process
## 🤝 Contributing
Issues and Pull Requests are welcome to help improve the project.
## 📈 Star History
[![Stargazers over time](https://starchart.cc/cedar2025/Xboard.svg)](https://starchart.cc/cedar2025/Xboard)
+100
View File
@@ -0,0 +1,100 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Google\Cloud\Storage\StorageClient;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Log;
use Symfony\Component\Process\Process;
class BackupDatabase extends Command
{
protected $signature = 'backup:database {upload?}';
protected $description = '备份数据库并上传到 Google Cloud Storage';
public function handle()
{
$isUpload = $this->argument('upload');
// 如果是上传到云端则判断是否存在必要配置
if($isUpload){
$requiredConfigs = ['database.connections.mysql', 'cloud_storage.google_cloud.key_file', 'cloud_storage.google_cloud.storage_bucket'];
foreach ($requiredConfigs as $config) {
if (blank(config($config))) {
$this->error("❌:缺少必要配置项: $config , 取消备份");
return;
}
}
}
// 数据库备份逻辑
try{
if (config('database.default') === 'mysql'){
$databaseBackupPath = storage_path('backup/' . now()->format('Y-m-d_H-i-s') . '_' . config('database.connections.mysql.database') . '_database_backup.sql');
$this->info("1️⃣:开始备份Mysql");
\Spatie\DbDumper\Databases\MySql::create()
->setHost(config('database.connections.mysql.host'))
->setPort(config('database.connections.mysql.port'))
->setDbName(config('database.connections.mysql.database'))
->setUserName(config('database.connections.mysql.username'))
->setPassword(config('database.connections.mysql.password'))
->dumpToFile($databaseBackupPath);
$this->info("2️⃣:Mysql备份完成");
}elseif(config('database.default') === 'sqlite'){
$databaseBackupPath = storage_path('backup/' . now()->format('Y-m-d_H-i-s') . '_sqlite' . '_database_backup.sql');
$this->info("1️⃣:开始备份Sqlite");
\Spatie\DbDumper\Databases\Sqlite::create()
->setDbName(config('database.connections.sqlite.database'))
->dumpToFile($databaseBackupPath);
$this->info("2️⃣:Sqlite备份完成");
}else{
$this->error('备份失败,你的数据库不是sqlite或者mysql');
return;
}
$this->info('3️⃣:开始压缩备份文件');
// 使用 gzip 压缩备份文件
$compressedBackupPath = $databaseBackupPath . '.gz';
$gzipCommand = new Process(["gzip", "-c", $databaseBackupPath]);
$gzipCommand->run();
// 检查压缩是否成功
if ($gzipCommand->isSuccessful()) {
// 压缩成功,你可以删除原始备份文件
file_put_contents($compressedBackupPath, $gzipCommand->getOutput());
$this->info('4️⃣:文件压缩成功');
unlink($databaseBackupPath);
} else {
// 压缩失败,处理错误
echo $gzipCommand->getErrorOutput();
$this->error('😔:文件压缩失败');
unlink($databaseBackupPath);
return;
}
if (!$isUpload){
$this->info("🎉:数据库成功备份到:$compressedBackupPath");
}else{
// 传到云盘
$this->info("5️⃣:开始将备份上传到Google Cloud");
// Google Cloud Storage 配置
$storage = new StorageClient([
'keyFilePath' => config('cloud_storage.google_cloud.key_file'),
]);
$bucket = $storage->bucket(config('cloud_storage.google_cloud.storage_bucket'));
$objectName = 'backup/' . now()->format('Y-m-d_H-i-s') . '_database_backup.sql.gz';
// 上传文件
$bucket->upload(fopen($compressedBackupPath, 'r'), [
'name' => $objectName,
]);
// 输出文件链接
Log::channel('backup')->info("🎉:数据库备份已上传到 Google Cloud Storage: $objectName");
$this->info("🎉:数据库备份已上传到 Google Cloud Storage: $objectName");
File::delete($compressedBackupPath);
}
}catch(\Exception $e){
Log::channel('backup')->error("😔:数据库备份失败 \n" . $e);
$this->error("😔:数据库备份失败\n" . $e);
File::delete($compressedBackupPath);
}
}
}
+129
View File
@@ -0,0 +1,129 @@
<?php
namespace App\Console\Commands;
use App\Models\CommissionLog;
use Illuminate\Console\Command;
use App\Models\Order;
use App\Models\User;
use Illuminate\Support\Facades\DB;
class CheckCommission extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'check:commission';
/**
* The console command description.
*
* @var string
*/
protected $description = '返佣服务';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
$this->autoCheck();
$this->autoPayCommission();
}
public function autoCheck()
{
if ((int)admin_setting('commission_auto_check_enable', 1)) {
Order::where('commission_status', 0)
->where('invite_user_id', '!=', NULL)
->where('status', 3)
->where('updated_at', '<=', strtotime('-3 day', time()))
->update([
'commission_status' => 1
]);
}
}
public function autoPayCommission()
{
$orders = Order::where('commission_status', 1)
->where('invite_user_id', '!=', NULL)
->get();
foreach ($orders as $order) {
try{
DB::beginTransaction();
if (!$this->payHandle($order->invite_user_id, $order)) {
DB::rollBack();
continue;
}
$order->commission_status = 2;
if (!$order->save()) {
DB::rollBack();
continue;
}
DB::commit();
} catch (\Exception $e){
DB::rollBack();
throw $e;
}
}
}
public function payHandle($inviteUserId, Order $order)
{
$level = 3;
if ((int)admin_setting('commission_distribution_enable', 0)) {
$commissionShareLevels = [
0 => (int)admin_setting('commission_distribution_l1'),
1 => (int)admin_setting('commission_distribution_l2'),
2 => (int)admin_setting('commission_distribution_l3')
];
} else {
$commissionShareLevels = [
0 => 100
];
}
for ($l = 0; $l < $level; $l++) {
$inviter = User::find($inviteUserId);
if (!$inviter) continue;
if (!isset($commissionShareLevels[$l])) continue;
$commissionBalance = $order->commission_balance * ($commissionShareLevels[$l] / 100);
if (!$commissionBalance) continue;
if ((int)admin_setting('withdraw_close_enable', 0)) {
$inviter->increment('balance', $commissionBalance);
} else {
$inviter->increment('commission_balance', $commissionBalance);
}
if (!$inviter->save()) {
DB::rollBack();
return false;
}
CommissionLog::create([
'invite_user_id' => $inviteUserId,
'user_id' => $order->user_id,
'trade_no' => $order->trade_no,
'order_amount' => $order->total_amount,
'get_amount' => $commissionBalance
]);
$inviteUserId = $inviter->invite_user_id;
// update order actual commission balance
$order->actual_commission_balance = $order->actual_commission_balance + $commissionBalance;
}
return true;
}
}
+53
View File
@@ -0,0 +1,53 @@
<?php
namespace App\Console\Commands;
use App\Jobs\OrderHandleJob;
use App\Services\OrderService;
use Illuminate\Console\Command;
use App\Models\Order;
use App\Models\User;
use App\Models\Plan;
use Illuminate\Support\Facades\DB;
class CheckOrder extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'check:order';
/**
* The console command description.
*
* @var string
*/
protected $description = '订单检查任务';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
Order::whereIn('status', [Order::STATUS_PENDING, Order::STATUS_PROCESSING])
->orderBy('created_at', 'ASC')
->lazyById(200)
->each(function ($order) {
OrderHandleJob::dispatch($order->trade_no);
});
}
}
+64
View File
@@ -0,0 +1,64 @@
<?php
namespace App\Console\Commands;
use App\Services\ServerService;
use App\Services\TelegramService;
use App\Utils\CacheKey;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Cache;
class CheckServer extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'check:server';
/**
* The console command description.
*
* @var string
*/
protected $description = '节点检查任务';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
$this->checkOffline();
}
private function checkOffline()
{
$servers = ServerService::getAllServers();
foreach ($servers as $server) {
if ($server['parent_id']) continue;
if ($server['last_check_at'] && (time() - $server['last_check_at']) > 1800) {
$telegramService = new TelegramService();
$message = sprintf(
"节点掉线通知\r\n----\r\n节点名称:%s\r\n节点地址:%s\r\n",
$server['name'],
$server['host']
);
$telegramService->sendMessageWithAdmin($message);
Cache::forget(CacheKey::get(sprintf("SERVER_%s_LAST_CHECK_AT", strtoupper($server['type'])), $server->id));
}
}
}
}
+51
View File
@@ -0,0 +1,51 @@
<?php
namespace App\Console\Commands;
use App\Models\Ticket;
use Illuminate\Console\Command;
class CheckTicket extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'check:ticket';
/**
* The console command description.
*
* @var string
*/
protected $description = '工单检查任务';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
Ticket::where('status', 0)
->where('updated_at', '<=', time() - 24 * 3600)
->where('reply_status', Ticket::REPLY_STATUS_REPLIED)
->lazyById(200)
->each(function ($ticket) {
if ($ticket->user_id === $ticket->last_reply_user_id) return;
$ticket->status = Ticket::STATUS_CLOSED;
$ticket->save();
});
}
}
@@ -0,0 +1,63 @@
<?php
namespace App\Console\Commands;
use App\Models\Server;
use App\Models\User;
use App\Services\NodeSyncService;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Redis;
class CheckTrafficExceeded extends Command
{
protected $signature = 'check:traffic-exceeded';
protected $description = '检查流量超标用户并通知节点';
public function handle()
{
$count = Redis::scard('traffic:pending_check');
if ($count <= 0) {
return;
}
$pendingUserIds = array_map('intval', Redis::spop('traffic:pending_check', $count));
$exceededUsers = User::toBase()
->whereIn('id', $pendingUserIds)
->whereRaw('u + d >= transfer_enable')
->where('transfer_enable', '>', 0)
->where('banned', 0)
->select(['id', 'group_id'])
->get();
if ($exceededUsers->isEmpty()) {
return;
}
$groupedUsers = $exceededUsers->groupBy('group_id');
$notifiedCount = 0;
foreach ($groupedUsers as $groupId => $users) {
if (!$groupId) {
continue;
}
$userIdsInGroup = $users->pluck('id')->toArray();
$servers = Server::whereJsonContains('group_ids', (string) $groupId)->get();
foreach ($servers as $server) {
if (!NodeSyncService::isNodeOnline($server->id)) {
continue;
}
NodeSyncService::push($server->id, 'sync.user.delta', [
'action' => 'remove',
'users' => array_map(fn($id) => ['id' => $id], $userIdsInGroup),
]);
$notifiedCount++;
}
}
$this->info("Checked " . count($pendingUserIds) . " users, notified {$notifiedCount} nodes for " . $exceededUsers->count() . " exceeded users.");
}
}
@@ -0,0 +1,27 @@
<?php
namespace App\Console\Commands;
use App\Models\User;
use Illuminate\Console\Command;
class CleanupOnlineStatus extends Command
{
protected $signature = 'cleanup:online-status';
protected $description = 'Reset stale online_count for users whose devices have expired from Redis';
public function handle(): void
{
$affected = User::where('online_count', '>', 0)
->where(function ($query) {
$query->where('last_online_at', '<', now()->subMinutes(10))
->orWhereNull('last_online_at');
})
->update(['online_count' => 0]);
if ($affected > 0) {
$this->info("Reset online_count for {$affected} stale users.");
}
}
}
+51
View File
@@ -0,0 +1,51 @@
<?php
namespace App\Console\Commands;
use App\Models\Ticket;
use App\Models\User;
use Illuminate\Console\Command;
class ClearUser extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'clear:user';
/**
* The console command description.
*
* @var string
*/
protected $description = '清理用户';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
$builder = User::where('plan_id', NULL)
->where('transfer_enable', 0)
->where('expired_at', 0)
->where('last_login_at', NULL);
$count = $builder->count();
if ($builder->delete()) {
$this->info("已删除{$count}位没有任何数据的用户");
}
}
}
+42
View File
@@ -0,0 +1,42 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Str;
class HookList extends Command
{
protected $signature = 'hook:list';
protected $description = '列出系统支持的所有 hooks(静态扫描代码)';
public function handle()
{
$paths = [base_path('app'), base_path('plugins-core'), base_path('plugins')];
$hooks = collect();
$pattern = '/HookManager::(call|filter|register|registerFilter)\([\'\"]([a-zA-Z0-9_.-]+)[\'\"]/';
foreach ($paths as $path) {
$files = collect(
is_dir($path) ? (new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($path))) : []
)->filter(fn($f) => Str::endsWith($f, '.php'));
foreach ($files as $file) {
$content = @file_get_contents($file);
if ($content && preg_match_all($pattern, $content, $matches)) {
foreach ($matches[2] as $hook) {
$hooks->push($hook);
}
}
}
}
$hooks = $hooks->unique()->sort()->values();
if ($hooks->isEmpty()) {
$this->info('未扫描到任何 hook');
} else {
$this->info('All Supported Hooks:');
foreach ($hooks as $hook) {
$this->line(' ' . $hook);
}
}
}
}
+186
View File
@@ -0,0 +1,186 @@
<?php
namespace App\Console\Commands;
use App\Models\Setting;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\DB;
class MigrateFromV2b extends Command
{
protected $signature = 'migrateFromV2b {version?}';
protected $description = '供不同版本V2b迁移到本项目的脚本';
public function handle()
{
$version = $this->argument('version');
if($version === 'config'){
$this->MigrateV2ConfigToV2Settings();
return;
}
// Define your SQL commands based on versions
$sqlCommands = [
'dev231027' => [
// SQL commands for version Dev 2023/10/27
'ALTER TABLE v2_order ADD COLUMN surplus_order_ids TEXT NULL;',
'ALTER TABLE v2_plan DROP COLUMN daily_unit_price, DROP COLUMN transfer_unit_price;',
'ALTER TABLE v2_server_hysteria DROP COLUMN ignore_client_bandwidth, DROP COLUMN obfs_type;'
],
'1.7.4' => [
'CREATE TABLE `v2_server_vless` (
`id` INT AUTO_INCREMENT PRIMARY KEY,
`group_id` TEXT NOT NULL,
`route_id` TEXT NULL,
`name` VARCHAR(255) NOT NULL,
`parent_id` INT NULL,
`host` VARCHAR(255) NOT NULL,
`port` INT NOT NULL,
`server_port` INT NOT NULL,
`tls` BOOLEAN NOT NULL,
`tls_settings` TEXT NULL,
`flow` VARCHAR(64) NULL,
`network` VARCHAR(11) NOT NULL,
`network_settings` TEXT NULL,
`tags` TEXT NULL,
`rate` VARCHAR(11) NOT NULL,
`show` BOOLEAN DEFAULT 0,
`sort` INT NULL,
`created_at` INT NOT NULL,
`updated_at` INT NOT NULL
);'
],
'1.7.3' => [
'ALTER TABLE `v2_stat_order` RENAME TO `v2_stat`;',
"ALTER TABLE `v2_stat` CHANGE COLUMN order_amount paid_total INT COMMENT '订单合计';",
"ALTER TABLE `v2_stat` CHANGE COLUMN order_count paid_count INT COMMENT '邀请佣金';",
"ALTER TABLE `v2_stat` CHANGE COLUMN commission_amount commission_total INT COMMENT '佣金合计';",
"ALTER TABLE `v2_stat`
ADD COLUMN order_count INT NULL,
ADD COLUMN order_total INT NULL,
ADD COLUMN register_count INT NULL,
ADD COLUMN invite_count INT NULL,
ADD COLUMN transfer_used_total VARCHAR(32) NULL;
",
"CREATE TABLE `v2_log` (
`id` INT AUTO_INCREMENT PRIMARY KEY,
`title` TEXT NOT NULL,
`level` VARCHAR(11) NULL,
`host` VARCHAR(255) NULL,
`uri` VARCHAR(255) NOT NULL,
`method` VARCHAR(11) NOT NULL,
`data` TEXT NULL,
`ip` VARCHAR(128) NULL,
`context` TEXT NULL,
`created_at` INT NOT NULL,
`updated_at` INT NOT NULL
);",
'CREATE TABLE `v2_server_hysteria` (
`id` INT AUTO_INCREMENT PRIMARY KEY,
`group_id` VARCHAR(255) NOT NULL,
`route_id` VARCHAR(255) NULL,
`name` VARCHAR(255) NOT NULL,
`parent_id` INT NULL,
`host` VARCHAR(255) NOT NULL,
`port` VARCHAR(11) NOT NULL,
`server_port` INT NOT NULL,
`tags` VARCHAR(255) NULL,
`rate` VARCHAR(11) NOT NULL,
`show` BOOLEAN DEFAULT FALSE,
`sort` INT NULL,
`up_mbps` INT NOT NULL,
`down_mbps` INT NOT NULL,
`server_name` VARCHAR(64) NULL,
`insecure` BOOLEAN DEFAULT FALSE,
`created_at` INT NOT NULL,
`updated_at` INT NOT NULL
);',
"CREATE TABLE `v2_server_vless` (
`id` INT AUTO_INCREMENT PRIMARY KEY,
`group_id` TEXT NOT NULL,
`route_id` TEXT NULL,
`name` VARCHAR(255) NOT NULL,
`parent_id` INT NULL,
`host` VARCHAR(255) NOT NULL,
`port` INT NOT NULL,
`server_port` INT NOT NULL,
`tls` BOOLEAN NOT NULL,
`tls_settings` TEXT NULL,
`flow` VARCHAR(64) NULL,
`network` VARCHAR(11) NOT NULL,
`network_settings` TEXT NULL,
`tags` TEXT NULL,
`rate` VARCHAR(11) NOT NULL,
`show` BOOLEAN DEFAULT FALSE,
`sort` INT NULL,
`created_at` INT NOT NULL,
`updated_at` INT NOT NULL
);",
],
'wyx2685' => [
"ALTER TABLE `v2_plan` DROP COLUMN `device_limit`;",
"ALTER TABLE `v2_server_hysteria` DROP COLUMN `version`, DROP COLUMN `obfs`, DROP COLUMN `obfs_password`;",
"ALTER TABLE `v2_server_trojan` DROP COLUMN `network`, DROP COLUMN `network_settings`;",
"ALTER TABLE `v2_user` DROP COLUMN `device_limit`;"
]
];
if (!$version) {
$version = $this->choice('请选择你迁移前的V2board版本:', array_keys($sqlCommands));
}
if (array_key_exists($version, $sqlCommands)) {
try {
foreach ($sqlCommands[$version] as $sqlCommand) {
// Execute SQL command
DB::statement($sqlCommand);
}
$this->info('1️⃣、数据库差异矫正成功');
// 初始化数据库迁移
$this->call('db:seed', ['--class' => 'OriginV2bMigrationsTableSeeder']);
$this->info('2️⃣、数据库迁移记录初始化成功');
$this->call('xboard:update');
$this->info('3️⃣、更新成功');
$this->info("🎉:成功从 $version 迁移到Xboard");
} catch (\Exception $e) {
// An error occurred, rollback the transaction
$this->error('迁移失败'. $e->getMessage() );
}
} else {
$this->error("你所输入的版本未找到");
}
}
public function MigrateV2ConfigToV2Settings()
{
Artisan::call('config:clear');
$configValue = config('v2board') ?? [];
foreach ($configValue as $k => $v) {
// 检查记录是否已存在
$existingSetting = Setting::where('name', $k)->first();
// 如果记录不存在,则插入
if ($existingSetting) {
$this->warn("配置 {$k} 在数据库已经存在, 忽略");
continue;
}
Setting::create([
'name' => $k,
'value' => is_array($v)? json_encode($v) : $v,
]);
$this->info("配置 {$k} 迁移成功");
}
Artisan::call('config:cache');
$this->info('所有配置迁移完成');
}
}
@@ -0,0 +1,34 @@
<?php
namespace App\Console\Commands;
use App\WebSocket\NodeWorker;
use Illuminate\Console\Command;
class NodeWebSocketServer extends Command
{
protected $signature = 'ws-server
{action=start : start | stop | restart | reload | status}
{--d : Start in daemon mode}
{--host=0.0.0.0 : Listen address}
{--port=8076 : Listen port}';
protected $description = 'Start the WebSocket server for node-panel synchronization';
public function handle(): void
{
global $argv;
$action = $this->argument('action');
$argv[1] = $action;
if ($this->option('d')) {
$argv[2] = '-d';
}
$host = $this->option('host');
$port = $this->option('port');
$worker = new NodeWorker($host, $port);
$worker->run();
}
}
@@ -0,0 +1,16 @@
<?php
namespace App\Console\Commands;
use App\Services\PaymentHealth\Monitor;
use Illuminate\Console\Command;
class PaymentHealthCheck extends Command
{
protected $signature='payment:health-check';
protected $description='Probe configured EPay cashiers once per six-hour slot and manage only monitor-owned outages';
public function handle(Monitor $monitor): int
{
try{$this->line(json_encode($monitor->run(),JSON_UNESCAPED_UNICODE|JSON_THROW_ON_ERROR));return self::SUCCESS;}
catch(\Throwable $e){$this->error('payment_health_failed_closed: '.get_class($e));return self::FAILURE;}
}
}
+32
View File
@@ -0,0 +1,32 @@
<?php
namespace App\Console\Commands;
use App\Services\MailFlow\ImapInbox;
use App\Services\MailFlow\Settings;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Cache;
class PollMailInbox extends Command
{
protected $signature = 'mail:poll-inbox';
protected $description = 'Read new conventional mailbox headers and queue automatic acknowledgements';
public function handle(ImapInbox $inbox): int
{
if (!Settings::get('enabled') || !Settings::get('inbound_enabled')) {
return self::SUCCESS;
}
$lock = Cache::lock('mailflow:inbox', 1800);
if (!$lock->get()) { return self::SUCCESS; }
try {
$this->info('New incoming messages: ' . $inbox->poll());
return self::SUCCESS;
} catch (\Throwable $e) {
$this->error('Inbox polling failed (' . get_class($e) . '). Check the IMAP settings/extension.');
return self::FAILURE;
} finally {
$lock->release();
}
}
}
+59
View File
@@ -0,0 +1,59 @@
<?php
namespace App\Console\Commands;
use App\Jobs\SendMailMessageJob;
use App\Models\MailMessage;
use App\Services\MailFlow\DeliveryEvents;
use App\Services\MailFlow\Settings;
use Illuminate\Console\Command;
class ReconcileMail extends Command
{
protected $signature = 'mail:reconcile';
protected $description = 'Recover persisted mail tasks and delivery callbacks without cross-provider duplicates';
public function handle(DeliveryEvents $events): int
{
$enabled = Settings::get('enabled');
if (!$enabled && !\Illuminate\Support\Facades\Schema::hasTable('v2_mail_messages')) { return self::SUCCESS; }
if ($enabled) {
MailMessage::where('direction', 'event')->where('status', 'pending')->orderBy('id')->limit(50)->get()
->each(function ($event) use ($events) {
try { $events->apply($event, true); } catch (\Throwable $e) { /* retain for next poll */ }
});
if (Settings::get('resend_enabled') && Settings::get('resend_key')) {
$messages = MailMessage::where('direction', 'out')->where('channel', 'resend')
->whereNotNull('provider_id')->whereIn('status', ['submitted', 'delayed'])
->where('created_at', '>', now()->subDays(7))
->orderBy('updated_at')->orderBy('id')->limit(10)->get();
foreach ($messages as $message) {
try { $events->refreshStatus($message); }
catch (\Throwable $e) { break; } // Preserve status and retry next cycle, including rate limits.
if (!app()->runningUnitTests()) { usleep(600000); }
}
}
}
MailMessage::where('direction', 'out')->whereNotNull('payload')->where('updated_at', '<', now()->subMinutes(2))
->when(!$enabled, fn ($q) => $q->whereIn('purpose', ['service_expired', 'traffic_reminder', 'expiry_reminder', 'automatic_broadcast']))
->where(function ($query) {
$query->where('status', 'pending')->orWhere('status', 'sending')
->orWhere(fn ($q) => $q->where('status', 'unknown')->where('channel', 'resend'));
})->orderBy('id')->limit(100)->get()->each(function ($message) {
if ($message->attempts >= 6 && $message->status === 'unknown') {
$message->update(['payload' => null]);
return;
}
if ($message->attempts >= 6 && $message->status === 'pending') {
$message->update(['status' => 'failed', 'error_code' => 'mail_retry_exhausted', 'payload' => null]);
return;
}
SendMailMessageJob::dispatch($message->id);
});
MailMessage::where('direction', 'in')->where('created_at', '<', now()->subDays(30))->update(['payload' => null]);
// Verification/login content must not remain indefinitely in encrypted storage.
MailMessage::whereNotNull('payload')->where('direction', 'out')->where('first_attempt_at', '<', now()->subHours(23))
->update(['payload' => null]);
return self::SUCCESS;
}
}
+41
View File
@@ -0,0 +1,41 @@
<?php
namespace App\Console\Commands;
use App\Models\MailDailyReport;
use App\Services\MailFlow\DailyReportService;
use App\Services\MailFlow\Settings;
use Illuminate\Console\Command;
class ReportMailUsage extends Command
{
protected $signature = 'mail:report-usage';
protected $description = 'Report the latest complete 08:00-to-08:00 mail period through TeleHub';
public function handle(DailyReportService $reports): int
{
if (!Settings::get('enabled') || !Settings::get('report_enabled')
|| !config('mail_report.enabled', false) || config('app.env') !== 'production') return self::SUCCESS;
try {
$startDate = (string) config('mail_report.start_date');
if (!preg_match('/\A\d{4}-\d{2}-\d{2}\z/D', $startDate)) throw new \RuntimeException('mail_report_start_required');
$now = now()->setTimezone('Asia/Shanghai');
$end = $now->copy()->startOfDay()->setTime(8, 0);
if ($now->lt($end)) $end->subDay();
if ($end->copy()->subDay()->toDateString() >= $startDate) $reports->snapshot($end->utc());
$attention = false;
MailDailyReport::where('report_date', '>=', $startDate)->whereIn('status', ['pending', 'queued', 'sending'])
->orderBy('id')->limit(10)->get()->each(function ($report) use ($reports, &$attention) {
$reports->send($report);
$report->refresh();
$attention = $attention || in_array($report->status, ['failed', 'unknown', 'uncertain'], true) || $report->error_code !== null;
$this->line(json_encode(['id' => $report->id, 'report_date' => $report->report_date, 'status' => $report->status,
'error_code' => $report->error_code], JSON_UNESCAPED_UNICODE|JSON_THROW_ON_ERROR));
});
return $attention ? self::FAILURE : self::SUCCESS;
} catch (\Throwable $e) {
$this->error('mail_report_failed_closed: ' . get_class($e));
return self::FAILURE;
}
}
}
@@ -0,0 +1,14 @@
<?php
namespace App\Console\Commands;
use App\Services\OrderReporting\Reporter;
use Illuminate\Console\Command;
class ReportOrderPayments extends Command
{
protected $signature='orders:report-payments';
protected $description='Recover asynchronous payment notifications and snapshot the 08:00 payment report';
public function handle(Reporter $reports):int {
if(!$reports->enabled())return self::SUCCESS;
try {$recovered=$reports->reconcile();$daily=$reports->daily();$queued=$reports->queueDue();$this->line(json_encode(['recovered'=>$recovered,'daily_event_id'=>$daily?->id,'queued'=>$queued]));return self::SUCCESS;}
catch(\Throwable $e){$this->error('order_report_failed_closed: '.get_class($e));return self::FAILURE;}
}
}
@@ -0,0 +1,20 @@
<?php
namespace App\Console\Commands;
use App\Services\RegistrationReport\Reporter;
use Illuminate\Console\Command;
class ReportRegistrations extends Command
{
protected $signature = 'report:registrations {--dry-run : Preview counts without HTTP or state changes}';
protected $description = 'Report each instance registration count at 08:00 Asia/Shanghai through TeleHub';
public function handle(Reporter $reporter): int
{
try {
$result=$reporter->run(dryRun:(bool)$this->option('dry-run'));
$this->line(json_encode($result,JSON_UNESCAPED_UNICODE|JSON_THROW_ON_ERROR));
return ($result['needs_attention']??false) ? self::FAILURE : self::SUCCESS;
} catch (\Throwable $e) {
$this->error('registration_report_failed_closed: '.get_class($e));
return self::FAILURE;
}
}
}
+48
View File
@@ -0,0 +1,48 @@
<?php
namespace App\Console\Commands;
use App\Models\AdminAuditLog;
use App\Models\StatServer;
use App\Models\StatUser;
use Illuminate\Console\Command;
class ResetLog extends Command
{
protected $builder;
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'reset:log';
/**
* The console command description.
*
* @var string
*/
protected $description = '清空日志';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
StatUser::where('record_at', '<', strtotime('-2 month', time()))->delete();
StatServer::where('record_at', '<', strtotime('-2 month', time()))->delete();
AdminAuditLog::where('created_at', '<', strtotime('-3 month', time()))->delete();
}
}
+55
View File
@@ -0,0 +1,55 @@
<?php
namespace App\Console\Commands;
use App\Models\Plan;
use App\Utils\Helper;
use Illuminate\Console\Command;
use App\Models\User;
use Illuminate\Support\Facades\DB;
class ResetPassword extends Command
{
protected $builder;
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'reset:password {email} {password?}';
/**
* The console command description.
*
* @var string
*/
protected $description = '重置用户密码';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
$password = $this->argument('password') ;
$user = User::byEmail($this->argument('email'))->first();
if (!$user) abort(500, '邮箱不存在');
$password = $password ?? Helper::guid(false);
$user->password = password_hash($password, PASSWORD_DEFAULT);
$user->password_algo = null;
if (!$user->save()) abort(500, '重置失败');
$this->info("!!!重置成功!!!");
$this->info("新密码为:{$password},请尽快修改密码。");
}
}
+289
View File
@@ -0,0 +1,289 @@
<?php
namespace App\Console\Commands;
use App\Models\User;
use App\Models\TrafficResetLog;
use App\Services\TrafficResetService;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
class ResetTraffic extends Command
{
protected $signature = 'reset:traffic {--fix-null : 修正模式,重新计算next_reset_at为null的用户} {--force : 强制模式,重新计算所有用户的重置时间}';
protected $description = '流量重置 - 处理所有需要重置的用户';
public function __construct(
private readonly TrafficResetService $trafficResetService
) {
parent::__construct();
}
public function handle(): int
{
$fixNull = $this->option('fix-null');
$force = $this->option('force');
$this->info('🚀 开始执行流量重置任务...');
if ($fixNull) {
$this->warn('🔧 修正模式 - 将重新计算next_reset_at为null的用户');
} elseif ($force) {
$this->warn('⚡ 强制模式 - 将重新计算所有用户的重置时间');
}
try {
$result = $fixNull ? $this->performFix() : ($force ? $this->performForce() : $this->performReset());
$this->displayResults($result, $fixNull || $force);
return self::SUCCESS;
} catch (\Exception $e) {
$this->error("❌ 任务执行失败: {$e->getMessage()}");
Log::error('流量重置命令执行失败', [
'error' => $e->getMessage(),
'trace' => $e->getTraceAsString(),
]);
return self::FAILURE;
}
}
private function displayResults(array $result, bool $isSpecialMode): void
{
$this->info("✅ 任务完成!\n");
if ($isSpecialMode) {
$this->displayFixResults($result);
} else {
$this->displayExecutionResults($result);
}
}
private function displayFixResults(array $result): void
{
$this->info("📊 修正结果统计:");
$this->info("🔍 发现用户总数: {$result['total_found']}");
$this->info("✅ 成功修正数量: {$result['total_fixed']}");
$this->info("⏱️ 总执行时间: {$result['duration']} 秒");
if ($result['error_count'] > 0) {
$this->warn("⚠️ 错误数量: {$result['error_count']}");
$this->warn("详细错误信息请查看日志");
} else {
$this->info("✨ 无错误发生");
}
if ($result['total_found'] > 0) {
$avgTime = round($result['duration'] / $result['total_found'], 4);
$this->info("⚡ 平均处理速度: {$avgTime} 秒/用户");
}
}
private function displayExecutionResults(array $result): void
{
$this->info("📊 执行结果统计:");
$this->info("👥 处理用户总数: {$result['total_processed']}");
$this->info("🔄 重置用户数量: {$result['total_reset']}");
$this->info("⏱️ 总执行时间: {$result['duration']} 秒");
if ($result['error_count'] > 0) {
$this->warn("⚠️ 错误数量: {$result['error_count']}");
$this->warn("详细错误信息请查看日志");
} else {
$this->info("✨ 无错误发生");
}
if ($result['total_processed'] > 0) {
$avgTime = round($result['duration'] / $result['total_processed'], 4);
$this->info("⚡ 平均处理速度: {$avgTime} 秒/用户");
}
}
private function performReset(): array
{
$startTime = microtime(true);
$totalResetCount = 0;
$errors = [];
$users = $this->getResetQuery()->get();
if ($users->isEmpty()) {
$this->info("😴 当前没有需要重置的用户");
return [
'total_processed' => 0,
'total_reset' => 0,
'error_count' => 0,
'duration' => round(microtime(true) - $startTime, 2),
];
}
$this->info("找到 {$users->count()} 个需要重置的用户");
foreach ($users as $user) {
try {
$totalResetCount += (int) $this->trafficResetService->checkAndReset($user, TrafficResetLog::SOURCE_CRON);
} catch (\Exception $e) {
$errors[] = [
'user_id' => $user->id,
'email' => $user->email,
'error' => $e->getMessage(),
];
Log::error('用户流量重置失败', [
'user_id' => $user->id,
'error' => $e->getMessage(),
]);
}
}
return [
'total_processed' => $users->count(),
'total_reset' => $totalResetCount,
'error_count' => count($errors),
'duration' => round(microtime(true) - $startTime, 2),
];
}
private function performFix(): array
{
$startTime = microtime(true);
$nullUsers = $this->getNullResetTimeUsers();
if ($nullUsers->isEmpty()) {
$this->info("✅ 没有发现next_reset_at为null的用户");
return [
'total_found' => 0,
'total_fixed' => 0,
'error_count' => 0,
'duration' => round(microtime(true) - $startTime, 2),
];
}
$this->info("🔧 发现 {$nullUsers->count()} 个next_reset_at为null的用户,开始修正...");
$fixedCount = 0;
$errors = [];
foreach ($nullUsers as $user) {
try {
$nextResetTime = $this->trafficResetService->calculateNextResetTime($user);
if ($nextResetTime) {
$user->next_reset_at = $nextResetTime->timestamp;
$user->save();
$fixedCount++;
}
} catch (\Exception $e) {
$errors[] = [
'user_id' => $user->id,
'email' => $user->email,
'error' => $e->getMessage(),
];
Log::error('修正用户next_reset_at失败', [
'user_id' => $user->id,
'error' => $e->getMessage(),
]);
}
}
return [
'total_found' => $nullUsers->count(),
'total_fixed' => $fixedCount,
'error_count' => count($errors),
'duration' => round(microtime(true) - $startTime, 2),
];
}
private function performForce(): array
{
$startTime = microtime(true);
$allUsers = $this->getAllUsers();
if ($allUsers->isEmpty()) {
$this->info("✅ 没有发现需要处理的用户");
return [
'total_found' => 0,
'total_fixed' => 0,
'error_count' => 0,
'duration' => round(microtime(true) - $startTime, 2),
];
}
$this->info("⚡ 发现 {$allUsers->count()} 个用户,开始重新计算重置时间...");
$fixedCount = 0;
$errors = [];
foreach ($allUsers as $user) {
try {
$nextResetTime = $this->trafficResetService->calculateNextResetTime($user);
if ($nextResetTime) {
$user->next_reset_at = $nextResetTime->timestamp;
$user->save();
$fixedCount++;
}
} catch (\Exception $e) {
$errors[] = [
'user_id' => $user->id,
'email' => $user->email,
'error' => $e->getMessage(),
];
Log::error('强制重新计算用户next_reset_at失败', [
'user_id' => $user->id,
'error' => $e->getMessage(),
]);
}
}
return [
'total_found' => $allUsers->count(),
'total_fixed' => $fixedCount,
'error_count' => count($errors),
'duration' => round(microtime(true) - $startTime, 2),
];
}
private function getResetQuery()
{
return User::where('next_reset_at', '<=', time())
->whereNotNull('next_reset_at')
->where(function ($query) {
$query->where('expired_at', '>', time())
->orWhereNull('expired_at');
})
->where('banned', 0)
->whereNotNull('plan_id');
}
private function getNullResetTimeUsers()
{
return User::whereNull('next_reset_at')
->whereNotNull('plan_id')
->where(function ($query) {
$query->where('expired_at', '>', time())
->orWhereNull('expired_at');
})
->where('banned', 0)
->with('plan:id,name,reset_traffic_method')
->get();
}
private function getAllUsers()
{
return User::whereNotNull('plan_id')
->where(function ($query) {
$query->where('expired_at', '>', time())
->orWhereNull('expired_at');
})
->where('banned', 0)
->with('plan:id,name,reset_traffic_method')
->get();
}
}
+58
View File
@@ -0,0 +1,58 @@
<?php
namespace App\Console\Commands;
use App\Models\Plan;
use App\Utils\Helper;
use Illuminate\Console\Command;
use App\Models\User;
use Illuminate\Support\Facades\DB;
class ResetUser extends Command
{
protected $builder;
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'reset:user';
/**
* The console command description.
*
* @var string
*/
protected $description = '重置所有用户信息';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
if (!$this->confirm("确定要重置所有用户安全信息吗?")) {
return;
}
ini_set('memory_limit', -1);
$users = User::all();
foreach ($users as $user)
{
$user->token = Helper::guid();
$user->uuid = Helper::guid(true);
$user->save();
$this->info("已重置用户{$user->email}的安全信息");
}
}
}
@@ -0,0 +1,12 @@
<?php
namespace App\Console\Commands;
use App\Jobs\SendTelegramTicketJob;
use App\Models\TelegramTicketMessage;
use Illuminate\Console\Command;
class RetryTelegramTickets extends Command {
protected $signature='telegram:tickets:retry';protected $description='Queue pending ticket notifications without resending uncertain deliveries';
public function handle():int {
TelegramTicketMessage::where('status','sending')->where('updated_at','<',now()->subMinutes(5))->update(['status'=>'unknown','error_code'=>'worker_interrupted']);
TelegramTicketMessage::where('status','pending')->where('created_at','<',now()->subMinute())->where(fn($q)=>$q->whereNull('available_at')->orWhere('available_at','<=',now()))->limit(100)->get()->each(fn($r)=>SendTelegramTicketJob::dispatch($r->id));return self::SUCCESS;
}
}
@@ -0,0 +1,22 @@
<?php
namespace App\Console\Commands;
use App\Services\MailFlow\AutomaticMailPolicy;
use App\Services\MailFlow\ExpiredSubscriptionNotifier;
use Illuminate\Console\Command;
class SendExpiredSubscriptionMail extends Command
{
protected $signature = 'send:expiredSubscriptionMail';
protected $description = 'Queue current tier-two subscription expiry notifications';
public function handle(ExpiredSubscriptionNotifier $notifier): int
{
$state = AutomaticMailPolicy::state();
if ($state === null) { $this->warn('自动邮件档位暂不可读取'); return self::FAILURE; }
if ($state['level'] !== 2) { return self::SUCCESS; }
$this->info('套餐到期通知已派发:' . $notifier->queueDue());
return self::SUCCESS;
}
}
+108
View File
@@ -0,0 +1,108 @@
<?php
namespace App\Console\Commands;
use App\Services\MailService;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
class SendRemindMail extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'send:remindMail
{--chunk-size=500 : 每批处理的用户数量}
{--force : 强制执行,跳过确认}';
/**
* The console command description.
*
* @var string
*/
protected $description = '发送提醒邮件';
/**
* Execute the console command.
*
* @return int
*/
public function handle(): int
{
$state = \App\Services\MailFlow\AutomaticMailPolicy::state();
if (!$state || $state['level'] !== 1) {
$this->info('当前档位不派发流量及到期前提醒');
return 0;
}
if (!admin_setting('remind_mail_enable', false)) {
$this->warn('邮件提醒功能未启用');
return 0;
}
$chunkSize = max(100, min(2000, (int) $this->option('chunk-size')));
$mailService = new MailService();
$totalUsers = $mailService->getTotalUsersNeedRemind();
if ($totalUsers === 0) {
$this->info('没有需要发送提醒邮件的用户');
return 0;
}
$this->displayInfo($totalUsers, $chunkSize);
if (!$this->option('force') && !$this->confirm("确定要发送提醒邮件给 {$totalUsers} 个用户吗?")) {
return 0;
}
$startTime = microtime(true);
$progressBar = $this->output->createProgressBar((int) ceil($totalUsers / $chunkSize));
$progressBar->start();
$statistics = $mailService->processUsersInChunks($chunkSize, function () use ($progressBar) {
$progressBar->advance();
});
$progressBar->finish();
$this->newLine();
$this->displayResults($statistics, microtime(true) - $startTime);
$this->logResults($statistics);
return 0;
}
private function displayInfo(int $totalUsers, int $chunkSize): void
{
$this->table(['项目', '值'], [
['需要处理的用户', number_format($totalUsers)],
['批次大小', $chunkSize],
['预计批次', ceil($totalUsers / $chunkSize)],
]);
}
private function displayResults(array $stats, float $duration): void
{
$this->info('✅ 提醒邮件发送完成!');
$this->table(['统计项', '数量'], [
['总处理用户', number_format($stats['processed_users'])],
['过期提醒邮件', number_format($stats['expire_emails'])],
['流量提醒邮件', number_format($stats['traffic_emails'])],
['跳过用户', number_format($stats['skipped'])],
['错误数量', number_format($stats['errors'])],
['总耗时', round($duration, 2) . ' 秒'],
['平均速度', round($stats['processed_users'] / max($duration, 0.1), 1) . ' 用户/秒'],
]);
if ($stats['errors'] > 0) {
$this->warn("⚠️ 有 {$stats['errors']} 个用户的邮件发送失败,请检查日志");
}
}
private function logResults(array $statistics): void
{
Log::info('SendRemindMail命令执行完成', ['statistics' => $statistics]);
}
}
+41
View File
@@ -0,0 +1,41 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
class Test extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'test';
/**
* The console command description.
*
* @var string
*/
protected $description = '';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
}
}
+385
View File
@@ -0,0 +1,385 @@
<?php
namespace App\Console\Commands;
use App\Services\Plugin\PluginManager;
use Illuminate\Console\Command;
use Illuminate\Encryption\Encrypter;
use App\Models\User;
use App\Utils\Helper;
use Illuminate\Support\Env;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\File;
use function Laravel\Prompts\confirm;
use function Laravel\Prompts\text;
use function Laravel\Prompts\note;
use function Laravel\Prompts\select;
class XboardInstall extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'xboard:install';
/**
* The console command description.
*
* @var string
*/
protected $description = 'xboard 初始化安装';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
try {
$isDocker = file_exists('/.dockerenv');
$enableSqlite = getenv('ENABLE_SQLITE', false);
$enableRedis = getenv('ENABLE_REDIS', false);
$adminAccount = getenv('ADMIN_ACCOUNT', false);
$this->info("__ __ ____ _ ");
$this->info("\ \ / /| __ ) ___ __ _ _ __ __| | ");
$this->info(" \ \/ / | __ \ / _ \ / _` | '__/ _` | ");
$this->info(" / /\ \ | |_) | (_) | (_| | | | (_| | ");
$this->info("/_/ \_\|____/ \___/ \__,_|_| \__,_| ");
if (
(File::exists(base_path() . '/.env') && $this->getEnvValue('INSTALLED'))
|| (getenv('INSTALLED', false) && $isDocker)
) {
$securePath = admin_setting('secure_path', admin_setting('frontend_admin_path', hash('crc32b', config('app.key'))));
$this->info("访问 http(s)://你的站点/{$securePath} 进入管理面板,你可以在用户中心修改你的密码。");
$this->warn("如需重新安装请清空目录下 .env 文件的内容(Docker安装方式不可以删除此文件)");
$this->warn("快捷清空.env命令:");
note('rm .env && touch .env');
return;
}
if (is_dir(base_path() . '/.env')) {
$this->error('😔:安装失败,Docker环境下安装请保留空的 .env 文件');
return;
}
// 选择数据库类型
$dbType = $enableSqlite ? 'sqlite' : select(
label: '请选择数据库类型',
options: [
'sqlite' => 'SQLite (无需额外安装)',
'mysql' => 'MySQL',
'postgresql' => 'PostgreSQL'
],
default: 'sqlite'
);
// 使用 match 表达式配置数据库
$envConfig = match ($dbType) {
'sqlite' => $this->configureSqlite(),
'mysql' => $this->configureMysql(),
'postgresql' => $this->configurePostgresql(),
default => throw new \InvalidArgumentException("不支持的数据库类型: {$dbType}")
};
if (is_null($envConfig)) {
return; // 用户选择退出安装
}
$envConfig['APP_KEY'] = 'base64:' . base64_encode(Encrypter::generateKey('AES-256-CBC'));
$isReidsValid = false;
while (!$isReidsValid) {
// 判断是否为Docker环境
$useBuiltinRedis = $isDocker && ($enableRedis || confirm(label: '是否启用Docker内置的Redis', default: true, yes: '启用', no: '不启用'));
if ($useBuiltinRedis) {
$envConfig['REDIS_HOST'] = '/data/redis.sock';
$envConfig['REDIS_PORT'] = 0;
$envConfig['REDIS_PASSWORD'] = null;
$isReidsValid = true;
break;
}
$envConfig['REDIS_HOST'] = text(label: '请输入Redis地址', default: '127.0.0.1', required: true);
$envConfig['REDIS_PORT'] = text(label: '请输入Redis端口', default: '6379', required: true);
$envConfig['REDIS_PASSWORD'] = text(label: '请输入redis密码(默认: null)', default: '');
$redisConfig = [
'client' => 'phpredis',
'default' => [
'host' => $envConfig['REDIS_HOST'],
'password' => $envConfig['REDIS_PASSWORD'],
'port' => $envConfig['REDIS_PORT'],
'database' => 0,
],
];
try {
$redis = new \Illuminate\Redis\RedisManager(app(), 'phpredis', $redisConfig);
$redis->ping();
$isReidsValid = true;
} catch (\Exception $e) {
// 连接失败,输出错误消息
$this->error("redis连接失败:" . $e->getMessage());
$this->info("请重新输入REDIS配置");
$enableRedis = false;
sleep(1);
}
}
if (!copy(base_path() . '/.env.example', base_path() . '/.env')) {
abort(500, '复制环境文件失败,请检查目录权限');
}
;
$email = !empty($adminAccount) ? $adminAccount : text(
label: '请输入管理员账号',
default: '[email protected]',
required: true,
validate: fn(string $email): ?string => match (true) {
!filter_var($email, FILTER_VALIDATE_EMAIL) => '请输入有效的邮箱地址.',
default => null,
}
);
$password = Helper::guid(false);
$this->saveToEnv($envConfig);
$installDriverOverrides = [
'CACHE_DRIVER' => 'array',
'QUEUE_CONNECTION' => 'sync',
'SESSION_DRIVER' => 'array',
];
foreach ($installDriverOverrides as $key => $value) {
putenv("{$key}={$value}");
$_ENV[$key] = $value;
$_SERVER[$key] = $value;
}
Config::set('cache.default', 'array');
Config::set('queue.default', 'sync');
Config::set('session.driver', 'array');
$this->call('config:cache');
Artisan::call('cache:clear');
$this->info('正在导入数据库请稍等...');
Artisan::call("migrate", ['--force' => true]);
$this->info(Artisan::output());
$this->info('数据库导入完成');
$this->info('开始注册管理员账号');
if (!self::registerAdmin($email, $password)) {
abort(500, '管理员账号注册失败,请重试');
}
$this->info('正在安装默认插件...');
PluginManager::installDefaultPlugins();
$this->info('默认插件安装完成');
$this->info('🎉:一切就绪');
$this->info("管理员邮箱:{$email}");
$this->info("管理员密码:{$password}");
$defaultSecurePath = hash('crc32b', config('app.key'));
$this->info("访问 http(s)://你的站点/{$defaultSecurePath} 进入管理面板,你可以在用户中心修改你的密码。");
$envConfig['INSTALLED'] = true;
$this->saveToEnv($envConfig);
foreach (array_keys($installDriverOverrides) as $key) {
putenv($key);
unset($_ENV[$key], $_SERVER[$key]);
}
Artisan::call('config:clear');
} catch (\Exception $e) {
$this->error($e);
}
}
public static function registerAdmin($email, $password)
{
$user = new User();
$user->email = $email;
if (strlen($password) < 8) {
abort(500, '管理员密码长度最小为8位字符');
}
$user->password = password_hash($password, PASSWORD_DEFAULT);
$user->uuid = Helper::guid(true);
$user->token = Helper::guid();
$user->is_admin = 1;
return $user->save();
}
private function set_env_var($key, $value)
{
$value = !strpos($value, ' ') ? $value : '"' . $value . '"';
$key = strtoupper($key);
$envPath = app()->environmentFilePath();
$contents = file_get_contents($envPath);
if (preg_match("/^{$key}=[^\r\n]*/m", $contents, $matches)) {
$contents = str_replace($matches[0], "{$key}={$value}", $contents);
} else {
$contents .= "\n{$key}={$value}\n";
}
return file_put_contents($envPath, $contents) !== false;
}
private function saveToEnv($data = [])
{
foreach ($data as $key => $value) {
self::set_env_var($key, $value);
}
return true;
}
function getEnvValue($key, $default = null)
{
$dotenv = \Dotenv\Dotenv::createImmutable(base_path());
$dotenv->load();
return Env::get($key, $default);
}
/**
* 配置 SQLite 数据库
*
* @return array|null
*/
private function configureSqlite(): ?array
{
$sqliteFile = '.docker/.data/database.sqlite';
if (!file_exists(base_path($sqliteFile))) {
// 创建空文件
if (!touch(base_path($sqliteFile))) {
$this->info("sqlite创建成功: $sqliteFile");
}
}
$envConfig = [
'DB_CONNECTION' => 'sqlite',
'DB_DATABASE' => $sqliteFile,
'DB_HOST' => '',
'DB_USERNAME' => '',
'DB_PASSWORD' => '',
];
try {
Config::set("database.default", 'sqlite');
Config::set("database.connections.sqlite.database", base_path($envConfig['DB_DATABASE']));
DB::purge('sqlite');
DB::connection('sqlite')->getPdo();
if (!blank(DB::connection('sqlite')->getPdo()->query("SELECT name FROM sqlite_master WHERE type='table'")->fetchAll(\PDO::FETCH_COLUMN))) {
if (confirm(label: '检测到数据库中已经存在数据,是否要清空数据库以便安装新的数据?', default: false, yes: '清空', no: '退出安装')) {
$this->info('正在清空数据库请稍等');
$this->call('db:wipe', ['--force' => true]);
$this->info('数据库清空完成');
} else {
return null;
}
}
} catch (\Exception $e) {
$this->error("SQLite数据库连接失败:" . $e->getMessage());
return null;
}
return $envConfig;
}
/**
* 配置 MySQL 数据库
*
* @return array
*/
private function configureMysql(): array
{
while (true) {
$envConfig = [
'DB_CONNECTION' => 'mysql',
'DB_HOST' => text(label: "请输入MySQL数据库地址", default: '127.0.0.1', required: true),
'DB_PORT' => text(label: '请输入MySQL数据库端口', default: '3306', required: true),
'DB_DATABASE' => text(label: '请输入MySQL数据库名', default: 'xboard', required: true),
'DB_USERNAME' => text(label: '请输入MySQL数据库用户名', default: 'root', required: true),
'DB_PASSWORD' => text(label: '请输入MySQL数据库密码', required: false),
];
try {
Config::set("database.default", 'mysql');
Config::set("database.connections.mysql.host", $envConfig['DB_HOST']);
Config::set("database.connections.mysql.port", $envConfig['DB_PORT']);
Config::set("database.connections.mysql.database", $envConfig['DB_DATABASE']);
Config::set("database.connections.mysql.username", $envConfig['DB_USERNAME']);
Config::set("database.connections.mysql.password", $envConfig['DB_PASSWORD']);
DB::purge('mysql');
DB::connection('mysql')->getPdo();
if (!blank(DB::connection('mysql')->select('SHOW TABLES'))) {
if (confirm(label: '检测到数据库中已经存在数据,是否要清空数据库以便安装新的数据?', default: false, yes: '清空', no: '不清空')) {
$this->info('正在清空数据库请稍等');
$this->call('db:wipe', ['--force' => true]);
$this->info('数据库清空完成');
return $envConfig;
} else {
continue; // 重新输入配置
}
}
return $envConfig;
} catch (\Exception $e) {
$this->error("MySQL数据库连接失败:" . $e->getMessage());
$this->info("请重新输入MySQL数据库配置");
}
}
}
/**
* 配置 PostgreSQL 数据库
*
* @return array
*/
private function configurePostgresql(): array
{
while (true) {
$envConfig = [
'DB_CONNECTION' => 'pgsql',
'DB_HOST' => text(label: "请输入PostgreSQL数据库地址", default: '127.0.0.1', required: true),
'DB_PORT' => text(label: '请输入PostgreSQL数据库端口', default: '5432', required: true),
'DB_DATABASE' => text(label: '请输入PostgreSQL数据库名', default: 'xboard', required: true),
'DB_USERNAME' => text(label: '请输入PostgreSQL数据库用户名', default: 'postgres', required: true),
'DB_PASSWORD' => text(label: '请输入PostgreSQL数据库密码', required: false),
];
try {
Config::set("database.default", 'pgsql');
Config::set("database.connections.pgsql.host", $envConfig['DB_HOST']);
Config::set("database.connections.pgsql.port", $envConfig['DB_PORT']);
Config::set("database.connections.pgsql.database", $envConfig['DB_DATABASE']);
Config::set("database.connections.pgsql.username", $envConfig['DB_USERNAME']);
Config::set("database.connections.pgsql.password", $envConfig['DB_PASSWORD']);
DB::purge('pgsql');
DB::connection('pgsql')->getPdo();
// 检查PostgreSQL数据库是否有表
$tables = DB::connection('pgsql')->select("SELECT tablename FROM pg_tables WHERE schemaname = 'public'");
if (!blank($tables)) {
if (confirm(label: '检测到数据库中已经存在数据,是否要清空数据库以便安装新的数据?', default: false, yes: '清空', no: '不清空')) {
$this->info('正在清空数据库请稍等');
$this->call('db:wipe', ['--force' => true]);
$this->info('数据库清空完成');
return $envConfig;
} else {
continue; // 重新输入配置
}
}
return $envConfig;
} catch (\Exception $e) {
$this->error("PostgreSQL数据库连接失败:" . $e->getMessage());
$this->info("请重新输入PostgreSQL数据库配置");
}
}
}
}
+45
View File
@@ -0,0 +1,45 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
class XboardRollback extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'xboard:rollback';
/**
* The console command description.
*
* @var string
*/
protected $description = 'xboard 回滚';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
$this->info('正在回滚数据库请稍等...');
\Artisan::call("migrate:rollback");
$this->info(\Artisan::output());
}
}
+75
View File
@@ -0,0 +1,75 @@
<?php
namespace App\Console\Commands;
use App\Services\StatisticalService;
use Illuminate\Console\Command;
use App\Models\Stat;
use Illuminate\Support\Facades\Log;
class XboardStatistics extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'xboard:statistics';
/**
* The console command description.
*
* @var string
*/
protected $description = '统计任务';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
$startAt = microtime(true);
ini_set('memory_limit', -1);
// $this->statUser();
// $this->statServer();
$this->stat();
info('统计任务执行完毕。耗时:' . (microtime(true) - $startAt) / 1000);
}
private function stat()
{
try {
$endAt = strtotime(date('Y-m-d'));
$startAt = strtotime('-1 day', $endAt);
$statisticalService = new StatisticalService();
$statisticalService->setStartAt($startAt);
$statisticalService->setEndAt($endAt);
$data = $statisticalService->generateStatData();
$data['record_at'] = $startAt;
$data['record_type'] = 'd';
$statistic = Stat::where('record_at', $startAt)
->where('record_type', 'd')
->first();
if ($statistic) {
$statistic->update($data);
return;
}
Stat::create($data);
} catch (\Exception $e) {
Log::error($e->getMessage(), ['exception' => $e]);
}
}
}
+65
View File
@@ -0,0 +1,65 @@
<?php
namespace App\Console\Commands;
use App\Services\ThemeService;
use App\Services\UpdateService;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Artisan;
use App\Services\Plugin\PluginManager;
class XboardUpdate extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'xboard:update';
/**
* The console command description.
*
* @var string
*/
protected $description = 'xboard 更新';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
$this->info('正在导入数据库请稍等...');
Artisan::call("migrate", ['--force' => true]);
$this->info(Artisan::output());
$this->info('正在检查并安装默认插件...');
PluginManager::installDefaultPlugins();
$this->info('默认插件检查完成');
$updateService = new UpdateService();
$updateService->updateVersionCache();
$themeService = app(ThemeService::class);
$themeService->refreshCurrentTheme();
if (config('queue.default') === 'sync') {
$this->info('horizon:terminate skipped (sync queue, no workers to terminate).');
} else {
try {
Artisan::call('horizon:terminate');
} catch (\Throwable $e) {
$this->warn('horizon:terminate skipped: ' . $e->getMessage());
}
}
$this->info('更新完毕,队列服务已重启,你无需进行任何操作。');
}
}
+88
View File
@@ -0,0 +1,88 @@
<?php
namespace App\Console;
use App\Services\Plugin\PluginManager;
use App\Utils\CacheKey;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
use Illuminate\Support\Facades\Cache;
class Kernel extends ConsoleKernel
{
/**
* The Artisan commands provided by your application.
*
* @var array
*/
protected $commands = [
//
];
/**
* Define the application's command schedule.
*
* @param \Illuminate\Console\Scheduling\Schedule $schedule
* @return void
*/
protected function schedule(Schedule $schedule): void
{
$schedule->command('telegram:tickets:retry')->everyMinute()->withoutOverlapping();
// Common to all XB instances; each production instance uses its own state and TeleHub caller.
$registrationMutex = 'xb-registration-'.hash('sha256', (string)config('registration_report.project').'|'.(string)config('app.url'));
$schedule->command('report:registrations')->timezone('Asia/Shanghai')->dailyAt('08:00')->onOneServer()->withoutOverlapping(10)->createMutexNameUsing($registrationMutex.'-daily')->when(fn () => config('registration_report.enabled', false));
$schedule->command('report:registrations')->everyFiveMinutes()->onOneServer()->withoutOverlapping(10)->createMutexNameUsing($registrationMutex.'-retry')->when(fn () => config('registration_report.enabled', false));
// Each instance keeps its own durable payment-event outbox and notification worker.
$orderMutex = 'xb-order-reports-'.hash('sha256', (string)config('order_report.project').'|'.(string)config('app.url'));
$schedule->command('orders:report-payments')->everyMinute()->onOneServer()->withoutOverlapping(5)->createMutexNameUsing($orderMutex.'-retry')->when(fn () => config('order_report.enabled', false));
$schedule->command('orders:report-payments')->timezone('Asia/Shanghai')->dailyAt('08:00')->onOneServer()->withoutOverlapping(5)->createMutexNameUsing($orderMutex.'-daily')->when(fn () => config('order_report.enabled', false));
$schedule->command('payment:health-check')->timezone('Asia/Shanghai')->cron('0 */6 * * *')->withoutOverlapping(30);
Cache::put(CacheKey::get('SCHEDULE_LAST_CHECK_AT', null), time());
// v2board
$schedule->command('xboard:statistics')->dailyAt('0:10')->onOneServer();
// check
$schedule->command('check:order')->everyMinute()->onOneServer()->withoutOverlapping(5);
$schedule->command('check:commission')->everyMinute()->onOneServer()->withoutOverlapping(5);
$schedule->command('check:ticket')->everyMinute()->onOneServer()->withoutOverlapping(5);
$schedule->command('check:traffic-exceeded')->everyMinute()->onOneServer()->withoutOverlapping(10)->runInBackground();
// reset
$schedule->command('reset:traffic')->everyMinute()->onOneServer()->withoutOverlapping(10);
$schedule->command('reset:log')->daily()->onOneServer();
// send
$schedule->command('send:remindMail', ['--force'])->dailyAt('11:30')->onOneServer();
$schedule->command('send:expiredSubscriptionMail')->everyMinute()->onOneServer()->withoutOverlapping(10);
// Mail flow stays disabled until explicitly configured.
$schedule->command('mail:poll-inbox')->everyMinute()->onOneServer()->withoutOverlapping(30)->runInBackground();
$schedule->command('mail:reconcile')->everyFiveMinutes()->onOneServer()->withoutOverlapping(10)->runInBackground();
$schedule->command('mail:report-usage')->timezone('Asia/Shanghai')->dailyAt('08:00')->onOneServer()->withoutOverlapping(10);
$schedule->command('mail:report-usage')->everyFiveMinutes()->onOneServer()->withoutOverlapping(10);
// horizon metrics
$schedule->command('horizon:snapshot')->everyFiveMinutes()->onOneServer();
// cleanup stale online_count (GC for Redis TTL expiration)
$schedule->command('cleanup:online-status')->everyFiveMinutes()->onOneServer();
// backup Timing
// if (env('ENABLE_AUTO_BACKUP_AND_UPDATE', false)) {
// $schedule->command('backup:database', ['true'])->daily()->onOneServer();
// }
app(PluginManager::class)->registerPluginSchedules($schedule);
}
/**
* Register the commands for the application.
*
* @return void
*/
protected function commands()
{
$this->load(__DIR__ . '/Commands');
try {
app(PluginManager::class)->initializeEnabledPlugins();
} catch (\Exception $e) {
}
require base_path('routes/console.php');
}
}
+10
View File
@@ -0,0 +1,10 @@
<?php
namespace App\Contracts;
interface PaymentInterface
{
public function form(): array;
public function pay($order): array;
public function notify($params);
}
+23
View File
@@ -0,0 +1,23 @@
<?php
namespace App\Exceptions;
use Exception;
class ApiException extends Exception
{
protected $code; // 错误码
protected $message; // 错误消息
protected $errors; // 全部错误信息
public function __construct($message = null, $code = 400, $errors = null)
{
$this->message = $message;
$this->code = $code;
$this->errors = $errors;
}
public function errors(){
return $this->errors;
}
}
+19
View File
@@ -0,0 +1,19 @@
<?php
namespace App\Exceptions;
use Exception;
class BusinessException extends Exception
{
/**
* 业务异常构造函数
* @param array $codeResponse 状态码
* @param string $info 自定义返回信息,不为空时会替换掉codeResponse 里面的message文字信息
*/
public function __construct(array $codeResponse, $info = '')
{
[$code, $message] = $codeResponse;
parent::__construct($info ?: $message, $code);
}
}
+101
View File
@@ -0,0 +1,101 @@
<?php
namespace App\Exceptions;
use App\Helpers\ApiResponse;
use App\Services\Plugin\InterceptResponseException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Support\Arr;
use Illuminate\View\ViewException;
use Throwable;
class Handler extends ExceptionHandler
{
use ApiResponse;
/**
* A list of the exception types that are not reported.
*
* @var array<int, class-string<Throwable>>
*/
protected $dontReport = [
ApiException::class,
InterceptResponseException::class
];
/**
* A list of the inputs that are never flashed for validation exceptions.
*
* @var array<int, string>
*/
protected $dontFlash = [
'password',
'password_confirmation',
];
/**
* Report or log an exception.
*
* @param \Throwable $exception
* @return void
*
* @throws \Throwable
*/
public function report(Throwable $exception)
{
parent::report($exception);
}
/**
* Render an exception into an HTTP response.
*
* @param \Illuminate\Http\Request $request
* @param \Throwable $exception
* @return \Symfony\Component\HttpFoundation\Response
*
* @throws \Throwable
*/
public function render($request, Throwable $exception)
{
if ($exception instanceof ViewException) {
return $this->fail([500, '主题渲染失败。如更新主题,参数可能发生变化请重新配置主题后再试。']);
}
// ApiException主动抛出错误
if ($exception instanceof ApiException) {
$code = $exception->getCode();
$message = $exception->getMessage();
$errors = $exception->errors();
return $this->fail([$code, $message],null,$errors);
}
return parent::render($request, $exception);
}
/**
* Register the exception handling callbacks for the application.
*/
public function register(): void
{
$this->reportable(function (Throwable $e) {
//
});
$this->renderable(function (InterceptResponseException $e) {
return $e->getResponse();
});
}
protected function convertExceptionToArray(Throwable $e)
{
return config('app.debug') ? [
'message' => $e->getMessage(),
'exception' => get_class($e),
'file' => $e->getFile(),
'line' => $e->getLine(),
'trace' => collect($e->getTrace())->map(function ($trace) {
return Arr::except($trace, ['args']);
})->all(),
] : [
'message' => $this->isHttpException($e) ? $e->getMessage() : __("Uh-oh, we've had some problems, we're working on it."),
];
}
}
+79
View File
@@ -0,0 +1,79 @@
<?php
namespace App\Helpers;
use App\Helpers\ResponseEnum;
use App\Exceptions\BusinessException;
use Illuminate\Http\JsonResponse;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Collection;
trait ApiResponse
{
/**
* 成功
* @param mixed $data
* @param array $codeResponse
* @return JsonResponse
*/
public function success($data = null, $codeResponse = ResponseEnum::HTTP_OK): JsonResponse
{
return $this->jsonResponse('success', $codeResponse, $data, null);
}
/**
* 失败
* @param array $codeResponse
* @param mixed $data
* @param mixed $error
* @return JsonResponse
*/
public function fail($codeResponse = ResponseEnum::HTTP_ERROR, $data = null, $error = null): JsonResponse
{
return $this->jsonResponse('fail', $codeResponse, $data, $error);
}
/**
* json响应
* @param $status
* @param $codeResponse
* @param $data
* @param $error
* @return JsonResponse
*/
private function jsonResponse($status, $codeResponse, $data, $error): JsonResponse
{
list($code, $message) = $codeResponse;
return response()
->json([
'status' => $status,
// 'code' => $code,
'message' => $message,
'data' => $data ?? null,
'error' => $error,
], (int) substr(((string) $code), 0, 3));
}
public function paginate(LengthAwarePaginator $page)
{
return response()->json([
'total' => $page->total(),
'current_page' => $page->currentPage(),
'per_page' => $page->perPage(),
'last_page' => $page->lastPage(),
'data' => $page->items()
]);
}
/**
* 业务异常返回
* @param array $codeResponse
* @param string $info
* @throws BusinessException
*/
public function throwBusinessException(array $codeResponse = ResponseEnum::HTTP_ERROR, string $info = '')
{
throw new BusinessException($codeResponse, $info);
}
}
+82
View File
@@ -0,0 +1,82 @@
<?php
use App\Support\Setting;
if (!function_exists('admin_setting')) {
/**
* 获取或保存配置参数.
*
* @param string|array $key
* @param mixed $default
* @return App\Support\Setting|mixed
*/
function admin_setting($key = null, $default = null)
{
$setting = app(Setting::class);
if ($key === null) {
return $setting->toArray();
}
if (is_array($key)) {
$setting->save($key);
return '';
}
$default = config('v2board.' . $key) ?? $default;
return $setting->get($key) ?? $default;
}
}
if (!function_exists('subscribe_template')) {
/**
* Get subscribe template content by protocol name.
*/
function subscribe_template(string $name): ?string
{
return \App\Models\SubscribeTemplate::getContent($name);
}
}
if (!function_exists('admin_settings_batch')) {
/**
* 批量获取配置参数,性能优化版本
*
* @param array $keys 配置键名数组
* @return array 返回键值对数组
*/
function admin_settings_batch(array $keys): array
{
return app(Setting::class)->getBatch($keys);
}
}
if (!function_exists('source_base_url')) {
/**
* 获取来源基础URL,优先Referer,其次Host
* @param string $path
* @return string
*/
function source_base_url(string $path = ''): string
{
$baseUrl = '';
$referer = request()->header('Referer');
if ($referer) {
$parsedUrl = parse_url($referer);
if (isset($parsedUrl['scheme']) && isset($parsedUrl['host'])) {
$baseUrl = $parsedUrl['scheme'] . '://' . $parsedUrl['host'];
if (isset($parsedUrl['port'])) {
$baseUrl .= ':' . $parsedUrl['port'];
}
}
}
if (!$baseUrl) {
$baseUrl = request()->getSchemeAndHttpHost();
}
$baseUrl = rtrim($baseUrl, '/');
$path = ltrim($path, '/');
return $baseUrl . '/' . $path;
}
}
+81
View File
@@ -0,0 +1,81 @@
<?php
namespace App\Helpers;
class ResponseEnum
{
// 001 ~ 099 表示系统状态;100 ~ 199 表示授权业务;200 ~ 299 表示用户业务
/*-------------------------------------------------------------------------------------------*/
// 100开头的表示 信息提示,这类状态表示临时的响应
// 100 - 继续
// 101 - 切换协议
/*-------------------------------------------------------------------------------------------*/
// 200表示服务器成功地接受了客户端请求
const HTTP_OK = [200001, '操作成功'];
const HTTP_ERROR = [200002, '操作失败'];
const HTTP_ACTION_COUNT_ERROR = [200302, '操作频繁'];
const USER_SERVICE_LOGIN_SUCCESS = [200200, '登录成功'];
const USER_SERVICE_LOGIN_ERROR = [200201, '登录失败'];
const USER_SERVICE_LOGOUT_SUCCESS = [200202, '退出登录成功'];
const USER_SERVICE_LOGOUT_ERROR = [200203, '退出登录失败'];
const USER_SERVICE_REGISTER_SUCCESS = [200104, '注册成功'];
const USER_SERVICE_REGISTER_ERROR = [200105, '注册失败'];
const USER_ACCOUNT_REGISTERED = [23001, '账号已注册'];
/*-------------------------------------------------------------------------------------------*/
// 300开头的表示服务器重定向,指向的别的地方,客户端浏览器必须采取更多操作来实现请求
// 302 - 对象已移动。
// 304 - 未修改。
// 307 - 临时重定向。
/*-------------------------------------------------------------------------------------------*/
// 400开头的表示客户端错误请求错误,请求不到数据,或者找不到等等
// 400 - 错误的请求
const CLIENT_NOT_FOUND_HTTP_ERROR = [400001, '请求失败'];
const CLIENT_PARAMETER_ERROR = [400200, '参数错误'];
const CLIENT_CREATED_ERROR = [400201, '数据已存在'];
const CLIENT_DELETED_ERROR = [400202, '数据不存在'];
// 401 - 访问被拒绝
const CLIENT_HTTP_UNAUTHORIZED = [401001, '授权失败,请先登录'];
const CLIENT_HTTP_UNAUTHORIZED_EXPIRED = [401200, '账号信息已过期,请重新登录'];
const CLIENT_HTTP_UNAUTHORIZED_BLACKLISTED = [401201, '账号在其他设备登录,请重新登录'];
// 403 - 禁止访问
// 404 - 没有找到文件或目录
const CLIENT_NOT_FOUND_ERROR = [404001, '没有找到该页面'];
// 405 - 用来访问本页面的 HTTP 谓词不被允许(方法不被允许)
const CLIENT_METHOD_HTTP_TYPE_ERROR = [405001, 'HTTP请求类型错误'];
// 406 - 客户端浏览器不接受所请求页面的 MIME 类型
// 407 - 要求进行代理身份验证
// 412 - 前提条件失败
// 413 – 请求实体太大
// 414 - 请求 URI 太长
// 415 – 不支持的媒体类型
// 416 – 所请求的范围无法满足
// 417 – 执行失败
// 423 – 锁定的错误
/*-------------------------------------------------------------------------------------------*/
// 500开头的表示服务器错误,服务器因为代码,或者什么原因终止运行
// 服务端操作错误码:500 ~ 599 开头,后拼接 3 位
// 500 - 内部服务器错误
const SYSTEM_ERROR = [500001, '服务器错误'];
const SYSTEM_UNAVAILABLE = [500002, '服务器正在维护,暂不可用'];
const SYSTEM_CACHE_CONFIG_ERROR = [500003, '缓存配置错误'];
const SYSTEM_CACHE_MISSED_ERROR = [500004, '缓存未命中'];
const SYSTEM_CONFIG_ERROR = [500005, '系统配置错误'];
// 业务操作错误码(外部服务或内部服务调用)
const SERVICE_REGISTER_ERROR = [500101, '注册失败'];
const SERVICE_LOGIN_ERROR = [500102, '登录失败'];
const SERVICE_LOGIN_ACCOUNT_ERROR = [500103, '账号或密码错误'];
const SERVICE_USER_INTEGRAL_ERROR = [500200, '积分不足'];
//501 - 页眉值指定了未实现的配置
//502 - Web 服务器用作网关或代理服务器时收到了无效响应
//503 - 服务不可用。这个错误代码为 IIS 6.0 所专用
//504 - 网关超时
//505 - HTTP 版本不受支持
/*-------------------------------------------------------------------------------------------*/
}
+13
View File
@@ -0,0 +1,13 @@
<?php
namespace App\Http\Controllers;
use App\Helpers\ApiResponse;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Routing\Controller as BaseController;
class Controller extends BaseController
{
use DispatchesJobs, ValidatesRequests, ApiResponse;
}
+26
View File
@@ -0,0 +1,26 @@
<?php
namespace App\Http\Controllers;
use App\Traits\HasPluginConfig;
/**
* 插件控制器基类
*
* 为所有插件控制器提供通用功能
*/
abstract class PluginController extends Controller
{
use HasPluginConfig;
/**
* 执行插件操作前的检查
*/
protected function beforePluginAction(): ?array
{
if (!$this->isPluginEnabled()) {
return [400, '插件未启用'];
}
return null;
}
}
@@ -0,0 +1,90 @@
<?php
namespace App\Http\Controllers\V1\Client;
use App\Http\Controllers\Controller;
use App\Services\ServerService;
use App\Services\UserService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\File;
use Symfony\Component\Yaml\Yaml;
class AppController extends Controller
{
public function getConfig(Request $request)
{
$servers = [];
$user = $request->user();
$userService = new UserService();
if ($userService->isAvailable($user)) {
$servers = ServerService::getAvailableServers($user);
}
$defaultConfig = base_path() . '/resources/rules/app.clash.yaml';
$customConfig = base_path() . '/resources/rules/custom.app.clash.yaml';
if (File::exists($customConfig)) {
$config = Yaml::parseFile($customConfig);
} else {
$config = Yaml::parseFile($defaultConfig);
}
$proxy = [];
$proxies = [];
foreach ($servers as $item) {
$protocol_settings = $item['protocol_settings'];
if ($item['type'] === 'shadowsocks'
&& in_array(data_get($protocol_settings, 'cipher'), [
'aes-128-gcm',
'aes-192-gcm',
'aes-256-gcm',
'chacha20-ietf-poly1305'
])
) {
array_push($proxy, \App\Protocols\Clash::buildShadowsocks($user['uuid'], $item));
array_push($proxies, $item['name']);
}
if ($item['type'] === 'vmess') {
array_push($proxy, \App\Protocols\Clash::buildVmess($user['uuid'], $item));
array_push($proxies, $item['name']);
}
if ($item['type'] === 'trojan') {
array_push($proxy, \App\Protocols\Clash::buildTrojan($user['uuid'], $item));
array_push($proxies, $item['name']);
}
}
$config['proxies'] = array_merge($config['proxies'] ? $config['proxies'] : [], $proxy);
foreach ($config['proxy-groups'] as $k => $v) {
$config['proxy-groups'][$k]['proxies'] = array_merge($config['proxy-groups'][$k]['proxies'], $proxies);
}
return(Yaml::dump($config));
}
public function getVersion(Request $request)
{
if (strpos($request->header('user-agent'), 'tidalab/4.0.0') !== false
|| strpos($request->header('user-agent'), 'tunnelab/4.0.0') !== false
) {
if (strpos($request->header('user-agent'), 'Win64') !== false) {
$data = [
'version' => admin_setting('windows_version'),
'download_url' => admin_setting('windows_download_url')
];
} else {
$data = [
'version' => admin_setting('macos_version'),
'download_url' => admin_setting('macos_download_url')
];
}
}else{
$data = [
'windows_version' => admin_setting('windows_version'),
'windows_download_url' => admin_setting('windows_download_url'),
'macos_version' => admin_setting('macos_version'),
'macos_download_url' => admin_setting('macos_download_url'),
'android_version' => admin_setting('android_version'),
'android_download_url' => admin_setting('android_download_url')
];
}
return $this->success($data);
}
}
@@ -0,0 +1,247 @@
<?php
namespace App\Http\Controllers\V1\Client;
use App\Http\Controllers\Controller;
use App\Models\Server;
use App\Protocols\General;
use App\Services\Plugin\HookManager;
use App\Services\ServerService;
use App\Services\UserService;
use App\Utils\Helper;
use Illuminate\Http\Request;
class ClientController extends Controller
{
/**
* Protocol prefix mapping for server names
*/
private const PROTOCOL_PREFIXES = [
'hysteria' => [
1 => '[Hy]',
2 => '[Hy2]'
],
'vless' => '[vless]',
'shadowsocks' => '[ss]',
'vmess' => '[vmess]',
'trojan' => '[trojan]',
'tuic' => '[tuic]',
'socks' => '[socks]',
'anytls' => '[anytls]'
];
public function subscribe(Request $request)
{
HookManager::call('client.subscribe.before');
$request->validate([
'types' => ['nullable', 'string'],
'filter' => ['nullable', 'string'],
'flag' => ['nullable', 'string'],
]);
$user = $request->user();
$userService = new UserService();
if (!$userService->isAvailable($user)) {
HookManager::call('client.subscribe.unavailable');
return response('', 403, ['Content-Type' => 'text/plain']);
}
return $this->doSubscribe($request, $user);
}
public function doSubscribe(Request $request, $user, $servers = null)
{
if ($servers === null) {
$servers = ServerService::getAvailableServers($user);
$servers = HookManager::filter('client.subscribe.servers', $servers, $user, $request);
}
$clientInfo = $this->getClientInfo($request);
$requestedTypes = $this->parseRequestedTypes($request->input('types'));
$filterKeywords = $this->parseFilterKeywords($request->input('filter'));
$protocolClassName = app('protocols.manager')->matchProtocolClassName($clientInfo['flag'])
?? General::class;
$serversFiltered = $this->filterServers(
servers: $servers,
allowedTypes: $requestedTypes,
filterKeywords: $filterKeywords
);
$this->setSubscribeInfoToServers($serversFiltered, $user, count($servers) - count($serversFiltered));
$serversFiltered = $this->addPrefixToServerName($serversFiltered);
// Instantiate the protocol class with filtered servers and client info
$protocolInstance = app()->make($protocolClassName, [
'user' => $user,
'servers' => $serversFiltered,
'clientName' => $clientInfo['name'] ?? null,
'clientVersion' => $clientInfo['version'] ?? null,
'userAgent' => $clientInfo['flag'] ?? null
]);
return $protocolInstance->handle();
}
/**
* Parses the input string for requested server types.
*/
private function parseRequestedTypes(?string $typeInputString): array
{
if (blank($typeInputString) || $typeInputString === 'all') {
return Server::VALID_TYPES;
}
$requested = collect(preg_split('/[|,|]+/', $typeInputString))
->map(fn($type) => trim($type))
->filter() // Remove empty strings that might result from multiple delimiters
->all();
return array_values(array_intersect($requested, Server::VALID_TYPES));
}
/**
* Parses the input string for filter keywords.
*/
private function parseFilterKeywords(?string $filterInputString): ?array
{
if (blank($filterInputString) || mb_strlen($filterInputString) > 20) {
return null;
}
return collect(preg_split('/[|,|]+/', $filterInputString))
->map(fn($keyword) => trim($keyword))
->filter() // Remove empty strings
->all();
}
/**
* Filters servers based on allowed types and keywords.
*/
private function filterServers(array $servers, array $allowedTypes, ?array $filterKeywords): array
{
return collect($servers)->filter(function ($server) use ($allowedTypes, $filterKeywords) {
// Condition 1: Server type must be in the list of allowed types
if ($allowedTypes && !in_array($server['type'], $allowedTypes)) {
return false; // Filter out (don't keep)
}
// Condition 2: If filterKeywords are provided, at least one keyword must match
if (!empty($filterKeywords)) { // Check if $filterKeywords is not empty
$keywordMatch = collect($filterKeywords)->contains(function ($keyword) use ($server) {
return stripos($server['name'], $keyword) !== false
|| in_array($keyword, $server['tags'] ?? []);
});
if (!$keywordMatch) {
return false; // Filter out if no keywords match
}
}
// Keep the server if its type is allowed AND (no filter keywords OR at least one keyword matched)
return true;
})->values()->all();
}
private function getClientInfo(Request $request): array
{
$flag = strtolower($request->input('flag') ?? $request->header('User-Agent', ''));
$clientName = null;
$clientVersion = null;
if (preg_match('/([a-zA-Z0-9\-_]+)[\/\s]+(v?[0-9]+(?:\.[0-9]+){0,2})/', $flag, $matches)) {
$potentialName = strtolower($matches[1]);
$clientVersion = preg_replace('/^v/', '', $matches[2]);
if (in_array($potentialName, app('protocols.flags'))) {
$clientName = $potentialName;
}
}
if (!$clientName) {
$flags = collect(app('protocols.flags'))->sortByDesc(fn($f) => strlen($f))->values()->all();
foreach ($flags as $name) {
if (stripos($flag, $name) !== false) {
$clientName = $name;
if (!$clientVersion) {
$pattern = '/' . preg_quote($name, '/') . '[\/\s]+(v?[0-9]+(?:\.[0-9]+){0,2})/i';
if (preg_match($pattern, $flag, $vMatches)) {
$clientVersion = preg_replace('/^v/', '', $vMatches[1]);
}
}
break;
}
}
}
if (!$clientVersion) {
if (preg_match('/\/v?(\d+(?:\.\d+){0,2})/', $flag, $matches)) {
$clientVersion = $matches[1];
}
}
return [
'flag' => $flag,
'name' => $clientName,
'version' => $clientVersion
];
}
private function setSubscribeInfoToServers(&$servers, $user, $rejectServerCount = 0)
{
if (!isset($servers[0]))
return;
if ($rejectServerCount > 0) {
array_unshift($servers, array_merge($servers[0], [
'name' => "过滤掉{$rejectServerCount}条线路",
]));
}
if (!(int) admin_setting('show_info_to_server_enable', 0))
return;
$useTraffic = $user['u'] + $user['d'];
$totalTraffic = $user['transfer_enable'];
$remainingTraffic = Helper::trafficConvert($totalTraffic - $useTraffic);
$expiredDate = $user['expired_at'] ? date('Y-m-d', $user['expired_at']) : __('长期有效');
$userService = new UserService();
$resetDay = $userService->getResetDay($user);
array_unshift($servers, array_merge($servers[0], [
'name' => "套餐到期:{$expiredDate}",
]));
if ($resetDay) {
array_unshift($servers, array_merge($servers[0], [
'name' => "距离下次重置剩余:{$resetDay} 天",
]));
}
array_unshift($servers, array_merge($servers[0], [
'name' => "剩余流量:{$remainingTraffic}",
]));
}
private function addPrefixToServerName(array $servers): array
{
if (!admin_setting('show_protocol_to_server_enable', false)) {
return $servers;
}
return collect($servers)
->map(function (array $server): array {
$server['name'] = $this->getPrefixedServerName($server);
return $server;
})
->all();
}
private function getPrefixedServerName(array $server): string
{
$type = $server['type'] ?? '';
if (!isset(self::PROTOCOL_PREFIXES[$type])) {
return $server['name'] ?? '';
}
$prefix = is_array(self::PROTOCOL_PREFIXES[$type])
? self::PROTOCOL_PREFIXES[$type][$server['protocol_settings']['version'] ?? 1] ?? ''
: self::PROTOCOL_PREFIXES[$type];
return $prefix . ($server['name'] ?? '');
}
}
@@ -0,0 +1,41 @@
<?php
namespace App\Http\Controllers\V1\Guest;
use App\Http\Controllers\Controller;
use App\Services\Plugin\HookManager;
use App\Utils\Dict;
use App\Utils\Helper;
use Illuminate\Support\Facades\Http;
class CommController extends Controller
{
public function config()
{
$data = [
'app_name' => config('app.name'),
'app_full_name' => config('app.full_name'),
'tos_url' => admin_setting('tos_url'),
'is_email_verify' => (int) admin_setting('email_verify', 0) ? 1 : 0,
'is_invite_force' => (int) admin_setting('invite_force', 0) ? 1 : 0,
'email_whitelist_suffix' => (int) admin_setting('email_whitelist_enable', 0)
? Helper::getEmailSuffix()
: 0,
'is_captcha' => (int) admin_setting('captcha_enable', 0) ? 1 : 0,
'captcha_type' => admin_setting('captcha_type', 'recaptcha'),
'recaptcha_site_key' => admin_setting('recaptcha_site_key'),
'recaptcha_v3_site_key' => admin_setting('recaptcha_v3_site_key'),
'recaptcha_v3_score_threshold' => admin_setting('recaptcha_v3_score_threshold', 0.5),
'turnstile_site_key' => admin_setting('turnstile_site_key'),
'app_description' => admin_setting('app_description'),
'app_url' => admin_setting('app_url'),
'logo' => admin_setting('logo'),
// 保持向后兼容
'is_recaptcha' => (int) admin_setting('captcha_enable', 0) ? 1 : 0,
];
$data = HookManager::filter('guest_comm_config', $data);
return $this->success($data);
}
}
@@ -0,0 +1,52 @@
<?php
namespace App\Http\Controllers\V1\Guest;
use App\Http\Controllers\Controller;
use App\Models\Order;
use App\Services\OrderService;
use App\Services\PaymentService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use App\Services\Plugin\HookManager;
class PaymentController extends Controller
{
public function notify($method, $uuid, Request $request)
{
HookManager::call('payment.notify.before', [$method, $uuid, $request]);
try {
$paymentService = new PaymentService($method, null, $uuid);
$verify = $paymentService->notify($request->input());
if (!$verify) {
HookManager::call('payment.notify.failed', [$method, $uuid, $request]);
return $this->fail([422, 'verify error']);
}
HookManager::call('payment.notify.verified', $verify);
if (!$this->handle($verify['trade_no'], $verify['callback_no'])) {
return $this->fail([400, 'handle error']);
}
return (isset($verify['custom_result']) ? $verify['custom_result'] : 'success');
} catch (\Exception $e) {
Log::error($e);
return $this->fail([500, 'fail']);
}
}
private function handle($tradeNo, $callbackNo)
{
$order = Order::where('trade_no', $tradeNo)->first();
if (!$order) {
return $this->fail([400202, 'order is not found']);
}
if ($order->status !== Order::STATUS_PENDING)
return true;
$orderService = new OrderService($order);
if (!$orderService->paid($callbackNo)) {
return false;
}
HookManager::call('payment.notify.success', $order);
return true;
}
}
+25
View File
@@ -0,0 +1,25 @@
<?php
namespace App\Http\Controllers\V1\Guest;
use App\Http\Controllers\Controller;
use App\Http\Resources\PlanResource;
use App\Models\Plan;
use App\Services\PlanService;
use Auth;
use Illuminate\Http\Request;
class PlanController extends Controller
{
protected $planService;
public function __construct(PlanService $planService)
{
$this->planService = $planService;
}
public function fetch(Request $request)
{
$plan = $this->planService->getAvailablePlans();
return $this->success(PlanResource::collection($plan));
}
}
@@ -0,0 +1,26 @@
<?php
namespace App\Http\Controllers\V1\Guest;
use App\Http\Controllers\Controller;
use App\Services\MailFlow\DeliveryEvents;
use App\Services\MailFlow\Settings;
use App\Services\MailFlow\WebhookSignature;
use Illuminate\Http\Request;
class ResendController extends Controller
{
public function webhook(Request $request, WebhookSignature $signature, DeliveryEvents $events)
{
abort_unless(Settings::get('enabled'), 404);
$body = $request->getContent();
abort_if(strlen($body) > 262144, 413);
$id = (string) $request->header('svix-id');
abort_unless($signature->valid($body, $id, (string) $request->header('svix-timestamp'),
(string) $request->header('svix-signature'), (string) Settings::get('resend_webhook_secret')), 401);
$event = json_decode($body, true);
abort_unless(is_array($event), 400);
$events->receive($id, $event);
return response()->json(['ok' => true]);
}
}
@@ -0,0 +1,135 @@
<?php
namespace App\Http\Controllers\V1\Guest;
use App\Exceptions\ApiException;
use App\Http\Controllers\Controller;
use App\Models\User;
use App\Services\Plugin\HookManager;
use App\Services\TelegramService;
use App\Services\UserService;
use Illuminate\Http\Request;
class TelegramController extends Controller
{
protected ?object $msg = null;
protected TelegramService $telegramService;
protected UserService $userService;
public function __construct(TelegramService $telegramService, UserService $userService)
{
$this->telegramService = $telegramService;
$this->userService = $userService;
}
public function webhook(Request $request): void
{
$botToken = (string) admin_setting('telegram_bot_token', '');
if ($botToken === '' || !admin_setting('telegram_bot_enable', false)) { throw new ApiException('Telegram bot disabled', 401); }
$secret = (string) admin_setting('telegram_webhook_secret', '');
$expectedToken = md5($botToken);
if ($secret !== '' ? !hash_equals($secret, (string) $request->header('X-Telegram-Bot-Api-Secret-Token', '')) : !hash_equals($expectedToken, (string) $request->input('access_token', ''))) {
throw new ApiException('access_token is error', 401);
}
$data = $request->json()->all();
$this->formatMessage($data);
if ($this->msg) {
app(\App\Services\TelegramTickets\TicketBridge::class)->observeIncoming($this->msg->raw_message, (int) $this->msg->update_id);
}
$this->formatChatJoinRequest($data);
$this->handle();
}
private function handle(): void
{
if (!$this->msg)
return;
$msg = $this->msg;
$this->processBotName($msg);
try {
HookManager::call('telegram.message.before', [$msg]);
$handled = HookManager::filter('telegram.message.handle', false, [$msg]);
if (!$handled) {
HookManager::call('telegram.message.unhandled', [$msg]);
}
HookManager::call('telegram.message.after', [$msg]);
} catch (\Exception $e) {
if (($msg->message_type ?? '') === 'reply_message') { throw new ApiException('工单回复暂时未完成,请重试', 500); }
HookManager::call('telegram.message.error', [$msg, $e]);
$this->telegramService->sendMessage($msg->chat_id, '暂时无法处理,请稍后重试。');
}
}
private function processBotName(object $msg): void
{
$commandParts = explode('@', $msg->command);
if (count($commandParts) === 2) {
$botName = $this->getBotName();
if ($commandParts[1] === $botName) {
$msg->command = $commandParts[0];
}
}
}
private function getBotName(): string
{
$response = $this->telegramService->getMe();
return $response->result->username;
}
private function formatMessage(array $data): void
{
if (!isset($data['message']['text']))
return;
$message = $data['message'];
$text = explode(' ', $message['text']);
$this->msg = (object) [
'raw_message' => $message,
'update_id' => $data['update_id'] ?? 0,
'command' => $text[0],
'args' => array_slice($text, 1),
'chat_id' => $message['chat']['id'],
'message_id' => $message['message_id'],
'message_type' => 'message',
'text' => $message['text'],
'is_private' => $message['chat']['type'] === 'private',
];
if (isset($message['reply_to_message']['text'])) {
$this->msg->message_type = 'reply_message';
$this->msg->reply_text = $message['reply_to_message']['text'];
}
}
private function formatChatJoinRequest(array $data): void
{
$joinRequest = $data['chat_join_request'] ?? null;
if (!$joinRequest)
return;
$chatId = $joinRequest['chat']['id'] ?? null;
$userId = $joinRequest['from']['id'] ?? null;
if (!$chatId || !$userId)
return;
$user = User::where('telegram_id', $userId)->first();
if (!$user) {
$this->telegramService->declineChatJoinRequest($chatId, $userId);
return;
}
if (!$this->userService->isAvailable($user)) {
$this->telegramService->declineChatJoinRequest($chatId, $userId);
return;
}
$this->telegramService->approveChatJoinRequest($chatId, $userId);
}
}
@@ -0,0 +1,175 @@
<?php
namespace App\Http\Controllers\V1\Passport;
use App\Helpers\ResponseEnum;
use App\Http\Controllers\Controller;
use App\Http\Requests\Passport\AuthForget;
use App\Http\Requests\Passport\AuthLogin;
use App\Http\Requests\Passport\AuthRegister;
use App\Services\Auth\LoginService;
use App\Services\Auth\MailLinkService;
use App\Services\Auth\RegisterService;
use App\Services\AuthService;
use Illuminate\Http\Request;
class AuthController extends Controller
{
protected MailLinkService $mailLinkService;
protected RegisterService $registerService;
protected LoginService $loginService;
public function __construct(
MailLinkService $mailLinkService,
RegisterService $registerService,
LoginService $loginService
) {
$this->mailLinkService = $mailLinkService;
$this->registerService = $registerService;
$this->loginService = $loginService;
}
/**
* 通过邮件链接登录
*/
public function loginWithMailLink(Request $request)
{
$params = $request->validate([
'email' => 'required|email:strict',
'redirect' => 'nullable'
]);
[$success, $result] = $this->mailLinkService->handleMailLink(
$params['email'],
$request->input('redirect')
);
if (!$success) {
return $this->fail($result);
}
return $this->success($result);
}
/**
* 用户注册
*/
public function register(AuthRegister $request)
{
[$success, $result] = $this->registerService->register($request);
if (!$success) {
return $this->fail($result);
}
$authService = new AuthService($result);
return $this->success($authService->generateAuthData());
}
/**
* 用户登录
*/
public function login(AuthLogin $request)
{
$email = $request->input('email');
$password = $request->input('password');
[$success, $result] = $this->loginService->login($email, $password);
if (!$success) {
return $this->fail($result);
}
$authService = new AuthService($result);
return $this->success($authService->generateAuthData());
}
/**
* 通过token登录
*/
public function token2Login(Request $request)
{
// 处理直接通过token重定向
if ($token = $request->input('token')) {
$redirect = '/#/login?verify=' . $token . '&redirect=' . ($request->input('redirect', 'dashboard'));
return redirect()->to(
admin_setting('app_url')
? admin_setting('app_url') . $redirect
: url($redirect)
);
}
// 处理通过验证码登录
if ($verify = $request->input('verify')) {
$userId = $this->mailLinkService->handleTokenLogin($verify);
if (!$userId) {
return response()->json([
'message' => __('Token error')
], 400);
}
$user = \App\Models\User::find($userId);
if (!$user) {
return response()->json([
'message' => __('User not found')
], 400);
}
$authService = new AuthService($user);
return response()->json([
'data' => $authService->generateAuthData()
]);
}
return response()->json([
'message' => __('Invalid request')
], 400);
}
/**
* 获取快速登录URL
*/
public function getQuickLoginUrl(Request $request)
{
$authorization = $request->input('auth_data') ?? $request->header('authorization');
if (!$authorization) {
return response()->json([
'message' => ResponseEnum::CLIENT_HTTP_UNAUTHORIZED
], 401);
}
$user = AuthService::findUserByBearerToken($authorization);
if (!$user) {
return response()->json([
'message' => ResponseEnum::CLIENT_HTTP_UNAUTHORIZED_EXPIRED
], 401);
}
$url = $this->loginService->generateQuickLoginUrl($user, $request->input('redirect'));
return $this->success($url);
}
/**
* 忘记密码处理
*/
public function forget(AuthForget $request)
{
[$success, $result] = $this->loginService->resetPassword(
$request->input('email'),
$request->input('email_code'),
$request->input('password')
);
if (!$success) {
return $this->fail($result);
}
return $this->success(true);
}
}
@@ -0,0 +1,78 @@
<?php
namespace App\Http\Controllers\V1\Passport;
use App\Http\Controllers\Controller;
use App\Http\Requests\Passport\CommSendEmailVerify;
use App\Jobs\SendEmailJob;
use App\Models\InviteCode;
use App\Models\User;
use App\Services\CaptchaService;
use App\Utils\CacheKey;
use App\Utils\Helper;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
class CommController extends Controller
{
public function sendEmailVerify(CommSendEmailVerify $request)
{
// 验证人机验证码
$captchaService = app(CaptchaService::class);
[$captchaValid, $captchaError] = $captchaService->verify($request);
if (!$captchaValid) {
return $this->fail($captchaError);
}
$email = $request->input('email');
// 检查白名单后缀限制
if ((int) admin_setting('email_whitelist_enable', 0)) {
$isRegisteredEmail = User::byEmail($email)->exists();
if (!$isRegisteredEmail) {
$allowedSuffixes = Helper::getEmailSuffix();
$emailSuffix = substr(strrchr($email, '@'), 1);
if (!in_array($emailSuffix, $allowedSuffixes)) {
return $this->fail([400, __('Email suffix is not in whitelist')]);
}
}
}
if (Cache::get(CacheKey::get('LAST_SEND_EMAIL_VERIFY_TIMESTAMP', $email))) {
return $this->fail([400, __('Email verification code has been sent, please request again later')]);
}
$code = rand(100000, 999999);
$subject = admin_setting('app_name', 'XBoard') . __('Email verification code');
SendEmailJob::dispatch([
'email' => $email,
'subject' => $subject,
'template_name' => 'verify',
'purpose' => 'verification',
'expires_at' => now()->addMinutes(5)->toDateTimeString(),
'template_value' => [
'name' => admin_setting('app_name', 'XBoard'),
'code' => $code,
'url' => admin_setting('app_url')
]
]);
Cache::put(CacheKey::get('EMAIL_VERIFY_CODE', $email), $code, 300);
Cache::put(CacheKey::get('LAST_SEND_EMAIL_VERIFY_TIMESTAMP', $email), time(), 60);
return $this->success(true);
}
public function pv(Request $request)
{
$inviteCode = InviteCode::where('code', $request->input('invite_code'))->first();
if ($inviteCode) {
$inviteCode->pv = $inviteCode->pv + 1;
$inviteCode->save();
}
return $this->success(true);
}
}
@@ -0,0 +1,65 @@
<?php
namespace App\Http\Controllers\V1\Server;
use App\Exceptions\ApiException;
use App\Http\Controllers\Controller;
use App\Models\ServerShadowsocks;
use App\Services\ServerService;
use App\Services\UserService;
use App\Utils\CacheKey;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
/*
* Tidal Lab Shadowsocks
* Github: https://github.com/tokumeikoi/tidalab-ss
*/
class ShadowsocksTidalabController extends Controller
{
// 后端获取用户
public function user(Request $request)
{
ini_set('memory_limit', -1);
$server = $request->attributes->get('node_info');
Cache::put(CacheKey::get('SERVER_SHADOWSOCKS_LAST_CHECK_AT', $server->id), time(), 3600);
$users = ServerService::getAvailableUsers($server);
$result = [];
foreach ($users as $user) {
array_push($result, [
'id' => $user->id,
'port' => $server->server_port,
'cipher' => $server->cipher,
'secret' => $user->uuid
]);
}
$eTag = sha1(json_encode($result));
if (strpos($request->header('If-None-Match'), $eTag) !== false ) {
return response(null,304);
}
return response([
'data' => $result
])->header('ETag', "\"{$eTag}\"");
}
// 后端提交数据
public function submit(Request $request)
{
$server = $request->attributes->get('node_info');
$data = json_decode(request()->getContent(), true);
Cache::put(CacheKey::get('SERVER_SHADOWSOCKS_ONLINE_USER', $server->id), count($data), 3600);
Cache::put(CacheKey::get('SERVER_SHADOWSOCKS_LAST_PUSH_AT', $server->id), time(), 3600);
$userService = new UserService();
$formatData = [];
foreach ($data as $item) {
$formatData[$item['user_id']] = [$item['u'], $item['d']];
}
$userService->trafficFetch($server, 'shadowsocks', $formatData);
return response([
'ret' => 1,
'msg' => 'ok'
]);
}
}
@@ -0,0 +1,108 @@
<?php
namespace App\Http\Controllers\V1\Server;
use App\Exceptions\ApiException;
use App\Http\Controllers\Controller;
use App\Models\ServerTrojan;
use App\Services\ServerService;
use App\Services\UserService;
use App\Utils\CacheKey;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
/*
* Tidal Lab Trojan
* Github: https://github.com/tokumeikoi/tidalab-trojan
*/
class TrojanTidalabController extends Controller
{
const TROJAN_CONFIG = '{"run_type":"server","local_addr":"0.0.0.0","local_port":443,"remote_addr":"www.taobao.com","remote_port":80,"password":[],"ssl":{"cert":"server.crt","key":"server.key","sni":"domain.com"},"api":{"enabled":true,"api_addr":"127.0.0.1","api_port":10000}}';
// 后端获取用户
public function user(Request $request)
{
ini_set('memory_limit', -1);
$server = $request->attributes->get('node_info');
if ($server->type !== 'trojan') {
return $this->fail([400, '节点不存在']);
}
Cache::put(CacheKey::get('SERVER_TROJAN_LAST_CHECK_AT', $server->id), time(), 3600);
$users = ServerService::getAvailableUsers($server);
$result = [];
foreach ($users as $user) {
$user->trojan_user = [
"password" => $user->uuid,
];
unset($user->uuid);
array_push($result, $user);
}
$eTag = sha1(json_encode($result));
if (strpos($request->header('If-None-Match'), $eTag) !== false) {
return response(null, 304);
}
return response([
'msg' => 'ok',
'data' => $result,
])->header('ETag', "\"{$eTag}\"");
}
// 后端提交数据
public function submit(Request $request)
{
$server = $request->attributes->get('node_info');
if ($server->type !== 'trojan') {
return $this->fail([400, '节点不存在']);
}
$data = json_decode(request()->getContent(), true);
Cache::put(CacheKey::get('SERVER_TROJAN_ONLINE_USER', $server->id), count($data), 3600);
Cache::put(CacheKey::get('SERVER_TROJAN_LAST_PUSH_AT', $server->id), time(), 3600);
$userService = new UserService();
$formatData = [];
foreach ($data as $item) {
$formatData[$item['user_id']] = [$item['u'], $item['d']];
}
$userService->trafficFetch($server, 'trojan', $formatData);
return response([
'ret' => 1,
'msg' => 'ok'
]);
}
// 后端获取配置
public function config(Request $request)
{
$server = $request->attributes->get('node_info');
if ($server->type !== 'trojan') {
return $this->fail([400, '节点不存在']);
}
$request->validate([
'node_id' => 'required',
'local_port' => 'required'
], [
'node_id.required' => '节点ID不能为空',
'local_port.required' => '本地端口不能为空'
]);
try {
$json = $this->getTrojanConfig($server, $request->input('local_port'));
} catch (\Exception $e) {
\Log::error($e);
return $this->fail([500, '配置获取失败']);
}
return (json_encode($json, JSON_UNESCAPED_UNICODE));
}
private function getTrojanConfig($server, int $localPort)
{
$protocolSettings = $server->protocol_settings;
$json = json_decode(self::TROJAN_CONFIG);
$json->local_port = $server->server_port;
$json->ssl->sni = data_get($protocolSettings, 'server_name', $server->host);
$json->ssl->cert = "/root/.cert/server.crt";
$json->ssl->key = "/root/.cert/server.key";
$json->api->api_port = $localPort;
return $json;
}
}
@@ -0,0 +1,114 @@
<?php
namespace App\Http\Controllers\V1\Server;
use App\Http\Controllers\Controller;
use App\Services\DeviceStateService;
use App\Services\ServerService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Http\JsonResponse;
class UniProxyController extends Controller
{
public function __construct(
private readonly DeviceStateService $deviceStateService
) {
}
private function getNodeInfo(Request $request)
{
return $request->attributes->get('node_info');
}
public function user(Request $request)
{
ini_set('memory_limit', -1);
$node = $this->getNodeInfo($request);
ServerService::touchNode($node);
$response['users'] = ServerService::getAvailableUsers($node);
$eTag = sha1(json_encode($response));
if (str_contains($request->header('If-None-Match', ''), $eTag)) {
return response(null, 304);
}
return response($response)->header('ETag', "\"{$eTag}\"");
}
public function push(Request $request)
{
$res = json_decode(request()->getContent(), true);
if (!is_array($res)) {
return $this->fail([422, 'Invalid data format']);
}
$node = $this->getNodeInfo($request);
ServerService::processTraffic($node, $res);
return $this->success(true);
}
public function config(Request $request)
{
$node = $this->getNodeInfo($request);
$response = ServerService::buildNodeConfig($node);
$response['base_config'] = [
'push_interval' => (int) admin_setting('server_push_interval', 60),
'pull_interval' => (int) admin_setting('server_pull_interval', 60)
];
$eTag = sha1(json_encode($response));
if (str_contains($request->header('If-None-Match', ''), $eTag)) {
return response(null, 304);
}
return response($response)->header('ETag', "\"{$eTag}\"");
}
public function alivelist(Request $request): JsonResponse
{
$node = $this->getNodeInfo($request);
$deviceLimitUsers = ServerService::getAvailableUsers($node)
->where('device_limit', '>', 0);
$alive = $this->deviceStateService->getAliveList(collect($deviceLimitUsers));
return response()->json(['alive' => (object) $alive]);
}
public function alive(Request $request): JsonResponse
{
$node = $this->getNodeInfo($request);
$data = json_decode(request()->getContent(), true);
if ($data === null) {
return response()->json(['error' => 'Invalid online data'], 400);
}
ServerService::processAlive($node->id, $data);
return response()->json(['data' => true]);
}
public function status(Request $request): JsonResponse
{
$node = $this->getNodeInfo($request);
$data = $request->validate([
'cpu' => 'required|numeric|min:0|max:100',
'mem.total' => 'required|integer|min:0',
'mem.used' => 'required|integer|min:0',
'swap.total' => 'required|integer|min:0',
'swap.used' => 'required|integer|min:0',
'disk.total' => 'required|integer|min:0',
'disk.used' => 'required|integer|min:0',
]);
ServerService::processStatus($node, $data);
return response()->json(['data' => true, 'code' => 0, 'message' => 'success']);
}
}
@@ -0,0 +1,39 @@
<?php
namespace App\Http\Controllers\V1\User;
use App\Exceptions\ApiException;
use App\Http\Controllers\Controller;
use App\Models\Payment;
use App\Utils\Dict;
use Illuminate\Http\Request;
class CommController extends Controller
{
public function config()
{
$data = [
'is_telegram' => (int)admin_setting('telegram_bot_enable', 0),
'telegram_discuss_link' => admin_setting('telegram_discuss_link'),
'stripe_pk' => admin_setting('stripe_pk_live'),
'withdraw_methods' => admin_setting('commission_withdraw_method', Dict::WITHDRAW_METHOD_WHITELIST_DEFAULT),
'withdraw_close' => (int)admin_setting('withdraw_close_enable', 0),
'currency' => admin_setting('currency', 'CNY'),
'currency_symbol' => admin_setting('currency_symbol', '¥'),
'commission_distribution_enable' => (int)admin_setting('commission_distribution_enable', 0),
'commission_distribution_l1' => admin_setting('commission_distribution_l1'),
'commission_distribution_l2' => admin_setting('commission_distribution_l2'),
'commission_distribution_l3' => admin_setting('commission_distribution_l3')
];
return $this->success($data);
}
public function getStripePublicKey(Request $request)
{
$payment = Payment::where('id', $request->input('id'))
->where('payment', 'StripeCredit')
->first();
if (!$payment) throw new ApiException('payment is not found');
return $this->success($payment->config['stripe_pk_live']);
}
}
@@ -0,0 +1,25 @@
<?php
namespace App\Http\Controllers\V1\User;
use App\Exceptions\ApiException;
use App\Http\Controllers\Controller;
use App\Http\Resources\CouponResource;
use App\Services\CouponService;
use Illuminate\Http\Request;
class CouponController extends Controller
{
public function check(Request $request)
{
if (empty($request->input('code'))) {
return $this->fail([422, __('Coupon cannot be empty')]);
}
$couponService = new CouponService($request->input('code'));
$couponService->setPlanId($request->input('plan_id'));
$couponService->setUserId($request->user()->id);
$couponService->setPeriod($request->input('period'));
$couponService->check();
return $this->success(CouponResource::make($couponService->getCoupon()));
}
}
@@ -0,0 +1,193 @@
<?php
namespace App\Http\Controllers\V1\User;
use App\Exceptions\ApiException;
use App\Http\Controllers\Controller;
use App\Http\Requests\User\GiftCardCheckRequest;
use App\Http\Requests\User\GiftCardRedeemRequest;
use App\Models\GiftCardUsage;
use App\Services\GiftCardService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
class GiftCardController extends Controller
{
/**
* 查询兑换码信息
*/
public function check(GiftCardCheckRequest $request)
{
try {
$giftCardService = new GiftCardService($request->input('code'));
$giftCardService->setUser($request->user());
// 1. 验证礼品卡本身是否有效 (如不存在、已过期、已禁用)
$giftCardService->validateIsActive();
// 2. 检查用户是否满足使用条件,但不在此处抛出异常
$eligibility = $giftCardService->checkUserEligibility();
// 3. 获取卡片信息和奖励预览
$codeInfo = $giftCardService->getCodeInfo();
$rewardPreview = $giftCardService->previewRewards();
return $this->success([
'code_info' => $codeInfo, // 这里面已经包含 plan_info
'reward_preview' => $rewardPreview,
'can_redeem' => $eligibility['can_redeem'],
'reason' => $eligibility['reason'],
]);
} catch (ApiException $e) {
// 这里只捕获 validateIsActive 抛出的异常
return $this->fail([400, $e->getMessage()]);
} catch (\Exception $e) {
Log::error('礼品卡查询失败', [
'code' => $request->input('code'),
'user_id' => $request->user()->id,
'error' => $e->getMessage(),
]);
return $this->fail([500, '查询失败,请稍后重试']);
}
}
/**
* 使用兑换码
*/
public function redeem(GiftCardRedeemRequest $request)
{
try {
$giftCardService = new GiftCardService($request->input('code'));
$giftCardService->setUser($request->user());
$giftCardService->validate();
// 使用礼品卡
$result = $giftCardService->redeem([
// 'ip_address' => $request->ip(),
'user_agent' => $request->userAgent(),
]);
Log::info('礼品卡使用成功', [
'code' => $request->input('code'),
'user_id' => $request->user()->id,
'rewards' => $result['rewards'],
]);
return $this->success([
'message' => '兑换成功!',
'rewards' => $result['rewards'],
'invite_rewards' => $result['invite_rewards'],
'template_name' => $result['template_name'],
]);
} catch (ApiException $e) {
return $this->fail([400, $e->getMessage()]);
} catch (\Exception $e) {
Log::error('礼品卡使用失败', [
'code' => $request->input('code'),
'user_id' => $request->user()->id,
'error' => $e->getMessage(),
'trace' => $e->getTraceAsString(),
]);
return $this->fail([500, '兑换失败,请稍后重试']);
}
}
/**
* 获取用户兑换记录
*/
public function history(Request $request)
{
$request->validate([
'page' => 'integer|min:1',
'per_page' => 'integer|min:1|max:100',
]);
$perPage = $request->input('per_page', 15);
$usages = GiftCardUsage::with(['template', 'code'])
->where('user_id', $request->user()->id)
->orderBy('created_at', 'desc')
->paginate($perPage);
$data = $usages->getCollection()->map(function (GiftCardUsage $usage) {
return [
'id' => $usage->id,
'code' => ($usage->code instanceof \App\Models\GiftCardCode && $usage->code->code)
? (substr($usage->code->code, 0, 8) . '****')
: '',
'template_name' => $usage->template->name ?? '',
'template_type' => $usage->template->type ?? '',
'template_type_name' => $usage->template->type_name ?? '',
'rewards_given' => $usage->rewards_given,
'invite_rewards' => $usage->invite_rewards,
'multiplier_applied' => $usage->multiplier_applied,
'created_at' => $usage->created_at,
];
})->values();
return response()->json([
'data' => $data,
'pagination' => [
'current_page' => $usages->currentPage(),
'last_page' => $usages->lastPage(),
'per_page' => $usages->perPage(),
'total' => $usages->total(),
],
]);
}
/**
* 获取兑换记录详情
*/
public function detail(Request $request)
{
$request->validate([
'id' => 'required|integer|exists:v2_gift_card_usage,id',
]);
$usage = GiftCardUsage::with(['template', 'code', 'inviteUser'])
->where('user_id', $request->user()->id)
->where('id', $request->input('id'))
->first();
if (!$usage) {
return $this->fail([404, '记录不存在']);
}
return $this->success([
'id' => $usage->id,
'code' => $usage->code->code ?? '',
'template' => [
'name' => $usage->template->name ?? '',
'description' => $usage->template->description ?? '',
'type' => $usage->template->type ?? '',
'type_name' => $usage->template->type_name ?? '',
'icon' => $usage->template->icon ?? '',
'theme_color' => $usage->template->theme_color ?? '',
],
'rewards_given' => $usage->rewards_given,
'invite_rewards' => $usage->invite_rewards,
'invite_user' => $usage->inviteUser ? [
'id' => $usage->inviteUser->id ?? '',
'email' => isset($usage->inviteUser->email) ? (substr($usage->inviteUser->email, 0, 3) . '***@***') : '',
] : null,
'user_level_at_use' => $usage->user_level_at_use,
'plan_id_at_use' => $usage->plan_id_at_use,
'multiplier_applied' => $usage->multiplier_applied,
// 'ip_address' => $usage->ip_address,
'notes' => $usage->notes,
'created_at' => $usage->created_at,
]);
}
/**
* 获取可用的礼品卡类型
*/
public function types(Request $request)
{
return $this->success([
'types' => \App\Models\GiftCardTemplate::getTypeMap(),
]);
}
}
@@ -0,0 +1,79 @@
<?php
namespace App\Http\Controllers\V1\User;
use App\Exceptions\ApiException;
use App\Http\Controllers\Controller;
use App\Http\Resources\ComissionLogResource;
use App\Http\Resources\InviteCodeResource;
use App\Models\CommissionLog;
use App\Models\InviteCode;
use App\Models\Order;
use App\Models\User;
use App\Utils\Helper;
use Illuminate\Http\Request;
class InviteController extends Controller
{
public function save(Request $request)
{
if (InviteCode::where('user_id', $request->user()->id)->where('status', 0)->count() >= admin_setting('invite_gen_limit', 5)) {
return $this->fail([400,__('The maximum number of creations has been reached')]);
}
$inviteCode = new InviteCode();
$inviteCode->user_id = $request->user()->id;
$inviteCode->code = Helper::randomChar(8);
return $this->success($inviteCode->save());
}
public function details(Request $request)
{
$current = $request->input('current') ? $request->input('current') : 1;
$pageSize = $request->input('page_size') >= 10 ? $request->input('page_size') : 10;
$builder = CommissionLog::where('invite_user_id', $request->user()->id)
->where('get_amount', '>', 0)
->orderBy('created_at', 'DESC');
$total = $builder->count();
$details = $builder->forPage($current, $pageSize)
->get();
return response([
'data' => ComissionLogResource::collection($details),
'total' => $total
]);
}
public function fetch(Request $request)
{
$commission_rate = admin_setting('invite_commission', 10);
$user = User::find($request->user()->id)
->load(['codes' => fn($query) => $query->where('status', 0)]);
if ($user->commission_rate) {
$commission_rate = $user->commission_rate;
}
$uncheck_commission_balance = (int)Order::where('status', 3)
->where('commission_status', 0)
->where('invite_user_id', $user->id)
->sum('commission_balance');
if (admin_setting('commission_distribution_enable', 0)) {
$uncheck_commission_balance = $uncheck_commission_balance * (admin_setting('commission_distribution_l1') / 100);
}
$stat = [
//已注册用户数
(int)User::where('invite_user_id', $user->id)->count(),
//有效的佣金
(int)CommissionLog::where('invite_user_id', $user->id)
->sum('get_amount'),
//确认中的佣金
$uncheck_commission_balance,
//佣金比例
(int)$commission_rate,
//可用佣金
(int)$user->commission_balance
];
$data = [
'codes' => InviteCodeResource::collection($user->codes),
'stat' => $stat
];
return $this->success($data);
}
}
@@ -0,0 +1,150 @@
<?php
namespace App\Http\Controllers\V1\User;
use App\Exceptions\ApiException;
use App\Http\Controllers\Controller;
use App\Http\Resources\KnowledgeResource;
use App\Models\Knowledge;
use App\Models\User;
use App\Services\Plugin\HookManager;
use App\Services\UserService;
use App\Utils\Helper;
use Illuminate\Http\Request;
class KnowledgeController extends Controller
{
private UserService $userService;
public function __construct(UserService $userService)
{
$this->userService = $userService;
}
public function fetch(Request $request)
{
$request->validate([
'id' => 'nullable|sometimes|integer|min:1',
'language' => 'nullable|sometimes|string|max:10',
'keyword' => 'nullable|sometimes|string|max:255',
]);
return $request->input('id')
? $this->fetchSingle($request)
: $this->fetchList($request);
}
private function fetchSingle(Request $request)
{
$knowledge = $this->buildKnowledgeQuery()
->where('id', $request->input('id'))
->first();
if (!$knowledge) {
return $this->fail([500, __('Article does not exist')]);
}
$knowledge = $knowledge->toArray();
$knowledge = $this->processKnowledgeContent($knowledge, $request->user());
return $this->success(KnowledgeResource::make($knowledge));
}
private function fetchList(Request $request)
{
$builder = $this->buildKnowledgeQuery(['id', 'category', 'title', 'updated_at', 'body'])
->where('language', $request->input('language'))
->orderBy('sort', 'ASC');
$keyword = $request->input('keyword');
if ($keyword) {
$builder = $builder->where(function ($query) use ($keyword) {
$query->where('title', 'LIKE', "%{$keyword}%")
->orWhere('body', 'LIKE', "%{$keyword}%");
});
}
$knowledges = $builder->get()
->map(function ($knowledge) use ($request) {
$knowledge = $knowledge->toArray();
$knowledge = $this->processKnowledgeContent($knowledge, $request->user());
return KnowledgeResource::make($knowledge);
})
->groupBy('category');
return $this->success($knowledges);
}
private function buildKnowledgeQuery(array $select = ['*'])
{
return Knowledge::select($select)->where('show', 1);
}
private function processKnowledgeContent(array $knowledge, User $user): array
{
if (!isset($knowledge['body'])) {
return $knowledge;
}
if (!$this->userService->isAvailable($user)) {
$this->formatAccessData($knowledge['body']);
}
$subscribeUrl = Helper::getSubscribeUrl($user['token']);
$knowledge['body'] = $this->replacePlaceholders($knowledge['body'], $subscribeUrl);
return $knowledge;
}
private function formatAccessData(&$body): void
{
$rules = [
[
'type' => 'regex',
'pattern' => '/<!--access start-->(.*?)<!--access end-->/s',
'replacement' => '<div class="v2board-no-access">' . __('You must have a valid subscription to view content in this area') . '</div>'
]
];
$this->applyReplacementRules($body, $rules);
}
private function replacePlaceholders(string $body, string $subscribeUrl): string
{
$rules = [
[
'type' => 'string',
'search' => '{{siteName}}',
'replacement' => admin_setting('app_name', 'XBoard')
],
[
'type' => 'string',
'search' => '{{subscribeUrl}}',
'replacement' => $subscribeUrl
],
[
'type' => 'string',
'search' => '{{urlEncodeSubscribeUrl}}',
'replacement' => urlencode($subscribeUrl)
],
[
'type' => 'string',
'search' => '{{safeBase64SubscribeUrl}}',
'replacement' => str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($subscribeUrl))
]
];
$this->applyReplacementRules($body, $rules);
return $body;
}
private function applyReplacementRules(string &$body, array $rules): void
{
foreach ($rules as $rule) {
if ($rule['type'] === 'regex') {
$body = preg_replace($rule['pattern'], $rule['replacement'], $body);
} else {
$body = str_replace($rule['search'], $rule['replacement'], $body);
}
}
}
}
@@ -0,0 +1,26 @@
<?php
namespace App\Http\Controllers\V1\User;
use App\Http\Controllers\Controller;
use App\Models\Notice;
use Illuminate\Http\Request;
class NoticeController extends Controller
{
public function fetch(Request $request)
{
$current = $request->input('current') ? $request->input('current') : 1;
$pageSize = 5;
$model = Notice::orderBy('sort', 'ASC')
->orderBy('id', 'DESC')
->where('show', true);
$total = $model->count();
$res = $model->forPage($current, $pageSize)
->get();
return response([
'data' => $res,
'total' => $total
]);
}
}
+215
View File
@@ -0,0 +1,215 @@
<?php
namespace App\Http\Controllers\V1\User;
use App\Exceptions\ApiException;
use App\Http\Controllers\Controller;
use App\Http\Requests\User\OrderSave;
use App\Http\Resources\OrderResource;
use App\Models\Order;
use App\Models\Payment;
use App\Models\Plan;
use App\Models\User;
use App\Services\CouponService;
use App\Services\OrderService;
use App\Services\PaymentService;
use App\Services\PlanService;
use App\Services\UserService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class OrderController extends Controller
{
public function fetch(Request $request)
{
$request->validate([
'status' => 'nullable|integer|in:0,1,2,3',
]);
$orders = Order::with('plan')
->where('user_id', $request->user()->id)
->when($request->input('status') !== null, function ($query) use ($request) {
$query->where('status', $request->input('status'));
})
->orderBy('created_at', 'DESC')
->get();
return $this->success(OrderResource::collection($orders));
}
public function detail(Request $request)
{
$request->validate([
'trade_no' => 'required|string',
]);
$order = Order::with(['payment', 'plan'])
->where('user_id', $request->user()->id)
->where('trade_no', $request->input('trade_no'))
->first();
if (!$order) {
return $this->fail([400, __('Order does not exist or has been paid')]);
}
$order['try_out_plan_id'] = (int) admin_setting('try_out_plan_id');
if (!$order->plan) {
return $this->fail([400, __('Subscription plan does not exist')]);
}
if ($order->surplus_order_ids) {
$order['surplus_orders'] = Order::whereIn('id', $order->surplus_order_ids)->get();
}
return $this->success(OrderResource::make($order));
}
public function save(OrderSave $request)
{
$request->validate([
'plan_id' => 'required|exists:App\Models\Plan,id',
'period' => 'required|string'
]);
$user = User::findOrFail($request->user()->id);
$userService = app(UserService::class);
if ($userService->isNotCompleteOrderByUserId($user->id)) {
throw new ApiException(__('You have an unpaid or pending order, please try again later or cancel it'));
}
$plan = Plan::findOrFail($request->input('plan_id'));
$planService = new PlanService($plan);
$planService->validatePurchase($user, $request->input('period'));
$order = OrderService::createFromRequest(
$user,
$plan,
$request->input('period'),
$request->input('coupon_code')
);
return $this->success($order->trade_no);
}
protected function applyCoupon(Order $order, string $couponCode): void
{
$couponService = new CouponService($couponCode);
if (!$couponService->use($order)) {
throw new ApiException(__('Coupon failed'));
}
$order->coupon_id = $couponService->getId();
}
protected function handleUserBalance(Order $order, User $user, UserService $userService): void
{
$remainingBalance = $user->balance - $order->total_amount;
if ($remainingBalance > 0) {
if (!$userService->addBalance($order->user_id, -$order->total_amount)) {
throw new ApiException(__('Insufficient balance'));
}
$order->balance_amount = $order->total_amount;
$order->total_amount = 0;
} else {
if (!$userService->addBalance($order->user_id, -$user->balance)) {
throw new ApiException(__('Insufficient balance'));
}
$order->balance_amount = $user->balance;
$order->total_amount = $order->total_amount - $user->balance;
}
}
public function checkout(Request $request)
{
$tradeNo = $request->input('trade_no');
$method = $request->input('method');
$order = Order::where('trade_no', $tradeNo)
->where('user_id', $request->user()->id)
->where('status', 0)
->first();
if (!$order) {
return $this->fail([400, __('Order does not exist or has been paid')]);
}
if ($order->total_amount < 0) {
return $this->fail([400, __('Order amount is invalid')]);
}
// free process
if ($order->total_amount <= 0) {
$orderService = new OrderService($order);
if (!$orderService->paid($order->trade_no))
return $this->fail([400, '支付失败']);
return response([
'type' => -1,
'data' => true
]);
}
$payment = Payment::find($method);
if (!$payment || !$payment->enable) {
return $this->fail([400, __('Payment method is not available')]);
}
$paymentService = new PaymentService($payment->payment, $payment->id);
$order->handling_amount = NULL;
if ($payment->handling_fee_fixed || $payment->handling_fee_percent) {
$order->handling_amount = (int) round(($order->total_amount * ($payment->handling_fee_percent / 100)) + $payment->handling_fee_fixed);
}
$order->payment_id = $method;
if (!$order->save())
return $this->fail([400, __('Request failed, please try again later')]);
$result = $paymentService->pay([
'trade_no' => $tradeNo,
'total_amount' => isset($order->handling_amount) ? ($order->total_amount + $order->handling_amount) : $order->total_amount,
'user_id' => $order->user_id,
'stripe_token' => $request->input('token')
]);
return response([
'type' => $result['type'],
'data' => $result['data']
]);
}
public function check(Request $request)
{
$tradeNo = $request->input('trade_no');
$order = Order::where('trade_no', $tradeNo)
->where('user_id', $request->user()->id)
->first();
if (!$order) {
return $this->fail([400, __('Order does not exist')]);
}
return $this->success($order->status);
}
public function getPaymentMethod()
{
$methods = Payment::select([
'id',
'name',
'payment',
'icon',
'handling_fee_fixed',
'handling_fee_percent'
])
->where('enable', 1)
->orderBy('sort', 'ASC')
->get();
return $this->success($methods);
}
public function cancel(Request $request)
{
if (empty($request->input('trade_no'))) {
return $this->fail([422, __('Invalid parameter')]);
}
$order = Order::where('trade_no', $request->input('trade_no'))
->where('user_id', $request->user()->id)
->first();
if (!$order) {
return $this->fail([400, __('Order does not exist')]);
}
if ($order->status !== 0) {
return $this->fail([400, __('You can only cancel pending orders')]);
}
$orderService = new OrderService($order);
if (!$orderService->cancel()) {
return $this->fail([400, __('Cancel failed')]);
}
return $this->success(true);
}
}
+38
View File
@@ -0,0 +1,38 @@
<?php
namespace App\Http\Controllers\V1\User;
use App\Exceptions\ApiException;
use App\Http\Controllers\Controller;
use App\Http\Resources\PlanResource;
use App\Models\Plan;
use App\Models\User;
use App\Services\PlanService;
use Illuminate\Http\Request;
class PlanController extends Controller
{
protected PlanService $planService;
public function __construct(PlanService $planService)
{
$this->planService = $planService;
}
public function fetch(Request $request)
{
$user = User::find($request->user()->id);
if ($request->input('id')) {
$plan = Plan::where('id', $request->input('id'))->first();
if (!$plan) {
return $this->fail([400, __('Subscription plan does not exist')]);
}
if (!$this->planService->isPlanAvailableForUser($plan, $user)) {
return $this->fail([400, __('Subscription plan does not exist')]);
}
return $this->success(PlanResource::make($plan));
}
$plans = $this->planService->getAvailablePlans($user);
return $this->success(PlanResource::collection($plans));
}
}
@@ -0,0 +1,31 @@
<?php
namespace App\Http\Controllers\V1\User;
use App\Http\Controllers\Controller;
use App\Http\Resources\NodeResource;
use App\Models\User;
use App\Services\ServerService;
use App\Services\UserService;
use Illuminate\Http\Request;
class ServerController extends Controller
{
public function fetch(Request $request)
{
$user = User::find($request->user()->id);
$servers = [];
$userService = new UserService();
if ($userService->isAvailable($user)) {
$servers = ServerService::getAvailableServers($user);
}
$eTag = sha1(json_encode(array_column($servers, 'cache_key')));
if (strpos($request->header('If-None-Match', ''), $eTag) !== false ) {
return response(null,304);
}
$data = NodeResource::collection($servers);
return response([
'data' => $data
])->header('ETag', "\"{$eTag}\"");
}
}
@@ -0,0 +1,26 @@
<?php
namespace App\Http\Controllers\V1\User;
use App\Http\Controllers\Controller;
use App\Http\Resources\TrafficLogResource;
use App\Models\StatUser;
use App\Services\StatisticalService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class StatController extends Controller
{
public function getTrafficLog(Request $request)
{
$startDate = now()->startOfMonth()->timestamp;
$records = StatUser::query()
->where('user_id', $request->user()->id)
->where('record_at', '>=', $startDate)
->orderBy('record_at', 'DESC')
->get();
$data = TrafficLogResource::collection(collect($records));
return $this->success($data);
}
}
@@ -0,0 +1,26 @@
<?php
namespace App\Http\Controllers\V1\User;
use App\Http\Controllers\Controller;
use App\Models\User;
use App\Services\TelegramService;
use Illuminate\Http\Request;
class TelegramController extends Controller
{
public function getBotInfo()
{
$telegramService = new TelegramService();
$response = $telegramService->getMe();
$data = [
'username' => $response->result->username
];
return $this->success($data);
}
public function unbind(Request $request)
{
$user = User::where('user_id', $request->user()->id)->first();
}
}
@@ -0,0 +1,154 @@
<?php
namespace App\Http\Controllers\V1\User;
use App\Http\Controllers\Controller;
use App\Http\Requests\User\TicketSave;
use App\Http\Requests\User\TicketWithdraw;
use App\Http\Resources\TicketResource;
use App\Models\Ticket;
use App\Models\TicketMessage;
use App\Models\User;
use App\Services\TicketService;
use App\Utils\Dict;
use Illuminate\Http\Request;
use App\Services\Plugin\HookManager;
use Illuminate\Support\Facades\Log;
class TicketController extends Controller
{
public function fetch(Request $request)
{
if ($request->input('id')) {
$ticket = Ticket::where('id', $request->input('id'))
->where('user_id', $request->user()->id)
->first()
->load('message');
if (!$ticket) {
return $this->fail([400, __('Ticket does not exist')]);
}
$ticket['message'] = TicketMessage::where('ticket_id', $ticket->id)->get();
$ticket['message']->each(function ($message) use ($ticket) {
$message['is_me'] = ($message['user_id'] == $ticket->user_id);
});
return $this->success(TicketResource::make($ticket)->additional(['message' => true]));
}
$ticket = Ticket::where('user_id', $request->user()->id)
->orderBy('created_at', 'DESC')
->get();
return $this->success(TicketResource::collection($ticket));
}
public function save(TicketSave $request)
{
$ticketService = new TicketService();
$ticket = $ticketService->createTicket(
$request->user()->id,
$request->input('subject'),
$request->input('level'),
$request->input('message')
);
HookManager::call('ticket.create.after', $ticket);
return $this->success(true);
}
public function reply(Request $request)
{
if (empty($request->input('id'))) {
return $this->fail([400, __('Invalid parameter')]);
}
if (empty($request->input('message'))) {
return $this->fail([400, __('Message cannot be empty')]);
}
$ticket = Ticket::where('id', $request->input('id'))
->where('user_id', $request->user()->id)
->first();
if (!$ticket) {
return $this->fail([400, __('Ticket does not exist')]);
}
if ($ticket->status) {
return $this->fail([400, __('The ticket is closed and cannot be replied')]);
}
if ((int) admin_setting('ticket_must_wait_reply', 0) && $request->user()->id == $this->getLastMessage($ticket->id)->user_id) {
return $this->fail(codeResponse: [400, __('Please wait for the technical enginneer to reply')]);
}
$ticketService = new TicketService();
if (
!$ticketService->reply(
$ticket,
$request->input('message'),
$request->user()->id
)
) {
return $this->fail([400, __('Ticket reply failed')]);
}
HookManager::call('ticket.reply.user.after', $ticket);
return $this->success(true);
}
public function close(Request $request)
{
if (empty($request->input('id'))) {
return $this->fail([422, __('Invalid parameter')]);
}
$ticket = Ticket::where('id', $request->input('id'))
->where('user_id', $request->user()->id)
->first();
if (!$ticket) {
return $this->fail([400, __('Ticket does not exist')]);
}
$ticket->status = Ticket::STATUS_CLOSED;
if (!$ticket->save()) {
return $this->fail([500, __('Close failed')]);
}
return $this->success(true);
}
private function getLastMessage($ticketId)
{
return TicketMessage::where('ticket_id', $ticketId)
->orderBy('id', 'DESC')
->first();
}
public function withdraw(TicketWithdraw $request)
{
if ((int) admin_setting('withdraw_close_enable', 0)) {
return $this->fail([400, 'Unsupported withdraw']);
}
if (
!in_array(
$request->input('withdraw_method'),
admin_setting('commission_withdraw_method', Dict::WITHDRAW_METHOD_WHITELIST_DEFAULT)
)
) {
return $this->fail([422, __('Unsupported withdrawal method')]);
}
$user = User::find($request->user()->id);
$limit = admin_setting('commission_withdraw_limit', 100);
if ($limit > ($user->commission_balance / 100)) {
return $this->fail([422, __('The current required minimum withdrawal commission is :limit', ['limit' => $limit])]);
}
try {
$ticketService = new TicketService();
$subject = __('[Commission Withdrawal Request] This ticket is opened by the system');
$message = sprintf(
"%s\r\n%s",
__('Withdrawal method') . ":" . $request->input('withdraw_method'),
__('Withdrawal account') . ":" . $request->input('withdraw_account')
);
$ticket = $ticketService->createTicket(
$request->user()->id,
$subject,
2,
$message
);
} catch (\Exception $e) {
throw $e;
}
HookManager::call('ticket.create.after', $ticket);
return $this->success(true);
}
}
+223
View File
@@ -0,0 +1,223 @@
<?php
namespace App\Http\Controllers\V1\User;
use App\Http\Controllers\Controller;
use App\Http\Requests\User\UserChangePassword;
use App\Http\Requests\User\UserTransfer;
use App\Http\Requests\User\UserUpdate;
use App\Models\Order;
use App\Models\Plan;
use App\Models\Ticket;
use App\Models\User;
use App\Services\Auth\LoginService;
use App\Services\AuthService;
use App\Services\Plugin\HookManager;
use App\Services\UserService;
use App\Utils\CacheKey;
use App\Utils\Helper;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
class UserController extends Controller
{
protected $loginService;
public function __construct(
LoginService $loginService
) {
$this->loginService = $loginService;
}
public function getActiveSession(Request $request)
{
$user = $request->user();
$authService = new AuthService($user);
return $this->success($authService->getSessions());
}
public function removeActiveSession(Request $request)
{
$user = $request->user();
$authService = new AuthService($user);
return $this->success($authService->removeSession($request->input('session_id')));
}
public function checkLogin(Request $request)
{
$data = [
'is_login' => $request->user()?->id ? true : false
];
if ($request->user()?->is_admin) {
$data['is_admin'] = true;
}
return $this->success($data);
}
public function changePassword(UserChangePassword $request)
{
$user = $request->user();
if (
!Helper::multiPasswordVerify(
$user->password_algo,
$user->password_salt,
$request->input('old_password'),
$user->password
)
) {
return $this->fail([400, __('The old password is wrong')]);
}
$user->password = password_hash($request->input('new_password'), PASSWORD_DEFAULT);
$user->password_algo = NULL;
$user->password_salt = NULL;
if (!$user->save()) {
return $this->fail([400, __('Save failed')]);
}
$currentToken = $user->currentAccessToken();
if ($currentToken) {
$user->tokens()->where('id', '!=', $currentToken->id)->delete();
} else {
$user->tokens()->delete();
}
return $this->success(true);
}
public function info(Request $request)
{
$user = User::where('id', $request->user()->id)
->select([
'email',
'transfer_enable',
'last_login_at',
'created_at',
'banned',
'remind_expire',
'remind_traffic',
'expired_at',
'balance',
'commission_balance',
'plan_id',
'discount',
'commission_rate',
'telegram_id',
'uuid'
])
->first();
if (!$user) {
return $this->fail([400, __('The user does not exist')]);
}
$user['avatar_url'] = 'https://cdn.v2ex.com/gravatar/' . md5($user->email) . '?s=64&d=identicon';
return $this->success($user);
}
public function getStat(Request $request)
{
$stat = [
Order::where('status', 0)
->where('user_id', $request->user()->id)
->count(),
Ticket::where('status', 0)
->where('user_id', $request->user()->id)
->count(),
User::where('invite_user_id', $request->user()->id)
->count()
];
return $this->success($stat);
}
public function getSubscribe(Request $request)
{
$user = User::where('id', $request->user()->id)
->select([
'plan_id',
'token',
'expired_at',
'u',
'd',
'transfer_enable',
'email',
'uuid',
'device_limit',
'speed_limit',
'next_reset_at'
])
->first();
if (!$user) {
return $this->fail([400, __('The user does not exist')]);
}
if ($user->plan_id) {
$user['plan'] = Plan::find($user->plan_id);
if (!$user['plan']) {
return $this->fail([400, __('Subscription plan does not exist')]);
}
}
$user['subscribe_url'] = Helper::getSubscribeUrl($user['token']);
$userService = new UserService();
$user['reset_day'] = $userService->getResetDay($user);
$user = HookManager::filter('user.subscribe.response', $user);
return $this->success($user);
}
public function resetSecurity(Request $request)
{
$user = $request->user();
$user->uuid = Helper::guid(true);
$user->token = Helper::guid();
if (!$user->save()) {
return $this->fail([400, __('Reset failed')]);
}
return $this->success(Helper::getSubscribeUrl($user->token));
}
public function update(UserUpdate $request)
{
$updateData = $request->only([
'remind_expire',
'remind_traffic'
]);
$user = $request->user();
try {
$user->update($updateData);
} catch (\Exception $e) {
return $this->fail([400, __('Save failed')]);
}
return $this->success(true);
}
public function transfer(UserTransfer $request)
{
$amount = $request->input('transfer_amount');
try {
DB::transaction(function () use ($request, $amount) {
$user = User::lockForUpdate()->find($request->user()->id);
if (!$user) {
throw new \Exception(__('The user does not exist'));
}
if ($amount > $user->commission_balance) {
throw new \Exception(__('Insufficient commission balance'));
}
$user->commission_balance -= $amount;
$user->balance += $amount;
if (!$user->save()) {
throw new \Exception(__('Transfer failed'));
}
});
} catch (\Exception $e) {
return $this->fail([400, $e->getMessage()]);
}
return $this->success(true);
}
public function getQuickLoginUrl(Request $request)
{
$user = $request->user();
$url = $this->loginService->generateQuickLoginUrl($user, $request->input('redirect'));
return $this->success($url);
}
}
@@ -0,0 +1,322 @@
<?php
namespace App\Http\Controllers\V2\Admin;
use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\ConfigSave;
use App\Models\SubscribeTemplate;
use App\Services\MailService;
use App\Services\TelegramService;
use App\Services\ThemeService;
use App\Utils\Dict;
use Illuminate\Http\Request;
class ConfigController extends Controller
{
public function getEmailTemplate()
{
$path = resource_path('views/mail/');
$files = array_map(function ($item) use ($path) {
return str_replace($path, '', $item);
}, glob($path . '*'));
return $this->success($files);
}
public function getThemeTemplate()
{
$path = public_path('theme/');
$files = array_map(function ($item) use ($path) {
return str_replace($path, '', $item);
}, glob($path . '*'));
return $this->success($files);
}
public function testSendMail(Request $request)
{
$mailLog = MailService::sendEmail([
'email' => $request->user()->email,
'subject' => 'This is xboard test email',
'template_name' => 'notify',
'purpose' => 'admin_test',
'template_value' => [
'name' => admin_setting('app_name', 'XBoard'),
'content' => 'This is xboard test email',
'url' => admin_setting('app_url')
]
]);
return response([
'data' => $mailLog,
]);
}
public function setTelegramWebhook(Request $request)
{
$hookUrl = $this->resolveTelegramWebhookUrl();
if (blank($hookUrl)) {
return $this->fail([422, 'Telegram Webhook地址未配置']);
}
$telegramService = new TelegramService($request->input('telegram_bot_token'));
$telegramService->getMe();
$existing = $telegramService->getWebhookInfo()->result->url ?? '';
if ($existing !== '' && (parse_url($existing, PHP_URL_HOST) !== parse_url($hookUrl, PHP_URL_HOST) || parse_url($existing, PHP_URL_PATH) !== parse_url($hookUrl, PHP_URL_PATH))) {
return $this->fail([422, '机器人已有其他 Webhook,未覆盖。请使用独立客服机器人或先确认现有用途。']);
}
$secret = bin2hex(random_bytes(32));
$telegramService->setWebhook($hookUrl, $secret);
admin_setting(['telegram_webhook_secret' => $secret, 'telegram_bot_enable' => true]);
$telegramService->registerBotCommands();
return $this->success([
'success' => true,
'webhook_url' => $hookUrl,
'webhook_base_url' => $this->getTelegramWebhookBaseUrl(),
]);
}
public function fetch(Request $request)
{
$key = $request->input('key');
$configMappings = $this->getConfigMappings();
if ($key && isset($configMappings[$key])) {
return $this->success([$key => $configMappings[$key]]);
}
return $this->success($configMappings);
}
/**
* 获取配置映射数据
*
* @return array 配置映射数组
*/
private function getConfigMappings(): array
{
return [
'invite' => [
'invite_force' => (bool) admin_setting('invite_force', 0),
'invite_commission' => admin_setting('invite_commission', 10),
'invite_gen_limit' => admin_setting('invite_gen_limit', 5),
'invite_never_expire' => (bool) admin_setting('invite_never_expire', 0),
'commission_first_time_enable' => (bool) admin_setting('commission_first_time_enable', 1),
'commission_auto_check_enable' => (bool) admin_setting('commission_auto_check_enable', 1),
'commission_withdraw_limit' => admin_setting('commission_withdraw_limit', 100),
'commission_withdraw_method' => admin_setting('commission_withdraw_method', Dict::WITHDRAW_METHOD_WHITELIST_DEFAULT),
'withdraw_close_enable' => (bool) admin_setting('withdraw_close_enable', 0),
'commission_distribution_enable' => (bool) admin_setting('commission_distribution_enable', 0),
'commission_distribution_l1' => admin_setting('commission_distribution_l1'),
'commission_distribution_l2' => admin_setting('commission_distribution_l2'),
'commission_distribution_l3' => admin_setting('commission_distribution_l3')
],
'site' => [
'logo' => admin_setting('logo'),
'force_https' => (int) admin_setting('force_https', 0),
'stop_register' => (int) admin_setting('stop_register', 0),
'app_name' => admin_setting('app_name', 'XBoard'),
'app_description' => admin_setting('app_description', 'XBoard is best!'),
'app_url' => admin_setting('app_url'),
'subscribe_url' => admin_setting('subscribe_url'),
'try_out_plan_id' => (int) admin_setting('try_out_plan_id', 0),
'try_out_hour' => (int) admin_setting('try_out_hour', 1),
'tos_url' => admin_setting('tos_url'),
'currency' => admin_setting('currency', 'CNY'),
'currency_symbol' => admin_setting('currency_symbol', '¥'),
'ticket_must_wait_reply' => (bool) admin_setting('ticket_must_wait_reply', 0),
],
'subscribe' => [
'plan_change_enable' => (bool) admin_setting('plan_change_enable', 1),
'reset_traffic_method' => (int) admin_setting('reset_traffic_method', 0),
'surplus_enable' => (bool) admin_setting('surplus_enable', 1),
'new_order_event_id' => (int) admin_setting('new_order_event_id', 0),
'renew_order_event_id' => (int) admin_setting('renew_order_event_id', 0),
'change_order_event_id' => (int) admin_setting('change_order_event_id', 0),
'show_info_to_server_enable' => (bool) admin_setting('show_info_to_server_enable', 0),
'show_protocol_to_server_enable' => (bool) admin_setting('show_protocol_to_server_enable', 0),
'default_remind_expire' => (bool) admin_setting('default_remind_expire', 1),
'default_remind_traffic' => (bool) admin_setting('default_remind_traffic', 1),
'subscribe_path' => admin_setting('subscribe_path', 's'),
],
'frontend' => [
'frontend_theme' => admin_setting('frontend_theme', 'Xboard'),
'frontend_theme_sidebar' => admin_setting('frontend_theme_sidebar', 'light'),
'frontend_theme_header' => admin_setting('frontend_theme_header', 'dark'),
'frontend_theme_color' => admin_setting('frontend_theme_color', 'default'),
'frontend_background_url' => admin_setting('frontend_background_url'),
],
'server' => [
'server_token' => admin_setting('server_token'),
'server_pull_interval' => admin_setting('server_pull_interval', 60),
'server_push_interval' => admin_setting('server_push_interval', 60),
'device_limit_mode' => (int) admin_setting('device_limit_mode', 0),
'server_ws_enable' => (bool) admin_setting('server_ws_enable', 1),
'server_ws_url' => admin_setting('server_ws_url', ''),
],
'email' => [
'email_host' => admin_setting('email_host'),
'email_port' => admin_setting('email_port'),
'email_username' => admin_setting('email_username'),
'email_password' => admin_setting('email_password'),
'email_encryption' => admin_setting('email_encryption'),
'email_from_address' => admin_setting('email_from_address'),
'remind_mail_enable' => (bool) admin_setting('remind_mail_enable', false),
'automatic_mail_level' => \App\Services\MailFlow\AutomaticMailPolicy::state()['level'] ?? null,
'mail_flow' => \App\Services\MailFlow\Settings::publicSettings(),
],
'telegram' => [
'telegram_bot_enable' => (bool) admin_setting('telegram_bot_enable', 0),
'telegram_bot_token' => admin_setting('telegram_bot_token'),
'telegram_webhook_url' => admin_setting('telegram_webhook_url'),
'telegram_discuss_link' => admin_setting('telegram_discuss_link')
],
'app' => [
'windows_version' => admin_setting('windows_version', ''),
'windows_download_url' => admin_setting('windows_download_url', ''),
'macos_version' => admin_setting('macos_version', ''),
'macos_download_url' => admin_setting('macos_download_url', ''),
'android_version' => admin_setting('android_version', ''),
'android_download_url' => admin_setting('android_download_url', '')
],
'safe' => [
'email_verify' => (bool) admin_setting('email_verify', 0),
'safe_mode_enable' => (bool) admin_setting('safe_mode_enable', 0),
'secure_path' => admin_setting('secure_path', admin_setting('frontend_admin_path', hash('crc32b', config('app.key')))),
'email_whitelist_enable' => (bool) admin_setting('email_whitelist_enable', 0),
'email_whitelist_suffix' => admin_setting('email_whitelist_suffix', Dict::EMAIL_WHITELIST_SUFFIX_DEFAULT),
'email_gmail_limit_enable' => (bool) admin_setting('email_gmail_limit_enable', 0),
'captcha_enable' => (bool) admin_setting('captcha_enable', 0),
'captcha_type' => admin_setting('captcha_type', 'recaptcha'),
'recaptcha_key' => admin_setting('recaptcha_key', ''),
'recaptcha_site_key' => admin_setting('recaptcha_site_key', ''),
'recaptcha_v3_secret_key' => admin_setting('recaptcha_v3_secret_key', ''),
'recaptcha_v3_site_key' => admin_setting('recaptcha_v3_site_key', ''),
'recaptcha_v3_score_threshold' => admin_setting('recaptcha_v3_score_threshold', 0.5),
'turnstile_secret_key' => admin_setting('turnstile_secret_key', ''),
'turnstile_site_key' => admin_setting('turnstile_site_key', ''),
'register_limit_by_ip_enable' => (bool) admin_setting('register_limit_by_ip_enable', 0),
'register_limit_count' => admin_setting('register_limit_count', 3),
'register_limit_expire' => admin_setting('register_limit_expire', 60),
'password_limit_enable' => (bool) admin_setting('password_limit_enable', 1),
'password_limit_count' => admin_setting('password_limit_count', 5),
'password_limit_expire' => admin_setting('password_limit_expire', 60),
// 保持向后兼容
'recaptcha_enable' => (bool) admin_setting('captcha_enable', 0)
],
'subscribe_template' => [
'subscribe_template_singbox' => $this->formatTemplateContent(
subscribe_template('singbox') ?? '',
'json'
),
'subscribe_template_clash' => subscribe_template('clash') ?? '',
'subscribe_template_clashmeta' => subscribe_template('clashmeta') ?? '',
'subscribe_template_stash' => subscribe_template('stash') ?? '',
'subscribe_template_surge' => subscribe_template('surge') ?? '',
'subscribe_template_surfboard' => subscribe_template('surfboard') ?? ''
]
];
}
public function save(ConfigSave $request)
{
$data = $request->validated();
\App\Support\SiteProfile::assertSettingsWritable($data);
$templateKeys = [
'subscribe_template_singbox' => 'singbox',
'subscribe_template_clash' => 'clash',
'subscribe_template_clashmeta' => 'clashmeta',
'subscribe_template_stash' => 'stash',
'subscribe_template_surge' => 'surge',
'subscribe_template_surfboard' => 'surfboard',
];
foreach ($data as $k => $v) {
if ($k === 'automatic_mail_level') {
\App\Services\MailFlow\AutomaticMailPolicy::save((int) $v);
continue;
}
if ($k === 'mail_flow') {
$previous = (array) admin_setting('mail_flow', []);
foreach (['resend_key', 'resend_webhook_secret', 'imap_password'] as $secret) {
if (array_key_exists($secret, $v) && ($v[$secret] === null || $v[$secret] === '')) {
unset($v[$secret]); // Blank means keep the saved secret.
} elseif (!empty($v[$secret])) {
$v[$secret] = 'encrypted:' . \Illuminate\Support\Facades\Crypt::encryptString($v[$secret]);
}
}
$v = array_replace($previous, $v);
\Illuminate\Support\Facades\Cache::forget('mailflow:resend:usage');
}
if (isset($templateKeys[$k])) {
SubscribeTemplate::setContent($templateKeys[$k], $v);
continue;
}
if ($k == 'frontend_theme') {
$themeService = app(ThemeService::class);
$themeService->switch($v);
}
admin_setting([$k => $v]);
}
return $this->success(true);
}
/**
* 格式化模板内容
*
* @param mixed $content 模板内容
* @param string $format 输出格式 (json|string)
* @return string 格式化后的内容
*/
private function formatTemplateContent(mixed $content, string $format = 'string'): string
{
return match ($format) {
'json' => match (true) {
is_array($content) => json_encode(
value: $content,
flags: JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES
),
is_string($content) && str($content)->isJson() => rescue(
callback: fn() => json_encode(
value: json_decode($content, associative: true, flags: JSON_THROW_ON_ERROR),
flags: JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES
),
rescue: $content,
report: false
),
default => str($content)->toString()
},
default => str($content)->toString()
};
}
private function getTelegramWebhookBaseUrl(): ?string
{
$customUrl = trim((string) admin_setting('telegram_webhook_url', ''));
if ($customUrl !== '') {
return rtrim($customUrl, '/');
}
$appUrl = trim((string) admin_setting('app_url', ''));
if ($appUrl !== '') {
return rtrim($appUrl, '/');
}
return null;
}
private function resolveTelegramWebhookUrl(): ?string
{
$baseUrl = $this->getTelegramWebhookBaseUrl();
if (!$baseUrl) {
return null;
}
if (str_contains($baseUrl, '/api/v1/guest/telegram/webhook')) {
return $baseUrl;
}
return $baseUrl . '/api/v1/guest/telegram/webhook';
}
}
@@ -0,0 +1,186 @@
<?php
namespace App\Http\Controllers\V2\Admin;
use App\Exceptions\ApiException;
use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\CouponGenerate;
use App\Http\Requests\Admin\CouponSave;
use App\Models\Coupon;
use App\Utils\Helper;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class CouponController extends Controller
{
private function applyFiltersAndSorts(Request $request, $builder)
{
if ($request->has('filter')) {
collect($request->input('filter'))->each(function ($filter) use ($builder) {
$key = $filter['id'];
$value = $filter['value'];
$builder->where(function ($query) use ($key, $value) {
if (is_array($value)) {
$query->whereIn($key, $value);
} else {
$query->where($key, 'like', "%{$value}%");
}
});
});
}
if ($request->has('sort')) {
collect($request->input('sort'))->each(function ($sort) use ($builder) {
$key = $sort['id'];
$value = $sort['desc'] ? 'DESC' : 'ASC';
$builder->orderBy($key, $value);
});
}
}
public function fetch(Request $request)
{
$current = $request->input('current', 1);
$pageSize = $request->input('pageSize', 10);
$builder = Coupon::query();
$this->applyFiltersAndSorts($request, $builder);
$coupons = $builder
->orderBy('created_at', 'desc')
->paginate($pageSize, ["*"], 'page', $current);
return $this->paginate($coupons);
}
public function update(Request $request)
{
$params = $request->validate([
'id' => 'required|numeric',
'show' => 'nullable|boolean'
], [
'id.required' => '优惠券ID不能为空',
'id.numeric' => '优惠券ID必须为数字'
]);
try {
DB::beginTransaction();
$coupon = Coupon::find($request->input('id'));
if (!$coupon) {
throw new ApiException(400201, '优惠券不存在');
}
$coupon->update($params);
DB::commit();
} catch (\Exception $e) {
\Log::error($e);
return $this->fail([500, '保存失败']);
}
}
public function show(Request $request)
{
$request->validate([
'id' => 'required|numeric'
], [
'id.required' => '优惠券ID不能为空',
'id.numeric' => '优惠券ID必须为数字'
]);
$coupon = Coupon::find($request->input('id'));
if (!$coupon) {
return $this->fail([400202, '优惠券不存在']);
}
$coupon->show = !$coupon->show;
if (!$coupon->save()) {
return $this->fail([500, '保存失败']);
}
return $this->success(true);
}
public function generate(CouponGenerate $request)
{
if ($request->input('generate_count')) {
$this->multiGenerate($request);
return;
}
$params = $request->validated();
if (!$request->input('id')) {
if (!isset($params['code'])) {
$params['code'] = Helper::randomChar(8);
}
if (!Coupon::create($params)) {
return $this->fail([500, '创建失败']);
}
} else {
try {
Coupon::find($request->input('id'))->update($params);
} catch (\Exception $e) {
\Log::error($e);
return $this->fail([500, '保存失败']);
}
}
return $this->success(true);
}
private function multiGenerate(CouponGenerate $request)
{
$coupons = [];
$coupon = $request->validated();
$coupon['created_at'] = $coupon['updated_at'] = time();
$coupon['show'] = 1;
unset($coupon['generate_count']);
for ($i = 0; $i < $request->input('generate_count'); $i++) {
$coupon['code'] = Helper::randomChar(8);
array_push($coupons, $coupon);
}
try {
DB::beginTransaction();
if (
!Coupon::insert(array_map(function ($item) use ($coupon) {
// format data
if (isset($item['limit_plan_ids']) && is_array($item['limit_plan_ids'])) {
$item['limit_plan_ids'] = json_encode($coupon['limit_plan_ids']);
}
if (isset($item['limit_period']) && is_array($item['limit_period'])) {
$item['limit_period'] = json_encode($coupon['limit_period']);
}
return $item;
}, $coupons))
) {
throw new \Exception();
}
DB::commit();
} catch (\Exception $e) {
DB::rollBack();
return $this->fail([500, '生成失败']);
}
$data = "名称,类型,金额或比例,开始时间,结束时间,可用次数,可用于订阅,券码,生成时间\r\n";
foreach ($coupons as $coupon) {
$type = ['', '金额', '比例'][$coupon['type']];
$value = ['', ($coupon['value'] / 100), $coupon['value']][$coupon['type']];
$startTime = date('Y-m-d H:i:s', $coupon['started_at']);
$endTime = date('Y-m-d H:i:s', $coupon['ended_at']);
$limitUse = $coupon['limit_use'] ?? '不限制';
$createTime = date('Y-m-d H:i:s', $coupon['created_at']);
$limitPlanIds = isset($coupon['limit_plan_ids']) ? implode("/", $coupon['limit_plan_ids']) : '不限制';
$data .= "{$coupon['name']},{$type},{$value},{$startTime},{$endTime},{$limitUse},{$limitPlanIds},{$coupon['code']},{$createTime}\r\n";
}
echo $data;
}
public function drop(Request $request)
{
$request->validate([
'id' => 'required|numeric'
], [
'id.required' => '优惠券ID不能为空',
'id.numeric' => '优惠券ID必须为数字'
]);
$coupon = Coupon::find($request->input('id'));
if (!$coupon) {
return $this->fail([400202, '优惠券不存在']);
}
if (!$coupon->delete()) {
return $this->fail([500, '删除失败']);
}
return $this->success(true);
}
}
@@ -0,0 +1,35 @@
<?php
namespace App\Http\Controllers\V2\Admin;
use App\Http\Controllers\Controller;
use App\Services\CustomerService\Settings;
use Illuminate\Http\Request;
use Illuminate\Validation\ValidationException;
class CustomerServiceController extends Controller
{
public function fetch(Settings $settings) { return $this->success($settings->all()); }
public function save(Request $request, Settings $settings) {
$data=$request->validate([
'enabled'=>'required|boolean','base_url'=>'present|nullable|url:http,https|max:255',
'website_token'=>'present|nullable|string|max:255', 'working_hours'=>'present|nullable|string|max:200',
'offline_title'=>'required|string|max:100','offline_message'=>'required|string|max:500',
'ticket_url'=>'required|string|max:500','telegram_enabled'=>'required|boolean',
'telegram_bot_code'=>'required|regex:/^[a-z0-9_-]+$/|max:64',
'telegram_target_code'=>'required|regex:/^[a-z0-9_-]+$/|max:64',
]);
$data['base_url']=rtrim($data['base_url']??'', '/');
$data['website_token']=$data['website_token']??'';
$data['working_hours']=$data['working_hours']??'';
if ($data['enabled'] && (!$data['base_url'] || !$data['website_token'])) {
throw ValidationException::withMessages(['enabled'=>'启用客服需要服务地址和网站标识']);
}
$parts=parse_url($data['base_url']);
if ($data['base_url'] && (!$parts || isset($parts['user']) || isset($parts['pass']) || isset($parts['query']) || isset($parts['fragment']) || !empty($parts['path']))) {
throw ValidationException::withMessages(['base_url'=>'请填写不带路径或认证信息的服务源地址']);
}
if (!str_starts_with($data['ticket_url'],'/') || str_starts_with($data['ticket_url'],'//') || preg_match('/[\\\\\x00-\x20]/',$data['ticket_url'])) {
throw ValidationException::withMessages(['ticket_url'=>'工单入口必须是本站绝对路径']);
}
admin_setting(['customer_service'=>$data]);
return $this->success($settings->all());
}
}
@@ -0,0 +1,622 @@
<?php
namespace App\Http\Controllers\V2\Admin;
use App\Http\Controllers\Controller;
use App\Models\GiftCardCode;
use App\Models\GiftCardTemplate;
use App\Models\GiftCardUsage;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Validation\Rule;
use Illuminate\Support\Facades\DB;
class GiftCardController extends Controller
{
/**
* 获取礼品卡模板列表
*/
public function templates(Request $request)
{
$request->validate([
'type' => 'integer|min:1|max:10',
'status' => 'integer|in:0,1',
'page' => 'integer|min:1',
'per_page' => 'integer|min:1|max:1000',
]);
$query = GiftCardTemplate::query();
if ($request->has('type')) {
$query->where('type', $request->input('type'));
}
if ($request->has('status')) {
$query->where('status', $request->input('status'));
}
$perPage = $request->input('per_page', 15);
$templates = $query->orderBy('sort', 'asc')
->orderBy('created_at', 'desc')
->paginate($perPage);
$data = $templates->getCollection()->map(function ($template) {
return [
'id' => $template->id,
'name' => $template->name,
'description' => $template->description,
'type' => $template->type,
'type_name' => $template->type_name,
'status' => $template->status,
'conditions' => $template->conditions,
'rewards' => $template->rewards,
'limits' => $template->limits,
'special_config' => $template->special_config,
'icon' => $template->icon,
'background_image' => $template->background_image,
'theme_color' => $template->theme_color,
'sort' => $template->sort,
'admin_id' => $template->admin_id,
'created_at' => $template->created_at,
'updated_at' => $template->updated_at,
// 统计信息
'codes_count' => $template->codes()->count(),
'used_count' => $template->usages()->count(),
];
})->values();
return $this->paginate( $templates);
}
/**
* 创建礼品卡模板
*/
public function createTemplate(Request $request)
{
$request->validate([
'name' => 'required|string|max:255',
'description' => 'nullable|string',
'type' => [
'required',
'integer',
Rule::in(array_keys(GiftCardTemplate::getTypeMap()))
],
'status' => 'boolean',
'conditions' => 'nullable|array',
'rewards' => 'required|array',
'limits' => 'nullable|array',
'special_config' => 'nullable|array',
'icon' => 'nullable|string|max:255',
'background_image' => 'nullable|string|url|max:255',
'theme_color' => 'nullable|string|regex:/^#[0-9A-Fa-f]{6}$/',
'sort' => 'integer|min:0',
], [
'name.required' => '礼品卡名称不能为空',
'type.required' => '礼品卡类型不能为空',
'type.in' => '无效的礼品卡类型',
'rewards.required' => '奖励配置不能为空',
'theme_color.regex' => '主题色格式不正确',
'background_image.url' => '背景图片必须是有效的URL',
]);
try {
$template = GiftCardTemplate::create([
'name' => $request->input('name'),
'description' => $request->input('description'),
'type' => $request->input('type'),
'status' => $request->input('status', true),
'conditions' => $request->input('conditions'),
'rewards' => $request->input('rewards'),
'limits' => $request->input('limits'),
'special_config' => $request->input('special_config'),
'icon' => $request->input('icon'),
'background_image' => $request->input('background_image'),
'theme_color' => $request->input('theme_color', '#1890ff'),
'sort' => $request->input('sort', 0),
'admin_id' => $request->user()->id,
'created_at' => time(),
'updated_at' => time(),
]);
return $this->success($template);
} catch (\Exception $e) {
Log::error('创建礼品卡模板失败', [
'admin_id' => $request->user()->id,
'data' => $request->all(),
'error' => $e->getMessage(),
]);
return $this->fail([500, '创建失败']);
}
}
/**
* 更新礼品卡模板
*/
public function updateTemplate(Request $request)
{
$validatedData = $request->validate([
'id' => 'required|integer|exists:v2_gift_card_template,id',
'name' => 'sometimes|required|string|max:255',
'description' => 'sometimes|nullable|string',
'type' => [
'sometimes',
'required',
'integer',
Rule::in(array_keys(GiftCardTemplate::getTypeMap()))
],
'status' => 'sometimes|boolean',
'conditions' => 'sometimes|nullable|array',
'rewards' => 'sometimes|required|array',
'limits' => 'sometimes|nullable|array',
'special_config' => 'sometimes|nullable|array',
'icon' => 'sometimes|nullable|string|max:255',
'background_image' => 'sometimes|nullable|string|url|max:255',
'theme_color' => 'sometimes|nullable|string|regex:/^#[0-9A-Fa-f]{6}$/',
'sort' => 'sometimes|integer|min:0',
]);
$template = GiftCardTemplate::find($validatedData['id']);
if (!$template) {
return $this->fail([404, '模板不存在']);
}
try {
$updateData = collect($validatedData)->except('id')->all();
if (empty($updateData)) {
return $this->success($template);
}
$updateData['updated_at'] = time();
$template->update($updateData);
return $this->success($template->fresh());
} catch (\Exception $e) {
Log::error('更新礼品卡模板失败', [
'admin_id' => $request->user()->id,
'template_id' => $template->id,
'error' => $e->getMessage(),
]);
return $this->fail([500, '更新失败']);
}
}
/**
* 删除礼品卡模板
*/
public function deleteTemplate(Request $request)
{
$request->validate([
'id' => 'required|integer|exists:v2_gift_card_template,id',
]);
$template = GiftCardTemplate::find($request->input('id'));
if (!$template) {
return $this->fail([404, '模板不存在']);
}
// 检查是否有关联的兑换码
if ($template->codes()->exists()) {
return $this->fail([400, '该模板下存在兑换码,无法删除']);
}
try {
$template->delete();
return $this->success(true);
} catch (\Exception $e) {
Log::error('删除礼品卡模板失败', [
'admin_id' => $request->user()->id,
'template_id' => $template->id,
'error' => $e->getMessage(),
]);
return $this->fail([500, '删除失败']);
}
}
/**
* 生成兑换码
*/
public function generateCodes(Request $request)
{
$request->validate([
'template_id' => 'required|integer|exists:v2_gift_card_template,id',
'count' => 'required|integer|min:1|max:10000',
'prefix' => 'nullable|string|max:10|regex:/^[A-Z0-9]*$/',
'expires_hours' => 'nullable|integer|min:1',
'max_usage' => 'integer|min:1|max:1000',
], [
'template_id.required' => '请选择礼品卡模板',
'count.required' => '请指定生成数量',
'count.max' => '单次最多生成10000个兑换码',
'prefix.regex' => '前缀只能包含大写字母和数字',
]);
$template = GiftCardTemplate::find($request->input('template_id'));
if (!$template->isAvailable()) {
return $this->fail([400, '模板已被禁用']);
}
try {
$options = [
'prefix' => $request->input('prefix', 'GC'),
'max_usage' => $request->input('max_usage', 1),
];
if ($request->has('expires_hours')) {
$options['expires_at'] = time() + ($request->input('expires_hours') * 3600);
}
$batchId = GiftCardCode::batchGenerate(
$request->input('template_id'),
$request->input('count'),
$options
);
// 查询本次生成的所有兑换码
$codes = GiftCardCode::where('batch_id', $batchId)->get();
// 判断是否导出 CSV
if ($request->input('download_csv')) {
$headers = [
'Content-Type' => 'text/csv',
'Content-Disposition' => 'attachment; filename="gift_codes.csv"',
];
$callback = function () use ($codes, $template) {
$handle = fopen('php://output', 'w');
// 表头
fputcsv($handle, [
'兑换码',
'前缀',
'有效期',
'最大使用次数',
'批次号',
'创建时间',
'模板名称',
'模板类型',
'模板奖励',
'状态',
'使用者',
'使用时间',
'备注'
]);
foreach ($codes as $code) {
$expireDate = $code->expires_at ? date('Y-m-d H:i:s', $code->expires_at) : '长期有效';
$createDate = date('Y-m-d H:i:s', $code->created_at);
$templateName = $template->name ?? '';
$templateType = $template->type ?? '';
$templateRewards = $template->rewards ? json_encode($template->rewards, JSON_UNESCAPED_UNICODE) : '';
// 状态判断
$status = $code->status_name;
$usedBy = $code->user_id ?? '';
$usedAt = $code->used_at ? date('Y-m-d H:i:s', $code->used_at) : '';
$remark = $code->remark ?? '';
fputcsv($handle, [
$code->code,
$code->prefix ?? '',
$expireDate,
$code->max_usage,
$code->batch_id,
$createDate,
$templateName,
$templateType,
$templateRewards,
$status,
$usedBy,
$usedAt,
$remark,
]);
}
fclose($handle);
};
return response()->streamDownload($callback, 'gift_codes.csv', $headers);
}
Log::info('批量生成兑换码', [
'admin_id' => $request->user()->id,
'template_id' => $request->input('template_id'),
'count' => $request->input('count'),
'batch_id' => $batchId,
]);
return $this->success([
'batch_id' => $batchId,
'count' => $request->input('count'),
'message' => '生成成功',
]);
} catch (\Exception $e) {
Log::error('生成兑换码失败', [
'admin_id' => $request->user()->id,
'data' => $request->all(),
'error' => $e->getMessage(),
]);
return $this->fail([500, '生成失败']);
}
}
/**
* 获取兑换码列表
*/
public function codes(Request $request)
{
$request->validate([
'template_id' => 'integer|exists:v2_gift_card_template,id',
'batch_id' => 'string',
'status' => 'integer|in:0,1,2,3',
'page' => 'integer|min:1',
'per_page' => 'integer|min:1|max:500',
]);
$query = GiftCardCode::with(['template', 'user']);
if ($request->has('template_id')) {
$query->where('template_id', $request->input('template_id'));
}
if ($request->has('batch_id')) {
$query->where('batch_id', $request->input('batch_id'));
}
if ($request->has('status')) {
$query->where('status', $request->input('status'));
}
$perPage = $request->input('per_page', 15);
$codes = $query->orderBy('created_at', 'desc')->paginate($perPage);
$data = $codes->getCollection()->map(function ($code) {
return [
'id' => $code->id,
'template_id' => $code->template_id,
'template_name' => $code->template->name ?? '',
'code' => $code->code,
'batch_id' => $code->batch_id,
'status' => $code->status,
'status_name' => $code->status_name,
'user_id' => $code->user_id,
'user_email' => $code->user ? (substr($code->user->email ?? '', 0, 3) . '***@***') : null,
'used_at' => $code->used_at,
'expires_at' => $code->expires_at,
'usage_count' => $code->usage_count,
'max_usage' => $code->max_usage,
'created_at' => $code->created_at,
];
})->values();
return $this->paginate($codes);
}
/**
* 禁用/启用兑换码
*/
public function toggleCode(Request $request)
{
$request->validate([
'id' => 'required|integer|exists:v2_gift_card_code,id',
'action' => 'required|string|in:disable,enable',
]);
$code = GiftCardCode::find($request->input('id'));
if (!$code) {
return $this->fail([404, '兑换码不存在']);
}
try {
if ($request->input('action') === 'disable') {
$code->markAsDisabled();
} else {
if ($code->status === GiftCardCode::STATUS_DISABLED) {
$code->status = GiftCardCode::STATUS_UNUSED;
$code->save();
}
}
return $this->success([
'message' => $request->input('action') === 'disable' ? '已禁用' : '已启用',
]);
} catch (\Exception $e) {
return $this->fail([500, '操作失败']);
}
}
/**
* 导出兑换码
*/
public function exportCodes(Request $request)
{
$request->validate([
'batch_id' => 'required|string|exists:v2_gift_card_code,batch_id',
]);
$codes = GiftCardCode::where('batch_id', $request->input('batch_id'))
->orderBy('created_at', 'asc')
->get(['code']);
$content = $codes->pluck('code')->implode("\n");
return response($content)
->header('Content-Type', 'text/plain')
->header('Content-Disposition', 'attachment; filename="gift_cards_' . $request->input('batch_id') . '.txt"');
}
/**
* 获取使用记录
*/
public function usages(Request $request)
{
$request->validate([
'template_id' => 'integer|exists:v2_gift_card_template,id',
'user_id' => 'integer|exists:v2_user,id',
'page' => 'integer|min:1',
'per_page' => 'integer|min:1|max:500',
]);
$query = GiftCardUsage::with(['template', 'code', 'user', 'inviteUser']);
if ($request->has('template_id')) {
$query->where('template_id', $request->input('template_id'));
}
if ($request->has('user_id')) {
$query->where('user_id', $request->input('user_id'));
}
$perPage = $request->input('per_page', 15);
$usages = $query->orderBy('created_at', 'desc')->paginate($perPage);
$usages->transform(function ($usage) {
return [
'id' => $usage->id,
'code' => $usage->code->code ?? '',
'template_name' => $usage->template->name ?? '',
'user_email' => $usage->user->email ?? '',
'invite_user_email' => $usage->inviteUser ? (substr($usage->inviteUser->email ?? '', 0, 3) . '***@***') : null,
'rewards_given' => $usage->rewards_given,
'invite_rewards' => $usage->invite_rewards,
'multiplier_applied' => $usage->multiplier_applied,
'created_at' => $usage->created_at,
];
})->values();
return $this->paginate($usages);
}
/**
* 获取统计数据
*/
public function statistics(Request $request)
{
$request->validate([
'start_date' => 'date_format:Y-m-d',
'end_date' => 'date_format:Y-m-d',
]);
$startDate = $request->input('start_date', date('Y-m-d', strtotime('-30 days')));
$endDate = $request->input('end_date', date('Y-m-d'));
// 总体统计
$totalStats = [
'templates_count' => GiftCardTemplate::count(),
'active_templates_count' => GiftCardTemplate::where('status', 1)->count(),
'codes_count' => GiftCardCode::count(),
'used_codes_count' => GiftCardCode::where('status', GiftCardCode::STATUS_USED)->count(),
'usages_count' => GiftCardUsage::count(),
];
// 每日使用统计
$driver = DB::connection()->getDriverName();
$dateExpression = "date(created_at, 'unixepoch')"; // Default for SQLite
if ($driver === 'mysql') {
$dateExpression = 'DATE(FROM_UNIXTIME(created_at))';
} elseif ($driver === 'pgsql') {
$dateExpression = 'date(to_timestamp(created_at))';
}
$dailyUsages = GiftCardUsage::selectRaw("{$dateExpression} as date, COUNT(*) as count")
->whereRaw("{$dateExpression} BETWEEN ? AND ?", [$startDate, $endDate])
->groupBy('date')
->orderBy('date')
->get();
// 类型统计
$typeStats = GiftCardUsage::with('template')
->selectRaw('template_id, COUNT(*) as count')
->groupBy('template_id')
->get()
->map(function ($item) {
return [
'template_name' => $item->template->name ?? '',
'type_name' => $item->template->type_name ?? '',
'count' => $item->count ?? 0,
];
});
return $this->success([
'total_stats' => $totalStats,
'daily_usages' => $dailyUsages,
'type_stats' => $typeStats,
]);
}
/**
* 获取所有可用的礼品卡类型
*/
public function types()
{
return $this->success(GiftCardTemplate::getTypeMap());
}
/**
* 更新单个兑换码
*/
public function updateCode(Request $request)
{
$validatedData = $request->validate([
'id' => 'required|integer|exists:v2_gift_card_code,id',
'expires_at' => 'sometimes|nullable|integer',
'max_usage' => 'sometimes|integer|min:1|max:1000',
'status' => 'sometimes|integer|in:0,1,2,3',
]);
$code = GiftCardCode::find($validatedData['id']);
if (!$code) {
return $this->fail([404, '礼品卡不存在']);
}
try {
$updateData = collect($validatedData)->except('id')->all();
if (empty($updateData)) {
return $this->success($code);
}
$updateData['updated_at'] = time();
$code->update($updateData);
return $this->success($code->fresh());
} catch (\Exception $e) {
Log::error('更新礼品卡信息失败', [
'admin_id' => $request->user()->id,
'code_id' => $code->id,
'error' => $e->getMessage(),
]);
return $this->fail([500, '更新失败']);
}
}
/**
* 删除礼品卡
*/
public function deleteCode(Request $request)
{
$request->validate([
'id' => 'required|integer|exists:v2_gift_card_code,id',
]);
$code = GiftCardCode::find($request->input('id'));
if (!$code) {
return $this->fail([404, '礼品卡不存在']);
}
// 检查是否已被使用
if ($code->status === GiftCardCode::STATUS_USED) {
return $this->fail([400, '该礼品卡已被使用,无法删除']);
}
try {
// 检查是否有关联的使用记录
if ($code->usages()->exists()) {
return $this->fail([400, '该礼品卡存在使用记录,无法删除']);
}
$code->delete();
return $this->success(['message' => '删除成功']);
} catch (\Exception $e) {
Log::error('删除礼品卡失败', [
'admin_id' => $request->user()->id,
'code_id' => $code->id,
'error' => $e->getMessage(),
]);
return $this->fail([500, '删除失败']);
}
}
}
@@ -0,0 +1,113 @@
<?php
namespace App\Http\Controllers\V2\Admin;
use App\Exceptions\ApiException;
use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\KnowledgeSave;
use App\Http\Requests\Admin\KnowledgeSort;
use App\Models\Knowledge;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class KnowledgeController extends Controller
{
public function fetch(Request $request)
{
if ($request->input('id')) {
$knowledge = Knowledge::find($request->input('id'))->toArray();
if (!$knowledge)
return $this->fail([400202, '知识不存在']);
return $this->success($knowledge);
}
$data = Knowledge::select(['title', 'id', 'updated_at', 'category', 'show'])
->orderBy('sort', 'ASC')
->get();
return $this->success($data);
}
public function getCategory(Request $request)
{
return $this->success(array_keys(Knowledge::get()->groupBy('category')->toArray()));
}
public function save(KnowledgeSave $request)
{
$params = $request->validated();
if (!$request->input('id')) {
if (!Knowledge::create($params)) {
return $this->fail([500, '创建失败']);
}
} else {
try {
Knowledge::find($request->input('id'))->update($params);
} catch (\Exception $e) {
\Log::error($e);
return $this->fail([500, '创建失败']);
}
}
return $this->success(true);
}
public function show(Request $request)
{
$request->validate([
'id' => 'required|numeric'
], [
'id.required' => '知识库ID不能为空'
]);
$knowledge = Knowledge::find($request->input('id'));
if (!$knowledge) {
throw new ApiException('知识不存在');
}
$knowledge->show = !$knowledge->show;
if (!$knowledge->save()) {
throw new ApiException('保存失败');
}
return $this->success(true);
}
public function sort(Request $request)
{
$request->validate([
'ids' => 'required|array'
], [
'ids.required' => '参数有误',
'ids.array' => '参数有误'
]);
try {
DB::beginTransaction();
foreach ($request->input('ids') as $k => $v) {
$knowledge = Knowledge::find($v);
$knowledge->timestamps = false;
$knowledge->update(['sort' => $k + 1]);
}
DB::commit();
} catch (\Exception $e) {
DB::rollBack();
throw new ApiException('保存失败');
}
return $this->success(true);
}
public function drop(Request $request)
{
$request->validate([
'id' => 'required|numeric'
], [
'id.required' => '知识库ID不能为空'
]);
$knowledge = Knowledge::find($request->input('id'));
if (!$knowledge) {
return $this->fail([400202, '知识不存在']);
}
if (!$knowledge->delete()) {
return $this->fail([500, '删除失败']);
}
return $this->success(true);
}
}
@@ -0,0 +1,34 @@
<?php
namespace App\Http\Controllers\V2\Admin;
use App\Http\Controllers\Controller;
use App\Models\MailDailyReport;
use App\Models\MailMessage;
use App\Models\MailQuotaBucket;
use App\Services\MailFlow\Settings;
use Illuminate\Support\Facades\Schema;
class MailFlowController extends Controller
{
public function incoming(\Illuminate\Http\Request $request)
{
$data = $request->validate(['id' => 'required|integer|min:1']);
$message = MailMessage::where('direction', 'in')->findOrFail($data['id']);
return $this->success(['email' => $message->email, 'subject' => $message->subject, 'text' => $message->payload['text'] ?? '']);
}
public function status()
{
$ready = Schema::hasTable('v2_mail_messages') && Schema::hasTable('v2_mail_quota_buckets') && Schema::hasTable('v2_mail_daily_reports');
return $this->success([
'automatic_mail_level' => \App\Services\MailFlow\AutomaticMailPolicy::state()['level'] ?? null,
'settings' => Settings::publicSettings(), 'database_ready' => $ready,
'imap_available' => function_exists('imap_open'),
'quota' => $ready ? MailQuotaBucket::where('resets_at', '>', now())->get() : [],
'messages' => $ready ? MailMessage::whereIn('direction', ['in', 'out'])->latest('id')->limit(50)
->get(['id', 'direction', 'purpose', 'channel', 'email', 'status', 'error_code', 'fallback_reason', 'created_at']) : [],
'reports' => $ready ? MailDailyReport::latest('id')->limit(7)->get() : [],
]);
}
}
@@ -0,0 +1,270 @@
<?php
namespace App\Http\Controllers\V2\Admin;
use App\Http\Controllers\Controller;
use App\Models\MailTemplate;
use App\Services\MailService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
class MailTemplateController extends Controller
{
public function list()
{
$dbTemplates = MailTemplate::all()->keyBy('name');
$result = [];
foreach (MailTemplate::TEMPLATES as $name => $meta) {
$db = $dbTemplates->get($name);
$result[] = [
'name' => $name,
'label' => $meta['label'],
'customized' => $db !== null,
'subject' => $db?->subject,
'updated_at' => $db?->updated_at?->timestamp,
];
}
return $this->success($result);
}
public function get(Request $request)
{
$name = $request->input('name');
$meta = MailTemplate::getMeta($name);
if (!$meta) {
return $this->fail([404, '模板不存在']);
}
$db = MailTemplate::where('name', $name)->first();
return $this->success([
'name' => $name,
'label' => $meta['label'],
'required_vars' => $meta['required_vars'],
'optional_vars' => $meta['optional_vars'],
'customized' => $db !== null,
'subject' => $db?->subject ?? $this->getDefaultSubject($name),
'content' => $db?->content ?? $this->getDefaultContent($name),
]);
}
public function save(Request $request)
{
$params = $request->validate([
'name' => 'required|string',
'subject' => 'required|string|max:255',
'content' => 'required|string',
]);
$meta = MailTemplate::getMeta($params['name']);
if (!$meta) {
return $this->fail([404, '模板不存在']);
}
$errors = MailTemplate::validateContent($params['name'], $params['content']);
if (!empty($errors)) {
return $this->fail([422, implode('; ', $errors)]);
}
MailTemplate::updateOrCreate(
['name' => $params['name']],
['subject' => $params['subject'], 'content' => $params['content']]
);
Cache::forget("mail_template:{$params['name']}");
return $this->success(true);
}
public function reset(Request $request)
{
$name = $request->input('name');
$meta = MailTemplate::getMeta($name);
if (!$meta) {
return $this->fail([404, '模板不存在']);
}
MailTemplate::where('name', $name)->delete();
Cache::forget("mail_template:{$name}");
return $this->success(true);
}
public function test(Request $request)
{
$name = $request->input('name');
$meta = MailTemplate::getMeta($name);
if (!$meta) {
return $this->fail([404, '模板不存在']);
}
$email = $request->input('email', $request->user()->email);
$testVars = $this->getTestVars($name);
try {
$log = MailService::sendEmail([
'email' => $email,
'subject' => $this->getTestSubject($name),
'template_name' => $name,
'purpose' => 'admin_test',
'template_value' => $testVars,
]);
if ($log['error']) {
return $this->fail([500, '发送失败: ' . $log['error']]);
}
return $this->success(true);
} catch (\Exception $e) {
Log::error($e);
return $this->fail([500, '发送失败: ' . $e->getMessage()]);
}
}
private function getTestSubject(string $name): string
{
$appName = admin_setting('app_name', 'XBoard');
return match ($name) {
'verify' => "{$appName} - 验证码测试",
'notify' => "{$appName} - 通知测试",
'remindExpire' => "{$appName} - 到期提醒测试",
'serviceExpired' => "{$appName} - 套餐已到期测试",
'remindTraffic' => "{$appName} - 流量提醒测试",
'mailLogin' => "{$appName} - 登录链接测试",
default => "{$appName} - 邮件测试",
};
}
private function getTestVars(string $name): array
{
$appName = admin_setting('app_name', 'XBoard');
$appUrl = admin_setting('app_url', 'https://example.com');
return match ($name) {
'verify' => [
'name' => $appName,
'code' => '123456',
'url' => $appUrl,
],
'notify' => [
'name' => $appName,
'content' => '这是一封测试通知邮件。',
'url' => $appUrl,
],
'remindExpire' => [
'name' => $appName,
'url' => $appUrl,
],
'remindTraffic' => [
'name' => $appName,
'url' => $appUrl,
],
'mailLogin' => [
'name' => $appName,
'link' => $appUrl . '/login?token=test-token',
'url' => $appUrl,
],
default => ['name' => $appName, 'url' => $appUrl],
};
}
private function getDefaultSubject(string $name): string
{
$appName = admin_setting('app_name', 'XBoard');
return match ($name) {
'verify' => "{$appName} - 邮箱验证码",
'notify' => "{$appName} - 站点通知",
'remindExpire' => "{$appName} - 服务即将到期",
'serviceExpired' => "{$appName} - 套餐已到期",
'remindTraffic' => "{$appName} - 流量使用提醒",
'mailLogin' => "{$appName} - 邮件登录",
default => "{$appName}",
};
}
private function getDefaultContent(string $name): string
{
$theme = 'default';
$viewName = "mail.{$theme}.{$name}";
try {
$viewPath = resource_path("views/mail/{$theme}/{$name}.blade.php");
if (file_exists($viewPath)) {
$blade = file_get_contents($viewPath);
return self::bladeToPlaceholder($blade);
}
} catch (\Throwable $e) {
// ignore
}
return self::hardcodedDefault($name);
}
/**
* Convert Blade syntax to {{placeholder}} syntax for editing.
*/
private static function bladeToPlaceholder(string $blade): string
{
// {{$var}} → {{var}}
$result = preg_replace('/\{\{\s*\$([a-zA-Z_]+)\s*\}\}/', '{{$1}}', $blade);
// {!! nl2br($var) !!} → {{var}}
$result = preg_replace('/\{!!\s*nl2br\(\$([a-zA-Z_]+)\)\s*!!\}/', '{{$1}}', $result);
// {!! $var !!} → {{var}}
$result = preg_replace('/\{!!\s*\$([a-zA-Z_]+)\s*!!\}/', '{{$1}}', $result);
return $result;
}
private static function hardcodedDefault(string $name): string
{
$layout = fn($title, $body) => <<<HTML
<div style="background: #eee">
<table width="600" border="0" align="center" cellpadding="0" cellspacing="0">
<tbody>
<tr>
<td>
<div style="background:#fff">
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<thead>
<tr>
<td valign="middle" style="padding-left:30px;background-color:#415A94;color:#fff;padding:20px 40px;font-size: 21px;">{{name}}</td>
</tr>
</thead>
<tbody>
<tr style="padding:40px 40px 0 40px;display:table-cell">
<td style="font-size:24px;line-height:1.5;color:#000;margin-top:40px">{$title}</td>
</tr>
<tr>
<td style="font-size:14px;color:#333;padding:24px 40px 0 40px">
尊敬的用户您好!<br /><br />{$body}
</td>
</tr>
</tbody>
</table>
</div>
<div>
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td style="padding:20px 40px;font-size:12px;color:#999;line-height:20px;background:#f7f7f7"><a href="{{url}}" style="font-size:14px;color:#929292">返回{{name}}</a></td>
</tr>
</tbody>
</table>
</div>
</td>
</tr>
</tbody>
</table>
</div>
HTML;
return match ($name) {
'verify' => $layout('邮箱验证码', '您的验证码是:{{code}},请在 5 分钟内进行验证。如果该验证码不为您本人申请,请无视。'),
'notify' => $layout('网站通知', '{{content}}'),
'remindExpire' => $layout('服务到期提醒', '您的服务即将在24小时内到期,如需继续使用请及时续费。'),
'serviceExpired' => $layout('套餐已到期', '您的套餐已到期。如需继续使用,请登录网站续费。'),
'remindTraffic' => $layout('流量使用提醒', '您的流量使用已达到80%,请注意流量使用情况。'),
'mailLogin' => $layout('登入到{{name}}', '您正在登入到{{name}}, 请在 5 分钟内点击下方链接进行登入。如果您未授权该登入请求,请无视。<a href="{{link}}">{{link}}</a>'),
default => $layout('通知', '{{content}}'),
};
}
}
@@ -0,0 +1,101 @@
<?php
namespace App\Http\Controllers\V2\Admin;
use App\Exceptions\ApiException;
use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\NoticeSave;
use App\Models\Notice;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class NoticeController extends Controller
{
public function fetch(Request $request)
{
return $this->success(
Notice::orderBy('sort', 'ASC')
->orderBy('id', 'DESC')
->get()
);
}
public function save(NoticeSave $request)
{
$data = $request->only([
'title',
'content',
'img_url',
'tags',
'show',
'popup'
]);
if (!$request->input('id')) {
if (!Notice::create($data)) {
return $this->fail([500, '保存失败']);
}
} else {
try {
Notice::find($request->input('id'))->update($data);
} catch (\Exception $e) {
return $this->fail([500, '保存失败']);
}
}
return $this->success(true);
}
public function show(Request $request)
{
if (empty($request->input('id'))) {
return $this->fail([500, '公告ID不能为空']);
}
$notice = Notice::find($request->input('id'));
if (!$notice) {
return $this->fail([400202, '公告不存在']);
}
$notice->show = $notice->show ? 0 : 1;
if (!$notice->save()) {
return $this->fail([500, '保存失败']);
}
return $this->success(true);
}
public function drop(Request $request)
{
if (empty($request->input('id'))) {
return $this->fail([422, '公告ID不能为空']);
}
$notice = Notice::find($request->input('id'));
if (!$notice) {
return $this->fail([400202, '公告不存在']);
}
if (!$notice->delete()) {
return $this->fail([500, '删除失败']);
}
return $this->success(true);
}
public function sort(Request $request)
{
$params = $request->validate([
'ids' => 'required|array'
]);
try {
DB::beginTransaction();
foreach ($params['ids'] as $k => $v) {
$notice = Notice::findOrFail($v);
$notice->update(['sort' => $k + 1]);
}
DB::commit();
return $this->success(true);
} catch (\Exception $e) {
DB::rollBack();
\Log::error($e);
return $this->fail([500, '排序保存失败']);
}
}
}
@@ -0,0 +1,252 @@
<?php
namespace App\Http\Controllers\V2\Admin;
use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\OrderAssign;
use App\Http\Requests\Admin\OrderUpdate;
use App\Models\Order;
use App\Models\Plan;
use App\Models\User;
use App\Services\OrderService;
use App\Services\PlanService;
use App\Services\UserService;
use App\Utils\Helper;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\Log;
class OrderController extends Controller
{
public function detail(Request $request)
{
$order = Order::with(['user', 'plan', 'commission_log', 'invite_user'])->find($request->input('id'));
if (!$order)
return $this->fail([400202, '订单不存在']);
if ($order->surplus_order_ids) {
$order['surplus_orders'] = Order::whereIn('id', $order->surplus_order_ids)->get();
}
$order['period'] = PlanService::getLegacyPeriod((string) $order->period);
return $this->success($order);
}
public function fetch(Request $request)
{
$current = $request->input('current', 1);
$pageSize = $request->input('pageSize', 10);
$orderModel = Order::with('plan:id,name');
if ($request->boolean('is_commission')) {
$orderModel->whereNotNull('invite_user_id')
->whereNotIn('status', [0, 2])
->where('commission_balance', '>', 0);
}
$this->applyFiltersAndSorts($request, $orderModel);
/** @var \Illuminate\Pagination\LengthAwarePaginator $paginatedResults */
$paginatedResults = $orderModel
->latest('created_at')
->paginate(
perPage: $pageSize,
page: $current
);
$paginatedResults->getCollection()->transform(function ($order) {
$orderArray = $order->toArray();
$orderArray['period'] = PlanService::getLegacyPeriod((string) $order->period);
return $orderArray;
});
return $this->paginate($paginatedResults);
}
private function applyFiltersAndSorts(Request $request, Builder $builder): void
{
$this->applyFilters($request, $builder);
$this->applySorting($request, $builder);
}
private function applyFilters(Request $request, Builder $builder): void
{
if (!$request->has('filter')) {
return;
}
collect($request->input('filter'))->each(function ($filter) use ($builder) {
$field = $filter['id'];
$value = $filter['value'];
$builder->where(function ($query) use ($field, $value) {
$this->buildFilterQuery($query, $field, $value);
});
});
}
private function buildFilterQuery(Builder $query, string $field, mixed $value): void
{
// Handle array values for 'in' operations
if (is_array($value)) {
$query->whereIn($field, $value);
return;
}
// Handle operator-based filtering
if (!is_string($value) || !str_contains($value, ':')) {
$query->where($field, 'like', "%{$value}%");
return;
}
[$operator, $filterValue] = explode(':', $value, 2);
// Convert numeric strings to appropriate type
if (is_numeric($filterValue)) {
$filterValue = strpos($filterValue, '.') !== false
? (float) $filterValue
: (int) $filterValue;
}
// Apply operator
$query->where($field, match (strtolower($operator)) {
'eq' => '=',
'gt' => '>',
'gte' => '>=',
'lt' => '<',
'lte' => '<=',
'like' => 'like',
'notlike' => 'not like',
'null' => static fn($q) => $q->whereNull($field),
'notnull' => static fn($q) => $q->whereNotNull($field),
default => 'like'
}, match (strtolower($operator)) {
'like', 'notlike' => "%{$filterValue}%",
'null', 'notnull' => null,
default => $filterValue
});
}
private function applySorting(Request $request, Builder $builder): void
{
if (!$request->has('sort')) {
return;
}
collect($request->input('sort'))->each(function ($sort) use ($builder) {
$field = $sort['id'];
$direction = $sort['desc'] ? 'DESC' : 'ASC';
$builder->orderBy($field, $direction);
});
}
public function paid(Request $request)
{
$order = Order::where('trade_no', $request->input('trade_no'))
->first();
if (!$order) {
return $this->fail([400202, '订单不存在']);
}
if ($order->status !== 0)
return $this->fail([400, '只能对待支付的订单进行操作']);
$orderService = new OrderService($order);
if (!$orderService->paid('manual_operation')) {
return $this->fail([500, '更新失败']);
}
return $this->success(true);
}
public function cancel(Request $request)
{
$order = Order::where('trade_no', $request->input('trade_no'))
->first();
if (!$order) {
return $this->fail([400202, '订单不存在']);
}
if ($order->status !== 0)
return $this->fail([400, '只能对待支付的订单进行操作']);
$orderService = new OrderService($order);
if (!$orderService->cancel()) {
return $this->fail([400, '更新失败']);
}
return $this->success(true);
}
public function update(OrderUpdate $request)
{
$params = $request->only([
'commission_status'
]);
$order = Order::where('trade_no', $request->input('trade_no'))
->first();
if (!$order) {
return $this->fail([400202, '订单不存在']);
}
try {
$order->update($params);
} catch (\Exception $e) {
Log::error($e);
return $this->fail([500, '更新失败']);
}
return $this->success(true);
}
public function assign(OrderAssign $request)
{
$plan = Plan::find($request->input('plan_id'));
$user = User::byEmail($request->input('email'))->first();
if (!$user) {
return $this->fail([400202, '该用户不存在']);
}
if (!$plan) {
return $this->fail([400202, '该订阅不存在']);
}
$userService = new UserService();
if ($userService->isNotCompleteOrderByUserId($user->id)) {
return $this->fail([400, '该用户还有待支付的订单,无法分配']);
}
try {
DB::beginTransaction();
$order = new Order();
$orderService = new OrderService($order);
$order->user_id = $user->id;
$order->plan_id = $plan->id;
$period = $request->input('period');
$order->period = PlanService::getPeriodKey((string) $period);
$order->trade_no = Helper::guid();
$order->total_amount = $request->input('total_amount');
if (PlanService::getPeriodKey((string) $order->period) === Plan::PERIOD_RESET_TRAFFIC) {
$order->type = Order::TYPE_RESET_TRAFFIC;
} else if ($user->plan_id !== NULL && $order->plan_id !== $user->plan_id) {
$order->type = Order::TYPE_UPGRADE;
} else if ($user->expired_at > time() && $order->plan_id == $user->plan_id) {
$order->type = Order::TYPE_RENEWAL;
} else {
$order->type = Order::TYPE_NEW_PURCHASE;
}
$orderService->setInvite($user);
if (!$order->save()) {
DB::rollBack();
return $this->fail([500, '订单创建失败']);
}
DB::commit();
} catch (\Exception $e) {
DB::rollBack();
throw $e;
}
return $this->success($order->trade_no);
}
}
@@ -0,0 +1,133 @@
<?php
namespace App\Http\Controllers\V2\Admin;
use App\Exceptions\ApiException;
use App\Http\Controllers\Controller;
use App\Models\Payment;
use App\Services\PaymentService;
use App\Utils\Helper;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
class PaymentController extends Controller
{
public function getPaymentMethods()
{
$methods = [];
$pluginMethods = PaymentService::getAllPaymentMethodNames();
$methods = array_merge($methods, $pluginMethods);
return $this->success(array_unique($methods));
}
public function fetch()
{
$payments = Payment::orderBy('sort', 'ASC')->get()->makeVisible('config');
foreach ($payments as $k => $v) {
$notifyUrl = url("/api/v1/guest/payment/notify/{$v->payment}/{$v->uuid}");
if ($v->notify_domain) {
$parseUrl = parse_url($notifyUrl);
$notifyUrl = $v->notify_domain . $parseUrl['path'];
}
$payments[$k]['notify_url'] = $notifyUrl;
}
return $this->success($payments);
}
public function getPaymentForm(Request $request)
{
try {
$paymentService = new PaymentService($request->input('payment'), $request->input('id'));
return $this->success(collect($paymentService->form()));
} catch (\Exception $e) {
return $this->fail([400, '支付方式不存在或未启用']);
}
}
public function show(Request $request)
{
$payment = Payment::find($request->input('id'));
if (!$payment)
return $this->fail([400202, '支付方式不存在']);
$payment->enable = !$payment->enable;
if (!$payment->save())
return $this->fail([500, '保存失败']);
return $this->success(true);
}
public function save(Request $request)
{
if (!admin_setting('app_url')) {
return $this->fail([400, '请在站点配置中配置站点地址']);
}
$params = $request->validate([
'name' => 'required',
'icon' => 'nullable',
'payment' => 'required',
'config' => 'required',
'notify_domain' => 'nullable|url',
'handling_fee_fixed' => 'nullable|integer',
'handling_fee_percent' => 'nullable|numeric|between:0,100'
], [
'name.required' => '显示名称不能为空',
'payment.required' => '网关参数不能为空',
'config.required' => '配置参数不能为空',
'notify_domain.url' => '自定义通知域名格式有误',
'handling_fee_fixed.integer' => '固定手续费格式有误',
'handling_fee_percent.between' => '百分比手续费范围须在0-100之间'
]);
if ($request->input('id')) {
$payment = Payment::find($request->input('id'));
if (!$payment)
return $this->fail([400202, '支付方式不存在']);
try {
$payment->update($params);
} catch (\Exception $e) {
Log::error($e);
return $this->fail([500, '保存失败']);
}
return $this->success(true);
}
$params['uuid'] = Helper::randomChar(8);
if (!Payment::create($params)) {
return $this->fail([500, '保存失败']);
}
return $this->success(true);
}
public function drop(Request $request)
{
$payment = Payment::find($request->input('id'));
if (!$payment)
return $this->fail([400202, '支付方式不存在']);
return $this->success($payment->delete());
}
public function sort(Request $request)
{
$request->validate([
'ids' => 'required|array'
], [
'ids.required' => '参数有误',
'ids.array' => '参数有误'
]);
try {
DB::beginTransaction();
foreach ($request->input('ids') as $k => $v) {
if (!Payment::find($v)->update(['sort' => $k + 1])) {
throw new \Exception();
}
}
DB::commit();
} catch (\Exception $e) {
DB::rollBack();
return $this->fail([500, '保存失败']);
}
return $this->success(true);
}
}
@@ -0,0 +1,137 @@
<?php
namespace App\Http\Controllers\V2\Admin;
use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\PlanSave;
use App\Models\Order;
use App\Models\Plan;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
class PlanController extends Controller
{
public function fetch(Request $request)
{
$plans = Plan::orderBy('sort', 'ASC')
->with([
'group:id,name'
])
->withCount([
'users',
'users as active_users_count' => function ($query) {
$query->where(function ($q) {
$q->where('expired_at', '>', time())
->orWhereNull('expired_at');
});
}
])
->get();
return $this->success($plans);
}
public function save(PlanSave $request)
{
$params = $request->validated();
if ($request->input('id')) {
$plan = Plan::find($request->input('id'));
if (!$plan) {
return $this->fail([400202, '该订阅不存在']);
}
DB::beginTransaction();
try {
if ($request->input('force_update')) {
User::where('plan_id', $plan->id)->update([
'group_id' => $params['group_id'],
'transfer_enable' => $params['transfer_enable'] * 1073741824,
'speed_limit' => $params['speed_limit'],
'device_limit' => $params['device_limit'],
]);
}
$plan->update($params);
DB::commit();
return $this->success(true);
} catch (\Exception $e) {
DB::rollBack();
Log::error($e);
return $this->fail([500, '保存失败']);
}
}
if (!Plan::create($params)) {
return $this->fail([500, '创建失败']);
}
return $this->success(true);
}
public function drop(Request $request)
{
if (Order::where('plan_id', $request->input('id'))->first()) {
return $this->fail([400201, '该订阅下存在订单无法删除']);
}
if (User::where('plan_id', $request->input('id'))->first()) {
return $this->fail([400201, '该订阅下存在用户无法删除']);
}
$plan = Plan::find($request->input('id'));
if (!$plan) {
return $this->fail([400202, '该订阅不存在']);
}
return $this->success($plan->delete());
}
public function update(Request $request)
{
$updateData = $request->only([
'show',
'renew',
'sell',
'display_device_limit'
]);
$plan = Plan::find($request->input('id'));
if (!$plan) {
return $this->fail([400202, '该订阅不存在']);
}
$request->validate([
'display_device_limit' => 'sometimes|nullable|integer|min:0|max:4294967295',
]);
try {
$plan->update($updateData);
} catch (\Exception $e) {
Log::error($e);
return $this->fail([500, '保存失败']);
}
return $this->success(true);
}
public function sort(Request $request)
{
$params = $request->validate([
'ids' => 'required|array'
]);
try {
DB::beginTransaction();
foreach ($params['ids'] as $k => $v) {
if (!Plan::find($v)->update(['sort' => $k + 1])) {
throw new \Exception();
}
}
DB::commit();
} catch (\Exception $e) {
DB::rollBack();
Log::error($e);
return $this->fail([500, '保存失败']);
}
return $this->success(true);
}
}
@@ -0,0 +1,346 @@
<?php
namespace App\Http\Controllers\V2\Admin;
use App\Http\Controllers\Controller;
use App\Models\Plugin;
use App\Services\Plugin\PluginManager;
use App\Services\Plugin\PluginConfigService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Str;
class PluginController extends Controller
{
protected PluginManager $pluginManager;
protected PluginConfigService $configService;
public function __construct(
PluginManager $pluginManager,
PluginConfigService $configService
) {
$this->pluginManager = $pluginManager;
$this->configService = $configService;
}
/**
* 获取所有插件类型
*/
public function types()
{
return response()->json([
'data' => [
[
'value' => Plugin::TYPE_FEATURE,
'label' => '功能',
'description' => '提供功能扩展的插件,如Telegram登录、邮件通知等',
'icon' => '🔧'
],
[
'value' => Plugin::TYPE_PAYMENT,
'label' => '支付方式',
'description' => '提供支付接口的插件,如支付宝、微信支付等',
'icon' => '💳'
]
]
]);
}
/**
* 获取插件列表
*/
public function index(Request $request)
{
$type = $request->query('type');
$installedPlugins = Plugin::when($type, function ($query) use ($type) {
return $query->byType($type);
})
->get()
->keyBy('code')
->toArray();
$plugins = [];
$seenCodes = [];
foreach ($this->pluginManager->getPluginPaths() as $pluginPath) {
if (!File::exists($pluginPath)) {
continue;
}
$directories = File::directories($pluginPath);
foreach ($directories as $directory) {
$configFile = $directory . '/config.json';
if (!File::exists($configFile)) {
continue;
}
$config = json_decode(File::get($configFile), true);
if (!$config || !isset($config['code'])) {
continue;
}
$code = $config['code'];
if (isset($seenCodes[$code])) {
continue;
}
$seenCodes[$code] = true;
$pluginType = $config['type'] ?? Plugin::TYPE_FEATURE;
if ($type && $pluginType !== $type) {
continue;
}
$installed = isset($installedPlugins[$code]);
$pluginConfig = $installed ? $this->configService->getConfig($code) : ($config['config'] ?? []);
$readmeFile = collect(['README.md', 'readme.md'])
->map(fn($f) => $directory . '/' . $f)
->first(fn($path) => File::exists($path));
$readmeContent = $readmeFile ? File::get($readmeFile) : '';
$needUpgrade = false;
if ($installed) {
$installedVersion = $installedPlugins[$code]['version'] ?? null;
$localVersion = $config['version'] ?? null;
if ($installedVersion && $localVersion && version_compare($localVersion, $installedVersion, '>')) {
$needUpgrade = true;
}
}
$isCore = $this->pluginManager->isCorePlugin($code);
$plugins[] = [
'code' => $config['code'],
'name' => $config['name'],
'version' => $config['version'],
'description' => $config['description'],
'author' => $config['author'],
'type' => $pluginType,
'is_installed' => $installed,
'is_enabled' => $installed ? $installedPlugins[$code]['is_enabled'] : false,
'is_protected' => $isCore,
'can_be_deleted' => !$isCore,
'config' => $pluginConfig,
'readme' => $readmeContent,
'need_upgrade' => $needUpgrade,
'admin_menus' => $config['admin_menus'] ?? null,
'admin_crud' => $config['admin_crud'] ?? null,
];
}
}
return response()->json([
'data' => $plugins
]);
}
/**
* 安装插件
*/
public function install(Request $request)
{
$request->validate([
'code' => 'required|string'
]);
try {
$this->pluginManager->install($request->input('code'));
return response()->json([
'message' => '插件安装成功'
]);
} catch (\Exception $e) {
return response()->json([
'message' => '插件安装失败:' . $e->getMessage()
], 400);
}
}
/**
* 卸载插件
*/
public function uninstall(Request $request)
{
$request->validate([
'code' => 'required|string'
]);
$code = $request->input('code');
$plugin = Plugin::where('code', $code)->first();
if ($plugin && $plugin->is_enabled) {
return response()->json([
'message' => '请先禁用插件后再卸载'
], 400);
}
try {
$this->pluginManager->uninstall($code);
return response()->json([
'message' => '插件卸载成功'
]);
} catch (\Exception $e) {
return response()->json([
'message' => '插件卸载失败:' . $e->getMessage()
], 400);
}
}
/**
* 升级插件
*/
public function upgrade(Request $request)
{
$request->validate([
'code' => 'required|string',
]);
try {
$this->pluginManager->update($request->input('code'));
return response()->json([
'message' => '插件升级成功'
]);
} catch (\Exception $e) {
return response()->json([
'message' => '插件升级失败:' . $e->getMessage()
], 400);
}
}
/**
* 启用插件
*/
public function enable(Request $request)
{
$request->validate([
'code' => 'required|string'
]);
try {
$this->pluginManager->enable($request->input('code'));
return response()->json([
'message' => '插件启用成功'
]);
} catch (\Exception $e) {
return response()->json([
'message' => '插件启用失败:' . $e->getMessage()
], 400);
}
}
/**
* 禁用插件
*/
public function disable(Request $request)
{
$request->validate([
'code' => 'required|string'
]);
$this->pluginManager->disable($request->input('code'));
return response()->json([
'message' => '插件禁用成功'
]);
}
/**
* 获取插件配置
*/
public function getConfig(Request $request)
{
$request->validate([
'code' => 'required|string'
]);
try {
$config = $this->configService->getConfig($request->input('code'));
return response()->json([
'data' => $config
]);
} catch (\Exception $e) {
return response()->json([
'message' => '获取配置失败:' . $e->getMessage()
], 400);
}
}
/**
* 更新插件配置
*/
public function updateConfig(Request $request)
{
$request->validate([
'code' => 'required|string',
'config' => 'required|array'
]);
try {
$this->configService->updateConfig(
$request->input('code'),
$request->input('config')
);
return response()->json([
'message' => '配置更新成功'
]);
} catch (\Exception $e) {
return response()->json([
'message' => '配置更新失败:' . $e->getMessage()
], 400);
}
}
/**
* 上传插件
*/
public function upload(Request $request)
{
$request->validate([
'file' => [
'required',
'file',
'mimes:zip',
'max:10240', // 最大10MB
]
], [
'file.required' => '请选择插件包文件',
'file.file' => '无效的文件类型',
'file.mimes' => '插件包必须是zip格式',
'file.max' => '插件包大小不能超过10MB'
]);
try {
$this->pluginManager->upload($request->file('file'));
return response()->json([
'message' => '插件上传成功'
]);
} catch (\Exception $e) {
return response()->json([
'message' => '插件上传失败:' . $e->getMessage()
], 400);
}
}
/**
* 删除插件
*/
public function delete(Request $request)
{
$request->validate([
'code' => 'required|string'
]);
$code = $request->input('code');
// 检查是否为核心插件
if ($this->pluginManager->isCorePlugin($code)) {
return response()->json([
'message' => '该插件为系统核心插件,不允许删除'
], 403);
}
try {
$this->pluginManager->delete($code);
return response()->json([
'message' => '插件删除成功'
]);
} catch (\Exception $e) {
return response()->json([
'message' => '插件删除失败:' . $e->getMessage()
], 400);
}
}
}
@@ -0,0 +1,66 @@
<?php
namespace App\Http\Controllers\V2\Admin\Server;
use App\Http\Controllers\Controller;
use App\Models\Plan;
use App\Models\Server;
use App\Models\ServerGroup;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
class GroupController extends Controller
{
public function fetch(Request $request): JsonResponse
{
$serverGroups = ServerGroup::query()
->orderByDesc('id')
->withCount('users')
->get();
// 只在需要时手动加载server_count
$serverGroups->each(function ($group) {
$group->setAttribute('server_count', $group->server_count);
});
return $this->success($serverGroups);
}
public function save(Request $request)
{
if (empty($request->input('name'))) {
return $this->fail([422, '组名不能为空']);
}
if ($request->input('id')) {
$serverGroup = ServerGroup::find($request->input('id'));
} else {
$serverGroup = new ServerGroup();
}
$serverGroup->name = $request->input('name');
return $this->success($serverGroup->save());
}
public function drop(Request $request)
{
$groupId = $request->input('id');
$serverGroup = ServerGroup::find($groupId);
if (!$serverGroup) {
return $this->fail([400202, '组不存在']);
}
if (Server::whereJsonContains('group_ids', $groupId)->exists()) {
return $this->fail([400, '该组已被节点所使用,无法删除']);
}
if (Plan::where('group_id', $groupId)->exists()) {
return $this->fail([400, '该组已被订阅所使用,无法删除']);
}
if (User::where('group_id', $groupId)->exists()) {
return $this->fail([400, '该组已被用户所使用,无法删除']);
}
return $this->success($serverGroup->delete());
}
}
@@ -0,0 +1,215 @@
<?php
namespace App\Http\Controllers\V2\Admin\Server;
use App\Exceptions\ApiException;
use App\Http\Controllers\Controller;
use App\Models\Server;
use App\Models\ServerMachine;
use App\Models\ServerMachineLoadHistory;
use App\Services\NodeSyncService;
use Illuminate\Http\Request;
class MachineController extends Controller
{
/**
* 获取机器列表(附带关联节点数)
*/
public function fetch(Request $request)
{
$machines = ServerMachine::withCount('servers')
->orderBy('id')
->get()
->map(function (ServerMachine $machine) {
return [
'id' => $machine->id,
'name' => $machine->name,
'notes' => $machine->notes,
'is_active' => $machine->is_active,
'last_seen_at' => $machine->last_seen_at,
'load_status' => $machine->load_status,
'servers_count' => $machine->servers_count,
'created_at' => $machine->created_at,
'updated_at' => $machine->updated_at,
];
});
return $this->success($machines);
}
/**
* 创建 / 更新机器
*/
public function save(Request $request)
{
$params = $request->validate([
'id' => 'nullable|integer|exists:v2_server_machine,id',
'name' => 'required|string|max:255',
'notes' => 'nullable|string',
'is_active' => 'nullable|boolean',
]);
if (!empty($params['id'])) {
$machine = ServerMachine::find($params['id']);
$update = ['name' => $params['name']];
if (array_key_exists('notes', $params)) {
$update['notes'] = $params['notes'];
}
if (array_key_exists('is_active', $params)) {
$update['is_active'] = $params['is_active'];
}
$machine->update($update);
return $this->success(true);
}
$machine = ServerMachine::create([
'name' => $params['name'],
'notes' => $params['notes'] ?? null,
'is_active' => $params['is_active'] ?? true,
'token' => ServerMachine::generateToken(),
]);
return $this->success([
'id' => $machine->id,
'token' => $machine->token,
'install_command' => $this->buildInstallCommand($request, $machine),
]);
}
/**
* 重置机器 Token
*/
public function resetToken(Request $request)
{
$params = $request->validate([
'id' => 'required|integer|exists:v2_server_machine,id',
]);
$machine = ServerMachine::find($params['id']);
$token = ServerMachine::generateToken();
$machine->update(['token' => $token]);
return $this->success(['token' => $token]);
}
/**
* 获取机器 Token(仅展示一次,用于首次配置)
*/
public function getToken(Request $request)
{
$params = $request->validate([
'id' => 'required|integer|exists:v2_server_machine,id',
]);
$machine = ServerMachine::find($params['id']);
return $this->success(['token' => $machine->token]);
}
/**
* 获取机器模式一键安装命令
*/
public function installCommand(Request $request)
{
$params = $request->validate([
'id' => 'required|integer|exists:v2_server_machine,id',
]);
$machine = ServerMachine::find($params['id']);
return $this->success([
'command' => $this->buildInstallCommand($request, $machine),
]);
}
/**
* 删除机器(自动解除关联节点)
*/
public function drop(Request $request)
{
$params = $request->validate([
'id' => 'required|integer|exists:v2_server_machine,id',
]);
$machine = ServerMachine::find($params['id']);
$machineId = $machine->id;
// Detach nodes first (sets machine_id = null), then delete and notify
Server::where('machine_id', $machineId)->update(['machine_id' => null]);
$machine->delete();
// Notify with empty node list so WS process cleans up registry
NodeSyncService::notifyMachineNodesChanged($machineId);
return $this->success(true);
}
/**
* 获取机器下的节点列表
*/
public function nodes(Request $request)
{
$params = $request->validate([
'machine_id' => 'required|integer|exists:v2_server_machine,id',
]);
$nodes = Server::where('machine_id', $params['machine_id'])
->orderBy('sort')
->get(['id', 'name', 'type', 'host', 'port', 'show', 'enabled', 'sort']);
return $this->success($nodes);
}
/**
* 获取机器负载历史
*/
public function history(Request $request)
{
$params = $request->validate([
'machine_id' => 'required|integer|exists:v2_server_machine,id',
'limit' => 'nullable|integer|min:10|max:1440',
'range_hours' => 'nullable|integer|min:1|max:24',
]);
$query = ServerMachineLoadHistory::query()
->where('machine_id', $params['machine_id']);
if (!empty($params['range_hours'])) {
$query->where('recorded_at', '>=', now()->subHours((int) $params['range_hours'])->timestamp);
}
$limit = (int) ($params['limit'] ?? 60);
$history = $query
->orderByDesc('recorded_at')
->limit($limit)
->get([
'cpu',
'mem_total',
'mem_used',
'disk_total',
'disk_used',
'net_in_speed',
'net_out_speed',
'recorded_at',
])
->reverse()
->values();
return $this->success($history);
}
private function buildInstallCommand(Request $request, ServerMachine $machine): string
{
$panelUrl = rtrim((string) (admin_setting('app_url') ?: $request->getSchemeAndHttpHost()), '/');
$installerUrl = 'https://raw.githubusercontent.com/cedar2025/xboard-node/dev/install.sh';
return sprintf(
'curl -fsSL %s | sudo bash -s -- --mode machine --panel %s --token %s --machine-id %d',
$installerUrl,
escapeshellarg($panelUrl),
escapeshellarg($machine->token),
$machine->id
);
}
}
@@ -0,0 +1,341 @@
<?php
namespace App\Http\Controllers\V2\Admin\Server;
use App\Exceptions\ApiException;
use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\ServerSave;
use App\Models\Server;
use App\Models\ServerGroup;
use App\Services\ServerService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
class ManageController extends Controller
{
public function getNodes(Request $request)
{
$servers = ServerService::getAllServers()->map(function ($item) {
$item['groups'] = ServerGroup::whereIn('id', $item['group_ids'] ?? [])->get(['name', 'id']);
$item['parent'] = $item->parent;
return $item;
});
return $this->success($servers);
}
public function sort(Request $request)
{
ini_set('post_max_size', '1m');
$params = $request->validate([
'*.id' => 'numeric',
'*.order' => 'numeric'
]);
try {
DB::beginTransaction();
collect($params)->each(function ($item) {
if (isset($item['id']) && isset($item['order'])) {
Server::where('id', $item['id'])->update(['sort' => $item['order']]);
}
});
DB::commit();
} catch (\Exception $e) {
DB::rollBack();
Log::error($e);
return $this->fail([500, '保存失败']);
}
return $this->success(true);
}
public function save(ServerSave $request)
{
$params = $request->validated();
if ($request->input('id')) {
$server = Server::find($request->input('id'));
if (!$server) {
return $this->fail([400202, '服务器不存在']);
}
try {
$server->update($params);
return $this->success(true);
} catch (\Exception $e) {
Log::error($e);
return $this->fail([500, '保存失败']);
}
}
try {
Server::create($params);
return $this->success(true);
} catch (\Exception $e) {
Log::error($e);
return $this->fail([500, '创建失败']);
}
}
public function update(Request $request)
{
$params = $request->validate([
'id' => 'required|integer',
'show' => 'nullable|integer',
'machine_id' => 'nullable|integer',
'enabled' => 'nullable|boolean',
]);
$server = Server::find($request->id);
if (!$server) {
return $this->fail([400202, '服务器不存在']);
}
if (array_key_exists('show', $params)) {
$server->show = (int) $params['show'];
}
if (array_key_exists('machine_id', $params)) {
$server->machine_id = $params['machine_id'] ?: null;
}
if (array_key_exists('enabled', $params)) {
$server->enabled = (bool) $params['enabled'];
}
if (!$server->save()) {
return $this->fail([500, '保存失败']);
}
return $this->success(true);
}
/**
* 删除
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\JsonResponse
*/
public function drop(Request $request)
{
$request->validate([
'id' => 'required|integer',
]);
$server = Server::find($request->id);
if (!$server) {
return $this->fail([400202, '服务器不存在']);
}
if ($server->delete() === false) {
return $this->fail([500, '删除失败']);
}
return $this->success(true);
}
/**
* 批量删除节点
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\JsonResponse
*/
public function batchDelete(Request $request)
{
$request->validate([
'ids' => 'required|array',
'ids.*' => 'integer',
]);
$ids = $request->input('ids');
if (empty($ids)) {
return $this->fail([400, '请选择要删除的节点']);
}
try {
$deleted = Server::whereIn('id', $ids)->delete();
if ($deleted === false) {
return $this->fail([500, '批量删除失败']);
}
return $this->success(true);
} catch (\Exception $e) {
Log::error($e);
return $this->fail([500, '批量删除失败']);
}
}
/**
* 重置节点流量
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\JsonResponse
*/
public function resetTraffic(Request $request)
{
$request->validate([
'id' => 'required|integer',
]);
$server = Server::find($request->id);
if (!$server) {
return $this->fail([400202, '服务器不存在']);
}
try {
$server->u = 0;
$server->d = 0;
$server->save();
Log::info("Server {$server->id} ({$server->name}) traffic reset by admin");
return $this->success(true);
} catch (\Exception $e) {
Log::error($e);
return $this->fail([500, '重置失败']);
}
}
/**
* 批量重置节点流量
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\JsonResponse
*/
public function batchResetTraffic(Request $request)
{
$request->validate([
'ids' => 'required|array',
'ids.*' => 'integer',
]);
$ids = $request->input('ids');
if (empty($ids)) {
return $this->fail([400, '请选择要重置的节点']);
}
try {
Server::whereIn('id', $ids)->update([
'u' => 0,
'd' => 0,
]);
Log::info("Servers " . implode(',', $ids) . " traffic reset by admin");
return $this->success(true);
} catch (\Exception $e) {
Log::error($e);
return $this->fail([500, '批量重置失败']);
}
}
/**
* 批量更新节点属性(show等)
*/
public function batchUpdate(Request $request)
{
$params = $request->validate([
'ids' => 'required|array',
'ids.*' => 'integer',
'show' => 'nullable|integer|in:0,1',
'enabled' => 'nullable|boolean',
'machine_id' => 'nullable|integer',
]);
$ids = $params['ids'];
if (empty($ids)) {
return $this->fail([400, '请选择要更新的节点']);
}
$update = [];
if (array_key_exists('show', $params) && $params['show'] !== null) {
$update['show'] = (int) $params['show'];
}
if (array_key_exists('enabled', $params) && $params['enabled'] !== null) {
$update['enabled'] = (bool) $params['enabled'];
}
if (array_key_exists('machine_id', $params)) {
$update['machine_id'] = $params['machine_id'] ?: null;
}
if (empty($update)) {
return $this->fail([400, '没有可更新的字段']);
}
try {
$servers = Server::whereIn('id', $ids)->get();
DB::transaction(function () use ($servers, $update) {
/** @var Server $server */
foreach ($servers as $server) {
$server->update($update);
}
});
return $this->success(true);
} catch (\Exception $e) {
Log::error($e);
return $this->fail([500, '批量更新失败']);
}
}
/**
* 复制节点
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\JsonResponse
*/
public function copy(Request $request)
{
$server = Server::find($request->input('id'));
if (!$server) {
return $this->fail([400202, '服务器不存在']);
}
$copiedServer = $server->replicate();
$copiedServer->show = 0;
$copiedServer->code = null;
$copiedServer->u = 0;
$copiedServer->d = 0;
$copiedServer->save();
return $this->success(true);
}
/**
* Generate ECH (Encrypted Client Hello) key pair.
* Returns PEM-encoded ECH key (server-side) and ECH config (client-side).
*/
public function generateEchKey(Request $request)
{
$publicName = $request->input('public_name', 'ech.example.com');
if (strlen($publicName) < 1 || strlen($publicName) > 253) {
throw new ApiException('public_name must be a valid domain (1-253 bytes)');
}
// Generate X25519 key pair
$privateKey = random_bytes(32);
$publicKey = sodium_crypto_scalarmult_base($privateKey);
$configId = random_int(0, 255);
// Build ECHConfigContents (draft-ietf-tls-esni-18)
$contents = '';
$contents .= pack('C', $configId); // config_id
$contents .= pack('n', 0x0020); // kem_id: DHKEM(X25519)
$contents .= pack('n', 32) . $publicKey; // public_key (length-prefixed)
// cipher_suites: 2 suites × 4 bytes = 8 bytes
$contents .= pack('n', 8); // cipher_suites byte length
$contents .= pack('nn', 0x0001, 0x0001); // HKDF-SHA256 + AES-128-GCM
$contents .= pack('nn', 0x0001, 0x0003); // HKDF-SHA256 + ChaCha20Poly1305
$contents .= pack('C', 0); // max_name_length
$contents .= pack('C', strlen($publicName)) . $publicName;
$contents .= pack('n', 0); // extensions: empty
// ECHConfig = version(2) + length(2) + contents
$echConfig = pack('n', 0xfe0d) . pack('n', strlen($contents)) . $contents;
// ECHConfigList = total_length(2) + configs
$echConfigList = pack('n', strlen($echConfig)) . $echConfig;
// ECH Keys = private_key_len(2) + key(32) + config_len(2) + config
$echKeysPayload = pack('n', 32) . $privateKey . pack('n', strlen($echConfig)) . $echConfig;
$keyPem = "-----BEGIN ECH KEYS-----\n"
. chunk_split(base64_encode($echKeysPayload), 64, "\n")
. "-----END ECH KEYS-----";
$configPem = "-----BEGIN ECH CONFIGS-----\n"
. chunk_split(base64_encode($echConfigList), 64, "\n")
. "-----END ECH CONFIGS-----";
return $this->success([
'key' => $keyPem,
'config' => $configPem,
]);
}
}
@@ -0,0 +1,64 @@
<?php
namespace App\Http\Controllers\V2\Admin\Server;
use App\Exceptions\ApiException;
use App\Http\Controllers\Controller;
use App\Models\ServerRoute;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
class RouteController extends Controller
{
public function fetch(Request $request)
{
$routes = ServerRoute::get();
return [
'data' => $routes
];
}
public function save(Request $request)
{
$params = $request->validate([
'remarks' => 'required',
'match' => 'required|array',
'action' => 'required|in:block,direct,dns,proxy',
'action_value' => 'nullable'
], [
'remarks.required' => '备注不能为空',
'match.required' => '匹配值不能为空',
'action.required' => '动作类型不能为空',
'action.in' => '动作类型参数有误'
]);
$params['match'] = array_filter($params['match']);
// TODO: remove on 1.8.0
if ($request->input('id')) {
try {
$route = ServerRoute::find($request->input('id'));
$route->update($params);
return $this->success(true);
} catch (\Exception $e) {
Log::error($e);
return $this->fail([500,'保存失败']);
}
}
try{
ServerRoute::create($params);
return $this->success(true);
}catch(\Exception $e){
Log::error($e);
return $this->fail([500,'创建失败']);
}
}
public function drop(Request $request)
{
$route = ServerRoute::find($request->input('id'));
if (!$route) throw new ApiException('路由不存在');
if (!$route->delete()) throw new ApiException('删除失败');
return [
'data' => true
];
}
}
Loaded 100 of 1883 files, more files were not shown because too many files have changed in this diff. Show more