99 lines
2.5 KiB
Go
99 lines
2.5 KiB
Go
package sandbox
|
|
|
|
import (
|
|
_ "embed"
|
|
|
|
"Moonshark/core/utils/logger"
|
|
|
|
luajit "git.sharkk.net/Sky/LuaJIT-to-Go"
|
|
)
|
|
|
|
//go:embed lua/sandbox.lua
|
|
var sandboxLua string
|
|
|
|
// InitializeSandbox loads the embedded Lua sandbox code into a Lua state
|
|
func InitializeSandbox(state *luajit.State) error {
|
|
// Compile once, use many times
|
|
bytecodeOnce.Do(precompileSandbox)
|
|
|
|
if sandboxBytecode != nil {
|
|
logger.Debug("Loading sandbox.lua from precompiled bytecode")
|
|
return state.LoadAndRunBytecode(sandboxBytecode, "sandbox.lua")
|
|
}
|
|
|
|
// Fallback if compilation failed
|
|
logger.Warning("Using non-precompiled sandbox.lua (bytecode compilation failed)")
|
|
return state.DoString(sandboxLua)
|
|
}
|
|
|
|
// ModuleInitializers stores initializer functions for core modules
|
|
type ModuleInitializers struct {
|
|
HTTP func(*luajit.State) error
|
|
Util func(*luajit.State) error
|
|
Session func(*luajit.State) error
|
|
Cookie func(*luajit.State) error
|
|
CSRF func(*luajit.State) error
|
|
}
|
|
|
|
// DefaultInitializers returns the default set of initializers
|
|
func DefaultInitializers() *ModuleInitializers {
|
|
return &ModuleInitializers{
|
|
HTTP: func(state *luajit.State) error {
|
|
// Register the native Go function first
|
|
if err := state.RegisterGoFunction("__http_request", httpRequest); err != nil {
|
|
logger.Error("[HTTP Module] Failed to register __http_request function: %v", err)
|
|
return err
|
|
}
|
|
return nil
|
|
},
|
|
Util: func(state *luajit.State) error {
|
|
// Register util functions
|
|
return RegisterModule(state, "util", UtilModuleFunctions())
|
|
},
|
|
Session: func(state *luajit.State) error {
|
|
// Session doesn't need special initialization
|
|
return nil
|
|
},
|
|
Cookie: func(state *luajit.State) error {
|
|
// Cookie doesn't need special initialization
|
|
return nil
|
|
},
|
|
CSRF: func(state *luajit.State) error {
|
|
// CSRF doesn't need special initialization
|
|
return nil
|
|
},
|
|
}
|
|
}
|
|
|
|
// InitializeAll initializes all modules in the Lua state
|
|
func InitializeAll(state *luajit.State, initializers *ModuleInitializers) error {
|
|
// Set up dependencies first
|
|
if err := initializers.Util(state); err != nil {
|
|
return err
|
|
}
|
|
|
|
if err := initializers.HTTP(state); err != nil {
|
|
return err
|
|
}
|
|
|
|
// Load the embedded sandbox code
|
|
if err := InitializeSandbox(state); err != nil {
|
|
return err
|
|
}
|
|
|
|
// Initialize the rest of the modules
|
|
if err := initializers.Session(state); err != nil {
|
|
return err
|
|
}
|
|
|
|
if err := initializers.Cookie(state); err != nil {
|
|
return err
|
|
}
|
|
|
|
if err := initializers.CSRF(state); err != nil {
|
|
return err
|
|
}
|
|
|
|
return nil
|
|
}
|