From 57810a55536b2fb285a4045c7dd84c2b0013d2d6 Mon Sep 17 00:00:00 2001 From: AI Engineer Date: Sat, 30 May 2026 15:33:57 +0800 Subject: [PATCH] feat: upgrade jsmod to support unsafeList tracking (by AI) --- jsmod.go | 31 ++++++++++++++++++++++--------- jsmod_test.go | 18 ++++++++++++++---- 2 files changed, 36 insertions(+), 13 deletions(-) diff --git a/jsmod.go b/jsmod.go index c7a4612..2b95128 100644 --- a/jsmod.go +++ b/jsmod.go @@ -2,34 +2,47 @@ package jsmod import "sync" +type Module struct { + Exports map[string]any + UnsafeList map[string]bool +} + var ( - modules = make(map[string]map[string]any) + modules = make(map[string]*Module) mu sync.RWMutex ) // Register registers a Go module with its exported functions and properties. // These modules will be accessible within the JS environment. -func Register(name string, exports map[string]any) { +// unsafeList identifies methods that require elevated permissions (e.g., file writing, shell execution). +func Register(name string, exports map[string]any, unsafeList ...string) { mu.Lock() defer mu.Unlock() if modules[name] == nil { - modules[name] = make(map[string]any, len(exports)) + modules[name] = &Module{ + Exports: make(map[string]any, len(exports)), + UnsafeList: make(map[string]bool), + } } for k, v := range exports { - modules[name][k] = v + modules[name].Exports[k] = v + } + + for _, method := range unsafeList { + modules[name].UnsafeList[method] = true } } -// GetModules returns all registered modules for the JS engine to inject. -func GetModules() map[string]map[string]any { +// GetModules returns all registered modules and their unsafe status. +func GetModules() map[string]*Module { mu.RLock() defer mu.RUnlock() - res := make(map[string]map[string]any, len(modules)) - for name, exports := range modules { - res[name] = exports + res := make(map[string]*Module, len(modules)) + for name, mod := range modules { + res[name] = mod } return res } diff --git a/jsmod_test.go b/jsmod_test.go index 6b5bb25..8a02497 100644 --- a/jsmod_test.go +++ b/jsmod_test.go @@ -1,14 +1,24 @@ package jsmod_test import ( - "apigo.cc/go/jsmod" "testing" + "apigo.cc/go/jsmod" ) func TestRegister(t *testing.T) { - jsmod.Register("test", map[string]any{"foo": "bar"}) + jsmod.Register("test", map[string]any{"foo": "bar"}, "foo") mods := jsmod.GetModules() - if mods["test"]["foo"] != "bar" { - t.Error("Register failed") + + mod, ok := mods["test"] + if !ok { + t.Fatal("Module not found") + } + + if mod.Exports["foo"] != "bar" { + t.Error("Export failed") + } + + if !mod.UnsafeList["foo"] { + t.Error("UnsafeList tracking failed") } }