173 Commits
v1b15 ... v1

Author SHA1 Message Date
Masu Baumgartner
39a1bdeb5d Merge pull request #373 from Moonlight-Panel/v1_FixWingsContentLenght
Fix Content-Lenght for wings
2024-04-01 12:46:30 +02:00
Masu Baumgartner
18f107e485 A possible hotfix 2024-04-01 10:45:01 +00:00
Masu Baumgartner
b56b94041f Update README.md 2024-03-04 11:02:32 +01:00
Marcel Baumgartner
1a3b339983 Merge pull request #369 from NaysKutzu/patch-1
Update README.md
2024-02-09 14:22:39 +01:00
NaysKutzu
106af71c17 Update README.md
Update the logo because it won't be displayed due to your captcha on the page
2024-02-09 14:20:46 +01:00
Marcel Baumgartner
cb1da9f5cd Removed old license 2024-02-06 21:38:33 +01:00
Marcel Baumgartner
743b0b1c1b Updated license 2024-02-06 21:37:32 +01:00
Marcel Baumgartner
8fe695f0cf Merge pull request #367 from gOOvER/issuetemplates
added issue templates
2024-02-03 09:09:09 +01:00
Marcel Baumgartner
344ea046f2 Merge pull request #366 from gOOvER/dependabot
added dependabot.yml to autocheck action updates
2024-02-03 09:08:57 +01:00
Marcel Baumgartner
73a014500d Merge pull request #365 from gOOvER/updateworkflow
update workflow files to latest releases
2024-02-03 09:08:38 +01:00
gOOvER
d3f8ba5434 added issue templates 2024-02-03 08:44:05 +01:00
gOOvER
c068679f9b added dependabot.yml to autocheck action updates 2024-02-03 08:27:36 +01:00
gOOvER
9dfba1e6c4 update workflow files to latest releases 2024-02-03 08:24:07 +01:00
Marcel Baumgartner
27f9ca551c Create FUNDING.yml 2024-01-31 10:35:55 +01:00
Marcel Baumgartner
4d69e8bacb Merge pull request #361 from Dannyx1604/patch-1
Update README.md (grammar check)
2024-01-25 21:43:00 +01:00
Dannyx
ed2d33c69b Update README.md (grammar check) 2024-01-25 21:39:48 +01:00
Marcel Baumgartner
d880189f2b Hotfix for WingsServerConverter 2024-01-12 19:45:18 +01:00
Marcel Baumgartner
9221a66597 Merge pull request #324 from Moonlight-Panel/FixLetsEncrypt
Added additional logs for lets encrypt certificates
2023-10-13 23:02:45 +02:00
Marcel Baumgartner
e1c4f8a2a9 Added additional logs for lets encrypt certificates 2023-10-13 23:02:23 +02:00
Marcel Baumgartner
84d39c1c75 Merge pull request #318 from Moonlight-Panel/AddBotCheck
Implemented a basic bot check
2023-09-18 18:59:02 +02:00
Marcel Baumgartner
9abd9d86b2 Implemented a basic bot check 2023-09-18 18:58:32 +02:00
Marcel Baumgartner
73a07761f8 Merge pull request #317 from Moonlight-Panel/AddManualMalwareScan
Added manual malware scan
2023-09-12 10:50:29 +02:00
Marcel Baumgartner
ebe2d9d7ef Added manual malware scan 2023-09-12 08:49:12 +00:00
Marcel Baumgartner
48b12fde90 Merge pull request #316 from Moonlight-Panel/FixIpBinding
Fixed ip binding
2023-09-10 03:13:31 +02:00
Marcel Baumgartner
8ac4fae9c1 Fixed ip binding 2023-09-10 03:12:54 +02:00
Marcel Baumgartner
d224f1e1bb Merge pull request #315 from Moonlight-Panel/FixStartup
Fixed startup for new instances
2023-09-10 03:00:46 +02:00
Marcel Baumgartner
13131e6fca Fixed startup for new instances 2023-09-10 03:00:09 +02:00
Marcel Baumgartner
26fdfe112b Merge pull request #313 from Moonlight-Panel/FixProfileMenu
Fixed profile menu
2023-09-09 09:48:59 +02:00
Marcel Baumgartner
ecf0d372e5 Fixed profile menu 2023-09-09 09:47:44 +02:00
Marcel Baumgartner
e281cfadbd Fixed typo 2023-09-07 20:45:00 +02:00
Marcel Baumgartner
ae2228e08a Added release build. Modified canary build events 2023-09-07 20:09:04 +02:00
Marcel Baumgartner
3f5a7504fa Merge branch 'main' of https://github.com/Moonlight-Panel/Moonlight 2023-09-07 18:14:26 +02:00
Marcel Baumgartner
f8af48aeab Added canary build action. Not tested yet 2023-09-07 18:14:22 +02:00
Marcel Baumgartner
9b9656892d Update README.md 2023-09-06 20:18:16 +02:00
Marcel Baumgartner
db2c6ec30d Merge pull request #311 from Moonlight-Panel/FixAuthDesign
Fixed login and register oauth2 view
2023-09-06 20:06:08 +02:00
Marcel Baumgartner
e46122b030 Fixed login and register oauth2 view 2023-09-06 20:05:38 +02:00
Marcel Baumgartner
1a9836a884 Merge pull request #309 from Moritz-Deiaco/main
added a 'moonlight worth' scrollbar
2023-09-06 19:58:34 +02:00
Marcel Baumgartner
ef930400c8 Fixed issues with other scrollbars 2023-09-06 19:58:12 +02:00
Moritz
450a954b9d Merge branch 'Moonlight-Panel:main' into main 2023-09-06 19:51:07 +02:00
Moritz
31ba5f04cc somechanges for uwu 2023-09-06 19:48:38 +02:00
Moritz
6ca024d6cb made the corners squared like masuwu wanted 2023-09-06 19:33:39 +02:00
Marcel Baumgartner
cef5cb11cb Merge pull request #310 from Moonlight-Panel/NewStartup
Switched to new startup
2023-09-06 19:26:31 +02:00
Marcel Baumgartner
e91a9b2239 Switched to new startup 2023-09-06 19:25:01 +02:00
Moritz
d7ca9d1fe6 added a 'moonlight worth' scrollbar 2023-09-06 19:14:09 +02:00
Marcel Baumgartner
564745b4a2 Merge pull request #308 from Moonlight-Panel/AddAutoLetsEncrypt
Added auto lets encrypt certificate issuing
2023-09-06 17:45:00 +02:00
Marcel Baumgartner
74361b7a4a Small changes 2023-09-06 17:40:56 +02:00
Marcel Baumgartner
7a992d71fb Merge pull request #305 from Moonlight-Panel/FixSharedDomain
Fixed shared domain loading
2023-09-06 17:19:51 +02:00
Marcel Baumgartner
b8d30f0380 Fixed shared domain loading 2023-09-06 17:19:32 +02:00
Marcel Baumgartner
07d7df8188 Merge pull request #304 from Moonlight-Panel/UpdateBadScriptFilter
Updated bad script filters
2023-09-06 17:08:22 +02:00
Marcel Baumgartner
2ddb8723af Updated bad script filters 2023-09-06 17:07:48 +02:00
Marcel Baumgartner
caf990dd4e Merge pull request #302 from Moonlight-Panel/FixHostRename
Fixed host file system rename
2023-09-06 15:43:53 +02:00
Marcel Baumgartner
d0401a1709 Fixed host file system rename 2023-09-06 13:42:48 +00:00
Marcel Baumgartner
67974123db Added some config files for codespaces. Modified for codespaces 2023-09-06 13:10:57 +00:00
Marcel Baumgartner
05817a8866 Added devcontainer for testing 2023-09-06 14:05:38 +02:00
Marcel Baumgartner
707776f1ed Merge pull request #301 from Moonlight-Panel/NewBadScriptScan
Added new bad script scan in order to find reduce scan time
2023-09-05 01:24:20 +02:00
Marcel Baumgartner
4ba7634b94 Added new bad script scan in order to find reduce scan time 2023-09-05 01:23:31 +02:00
Marcel Baumgartner
732abe53e0 Implemented a basic https certificate issuing using lets encrypt 2023-09-04 21:58:26 +02:00
Marcel Baumgartner
37b1288ae6 Update README.md 2023-09-04 21:24:04 +02:00
Marcel Baumgartner
dda302ebf1 Merge pull request #300 from Moonlight-Panel/SmallFixes
Fixed some small bugs
2023-08-31 01:29:12 +02:00
Marcel Baumgartner
f1aace98c3 Fixed some small bugs 2023-08-31 01:28:56 +02:00
Marcel Baumgartner
f48ec2245c Merge pull request #299 from Moonlight-Panel/AddNewScan
Added discord nuke bot scan
2023-08-31 01:03:24 +02:00
Marcel Baumgartner
37a3a35120 Added discord nuke bot scan 2023-08-31 01:01:15 +02:00
Marcel Baumgartner
c549d45d54 Merge pull request #298 from Moonlight-Panel/AddProxyScan
Added proxy scan
2023-08-30 16:21:46 +02:00
Marcel Baumgartner
42a011541c Added proxy scan 2023-08-30 16:20:57 +02:00
Marcel Baumgartner
71a8839f5f Merge pull request #297 from Moonlight-Panel/AddLiveStatistics
Add live statistics
2023-08-29 16:10:31 +02:00
Marcel Baumgartner
b99e8b5476 Merge branch 'main' into AddLiveStatistics 2023-08-29 16:10:16 +02:00
Marcel Baumgartner
5793bd9747 Added new live statistics to navigation 2023-08-29 16:07:43 +02:00
Marcel Baumgartner
24ce51a62e Merge pull request #296 from Moonlight-Panel/NewAdminDomainNavigation
Added new admin domain navigation
2023-08-29 15:55:46 +02:00
Marcel Baumgartner
762d3cc1a1 Added new admin domain navigation 2023-08-29 15:54:37 +02:00
Marcel Baumgartner
ea19105006 Fixed null server handling for the malware result event 2023-08-29 15:11:42 +02:00
Marcel Baumgartner
a372c756e4 Merge pull request #295 from Moonlight-Panel/AddIpFiltering
Implemented ip filtering to detect datacenter and vpn ips
2023-08-29 15:03:31 +02:00
Marcel Baumgartner
18b7c82613 Implemented ip filtering to detect datacenter and vpn ips 2023-08-29 15:03:07 +02:00
Marcel Baumgartner
5d91077d42 Updated MinerScan 2023-08-29 11:55:45 +02:00
Marcel Baumgartner
c0872d0d02 Fixed build errors caused by the removal of defaultstorage 2023-08-28 17:41:29 +02:00
Marcel Baumgartner
00722c4046 Merge pull request #294 from Moonlight-Panel/NewResourceSync
Switched to new resource sync
2023-08-28 17:33:37 +02:00
Marcel Baumgartner
f16a29dafb Switched to new resource sync 2023-08-28 17:32:34 +02:00
Marcel Baumgartner
6da8393612 Merge pull request #293 from Moonlight-Panel/SmallFixes
Some small fixes
2023-08-28 16:29:54 +02:00
Marcel Baumgartner
2ef00b81b8 Switched to new apex charts version 2023-08-28 16:27:59 +02:00
Marcel Baumgartner
0be4ebc7ff Small fix when starting a new malware scan 2023-08-28 16:20:24 +02:00
Marcel Baumgartner
e0d5e754b7 Merge pull request #292 from Moonlight-Panel/ImprovedMalwareScan
Improved malware scan. Added server and user purge
2023-08-28 05:09:10 +02:00
Marcel Baumgartner
6972c2bb32 Improved malware scan. Added server and user purge 2023-08-28 05:08:52 +02:00
Marcel Baumgartner
95ba81eab4 Merge pull request #291 from Moonlight-Panel/FixInitialInstallConsole
Fixed initial install console and added a better redirect handling when creating a server
2023-08-27 20:41:40 +02:00
Marcel Baumgartner
b9c094cafa Fixed initial install console and added a better redirect handling when creating a server 2023-08-27 20:40:58 +02:00
Marcel Baumgartner
bada1e829b Merge pull request #290 from Moonlight-Panel/ReduceExternalJs
Reduced external js, added libraries to assets
2023-08-27 17:29:57 +02:00
Marcel Baumgartner
1d33cf3110 Reduced external js, added libraries to assets 2023-08-27 17:29:37 +02:00
Marcel Baumgartner
abfcefba60 Merge pull request #286 from Moonlight-Panel/OwO
OwO
2023-08-23 17:42:48 +02:00
Marcel Baumgartner
6efb443481 Update launchSettings.json 2023-08-23 17:42:24 +02:00
Marcel Baumgartner
10c017932a Added a basic live statistics system 2023-08-23 17:29:34 +02:00
Marcel Baumgartner
a4be4bdc52 Merge pull request #285 from Moonlight-Panel/ImproveTotpSetup
Improved totp setup
2023-08-23 13:33:01 +02:00
Marcel Baumgartner
88d5a1de86 Improved totp setup 2023-08-23 13:32:23 +02:00
Marcel Baumgartner
1b88827d16 Merge pull request #284 from Moonlight-Panel/UserDiscordIdFilter
Added discord id filter
2023-08-23 13:23:52 +02:00
Marcel Baumgartner
12e25dc4bc Added discord id filter 2023-08-23 13:23:36 +02:00
Marcel Baumgartner
37c3fc7a53 Merge pull request #283 from Moonlight-Panel/ImproveFrontend
Improve frontend
2023-08-23 13:17:51 +02:00
Marcel Baumgartner
0c6cbe0ba7 Changed background image
Thanks to @nuhuhwy
2023-08-23 13:10:21 +02:00
Marcel Baumgartner
5cf63240a3 Removed the white mode and useless css 2023-08-23 13:06:04 +02:00
Marcel Baumgartner
4d04d12a39 Removed old js calls 2023-08-23 12:35:30 +02:00
Marcel Baumgartner
b846b28802 Reduced css and js which was not used 2023-08-23 11:20:52 +02:00
Marcel Baumgartner
b94217abc0 Merge pull request #277 from 1Pot2Nutella-p/FRlanguage
add french language
2023-08-17 18:44:21 +02:00
1Pot2Nutella-p
de0d6a3808 add frensh language 2023-08-16 20:56:49 +02:00
Marcel Baumgartner
eca9b6ec52 Merge pull request #275 from Moonlight-Panel/RedesignServerPage
Redesign server page
2023-08-15 22:10:39 +02:00
Marcel Baumgartner
b6e048e982 Added spacing to network tab 2023-08-15 22:07:47 +02:00
Marcel Baumgartner
b8b2ae7865 Merge pull request #274 from Moonlight-Panel/ImproveServerTabIconHandling
Improved server tab icon handling
2023-08-15 21:59:51 +02:00
Marcel Baumgartner
0611988019 Improved server tab icon handling 2023-08-15 21:59:35 +02:00
Marcel Baumgartner
f9fd7199b6 Merge pull request #273 from realspinelle/SomeUXFix
Set unsorted servers to open by default
2023-08-15 19:58:28 +02:00
realspinelle
6ff4861fc6 Set unsorted servers to open by default 2023-08-15 19:21:31 +02:00
Marcel Baumgartner
2db7748703 Merge pull request #272 from Moonlight-Panel/ImproveLatencyCheckThreshold
Improved latency check default threshould
2023-08-15 15:50:30 +02:00
Marcel Baumgartner
87744e4846 Improved latency check default threshould
As mentioned in issue 263
2023-08-15 15:49:55 +02:00
Marcel Baumgartner
ce7125b50b Merge pull request #271 from Moonlight-Panel/ImproveAutoAdminSecurity
Improved auto admin security
2023-08-15 15:45:46 +02:00
Marcel Baumgartner
31d8c3f469 Improved auto admin security
As mentioned in issue 253
2023-08-15 15:45:12 +02:00
Marcel Baumgartner
c80622c2fd Merge pull request #270 from Moonlight-Panel/ImproveSecurityLogPrivacy
Improved the privacy for security logs
2023-08-15 15:33:38 +02:00
Marcel Baumgartner
95e659e5f7 Improved the privacy for security logs
As mentioned in issue 262
2023-08-15 15:33:18 +02:00
Marcel Baumgartner
c155909e82 Merge pull request #269 from Moonlight-Panel/MoveChangelog
Moved changelog to admin section
2023-08-15 15:26:44 +02:00
Marcel Baumgartner
0011ed29b7 Moved changelog to admin section 2023-08-15 15:26:24 +02:00
Marcel Baumgartner
52c4ca0c0a Merge pull request #268 from Moonlight-Panel/AddBetterSelfbotDetection
Improved the whole malware scan system. Made it possible for plugins to add them. Improved self bot detection for python
2023-08-15 15:15:30 +02:00
Marcel Baumgartner
c197d0ca96 Improved the whole malware scan system. Made it possible for plugins to add them. Improved self bot detection for python 2023-08-15 15:14:28 +02:00
Marcel Baumgartner
25902034e9 Switched to horizontal nav bar in the server view 2023-08-14 22:16:59 +02:00
Marcel Baumgartner
b10db643fe Merge pull request #266 from Moonlight-Panel/ImproveSoftErrors
Improved soft error boundary
2023-08-14 18:33:58 +02:00
Marcel Baumgartner
4c7ffe6714 Improved soft error boundary 2023-08-14 18:22:20 +02:00
Marcel Baumgartner
a0c2b45a61 Merge pull request #249 from Dannyx1604/main
Update README.md because of new installer
2023-08-13 21:16:53 +02:00
Marcel Baumgartner
e49a9d3505 Merge branch 'main' into main 2023-08-13 21:16:42 +02:00
Dannyx
7ddae9c3e1 t
t
2023-08-13 20:04:47 +02:00
Daniel Balk
290e865ae0 Merge pull request #261 from NaysKutzu/main
Fix a lot of typing mistakes and added Romanian translations.
2023-08-09 15:52:42 +02:00
NaysKutzu
00ee625e2e Create ro_ro.lang 2023-08-09 15:10:57 +02:00
NaysKutzu
274e2d93f2 Fix the locations of the elements. 2023-08-09 14:48:09 +02:00
NaysKutzu
781171f7c5 Fix typo 2023-08-09 14:46:41 +02:00
NaysKutzu
4a8618da79 Merge pull request #1 from NaysKutzu/NaysKutzu-patch-1
Fix some typos in the README.
2023-08-09 14:44:23 +02:00
NaysKutzu
296cf0db6f Fix typo in readme 2023-08-09 14:43:26 +02:00
Marcel Baumgartner
48cdba5155 Removed unused a tags in ticket view 2023-08-09 04:08:28 +02:00
Marcel Baumgartner
35c1b255b5 Update README.md 2023-08-09 03:47:50 +02:00
Marcel Baumgartner
244b920305 Merge pull request #260 from Moonlight-Panel/RemoveFormatterByteUtils
switched to the new converter instead of the formatter functions to convert byte sizes
2023-08-09 03:46:42 +02:00
Marcel Baumgartner
3d4a2128e2 switched to the new converter instead of the formatter functions to convert byte sizes 2023-08-09 03:42:33 +02:00
Marcel Baumgartner
1cf8430ad8 Small include improvment 2023-08-09 03:33:28 +02:00
Marcel Baumgartner
a9b7d10fb0 Fix invalid include with new include 2023-08-09 03:23:34 +02:00
Marcel Baumgartner
47e333630e Removed useless links in the tickets overview for admins 2023-08-09 01:00:55 +02:00
Marcel Baumgartner
8b41a9fc13 Add message sender include 2023-08-09 00:57:40 +02:00
Marcel Baumgartner
d09957fdac Merge pull request #259 from Moonlight-Panel/ImproveBackgroundImage
Made the background image darker
2023-08-09 00:37:53 +02:00
Marcel Baumgartner
f9ecb61d71 Made the background image darker
Thanks to https://github.com/nuhuhwy
2023-08-09 00:37:36 +02:00
Marcel Baumgartner
ef92dd47ad Merge pull request #258 from Moonlight-Panel/ImproveTicketSystemUI
Improved ticket system ui and some backend code
2023-08-09 00:36:33 +02:00
Marcel Baumgartner
c2c533675b Improved ticket system ui and some backend code 2023-08-09 00:35:49 +02:00
Marcel Baumgartner
569dd69bdd Merge pull request #257 from Moritz-Deiaco/main
pagination button gap fix
2023-08-08 17:14:07 +02:00
Moritz
242870b3e1 pagination button gap fix 2023-08-08 17:08:54 +02:00
Daniel Balk
30b6e45235 Merge pull request #254 from Moritz-Deiaco/main
New Translations
2023-08-08 16:33:00 +02:00
Moritz
cd62fdc5f6 fixed a typo, rechecked everything 2023-08-08 16:28:46 +02:00
Moritz Deiaco
2c54b91e6c New translations in de_de.lang 2023-08-08 12:16:14 +02:00
Marcel Baumgartner
388deacf60 Merge pull request #250 from Moonlight-Panel/ImproveInstallUX
Improved install user experience
2023-08-08 00:54:10 +02:00
Marcel Baumgartner
aa547038de Improved install user experience 2023-08-08 00:53:00 +02:00
Dannyx
78bfd68d63 Update README.md because of New installer 2023-08-07 22:23:20 +02:00
Marcel Baumgartner
17e3345b8a Added date formatter for user overview 2023-08-06 22:00:59 +02:00
Marcel Baumgartner
f95312c1e3 Merge pull request #248 from Moonlight-Panel/AddTicketSystem
Added ticket system
2023-08-06 21:57:24 +02:00
Marcel Baumgartner
2144ca3823 Added byte converter and fixed memory view at the nodes 2023-08-06 21:55:23 +02:00
Marcel Baumgartner
de45ff40d8 Implemented a basic ticket system 2023-08-04 14:00:25 +02:00
Marcel Baumgartner
606085c012 Merge pull request #242 from Moonlight-Panel/AddNewBackupFormat
Added new backup format
2023-08-02 22:05:39 +02:00
Marcel Baumgartner
00525d8099 Added new backup format 2023-08-02 22:05:07 +02:00
Marcel Baumgartner
26617d67f5 Merge pull request #241 from Moonlight-Panel/SmallFixes
Did some small fixes, added connection timeout check, improved ux
2023-08-02 03:07:47 +02:00
Marcel Baumgartner
600bec3417 Did some small fixes, added connection timeout check, improved ux 2023-08-02 03:06:54 +02:00
Marcel Baumgartner
4e85d1755a Merge pull request #240 from DatGamet/patch-1
Update de_de.lang
2023-08-02 01:39:58 +02:00
DatGamet
0832936933 Update de_de.lang 2023-08-02 01:39:08 +02:00
Marcel Baumgartner
ecda2ec6d1 Merge pull request #239 from Moonlight-Panel/FixPluginSystem
Fixed plugin loading system
2023-08-01 22:21:54 +02:00
Marcel Baumgartner
6f3765a3bf Fixed plugin loading system 2023-08-01 22:21:19 +02:00
Marcel Baumgartner
29002d3445 Update Moonlight.csproj 2023-08-01 20:38:22 +02:00
Marcel Baumgartner
6d0456a008 Merge pull request #238 from Moonlight-Panel/AddDdosProtection
Added new ddos protection
2023-07-24 00:33:22 +02:00
Marcel Baumgartner
3e698123bb Merge branch 'main' into AddDdosProtection 2023-07-24 00:33:01 +02:00
Marcel Baumgartner
f3fb86819a Merge pull request #237 from Moonlight-Panel/FixDomainIdentityIssues
Fixed domain identity issues
2023-07-24 00:30:50 +02:00
Marcel Baumgartner
e2248a8444 Fixed domain identity issues 2023-07-24 00:30:18 +02:00
Marcel Baumgartner
2cf2b77090 Added new ddos protection 2023-07-24 00:23:29 +02:00
Marcel Baumgartner
fedc9278d4 Updated dependencies 2023-07-23 22:12:17 +02:00
Marcel Baumgartner
f29206a69b Merge pull request #236 from Moonlight-Panel/AddPluginSystem
Add plugin system
2023-07-23 21:31:26 +02:00
Marcel Baumgartner
0658e55a78 Implemented basic plugin store and improved plugin system 2023-07-23 21:30:57 +02:00
Marcel Baumgartner
21bea974a9 Implemented a basic plugin system 2023-07-22 23:44:45 +02:00
Marcel Baumgartner
33ef09433e Merge pull request #235 from Moonlight-Panel/AddMinerCheck
Add basic miner check
2023-07-22 02:24:16 +02:00
Marcel Baumgartner
173bff67df Add basic miner check 2023-07-22 02:08:39 +02:00
Marcel Baumgartner
512a989609 Merge pull request #234 from Moonlight-Panel/FixDomainOwnerMatching
Fixed domain owner matching
2023-07-20 17:24:05 +02:00
Marcel Baumgartner
2d7dac5089 Fixed domain owner matching 2023-07-20 17:17:05 +02:00
263 changed files with 17024 additions and 354399 deletions

View File

@@ -0,0 +1,20 @@
{
"name": "C# (.NET)",
"image": "mcr.microsoft.com/devcontainers/dotnet:0-6.0",
"customizations": {
"vscode": {
"settings": {},
"extensions": [
"streetsidesoftware.code-spell-checker"
]
}
},
"portsAttributes": {
"5118": {
"label": "Moonlight",
"onAutoForward": "notify"
}
}
}

2
.github/FUNDING.yml vendored Normal file
View File

@@ -0,0 +1,2 @@
# These are supported funding model platforms
ko_fi: masuowo

96
.github/ISSUE_TEMPLATE/bug-report.yml vendored Normal file
View File

@@ -0,0 +1,96 @@
name: Bug Report
description: Something isn't working quite right in the software.
labels: [not confirmed]
body:
- type: markdown
attributes:
value: |
Bug reports should only be used for reporting issues with how the software works. For assistance installing this software, as well as debugging issues with dependencies, please use our [Discord server](https://discord.gg/TJaspT7A8p).
- type: textarea
attributes:
label: Current Behavior
description: Please provide a clear & concise description of the issue.
validations:
required: true
- type: textarea
attributes:
label: Expected Behavior
description: Please describe what you expected to happen.
validations:
required: true
- type: textarea
attributes:
label: Steps to Reproduce
description: Please be as detailed as possible when providing steps to reproduce, failure to provide steps will result in this issue being closed.
validations:
required: true
- type: input
id: panel-version
attributes:
label: Panel Version
description: Version number of your Panel (latest is not a version)
placeholder: 1.4.0
validations:
required: true
- type: input
id: daemon-version
attributes:
label: Daemon Version
description: Version number of your Daemon (latest is not a version)
placeholder: 1.4.2
validations:
required: true
- type: input
id: wings-version
attributes:
label: Wings Version
description: Version number of your Wings (latest is not a version)
placeholder: 1.4.2
validations:
required: true
- type: input
id: image-details
attributes:
label: Games and/or Images Affected
description: Please include the specific game(s) or Image(s) you are running into this bug with.
placeholder: Minecraft (Paper), Minecraft (Forge)
- type: input
id: docker-image
attributes:
label: Docker Image
description: The specific Docker image you are using for the game(s) above.
placeholder: ghcr.io/xxx/yolks:java_17
- type: textarea
id: panel-logs
attributes:
label: Error Logs
description: |
Run the following command to collect logs on your system.
Panel: `docker logs moonlight`
Wings: `sudo wings diagnostics`
placeholder: logs here
render: bash
validations:
required: false
- type: checkboxes
attributes:
label: Is there an existing issue for this?
description: Please [search here](https://github.com/Moonlight-Panel/Moonlight/issues) to see if an issue already exists for your problem.
options:
- label: I have searched the existing issues before opening this issue.
required: true
- label: I have provided all relevant details, including the specific game and Docker images I am using if this issue is related to running a server.
required: true
- label: I have checked in the Discord server and believe this is a bug with the software, and not a configuration issue with my specific system.
required: true

8
.github/ISSUE_TEMPLATE/config.yml vendored Normal file
View File

@@ -0,0 +1,8 @@
blank_issues_enabled: true
contact_links:
- name: Installation Help
url: https://discord.gg/TJaspT7A8p
about: Please visit our Discord for help with your installation.
- name: General Question
url: https://discord.gg/TJaspT7A8p
about: Please visit our Discord for general questions about Moonlight Panel.

View File

@@ -0,0 +1,32 @@
name: Feature Request
description: Suggest a new feature or improvement for the software.
labels: [feature request]
body:
- type: checkboxes
attributes:
label: Is there an existing feature request for this?
description: Please [search here](https://github.com/Moonlight-Panel/Moonlight/issues?q=is%3Aissue) to see if someone else has already suggested this.
options:
- label: I have searched the existing issues before opening this feature request.
required: true
- type: textarea
attributes:
label: Describe the feature you would like to see.
description: "A clear & concise description of the feature you'd like to have added, and what issues it would solve."
validations:
required: true
- type: textarea
attributes:
label: Describe the solution you'd like.
description: "You must explain how you'd like to see this feature implemented. Technical implementation details are not necessary, rather an idea of how you'd like to see this feature used."
validations:
required: true
- type: textarea
attributes:
label: Additional context to this request.
description: "Add any other context or screenshots about the feature request."
validations:
required: false

12
.github/dependabot.yml vendored Normal file
View File

@@ -0,0 +1,12 @@
# To get started with Dependabot version updates, you'll need to specify which
# package ecosystems to update and where the package manifests are located.
# Please see the documentation for all configuration options:
# https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates
version: 2
updates:
# Maintain Github workflows
- package-ecosystem: "github-actions"
directory: "/" # Must be set to / although they're located in .github/workflows
schedule:
interval: "daily"

View File

@@ -0,0 +1,27 @@
name: Canary Docker Build
on:
workflow_dispatch:
pull_request:
types:
- closed
branches: [ "main" ]
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Login into docker hub
run: docker login -u ${{ secrets.DOCKER_USER }} -p ${{ secrets.DOCKER_PW }}
- name: Build and Push Docker image
uses: docker/build-push-action@v5
with:
context: .
file: ./Moonlight/Dockerfile
push: true
tags: moonlightpanel/moonlight:canary
platforms: linux/amd64,linux/arm64

View File

@@ -0,0 +1,25 @@
name: Release Docker Build
on:
workflow_dispatch:
release:
types: [ published ]
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Login into docker hub
run: docker login -u ${{ secrets.DOCKER_USER }} -p ${{ secrets.DOCKER_PW }}
- name: Build and Push Docker image
uses: docker/build-push-action@v5
with:
context: .
file: ./Moonlight/Dockerfile
push: true
tags: moonlightpanel/moonlight:beta
platforms: linux/amd64,linux/arm64

View File

@@ -13,6 +13,6 @@ jobs:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- name: Checkout code - name: Checkout code
uses: actions/checkout@v2 uses: actions/checkout@v4
- name: Build Docker image - name: Build Docker image
run: docker build -t moonlightpanel/moonlight:${{ github.sha }} -f Moonlight/Dockerfile . run: docker build -t moonlightpanel/moonlight:${{ github.sha }} -f Moonlight/Dockerfile .

View File

@@ -0,0 +1,3 @@
<values>
<value name="mac.address" type="string">a6a05ab0b1614c08281b54fc3b3339170b0f57a5e246c20b7393333dfa28f8f1</value>
</values>

View File

@@ -0,0 +1,3 @@
<values>
<value name="StillAlive" type="qword">133564417297189136</value>
</values>

View File

@@ -0,0 +1,3 @@
<values>
<value name="MachineId" type="string">{A6A05AB0-B161-4C08-281B-54FC3B333917}</value>
</values>

35
.vscode/launch.json vendored Normal file
View File

@@ -0,0 +1,35 @@
{
"version": "0.2.0",
"configurations": [
{
// Use IntelliSense to find out which attributes exist for C# debugging
// Use hover for the description of the existing attributes
// For further information visit https://github.com/dotnet/vscode-csharp/blob/main/debugger-launchjson.md.
"name": ".NET Core Launch (web)",
"type": "coreclr",
"request": "launch",
"preLaunchTask": "build",
// If you have changed target frameworks, make sure to update the program path.
"program": "${workspaceFolder}/Moonlight/bin/Debug/net6.0/Moonlight.dll",
"args": [],
"cwd": "${workspaceFolder}/Moonlight",
"stopAtEntry": false,
// Enable launching a web browser when ASP.NET Core starts. For more information: https://aka.ms/VSCode-CS-LaunchJson-WebBrowser
"serverReadyAction": {
"action": "openExternally",
"pattern": "\\bNow listening on:\\s+(https?://\\S+)"
},
"env": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"sourceFileMap": {
"/Views": "${workspaceFolder}/Views"
}
},
{
"name": ".NET Core Attach",
"type": "coreclr",
"request": "attach"
}
]
}

41
.vscode/tasks.json vendored Normal file
View File

@@ -0,0 +1,41 @@
{
"version": "2.0.0",
"tasks": [
{
"label": "build",
"command": "dotnet",
"type": "process",
"args": [
"build",
"${workspaceFolder}/Moonlight.sln",
"/property:GenerateFullPaths=true",
"/consoleloggerparameters:NoSummary"
],
"problemMatcher": "$msCompile"
},
{
"label": "publish",
"command": "dotnet",
"type": "process",
"args": [
"publish",
"${workspaceFolder}/Moonlight.sln",
"/property:GenerateFullPaths=true",
"/consoleloggerparameters:NoSummary"
],
"problemMatcher": "$msCompile"
},
{
"label": "watch",
"command": "dotnet",
"type": "process",
"args": [
"watch",
"run",
"--project",
"${workspaceFolder}/Moonlight.sln"
],
"problemMatcher": "$msCompile"
}
]
}

121
LICENSE Normal file
View File

@@ -0,0 +1,121 @@
Creative Commons Legal Code
CC0 1.0 Universal
CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE
LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN
ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS
INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES
REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS
PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM
THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED
HEREUNDER.
Statement of Purpose
The laws of most jurisdictions throughout the world automatically confer
exclusive Copyright and Related Rights (defined below) upon the creator
and subsequent owner(s) (each and all, an "owner") of an original work of
authorship and/or a database (each, a "Work").
Certain owners wish to permanently relinquish those rights to a Work for
the purpose of contributing to a commons of creative, cultural and
scientific works ("Commons") that the public can reliably and without fear
of later claims of infringement build upon, modify, incorporate in other
works, reuse and redistribute as freely as possible in any form whatsoever
and for any purposes, including without limitation commercial purposes.
These owners may contribute to the Commons to promote the ideal of a free
culture and the further production of creative, cultural and scientific
works, or to gain reputation or greater distribution for their Work in
part through the use and efforts of others.
For these and/or other purposes and motivations, and without any
expectation of additional consideration or compensation, the person
associating CC0 with a Work (the "Affirmer"), to the extent that he or she
is an owner of Copyright and Related Rights in the Work, voluntarily
elects to apply CC0 to the Work and publicly distribute the Work under its
terms, with knowledge of his or her Copyright and Related Rights in the
Work and the meaning and intended legal effect of CC0 on those rights.
1. Copyright and Related Rights. A Work made available under CC0 may be
protected by copyright and related or neighboring rights ("Copyright and
Related Rights"). Copyright and Related Rights include, but are not
limited to, the following:
i. the right to reproduce, adapt, distribute, perform, display,
communicate, and translate a Work;
ii. moral rights retained by the original author(s) and/or performer(s);
iii. publicity and privacy rights pertaining to a person's image or
likeness depicted in a Work;
iv. rights protecting against unfair competition in regards to a Work,
subject to the limitations in paragraph 4(a), below;
v. rights protecting the extraction, dissemination, use and reuse of data
in a Work;
vi. database rights (such as those arising under Directive 96/9/EC of the
European Parliament and of the Council of 11 March 1996 on the legal
protection of databases, and under any national implementation
thereof, including any amended or successor version of such
directive); and
vii. other similar, equivalent or corresponding rights throughout the
world based on applicable law or treaty, and any national
implementations thereof.
2. Waiver. To the greatest extent permitted by, but not in contravention
of, applicable law, Affirmer hereby overtly, fully, permanently,
irrevocably and unconditionally waives, abandons, and surrenders all of
Affirmer's Copyright and Related Rights and associated claims and causes
of action, whether now known or unknown (including existing as well as
future claims and causes of action), in the Work (i) in all territories
worldwide, (ii) for the maximum duration provided by applicable law or
treaty (including future time extensions), (iii) in any current or future
medium and for any number of copies, and (iv) for any purpose whatsoever,
including without limitation commercial, advertising or promotional
purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each
member of the public at large and to the detriment of Affirmer's heirs and
successors, fully intending that such Waiver shall not be subject to
revocation, rescission, cancellation, termination, or any other legal or
equitable action to disrupt the quiet enjoyment of the Work by the public
as contemplated by Affirmer's express Statement of Purpose.
3. Public License Fallback. Should any part of the Waiver for any reason
be judged legally invalid or ineffective under applicable law, then the
Waiver shall be preserved to the maximum extent permitted taking into
account Affirmer's express Statement of Purpose. In addition, to the
extent the Waiver is so judged Affirmer hereby grants to each affected
person a royalty-free, non transferable, non sublicensable, non exclusive,
irrevocable and unconditional license to exercise Affirmer's Copyright and
Related Rights in the Work (i) in all territories worldwide, (ii) for the
maximum duration provided by applicable law or treaty (including future
time extensions), (iii) in any current or future medium and for any number
of copies, and (iv) for any purpose whatsoever, including without
limitation commercial, advertising or promotional purposes (the
"License"). The License shall be deemed effective as of the date CC0 was
applied by Affirmer to the Work. Should any part of the License for any
reason be judged legally invalid or ineffective under applicable law, such
partial invalidity or ineffectiveness shall not invalidate the remainder
of the License, and in such case Affirmer hereby affirms that he or she
will not (i) exercise any of his or her remaining Copyright and Related
Rights in the Work or (ii) assert any associated claims and causes of
action with respect to the Work, in either case contrary to Affirmer's
express Statement of Purpose.
4. Limitations and Disclaimers.
a. No trademark or patent rights held by Affirmer are waived, abandoned,
surrendered, licensed or otherwise affected by this document.
b. Affirmer offers the Work as-is and makes no representations or
warranties of any kind concerning the Work, express, implied,
statutory or otherwise, including without limitation warranties of
title, merchantability, fitness for a particular purpose, non
infringement, or the absence of latent or other defects, accuracy, or
the present or absence of errors, whether or not discoverable, all to
the greatest extent permissible under applicable law.
c. Affirmer disclaims responsibility for clearing rights of other persons
that may apply to the Work or any use thereof, including without
limitation any person's Copyright and Related Rights in the Work.
Further, Affirmer disclaims responsibility for obtaining any necessary
consents, permissions or other rights required for any use of the
Work.
d. Affirmer understands and acknowledges that Creative Commons is not a
party to this document and has no duty or obligation with respect to
this CC0 or use of the Work.

View File

@@ -1,128 +0,0 @@
<h3>Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International Public License (modified)</h3>
<p>By exercising the Licensed Rights (defined below), You accept and agree to be bound by the terms and conditions of this Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International Public License ("Public License"). To the extent this Public License may be interpreted as a contract, You are granted the Licensed Rights in consideration of Your acceptance of these terms and conditions, and the Licensor grants You such rights in consideration of benefits the Licensor receives from making the Licensed Material available under these terms and conditions.</p>
<p id="s1"><strong>Section 1 Definitions.</strong></p>
<ol type="a">
<li id="s1a"><strong>Adapted Material</strong> means material subject to Copyright and Similar Rights that is derived from or based upon the Licensed Material and in which the Licensed Material is translated, altered, arranged, transformed, or otherwise modified in a manner requiring permission under the Copyright and Similar Rights held by the Licensor. For purposes of this Public License, where the Licensed Material is a musical work, performance, or sound recording, Adapted Material is always produced where the Licensed Material is synched in timed relation with a moving image.</li>
<li id="s1b"><strong>Adapter's License</strong> means the license You apply to Your Copyright and Similar Rights in Your contributions to Adapted Material in accordance with the terms and conditions of this Public License.</li>
<li id="s1c"><strong>BY-NC-SA Compatible License</strong> means a license listed at <a href="//creativecommons.org/compatiblelicenses"> creativecommons.org/compatiblelicenses</a>, approved by Creative Commons as essentially the equivalent of this Public License.</li>
<li id="s1d"><strong>Copyright and Similar Rights</strong> means copyright and/or similar rights closely related to copyright including, without limitation, performance, broadcast, sound recording, and Sui Generis Database Rights, without regard to how the rights are labeled or categorized. For purposes of this Public License, the rights specified in Section <a href="#s2b">2(b)(1)-(2)</a> are not Copyright and Similar Rights.</li>
<li id="s1e"><strong>Effective Technological Measures</strong> means those measures that, in the absence of proper authority, may not
be circumvented under laws fulfilling obligations under Article 11 of the WIPO Copyright Treaty adopted on December 20, 1996, and/or similar
international agreements.</li>
<li id="s1f"><strong>Exceptions and Limitations</strong> means fair use, fair dealing, and/or any other exception or limitation to Copyright and Similar Rights that applies to Your use of the Licensed Material.</li>
<li id="s1g"><strong>License Elements</strong> means the license attributes listed in the name of a Creative Commons Public License. The License Elements of this Public License are Attribution, NonCommercial, and ShareAlike.</li>
<li id="s1h"><strong>Licensed Material</strong> means the artistic or literary work, database, or other material to which the Licensor applied this Public License.</li>
<li id="s1i"><strong>Licensed Rights</strong> means the rights granted to You subject to the terms and conditions of this Public License, which are limited to all Copyright and Similar Rights that apply to Your use of the Licensed Material and that the Licensor has authority to license.</li>
<li id="s1j"><strong>Licensor</strong> means the individual(s) or entity(ies) granting rights under this Public License.</li>
<li id="s1k"><strong>NonCommercial</strong> means not primarily intended for or directed towards commercial advantage or monetary compensation. This also includes free hosting services or simmular which have no direct permission from the moonlight panel team to use this software. For purposes of this Public License, the exchange of the Licensed Material for other material subject to Copyright and Similar Rights by digital file-sharing or similar means is NonCommercial provided there is no payment of monetary compensation in connection with the exchange.</li>
<li id="s1l"><strong>Share</strong> means to provide material to the public by any means or process that requires permission under the Licensed Rights, such as reproduction, public display, public performance, distribution, dissemination, communication, or importation, and to make material available to the public including in ways that members of the public may access the material from a place and at a time individually chosen by them.</li>
<li id="s1m"><strong>Sui Generis Database Rights</strong> means rights other than copyright resulting from Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, as amended and/or succeeded, as well as other essentially equivalent rights anywhere in the world.</li>
<li id="s1n"><strong>You</strong> means the individual or entity exercising the Licensed Rights under this Public License. <strong>Your</strong> has a corresponding meaning.</li>
</ol>
<p id="s2"><strong>Section 2 Scope.</strong></p>
<ol type="a">
<li id="s2a"><strong>License grant</strong>.
<ol>
<li id="s2a1">Subject to the terms and conditions of this Public License, the Licensor hereby grants You a worldwide, royalty-free, non-sublicensable, non-exclusive, irrevocable license to exercise the Licensed Rights in the Licensed Material to:
<ol type="A">
<li id="s2a1A">reproduce and Share the Licensed Material, in whole or in part, for NonCommercial purposes only; and</li>
<li id="s2a1B">produce, reproduce, and Share Adapted Material for NonCommercial purposes only.</li>
</ol>
</li><li id="s2a2"><span style="text-decoration: underline;">Exceptions and Limitations</span>. For the avoidance of doubt, where Exceptions and Limitations apply to Your use, this Public License does not apply, and You do not need to comply with its terms and conditions.</li>
<li id="s2a3"><span style="text-decoration: underline;">Term</span>. The term of this Public License is specified in Section <a href="#s6a">6(a)</a>.</li>
<li id="s2a4"><span style="text-decoration: underline;">Media and formats; technical modifications allowed</span>. The Licensor authorizes You to exercise the Licensed Rights in all media and formats whether now known or hereafter created, and to make technical modifications necessary to do so. The Licensor waives and/or agrees not to assert any right or authority to forbid You from making technical modifications necessary to exercise the Licensed Rights, including technical modifications necessary to circumvent Effective Technological Measures. For purposes of this Public License, simply making modifications authorized by this Section <a href="#s2a4">2(a)(4)</a> never produces Adapted Material.</li>
<li id="s2a5"><span style="text-decoration: underline;">Downstream recipients</span>.
<div class="para">
<ol type="A">
<li id="s2a5A"><span style="text-decoration: underline;">Offer from the Licensor Licensed Material</span>. Every recipient of the Licensed Material automatically receives an offer from the Licensor to exercise the Licensed Rights under the terms and conditions of this Public License.</li>
<li id="s2a5B"><span style="text-decoration: underline;">Additional offer from the Licensor Adapted Material</span>. Every recipient of Adapted Material from You automatically receives an offer from the Licensor to exercise the Licensed Rights in the Adapted Material under the conditions of the Adapters License You apply.</li>
<li id="s2a5C"><span style="text-decoration: underline;">No downstream restrictions</span>. You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, the Licensed Material if doing so restricts exercise of the Licensed Rights by any recipient of the Licensed Material.</li>
</ol>
</div>
</li><li id="s2a6"><span style="text-decoration: underline;">No endorsement</span>. Nothing in this Public License constitutes or may be construed as permission to assert or imply that You are, or that Your use of the Licensed Material is, connected with, or sponsored, endorsed, or granted official status by, the Licensor or others designated to receive attribution as provided in Section <a href="#s3a1Ai">3(a)(1)(A)(i)</a>.</li>
</ol>
</li><li id="s2b"><p><strong>Other rights</strong>.</p>
<ol>
<li id="s2b1">Moral rights, such as the right of integrity, are not licensed under this Public License, nor are publicity, privacy, and/or other similar personality rights; however, to the extent possible, the Licensor waives and/or agrees not to assert any such rights held by the Licensor to the limited extent necessary to allow You to exercise the Licensed Rights, but not otherwise.</li>
<li id="s2b2">Patent and trademark rights are not licensed under this Public License.</li>
<li id="s2b3">To the extent possible, the Licensor waives any right to collect royalties from You for the exercise of the Licensed Rights, whether directly or through a collecting society under any voluntary or waivable statutory or compulsory licensing scheme. In all other cases the Licensor expressly reserves any right to collect such royalties, including when the Licensed Material is used other than for NonCommercial purposes.</li>
</ol>
</li>
</ol>
<p id="s3"><strong>Section 3 License Conditions.</strong></p>
<p>Your exercise of the Licensed Rights is expressly made subject to the following conditions.</p>
<ol type="a">
<li id="s3a"><p><strong>Attribution</strong>.</p>
<ol>
<li id="s3a1"><p>If You Share the Licensed Material (including in modified form), You must:</p>
<ol type="A">
<li id="s3a1A">retain the following if it is supplied by the Licensor with the Licensed Material:
<ol type="i">
<li id="s3a1Ai">identification of the creator(s) of the Licensed Material and any others designated to receive attribution, in any reasonable manner requested by the Licensor (including by pseudonym if designated);</li>
<li id="s3a1Aii">a copyright notice;</li>
<li id="s3a1Aiii">a notice that refers to this Public License; </li>
<li id="s3a1Aiv">a notice that refers to the disclaimer of warranties;</li>
<li id="s3a1Av">a URI or hyperlink to the Licensed Material to the extent reasonably practicable;</li>
</ol>
</li><li id="s3a1B">indicate if You modified the Licensed Material and retain an indication of any previous modifications; and</li>
<li id="s3a1C">indicate the Licensed Material is licensed under this Public License,
and include the text of, or the URI or hyperlink to, this Public
License.</li>
</ol>
</li>
<li id="s3a2">You may satisfy the conditions in Section <a href="#s3a1">3(a)(1)</a> in any reasonable manner based on the medium, means, and context in which You Share the Licensed Material. For example, it may be reasonable to satisfy the conditions by providing a URI or hyperlink to a resource that includes the required information.</li>
<li id="s3a3">If requested by the Licensor, You must remove any of the information required by Section <a href="#s3a1A">3(a)(1)(A)</a> to the extent reasonably practicable.</li>
</ol>
</li>
<li id="s3b"><strong>ShareAlike</strong>.
<p>In addition to the conditions in Section <a href="#s3a">3(a)</a>, if You Share Adapted Material You produce, the following conditions also apply.</p>
<ol>
<li id="s3b1">The Adapters License You apply must be a Creative Commons license with the same License Elements, this version or later, or a BY-NC-SA Compatible License.</li>
<li id="s3b2">You must include the text of, or the URI or hyperlink to, the Adapter's License You apply. You may satisfy this condition in any reasonable manner based on the medium, means, and context in which You Share Adapted Material.</li>
<li id="s3b3">You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, Adapted Material that restrict exercise of the rights granted under the Adapter's License You apply.</li>
</ol>
</li>
</ol>
<p id="s4"><strong>Section 4 Sui Generis Database Rights.</strong></p>
<p>Where the Licensed Rights include Sui Generis Database Rights that apply to Your use of the Licensed Material:</p>
<ol type="a">
<li id="s4a">for the avoidance of doubt, Section <a href="#s2a1">2(a)(1)</a> grants You the right to extract, reuse, reproduce, and Share all or a substantial portion of the contents of the database for NonCommercial purposes only;</li>
<li id="s4b">if You include all or a substantial portion of the database contents in a database in which You have Sui Generis Database Rights, then the database in which You have Sui Generis Database Rights (but not its individual contents) is Adapted Material, including for purposes of Section <a href="#s3b">3(b)</a>; and</li>
<li id="s4c">You must comply with the conditions in Section <a href="#s3a">3(a)</a> if You Share all or a substantial portion of the contents of the database.</li>
</ol>
For the avoidance of doubt, this Section <a href="#s4">4</a> supplements and does not replace Your obligations under this Public License where the Licensed Rights include other Copyright and Similar Rights.
<p id="s5"><strong>Section 5 Disclaimer of Warranties and Limitation of Liability.</strong></p>
<ol style="font-weight: bold;" type="a">
<li id="s5a"><strong>Unless otherwise separately undertaken by the Licensor, to the extent possible, the Licensor offers the Licensed Material as-is and as-available, and makes no representations or warranties of any kind concerning the Licensed Material, whether express, implied, statutory, or other. This includes, without limitation, warranties of title, merchantability, fitness for a particular purpose, non-infringement, absence of latent or other defects, accuracy, or the presence or absence of errors, whether or not known or discoverable. Where disclaimers of warranties are not allowed in full or in part, this disclaimer may not apply to You.</strong></li>
<li id="s5b"><strong>To the extent possible, in no event will the Licensor be liable to You on any legal theory (including, without limitation, negligence) or otherwise for any direct, special, indirect, incidental, consequential, punitive, exemplary, or other losses, costs, expenses, or damages arising out of this Public License or use of the Licensed Material, even if the Licensor has been advised of the possibility of such losses, costs, expenses, or damages. Where a limitation of liability is not allowed in full or in part, this limitation may not apply to You.</strong></li>
</ol>
<ol start="3" type="a">
<li id="s5c">The disclaimer of warranties and limitation of liability provided above shall be interpreted in a manner that, to the extent possible, most closely approximates an absolute disclaimer and waiver of all liability.</li>
</ol>
<p id="s6"><strong>Section 6 Term and Termination.</strong></p>
<ol type="a">
<li id="s6a">This Public License applies for the term of the Copyright and Similar Rights licensed here. However, if You fail to comply with this Public License, then Your rights under this Public License terminate automatically.</li>
<li id="s6b">
<p>Where Your right to use the Licensed Material has terminated under Section <a href="#s6a">6(a)</a>, it reinstates:</p>
<ol>
<li id="s6b1">automatically as of the date the violation is cured, provided it is cured within 30 days of Your discovery of the violation; or</li>
<li id="s6b2">upon express reinstatement by the Licensor.</li>
</ol>
For the avoidance of doubt, this Section <a href="#s6b">6(b)</a> does not affect any right the Licensor may have to seek remedies for Your violations of this Public License.</li>
<li id="s6c">For the avoidance of doubt, the Licensor may also offer the Licensed Material under separate terms or conditions or stop distributing the Licensed Material at any time; however, doing so will not terminate this Public License.</li>
<li id="s6d">Sections <a href="#s1">1</a>, <a href="#s5">5</a>, <a href="#s6">6</a>, <a href="#s7">7</a>, and <a href="#s8">8</a> survive termination of this Public License.</li>
</ol>
<p id="s7"><strong>Section 7 Other Terms and Conditions.</strong></p>
<ol type="a">
<li id="s7a">The Licensor shall not be bound by any additional or different terms or conditions communicated by You unless expressly agreed.</li>
<li id="s7b">Any arrangements, understandings, or agreements regarding the Licensed Material not stated herein are separate from and independent of the terms and conditions of this Public License.</li>
</ol>
<p id="s8"><strong>Section 8 Interpretation.</strong></p>
<ol type="a">
<li id="s8a">For the avoidance of doubt, this Public License does not, and shall not be interpreted to, reduce, limit, restrict, or impose conditions on any use of the Licensed Material that could lawfully be made without permission under this Public License.</li>
<li id="s8b">To the extent possible, if any provision of this Public License is deemed unenforceable, it shall be automatically reformed to the minimum extent necessary to make it enforceable. If the provision cannot be reformed, it shall be severed from this Public License without affecting the enforceability of the remaining terms and conditions.</li>
<li id="s8c">No term or condition of this Public License will be waived and no failure to comply consented to unless expressly agreed to by the Licensor.</li>
<li id="s8d">Nothing in this Public License constitutes or may be interpreted as a limitation upon, or waiver of, any privileges and immunities that apply to the Licensor or You, including from the legal processes of any jurisdiction or authority.</li>
</ol>
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, TITLE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@@ -8,8 +8,7 @@ using Newtonsoft.Json;
public class ConfigV1 public class ConfigV1
{ {
[JsonProperty("Moonlight")] [JsonProperty("Moonlight")] public MoonlightData Moonlight { get; set; } = new();
public MoonlightData Moonlight { get; set; } = new();
public class MoonlightData public class MoonlightData
{ {
@@ -17,6 +16,17 @@ public class ConfigV1
[Description("The url moonlight is accesible with from the internet")] [Description("The url moonlight is accesible with from the internet")]
public string AppUrl { get; set; } = "http://your-moonlight-url-without-slash"; public string AppUrl { get; set; } = "http://your-moonlight-url-without-slash";
[JsonProperty("EnableLatencyCheck")]
[Description(
"This will enable a latency check for connections to moonlight. Users with an too high latency will be warned that moonlight might be buggy for them")]
public bool EnableLatencyCheck { get; set; } = true;
[JsonProperty("LatencyCheckThreshold")]
[Description("Specify the latency threshold which has to be reached in order to trigger the warning message")]
public int LatencyCheckThreshold { get; set; } = 1000;
[JsonProperty("LetsEncrypt")] public LetsEncrypt LetsEncrypt { get; set; } = new();
[JsonProperty("Auth")] public AuthData Auth { get; set; } = new(); [JsonProperty("Auth")] public AuthData Auth { get; set; } = new();
[JsonProperty("Database")] public DatabaseData Database { get; set; } = new(); [JsonProperty("Database")] public DatabaseData Database { get; set; } = new();
@@ -39,7 +49,8 @@ public class ConfigV1
[JsonProperty("Cleanup")] public CleanupData Cleanup { get; set; } = new(); [JsonProperty("Cleanup")] public CleanupData Cleanup { get; set; } = new();
[JsonProperty("DiscordNotifications")] public DiscordNotificationsData DiscordNotifications { get; set; } = new(); [JsonProperty("DiscordNotifications")]
public DiscordNotificationsData DiscordNotifications { get; set; } = new();
[JsonProperty("Statistics")] public StatisticsData Statistics { get; set; } = new(); [JsonProperty("Statistics")] public StatisticsData Statistics { get; set; } = new();
@@ -50,12 +61,49 @@ public class ConfigV1
[JsonProperty("Sentry")] public SentryData Sentry { get; set; } = new(); [JsonProperty("Sentry")] public SentryData Sentry { get; set; } = new();
[JsonProperty("Stripe")] public StripeData Stripe { get; set; } = new(); [JsonProperty("Stripe")] public StripeData Stripe { get; set; } = new();
[JsonProperty("Tickets")] public TicketsData Tickets { get; set; } = new();
}
public class LetsEncrypt
{
[JsonProperty("Enable")]
[Description("Enable automatic lets encrypt certificate issuing. This is a beta feature")]
public bool Enable { get; set; } = false;
[JsonProperty("ExpireEmail")]
[Description("Lets encrypt will send you an email upon certificate expiration to this address")]
public string ExpireEmail { get; set; } = "your@email.test";
[JsonProperty("CountryCode")]
[Description("Country code to use for generating the certificate")]
public string CountryCode { get; set; } = "DE";
[JsonProperty("State")]
[Description("State to use for generating the certificate")]
public string State { get; set; } = "Germany";
[JsonProperty("Locality")]
[Description("Locality to use for generating the certificate")]
public string Locality { get; set; } = "Bavaria";
[JsonProperty("Organization")]
[Description("Organization to use for generating the certificate")]
public string Organization { get; set; } = "Moonlight Panel";
}
public class TicketsData
{
[JsonProperty("WelcomeMessage")]
[Description("The message that will be sent when a user created a ticket")]
public string WelcomeMessage { get; set; } = "Welcome to the support";
} }
public class StripeData public class StripeData
{ {
[JsonProperty("ApiKey")] [JsonProperty("ApiKey")]
[Description("Put here your stripe api key if you add subscriptions. Currently the only billing option is stripe which is enabled by default and cannot be turned off. This feature is still experimental")] [Description(
"Put here your stripe api key if you add subscriptions. Currently the only billing option is stripe which is enabled by default and cannot be turned off. This feature is still experimental")]
public string ApiKey { get; set; } = ""; public string ApiKey { get; set; } = "";
} }
@@ -68,6 +116,14 @@ public class ConfigV1
[JsonProperty("DenyRegister")] [JsonProperty("DenyRegister")]
[Description("Prevent every new user to register")] [Description("Prevent every new user to register")]
public bool DenyRegister { get; set; } = false; public bool DenyRegister { get; set; } = false;
[JsonProperty("CheckForBots")]
[Description("Check for bots when a user has been registered")]
public bool CheckForBots { get; set; } = true;
[JsonProperty("BlockLinuxUsers")]
[Description("Blocks linux users from registering")]
public bool BlockLinuxUsers { get; set; } = false;
} }
public class CleanupData public class CleanupData
@@ -89,7 +145,8 @@ public class ConfigV1
public long Uptime { get; set; } = 6; public long Uptime { get; set; } = 6;
[JsonProperty("Enable")] [JsonProperty("Enable")]
[Description("The cleanup system provides a fair way for stopping unused servers and staying stable even with overallocation. A detailed explanation: docs.endelon-hosting.de/erklaerungen/cleanup")] [Description(
"The cleanup system provides a fair way for stopping unused servers and staying stable even with overallocation. A detailed explanation: docs.endelon-hosting.de/erklaerungen/cleanup")]
public bool Enable { get; set; } = false; public bool Enable { get; set; } = false;
[JsonProperty("MinUptime")] [JsonProperty("MinUptime")]
@@ -103,9 +160,7 @@ public class ConfigV1
[JsonProperty("Host")] public string Host { get; set; } = "your.database.host"; [JsonProperty("Host")] public string Host { get; set; } = "your.database.host";
[JsonProperty("Password")] [JsonProperty("Password")] [Blur] public string Password { get; set; } = "secret";
[Blur]
public string Password { get; set; } = "secret";
[JsonProperty("Port")] public long Port { get; set; } = 3306; [JsonProperty("Port")] public long Port { get; set; } = 3306;
@@ -123,6 +178,7 @@ public class ConfigV1
[Blur] [Blur]
public string Token { get; set; } = Guid.NewGuid().ToString(); public string Token { get; set; } = Guid.NewGuid().ToString();
} }
public class DiscordBotData public class DiscordBotData
{ {
[JsonProperty("Enable")] [JsonProperty("Enable")]
@@ -146,7 +202,8 @@ public class ConfigV1
public class DiscordNotificationsData public class DiscordNotificationsData
{ {
[JsonProperty("Enable")] [JsonProperty("Enable")]
[Description("The discord notification system sends you a message everytime a event like a new support chat message is triggered with usefull data describing the event")] [Description(
"The discord notification system sends you a message everytime a event like a new support chat message is triggered with usefull data describing the event")]
public bool Enable { get; set; } = false; public bool Enable { get; set; } = false;
[JsonProperty("WebHook")] [JsonProperty("WebHook")]
@@ -183,19 +240,23 @@ public class ConfigV1
public class HeadersData public class HeadersData
{ {
[JsonProperty("Color")] [JsonProperty("Color")]
[Description("This specifies the color of the embed generated by platforms like discord when someone posts a link to your moonlight instance")] [Description(
"This specifies the color of the embed generated by platforms like discord when someone posts a link to your moonlight instance")]
public string Color { get; set; } = "#4b27e8"; public string Color { get; set; } = "#4b27e8";
[JsonProperty("Description")] [JsonProperty("Description")]
[Description("This specifies the description text of the embed generated by platforms like discord when someone posts a link to your moonlight instance and can also help google to index your moonlight instance correctly")] [Description(
"This specifies the description text of the embed generated by platforms like discord when someone posts a link to your moonlight instance and can also help google to index your moonlight instance correctly")]
public string Description { get; set; } = "the next generation hosting panel"; public string Description { get; set; } = "the next generation hosting panel";
[JsonProperty("Keywords")] [JsonProperty("Keywords")]
[Description("To help search engines like google to index your moonlight instance correctly you can specify keywords seperated by a comma here")] [Description(
"To help search engines like google to index your moonlight instance correctly you can specify keywords seperated by a comma here")]
public string Keywords { get; set; } = "moonlight"; public string Keywords { get; set; } = "moonlight";
[JsonProperty("Title")] [JsonProperty("Title")]
[Description("This specifies the title of the embed generated by platforms like discord when someone posts a link to your moonlight instance")] [Description(
"This specifies the title of the embed generated by platforms like discord when someone posts a link to your moonlight instance")]
public string Title { get; set; } = "Moonlight - endelon.link"; public string Title { get; set; } = "Moonlight - endelon.link";
} }
@@ -205,9 +266,7 @@ public class ConfigV1
[JsonProperty("Server")] public string Server { get; set; } = "your.mail.host"; [JsonProperty("Server")] public string Server { get; set; } = "your.mail.host";
[JsonProperty("Password")] [JsonProperty("Password")] [Blur] public string Password { get; set; } = "secret";
[Blur]
public string Password { get; set; } = "secret";
[JsonProperty("Port")] public int Port { get; set; } = 465; [JsonProperty("Port")] public int Port { get; set; } = 465;
@@ -245,19 +304,19 @@ public class ConfigV1
[JsonProperty("ClientId")] public string ClientId { get; set; } [JsonProperty("ClientId")] public string ClientId { get; set; }
[JsonProperty("ClientSecret")] [JsonProperty("ClientSecret")] [Blur] public string ClientSecret { get; set; }
[Blur]
public string ClientSecret { get; set; }
} }
public class RatingData public class RatingData
{ {
[JsonProperty("Enabled")] [JsonProperty("Enabled")]
[Description("The rating systems shows a user who is registered longer than the set amout of days a popup to rate this platform if he hasnt rated it before")] [Description(
"The rating systems shows a user who is registered longer than the set amout of days a popup to rate this platform if he hasnt rated it before")]
public bool Enabled { get; set; } = false; public bool Enabled { get; set; } = false;
[JsonProperty("Url")] [JsonProperty("Url")]
[Description("This is the url a user who rated above a set limit is shown to rate you again. Its recommended to put your google or trustpilot rate link here")] [Description(
"This is the url a user who rated above a set limit is shown to rate you again. Its recommended to put your google or trustpilot rate link here")]
public string Url { get; set; } = "https://link-to-google-or-smth"; public string Url { get; set; } = "https://link-to-google-or-smth";
[JsonProperty("MinRating")] [JsonProperty("MinRating")]
@@ -272,32 +331,49 @@ public class ConfigV1
public class SecurityData public class SecurityData
{ {
[JsonProperty("Token")] [JsonProperty("Token")]
[Description("This is the moonlight app token. It is used to encrypt and decrypt data and validte tokens and sessions")] [Description(
"This is the moonlight app token. It is used to encrypt and decrypt data and validate tokens and sessions")]
[Blur] [Blur]
public string Token { get; set; } = Guid.NewGuid().ToString(); public string Token { get; set; } = Guid.NewGuid().ToString();
[JsonProperty("MalwareCheckOnStart")]
[Description(
"This option will enable the scanning for malware on every server before it has been started and if something has been found, the power action will be canceled")]
public bool MalwareCheckOnStart { get; set; } = true;
[JsonProperty("BlockIpDuration")]
[Description("The duration in minutes a ip will be blocked by the anti ddos system")]
public int BlockIpDuration { get; set; } = 15;
[JsonProperty("ReCaptcha")] public ReCaptchaData ReCaptcha { get; set; } = new(); [JsonProperty("ReCaptcha")] public ReCaptchaData ReCaptcha { get; set; } = new();
[JsonProperty("BlockDatacenterIps")]
[Description(
"If this option is enabled, users with an ip from datacenters will not be able to access the panel")]
public bool BlockDatacenterIps { get; set; } = true;
[JsonProperty("AllowCloudflareIps")]
[Description("Allow cloudflare ips to bypass the datacenter ip check")]
public bool AllowCloudflareIps { get; set; } = false;
} }
public class ReCaptchaData public class ReCaptchaData
{ {
[JsonProperty("Enable")] [JsonProperty("Enable")]
[Description("Enables repatcha at places like the register page. For information how to get your recaptcha credentails go to google.com/recaptcha/about/")] [Description(
"Enables repatcha at places like the register page. For information how to get your recaptcha credentails go to google.com/recaptcha/about/")]
public bool Enable { get; set; } = false; public bool Enable { get; set; } = false;
[JsonProperty("SiteKey")] [JsonProperty("SiteKey")] [Blur] public string SiteKey { get; set; } = "recaptcha site key here";
[Blur]
public string SiteKey { get; set; } = "recaptcha site key here";
[JsonProperty("SecretKey")] [JsonProperty("SecretKey")] [Blur] public string SecretKey { get; set; } = "recaptcha secret here";
[Blur]
public string SecretKey { get; set; } = "recaptcha secret here";
} }
public class SentryData public class SentryData
{ {
[JsonProperty("Enable")] [JsonProperty("Enable")]
[Description("Sentry is a way to monitor application crashes and performance issues in real time. Enable this option only if you set a sentry dsn")] [Description(
"Sentry is a way to monitor application crashes and performance issues in real time. Enable this option only if you set a sentry dsn")]
public bool Enable { get; set; } = false; public bool Enable { get; set; } = false;
[JsonProperty("Dsn")] [JsonProperty("Dsn")]

View File

@@ -42,6 +42,11 @@ public class DataContext : DbContext
public DbSet<IpBan> IpBans { get; set; } public DbSet<IpBan> IpBans { get; set; }
public DbSet<PermissionGroup> PermissionGroups { get; set; } public DbSet<PermissionGroup> PermissionGroups { get; set; }
public DbSet<SecurityLog> SecurityLogs { get; set; } public DbSet<SecurityLog> SecurityLogs { get; set; }
public DbSet<BlocklistIp> BlocklistIps { get; set; }
public DbSet<WhitelistIp> WhitelistIps { get; set; }
public DbSet<Ticket> Tickets { get; set; }
public DbSet<TicketMessage> TicketMessages { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{ {

View File

@@ -0,0 +1,10 @@
namespace Moonlight.App.Database.Entities;
public class BlocklistIp
{
public int Id { get; set; }
public string Ip { get; set; } = "";
public DateTime ExpiresAt { get; set; }
public long Packets { get; set; }
public DateTime CreatedAt { get; set; }
}

View File

@@ -0,0 +1,19 @@
using Moonlight.App.Models.Misc;
namespace Moonlight.App.Database.Entities;
public class Ticket
{
public int Id { get; set; }
public string IssueTopic { get; set; } = "";
public string IssueDescription { get; set; } = "";
public string IssueTries { get; set; } = "";
public User CreatedBy { get; set; }
public User? AssignedTo { get; set; }
public TicketPriority Priority { get; set; }
public TicketStatus Status { get; set; }
public TicketSubject Subject { get; set; }
public int SubjectId { get; set; }
public List<TicketMessage> Messages { get; set; } = new();
public DateTime CreatedAt { get; set; } = DateTime.UtcNow;
}

View File

@@ -0,0 +1,14 @@
namespace Moonlight.App.Database.Entities;
public class TicketMessage
{
public int Id { get; set; }
public string Content { get; set; } = "";
public string? AttachmentUrl { get; set; }
public User? Sender { get; set; }
public bool IsSystemMessage { get; set; }
public bool IsEdited { get; set; }
public bool IsSupportMessage { get; set; }
public DateTime CreatedAt { get; set; } = DateTime.UtcNow;
public DateTime UpdatedAt { get; set; } = DateTime.UtcNow;
}

View File

@@ -0,0 +1,7 @@
namespace Moonlight.App.Database.Entities;
public class WhitelistIp
{
public int Id { get; set; }
public string Ip { get; set; } = "";
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,59 @@
using System;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Moonlight.App.Database.Migrations
{
/// <inheritdoc />
public partial class AddIpRules : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "BlocklistIps",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn),
Ip = table.Column<string>(type: "longtext", nullable: false)
.Annotation("MySql:CharSet", "utf8mb4"),
ExpiresAt = table.Column<DateTime>(type: "datetime(6)", nullable: false),
Packets = table.Column<long>(type: "bigint", nullable: false),
CreatedAt = table.Column<DateTime>(type: "datetime(6)", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_BlocklistIps", x => x.Id);
})
.Annotation("MySql:CharSet", "utf8mb4");
migrationBuilder.CreateTable(
name: "WhitelistIps",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn),
Ip = table.Column<string>(type: "longtext", nullable: false)
.Annotation("MySql:CharSet", "utf8mb4")
},
constraints: table =>
{
table.PrimaryKey("PK_WhitelistIps", x => x.Id);
})
.Annotation("MySql:CharSet", "utf8mb4");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "BlocklistIps");
migrationBuilder.DropTable(
name: "WhitelistIps");
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,117 @@
using System;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Moonlight.App.Database.Migrations
{
/// <inheritdoc />
public partial class AddNewTicketModels : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Tickets",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn),
IssueTopic = table.Column<string>(type: "longtext", nullable: false)
.Annotation("MySql:CharSet", "utf8mb4"),
IssueDescription = table.Column<string>(type: "longtext", nullable: false)
.Annotation("MySql:CharSet", "utf8mb4"),
IssueTries = table.Column<string>(type: "longtext", nullable: false)
.Annotation("MySql:CharSet", "utf8mb4"),
CreatedById = table.Column<int>(type: "int", nullable: false),
AssignedToId = table.Column<int>(type: "int", nullable: true),
Priority = table.Column<int>(type: "int", nullable: false),
Status = table.Column<int>(type: "int", nullable: false),
Subject = table.Column<int>(type: "int", nullable: false),
SubjectId = table.Column<int>(type: "int", nullable: false),
CreatedAt = table.Column<DateTime>(type: "datetime(6)", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Tickets", x => x.Id);
table.ForeignKey(
name: "FK_Tickets_Users_AssignedToId",
column: x => x.AssignedToId,
principalTable: "Users",
principalColumn: "Id");
table.ForeignKey(
name: "FK_Tickets_Users_CreatedById",
column: x => x.CreatedById,
principalTable: "Users",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
})
.Annotation("MySql:CharSet", "utf8mb4");
migrationBuilder.CreateTable(
name: "TicketMessages",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn),
Content = table.Column<string>(type: "longtext", nullable: false)
.Annotation("MySql:CharSet", "utf8mb4"),
AttachmentUrl = table.Column<string>(type: "longtext", nullable: true)
.Annotation("MySql:CharSet", "utf8mb4"),
SenderId = table.Column<int>(type: "int", nullable: true),
IsSystemMessage = table.Column<bool>(type: "tinyint(1)", nullable: false),
IsEdited = table.Column<bool>(type: "tinyint(1)", nullable: false),
IsSupportMessage = table.Column<bool>(type: "tinyint(1)", nullable: false),
CreatedAt = table.Column<DateTime>(type: "datetime(6)", nullable: false),
UpdatedAt = table.Column<DateTime>(type: "datetime(6)", nullable: false),
TicketId = table.Column<int>(type: "int", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_TicketMessages", x => x.Id);
table.ForeignKey(
name: "FK_TicketMessages_Tickets_TicketId",
column: x => x.TicketId,
principalTable: "Tickets",
principalColumn: "Id");
table.ForeignKey(
name: "FK_TicketMessages_Users_SenderId",
column: x => x.SenderId,
principalTable: "Users",
principalColumn: "Id");
})
.Annotation("MySql:CharSet", "utf8mb4");
migrationBuilder.CreateIndex(
name: "IX_TicketMessages_SenderId",
table: "TicketMessages",
column: "SenderId");
migrationBuilder.CreateIndex(
name: "IX_TicketMessages_TicketId",
table: "TicketMessages",
column: "TicketId");
migrationBuilder.CreateIndex(
name: "IX_Tickets_AssignedToId",
table: "Tickets",
column: "AssignedToId");
migrationBuilder.CreateIndex(
name: "IX_Tickets_CreatedById",
table: "Tickets",
column: "CreatedById");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "TicketMessages");
migrationBuilder.DropTable(
name: "Tickets");
}
}
}

View File

@@ -19,6 +19,30 @@ namespace Moonlight.App.Database.Migrations
.HasAnnotation("ProductVersion", "7.0.3") .HasAnnotation("ProductVersion", "7.0.3")
.HasAnnotation("Relational:MaxIdentifierLength", 64); .HasAnnotation("Relational:MaxIdentifierLength", 64);
modelBuilder.Entity("Moonlight.App.Database.Entities.BlocklistIp", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<DateTime>("CreatedAt")
.HasColumnType("datetime(6)");
b.Property<DateTime>("ExpiresAt")
.HasColumnType("datetime(6)");
b.Property<string>("Ip")
.IsRequired()
.HasColumnType("longtext");
b.Property<long>("Packets")
.HasColumnType("bigint");
b.HasKey("Id");
b.ToTable("BlocklistIps");
});
modelBuilder.Entity("Moonlight.App.Database.Entities.CloudPanel", b => modelBuilder.Entity("Moonlight.App.Database.Entities.CloudPanel", b =>
{ {
b.Property<int>("Id") b.Property<int>("Id")
@@ -690,6 +714,97 @@ namespace Moonlight.App.Database.Migrations
b.ToTable("SupportChatMessages"); b.ToTable("SupportChatMessages");
}); });
modelBuilder.Entity("Moonlight.App.Database.Entities.Ticket", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<int?>("AssignedToId")
.HasColumnType("int");
b.Property<DateTime>("CreatedAt")
.HasColumnType("datetime(6)");
b.Property<int>("CreatedById")
.HasColumnType("int");
b.Property<string>("IssueDescription")
.IsRequired()
.HasColumnType("longtext");
b.Property<string>("IssueTopic")
.IsRequired()
.HasColumnType("longtext");
b.Property<string>("IssueTries")
.IsRequired()
.HasColumnType("longtext");
b.Property<int>("Priority")
.HasColumnType("int");
b.Property<int>("Status")
.HasColumnType("int");
b.Property<int>("Subject")
.HasColumnType("int");
b.Property<int>("SubjectId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("AssignedToId");
b.HasIndex("CreatedById");
b.ToTable("Tickets");
});
modelBuilder.Entity("Moonlight.App.Database.Entities.TicketMessage", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<string>("AttachmentUrl")
.HasColumnType("longtext");
b.Property<string>("Content")
.IsRequired()
.HasColumnType("longtext");
b.Property<DateTime>("CreatedAt")
.HasColumnType("datetime(6)");
b.Property<bool>("IsEdited")
.HasColumnType("tinyint(1)");
b.Property<bool>("IsSupportMessage")
.HasColumnType("tinyint(1)");
b.Property<bool>("IsSystemMessage")
.HasColumnType("tinyint(1)");
b.Property<int?>("SenderId")
.HasColumnType("int");
b.Property<int?>("TicketId")
.HasColumnType("int");
b.Property<DateTime>("UpdatedAt")
.HasColumnType("datetime(6)");
b.HasKey("Id");
b.HasIndex("SenderId");
b.HasIndex("TicketId");
b.ToTable("TicketMessages");
});
modelBuilder.Entity("Moonlight.App.Database.Entities.User", b => modelBuilder.Entity("Moonlight.App.Database.Entities.User", b =>
{ {
b.Property<int>("Id") b.Property<int>("Id")
@@ -842,6 +957,21 @@ namespace Moonlight.App.Database.Migrations
b.ToTable("WebSpaces"); b.ToTable("WebSpaces");
}); });
modelBuilder.Entity("Moonlight.App.Database.Entities.WhitelistIp", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<string>("Ip")
.IsRequired()
.HasColumnType("longtext");
b.HasKey("Id");
b.ToTable("WhitelistIps");
});
modelBuilder.Entity("Moonlight.App.Database.Entities.DdosAttack", b => modelBuilder.Entity("Moonlight.App.Database.Entities.DdosAttack", b =>
{ {
b.HasOne("Moonlight.App.Database.Entities.Node", "Node") b.HasOne("Moonlight.App.Database.Entities.Node", "Node")
@@ -1000,6 +1130,36 @@ namespace Moonlight.App.Database.Migrations
b.Navigation("Sender"); b.Navigation("Sender");
}); });
modelBuilder.Entity("Moonlight.App.Database.Entities.Ticket", b =>
{
b.HasOne("Moonlight.App.Database.Entities.User", "AssignedTo")
.WithMany()
.HasForeignKey("AssignedToId");
b.HasOne("Moonlight.App.Database.Entities.User", "CreatedBy")
.WithMany()
.HasForeignKey("CreatedById")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("AssignedTo");
b.Navigation("CreatedBy");
});
modelBuilder.Entity("Moonlight.App.Database.Entities.TicketMessage", b =>
{
b.HasOne("Moonlight.App.Database.Entities.User", "Sender")
.WithMany()
.HasForeignKey("SenderId");
b.HasOne("Moonlight.App.Database.Entities.Ticket", null)
.WithMany("Messages")
.HasForeignKey("TicketId");
b.Navigation("Sender");
});
modelBuilder.Entity("Moonlight.App.Database.Entities.User", b => modelBuilder.Entity("Moonlight.App.Database.Entities.User", b =>
{ {
b.HasOne("Moonlight.App.Database.Entities.Subscription", "CurrentSubscription") b.HasOne("Moonlight.App.Database.Entities.Subscription", "CurrentSubscription")
@@ -1055,6 +1215,11 @@ namespace Moonlight.App.Database.Migrations
b.Navigation("Variables"); b.Navigation("Variables");
}); });
modelBuilder.Entity("Moonlight.App.Database.Entities.Ticket", b =>
{
b.Navigation("Messages");
});
modelBuilder.Entity("Moonlight.App.Database.Entities.WebSpace", b => modelBuilder.Entity("Moonlight.App.Database.Entities.WebSpace", b =>
{ {
b.Navigation("Databases"); b.Navigation("Databases");

View File

@@ -113,13 +113,18 @@ public class EventSystem
return Task.CompletedTask; return Task.CompletedTask;
} }
public Task<T> WaitForEvent<T>(string id, object handle, Func<T, bool> filter) public Task<T> WaitForEvent<T>(string id, object handle, Func<T, bool>? filter = null)
{ {
var taskCompletionSource = new TaskCompletionSource<T>(); var taskCompletionSource = new TaskCompletionSource<T>();
Func<T, Task> action = async data => Func<T, Task> action = async data =>
{ {
if (filter.Invoke(data)) if (filter == null)
{
taskCompletionSource.SetResult(data);
await Off(id, handle);
}
else if(filter.Invoke(data))
{ {
taskCompletionSource.SetResult(data); taskCompletionSource.SetResult(data);
await Off(id, handle); await Off(id, handle);

View File

@@ -0,0 +1,119 @@
using System.Diagnostics;
using System.IO.Compression;
using Microsoft.EntityFrameworkCore;
using Moonlight.App.Database;
using Moonlight.App.Services;
using MySql.Data.MySqlClient;
namespace Moonlight.App.Helpers;
public class BackupHelper
{
public async Task CreateBackup(string path)
{
Logger.Info("Started moonlight backup creation");
Logger.Info($"This backup will be saved to '{path}'");
var stopWatch = new Stopwatch();
stopWatch.Start();
var cachePath = PathBuilder.Dir("storage", "backups", "cache");
Directory.CreateDirectory(cachePath);
//
// Exporting database
//
Logger.Info("Exporting database");
var configService = new ConfigService(new());
var dataContext = new DataContext(configService);
await using MySqlConnection conn = new MySqlConnection(dataContext.Database.GetConnectionString());
await using MySqlCommand cmd = new MySqlCommand();
using MySqlBackup mb = new MySqlBackup(cmd);
cmd.Connection = conn;
await conn.OpenAsync();
mb.ExportToFile(PathBuilder.File(cachePath, "database.sql"));
await conn.CloseAsync();
//
// Saving config
//
Logger.Info("Saving configuration");
File.Copy(
PathBuilder.File("storage", "configs", "config.json"),
PathBuilder.File(cachePath, "config.json"));
//
// Saving all storage items needed to restore the panel
//
Logger.Info("Saving resources");
CopyDirectory(
PathBuilder.Dir("storage", "resources"),
PathBuilder.Dir(cachePath, "resources"));
Logger.Info("Saving logs");
CopyDirectory(
PathBuilder.Dir("storage", "logs"),
PathBuilder.Dir(cachePath, "logs"));
Logger.Info("Saving uploads");
CopyDirectory(
PathBuilder.Dir("storage", "uploads"),
PathBuilder.Dir(cachePath, "uploads"));
//
// Compressing the backup to a single file
//
Logger.Info("Compressing");
ZipFile.CreateFromDirectory(cachePath,
path,
CompressionLevel.Fastest,
false);
Directory.Delete(cachePath, true);
stopWatch.Stop();
Logger.Info($"Backup successfully created. Took {stopWatch.Elapsed.TotalSeconds} seconds");
}
private void CopyDirectory(string sourceDirName, string destDirName, bool copySubDirs = true)
{
DirectoryInfo dir = new DirectoryInfo(sourceDirName);
if (!dir.Exists)
{
throw new DirectoryNotFoundException($"Source directory does not exist or could not be found: {sourceDirName}");
}
if (!Directory.Exists(destDirName))
{
Directory.CreateDirectory(destDirName);
}
FileInfo[] files = dir.GetFiles();
foreach (FileInfo file in files)
{
string tempPath = Path.Combine(destDirName, file.Name);
file.CopyTo(tempPath, false);
}
if (copySubDirs)
{
DirectoryInfo[] dirs = dir.GetDirectories();
foreach (DirectoryInfo subdir in dirs)
{
string tempPath = Path.Combine(destDirName, subdir.Name);
CopyDirectory(subdir.FullName, tempPath, copySubDirs);
}
}
}
}

View File

@@ -0,0 +1,56 @@
namespace Moonlight.App.Helpers;
public class ByteSizeValue
{
public long Bytes { get; set; }
public long KiloBytes
{
get => Bytes / 1024;
set => Bytes = value * 1024;
}
public long MegaBytes
{
get => KiloBytes / 1024;
set => KiloBytes = value * 1024;
}
public long GigaBytes
{
get => MegaBytes / 1024;
set => MegaBytes = value * 1024;
}
public static ByteSizeValue FromBytes(long bytes)
{
return new()
{
Bytes = bytes
};
}
public static ByteSizeValue FromKiloBytes(long kiloBytes)
{
return new()
{
KiloBytes = kiloBytes
};
}
public static ByteSizeValue FromMegaBytes(long megaBytes)
{
return new()
{
MegaBytes = megaBytes
};
}
public static ByteSizeValue FromGigaBytes(long gigaBytes)
{
return new()
{
GigaBytes = gigaBytes
};
}
}

View File

@@ -0,0 +1,12 @@
using Microsoft.AspNetCore.Components;
namespace Moonlight.App.Helpers;
public class ComponentHelper
{
public static RenderFragment FromType(Type type) => builder =>
{
builder.OpenComponent(0, type);
builder.CloseComponent();
};
}

View File

@@ -45,7 +45,18 @@ public class DatabaseCheckupService
{ {
Logger.Info($"{migrations.Length} migrations pending. Updating now"); Logger.Info($"{migrations.Length} migrations pending. Updating now");
await BackupDatabase(); try
{
var backupHelper = new BackupHelper();
await backupHelper.CreateBackup(
PathBuilder.File("storage", "backups", $"{new DateTimeOffset(DateTime.UtcNow).ToUnixTimeMilliseconds()}.zip"));
}
catch (Exception e)
{
Logger.Fatal("Unable to create backup");
Logger.Fatal(e);
Logger.Fatal("Moonlight will continue to start and apply the migrations without a backup");
}
Logger.Info("Applying migrations"); Logger.Info("Applying migrations");
@@ -58,53 +69,4 @@ public class DatabaseCheckupService
Logger.Info("Database is up-to-date. No migrations have been performed"); Logger.Info("Database is up-to-date. No migrations have been performed");
} }
} }
public async Task BackupDatabase()
{
Logger.Info("Creating backup from database");
var configService = new ConfigService(new StorageService());
var dateTimeService = new DateTimeService();
var config = configService.Get().Moonlight.Database;
var connectionString = $"host={config.Host};" +
$"port={config.Port};" +
$"database={config.Database};" +
$"uid={config.Username};" +
$"pwd={config.Password}";
string file = PathBuilder.File("storage", "backups", $"{dateTimeService.GetCurrentUnix()}-mysql.sql");
Logger.Info($"Saving it to: {file}");
Logger.Info("Starting backup...");
try
{
var sw = new Stopwatch();
sw.Start();
await using MySqlConnection conn = new MySqlConnection(connectionString);
await using MySqlCommand cmd = new MySqlCommand();
using MySqlBackup mb = new MySqlBackup(cmd);
cmd.Connection = conn;
await conn.OpenAsync();
mb.ExportToFile(file);
await conn.CloseAsync();
sw.Stop();
Logger.Info($"Done. {sw.Elapsed.TotalSeconds}s");
}
catch (Exception e)
{
Logger.Fatal("-----------------------------------------------");
Logger.Fatal("Unable to create backup for moonlight database");
Logger.Fatal("Moonlight will start anyways in 30 seconds");
Logger.Fatal("-----------------------------------------------");
Logger.Fatal(e);
Thread.Sleep(TimeSpan.FromSeconds(30));
}
}
} }

View File

@@ -110,15 +110,15 @@ public class HostFileAccess : FileAccess
if (fileData.IsFile) if (fileData.IsFile)
File.Delete(currhp + fileData.Name); File.Delete(currhp + fileData.Name);
else else
Directory.Delete(currhp + fileData.Name); Directory.Delete(currhp + fileData.Name, true);
} }
public override async Task Move(FileData fileData, string newPath) public override async Task Move(FileData fileData, string newPath)
{ {
if (fileData.IsFile) if (fileData.IsFile)
File.Move(currhp + fileData.Name, newPath); File.Move(currhp + fileData.Name, BasePath + newPath);
else else
Directory.Move(currhp + fileData.Name, newPath); Directory.Move(currhp + fileData.Name, BasePath + newPath);
} }
public override Task Compress(params FileData[] files) public override Task Compress(params FileData[] files)

View File

@@ -43,19 +43,22 @@ public class WingsFileAccess : FileAccess
$"api/servers/{Server.Uuid}/files/list-directory?directory={CurrentPath}" $"api/servers/{Server.Uuid}/files/list-directory?directory={CurrentPath}"
); );
var x = new List<FileData>(); var result = new List<FileData>();
foreach (var response in res) foreach (var resGrouped in res.GroupBy(x => x.Directory))
{ {
x.Add(new() foreach (var resItem in resGrouped.OrderBy(x => x.Name))
{ {
Name = response.Name, result.Add(new()
Size = response.File ? response.Size : 0, {
IsFile = response.File, Name = resItem.Name,
Size = resItem.File ? resItem.Size : 0,
IsFile = resItem.File,
}); });
} }
}
return x.ToArray(); return result.ToArray();
} }
public override Task Cd(string dir) public override Task Cd(string dir)

View File

@@ -1,4 +1,5 @@
using System.Text; using System.Text;
using Microsoft.AspNetCore.Components;
using Moonlight.App.Services; using Moonlight.App.Services;
namespace Moonlight.App.Helpers; namespace Moonlight.App.Helpers;
@@ -156,11 +157,47 @@ public static class Formatter
} }
} }
public static double BytesToGb(long bytes) public static double CalculateAverage(List<double> values)
{ {
const double gbMultiplier = 1024 * 1024 * 1024; // 1 GB = 1024 MB * 1024 KB * 1024 B if (values == null || values.Count == 0)
{
throw new ArgumentException("The list cannot be null or empty.");
}
double gigabytes = (double)bytes / gbMultiplier; double sum = 0;
return gigabytes; foreach (double value in values)
{
sum += value;
}
return sum / values.Count;
}
public static double CalculatePercentage(double part, double total)
{
if (total == 0)
{
return 0;
}
return (part / total) * 100;
}
public static RenderFragment FormatLineBreaks(string content)
{
return builder =>
{
int i = 0;
var arr = content.Split("\n", StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
foreach (var line in arr)
{
builder.AddContent(i, line);
if (i++ != arr.Length - 1)
{
builder.AddMarkupContent(i, "<br/>");
}
}
};
} }
} }

View File

@@ -43,4 +43,48 @@ public static class StringHelper
return firstChar + restOfString; return firstChar + restOfString;
} }
public static string CutInHalf(string input)
{
if (string.IsNullOrEmpty(input))
return input;
int length = input.Length;
int halfLength = length / 2;
return input.Substring(0, halfLength);
}
public static bool EndsInOneOf(string suffix, IEnumerable<string> strings)
{
foreach (string str in strings)
{
if (suffix.EndsWith(str))
{
return true;
}
}
return false;
}
public static bool ContainsOneOf(string textToSearch, IEnumerable<string> strings, out string foundText)
{
foreach (string str in strings)
{
if (textToSearch.Contains(str))
{
foundText = str;
return true;
}
}
foundText = "";
return false;
}
public static bool ContainsOneOf(string textToSearch, IEnumerable<string> strings)
{
return ContainsOneOf(textToSearch, strings, out _);
}
} }

View File

@@ -218,6 +218,16 @@ public class WingsConsole : IDisposable
break; break;
case "install output": case "install output":
if (ServerState != ServerState.Installing)
{
// Because wings is sending "install output" events BEFORE
// sending the "install started" event,
// we need to set the install state here
// See https://github.com/pterodactyl/panel/issues/4853
// for more details
//await UpdateServerState(ServerState.Installing);
}
foreach (var line in eventData.Args) foreach (var line in eventData.Args)
{ {
await SaveMessage(line); await SaveMessage(line);

View File

@@ -61,6 +61,10 @@ public class WingsServerConverter
.First(x => x.Id == server.Image.Id); .First(x => x.Id == server.Image.Id);
// Container // Container
if(server.DockerImageIndex >= image.DockerImages.Count() || server.DockerImageIndex == -1)
wingsServer.Settings.Container.Image = image.DockerImages.Last().Name;
else
wingsServer.Settings.Container.Image = image.DockerImages[server.DockerImageIndex].Name; wingsServer.Settings.Container.Image = image.DockerImages[server.DockerImageIndex].Name;
// Egg // Egg

View File

@@ -3,6 +3,7 @@ using Moonlight.App.Database.Entities;
using Moonlight.App.Events; using Moonlight.App.Events;
using Moonlight.App.Http.Requests.Daemon; using Moonlight.App.Http.Requests.Daemon;
using Moonlight.App.Repositories; using Moonlight.App.Repositories;
using Moonlight.App.Services.Background;
namespace Moonlight.App.Http.Controllers.Api.Remote; namespace Moonlight.App.Http.Controllers.Api.Remote;
@@ -10,19 +11,17 @@ namespace Moonlight.App.Http.Controllers.Api.Remote;
[Route("api/remote/ddos")] [Route("api/remote/ddos")]
public class DdosController : Controller public class DdosController : Controller
{ {
private readonly NodeRepository NodeRepository; private readonly Repository<Node> NodeRepository;
private readonly EventSystem Event; private readonly DdosProtectionService DdosProtectionService;
private readonly DdosAttackRepository DdosAttackRepository;
public DdosController(NodeRepository nodeRepository, EventSystem eventSystem, DdosAttackRepository ddosAttackRepository) public DdosController(Repository<Node> nodeRepository, DdosProtectionService ddosProtectionService)
{ {
NodeRepository = nodeRepository; NodeRepository = nodeRepository;
Event = eventSystem; DdosProtectionService = ddosProtectionService;
DdosAttackRepository = ddosAttackRepository;
} }
[HttpPost("update")] [HttpPost("start")]
public async Task<ActionResult> Update([FromBody] DdosStatus ddosStatus) public async Task<ActionResult> Start([FromBody] DdosStart ddosStart)
{ {
var tokenData = Request.Headers.Authorization.ToString().Replace("Bearer ", ""); var tokenData = Request.Headers.Authorization.ToString().Replace("Bearer ", "");
var id = tokenData.Split(".")[0]; var id = tokenData.Split(".")[0];
@@ -36,17 +35,25 @@ public class DdosController : Controller
if (token != node.Token) if (token != node.Token)
return Unauthorized(); return Unauthorized();
var ddosAttack = new DdosAttack() await DdosProtectionService.ProcessDdosSignal(ddosStart.Ip, ddosStart.Packets);
return Ok();
}
[HttpPost("stop")]
public async Task<ActionResult> Stop([FromBody] DdosStop ddosStop)
{ {
Ongoing = ddosStatus.Ongoing, var tokenData = Request.Headers.Authorization.ToString().Replace("Bearer ", "");
Data = ddosStatus.Data, var id = tokenData.Split(".")[0];
Ip = ddosStatus.Ip, var token = tokenData.Split(".")[1];
Node = node
};
ddosAttack = DdosAttackRepository.Add(ddosAttack); var node = NodeRepository.Get().FirstOrDefault(x => x.TokenId == id);
await Event.Emit("node.ddos", ddosAttack); if (node == null)
return NotFound();
if (token != node.Token)
return Unauthorized();
return Ok(); return Ok();
} }

View File

@@ -0,0 +1,33 @@
using Microsoft.AspNetCore.Mvc;
using Moonlight.App.Events;
using Moonlight.App.Services;
namespace Moonlight.App.Http.Controllers.WellKnown;
[ApiController]
[Route(".well-known/acme-challenge")]
public class AcmeController : Controller
{
private readonly LetsEncryptService LetsEncryptService;
private readonly EventSystem Event;
public AcmeController(LetsEncryptService letsEncryptService, EventSystem eventSystem)
{
LetsEncryptService = letsEncryptService;
Event = eventSystem;
}
[HttpGet("{token}")]
public async Task<ActionResult> Get([FromRoute] string token)
{
if (string.IsNullOrEmpty(LetsEncryptService.HttpChallenge) || string.IsNullOrEmpty(LetsEncryptService.HttpChallengeToken))
return Problem();
if (string.IsNullOrEmpty(token) || LetsEncryptService.HttpChallengeToken != token)
return Problem();
await Event.Emit("letsEncrypt.challengeFetched");
return Ok(LetsEncryptService.HttpChallenge);
}
}

View File

@@ -0,0 +1,7 @@
namespace Moonlight.App.Http.Requests.Daemon;
public class DdosStart
{
public string Ip { get; set; } = "";
public long Packets { get; set; }
}

View File

@@ -1,8 +0,0 @@
namespace Moonlight.App.Http.Requests.Daemon;
public class DdosStatus
{
public bool Ongoing { get; set; }
public long Data { get; set; }
public string Ip { get; set; } = "";
}

View File

@@ -0,0 +1,7 @@
namespace Moonlight.App.Http.Requests.Daemon;
public class DdosStop
{
public string Ip { get; set; } = "";
public long Traffic { get; set; }
}

View File

@@ -0,0 +1,78 @@
using Moonlight.App.Database.Entities;
using Moonlight.App.Helpers;
using Moonlight.App.Models.Misc;
using Moonlight.App.Services;
namespace Moonlight.App.MalwareScans;
public class BadScriptsScan : MalwareScan
{
public override string Name => "BadScripts Scan";
public override string Description => "This scanner tries to find scripts like proxies or other bad stuff";
public async override Task<MalwareScanResult?> Scan(Server server, IServiceProvider serviceProvider)
{
var serverService = serviceProvider.GetRequiredService<ServerService>();
var fileAccess = await serverService.CreateFileAccess(server, null!);
string[] fileExtensions =
{
".py",
".js",
".json",
".txt",
".sh",
".env",
".md",
".html",
".htm"
};
string[] badWords =
{
"cloudscraper",
"shadowsocks",
"karma-ddos",
"quake",
"nuked by",
"nuke bot",
"t-e-s-tweb",
"nezha",
"rblxwild.com",
"proxyscrape",
"vless://",
"vmess://",
"trojan://",
"shadowrocket",
"urfate/afk-bot",
"token vc spammer",
"pretreer.com",
"madfutters.com",
"ultrafut",
"selfcord.py",
"https://github.com/go-gost/gost",
"nodejs-proxy"
};
var files = await fileAccess.Ls();
var filteredFiles = files.Where(x =>
StringHelper.EndsInOneOf(x.Name, fileExtensions));
foreach (var file in filteredFiles)
{
var content = await fileAccess.Read(file);
var processableContent = content.ToLower();
if (StringHelper.ContainsOneOf(processableContent, badWords, out string foundText))
{
return new()
{
Title = "Software which is not allowed",
Description = $"Found bad word in script '{file.Name}': '{foundText}'",
Author = "Marcel Baumgartner"
};
}
}
return null;
}
}

View File

@@ -0,0 +1,39 @@
using Moonlight.App.Database.Entities;
using Moonlight.App.Models.Misc;
using Moonlight.App.Services;
namespace Moonlight.App.MalwareScans;
public class FakePlayerPluginScan : MalwareScan
{
public override string Name => "Fake player plugin scan";
public override string Description => "This scan is a simple fake player plugin scan provided by moonlight";
public override async Task<MalwareScanResult?> Scan(Server server, IServiceProvider serviceProvider)
{
var serverService = serviceProvider.GetRequiredService<ServerService>();
var access = await serverService.CreateFileAccess(server, null!);
var fileElements = await access.Ls();
if (fileElements.Any(x => !x.IsFile && x.Name == "plugins")) // Check for plugins folder
{
await access.Cd("plugins");
fileElements = await access.Ls();
foreach (var fileElement in fileElements)
{
if (fileElement.Name.ToLower().Contains("fakeplayer"))
{
return new()
{
Title = "Fake player plugin",
Description = $"Suspicious plugin file: {fileElement.Name}",
Author = "Marcel Baumgartner"
};
}
}
}
return null;
}
}

View File

@@ -0,0 +1,37 @@
using Moonlight.App.Database.Entities;
using Moonlight.App.Models.Misc;
using Moonlight.App.Services;
namespace Moonlight.App.MalwareScans;
public class MinerJarScan : MalwareScan
{
public override string Name => "Miner jar scan";
public override string Description => "This scan is a simple miner jar scan provided by moonlight";
public override async Task<MalwareScanResult?> Scan(Server server, IServiceProvider serviceProvider)
{
var serverService = serviceProvider.GetRequiredService<ServerService>();
var access = await serverService.CreateFileAccess(server, null!);
var fileElements = await access.Ls();
if (fileElements.Any(x => x.Name == "libraries" && !x.IsFile))
{
await access.Cd("libraries");
fileElements = await access.Ls();
if (fileElements.Any(x => x.Name == "jdk" && !x.IsFile))
{
return new()
{
Title = "Found Miner",
Description = "Detected suspicious library directory which may contain a script for miners",
Author = "Marcel Baumgartner"
};
}
}
return null;
}
}

View File

@@ -0,0 +1,21 @@
using System.ComponentModel.DataAnnotations;
using Moonlight.App.Models.Misc;
namespace Moonlight.App.Models.Forms;
public class CreateTicketDataModel
{
[Required(ErrorMessage = "You need to specify a issue topic")]
[MinLength(5, ErrorMessage = "The issue topic needs to be longer than 5 characters")]
public string IssueTopic { get; set; }
[Required(ErrorMessage = "You need to specify a issue description")]
[MinLength(10, ErrorMessage = "The issue description needs to be longer than 10 characters")]
public string IssueDescription { get; set; }
[Required(ErrorMessage = "You need to specify your tries to solve this issue")]
public string IssueTries { get; set; }
public TicketSubject Subject { get; set; }
public int SubjectId { get; set; }
}

View File

@@ -0,0 +1,10 @@
using Moonlight.App.Database.Entities;
namespace Moonlight.App.Models.Misc;
public abstract class MalwareScan
{
public abstract string Name { get; }
public abstract string Description { get; }
public abstract Task<MalwareScanResult?> Scan(Server server, IServiceProvider serviceProvider);
}

View File

@@ -2,7 +2,7 @@
public class MalwareScanResult public class MalwareScanResult
{ {
public string Title { get; set; } = ""; public string Title { get; set; }
public string Description { get; set; } = ""; public string Description { get; set; } = "";
public string Author { get; set; } = ""; public string Author { get; set; } = "";
} }

View File

@@ -0,0 +1,6 @@
namespace Moonlight.App.Models.Misc;
public class OfficialMoonlightPlugin
{
public string Name { get; set; }
}

View File

@@ -0,0 +1,9 @@
namespace Moonlight.App.Models.Misc;
public enum TicketPriority
{
Low = 0,
Medium = 1,
High = 2,
Critical = 3
}

View File

@@ -0,0 +1,9 @@
namespace Moonlight.App.Models.Misc;
public enum TicketStatus
{
Closed = 0,
Open = 1,
WaitingForUser = 2,
Pending = 3
}

View File

@@ -0,0 +1,9 @@
namespace Moonlight.App.Models.Misc;
public enum TicketSubject
{
Webspace = 0,
Server = 1,
Domain = 2,
Other = 3
}

View File

@@ -16,6 +16,13 @@ public static class Permissions
Description = "View statistical information about the moonlight instance" Description = "View statistical information about the moonlight instance"
}; };
public static Permission AdminSysPlugins = new()
{
Index = 2,
Name = "Admin system plugins",
Description = "View and install plugins"
};
public static Permission AdminDomains = new() public static Permission AdminDomains = new()
{ {
Index = 4, Index = 4,
@@ -44,13 +51,6 @@ public static class Permissions
Description = "Create a new shared domain in the admin area" Description = "Create a new shared domain in the admin area"
}; };
public static Permission AdminNodeDdos = new()
{
Index = 8,
Name = "Admin Node DDoS",
Description = "Manage DDoS protection for nodes in the admin area"
};
public static Permission AdminNodeEdit = new() public static Permission AdminNodeEdit = new()
{ {
Index = 9, Index = 9,
@@ -401,6 +401,27 @@ public static class Permissions
Description = "View the security logs" Description = "View the security logs"
}; };
public static Permission AdminSecurityDdos = new()
{
Index = 59,
Name = "Admin security ddos",
Description = "Manage the integrated ddos protection"
};
public static Permission AdminChangelog = new()
{
Index = 60,
Name = "Admin changelog",
Description = "View the changelog"
};
public static Permission AdminStatisticsLive = new()
{
Index = 61,
Name = "Admin statistics live",
Description = "View the live statistics"
};
public static Permission? FromString(string name) public static Permission? FromString(string name)
{ {
var type = typeof(Permissions); var type = typeof(Permissions);

View File

@@ -0,0 +1,17 @@
using Moonlight.App.Models.Misc;
using Moonlight.App.Plugin.UI.Servers;
using Moonlight.App.Plugin.UI.Webspaces;
namespace Moonlight.App.Plugin;
public abstract class MoonlightPlugin
{
public string Name { get; set; } = "N/A";
public string Author { get; set; } = "N/A";
public string Version { get; set; } = "N/A";
public Func<ServerPageContext, Task>? OnBuildServerPage { get; set; }
public Func<WebspacePageContext, Task>? OnBuildWebspacePage { get; set; }
public Func<IServiceCollection, Task>? OnBuildServices { get; set; }
public Func<List<MalwareScan>, Task<List<MalwareScan>>>? OnBuildMalwareScans { get; set; }
}

View File

@@ -0,0 +1,12 @@
using Moonlight.App.Database.Entities;
namespace Moonlight.App.Plugin.UI.Servers;
public class ServerPageContext
{
public List<ServerTab> Tabs { get; set; } = new();
public List<ServerSetting> Settings { get; set; } = new();
public Server Server { get; set; }
public User User { get; set; }
public string[] ImageTags { get; set; }
}

View File

@@ -0,0 +1,9 @@
using Microsoft.AspNetCore.Components;
namespace Moonlight.App.Plugin.UI.Servers;
public class ServerSetting
{
public string Name { get; set; }
public RenderFragment Component { get; set; }
}

View File

@@ -0,0 +1,11 @@
using Microsoft.AspNetCore.Components;
namespace Moonlight.App.Plugin.UI.Servers;
public class ServerTab
{
public string Name { get; set; }
public string Route { get; set; }
public string Icon { get; set; }
public RenderFragment Component { get; set; }
}

View File

@@ -0,0 +1,10 @@
using Moonlight.App.Database.Entities;
namespace Moonlight.App.Plugin.UI.Webspaces;
public class WebspacePageContext
{
public List<WebspaceTab> Tabs { get; set; } = new();
public User User { get; set; }
public WebSpace WebSpace { get; set; }
}

View File

@@ -0,0 +1,10 @@
using Microsoft.AspNetCore.Components;
namespace Moonlight.App.Plugin.UI.Webspaces;
public class WebspaceTab
{
public string Name { get; set; } = "N/A";
public string Route { get; set; } = "/";
public RenderFragment Component { get; set; }
}

View File

@@ -93,14 +93,14 @@ public class CleanupService
Logger.Debug($"Max CPU: {maxCpu}"); Logger.Debug($"Max CPU: {maxCpu}");
executeCleanup = true; executeCleanup = true;
} }
else if (Formatter.BytesToGb(memoryMetrics.Total) - Formatter.BytesToGb(memoryMetrics.Used) < else if (ByteSizeValue.FromKiloBytes(memoryMetrics.Total).MegaBytes - ByteSizeValue.FromKiloBytes(memoryMetrics.Used).MegaBytes <
minMemory / 1024D) minMemory)
{ {
Logger.Debug($"{node.Name}: Memory Usage is too high"); Logger.Debug($"{node.Name}: Memory Usage is too high");
Logger.Debug($"Memory (Total): {Formatter.BytesToGb(memoryMetrics.Total)}"); Logger.Debug($"Memory (Total): {ByteSizeValue.FromKiloBytes(memoryMetrics.Total).MegaBytes}");
Logger.Debug($"Memory (Used): {Formatter.BytesToGb(memoryMetrics.Used)}"); Logger.Debug($"Memory (Used): {ByteSizeValue.FromKiloBytes(memoryMetrics.Used).MegaBytes}");
Logger.Debug( Logger.Debug(
$"Memory (Free): {Formatter.BytesToGb(memoryMetrics.Total) - Formatter.BytesToGb(memoryMetrics.Used)}"); $"Memory (Free): {ByteSizeValue.FromKiloBytes(memoryMetrics.Total).MegaBytes - ByteSizeValue.FromKiloBytes(memoryMetrics.Used).MegaBytes}");
Logger.Debug($"Min Memory: {minMemory}"); Logger.Debug($"Min Memory: {minMemory}");
executeCleanup = true; executeCleanup = true;
} }

View File

@@ -0,0 +1,129 @@
using Moonlight.App.ApiClients.Daemon;
using Moonlight.App.Database.Entities;
using Moonlight.App.Events;
using Moonlight.App.Helpers;
using Moonlight.App.Repositories;
namespace Moonlight.App.Services.Background;
public class DdosProtectionService
{
private readonly IServiceScopeFactory ServiceScopeFactory;
public DdosProtectionService(IServiceScopeFactory serviceScopeFactory)
{
ServiceScopeFactory = serviceScopeFactory;
Task.Run(UnBlocker);
}
private async Task UnBlocker()
{
var periodicTimer = new PeriodicTimer(TimeSpan.FromMinutes(5));
while (true)
{
using var scope = ServiceScopeFactory.CreateScope();
var blocklistIpRepo = scope.ServiceProvider.GetRequiredService<Repository<BlocklistIp>>();
var ips = blocklistIpRepo
.Get()
.ToArray();
foreach (var ip in ips)
{
if (DateTime.UtcNow > ip.ExpiresAt)
{
blocklistIpRepo.Delete(ip);
}
}
var newCount = blocklistIpRepo
.Get()
.Count();
if (newCount != ips.Length)
{
await RebuildNodeFirewalls();
}
await periodicTimer.WaitForNextTickAsync();
}
}
public async Task RebuildNodeFirewalls()
{
using var scope = ServiceScopeFactory.CreateScope();
var blocklistIpRepo = scope.ServiceProvider.GetRequiredService<Repository<BlocklistIp>>();
var nodeRepo = scope.ServiceProvider.GetRequiredService<Repository<Node>>();
var nodeService = scope.ServiceProvider.GetRequiredService<NodeService>();
var ips = blocklistIpRepo
.Get()
.Select(x => x.Ip)
.ToArray();
foreach (var node in nodeRepo.Get().ToArray())
{
try
{
await nodeService.RebuildFirewall(node, ips);
}
catch (Exception e)
{
Logger.Warn($"Error rebuilding firewall on node {node.Name}");
Logger.Warn(e);
}
}
}
public async Task ProcessDdosSignal(string ip, long packets)
{
using var scope = ServiceScopeFactory.CreateScope();
var blocklistRepo = scope.ServiceProvider.GetRequiredService<Repository<BlocklistIp>>();
var whitelistRepo = scope.ServiceProvider.GetRequiredService<Repository<WhitelistIp>>();
var whitelistIps = whitelistRepo.Get().ToArray();
if(whitelistIps.Any(x => x.Ip == ip))
return;
var blocklistIps = blocklistRepo.Get().ToArray();
if(blocklistIps.Any(x => x.Ip == ip))
return;
await BlocklistIp(ip, packets);
}
public async Task BlocklistIp(string ip, long packets)
{
using var scope = ServiceScopeFactory.CreateScope();
var blocklistRepo = scope.ServiceProvider.GetRequiredService<Repository<BlocklistIp>>();
var configService = scope.ServiceProvider.GetRequiredService<ConfigService>();
var eventSystem = scope.ServiceProvider.GetRequiredService<EventSystem>();
var blocklistIp = blocklistRepo.Add(new()
{
Ip = ip,
Packets = packets,
ExpiresAt = DateTime.UtcNow.AddMinutes(configService.Get().Moonlight.Security.BlockIpDuration),
CreatedAt = DateTime.UtcNow
});
await RebuildNodeFirewalls();
await eventSystem.Emit("ddos.add", blocklistIp);
}
public async Task UnBlocklistIp(string ip)
{
using var scope = ServiceScopeFactory.CreateScope();
var blocklistRepo = scope.ServiceProvider.GetRequiredService<Repository<BlocklistIp>>();
var blocklist = blocklistRepo.Get().First(x => x.Ip == ip);
blocklistRepo.Delete(blocklist);
await RebuildNodeFirewalls();
}
}

View File

@@ -31,11 +31,11 @@ public class DiscordNotificationService
Client = new(config.WebHook); Client = new(config.WebHook);
AppUrl = configService.Get().Moonlight.AppUrl; AppUrl = configService.Get().Moonlight.AppUrl;
Event.On<User>("supportChat.new", this, OnNewSupportChat); Event.On<Ticket>("tickets.new", this, OnNewTicket);
Event.On<SupportChatMessage>("supportChat.message", this, OnSupportChatMessage); Event.On<Ticket>("tickets.status", this, OnTicketStatusUpdated);
Event.On<User>("supportChat.close", this, OnSupportChatClose);
Event.On<User>("user.rating", this, OnUserRated); Event.On<User>("user.rating", this, OnUserRated);
Event.On<User>("billing.completed", this, OnBillingCompleted); Event.On<User>("billing.completed", this, OnBillingCompleted);
Event.On<BlocklistIp>("ddos.add", this, OnIpBlockListed);
} }
else else
{ {
@@ -43,6 +43,36 @@ public class DiscordNotificationService
} }
} }
private async Task OnTicketStatusUpdated(Ticket ticket)
{
await SendNotification("", builder =>
{
builder.Title = "Ticket status has been updated";
builder.AddField("Issue topic", ticket.IssueTopic);
builder.AddField("Status", ticket.Status);
if (ticket.AssignedTo != null)
{
builder.AddField("Assigned to", $"{ticket.AssignedTo.FirstName} {ticket.AssignedTo.LastName}");
}
builder.Color = Color.Green;
builder.Url = $"{AppUrl}/admin/support/view/{ticket.Id}";
});
}
private async Task OnIpBlockListed(BlocklistIp blocklistIp)
{
await SendNotification("", builder =>
{
builder.Color = Color.Red;
builder.Title = "New ddos attack detected";
builder.AddField("IP", blocklistIp.Ip);
builder.AddField("Packets", blocklistIp.Packets);
});
}
private async Task OnBillingCompleted(User user) private async Task OnBillingCompleted(User user)
{ {
await SendNotification("", builder => await SendNotification("", builder =>
@@ -72,46 +102,14 @@ public class DiscordNotificationService
}); });
} }
private async Task OnSupportChatClose(User user) private async Task OnNewTicket(Ticket ticket)
{ {
await SendNotification("", builder => await SendNotification("", builder =>
{ {
builder.Title = "A new support chat has been marked as closed"; builder.Title = "A new ticket has been created";
builder.Color = Color.Red; builder.AddField("Issue topic", ticket.IssueTopic);
builder.AddField("Email", user.Email);
builder.AddField("Firstname", user.FirstName);
builder.AddField("Lastname", user.LastName);
builder.Url = $"{AppUrl}/admin/support/view/{user.Id}";
});
}
private async Task OnSupportChatMessage(SupportChatMessage message)
{
if(message.Sender == null)
return;
await SendNotification("", builder =>
{
builder.Title = "New message in support chat";
builder.Color = Color.Blue;
builder.AddField("Message", message.Content);
builder.Author = new EmbedAuthorBuilder()
.WithName($"{message.Sender.FirstName} {message.Sender.LastName}")
.WithIconUrl(ResourceService.Avatar(message.Sender));
builder.Url = $"{AppUrl}/admin/support/view/{message.Recipient.Id}";
});
}
private async Task OnNewSupportChat(User user)
{
await SendNotification("", builder =>
{
builder.Title = "A new support chat has been marked as active";
builder.Color = Color.Green; builder.Color = Color.Green;
builder.AddField("Email", user.Email); builder.Url = $"{AppUrl}/admin/support/view/{ticket.Id}";
builder.AddField("Firstname", user.FirstName);
builder.AddField("Lastname", user.LastName);
builder.Url = $"{AppUrl}/admin/support/view/{user.Id}";
}); });
} }

View File

@@ -0,0 +1,148 @@
using Moonlight.App.ApiClients.Daemon.Resources;
using Moonlight.App.Database.Entities;
using Moonlight.App.Events;
using Moonlight.App.Exceptions;
using Moonlight.App.Helpers;
using Moonlight.App.Models.Misc;
using Moonlight.App.Repositories;
namespace Moonlight.App.Services.Background;
public class MalwareBackgroundScanService
{
private readonly EventSystem Event;
private readonly IServiceScopeFactory ServiceScopeFactory;
public bool IsRunning => !ScanTask?.IsCompleted ?? false;
public bool ScanAllServers { get; set; }
public readonly Dictionary<Server, MalwareScanResult> ScanResults;
public string Status { get; private set; } = "N/A";
private Task? ScanTask;
public MalwareBackgroundScanService(IServiceScopeFactory serviceScopeFactory, EventSystem eventSystem)
{
ServiceScopeFactory = serviceScopeFactory;
Event = eventSystem;
ScanResults = new();
}
public Task Start()
{
if (IsRunning)
throw new DisplayException("Malware scan is already running");
ScanTask = Task.Run(Run);
return Task.CompletedTask;
}
private async Task Run()
{
// Clean results
Status = "Clearing last results";
await Event.Emit("malwareScan.status", IsRunning);
lock (ScanResults)
ScanResults.Clear();
await Event.Emit("malwareScan.result");
using var scope = ServiceScopeFactory.CreateScope();
var serverRepo = scope.ServiceProvider.GetRequiredService<Repository<Server>>();
var malwareScanService = scope.ServiceProvider.GetRequiredService<MalwareScanService>();
Status = "Fetching servers to scan";
await Event.Emit("malwareScan.status", IsRunning);
Server[] servers;
if (ScanAllServers)
servers = serverRepo.Get().ToArray();
else
servers = await GetOnlineServers();
// Perform scan
int i = 1;
foreach (var server in servers)
{
Status = $"[{i} / {servers.Length}] Scanning server {server.Name}";
await Event.Emit("malwareScan.status", IsRunning);
var result = await malwareScanService.Perform(server);
if (result != null)
{
lock (ScanResults)
{
ScanResults.Add(server, result);
}
await Event.Emit("malwareScan.result", server);
}
i++;
}
Task.Run(async () => // Because we use the task as the status indicator we need to notify the event system in a new task
{
await Task.Delay(TimeSpan.FromSeconds(5));
await Event.Emit("malwareScan.status", IsRunning);
});
}
private async Task<Server[]> GetOnlineServers()
{
using var scope = ServiceScopeFactory.CreateScope();
// Load services from di scope
var nodeRepo = scope.ServiceProvider.GetRequiredService<Repository<Node>>();
var serverRepo = scope.ServiceProvider.GetRequiredService<Repository<Server>>();
var nodeService = scope.ServiceProvider.GetRequiredService<NodeService>();
var nodes = nodeRepo.Get().ToArray();
var containers = new List<Container>();
// Fetch and summarize all running containers from all nodes
Logger.Verbose("Fetching and summarizing all running containers from all nodes");
Status = "Fetching and summarizing all running containers from all nodes";
await Event.Emit("malwareScan.status", IsRunning);
foreach (var node in nodes)
{
var metrics = await nodeService.GetDockerMetrics(node);
foreach (var container in metrics.Containers)
{
containers.Add(container);
}
}
var containerServerMapped = new Dictionary<Server, Container>();
// Map all the containers to their corresponding server if existing
Logger.Verbose("Mapping all the containers to their corresponding server if existing");
Status = "Mapping all the containers to their corresponding server if existing";
await Event.Emit("malwareScan.status", IsRunning);
foreach (var container in containers)
{
if (Guid.TryParse(container.Name, out Guid uuid))
{
var server = serverRepo
.Get()
.FirstOrDefault(x => x.Uuid == uuid);
if(server == null)
continue;
containerServerMapped.Add(server, container);
}
}
return containerServerMapped.Keys.ToArray();
}
}

View File

@@ -1,196 +0,0 @@
using Moonlight.App.ApiClients.Daemon.Resources;
using Moonlight.App.Database.Entities;
using Moonlight.App.Events;
using Moonlight.App.Exceptions;
using Moonlight.App.Helpers;
using Moonlight.App.Models.Misc;
using Moonlight.App.Repositories;
namespace Moonlight.App.Services.Background;
public class MalwareScanService
{
private Repository<Server> ServerRepository;
private Repository<Node> NodeRepository;
private NodeService NodeService;
private ServerService ServerService;
private readonly EventSystem Event;
private readonly IServiceScopeFactory ServiceScopeFactory;
public bool IsRunning { get; private set; }
public readonly Dictionary<Server, MalwareScanResult[]> ScanResults;
public string Status { get; private set; } = "N/A";
public MalwareScanService(IServiceScopeFactory serviceScopeFactory, EventSystem eventSystem)
{
ServiceScopeFactory = serviceScopeFactory;
Event = eventSystem;
ScanResults = new();
}
public Task Start()
{
if (IsRunning)
throw new DisplayException("Malware scan is already running");
Task.Run(Run);
return Task.CompletedTask;
}
private async Task Run()
{
IsRunning = true;
Status = "Clearing last results";
await Event.Emit("malwareScan.status", IsRunning);
lock (ScanResults)
{
ScanResults.Clear();
}
await Event.Emit("malwareScan.result");
using var scope = ServiceScopeFactory.CreateScope();
// Load services from di scope
NodeRepository = scope.ServiceProvider.GetRequiredService<Repository<Node>>();
ServerRepository = scope.ServiceProvider.GetRequiredService<Repository<Server>>();
NodeService = scope.ServiceProvider.GetRequiredService<NodeService>();
ServerService = scope.ServiceProvider.GetRequiredService<ServerService>();
var nodes = NodeRepository.Get().ToArray();
var containers = new List<Container>();
// Fetch and summarize all running containers from all nodes
Logger.Verbose("Fetching and summarizing all running containers from all nodes");
Status = "Fetching and summarizing all running containers from all nodes";
await Event.Emit("malwareScan.status", IsRunning);
foreach (var node in nodes)
{
var metrics = await NodeService.GetDockerMetrics(node);
foreach (var container in metrics.Containers)
{
containers.Add(container);
}
}
var containerServerMapped = new Dictionary<Server, Container>();
// Map all the containers to their corresponding server if existing
Logger.Verbose("Mapping all the containers to their corresponding server if existing");
Status = "Mapping all the containers to their corresponding server if existing";
await Event.Emit("malwareScan.status", IsRunning);
foreach (var container in containers)
{
if (Guid.TryParse(container.Name, out Guid uuid))
{
var server = ServerRepository
.Get()
.FirstOrDefault(x => x.Uuid == uuid);
if(server == null)
continue;
containerServerMapped.Add(server, container);
}
}
// Perform scan
var resultsMapped = new Dictionary<Server, MalwareScanResult[]>();
foreach (var mapping in containerServerMapped)
{
Logger.Verbose($"Scanning server {mapping.Key.Name} for malware");
Status = $"Scanning server {mapping.Key.Name} for malware";
await Event.Emit("malwareScan.status", IsRunning);
var results = await PerformScanOnServer(mapping.Key, mapping.Value);
if (results.Any())
{
resultsMapped.Add(mapping.Key, results);
Logger.Verbose($"{results.Length} findings on server {mapping.Key.Name}");
}
}
Logger.Verbose($"Scan complete. Detected {resultsMapped.Count} servers with findings");
IsRunning = false;
Status = $"Scan complete. Detected {resultsMapped.Count} servers with findings";
await Event.Emit("malwareScan.status", IsRunning);
lock (ScanResults)
{
foreach (var mapping in resultsMapped)
{
ScanResults.Add(mapping.Key, mapping.Value);
}
}
await Event.Emit("malwareScan.result");
}
private async Task<MalwareScanResult[]> PerformScanOnServer(Server server, Container container)
{
var results = new List<MalwareScanResult>();
// TODO: Move scans to an universal format / api
// Define scans here
async Task ScanSelfBot()
{
var access = await ServerService.CreateFileAccess(server, null!);
var fileElements = await access.Ls();
if (fileElements.Any(x => x.Name == "tokens.txt"))
{
results.Add(new ()
{
Title = "Found SelfBot",
Description = "Detected suspicious 'tokens.txt' file which may contain tokens for a selfbot",
Author = "Marcel Baumgartner"
});
}
}
async Task ScanFakePlayerPlugins()
{
var access = await ServerService.CreateFileAccess(server, null!);
var fileElements = await access.Ls();
if (fileElements.Any(x => !x.IsFile && x.Name == "plugins")) // Check for plugins folder
{
await access.Cd("plugins");
fileElements = await access.Ls();
foreach (var fileElement in fileElements)
{
if (fileElement.Name.ToLower().Contains("fake"))
{
results.Add(new()
{
Title = "Fake player plugin",
Description = $"Suspicious plugin file: {fileElement.Name}",
Author = "Marcel Baumgartner"
});
}
}
}
}
// Execute scans
await ScanSelfBot();
await ScanFakePlayerPlugins();
return results.ToArray();
}
}

View File

@@ -17,7 +17,6 @@ public class ConfigService
public ConfigService(StorageService storageService) public ConfigService(StorageService storageService)
{ {
StorageService = storageService; StorageService = storageService;
StorageService.EnsureCreated();
if (!string.IsNullOrEmpty(Environment.GetEnvironmentVariable("ML_CONFIG_PATH"))) if (!string.IsNullOrEmpty(Environment.GetEnvironmentVariable("ML_CONFIG_PATH")))
Path = Environment.GetEnvironmentVariable("ML_CONFIG_PATH")!; Path = Environment.GetEnvironmentVariable("ML_CONFIG_PATH")!;

View File

@@ -5,6 +5,7 @@ using CloudFlare.Client.Api.Parameters.Data;
using CloudFlare.Client.Api.Result; using CloudFlare.Client.Api.Result;
using CloudFlare.Client.Api.Zones; using CloudFlare.Client.Api.Zones;
using CloudFlare.Client.Api.Zones.DnsRecord; using CloudFlare.Client.Api.Zones.DnsRecord;
using CloudFlare.Client.Client.Zones;
using CloudFlare.Client.Enumerators; using CloudFlare.Client.Enumerators;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Moonlight.App.Database.Entities; using Moonlight.App.Database.Entities;
@@ -82,12 +83,27 @@ public class DomainService
if (!ConfigService.Get().Moonlight.Domains.Enable) if (!ConfigService.Get().Moonlight.Domains.Enable)
return Array.Empty<Zone>(); return Array.Empty<Zone>();
var domains = GetData( var domains = new List<Zone>();
await Client.Zones.GetAsync(new()
var initialResponse = await Client.Zones.GetAsync();
domains.AddRange(GetData(initialResponse));
// Check if there are more pages
while (initialResponse.ResultInfo.Page < initialResponse.ResultInfo.TotalPage)
{ {
AccountId = AccountId // Get the next page of data
}) var nextPageResponse = await Client.Zones.GetAsync(
displayOptions: new()
{
Page = initialResponse.ResultInfo.Page + 1
}
); );
var nextPageZones = GetData(nextPageResponse);
domains.AddRange(nextPageZones);
initialResponse = nextPageResponse;
}
var sharedDomains = SharedDomainRepository.Get().ToArray(); var sharedDomains = SharedDomainRepository.Get().ToArray();

View File

@@ -1,23 +1,24 @@
using Moonlight.App.Helpers; using Moonlight.App.Helpers;
using Octokit;
namespace Moonlight.App.Services.Files; namespace Moonlight.App.Services.Files;
public class StorageService public class StorageService
{ {
public StorageService() public async Task EnsureCreated()
{
EnsureCreated();
}
public void EnsureCreated()
{ {
Directory.CreateDirectory(PathBuilder.Dir("storage", "uploads")); Directory.CreateDirectory(PathBuilder.Dir("storage", "uploads"));
Directory.CreateDirectory(PathBuilder.Dir("storage", "configs")); Directory.CreateDirectory(PathBuilder.Dir("storage", "configs"));
Directory.CreateDirectory(PathBuilder.Dir("storage", "resources")); Directory.CreateDirectory(PathBuilder.Dir("storage", "resources"));
Directory.CreateDirectory(PathBuilder.Dir("storage", "backups")); Directory.CreateDirectory(PathBuilder.Dir("storage", "backups"));
Directory.CreateDirectory(PathBuilder.Dir("storage", "logs")); Directory.CreateDirectory(PathBuilder.Dir("storage", "logs"));
Directory.CreateDirectory(PathBuilder.Dir("storage", "plugins"));
Directory.CreateDirectory(PathBuilder.Dir("storage", "certs"));
if(IsEmpty(PathBuilder.Dir("storage", "resources"))) await UpdateResources();
return;
if (IsEmpty(PathBuilder.Dir("storage", "resources")))
{ {
Logger.Info("Default resources not found. Copying default resources"); Logger.Info("Default resources not found. Copying default resources");
@@ -38,10 +39,75 @@ public class StorageService
} }
} }
private async Task UpdateResources()
{
try
{
Logger.Info("Checking resources");
var client = new GitHubClient(
new ProductHeaderValue("Moonlight-Panel"));
var user = "Moonlight-Panel";
var repo = "Resources";
var resourcesDir = PathBuilder.Dir("storage", "resources");
async Task CopyDirectory(string dirPath, string localDir)
{
IReadOnlyList<RepositoryContent> contents;
if (string.IsNullOrEmpty(dirPath))
contents = await client.Repository.Content.GetAllContents(user, repo);
else
contents = await client.Repository.Content.GetAllContents(user, repo, dirPath);
foreach (var content in contents)
{
string localPath = Path.Combine(localDir, content.Name);
if (content.Type == ContentType.File)
{
if (content.Name.EndsWith(".gitattributes"))
continue;
if (File.Exists(localPath) && !content.Name.EndsWith(".lang"))
continue;
if (content.Name.EndsWith(".lang") && File.Exists(localPath) &&
new FileInfo(localPath).Length == content.Size)
continue;
var fileContent = await client.Repository.Content.GetRawContent(user, repo, content.Path);
Directory.CreateDirectory(localDir); // Ensure the directory exists
await File.WriteAllBytesAsync(localPath, fileContent);
Logger.Debug($"Synced file '{content.Path}'");
}
else if (content.Type == ContentType.Dir)
{
await CopyDirectory(content.Path, localPath);
}
}
}
await CopyDirectory("", resourcesDir);
}
catch (RateLimitExceededException)
{
Logger.Warn("Unable to sync resources due to your ip being rate-limited by github");
}
catch (Exception e)
{
Logger.Warn("Unable to sync resources");
Logger.Warn(e);
}
}
private bool IsEmpty(string path) private bool IsEmpty(string path)
{ {
return !Directory.EnumerateFileSystemEntries(path).Any(); return !Directory.EnumerateFileSystemEntries(path).Any();
} }
private static void CopyFilesRecursively(string sourcePath, string targetPath) private static void CopyFilesRecursively(string sourcePath, string targetPath)
{ {
//Now Create all of the directories //Now Create all of the directories
@@ -51,7 +117,7 @@ public class StorageService
} }
//Copy all the files & Replaces any files with the same name //Copy all the files & Replaces any files with the same name
foreach (string newPath in Directory.GetFiles(sourcePath, "*.*",SearchOption.AllDirectories)) foreach (string newPath in Directory.GetFiles(sourcePath, "*.*", SearchOption.AllDirectories))
{ {
File.Copy(newPath, newPath.Replace(sourcePath, targetPath), true); File.Copy(newPath, newPath.Replace(sourcePath, targetPath), true);
} }

View File

@@ -0,0 +1,91 @@
using Moonlight.App.Helpers;
using Whois.NET;
namespace Moonlight.App.Services;
public class IpVerificationService
{
private readonly ConfigService ConfigService;
public IpVerificationService(ConfigService configService)
{
ConfigService = configService;
}
public async Task<bool> IsDatacenterOrVpn(string ip)
{
if (!ConfigService.Get().Moonlight.Security.BlockDatacenterIps)
return false;
if (string.IsNullOrEmpty(ip))
return false;
var datacenterNames = new List<string>()
{
"amazon",
"aws",
"microsoft",
"azure",
"google",
"google cloud",
"gcp",
"digitalocean",
"linode",
"vultr",
"ovh",
"ovhcloud",
"alibaba",
"oracle",
"ibm cloud",
"bluehost",
"godaddy",
"rackpace",
"hetzner",
"tencent",
"scaleway",
"softlayer",
"dreamhost",
"a2 hosting",
"inmotion hosting",
"red hat openstack",
"kamatera",
"hostgator",
"siteground",
"greengeeks",
"liquidweb",
"joyent",
"aruba",
"interoute",
"fastcomet",
"rosehosting",
"lunarpages",
"fatcow",
"jelastic",
"datacamp"
};
if(!ConfigService.Get().Moonlight.Security.AllowCloudflareIps)
datacenterNames.Add("cloudflare");
try
{
var response = await WhoisClient.QueryAsync(ip);
var responseText = response.Raw.ToLower();
foreach (var name in datacenterNames)
{
if (responseText.Contains(name))
{
Logger.Debug(name);
return true;
}
}
}
catch (Exception)
{
return false;
}
return false;
}
}

View File

@@ -0,0 +1,180 @@
using System.Security.Cryptography.X509Certificates;
using Certes;
using Certes.Acme;
using Microsoft.AspNetCore.Connections;
using Microsoft.AspNetCore.Http.Connections;
using Moonlight.App.Events;
using Moonlight.App.Helpers;
namespace Moonlight.App.Services;
public class LetsEncryptService
{
private readonly ConfigService ConfigService;
private readonly string LetsEncryptCertPath;
private readonly EventSystem Event;
private X509Certificate2 Certificate;
public string HttpChallenge { get; private set; } = "";
public string HttpChallengeToken { get; private set; } = "";
public LetsEncryptService(ConfigService configService, EventSystem eventSystem)
{
ConfigService = configService;
Event = eventSystem;
LetsEncryptCertPath = PathBuilder.File("storage", "certs", "letsencrypt.pfx");
}
public async Task AutoProcess()
{
try
{
if (!ConfigService.Get().Moonlight.LetsEncrypt.Enable)
return;
if (await CheckNeedsRenewal())
{
try
{
await Renew();
}
catch (Exception e)
{
Logger.Error("Unable to issue lets encrypt certificate");
Logger.Error(e);
}
}
else
Logger.Info("Skipping lets encrypt renewal");
await LoadCertificate();
}
catch(Exception e)
{
Logger.Error("Unhandled exception while auto proccessing lets encrypt certificates");
Logger.Error(e);
}
}
private Task LoadCertificate()
{
try
{
Certificate = new X509Certificate2(
LetsEncryptCertPath,
ConfigService.Get().Moonlight.Security.Token
);
Logger.Info($"Loaded ssl certificate. '{Certificate.FriendlyName}' issued by '{Certificate.IssuerName.Name}'");
}
catch (Exception e)
{
Logger.Warn("Unable to load ssl certificates");
Logger.Warn(e);
}
return Task.CompletedTask;
}
private async Task Renew()
{
Logger.Info("Renewing lets encrypt certificate");
var uri = new Uri(ConfigService.Get().Moonlight.AppUrl);
var config = ConfigService.Get().Moonlight.LetsEncrypt;
if (uri.HostNameType == UriHostNameType.IPv4 || uri.HostNameType == UriHostNameType.IPv6)
{
Logger.Warn("You cannot use an ip to issue a lets encrypt certificate");
return;
}
var acmeContext = new AcmeContext(WellKnownServers.LetsEncryptV2);
Logger.Info($"Starting lets encrypt certificate issuing. Using acme server '{acmeContext.DirectoryUri}'");
var account = await acmeContext.NewAccount(config.ExpireEmail, true);
Logger.Info("Creating order");
var order = await acmeContext.NewOrder(new[] { uri.Host });
var authZ = (await order.Authorizations()).First();
var challenge = await authZ.Http();
HttpChallengeToken = challenge.Token;
HttpChallenge = challenge.KeyAuthz;
Logger.Info("Waiting for http challenge to complete");
Task.Run(async () =>
{
await Task.Delay(TimeSpan.FromSeconds(3));
try
{
await challenge.Validate();
Logger.Info("Tried to validate");
}
catch (Exception e)
{
Logger.Error("Unable to validate challenge");
Logger.Error(e);
}
});
await Event.WaitForEvent<Object>("letsEncrypt.challengeFetched", this);
Logger.Info("Generating certificate");
var privateKey = KeyFactory.NewKey(KeyAlgorithm.ES256);
var certificate = await order.Generate(new CsrInfo
{
CountryName = config.CountryCode,
State = config.State,
Locality = config.Locality,
Organization = config.Organization,
OrganizationUnit = "Dev",
CommonName = uri.Host
}, privateKey);
var builder = certificate.ToPfx(privateKey);
var certBytes = builder.Build(
uri.Host,
ConfigService.Get().Moonlight.Security.Token
);
Logger.Info($"Saved lets encrypt certificate to '{LetsEncryptCertPath}'");
await File.WriteAllBytesAsync(LetsEncryptCertPath, certBytes);
}
private Task<bool> CheckNeedsRenewal()
{
if (!File.Exists(LetsEncryptCertPath))
{
Logger.Info("No lets encrypt certificate found");
return Task.FromResult(true);
}
var existingCert = new X509Certificate2(LetsEncryptCertPath, ConfigService.Get().Moonlight.Security.Token);
var expirationDate = existingCert.NotAfter;
if (DateTime.Now < expirationDate)
{
Logger.Info($"Lets encrypt certificate valid until {Formatter.FormatDate(expirationDate)}");
return Task.FromResult(false);
}
Logger.Info("Lets encrypt certificate expired");
return Task.FromResult(true);
}
public X509Certificate2? SelectCertificate(ConnectionContext? context, string? domain)
{
if (context == null)
return null;
return Certificate;
}
}

View File

@@ -0,0 +1,42 @@
using Moonlight.App.Database.Entities;
using Moonlight.App.MalwareScans;
using Moonlight.App.Models.Misc;
using Moonlight.App.Services.Plugins;
namespace Moonlight.App.Services;
public class MalwareScanService
{
private readonly PluginService PluginService;
private readonly IServiceScopeFactory ServiceScopeFactory;
public MalwareScanService(PluginService pluginService, IServiceScopeFactory serviceScopeFactory)
{
PluginService = pluginService;
ServiceScopeFactory = serviceScopeFactory;
}
public async Task<MalwareScanResult?> Perform(Server server)
{
var defaultScans = new List<MalwareScan>
{
new MinerJarScan(),
new FakePlayerPluginScan(),
new BadScriptsScan()
};
var scans = await PluginService.BuildMalwareScans(defaultScans.ToArray());
using var scope = ServiceScopeFactory.CreateScope();
foreach (var scan in scans)
{
var result = await scan.Scan(server, scope.ServiceProvider);
if (result != null)
return result;
}
return null;
}
}

View File

@@ -46,7 +46,7 @@ public class MoonlightService
try try
{ {
var client = new GitHubClient(new ProductHeaderValue("Moonlight")); var client = new GitHubClient(new ProductHeaderValue("Moonlight-Panel"));
var pullRequests = await client.PullRequest.GetAllForRepository("Moonlight-Panel", "Moonlight", new PullRequestRequest var pullRequests = await client.PullRequest.GetAllForRepository("Moonlight-Panel", "Moonlight", new PullRequestRequest
{ {

View File

@@ -50,6 +50,11 @@ public class NodeService
return await DaemonApiHelper.Get<DockerMetrics>(node, "metrics/docker"); return await DaemonApiHelper.Get<DockerMetrics>(node, "metrics/docker");
} }
public async Task RebuildFirewall(Node node, string[] ips)
{
await DaemonApiHelper.Post(node, "firewall/rebuild", ips);
}
public async Task Mount(Node node, string server, string serverPath, string path) public async Task Mount(Node node, string server, string serverPath, string path)
{ {
await DaemonApiHelper.Post(node, "mount", new Mount() await DaemonApiHelper.Post(node, "mount", new Mount()

View File

@@ -0,0 +1,109 @@
using System.Reflection;
using System.Runtime.Loader;
using Moonlight.App.Helpers;
using Moonlight.App.Models.Misc;
using Moonlight.App.Plugin;
using Moonlight.App.Plugin.UI.Servers;
using Moonlight.App.Plugin.UI.Webspaces;
namespace Moonlight.App.Services.Plugins;
public class PluginService
{
public readonly List<MoonlightPlugin> Plugins = new();
public readonly Dictionary<MoonlightPlugin, string> PluginFiles = new();
public Task ReloadPlugins()
{
PluginFiles.Clear();
Plugins.Clear();
// Try to update all plugins ending with .dll.cache
foreach (var pluginFile in Directory.EnumerateFiles(
PathBuilder.Dir(Directory.GetCurrentDirectory(), "storage", "plugins"))
.Where(x => x.EndsWith(".dll.cache")))
{
try
{
var realPath = pluginFile.Replace(".cache", "");
File.Copy(pluginFile, realPath, true);
File.Delete(pluginFile);
Logger.Info($"Updated plugin {realPath} on startup");
}
catch (Exception)
{
// ignored
}
}
var pluginType = typeof(MoonlightPlugin);
foreach (var pluginFile in Directory.EnumerateFiles(
PathBuilder.Dir(Directory.GetCurrentDirectory(), "storage", "plugins"))
.Where(x => x.EndsWith(".dll")))
{
var assembly = Assembly.LoadFile(pluginFile);
foreach (var type in assembly.GetTypes())
{
if (type.IsSubclassOf(pluginType))
{
var plugin = (Activator.CreateInstance(type) as MoonlightPlugin)!;
Logger.Info($"Loaded plugin '{plugin.Name}' ({plugin.Version}) by {plugin.Author}");
Plugins.Add(plugin);
PluginFiles.Add(plugin, pluginFile);
}
}
}
Logger.Info($"Loaded {Plugins.Count} plugins");
return Task.CompletedTask;
}
public async Task<ServerPageContext> BuildServerPage(ServerPageContext context)
{
foreach (var plugin in Plugins)
{
if (plugin.OnBuildServerPage != null)
await plugin.OnBuildServerPage.Invoke(context);
}
return context;
}
public async Task<WebspacePageContext> BuildWebspacePage(WebspacePageContext context)
{
foreach (var plugin in Plugins)
{
if (plugin.OnBuildWebspacePage != null)
await plugin.OnBuildWebspacePage.Invoke(context);
}
return context;
}
public async Task BuildServices(IServiceCollection serviceCollection)
{
foreach (var plugin in Plugins)
{
if (plugin.OnBuildServices != null)
await plugin.OnBuildServices.Invoke(serviceCollection);
}
}
public async Task<MalwareScan[]> BuildMalwareScans(MalwareScan[] defaultScans)
{
var scanList = defaultScans.ToList();
foreach (var plugin in Plugins)
{
if (plugin.OnBuildMalwareScans != null)
scanList = await plugin.OnBuildMalwareScans.Invoke(scanList);
}
return scanList.ToArray();
}
}

View File

@@ -0,0 +1,63 @@
using System.Text;
using Moonlight.App.Helpers;
using Moonlight.App.Models.Misc;
using Octokit;
namespace Moonlight.App.Services.Plugins;
public class PluginStoreService
{
private readonly GitHubClient Client;
private readonly PluginService PluginService;
public PluginStoreService(PluginService pluginService)
{
PluginService = pluginService;
Client = new(new ProductHeaderValue("Moonlight-Panel"));
}
public async Task<OfficialMoonlightPlugin[]> GetPlugins()
{
var items = await Client.Repository.Content.GetAllContents("Moonlight-Panel", "OfficialPlugins");
if (items == null)
{
Logger.Fatal("Unable to read plugin repo contents");
return Array.Empty<OfficialMoonlightPlugin>();
}
return items
.Where(x => x.Type == ContentType.Dir)
.Select(x => new OfficialMoonlightPlugin()
{
Name = x.Name
})
.ToArray();
}
public async Task<string> GetPluginReadme(OfficialMoonlightPlugin plugin)
{
var rawReadme = await Client.Repository.Content
.GetRawContent("Moonlight-Panel", "OfficialPlugins", $"{plugin.Name}/README.md");
if (rawReadme == null)
return "Error";
return Encoding.UTF8.GetString(rawReadme);
}
public async Task InstallPlugin(OfficialMoonlightPlugin plugin, bool updating = false)
{
var rawPlugin = await Client.Repository.Content
.GetRawContent("Moonlight-Panel", "OfficialPlugins", $"{plugin.Name}/{plugin.Name}.dll");
if (updating)
{
await File.WriteAllBytesAsync(PathBuilder.File("storage", "plugins", $"{plugin.Name}.dll.cache"), rawPlugin);
return;
}
await File.WriteAllBytesAsync(PathBuilder.File("storage", "plugins", $"{plugin.Name}.dll"), rawPlugin);
await PluginService.ReloadPlugins();
}
}

View File

@@ -12,6 +12,8 @@ using Moonlight.App.Helpers.Wings;
using Moonlight.App.Models.Misc; using Moonlight.App.Models.Misc;
using Moonlight.App.Repositories; using Moonlight.App.Repositories;
using Moonlight.App.Repositories.Servers; using Moonlight.App.Repositories.Servers;
using Moonlight.App.Services.Background;
using Moonlight.App.Services.Plugins;
using FileAccess = Moonlight.App.Helpers.Files.FileAccess; using FileAccess = Moonlight.App.Helpers.Files.FileAccess;
namespace Moonlight.App.Services; namespace Moonlight.App.Services;
@@ -32,6 +34,11 @@ public class ServerService
private readonly DateTimeService DateTimeService; private readonly DateTimeService DateTimeService;
private readonly EventSystem Event; private readonly EventSystem Event;
// We inject the dependencies for the malware scan service here because otherwise it may result in
// a circular dependency injection which will crash the app
private readonly PluginService PluginService;
private readonly IServiceScopeFactory ServiceScopeFactory;
public ServerService( public ServerService(
ServerRepository serverRepository, ServerRepository serverRepository,
WingsApiHelper wingsApiHelper, WingsApiHelper wingsApiHelper,
@@ -45,7 +52,9 @@ public class ServerService
NodeAllocationRepository nodeAllocationRepository, NodeAllocationRepository nodeAllocationRepository,
DateTimeService dateTimeService, DateTimeService dateTimeService,
EventSystem eventSystem, EventSystem eventSystem,
Repository<ServerVariable> serverVariablesRepository) Repository<ServerVariable> serverVariablesRepository,
PluginService pluginService,
IServiceScopeFactory serviceScopeFactory)
{ {
ServerRepository = serverRepository; ServerRepository = serverRepository;
WingsApiHelper = wingsApiHelper; WingsApiHelper = wingsApiHelper;
@@ -60,6 +69,8 @@ public class ServerService
DateTimeService = dateTimeService; DateTimeService = dateTimeService;
Event = eventSystem; Event = eventSystem;
ServerVariablesRepository = serverVariablesRepository; ServerVariablesRepository = serverVariablesRepository;
PluginService = pluginService;
ServiceScopeFactory = serviceScopeFactory;
} }
private Server EnsureNodeData(Server s) private Server EnsureNodeData(Server s)
@@ -99,6 +110,24 @@ public class ServerService
{ {
Server server = EnsureNodeData(s); Server server = EnsureNodeData(s);
if (ConfigService.Get().Moonlight.Security.MalwareCheckOnStart && signal == PowerSignal.Start ||
signal == PowerSignal.Restart)
{
var result = await new MalwareScanService(
PluginService,
ServiceScopeFactory
).Perform(server);
if (result != null)
{
Logger.Warn($"Found malware on server {server.Uuid}. Result: " + result.Title, "security");
throw new DisplayException(
$"Unable to start server. Found following malware on this server: {result.Title}. Please contact the support if you think this detection is a false positive",
true);
}
}
var rawSignal = signal.ToString().ToLower(); var rawSignal = signal.ToString().ToLower();
await WingsApiHelper.Post(server.Node, $"api/servers/{server.Uuid}/power", new ServerPower() await WingsApiHelper.Post(server.Node, $"api/servers/{server.Uuid}/power", new ServerPower()
@@ -420,10 +449,7 @@ public class ServerService
await new Retry() await new Retry()
.Times(3) .Times(3)
.At(x => x.Message.Contains("A task was canceled")) .At(x => x.Message.Contains("A task was canceled"))
.Call(async () => .Call(async () => { await WingsApiHelper.Delete(server.Node, $"api/servers/{server.Uuid}", null); });
{
await WingsApiHelper.Delete(server.Node, $"api/servers/{server.Uuid}", null);
});
} }
catch (WingsException e) catch (WingsException e)
{ {

View File

@@ -3,6 +3,7 @@ using JWT.Algorithms;
using JWT.Builder; using JWT.Builder;
using JWT.Exceptions; using JWT.Exceptions;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.JSInterop;
using Moonlight.App.Database.Entities; using Moonlight.App.Database.Entities;
using Moonlight.App.Helpers; using Moonlight.App.Helpers;
using Moonlight.App.Perms; using Moonlight.App.Perms;
@@ -16,6 +17,7 @@ public class IdentityService
private readonly Repository<User> UserRepository; private readonly Repository<User> UserRepository;
private readonly CookieService CookieService; private readonly CookieService CookieService;
private readonly IHttpContextAccessor HttpContextAccessor; private readonly IHttpContextAccessor HttpContextAccessor;
private readonly IJSRuntime JsRuntime;
private readonly string Secret; private readonly string Secret;
public User User { get; private set; } public User User { get; private set; }
@@ -29,11 +31,13 @@ public class IdentityService
CookieService cookieService, CookieService cookieService,
Repository<User> userRepository, Repository<User> userRepository,
IHttpContextAccessor httpContextAccessor, IHttpContextAccessor httpContextAccessor,
ConfigService configService) ConfigService configService,
IJSRuntime jsRuntime)
{ {
CookieService = cookieService; CookieService = cookieService;
UserRepository = userRepository; UserRepository = userRepository;
HttpContextAccessor = httpContextAccessor; HttpContextAccessor = httpContextAccessor;
JsRuntime = jsRuntime;
Secret = configService Secret = configService
.Get() .Get()
@@ -112,7 +116,7 @@ public class IdentityService
if (user == null) if (user == null)
{ {
Logger.Warn( Logger.Warn(
$"Cannot find user with the id '{userid}' in the database. Maybe the user has been deleted or a token has been successfully faked by a hacker"); $"Cannot find user with the id '{userid}' in the database. Maybe the user has been deleted or a token has been successfully faked by a hacker", "security");
return; return;
} }
@@ -260,4 +264,21 @@ public class IdentityService
Permissions.IsReadyOnly = true; Permissions.IsReadyOnly = true;
} }
public async Task<bool> GetBotStatus()
{
var webDriverStatus = await JsRuntime
.InvokeAsync<bool>("moonlight.utils.getWebDriverStatus");
if (webDriverStatus)
return true;
var languagesStatus = await JsRuntime
.InvokeAsync<bool>("moonlight.utils.getLanguagesStatus");
if (languagesStatus)
return true;
return false;
}
} }

View File

@@ -0,0 +1,67 @@
using Microsoft.AspNetCore.Components.Forms;
using Moonlight.App.Database.Entities;
using Moonlight.App.Models.Misc;
using Moonlight.App.Services.Files;
using Moonlight.App.Services.Sessions;
namespace Moonlight.App.Services.Tickets;
public class TicketAdminService
{
private readonly TicketServerService TicketServerService;
private readonly IdentityService IdentityService;
private readonly BucketService BucketService;
public Ticket? Ticket { get; set; }
public TicketAdminService(
TicketServerService ticketServerService,
IdentityService identityService,
BucketService bucketService)
{
TicketServerService = ticketServerService;
IdentityService = identityService;
BucketService = bucketService;
}
public async Task<TicketMessage> Send(string content, IBrowserFile? file = null)
{
string? attachment = null;
if (file != null)
{
attachment = await BucketService.StoreFile(
"tickets",
file.OpenReadStream(1024 * 1024 * 5),
file.Name);
}
return await TicketServerService.SendMessage(
Ticket!,
IdentityService.User,
content,
attachment,
true
);
}
public async Task UpdateStatus(TicketStatus status)
{
await TicketServerService.UpdateStatus(Ticket!, status);
}
public async Task UpdatePriority(TicketPriority priority)
{
await TicketServerService.UpdatePriority(Ticket!, priority);
}
public async Task<TicketMessage[]> GetMessages()
{
return await TicketServerService.GetMessages(Ticket!);
}
public async Task SetClaim(User? user)
{
await TicketServerService.SetClaim(Ticket!, user);
}
}

View File

@@ -0,0 +1,63 @@
using Microsoft.AspNetCore.Components.Forms;
using Moonlight.App.Database.Entities;
using Moonlight.App.Models.Misc;
using Moonlight.App.Services.Files;
using Moonlight.App.Services.Sessions;
namespace Moonlight.App.Services.Tickets;
public class TicketClientService
{
private readonly TicketServerService TicketServerService;
private readonly IdentityService IdentityService;
private readonly BucketService BucketService;
public Ticket? Ticket { get; set; }
public TicketClientService(
TicketServerService ticketServerService,
IdentityService identityService,
BucketService bucketService)
{
TicketServerService = ticketServerService;
IdentityService = identityService;
BucketService = bucketService;
}
public async Task<Ticket> Create(string issueTopic, string issueDescription, string issueTries, TicketSubject subject, int subjectId)
{
return await TicketServerService.Create(
IdentityService.User,
issueTopic,
issueDescription,
issueTries,
subject,
subjectId
);
}
public async Task<TicketMessage> Send(string content, IBrowserFile? file = null)
{
string? attachment = null;
if (file != null)
{
attachment = await BucketService.StoreFile(
"tickets",
file.OpenReadStream(1024 * 1024 * 5),
file.Name);
}
return await TicketServerService.SendMessage(
Ticket!,
IdentityService.User,
content,
attachment
);
}
public async Task<TicketMessage[]> GetMessages()
{
return await TicketServerService.GetMessages(Ticket!);
}
}

View File

@@ -0,0 +1,181 @@
using Microsoft.EntityFrameworkCore;
using Moonlight.App.Database.Entities;
using Moonlight.App.Events;
using Moonlight.App.Models.Misc;
using Moonlight.App.Repositories;
namespace Moonlight.App.Services.Tickets;
public class TicketServerService
{
private readonly IServiceScopeFactory ServiceScopeFactory;
private readonly EventSystem Event;
private readonly ConfigService ConfigService;
public TicketServerService(
IServiceScopeFactory serviceScopeFactory,
EventSystem eventSystem,
ConfigService configService)
{
ServiceScopeFactory = serviceScopeFactory;
Event = eventSystem;
ConfigService = configService;
}
public async Task<Ticket> Create(User creator, string issueTopic, string issueDescription, string issueTries, TicketSubject subject, int subjectId)
{
using var scope = ServiceScopeFactory.CreateScope();
var ticketRepo = scope.ServiceProvider.GetRequiredService<Repository<Ticket>>();
var userRepo = scope.ServiceProvider.GetRequiredService<Repository<User>>();
var creatorUser = userRepo
.Get()
.First(x => x.Id == creator.Id);
var ticket = ticketRepo.Add(new()
{
Priority = TicketPriority.Low,
Status = TicketStatus.Open,
AssignedTo = null,
IssueTopic = issueTopic,
IssueDescription = issueDescription,
IssueTries = issueTries,
Subject = subject,
SubjectId = subjectId,
CreatedBy = creatorUser
});
await Event.Emit("tickets.new", ticket);
// Do automatic stuff here
await SendSystemMessage(ticket, ConfigService.Get().Moonlight.Tickets.WelcomeMessage);
if (ticket.Subject != TicketSubject.Other)
{
await SendMessage(ticket, creatorUser, $"Subject :\n\n{ticket.Subject}: {ticket.SubjectId}");
}
//TODO: Check for opening times
return ticket;
}
public async Task SendSystemMessage(Ticket t, string content, string? attachmentUrl = null)
{
using var scope = ServiceScopeFactory.CreateScope();
var ticketRepo = scope.ServiceProvider.GetRequiredService<Repository<Ticket>>();
var ticket = ticketRepo.Get().First(x => x.Id == t.Id);
var message = new TicketMessage()
{
Content = content,
Sender = null,
AttachmentUrl = attachmentUrl,
IsSystemMessage = true
};
ticket.Messages.Add(message);
ticketRepo.Update(ticket);
await Event.Emit("tickets.message", message);
await Event.Emit($"tickets.{ticket.Id}.message", message);
}
public async Task UpdatePriority(Ticket t, TicketPriority priority)
{
if(t.Priority == priority)
return;
using var scope = ServiceScopeFactory.CreateScope();
var ticketRepo = scope.ServiceProvider.GetRequiredService<Repository<Ticket>>();
var ticket = ticketRepo.Get().First(x => x.Id == t.Id);
ticket.Priority = priority;
ticketRepo.Update(ticket);
await Event.Emit("tickets.status", ticket);
await Event.Emit($"tickets.{ticket.Id}.status", ticket);
await SendSystemMessage(ticket, $"The ticket priority has been changed to: {priority}");
}
public async Task UpdateStatus(Ticket t, TicketStatus status)
{
if(t.Status == status)
return;
using var scope = ServiceScopeFactory.CreateScope();
var ticketRepo = scope.ServiceProvider.GetRequiredService<Repository<Ticket>>();
var ticket = ticketRepo.Get().First(x => x.Id == t.Id);
ticket.Status = status;
ticketRepo.Update(ticket);
await Event.Emit("tickets.status", ticket);
await Event.Emit($"tickets.{ticket.Id}.status", ticket);
await SendSystemMessage(ticket, $"The ticket status has been changed to: {status}");
}
public async Task<TicketMessage> SendMessage(Ticket t, User sender, string content, string? attachmentUrl = null, bool isSupportMessage = false)
{
using var scope = ServiceScopeFactory.CreateScope();
var ticketRepo = scope.ServiceProvider.GetRequiredService<Repository<Ticket>>();
var userRepo = scope.ServiceProvider.GetRequiredService<Repository<User>>();
var ticket = ticketRepo.Get().First(x => x.Id == t.Id);
var user = userRepo.Get().First(x => x.Id == sender.Id);
var message = new TicketMessage()
{
Content = content,
Sender = user,
AttachmentUrl = attachmentUrl,
IsSupportMessage = isSupportMessage
};
ticket.Messages.Add(message);
ticketRepo.Update(ticket);
await Event.Emit("tickets.message", message);
await Event.Emit($"tickets.{ticket.Id}.message", message);
return message;
}
public Task<TicketMessage[]> GetMessages(Ticket ticket)
{
using var scope = ServiceScopeFactory.CreateScope();
var ticketRepo = scope.ServiceProvider.GetRequiredService<Repository<Ticket>>();
var tickets = ticketRepo
.Get()
.Include(x => x.CreatedBy)
.Include(x => x.Messages)
.ThenInclude(x => x.Sender)
.First(x => x.Id == ticket.Id);
return Task.FromResult(tickets.Messages.ToArray());
}
public async Task SetClaim(Ticket t, User? u = null)
{
using var scope = ServiceScopeFactory.CreateScope();
var ticketRepo = scope.ServiceProvider.GetRequiredService<Repository<Ticket>>();
var userRepo = scope.ServiceProvider.GetRequiredService<Repository<User>>();
var ticket = ticketRepo.Get().Include(x => x.AssignedTo).First(x => x.Id == t.Id);
var user = u == null ? u : userRepo.Get().First(x => x.Id == u.Id);
ticket.AssignedTo = user;
ticketRepo.Update(ticket);
await Event.Emit("tickets.status", ticket);
await Event.Emit($"tickets.{ticket.Id}.status", ticket);
var claimName = user == null ? "None" : user.FirstName + " " + user.LastName;
await SendSystemMessage(ticket, $"Ticked claim has been set to {claimName}");
}
}

View File

@@ -21,6 +21,7 @@ public class UserService
private readonly DateTimeService DateTimeService; private readonly DateTimeService DateTimeService;
private readonly ConfigService ConfigService; private readonly ConfigService ConfigService;
private readonly TempMailService TempMailService; private readonly TempMailService TempMailService;
private readonly MoonlightService MoonlightService;
private readonly string JwtSecret; private readonly string JwtSecret;
@@ -32,7 +33,8 @@ public class UserService
IdentityService identityService, IdentityService identityService,
IpLocateService ipLocateService, IpLocateService ipLocateService,
DateTimeService dateTimeService, DateTimeService dateTimeService,
TempMailService tempMailService) TempMailService tempMailService,
MoonlightService moonlightService)
{ {
UserRepository = userRepository; UserRepository = userRepository;
TotpService = totpService; TotpService = totpService;
@@ -42,6 +44,7 @@ public class UserService
IpLocateService = ipLocateService; IpLocateService = ipLocateService;
DateTimeService = dateTimeService; DateTimeService = dateTimeService;
TempMailService = tempMailService; TempMailService = tempMailService;
MoonlightService = moonlightService;
JwtSecret = configService JwtSecret = configService
.Get() .Get()
@@ -59,6 +62,19 @@ public class UserService
throw new DisplayException("This email is blacklisted"); throw new DisplayException("This email is blacklisted");
} }
if (ConfigService.Get().Moonlight.Auth.BlockLinuxUsers && IdentityService.Device.Contains("Linux"))
throw new DisplayException("This operation was disabled");
if (ConfigService.Get().Moonlight.Auth.CheckForBots)
{
var isABot = await IdentityService.GetBotStatus();
if (isABot)
{
throw new DisplayException("This operation was disabled");
}
}
// Check if the email is already taken // Check if the email is already taken
var emailTaken = UserRepository.Get().FirstOrDefault(x => x.Email == email) != null; var emailTaken = UserRepository.Get().FirstOrDefault(x => x.Email == email) != null;
@@ -67,16 +83,24 @@ public class UserService
throw new DisplayException("The email is already in use"); throw new DisplayException("The email is already in use");
} }
//TODO: Validation bool admin = false;
if (!UserRepository.Get().Any())
{
if ((DateTime.UtcNow - MoonlightService.StartTimestamp).TotalMinutes < 15)
admin = true;
else
throw new DisplayException("You have to register within 15 minutes after the start of moonlight to get admin permissions. Please restart moonlight in order to register as admin. Please note that this will only works once and will be deactivated after a admin has registered");
}
// Add user // Add user
var user = UserRepository.Add(new() var user = UserRepository.Add(new()
{ {
Address = "", Address = "",
Admin = false, Admin = admin,
City = "", City = "",
Country = "", Country = "",
Email = email, Email = email.ToLower(),
Password = BCrypt.Net.BCrypt.HashPassword(password), Password = BCrypt.Net.BCrypt.HashPassword(password),
FirstName = firstname, FirstName = firstname,
LastName = lastname, LastName = lastname,
@@ -108,7 +132,7 @@ public class UserService
if (user == null) if (user == null)
{ {
Logger.Warn($"Failed login attempt. Email: {email} Password: {password}", "security"); Logger.Warn($"Failed login attempt. Email: {email} Password: {StringHelper.CutInHalf(password)}", "security");
throw new DisplayException("Email and password combination not found"); throw new DisplayException("Email and password combination not found");
} }
@@ -117,7 +141,7 @@ public class UserService
return user.TotpEnabled; return user.TotpEnabled;
} }
Logger.Warn($"Failed login attempt. Email: {email} Password: {password}", "security"); Logger.Warn($"Failed login attempt. Email: {email} Password: {StringHelper.CutInHalf(password)}", "security");
throw new DisplayException("Email and password combination not found");; throw new DisplayException("Email and password combination not found");;
} }
@@ -150,7 +174,7 @@ public class UserService
} }
else else
{ {
Logger.Warn($"Failed login attempt. Email: {email} Password: {password}", "security"); Logger.Warn($"Failed login attempt. Email: {email} Password: {StringHelper.CutInHalf(password)}", "security");
throw new DisplayException("2FA code invalid"); throw new DisplayException("2FA code invalid");
} }
} }
@@ -192,7 +216,7 @@ public class UserService
if (user == null) if (user == null)
{ {
Logger.Warn($"Detected an sftp bruteforce attempt. ID: {id} Password: {password}", "security"); Logger.Warn($"Detected an sftp bruteforce attempt. ID: {id} Password: {StringHelper.CutInHalf(password)}", "security");
throw new Exception("Invalid username"); throw new Exception("Invalid username");
} }
@@ -203,7 +227,7 @@ public class UserService
return user; return user;
} }
Logger.Warn($"Detected an sftp bruteforce attempt. ID: {id} Password: {password}", "security"); Logger.Warn($"Detected an sftp bruteforce attempt. ID: {id} Password: {StringHelper.CutInHalf(password)}", "security");
throw new Exception("Invalid userid or password"); throw new Exception("Invalid userid or password");
} }

View File

@@ -22,5 +22,4 @@ COPY --from=publish /app/publish .
RUN mkdir -p /app/storage RUN mkdir -p /app/storage
RUN touch /app/storage/donttriggeranyerrors RUN touch /app/storage/donttriggeranyerrors
RUN rm -r /app/storage/* RUN rm -r /app/storage/*
COPY "Moonlight/defaultstorage" "/app/defaultstorage"
ENTRYPOINT ["dotnet", "Moonlight.dll"] ENTRYPOINT ["dotnet", "Moonlight.dll"]

View File

@@ -17,6 +17,7 @@
<PackageReference Include="BlazorDownloadFile" Version="2.4.0.2" /> <PackageReference Include="BlazorDownloadFile" Version="2.4.0.2" />
<PackageReference Include="BlazorMonaco" Version="2.1.0" /> <PackageReference Include="BlazorMonaco" Version="2.1.0" />
<PackageReference Include="BlazorTable" Version="1.17.0" /> <PackageReference Include="BlazorTable" Version="1.17.0" />
<PackageReference Include="Certes" Version="3.0.4" />
<PackageReference Include="CloudFlare.Client" Version="6.1.4" /> <PackageReference Include="CloudFlare.Client" Version="6.1.4" />
<PackageReference Include="CurrieTechnologies.Razor.SweetAlert2" Version="5.5.0" /> <PackageReference Include="CurrieTechnologies.Razor.SweetAlert2" Version="5.5.0" />
<PackageReference Include="Discord.Net" Version="3.10.0" /> <PackageReference Include="Discord.Net" Version="3.10.0" />
@@ -40,12 +41,12 @@
</PackageReference> </PackageReference>
<PackageReference Include="MineStat" Version="3.1.1" /> <PackageReference Include="MineStat" Version="3.1.1" />
<PackageReference Include="MySqlBackup.NET" Version="2.3.8" /> <PackageReference Include="MySqlBackup.NET" Version="2.3.8" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3-beta1" /> <PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="Octokit" Version="6.0.0" /> <PackageReference Include="Octokit" Version="6.0.0" />
<PackageReference Include="Otp.NET" Version="1.3.0" /> <PackageReference Include="Otp.NET" Version="1.3.0" />
<PackageReference Include="Pomelo.EntityFrameworkCore.MySql" Version="7.0.0" /> <PackageReference Include="Pomelo.EntityFrameworkCore.MySql" Version="7.0.0" />
<PackageReference Include="QRCoder" Version="1.4.3" /> <PackageReference Include="QRCoder" Version="1.4.3" />
<PackageReference Include="RestSharp" Version="109.0.0-preview.1" /> <PackageReference Include="RestSharp" Version="110.2.1-alpha.0.10" />
<PackageReference Include="Sentry.AspNetCore" Version="3.33.1" /> <PackageReference Include="Sentry.AspNetCore" Version="3.33.1" />
<PackageReference Include="Sentry.Serilog" Version="3.33.1" /> <PackageReference Include="Sentry.Serilog" Version="3.33.1" />
<PackageReference Include="Serilog" Version="3.0.0" /> <PackageReference Include="Serilog" Version="3.0.0" />
@@ -55,6 +56,7 @@
<PackageReference Include="SSH.NET" Version="2020.0.2" /> <PackageReference Include="SSH.NET" Version="2020.0.2" />
<PackageReference Include="Stripe.net" Version="41.23.0-beta.1" /> <PackageReference Include="Stripe.net" Version="41.23.0-beta.1" />
<PackageReference Include="UAParser" Version="3.1.47" /> <PackageReference Include="UAParser" Version="3.1.47" />
<PackageReference Include="WhoisClient.NET" Version="5.0.0" />
<PackageReference Include="XtermBlazor" Version="1.8.1" /> <PackageReference Include="XtermBlazor" Version="1.8.1" />
</ItemGroup> </ItemGroup>
@@ -84,6 +86,103 @@
<_ContentIncludedByDefault Remove="Shared\Components\AuditLogEntrys\AuditLogEntryChangePowerState.razor" /> <_ContentIncludedByDefault Remove="Shared\Components\AuditLogEntrys\AuditLogEntryChangePowerState.razor" />
<_ContentIncludedByDefault Remove="Shared\Components\AuditLogEntrys\AuditLogEntryLogin.razor" /> <_ContentIncludedByDefault Remove="Shared\Components\AuditLogEntrys\AuditLogEntryLogin.razor" />
<_ContentIncludedByDefault Remove="Shared\Components\AuditLogEntrys\AuditLogEntryRegister.razor" /> <_ContentIncludedByDefault Remove="Shared\Components\AuditLogEntrys\AuditLogEntryRegister.razor" />
<_ContentIncludedByDefault Remove="wwwroot\assets\plugins\custom\ckeditor\ckeditor-balloon-block.bundle.js" />
<_ContentIncludedByDefault Remove="wwwroot\assets\plugins\custom\ckeditor\ckeditor-balloon.bundle.js" />
<_ContentIncludedByDefault Remove="wwwroot\assets\plugins\custom\ckeditor\ckeditor-classic.bundle.js" />
<_ContentIncludedByDefault Remove="wwwroot\assets\plugins\custom\ckeditor\ckeditor-document.bundle.js" />
<_ContentIncludedByDefault Remove="wwwroot\assets\plugins\custom\ckeditor\ckeditor-inline.bundle.js" />
<_ContentIncludedByDefault Remove="wwwroot\assets\plugins\custom\cookiealert\cookiealert.bundle.css" />
<_ContentIncludedByDefault Remove="wwwroot\assets\plugins\custom\cookiealert\cookiealert.bundle.js" />
<_ContentIncludedByDefault Remove="wwwroot\assets\plugins\custom\cropper\cropper.bundle.css" />
<_ContentIncludedByDefault Remove="wwwroot\assets\plugins\custom\cropper\cropper.bundle.js" />
<_ContentIncludedByDefault Remove="wwwroot\assets\plugins\custom\datatables\datatables.bundle.css" />
<_ContentIncludedByDefault Remove="wwwroot\assets\plugins\custom\datatables\datatables.bundle.js" />
<_ContentIncludedByDefault Remove="wwwroot\assets\plugins\custom\draggable\draggable.bundle.js" />
<_ContentIncludedByDefault Remove="wwwroot\assets\plugins\custom\flotcharts\flotcharts.bundle.js" />
<_ContentIncludedByDefault Remove="wwwroot\assets\plugins\custom\formrepeater\formrepeater.bundle.js" />
<_ContentIncludedByDefault Remove="wwwroot\assets\plugins\custom\fslightbox\fslightbox.bundle.js" />
<_ContentIncludedByDefault Remove="wwwroot\assets\plugins\custom\fullcalendar\fullcalendar.bundle.css" />
<_ContentIncludedByDefault Remove="wwwroot\assets\plugins\custom\fullcalendar\fullcalendar.bundle.js" />
<_ContentIncludedByDefault Remove="wwwroot\assets\plugins\custom\jkanban\jkanban.bundle.css" />
<_ContentIncludedByDefault Remove="wwwroot\assets\plugins\custom\jkanban\jkanban.bundle.js" />
<_ContentIncludedByDefault Remove="wwwroot\assets\plugins\custom\jstree\images\jstree\32px.png" />
<_ContentIncludedByDefault Remove="wwwroot\assets\plugins\custom\jstree\images\jstree\throbber.gif" />
<_ContentIncludedByDefault Remove="wwwroot\assets\plugins\custom\jstree\jstree.bundle.css" />
<_ContentIncludedByDefault Remove="wwwroot\assets\plugins\custom\jstree\jstree.bundle.js" />
<_ContentIncludedByDefault Remove="wwwroot\assets\plugins\custom\leaflet\leaflet.bundle.css" />
<_ContentIncludedByDefault Remove="wwwroot\assets\plugins\custom\leaflet\leaflet.bundle.js" />
<_ContentIncludedByDefault Remove="wwwroot\assets\plugins\custom\prismjs\prismjs.bundle.css" />
<_ContentIncludedByDefault Remove="wwwroot\assets\plugins\custom\prismjs\prismjs.bundle.js" />
<_ContentIncludedByDefault Remove="wwwroot\assets\plugins\custom\tinymce\skins\content\dark\content.css" />
<_ContentIncludedByDefault Remove="wwwroot\assets\plugins\custom\tinymce\skins\content\dark\content.min.css" />
<_ContentIncludedByDefault Remove="wwwroot\assets\plugins\custom\tinymce\skins\content\default\content.css" />
<_ContentIncludedByDefault Remove="wwwroot\assets\plugins\custom\tinymce\skins\content\default\content.min.css" />
<_ContentIncludedByDefault Remove="wwwroot\assets\plugins\custom\tinymce\skins\content\document\content.css" />
<_ContentIncludedByDefault Remove="wwwroot\assets\plugins\custom\tinymce\skins\content\document\content.min.css" />
<_ContentIncludedByDefault Remove="wwwroot\assets\plugins\custom\tinymce\skins\content\writer\content.css" />
<_ContentIncludedByDefault Remove="wwwroot\assets\plugins\custom\tinymce\skins\content\writer\content.min.css" />
<_ContentIncludedByDefault Remove="wwwroot\assets\plugins\custom\tinymce\skins\ui\oxide-dark\content.css" />
<_ContentIncludedByDefault Remove="wwwroot\assets\plugins\custom\tinymce\skins\ui\oxide-dark\content.inline.css" />
<_ContentIncludedByDefault Remove="wwwroot\assets\plugins\custom\tinymce\skins\ui\oxide-dark\content.inline.min.css" />
<_ContentIncludedByDefault Remove="wwwroot\assets\plugins\custom\tinymce\skins\ui\oxide-dark\content.min.css" />
<_ContentIncludedByDefault Remove="wwwroot\assets\plugins\custom\tinymce\skins\ui\oxide-dark\content.mobile.css" />
<_ContentIncludedByDefault Remove="wwwroot\assets\plugins\custom\tinymce\skins\ui\oxide-dark\content.mobile.min.css" />
<_ContentIncludedByDefault Remove="wwwroot\assets\plugins\custom\tinymce\skins\ui\oxide-dark\skin.css" />
<_ContentIncludedByDefault Remove="wwwroot\assets\plugins\custom\tinymce\skins\ui\oxide-dark\skin.min.css" />
<_ContentIncludedByDefault Remove="wwwroot\assets\plugins\custom\tinymce\skins\ui\oxide-dark\skin.mobile.css" />
<_ContentIncludedByDefault Remove="wwwroot\assets\plugins\custom\tinymce\skins\ui\oxide-dark\skin.mobile.min.css" />
<_ContentIncludedByDefault Remove="wwwroot\assets\plugins\custom\tinymce\skins\ui\oxide-dark\skin.shadowdom.css" />
<_ContentIncludedByDefault Remove="wwwroot\assets\plugins\custom\tinymce\skins\ui\oxide-dark\skin.shadowdom.min.css" />
<_ContentIncludedByDefault Remove="wwwroot\assets\plugins\custom\tinymce\skins\ui\oxide\content.css" />
<_ContentIncludedByDefault Remove="wwwroot\assets\plugins\custom\tinymce\skins\ui\oxide\content.inline.css" />
<_ContentIncludedByDefault Remove="wwwroot\assets\plugins\custom\tinymce\skins\ui\oxide\content.inline.min.css" />
<_ContentIncludedByDefault Remove="wwwroot\assets\plugins\custom\tinymce\skins\ui\oxide\content.min.css" />
<_ContentIncludedByDefault Remove="wwwroot\assets\plugins\custom\tinymce\skins\ui\oxide\content.mobile.css" />
<_ContentIncludedByDefault Remove="wwwroot\assets\plugins\custom\tinymce\skins\ui\oxide\content.mobile.min.css" />
<_ContentIncludedByDefault Remove="wwwroot\assets\plugins\custom\tinymce\skins\ui\oxide\skin.css" />
<_ContentIncludedByDefault Remove="wwwroot\assets\plugins\custom\tinymce\skins\ui\oxide\skin.min.css" />
<_ContentIncludedByDefault Remove="wwwroot\assets\plugins\custom\tinymce\skins\ui\oxide\skin.mobile.css" />
<_ContentIncludedByDefault Remove="wwwroot\assets\plugins\custom\tinymce\skins\ui\oxide\skin.mobile.min.css" />
<_ContentIncludedByDefault Remove="wwwroot\assets\plugins\custom\tinymce\skins\ui\oxide\skin.shadowdom.css" />
<_ContentIncludedByDefault Remove="wwwroot\assets\plugins\custom\tinymce\skins\ui\oxide\skin.shadowdom.min.css" />
<_ContentIncludedByDefault Remove="wwwroot\assets\plugins\custom\tinymce\tinymce.bundle.js" />
<_ContentIncludedByDefault Remove="wwwroot\assets\plugins\custom\typedjs\typedjs.bundle.js" />
<_ContentIncludedByDefault Remove="wwwroot\assets\plugins\custom\vis-timeline\vis-timeline.bundle.css" />
<_ContentIncludedByDefault Remove="wwwroot\assets\plugins\custom\vis-timeline\vis-timeline.bundle.js" />
<_ContentIncludedByDefault Remove="wwwroot\assets\plugins\global\fonts\@fortawesome\fa-brands-400.ttf" />
<_ContentIncludedByDefault Remove="wwwroot\assets\plugins\global\fonts\@fortawesome\fa-brands-400.woff2" />
<_ContentIncludedByDefault Remove="wwwroot\assets\plugins\global\fonts\@fortawesome\fa-regular-400.ttf" />
<_ContentIncludedByDefault Remove="wwwroot\assets\plugins\global\fonts\@fortawesome\fa-regular-400.woff2" />
<_ContentIncludedByDefault Remove="wwwroot\assets\plugins\global\fonts\@fortawesome\fa-solid-900.ttf" />
<_ContentIncludedByDefault Remove="wwwroot\assets\plugins\global\fonts\@fortawesome\fa-solid-900.woff2" />
<_ContentIncludedByDefault Remove="wwwroot\assets\plugins\global\fonts\@fortawesome\fa-v4compatibility.ttf" />
<_ContentIncludedByDefault Remove="wwwroot\assets\plugins\global\fonts\@fortawesome\fa-v4compatibility.woff2" />
<_ContentIncludedByDefault Remove="wwwroot\assets\plugins\global\fonts\bootstrap-icons\bootstrap-icons.woff" />
<_ContentIncludedByDefault Remove="wwwroot\assets\plugins\global\fonts\bootstrap-icons\bootstrap-icons.woff2" />
<_ContentIncludedByDefault Remove="wwwroot\assets\plugins\global\fonts\fonticon\fonticon.css" />
<_ContentIncludedByDefault Remove="wwwroot\assets\plugins\global\fonts\fonticon\fonticon.eot" />
<_ContentIncludedByDefault Remove="wwwroot\assets\plugins\global\fonts\fonticon\fonticon.svg" />
<_ContentIncludedByDefault Remove="wwwroot\assets\plugins\global\fonts\fonticon\fonticon.ttf" />
<_ContentIncludedByDefault Remove="wwwroot\assets\plugins\global\fonts\fonticon\fonticon.woff" />
<_ContentIncludedByDefault Remove="wwwroot\assets\plugins\global\fonts\fonticon\fonticon.woff2" />
<_ContentIncludedByDefault Remove="wwwroot\assets\plugins\global\fonts\line-awesome\la-brands-400.eot" />
<_ContentIncludedByDefault Remove="wwwroot\assets\plugins\global\fonts\line-awesome\la-brands-400.svg" />
<_ContentIncludedByDefault Remove="wwwroot\assets\plugins\global\fonts\line-awesome\la-brands-400.ttf" />
<_ContentIncludedByDefault Remove="wwwroot\assets\plugins\global\fonts\line-awesome\la-brands-400.woff" />
<_ContentIncludedByDefault Remove="wwwroot\assets\plugins\global\fonts\line-awesome\la-brands-400.woff2" />
<_ContentIncludedByDefault Remove="wwwroot\assets\plugins\global\fonts\line-awesome\la-regular-400.eot" />
<_ContentIncludedByDefault Remove="wwwroot\assets\plugins\global\fonts\line-awesome\la-regular-400.svg" />
<_ContentIncludedByDefault Remove="wwwroot\assets\plugins\global\fonts\line-awesome\la-regular-400.ttf" />
<_ContentIncludedByDefault Remove="wwwroot\assets\plugins\global\fonts\line-awesome\la-regular-400.woff" />
<_ContentIncludedByDefault Remove="wwwroot\assets\plugins\global\fonts\line-awesome\la-regular-400.woff2" />
<_ContentIncludedByDefault Remove="wwwroot\assets\plugins\global\fonts\line-awesome\la-solid-900.eot" />
<_ContentIncludedByDefault Remove="wwwroot\assets\plugins\global\fonts\line-awesome\la-solid-900.svg" />
<_ContentIncludedByDefault Remove="wwwroot\assets\plugins\global\fonts\line-awesome\la-solid-900.ttf" />
<_ContentIncludedByDefault Remove="wwwroot\assets\plugins\global\fonts\line-awesome\la-solid-900.woff" />
<_ContentIncludedByDefault Remove="wwwroot\assets\plugins\global\fonts\line-awesome\la-solid-900.woff2" />
<_ContentIncludedByDefault Remove="wwwroot\assets\plugins\global\plugins.bundle.css" />
<_ContentIncludedByDefault Remove="wwwroot\assets\plugins\global\plugins.bundle.js" />
<_ContentIncludedByDefault Remove="wwwroot\assets\plugins\global\sourcemaps\tiny-slider.css.map" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
@@ -111,12 +210,4 @@
<AdditionalFiles Include="Shared\Views\Server\Settings\ServerResetSetting.razor" /> <AdditionalFiles Include="Shared\Views\Server\Settings\ServerResetSetting.razor" />
</ItemGroup> </ItemGroup>
<ItemGroup>
<Content Update="storage\configs\config.json.bak">
<ExcludeFromSingleFile>true</ExcludeFromSingleFile>
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
<CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
</Content>
</ItemGroup>
</Project> </Project>

View File

@@ -1,4 +1,4 @@
@using Microsoft.AspNetCore.Components.Web @using Microsoft.AspNetCore.Components.Web
@using Moonlight.App.Extensions @using Moonlight.App.Extensions
@using Moonlight.App.Repositories @using Moonlight.App.Repositories
@using Moonlight.App.Services @using Moonlight.App.Services
@@ -41,7 +41,6 @@
<link rel="stylesheet" type="text/css" href="/assets/css/style.bundle.css"/> <link rel="stylesheet" type="text/css" href="/assets/css/style.bundle.css"/>
<link rel="stylesheet" type="text/css" href="/assets/css/flashbang.css"/> <link rel="stylesheet" type="text/css" href="/assets/css/flashbang.css"/>
<link rel="stylesheet" type="text/css" href="/assets/css/snow.css"/>
<link rel="stylesheet" type="text/css" href="/assets/css/utils.css"/> <link rel="stylesheet" type="text/css" href="/assets/css/utils.css"/>
<link rel="stylesheet" type="text/css" href="/assets/css/boxicons.min.css"/> <link rel="stylesheet" type="text/css" href="/assets/css/boxicons.min.css"/>
<link rel="stylesheet" type="text/css" href="/assets/css/blazor.css"/> <link rel="stylesheet" type="text/css" href="/assets/css/blazor.css"/>
@@ -49,8 +48,7 @@
<link rel="stylesheet" type="text/css" href="/_content/XtermBlazor/XtermBlazor.css"/> <link rel="stylesheet" type="text/css" href="/_content/XtermBlazor/XtermBlazor.css"/>
<link rel="stylesheet" type="text/css" href="/_content/BlazorMonaco/lib/monaco-editor/min/vs/editor/editor.main.css"/> <link rel="stylesheet" type="text/css" href="/_content/BlazorMonaco/lib/monaco-editor/min/vs/editor/editor.main.css"/>
<link rel="stylesheet" type="text/css" href="/_content/Blazor.ContextMenu/blazorContextMenu.min.css"/> <link rel="stylesheet" type="text/css" href="/_content/Blazor.ContextMenu/blazorContextMenu.min.css"/>
<link rel="stylesheet" type="text/css" href="/assets/css/toastr.css"/>
<link href="/assets/plugins/global/plugins.bundle.css" rel="stylesheet" type="text/css"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/> <meta name="viewport" content="width=device-width, initial-scale=1"/>
<base href="~/"/> <base href="~/"/>
@@ -96,31 +94,38 @@
</div> </div>
</div> </div>
<script src="/assets/plugins/global/plugins.bundle.js"></script> <script src="/assets/js/popper.min.js"></script>
<script src="/assets/js/bootstrap.min.js"></script>
<script src="/_content/Blazor-ApexCharts/js/apex-charts.min.js"></script>
<script src="/_content/Blazor-ApexCharts/js/blazor-apex-charts.js"></script>
<script src="/_content/XtermBlazor/XtermBlazor.min.js"></script> <script src="/_content/XtermBlazor/XtermBlazor.min.js"></script>
<script src="/_content/BlazorTable/BlazorTable.min.js"></script> <script src="/_content/BlazorTable/BlazorTable.min.js"></script>
<script src="/_content/CurrieTechnologies.Razor.SweetAlert2/sweetAlert2.min.js"></script> <script src="/_content/CurrieTechnologies.Razor.SweetAlert2/sweetAlert2.min.js"></script>
<script src="/_content/Blazor.ContextMenu/blazorContextMenu.min.js"></script> <script src="/_content/Blazor.ContextMenu/blazorContextMenu.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@@shopify/draggable@1.0.0-beta.11/lib/draggable.bundle.js"></script> <script src="/assets/js/draggable.bundle.js"></script>
<script src="https://www.google.com/recaptcha/api.js"></script> <script src="https://www.google.com/recaptcha/api.js"></script>
<script src="https://cdn.jsdelivr.net/npm/xterm-addon-fit@0.7.0/lib/xterm-addon-fit.min.js"></script> <script src="/assets/js/xterm-addon-fit.min.js"></script>
<script src="/assets/js/jquery.min.js"></script>
<script src="/assets/js/toastr.min.js"></script>
<script src="/assets/js/apexcharts.js"></script>
<script src="/_content/BlazorMonaco/lib/monaco-editor/min/vs/loader.js"></script> <script src="/_content/BlazorMonaco/lib/monaco-editor/min/vs/loader.js"></script>
<script>require.config({ paths: { 'vs': '/_content/BlazorMonaco/lib/monaco-editor/min/vs' } });</script> <script>require.config({ paths: { 'vs': '/_content/BlazorMonaco/lib/monaco-editor/min/vs' } });</script>
<script src="/_content/BlazorMonaco/lib/monaco-editor/min/vs/editor/editor.main.js"></script> <script src="/_content/BlazorMonaco/lib/monaco-editor/min/vs/editor/editor.main.js"></script>
<script src="/_content/BlazorMonaco/jsInterop.js"></script> <script src="/_content/BlazorMonaco/jsInterop.js"></script>
<script src="/assets/js/scripts.bundle.js"></script>
<script src="/assets/js/moonlight.js"></script> <script src="/assets/js/moonlight.js"></script>
<script> <script>
moonlight.loading.registerXterm(); moonlight.loading.registerXterm();
</script> </script>
<script src="_content/Blazor-ApexCharts/js/apex-charts.min.js"></script>
<script src="_content/Blazor-ApexCharts/js/blazor-apex-charts.js"></script> <script src="_content/Blazor-ApexCharts/js/blazor-apex-charts.js"></script>
<script src="/_framework/blazor.server.js"></script> <script src="/_framework/blazor.server.js"></script>

View File

@@ -1,301 +1,17 @@
using BlazorDownloadFile;
using BlazorTable;
using HealthChecks.UI.Client;
using Moonlight.App.ApiClients.CloudPanel;
using Moonlight.App.ApiClients.Daemon;
using Moonlight.App.ApiClients.Modrinth;
using Moonlight.App.ApiClients.Paper;
using Moonlight.App.ApiClients.Telemetry;
using Moonlight.App.ApiClients.Wings;
using Moonlight.App.Database;
using Moonlight.App.Diagnostics.HealthChecks;
using Moonlight.App.Events;
using Moonlight.App.Helpers;
using Moonlight.App.Helpers.Wings;
using Moonlight.App.LogMigrator;
using Moonlight.App.Repositories;
using Moonlight.App.Repositories.Domains;
using Moonlight.App.Repositories.Servers;
using Moonlight.App.Services;
using Moonlight.App.Services.Addon;
using Moonlight.App.Services.Background;
using Moonlight.App.Services.DiscordBot;
using Moonlight.App.Services.Files;
using Moonlight.App.Services.Interop;
using Moonlight.App.Services.Mail;
using Moonlight.App.Services.Minecraft;
using Moonlight.App.Services.Notifications;
using Moonlight.App.Services.Sessions;
using Moonlight.App.Services.Statistics;
using Moonlight.App.Services.SupportChat;
using Sentry;
using Serilog;
using Serilog.Events;
using Stripe;
using SubscriptionService = Moonlight.App.Services.SubscriptionService;
namespace Moonlight namespace Moonlight
{ {
public class Program public class Program
{ {
private static readonly Startup Startup = new();
public static async Task Main(string[] args) public static async Task Main(string[] args)
{ {
// This will also copy all default config files Console.WriteLine("Moonlight Panel");
var configService = new ConfigService(new StorageService()); Console.WriteLine($"Copyright {DateTime.UtcNow.Year} moonlightpanel.xyz");
var shouldUseSentry = configService Console.WriteLine();
.Get()
.Moonlight.Sentry.Enable;
if (configService.DebugMode) await Startup.Init(args);
{ await Startup.Start();
if (shouldUseSentry)
{
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Verbose()
.Enrich.FromLogContext()
.WriteTo.Console(
outputTemplate: "{Timestamp:HH:mm:ss} [{Level:u3}] {SourceContext} {Message:lj}{NewLine}{Exception}")
.WriteTo.File(PathBuilder.File("storage", "logs", $"{DateTime.UtcNow:yyyy-MM-dd}.log"))
.WriteTo.Sentry(options =>
{
options.MinimumBreadcrumbLevel = LogEventLevel.Debug;
options.MinimumEventLevel = LogEventLevel.Warning;
})
.CreateLogger();
}
else
{
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Verbose()
.Enrich.FromLogContext()
.WriteTo.Console(
outputTemplate: "{Timestamp:HH:mm:ss} [{Level:u3}] {SourceContext} {Message:lj}{NewLine}{Exception}")
.WriteTo.File(PathBuilder.File("storage", "logs", $"{DateTime.UtcNow:yyyy-MM-dd}.log"))
.CreateLogger();
}
}
else
{
if (shouldUseSentry)
{
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Information()
.Enrich.FromLogContext()
.WriteTo.Console(
outputTemplate: "{Timestamp:HH:mm:ss} [{Level:u3}] {SourceContext} {Message:lj}{NewLine}{Exception}")
.WriteTo.Sentry(options =>
{
options.MinimumBreadcrumbLevel = LogEventLevel.Information;
options.MinimumEventLevel = LogEventLevel.Warning;
})
.WriteTo.File(PathBuilder.File("storage", "logs", $"{DateTime.UtcNow:yyyy-MM-dd}.log"))
.CreateLogger();
}
else
{
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Information()
.Enrich.FromLogContext()
.WriteTo.Console(
outputTemplate: "{Timestamp:HH:mm:ss} [{Level:u3}] {SourceContext} {Message:lj}{NewLine}{Exception}")
.WriteTo.File(PathBuilder.File("storage", "logs", $"{DateTime.UtcNow:yyyy-MM-dd}.log"))
.CreateLogger();
}
}
Logger.Info("Running pre-init tasks");
var databaseCheckupService = new DatabaseCheckupService(configService);
await databaseCheckupService.Perform();
var builder = WebApplication.CreateBuilder(args);
// Switch to logging.net injection
// TODO: Enable in production
builder.Logging.ClearProviders();
builder.Logging.AddProvider(new LogMigratorProvider());
// Add services to the container.
builder.Services.AddRazorPages();
builder.Services.AddServerSideBlazor()
.AddHubOptions(options =>
{
options.MaximumReceiveMessageSize = 10000000;
options.ClientTimeoutInterval = TimeSpan.FromSeconds(30);
options.HandshakeTimeout = TimeSpan.FromSeconds(10);
});
builder.Services.AddHttpContextAccessor();
builder.Services.AddHealthChecks()
.AddCheck<DatabaseHealthCheck>("Database")
.AddCheck<NodeHealthCheck>("Nodes")
.AddCheck<DaemonHealthCheck>("Daemons");
// Sentry
if (shouldUseSentry)
{
builder.WebHost.UseSentry(options =>
{
options.Dsn = configService
.Get()
.Moonlight.Sentry.Dsn;
options.Debug = configService.DebugMode;
options.DiagnosticLevel = SentryLevel.Warning;
options.TracesSampleRate = 1.0;
options.DiagnosticLogger = new SentryDiagnosticsLogger(SentryLevel.Warning);
});
}
// Databases
builder.Services.AddDbContext<DataContext>();
// Repositories
builder.Services.AddScoped<UserRepository>();
builder.Services.AddScoped<NodeRepository>();
builder.Services.AddScoped<ServerRepository>();
builder.Services.AddScoped<ServerBackupRepository>();
builder.Services.AddScoped<ImageRepository>();
builder.Services.AddScoped<DomainRepository>();
builder.Services.AddScoped<SharedDomainRepository>();
builder.Services.AddScoped<RevokeRepository>();
builder.Services.AddScoped<NotificationRepository>();
builder.Services.AddScoped<DdosAttackRepository>();
builder.Services.AddScoped<SubscriptionRepository>();
builder.Services.AddScoped<LoadingMessageRepository>();
builder.Services.AddScoped<NewsEntryRepository>();
builder.Services.AddScoped<NodeAllocationRepository>();
builder.Services.AddScoped<StatisticsRepository>();
builder.Services.AddScoped(typeof(Repository<>));
// Services
builder.Services.AddSingleton<ConfigService>();
builder.Services.AddSingleton<StorageService>();
builder.Services.AddScoped<CookieService>();
builder.Services.AddScoped<IdentityService>();
builder.Services.AddScoped<IpLocateService>();
builder.Services.AddScoped<AlertService>();
builder.Services.AddScoped<SmartTranslateService>();
builder.Services.AddScoped<UserService>();
builder.Services.AddScoped<TotpService>();
builder.Services.AddScoped<ToastService>();
builder.Services.AddScoped<NodeService>();
builder.Services.AddScoped<ServerService>();
builder.Services.AddSingleton<PaperService>();
builder.Services.AddScoped<ClipboardService>();
builder.Services.AddSingleton<ResourceService>();
builder.Services.AddScoped<DomainService>();
builder.Services.AddScoped<OneTimeJwtService>();
builder.Services.AddSingleton<NotificationServerService>();
builder.Services.AddScoped<NotificationAdminService>();
builder.Services.AddScoped<ModalService>();
builder.Services.AddScoped<SmartDeployService>();
builder.Services.AddScoped<WebSpaceService>();
builder.Services.AddScoped<StatisticsViewService>();
builder.Services.AddSingleton<DateTimeService>();
builder.Services.AddSingleton<EventSystem>();
builder.Services.AddScoped<FileDownloadService>();
builder.Services.AddScoped<ForgeService>();
builder.Services.AddScoped<FabricService>();
builder.Services.AddSingleton<BucketService>();
builder.Services.AddScoped<RatingService>();
builder.Services.AddScoped<ReCaptchaService>();
builder.Services.AddScoped<IpBanService>();
builder.Services.AddSingleton<OAuth2Service>();
builder.Services.AddScoped<DynamicBackgroundService>();
builder.Services.AddScoped<ServerAddonPluginService>();
builder.Services.AddScoped<KeyListenerService>();
builder.Services.AddScoped<PopupService>();
builder.Services.AddScoped<SubscriptionService>();
builder.Services.AddScoped<BillingService>();
builder.Services.AddScoped<SessionClientService>();
builder.Services.AddSingleton<SessionServerService>();
builder.Services.AddScoped<MailService>();
// Support chat
builder.Services.AddSingleton<SupportChatServerService>();
builder.Services.AddScoped<SupportChatClientService>();
builder.Services.AddScoped<SupportChatAdminService>();
// Helpers
builder.Services.AddSingleton<SmartTranslateHelper>();
builder.Services.AddScoped<WingsApiHelper>();
builder.Services.AddScoped<WingsServerConverter>();
builder.Services.AddSingleton<WingsJwtHelper>();
builder.Services.AddScoped<WingsConsoleHelper>();
builder.Services.AddSingleton<PaperApiHelper>();
builder.Services.AddSingleton<HostSystemHelper>();
builder.Services.AddScoped<DaemonApiHelper>();
builder.Services.AddScoped<CloudPanelApiHelper>();
builder.Services.AddScoped<ModrinthApiHelper>();
builder.Services.AddScoped<TelemetryApiHelper>();
// Background services
builder.Services.AddSingleton<DiscordBotService>();
builder.Services.AddSingleton<StatisticsCaptureService>();
builder.Services.AddSingleton<DiscordNotificationService>();
builder.Services.AddSingleton<CleanupService>();
builder.Services.AddSingleton<MalwareScanService>();
builder.Services.AddSingleton<TelemetryService>();
builder.Services.AddSingleton<TempMailService>();
// Other
builder.Services.AddSingleton<MoonlightService>();
// Third party services
builder.Services.AddBlazorTable();
builder.Services.AddBlazorContextMenu();
builder.Services.AddBlazorDownloadFile();
StripeConfiguration.ApiKey = configService
.Get()
.Moonlight.Stripe.ApiKey;
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
// Sentry
if (shouldUseSentry)
{
app.UseSentryTracing();
}
app.UseStaticFiles();
app.UseRouting();
app.UseWebSockets();
app.MapControllers();
app.MapBlazorHub();
app.MapFallbackToPage("/_Host");
app.MapHealthChecks("/_health", new()
{
ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse
});
// AutoStart services
_ = app.Services.GetRequiredService<CleanupService>();
_ = app.Services.GetRequiredService<DiscordBotService>();
_ = app.Services.GetRequiredService<StatisticsCaptureService>();
_ = app.Services.GetRequiredService<DiscordNotificationService>();
_ = app.Services.GetRequiredService<MalwareScanService>();
_ = app.Services.GetRequiredService<TelemetryService>();
_ = app.Services.GetRequiredService<TempMailService>();
_ = app.Services.GetRequiredService<MoonlightService>();
// Discord bot service
//var discordBotService = app.Services.GetRequiredService<DiscordBotService>();
await app.RunAsync();
} }
} }
} }

View File

@@ -9,7 +9,7 @@
"ASPNETCORE_ENVIRONMENT": "Development", "ASPNETCORE_ENVIRONMENT": "Development",
"ML_DEBUG": "true" "ML_DEBUG": "true"
}, },
"applicationUrl": "http://moonlight.testy:5118;https://localhost:7118;http://localhost:5118", "applicationUrl": "http://localhost:5118;http://moonlight.owo:5118",
"dotnetRunMessages": true "dotnetRunMessages": true
}, },
"Live DB": "Live DB":
@@ -21,7 +21,7 @@
"ML_DEBUG": "true", "ML_DEBUG": "true",
"ML_CONFIG_PATH": "storage\\configs\\live_config.json" "ML_CONFIG_PATH": "storage\\configs\\live_config.json"
}, },
"applicationUrl": "http://moonlight.testy:5118;https://localhost:7118;http://localhost:5118", "applicationUrl": "http://moonlight.owo:5118;http://localhost:5118",
"dotnetRunMessages": true "dotnetRunMessages": true
}, },
"Dev DB 1": "Dev DB 1":
@@ -33,7 +33,19 @@
"ML_DEBUG": "true", "ML_DEBUG": "true",
"ML_CONFIG_PATH": "storage\\configs\\dev_1_config.json" "ML_CONFIG_PATH": "storage\\configs\\dev_1_config.json"
}, },
"applicationUrl": "http://moonlight.testy:5118;https://localhost:7118;http://localhost:5118", "applicationUrl": "http://moonlight.owo:5118;http://localhost:5118",
"dotnetRunMessages": true
},
"Dev DB 2":
{
"commandName": "Project",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development",
"ML_DEBUG": "true",
"ML_CONFIG_PATH": "storage\\configs\\dev_2_config.json"
},
"applicationUrl": "http://moonlight.owo:5118;http://localhost:5118",
"dotnetRunMessages": true "dotnetRunMessages": true
} }
} }

View File

@@ -1,13 +0,0 @@
### Some explanations
defaultstorage:
This directory is for the default assets of a moonlight instance, e.g. lang files, images etc
storage:
This directory is empty in fresh moonlight instances and will be populated with example config upon first run.
Before using moonlight this config file has to be modified.
Also resources are going to be copied from the default storage to this storage.
To access files in this storage we recommend to use the PathBuilder functions to ensure cross platform compatibility.
The storage directory should be mounted to a specific path when using docker container so when the container is replaced/rebuild your storage will not be modified

View File

@@ -55,11 +55,14 @@
</div> </div>
} }
@if (OAuth2Service.Providers.Any())
{
<div class="separator separator-content my-14"> <div class="separator separator-content my-14">
<span class="w-125px text-gray-500 fw-semibold fs-7"> <span class="w-125px text-gray-500 fw-semibold fs-7">
<TL>Or with email</TL> <TL>Or with email</TL>
</span> </span>
</div> </div>
}
<div class="mt-3 mb-3"> <div class="mt-3 mb-3">
<InputText @bind-Value="LoginData.Email" type="email" placeholder="@(SmartTranslateService.Translate("Email"))" class="form-control bg-transparent"/> <InputText @bind-Value="LoginData.Email" type="email" placeholder="@(SmartTranslateService.Translate("Email"))" class="form-control bg-transparent"/>

View File

@@ -48,11 +48,14 @@
</div> </div>
} }
@if (OAuth2Service.Providers.Any())
{
<div class="separator separator-content my-10"> <div class="separator separator-content my-10">
<span class="w-125px text-gray-500 fw-semibold fs-7"> <span class="w-125px text-gray-500 fw-semibold fs-7">
<TL>Or with email</TL> <TL>Or with email</TL>
</span> </span>
</div> </div>
}
<SmartForm Model="UserRegisterModel" OnValidSubmit="CreateUser"> <SmartForm Model="UserRegisterModel" OnValidSubmit="CreateUser">
<div class="fv-row mb-4 fv-plugins-icon-container"> <div class="fv-row mb-4 fv-plugins-icon-container">

View File

@@ -12,8 +12,9 @@
@inject AlertService AlertService @inject AlertService AlertService
@inject ConfigService ConfigService @inject ConfigService ConfigService
@inject SmartTranslateService SmartTranslateService @inject SmartTranslateService SmartTranslateService
@inject NavigationManager NavigationManager
@if (Crashed) @if (HardCrashed)
{ {
<div class="card card-flush h-md-100"> <div class="card card-flush h-md-100">
<div class="card-body d-flex flex-column justify-content-between mt-9 bgi-no-repeat bgi-size-cover bgi-position-x-center pb-0"> <div class="card-body d-flex flex-column justify-content-between mt-9 bgi-no-repeat bgi-size-cover bgi-position-x-center pb-0">
@@ -30,6 +31,16 @@
</div> </div>
</div> </div>
} }
else if (SoftCrashed)
{
<div class="card card-body bg-danger mb-5">
<span class="text-center">
@(ErrorMessage)
</span>
</div>
@ChildContent
}
else else
{ {
@ChildContent @ChildContent
@@ -37,7 +48,22 @@ else
@code @code
{ {
private bool Crashed = false; private bool HardCrashed = false;
private bool SoftCrashed = false;
private string ErrorMessage = "";
protected override void OnInitialized()
{
NavigationManager.LocationChanged += OnPathChanged;
}
private void OnPathChanged(object? sender, LocationChangedEventArgs e)
{
if (SoftCrashed)
SoftCrashed = false;
StateHasChanged();
}
protected override async Task OnErrorAsync(Exception exception) protected override async Task OnErrorAsync(Exception exception)
{ {
@@ -50,74 +76,57 @@ else
{ {
if (displayException.DoNotTranslate) if (displayException.DoNotTranslate)
{ {
await AlertService.Error( await SoftCrash(displayException.Message);
displayException.Message
);
} }
else else
{ {
await AlertService.Error( await SoftCrash(SmartTranslateService.Translate(displayException.Message));
SmartTranslateService.Translate(displayException.Message)
);
} }
} }
else if (exception is CloudflareException cloudflareException) else if (exception is CloudflareException cloudflareException)
{ {
await AlertService.Error( await SoftCrash(SmartTranslateService.Translate("Error from cloudflare: ") + cloudflareException.Message);
SmartTranslateService.Translate("Error from cloudflare api"),
cloudflareException.Message
);
} }
else if (exception is WingsException wingsException) else if (exception is WingsException wingsException)
{ {
await AlertService.Error( await SoftCrash(SmartTranslateService.Translate("Error from wings: ") + wingsException.Message);
SmartTranslateService.Translate("Error from wings"),
wingsException.Message
);
//TODO: Error log service
Logger.Warn($"Wings exception status code: {wingsException.StatusCode}"); Logger.Warn($"Wings exception status code: {wingsException.StatusCode}");
} }
else if (exception is DaemonException daemonException) else if (exception is DaemonException daemonException)
{ {
await AlertService.Error( await SoftCrash(SmartTranslateService.Translate("Error from daemon: ") + daemonException.Message);
SmartTranslateService.Translate("Error from daemon"),
daemonException.Message
);
Logger.Warn($"Wings exception status code: {daemonException.StatusCode}"); Logger.Warn($"Wings exception status code: {daemonException.StatusCode}");
} }
else if (exception is ModrinthException modrinthException) else if (exception is ModrinthException modrinthException)
{ {
await AlertService.Error( await SoftCrash(SmartTranslateService.Translate("Error from modrinth: ") + modrinthException.Message);
SmartTranslateService.Translate("Error from modrinth"),
modrinthException.Message
);
} }
else if (exception is CloudPanelException cloudPanelException) else if (exception is CloudPanelException cloudPanelException)
{ {
await AlertService.Error( await SoftCrash(SmartTranslateService.Translate("Error from cloudpanel: ") + cloudPanelException.Message);
SmartTranslateService.Translate("Error from cloud panel"),
cloudPanelException.Message
);
} }
else if (exception is NotImplementedException) else if (exception is NotImplementedException)
{ {
await AlertService.Error(SmartTranslateService.Translate("This function is not implemented")); await SoftCrash(SmartTranslateService.Translate("This function is not implemented"));
} }
else if (exception is StripeException stripeException) else if (exception is StripeException stripeException)
{ {
await AlertService.Error( await SoftCrash(SmartTranslateService.Translate("Error from stripe: ") + stripeException.Message);
SmartTranslateService.Translate("Unknown error from stripe"),
stripeException.Message
);
} }
else else
{ {
Logger.Warn(exception); Logger.Warn(exception);
Crashed = true; HardCrashed = true;
await InvokeAsync(StateHasChanged); await InvokeAsync(StateHasChanged);
} }
} }
private Task SoftCrash(string message)
{
SoftCrashed = true;
ErrorMessage = message;
return Task.CompletedTask;
}
} }

View File

@@ -11,6 +11,13 @@
@implements IDisposable @implements IDisposable
<div class="card bg-black rounded"> <div class="card bg-black rounded">
@if (ShowHeader)
{
<div class="card-header">
<span class="card-title">@(Header)</span>
</div>
}
<div class="card-body"> <div class="card-body">
<MonacoEditor CssClass="h-100" @ref="Editor" Id="vseditor" ConstructionOptions="(x) => EditorOptions"/> <MonacoEditor CssClass="h-100" @ref="Editor" Id="vseditor" ConstructionOptions="(x) => EditorOptions"/>
</div> </div>
@@ -44,6 +51,12 @@
[Parameter] [Parameter]
public bool HideControls { get; set; } = false; public bool HideControls { get; set; } = false;
[Parameter]
public bool ShowHeader { get; set; } = false;
[Parameter]
public string Header { get; set; } = "Header.changeme.txt";
// Events // Events
[Parameter] [Parameter]
public Action<string> OnSubmit { get; set; } public Action<string> OnSubmit { get; set; }

View File

@@ -17,7 +17,9 @@
Language="@EditorLanguage" Language="@EditorLanguage"
OnCancel="() => Cancel()" OnCancel="() => Cancel()"
OnSubmit="(_) => Save()" OnSubmit="(_) => Save()"
HideControls="false"> HideControls="false"
ShowHeader="true"
Header="@(EditingFile.Name)">
</FileEditor> </FileEditor>
} }
else else

View File

@@ -2,7 +2,7 @@
@using BlazorContextMenu @using BlazorContextMenu
@using Moonlight.App.Helpers @using Moonlight.App.Helpers
<div class="table-responsive"> <div class="table-responsive single-color-scrollbar">
<div class="dataTables_scroll"> <div class="dataTables_scroll">
<div class="dataTables_scrollHead"> <div class="dataTables_scrollHead">
<div class="dataTables_scrollHeadInner"> <div class="dataTables_scrollHeadInner">
@@ -35,6 +35,8 @@
<tbody class="fw-semibold text-gray-600"> <tbody class="fw-semibold text-gray-600">
<LazyLoader Load="Load"> <LazyLoader Load="Load">
<ContentBlock @ref="ContentBlock" AllowContentOverride="true"> <ContentBlock @ref="ContentBlock" AllowContentOverride="true">
@if (Access.CurrentPath != "/")
{
<tr class="even"> <tr class="even">
<td class="w-10px"> <td class="w-10px">
</td> </td>
@@ -57,6 +59,7 @@
</div> </div>
</td> </td>
</tr> </tr>
}
@foreach (var file in Data) @foreach (var file in Data)
{ {
<tr class="even"> <tr class="even">

View File

@@ -0,0 +1,22 @@
<div class="card mb-5 mb-xl-10">
<div class="card-body pt-0 pb-0">
<ul class="nav nav-stretch nav-line-tabs nav-line-tabs-2x border-transparent fs-5 fw-bold">
<li class="nav-item mt-2">
<a class="nav-link text-active-primary ms-0 me-10 py-5 @(Index == 0 ? "active" : "")" href="/admin/domains">
<TL>Domains</TL>
</a>
</li>
<li class="nav-item mt-2">
<a class="nav-link text-active-primary ms-0 me-10 py-5 @(Index == 1 ? "active" : "")" href="/admin/domains/shared">
<TL>Shared domains</TL>
</a>
</li>
</ul>
</div>
</div>
@code
{
[Parameter]
public int Index { get; set; } = 0;
}

View File

@@ -26,6 +26,11 @@
<TL>Logs</TL> <TL>Logs</TL>
</a> </a>
</li> </li>
<li class="nav-item mt-2">
<a class="nav-link text-active-primary ms-0 me-10 py-5 @(Index == 5 ? "active" : "")" href="/admin/security/ddos">
<TL>Ddos protection</TL>
</a>
</li>
</ul> </ul>
</div> </div>
</div> </div>

View File

@@ -0,0 +1,22 @@
<div class="card mb-5 mb-xl-10">
<div class="card-body pt-0 pb-0">
<ul class="nav nav-stretch nav-line-tabs nav-line-tabs-2x border-transparent fs-5 fw-bold">
<li class="nav-item mt-2">
<a class="nav-link text-active-primary ms-0 me-10 py-5 @(Index == 0 ? "active" : "")" href="/admin/statistics">
<TL>Overview</TL>
</a>
</li>
<li class="nav-item mt-2">
<a class="nav-link text-active-primary ms-0 me-10 py-5 @(Index == 1 ? "active" : "")" href="/admin/statistics/live">
<TL>Live data</TL>
</a>
</li>
</ul>
</div>
</div>
@code
{
[Parameter]
public int Index { get; set; } = 0;
}

View File

@@ -34,6 +34,11 @@
<TL>Mail</TL> <TL>Mail</TL>
</a> </a>
</li> </li>
<li class="nav-item mt-2">
<a class="nav-link text-active-primary ms-0 me-10 py-5 @(Index == 10 ? "active" : "")" href="/admin/system/plugins">
<TL>Plugins</TL>
</a>
</li>
</ul> </ul>
</div> </div>
</div> </div>

View File

@@ -41,13 +41,6 @@
} }
<div class="app-navbar flex-shrink-0"> <div class="app-navbar flex-shrink-0">
<div class="app-navbar-item ms-1 ms-lg-3">
<ThemeSwitcher
ToggleBtnClass="btn btn-icon btn-custom btn-icon-muted btn-active-light btn-active-color-primary w-35px h-35px w-md-40px h-md-40px"
ToggleBtnIconClass="svg-icon svg-icon-2">
</ThemeSwitcher>
</div>
@if (User != null) @if (User != null)
{ {
<div class="app-navbar-item ms-1 ms-lg-3"> <div class="app-navbar-item ms-1 ms-lg-3">
@@ -56,43 +49,34 @@
</a> </a>
</div> </div>
<div class="app-navbar-item ms-1 ms-lg-3" id="kt_header_user_menu_toggle"> <div class="app-navbar-item ms-1 ms-lg-3 dropdown">
<div class="cursor-pointer symbol symbol-35px symbol-md-40px" data-kt-menu-trigger="click" data-kt-menu-attach="parent" data-kt-menu-placement="bottom-end"> <!-- Trigger -->
<img alt="Avatar" src="/api/moonlight/avatar/@(User.Id)"/> <a class="cursor-pointer d-block symbol symbol-35px symbol-md-40px" href="#" role="button" id="dropdownMenuLink" data-bs-toggle="dropdown" aria-expanded="false">
</div> <img alt="Avatar" src="/api/moonlight/avatar/@(User.Id)" width="35" height="35">
</a>
<div class="menu menu-sub menu-sub-dropdown menu-column menu-rounded menu-gray-800 menu-state-bg menu-state-primary fw-semibold py-4 fs-6 w-275px" data-kt-menu="true"> <!-- Dropdown Menu -->
<div class="menu-item px-3"> <div class="dropdown-menu dropdown-menu-end w-275px p-5" aria-labelledby="dropdownMenuLink">
<div class="menu-content d-flex align-items-center px-3"> <div class="dropdown-item py-4 bg-body bg-hover-body ps-0">
<div class="symbol symbol-50px me-5"> <div class="d-flex align-items-center">
<img alt="Avatar" src="/api/moonlight/avatar/@(User.Id)"/> <img alt="Avatar" src="/api/moonlight/avatar/@(User.Id)" class="rounded-circle me-3" width="50" height="50">
</div>
<div class="d-flex flex-column"> <div class="d-flex flex-column">
<div class="fw-bold d-flex align-items-center fs-5"> <div class="fw-bold d-flex align-items-center">
<div class="@(User.StreamerMode ? "blur" : "")"> <div class="@(User.StreamerMode ? "blur" : "")">
@(User.FirstName) @(User.LastName) @(User.FirstName) @(User.LastName)
</div> </div>
@if (User.Admin) @if (User.Admin)
{ {
<span class="badge badge-light-success fw-bold fs-8 px-2 py-1 ms-2">Admin</span> <span class="badge bg-success fw-bold ms-2">Admin</span>
} }
</div> </div>
<a class="fw-semibold text-muted text-hover-primary fs-7 @(User.StreamerMode ? "blur" : "")">@(User.Email)</a> <a class="fw-semibold text-muted text-decoration-none @(User.StreamerMode ? "blur" : "")">@User.Email</a>
</div> </div>
</div> </div>
</div> </div>
<div class="separator my-2"></div> <hr class="dropdown-divider">
<div class="menu-item px-5 my-1"> <a href="/profile" class="dropdown-item rounded fs-7 py-4">Profile</a>
<a href="/profile" class="menu-link px-5"> <a href="#" @onclick:preventDefault @onclick="Logout" class="dropdown-item rounded fs-7 py-4">Logout</a>
<TL>Profile</TL>
</a>
</div>
<div class="menu-item px-5">
<a @onclick="Logout" class="menu-link px-5">
<TL>Logout</TL>
</a>
</div>
</div> </div>
</div> </div>
} }

View File

@@ -1,25 +0,0 @@
@using Moonlight.App.Services.Files
@inject ResourceService ResourceService
<div id="kt_app_header" class="app-header">
<div class="app-container container-fluid d-flex align-items-stretch justify-content-between">
<div class="d-flex align-items-center d-lg-none ms-n2 me-2" title="Show sidebar menu">
<div class="btn btn-icon btn-active-color-primary w-35px h-35px" id="kt_app_sidebar_mobile_toggle">
<i class="bx bx-menu bx-md"></i>
</div>
</div>
<div class="d-flex align-items-center flex-grow-1 flex-lg-grow-0">
<a href="/" class="d-lg-none">
<img alt="Logo" src="@(ResourceService.Image("logo.svg"))" class="h-30px"/>
</a>
</div>
<div class="d-flex align-items-stretch justify-content-between flex-lg-grow-1" id="kt_app_header_wrapper">
<div class="app-header-menu app-header-mobile-drawer align-items-stretch" data-kt-drawer="true" data-kt-drawer-name="app-header-menu" data-kt-drawer-activate="{default: true, lg: false}" data-kt-drawer-overlay="true" data-kt-drawer-width="225px" data-kt-drawer-direction="end" data-kt-drawer-toggle="#kt_app_header_menu_toggle" data-kt-swapper="true" data-kt-swapper-mode="{default: 'append', lg: 'prepend'}" data-kt-swapper-parent="{default: '#kt_app_body', lg: '#kt_app_header_wrapper'}">
<div class="menu menu-rounded menu-column menu-lg-row my-5 my-lg-0 align-items-stretch fw-semibold px-2 px-lg-0" id="kt_app_header_menu" data-kt-menu="true">
</div>
</div>
<Navbar></Navbar>
</div>
</div>
</div>

View File

@@ -1,57 +0,0 @@
@using Moonlight.App.Services.Sessions
@using Moonlight.App.Database.Entities
@using Moonlight.App.Services
@using Moonlight.App.Services.Files
@inject IdentityService IdentityService
@inject ResourceService ResourceService
@inject IJSRuntime JsRuntime
<div id="kt_app_sidebar" class="app-sidebar flex-column" data-kt-drawer="true" data-kt-drawer-name="app-sidebar" data-kt-drawer-activate="{default: true, lg: false}" data-kt-drawer-overlay="true" data-kt-drawer-width="225px" data-kt-drawer-direction="start" data-kt-drawer-toggle="#kt_app_sidebar_mobile_toggle">
<div class="app-sidebar-logo px-6" id="kt_app_sidebar_logo">
<a href="@(User != null ? "/" : "/login")">
@if (sidebar == "dark-sidebar")
{
<img alt="Logo" src="@(ResourceService.Image("logolong.png"))" class="h-45px app-sidebar-logo-default"/>
}
else
{
if (sidebar == "light-sidebar")
{
<img alt="Logo" src="@(ResourceService.Image("logo.svg"))" class="theme-light-show h-20px app-sidebar-logo-default"/>
<img alt="Logo" src="@(ResourceService.Image("logo.svg"))" class="theme-dark-show h-20px app-sidebar-logo-default"/>
}
}
<img alt="Logo" src="@(ResourceService.Image("logo.svg"))" class="h-20px app-sidebar-logo-minimize"/>
</a>
<div id="kt_app_sidebar_toggle" class="app-sidebar-toggle btn btn-icon btn-shadow btn-sm btn-color-muted btn-active-color-primary body-bg h-30px w-30px position-absolute top-50 start-100 translate-middle rotate" data-kt-toggle="true" data-kt-toggle-state="active" data-kt-toggle-target="body" data-kt-toggle-name="app-sidebar-minimize">
<i class="bx bx-chevrons-left bx-md"></i>
</div>
</div>
<SidebarMenu></SidebarMenu>
<div class="app-sidebar-footer flex-column-auto pt-2 pb-6 px-6" id="kt_app_sidebar_footer">
<a href="/support" class="btn btn-flex flex-center btn-custom btn-primary overflow-hidden text-nowrap px-0 h-40px w-100 btn-label">
<i class="bx bx-sm bx-support"></i>
</a>
</div>
</div>
@code
{
private string sidebar;
private User? User;
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender)
{
User = IdentityService.User;
sidebar = await JsRuntime.InvokeAsync<string>("document.body.getAttribute", "data-kt-app-layout");
StateHasChanged();
}
}
}

Some files were not shown because too many files have changed in this diff Show More