package sandbox import ( "crypto/rand" "encoding/base64" "Moonshark/core/utils/logger" luajit "git.sharkk.net/Sky/LuaJIT-to-Go" ) // UtilModuleInitFunc returns an initializer for the util module func UtilModuleInitFunc() func(*luajit.State) error { return func(state *luajit.State) error { return RegisterModule(state, "util", UtilModuleFunctions()) } } // UtilModuleFunctions returns all functions for the util module func UtilModuleFunctions() map[string]luajit.GoFunction { return map[string]luajit.GoFunction{ "generate_token": GenerateToken, } } // GenerateToken creates a cryptographically secure random token func GenerateToken(s *luajit.State) int { // Get the length from the Lua arguments (default to 32) length := 32 if s.GetTop() >= 1 && s.IsNumber(1) { length = int(s.ToNumber(1)) } // Enforce minimum length for security if length < 16 { length = 16 } // Generate secure random bytes tokenBytes := make([]byte, length) if _, err := rand.Read(tokenBytes); err != nil { s.PushString("") logger.Error("Failed to generate secure token: %v", err) return 1 // Return empty string on error } // Encode as base64 token := base64.RawURLEncoding.EncodeToString(tokenBytes) // Trim to requested length (base64 might be longer) if len(token) > length { token = token[:length] } // Push the token to the Lua stack s.PushString(token) return 1 // One return value }