| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909 |
- package playground
- import (
- "encoding/json"
- "errors"
- "fmt"
- "path"
- "sort"
- "strings"
- "sync"
- "time"
- "github.com/robertkrimen/otto"
- )
- // Request is one run: the script, the request that calls it, the signed-in
- // user, the stored state (database, shares, tasks) and the mocked services.
- type Request struct {
- Script string `json:"script"` // vpath of the script, web:/... or user:/...
- Code string `json:"code"` // the editor's text; read from the drive when empty
- Method string `json:"method"`
- Query map[string]string `json:"query"`
- Form map[string]string `json:"form"`
- Body string `json:"body"`
- ContentType string `json:"contentType"`
- User User `json:"user"`
- State State `json:"state"`
- Mocks Mocks `json:"mocks"`
- TimeoutSec int `json:"timeoutSec"`
- Files []File `json:"files"`
- // Catalog lists the functions of libraries the playground cannot run,
- // from api.json ("git" -> ["git.status", ...]); they become mocks.
- Catalog map[string][]string `json:"catalog"`
- // Live receives WebSocket frames typed in the page while the script runs.
- Live <-chan WSIn `json:"-"`
- }
- // User is the account the script runs as.
- type User struct {
- Username string `json:"username"`
- Admin bool `json:"admin"`
- Groups []string `json:"groups"`
- QuotaTotal int64 `json:"quotaTotal"` // bytes, -1 for unlimited
- Modules []string `json:"modules"`
- }
- // State is what outlives a run: the system database, shares, scheduled
- // tasks, other accounts and the llm usage board. The page keeps it.
- type State struct {
- DB map[string]map[string]string `json:"db"`
- Shares []Share `json:"shares"`
- Tasks []Task `json:"tasks"`
- Users []string `json:"users"`
- LLMUsage LLMUsage `json:"llmUsage"`
- Jobs map[string]json.RawMessage `json:"jobs,omitempty"` // cnn async jobs
- }
- type Share struct {
- UUID string `json:"uuid"`
- Vpath string `json:"vpath"`
- Owner string `json:"owner"`
- Permission string `json:"permission"`
- ExpireAt int64 `json:"expireAt,omitempty"`
- }
- type Task struct {
- Name string `json:"name"`
- App string `json:"app"`
- Interval int64 `json:"interval"`
- Description string `json:"description"`
- Script string `json:"script"`
- Owner string `json:"owner"`
- }
- type LLMUsage struct {
- TotalTokens int64 `json:"totalTokens"`
- TotalRequests int64 `json:"totalRequests"`
- PerModel map[string]int64 `json:"perModel"`
- }
- // Result is what the page shows after a run.
- type Result struct {
- Mode string `json:"mode"` // "webapp" or "serverless"
- Status int `json:"status"`
- ContentType string `json:"contentType"`
- Headers map[string]string `json:"headers,omitempty"`
- Response string `json:"response"`
- Error *ScriptError `json:"error,omitempty"`
- Exited bool `json:"exited,omitempty"`
- Console []LogLine `json:"console"`
- Calls []Call `json:"calls"`
- Written []File `json:"written"`
- Removed []string `json:"removed"`
- State State `json:"state"`
- WS []WSFrame `json:"ws,omitempty"`
- Upgraded bool `json:"upgraded,omitempty"`
- Notifications []Notification `json:"notifications,omitempty"`
- Modules []json.RawMessage `json:"modules,omitempty"` // registerModule() calls
- DurationMs int64 `json:"durationMs"`
- }
- type ScriptError struct {
- Kind string `json:"kind"` // "error", "timeout"
- Message string `json:"message"`
- Stack string `json:"stack,omitempty"`
- }
- // LogLine is a console.log() line or a message ArozOS would write to the
- // server log (errors that make a function return false, for example).
- type LogLine struct {
- T int64 `json:"t"` // ms since the run started
- Source string `json:"source"`
- Level string `json:"level"` // "log", "warn", "error", "agi"
- Text string `json:"text"`
- }
- // Call records one call to a mocked service.
- type Call struct {
- T int64 `json:"t"`
- Lib string `json:"lib"`
- Fn string `json:"fn"`
- Args string `json:"args"`
- Result string `json:"result"`
- Rule string `json:"rule,omitempty"` // which mock answered
- }
- type Notification struct {
- To string `json:"to"`
- Title string `json:"title"`
- Message string `json:"message"`
- Priority string `json:"priority"`
- }
- // Hooks stream what happens while the script runs; both may be nil.
- type Hooks struct {
- Log func(LogLine)
- WS func(WSFrame)
- }
- var (
- errExitcall = errors.New("exit")
- errTimeout = errors.New("timeout")
- )
- // run is the state of one Run, shared by the script and its execd children.
- type run struct {
- req *Request
- hooks Hooks
- fs *memFS
- start time.Time
- mu sync.Mutex
- res *Result
- state State
- ws *wsConn
- headers map[string]string
- status int
- kids sync.WaitGroup
- vms []*otto.Otto // every VM of the run, so the time limit stops them all
- stopped bool
- }
- // Run executes the script and returns what a browser would receive, plus
- // everything the playground shows around it.
- func Run(req Request, hooks Hooks) *Result {
- r := &run{
- req: &req,
- hooks: hooks,
- fs: newMemFS(req.Files),
- start: time.Now(),
- res: &Result{Status: 200},
- state: req.State,
- headers: map[string]string{},
- }
- r.normalize()
- res := r.res
- res.Mode = r.mode()
- code := req.Code
- if code == "" {
- b, err := r.fs.ReadFile(req.Script)
- if err != nil {
- res.Status = 500
- res.Error = &ScriptError{Kind: "error", Message: "500 - Internal Server Error: Script not exists"}
- return r.finish()
- }
- code = string(b)
- }
- if ext := path.Ext(req.Script); ext != ".agi" && ext != ".js" {
- res.Status = 403
- res.Error = &ScriptError{Kind: "error", Message: "AGI script must have file extension of .agi or .js"}
- return r.finish()
- }
- vm := r.newVM(req.Script, false, "")
- r.injectRequest(vm)
- timeout := time.Duration(req.TimeoutSec) * time.Second
- timer := time.AfterFunc(timeout, r.stopAll)
- defer timer.Stop()
- r.exec(vm, code)
- // execd() children run on after the parent returns, as on a server;
- // wait for them (within the time limit) so their output is shown.
- done := make(chan struct{})
- go func() { r.kids.Wait(); close(done) }()
- select {
- case <-done:
- case <-time.After(time.Until(r.start.Add(timeout))):
- r.log("agi", "warn", "execd() scripts still running at the time limit; their output is cut off")
- }
- if r.ws != nil {
- r.ws.shutdown()
- }
- return r.finish()
- }
- func (r *run) normalize() {
- q := r.req
- if q.Method == "" {
- q.Method = "POST"
- }
- if q.TimeoutSec <= 0 || q.TimeoutSec > 300 {
- q.TimeoutSec = 30
- }
- if q.User.Username == "" {
- q.User.Username = "developer"
- }
- if q.User.Groups == nil {
- if q.User.Admin {
- q.User.Groups = []string{"administrator"}
- } else {
- q.User.Groups = []string{"user"}
- }
- }
- if q.User.QuotaTotal == 0 {
- q.User.QuotaTotal = -1
- }
- q.Script = Clean(q.Script)
- if r.state.DB == nil {
- r.state.DB = map[string]map[string]string{}
- }
- if r.state.LLMUsage.PerModel == nil {
- r.state.LLMUsage.PerModel = map[string]int64{}
- }
- if r.state.Jobs == nil {
- r.state.Jobs = map[string]json.RawMessage{}
- }
- if !containsString(r.state.Users, q.User.Username) {
- r.state.Users = append([]string{q.User.Username}, r.state.Users...)
- }
- }
- // mode is "webapp" for a script in the WebApp folder (run through
- // /system/ajgi/interface) and "serverless" for one on a user drive (run as
- // an external endpoint or from the File Manager).
- func (r *run) mode() string {
- if strings.HasPrefix(r.req.Script, "web:/") {
- return "webapp"
- }
- return "serverless"
- }
- // scriptFile is __FILE__: the path relative to the server root for a WebApp
- // script ("web/App/x.agi"), the vpath for a script on a drive.
- func (r *run) scriptFile(vpath string) string {
- if strings.HasPrefix(vpath, "web:/") {
- return "web/" + strings.TrimPrefix(vpath, "web:/")
- }
- return vpath
- }
- func (r *run) finish() *Result {
- res := r.res
- res.Written, res.Removed = r.fs.Changes()
- if res.Written == nil {
- res.Written = []File{}
- }
- if res.Console == nil {
- res.Console = []LogLine{}
- }
- if res.Calls == nil {
- res.Calls = []Call{}
- }
- if r.status != 0 {
- res.Status = r.status
- }
- if len(r.headers) > 0 {
- res.Headers = r.headers
- }
- res.State = r.state
- res.DurationMs = time.Since(r.start).Milliseconds()
- return res
- }
- // stopAll interrupts the script and every execd() child at the time limit.
- func (r *run) stopAll() {
- r.mu.Lock()
- defer r.mu.Unlock()
- r.stopped = true
- for _, vm := range r.vms {
- select {
- case vm.Interrupt <- func() { panic(errTimeout) }:
- default:
- }
- }
- }
- func (r *run) ms() int64 { return time.Since(r.start).Milliseconds() }
- func (r *run) log(source, level, text string) {
- l := LogLine{T: r.ms(), Source: source, Level: level, Text: text}
- r.mu.Lock()
- r.res.Console = append(r.res.Console, l)
- r.mu.Unlock()
- if r.hooks.Log != nil {
- r.hooks.Log(l)
- }
- }
- // raise is Gateway.RaiseError: it logs the error and throws it into the
- // script as an Error named name (FileLibError, ZipLibError, ...), which the
- // script may catch. The playground shows the log line in the console.
- // Call it only from a native function on the VM's own goroutine.
- // locked runs change while holding r.mu and returns its error. Raise only
- // after it returns: raise logs, and logging takes r.mu.
- func (r *run) locked(change func() error) error {
- r.mu.Lock()
- defer r.mu.Unlock()
- return change()
- }
- func (r *run) raise(vm *otto.Otto, name string, err error) otto.Value {
- if err == nil {
- err = errors.New("unknown error")
- }
- r.log("agi", "agi", "[AGI] "+name+": "+err.Error())
- panic(vm.MakeCustomError(name, err.Error()))
- }
- func (r *run) call(lib, fn, args, result, rule string) {
- r.mu.Lock()
- r.res.Calls = append(r.res.Calls, Call{T: r.ms(), Lib: lib, Fn: fn, Args: args, Result: result, Rule: rule})
- r.mu.Unlock()
- }
- // exec runs code on vm and turns exit(), the time limit and script errors
- // into the result.
- func (r *run) exec(vm *otto.Otto, code string) {
- defer func() {
- if caught := recover(); caught != nil {
- switch caught {
- case errExitcall:
- r.res.Exited = true
- r.res.ContentType = "" // exit() leaves the type to the browser
- r.res.Response = vmString(vm, "HTTP_RESP")
- case errTimeout:
- r.res.Status = 503
- r.res.Error = &ScriptError{Kind: "timeout", Message: fmt.Sprintf("Script stopped after %d s (the playground's time limit)", r.req.TimeoutSec)}
- default:
- r.res.Status = 500
- r.res.Error = &ScriptError{Kind: "error", Message: fmt.Sprint("VM crash: ", caught)}
- }
- }
- }()
- if _, err := vm.Run(code); err != nil {
- r.res.Status = 500
- se := &ScriptError{Kind: "error", Message: err.Error()}
- if oe, ok := err.(*otto.Error); ok {
- se.Stack = oe.String()
- }
- r.res.Error = se
- r.log("agi", "agi", fmt.Sprintf("[AGI] Script error in %s (user: %s): %s", r.scriptFile(r.req.Script), r.req.User.Username, err.Error()))
- return
- }
- r.res.Response = vmString(vm, "HTTP_RESP")
- r.res.ContentType = vmString(vm, "HTTP_HEADER")
- }
- func vmString(vm *otto.Otto, name string) string {
- v, err := vm.Get(name)
- if err != nil {
- return ""
- }
- s, _ := v.ToString()
- if s == "undefined" && v.IsUndefined() {
- return ""
- }
- return s
- }
- // newVM builds a VM the way ExecuteAGIScript does: the standard library,
- // the user functions and requirelib(). child marks an execd() script.
- func (r *run) newVM(script string, child bool, source string) *otto.Otto {
- vm := otto.New()
- vm.Interrupt = make(chan func(), 1)
- r.mu.Lock()
- r.vms = append(r.vms, vm)
- if r.stopped {
- vm.Interrupt <- func() { panic(errTimeout) }
- }
- r.mu.Unlock()
- if source == "" {
- source = "script"
- }
- r.injectStandard(vm, script, source)
- r.injectUser(vm, script, source)
- return vm
- }
- func (r *run) injectStandard(vm *otto.Otto, script, source string) {
- webapp := strings.HasPrefix(script, "web:/")
- vm.Set("BUILD_VERSION", "playground")
- vm.Set("INTERNAL_VERSION", "playground")
- vm.Set("LOADED_MODULES", r.loadedModules())
- vm.Set("LOADED_STORAGES", map[string]interface{}{"Owner": "system", "OtherPermission": "readonly", "Storages": r.vroots()})
- vm.Set("__FILE__", r.scriptFile(script))
- vm.Set("HTTP_RESP", "")
- vm.Set("HTTP_HEADER", "text/plain")
- vm.Set("EXECUTION_ID", newUUID())
- vm.Set("_agi_console_log", func(call otto.FunctionCall) otto.Value {
- parts := make([]string, 0, len(call.ArgumentList))
- for _, a := range call.ArgumentList {
- s, _ := a.ToString()
- parts = append(parts, s)
- }
- r.log(source, "log", strings.Join(parts, " "))
- return otto.UndefinedValue()
- })
- vm.Run(`var console = { log: _agi_console_log, warn: _agi_console_log, error: _agi_console_log, info: _agi_console_log };`)
- vm.Set("sendResp", func(call otto.FunctionCall) otto.Value {
- s, _ := call.Argument(0).ToString()
- vm.Set("HTTP_RESP", s)
- return otto.Value{}
- })
- vm.Set("echo", func(call otto.FunctionCall) otto.Value {
- s, _ := call.Argument(0).ToString()
- vm.Set("HTTP_RESP", vmString(vm, "HTTP_RESP")+s)
- return otto.Value{}
- })
- vm.Set("sendOK", func(call otto.FunctionCall) otto.Value {
- vm.Set("HTTP_RESP", "ok")
- return otto.Value{}
- })
- vm.Set("_sendJSONResp", func(call otto.FunctionCall) otto.Value {
- s, _ := call.Argument(0).ToString()
- vm.Set("HTTP_HEADER", "application/json")
- vm.Set("HTTP_RESP", s)
- return otto.Value{}
- })
- vm.Run(`
- sendJSONResp = function(object){
- if (typeof(object) === "object"){
- _sendJSONResp(JSON.stringify(object));
- }else{
- _sendJSONResp(object);
- }
- }
- `)
- vm.Set("addNightlyTask", func(call otto.FunctionCall) otto.Value {
- p, _ := call.Argument(0).ToString()
- if ext := path.Ext(p); ext != ".agi" && ext != ".js" {
- return r.raise(vm, "AGIError", errors.New("not an AGI script: "+p))
- }
- r.log("agi", "agi", "Nightly task registered: "+p+" (ArozOS runs it every night; the playground only records it)")
- return otto.TrueValue()
- })
- r.injectDB(vm)
- vm.Set("registerModule", func(call otto.FunctionCall) otto.Value {
- s, _ := call.Argument(0).ToString()
- var cfg map[string]interface{}
- if err := json.Unmarshal([]byte(s), &cfg); err != nil {
- return r.raise(vm, "AGIError", err)
- }
- if webapp {
- // Relative paths become paths from the web root, as on a server.
- dir := strings.SplitN(strings.TrimPrefix(script, "web:/"), "/", 2)[0]
- for _, f := range []string{"IconPath", "StartDir", "LaunchFWDir", "LaunchEmb"} {
- if v, ok := cfg[f].(string); ok && v != "" && !strings.HasPrefix(v, dir+"/") && !path.IsAbs(v) {
- cfg[f] = path.Join(dir, v)
- }
- }
- }
- b, _ := json.Marshal(cfg)
- r.mu.Lock()
- r.res.Modules = append(r.res.Modules, b)
- r.mu.Unlock()
- r.log("agi", "agi", fmt.Sprintf("Module registered: %v", cfg["Name"]))
- return otto.Value{}
- })
- vm.Set("registerExtensionIcon", func(call otto.FunctionCall) otto.Value {
- ext, _ := call.Argument(0).ToString()
- icon, _ := call.Argument(1).ToString()
- if ext == "" || ext == "undefined" {
- return r.raise(vm, "AGIError", errors.New("registerExtensionIcon: extension not given"))
- }
- if icon == "" || icon == "undefined" {
- return r.raise(vm, "AGIError", errors.New("registerExtensionIcon: icon path not given"))
- }
- r.log("agi", "agi", "Extension icon registered: "+ext+" -> "+icon)
- return otto.TrueValue()
- })
- if webapp {
- vm.Set("requirepkg", func(call otto.FunctionCall) otto.Value {
- return r.raise(vm, "AGIError", errors.New("requirepkg has been deprecated in agi v3.0"))
- })
- vm.Set("execpkg", func(call otto.FunctionCall) otto.Value {
- return r.raise(vm, "AGIError", errors.New("execpkg has been deprecated in agi v3.0"))
- })
- vm.Set("includes", func(call otto.FunctionCall) otto.Value {
- name, err := call.Argument(0).ToString()
- if err != nil {
- return r.raise(vm, "AGIError", err)
- }
- if path.Base(script) == path.Base(name) {
- return r.raise(vm, "AGIError", errors.New("includes: a script cannot include itself"))
- }
- target := Clean(path.Join(path.Dir(script), name))
- b, err := r.fs.ReadFile(target)
- if err != nil {
- return r.raise(vm, "AGIError", errors.New("includes: script not found: "+name))
- }
- if _, err := vm.Run(string(b)); err != nil {
- return r.raise(vm, "AGIError", fmt.Errorf("includes: %s failed: %s", name, err.Error()))
- }
- return otto.TrueValue()
- })
- }
- vm.Set("delay", func(call otto.FunctionCall) otto.Value {
- ms, err := call.Argument(0).ToInteger()
- if err != nil {
- return r.raise(vm, "AGIError", err)
- }
- if r.ws != nil && r.ws.pumps(vm) {
- r.ws.pump(vm, time.Duration(ms)*time.Millisecond)
- } else {
- time.Sleep(time.Duration(ms) * time.Millisecond)
- }
- return otto.TrueValue()
- })
- vm.Set("exit", func(call otto.FunctionCall) otto.Value {
- select {
- case vm.Interrupt <- func() { panic(errExitcall) }:
- default:
- }
- return otto.NullValue()
- })
- }
- // reservedTables are refused by the DB functions, as in src/agi.go.
- var reservedTables = []string{"auth", "permisson", "register", "desktop"}
- // tableErr is Gateway.checkDBTable: a reserved table, or one that must exist
- // and does not, is an error the DB functions throw
- func (r *run) tableErr(name string, mustExist bool) error {
- if containsString(reservedTables, name) {
- return errors.New("database table " + name + " is reserved by the system")
- }
- if mustExist && !r.tableExists(name) {
- return errors.New("database table " + name + " does not exist")
- }
- return nil
- }
- func (r *run) tableExists(name string) bool {
- r.mu.Lock()
- defer r.mu.Unlock()
- _, ok := r.state.DB[name]
- return ok
- }
- func (r *run) injectDB(vm *otto.Otto) {
- vm.Set("newDBTableIfNotExists", func(call otto.FunctionCall) otto.Value {
- t, err := call.Argument(0).ToString()
- if err != nil {
- return r.raise(vm, "AGIError", err)
- }
- if err := r.tableErr(t, false); err != nil {
- return r.raise(vm, "AGIError", err)
- }
- r.mu.Lock()
- if r.state.DB[t] == nil {
- r.state.DB[t] = map[string]string{}
- }
- r.mu.Unlock()
- return otto.TrueValue()
- })
- vm.Set("DBTableExists", func(call otto.FunctionCall) otto.Value {
- t, _ := call.Argument(0).ToString()
- r.mu.Lock()
- _, ok := r.state.DB[t]
- r.mu.Unlock()
- return boolValue(ok)
- })
- vm.Set("dropDBTable", func(call otto.FunctionCall) otto.Value {
- t, _ := call.Argument(0).ToString()
- if err := r.tableErr(t, true); err != nil {
- return r.raise(vm, "AGIError", err)
- }
- r.mu.Lock()
- delete(r.state.DB, t)
- r.mu.Unlock()
- return otto.TrueValue()
- })
- vm.Set("writeDBItem", func(call otto.FunctionCall) otto.Value {
- t, _ := call.Argument(0).ToString()
- if err := r.tableErr(t, true); err != nil {
- return r.raise(vm, "AGIError", err)
- }
- k, _ := call.Argument(1).ToString()
- v, _ := call.Argument(2).ToString()
- r.mu.Lock()
- r.state.DB[t][k] = v
- r.mu.Unlock()
- return otto.TrueValue()
- })
- vm.Set("readDBItem", func(call otto.FunctionCall) otto.Value {
- t, _ := call.Argument(0).ToString()
- k, _ := call.Argument(1).ToString()
- //A table that does not exist yet holds nothing: false, not an error
- if err := r.tableErr(t, false); err != nil {
- return r.raise(vm, "AGIError", err)
- }
- if !r.tableExists(t) {
- return otto.FalseValue()
- }
- r.mu.Lock()
- v := r.state.DB[t][k]
- r.mu.Unlock()
- out, _ := vm.ToValue(v)
- return out
- })
- vm.Set("listDBTable", func(call otto.FunctionCall) otto.Value {
- t, _ := call.Argument(0).ToString()
- if err := r.tableErr(t, false); err != nil {
- return r.raise(vm, "AGIError", err)
- }
- if !r.tableExists(t) {
- return otto.FalseValue()
- }
- r.mu.Lock()
- cp := map[string]string{}
- for k, v := range r.state.DB[t] {
- cp[k] = v
- }
- r.mu.Unlock()
- out, err := vm.ToValue(cp)
- if err != nil {
- return r.raise(vm, "AGIError", err)
- }
- return out
- })
- vm.Set("deleteDBItem", func(call otto.FunctionCall) otto.Value {
- t, _ := call.Argument(0).ToString()
- k, _ := call.Argument(1).ToString()
- if err := r.tableErr(t, true); err != nil {
- return r.raise(vm, "AGIError", err)
- }
- r.mu.Lock()
- delete(r.state.DB[t], k)
- r.mu.Unlock()
- return otto.TrueValue()
- })
- }
- // canRead / canWrite: the user may use user:/ and tmp:/. web:/ is not a
- // drive (scripts cannot reach ./web through filelib on a server either).
- func (r *run) canRead(vpath string) bool {
- return strings.HasPrefix(Clean(vpath), "user:/") || strings.HasPrefix(Clean(vpath), "tmp:/")
- }
- func (r *run) canWrite(vpath string) bool { return r.canRead(vpath) }
- func (r *run) vroots() []map[string]interface{} {
- return []map[string]interface{}{
- {"UUID": "user", "Name": "User", "Path": "user:/", "Hierarchy": "user", "ReadOnly": false, "Filesystem": "virtual"},
- {"UUID": "tmp", "Name": "tmp", "Path": "tmp:/", "Hierarchy": "user", "ReadOnly": false, "Filesystem": "virtual"},
- }
- }
- func (r *run) loadedModules() []map[string]interface{} {
- return []map[string]interface{}{
- {"Name": "Playground", "Desc": "The WebApp the playground scripts belong to", "Group": "Development", "IconPath": "Playground/img/icon.png", "Version": "1.0", "StartDir": "Playground/index.html", "SupportFW": true, "LaunchFWDir": "Playground/index.html", "SupportEmb": false, "InitFWSize": []int{720, 480}},
- {"Name": "File Manager", "Desc": "Explore and manage your files", "Group": "System Tools", "IconPath": "SystemAO/file_system/img/small_icon.png", "Version": "3.0", "StartDir": "SystemAO/file_system/file_explorer.html"},
- }
- }
- func (r *run) injectUser(vm *otto.Otto, script, source string) {
- u := r.req.User
- vm.Set("USERNAME", u.Username)
- vm.Set("USERICON", "img/desktop/system_icon/user.svg")
- vm.Set("USERQUOTA_TOTAL", u.QuotaTotal)
- vm.Set("USERQUOTA_USED", r.fs.UsedBytes("user"))
- vm.Set("USER_VROOTS", r.vroots())
- modules := u.Modules
- if modules == nil {
- modules = []string{"Playground", "File Manager"}
- }
- vm.Set("USER_MODULES", modules)
- for _, name := range []string{"decodeVirtualPath", "decodeAbsoluteVirtualPath", "encodeRealPath"} {
- name := name
- vm.Set(name, func(call otto.FunctionCall) otto.Value {
- r.log("agi", "agi", "Call to deprecated function "+name)
- return otto.FalseValue()
- })
- }
- vm.Set("pathCanWrite", func(call otto.FunctionCall) otto.Value {
- p, _ := call.Argument(0).ToString()
- return boolValue(r.canWrite(p))
- })
- vm.Set("getUserPermissionGroup", func(call otto.FunctionCall) otto.Value {
- groups := []map[string]interface{}{}
- for _, g := range u.Groups {
- groups = append(groups, map[string]interface{}{
- "Name": g, "IsAdmin": u.Admin && g == "administrator", "DefaultInterfaceModule": "Desktop",
- "DefaultStorageQuota": u.QuotaTotal, "AccessibleModules": modules,
- })
- }
- b, _ := json.Marshal(groups)
- out, _ := vm.ToValue(string(b))
- return out
- })
- vm.Set("userIsAdmin", func(call otto.FunctionCall) otto.Value { return boolValue(u.Admin) })
- //adminOnly throws for a user who is not an administrator
- adminOnly := func(name string) {
- if !u.Admin {
- r.raise(vm, "AGIError", errors.New("Permission Denied: "+name+" require admin permission"))
- }
- }
- vm.Set("userExists", func(call otto.FunctionCall) otto.Value {
- adminOnly("userExists")
- name, err := call.Argument(0).ToString()
- if err != nil || name == "undefined" {
- return r.raise(vm, "AGIError", errors.New("username is undefined"))
- }
- r.mu.Lock()
- defer r.mu.Unlock()
- return boolValue(containsString(r.state.Users, name))
- })
- vm.Set("createUser", func(call otto.FunctionCall) otto.Value {
- adminOnly("createUser")
- name, _ := call.Argument(0).ToString()
- pass, _ := call.Argument(1).ToString()
- group, _ := call.Argument(2).ToString()
- switch {
- case name == "undefined" || name == "":
- return r.raise(vm, "AGIError", errors.New("username is undefined"))
- case pass == "undefined":
- return r.raise(vm, "AGIError", errors.New("password is undefined"))
- case group == "undefined":
- return r.raise(vm, "AGIError", errors.New("defaultGroup is undefined"))
- case group != "administrator" && group != "user":
- return r.raise(vm, "AGIError", errors.New(group+" user-group not exists"))
- }
- err := r.locked(func() error {
- if containsString(r.state.Users, name) {
- return errors.New("Username already exists")
- }
- r.state.Users = append(r.state.Users, name)
- return nil
- })
- if err != nil {
- return r.raise(vm, "AGIError", err)
- }
- return otto.TrueValue()
- })
- vm.Set("editUser", func(call otto.FunctionCall) otto.Value {
- adminOnly("editUser")
- return otto.FalseValue()
- })
- vm.Set("removeUser", func(call otto.FunctionCall) otto.Value {
- adminOnly("removeUser")
- name, err := call.Argument(0).ToString()
- if err != nil || name == "undefined" {
- return r.raise(vm, "AGIError", errors.New("username is undefined"))
- }
- err = r.locked(func() error {
- for i, n := range r.state.Users {
- if n == name {
- r.state.Users = append(r.state.Users[:i], r.state.Users[i+1:]...)
- return nil
- }
- }
- return errors.New(name + " not exists")
- })
- if err != nil {
- return r.raise(vm, "AGIError", err)
- }
- return otto.TrueValue()
- })
- vm.Set("requirelib", func(call otto.FunctionCall) otto.Value {
- name, err := call.Argument(0).ToString()
- if err != nil {
- return r.raise(vm, "AGIError", err)
- }
- if r.loadLib(vm, name, script) {
- return otto.TrueValue()
- }
- r.log("agi", "agi", "Lib not found: "+name)
- return otto.FalseValue()
- })
- vm.Set("execd", func(call otto.FunctionCall) otto.Value {
- name, err := call.Argument(0).ToString()
- if err != nil {
- return r.raise(vm, "AGIError", err)
- }
- payload, _ := call.Argument(1).ToString()
- target := Clean(path.Join(path.Dir(script), name))
- b, err := r.fs.ReadFile(target)
- if err != nil {
- return r.raise(vm, "AGIError", errors.New("execd: script not found: "+name))
- }
- r.kids.Add(1)
- go func() {
- defer r.kids.Done()
- // The child keeps the parent's script path, as on a server.
- child := r.newVM(script, true, "execd:"+path.Base(target))
- child.Set("PARENT_DETACHED", true)
- child.Set("PARENT_PAYLOAD", payload)
- defer func() {
- if caught := recover(); caught != nil && caught != errExitcall && caught != errTimeout {
- r.log("execd:"+path.Base(target), "error", fmt.Sprint("VM crash: ", caught))
- }
- }()
- //Nothing waits for a detached script, so its error is only logged
- if _, err := child.Run(string(b)); err != nil {
- r.log("agi", "agi", "[AGI] Detached script "+path.Base(target)+" failed: "+err.Error())
- }
- }()
- return otto.TrueValue()
- })
- }
- // injectRequest sets what the HTTP request carries: POST fields as globals
- // for a WebApp script, getPara/postPara/readBody for a serverless one.
- func (r *run) injectRequest(vm *otto.Otto) {
- q := r.req
- if r.mode() == "webapp" {
- if strings.Contains(q.ContentType, "application/json") {
- fields := map[string]interface{}{}
- json.Unmarshal([]byte(q.Body), &fields)
- for k, v := range fields {
- vm.Set(k, v)
- }
- vm.Set("POST_data", q.Body)
- } else if q.Method == "POST" || q.Method == "PUT" || q.Method == "PATCH" {
- keys := make([]string, 0, len(q.Form))
- for k := range q.Form {
- keys = append(keys, k)
- }
- sort.Strings(keys)
- for _, k := range keys {
- vm.Set(k, q.Form[k])
- }
- }
- return
- }
- vm.Set("REQ_METHOD", q.Method)
- vm.Set("getPara", func(call otto.FunctionCall) otto.Value {
- k, _ := call.Argument(0).ToString()
- if v, ok := q.Query[k]; ok && k != "" {
- out, _ := vm.ToValue(v)
- return out
- }
- return otto.NullValue()
- })
- vm.Set("postPara", func(call otto.FunctionCall) otto.Value {
- k, _ := call.Argument(0).ToString()
- if v, ok := q.Form[k]; ok && k != "" {
- out, _ := vm.ToValue(v)
- return out
- }
- return otto.NullValue()
- })
- vm.Set("readBody", func(call otto.FunctionCall) otto.Value {
- body := q.Body
- if body == "" && len(q.Form) > 0 {
- body = encodeForm(q.Form)
- }
- out, _ := vm.ToValue(body)
- return out
- })
- }
- func boolValue(b bool) otto.Value {
- if b {
- return otto.TrueValue()
- }
- return otto.FalseValue()
- }
- func containsString(list []string, s string) bool {
- for _, v := range list {
- if v == s {
- return true
- }
- }
- return false
- }
|