2026-05-30 14:11:56 +08:00
|
|
|
package jsmod
|
|
|
|
|
|
2026-05-30 19:26:01 +08:00
|
|
|
import (
|
|
|
|
|
"context"
|
|
|
|
|
"sync"
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
type contextKey string
|
|
|
|
|
|
|
|
|
|
const SafeModeKey contextKey = "SafeMode"
|
|
|
|
|
|
|
|
|
|
// IsSafeMode checks if the provided context indicates that the execution is in safe mode.
|
|
|
|
|
func IsSafeMode(ctx context.Context) bool {
|
|
|
|
|
v := ctx.Value(SafeModeKey)
|
|
|
|
|
if sm, ok := v.(bool); ok {
|
|
|
|
|
return sm
|
|
|
|
|
}
|
|
|
|
|
return false // Default to false if not specified (internal trusted caller)
|
|
|
|
|
}
|
2026-05-30 14:11:56 +08:00
|
|
|
|
2026-05-30 15:33:57 +08:00
|
|
|
type Module struct {
|
|
|
|
|
Exports map[string]any
|
|
|
|
|
UnsafeList map[string]bool
|
|
|
|
|
}
|
|
|
|
|
|
2026-05-30 14:11:56 +08:00
|
|
|
var (
|
2026-05-30 15:33:57 +08:00
|
|
|
modules = make(map[string]*Module)
|
2026-05-30 14:11:56 +08:00
|
|
|
mu sync.RWMutex
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
// Register registers a Go module with its exported functions and properties.
|
|
|
|
|
// These modules will be accessible within the JS environment.
|
2026-05-30 15:33:57 +08:00
|
|
|
// unsafeList identifies methods that require elevated permissions (e.g., file writing, shell execution).
|
|
|
|
|
func Register(name string, exports map[string]any, unsafeList ...string) {
|
2026-05-30 14:11:56 +08:00
|
|
|
mu.Lock()
|
|
|
|
|
defer mu.Unlock()
|
|
|
|
|
|
|
|
|
|
if modules[name] == nil {
|
2026-05-30 15:33:57 +08:00
|
|
|
modules[name] = &Module{
|
|
|
|
|
Exports: make(map[string]any, len(exports)),
|
|
|
|
|
UnsafeList: make(map[string]bool),
|
|
|
|
|
}
|
2026-05-30 14:11:56 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
for k, v := range exports {
|
2026-05-30 15:33:57 +08:00
|
|
|
modules[name].Exports[k] = v
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
for _, method := range unsafeList {
|
|
|
|
|
modules[name].UnsafeList[method] = true
|
2026-05-30 14:11:56 +08:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-05-30 15:33:57 +08:00
|
|
|
// GetModules returns all registered modules and their unsafe status.
|
|
|
|
|
func GetModules() map[string]*Module {
|
2026-05-30 14:11:56 +08:00
|
|
|
mu.RLock()
|
|
|
|
|
defer mu.RUnlock()
|
|
|
|
|
|
2026-05-30 15:33:57 +08:00
|
|
|
res := make(map[string]*Module, len(modules))
|
|
|
|
|
for name, mod := range modules {
|
|
|
|
|
res[name] = mod
|
2026-05-30 14:11:56 +08:00
|
|
|
}
|
|
|
|
|
return res
|
|
|
|
|
}
|