package playground import ( "crypto/md5" "encoding/hex" "encoding/json" "errors" "path" "sort" "strings" "github.com/robertkrimen/otto" ) // loadLib is requirelib(): it injects a library into vm and reports whether // the name is known. func (r *run) loadLib(vm *otto.Otto, name, script string) bool { switch name { case "filelib": r.injectFilelib(vm, script) case "imagelib": r.injectImagelib(vm, script) case "ziplib": r.injectZiplib(vm) case "appdata": r.injectAppdata(vm) case "sysinfo": r.injectSysinfo(vm) case "share": r.injectShare(vm) case "notification": r.injectNotification(vm, script) case "scheduler": r.injectScheduler(vm, script) case "websocket": r.injectWebsocket(vm) case "http": r.injectHTTP(vm) case "llm": r.injectLLM(vm, script) case "cnn": r.injectCNN(vm, script) case "sqlite": r.injectSQLite(vm, script) default: fns, ok := r.req.Catalog[name] if !ok { return false } r.injectGeneric(vm, name, fns) } return true } // NativeLibs are the libraries the playground runs for real (on the drive) // or through its service mocks; anything else in api.json is a generic mock. var NativeLibs = []string{"filelib", "imagelib", "ziplib", "appdata", "sysinfo", "share", "notification", "scheduler", "websocket", "http", "llm", "cnn", "sqlite"} // relPath is RelativeVpathRewrite: a path without a root is relative to the // script, but only for a script on a drive (a WebApp script has no drive, so // the path is used as it is and then fails). func (r *run) relPath(script, vpath string) string { if strings.Contains(vpath, ":/") || strings.HasSuffix(vpath, ":") { return vpath } if strings.HasPrefix(script, "web:/") { return vpath } return Clean(path.Join(path.Dir(script), vpath)) } func denied(vm *otto.Otto, msg string) { panic(vm.MakeCustomError("PermissionDenied", msg)) } func argString(call otto.FunctionCall, i int) (string, bool) { a := call.Argument(i) if a.IsUndefined() { return "undefined", false } s, err := a.ToString() return s, err == nil } func (r *run) injectFilelib(vm *otto.Otto, script string) { fs := r.fs vm.Set("_filelib_writeFile", func(call otto.FunctionCall) otto.Value { p, _ := argString(call, 0) p = r.relPath(script, p) if !r.canWrite(p) { denied(vm, "Path access denied: "+p) } content, _ := call.Argument(1).ToString() if q := r.req.User.QuotaTotal; q >= 0 && fs.UsedBytes("user")+int64(len(content)) > q { r.raise(errors.New("Storage Quota Fulled")) return otto.FalseValue() } if err := fs.WriteFile(p, []byte(content)); err != nil { r.raise(fsErr("open", p, err)) return otto.FalseValue() } return otto.TrueValue() }) vm.Set("_filelib_deleteFile", func(call otto.FunctionCall) otto.Value { p, _ := argString(call, 0) p = r.relPath(script, p) if !r.canWrite(p) { denied(vm, "Path access denied: "+p) } if !fs.Exists(p) { r.raise(errors.New("File not exists")) return otto.FalseValue() } // os.Remove: a folder that is not empty stays, and the call still // reports true (ArozOS ignores the error). if err := fs.Remove(p); err != nil { r.log("agi", "agi", "deleteFile left "+p+" in place: "+err.Error()) } return otto.TrueValue() }) vm.Set("_filelib_readFile", func(call otto.FunctionCall) otto.Value { p, _ := argString(call, 0) p = r.relPath(script, p) if !r.canRead(p) { denied(vm, "Path access denied: "+p) } b, err := fs.ReadFile(p) if err != nil { r.raise(fsErr("open", p, err)) return otto.FalseValue() } out, _ := vm.ToValue(string(b)) return out }) vm.Set("_filelib_walk", func(call otto.FunctionCall) otto.Value { p, _ := argString(call, 0) mode, ok := argString(call, 1) if !ok { mode = "all" } p = r.relPath(script, p) if !r.canRead(p) { r.raise(errors.New("unable to resolve virtual path " + p)) return otto.FalseValue() } list, _ := fs.Walk(p) results := []string{} for _, e := range list { if (mode == "file" && e.Dir) || (mode == "folder" && !e.Dir) { continue } results = append(results, e.Vpath) } out, _ := vm.ToValue(results) return out }) glob := func(advanced bool) func(call otto.FunctionCall) otto.Value { return func(call otto.FunctionCall) otto.Value { pattern, _ := argString(call, 0) sortMode, ok := argString(call, 1) if !ok || sortMode == "" { sortMode = "default" } if !advanced && (path.Clean(pattern) == "/" || path.Clean(pattern) == ".") { out, _ := vm.ToValue([]string{"user:/", "tmp:/"}) return out } if !(advanced && pattern == "/") && !r.canRead(pattern) { denied(vm, "Path access denied") } sortMode = r.sortMode(sortMode, path.Dir(pattern)) list, err := fs.Glob(pattern) if err != nil { r.raise(err) return otto.FalseValue() } list = sortEntries(list, sortMode) results := []string{} for _, e := range list { if !isHiddenPath(e.Vpath) { results = append(results, e.Vpath) } } out, _ := vm.ToValue(results) return out } } vm.Set("_filelib_glob", glob(false)) vm.Set("_filelib_aglob", glob(true)) vm.Set("_filelib_readdir", func(call otto.FunctionCall) otto.Value { p, _ := argString(call, 0) p = r.relPath(script, p) if !r.canRead(p) { denied(vm, "Path access denied") } sortMode, ok := argString(call, 1) if !ok || sortMode == "" { sortMode = "default" } sortMode = r.sortMode(sortMode, p) list, err := fs.ReadDir(p) if err != nil { return otto.FalseValue() } if sortMode != "default" { list = sortEntries(list, sortMode) } type info struct { Filename string Filepath string Ext string Filesize int64 Modtime int64 IsDir bool } results := []info{} for _, e := range list { if strings.HasPrefix(e.Name, ".") { continue } results = append(results, info{e.Name, e.Vpath, path.Ext(e.Name), e.Size, e.Mtime.Unix(), e.Dir}) } b, _ := json.Marshal(results) out, _ := vm.ToValue(string(b)) return out }) vm.Set("_filelib_filesize", func(call otto.FunctionCall) otto.Value { p, _ := argString(call, 0) p = r.relPath(script, p) if !r.canRead(p) { denied(vm, "Path access denied") } _, size, _, err := fs.Stat(p) if err != nil { size = -1 // GetFileSize reports -1 for a file it cannot stat } out, _ := vm.ToValue(size) return out }) vm.Set("_filelib_fileExists", func(call otto.FunctionCall) otto.Value { p, _ := argString(call, 0) p = r.relPath(script, p) if !r.canRead(p) { denied(vm, "Path access denied") } return boolValue(fs.Exists(p)) }) vm.Set("_filelib_isDir", func(call otto.FunctionCall) otto.Value { p, _ := argString(call, 0) p = r.relPath(script, p) if !r.canRead(p) { denied(vm, "Path access denied: "+p) } if !fs.Exists(p) { panic(vm.MakeCustomError("File Not Exists", "Required path not exists")) } return boolValue(fs.IsDir(p)) }) vm.Set("_filelib_mkdir", func(call otto.FunctionCall) otto.Value { p, _ := argString(call, 0) if !r.canWrite(p) { denied(vm, "Path access denied") } if err := fs.MkdirAll(p); err != nil { r.log("agi", "agi", err.Error()) return otto.FalseValue() } return otto.TrueValue() }) vm.Set("_filelib_md5", func(call otto.FunctionCall) otto.Value { p, _ := argString(call, 0) p = r.relPath(script, p) if !r.canRead(p) { denied(vm, "Path access denied") } b, err := fs.ReadFile(p) if err != nil { return otto.FalseValue() } sum := md5.Sum(b) out, _ := vm.ToValue(hex.EncodeToString(sum[:])) return out }) vm.Set("_filelib_rname", func(call otto.FunctionCall) otto.Value { p, _ := argString(call, 0) p = r.relPath(script, p) switch { case strings.HasPrefix(Clean(p), "user:/"): out, _ := vm.ToValue("User") return out case strings.HasPrefix(Clean(p), "tmp:/"): out, _ := vm.ToValue("tmp") return out } return otto.FalseValue() }) vm.Set("_filelib_mtime", func(call otto.FunctionCall) otto.Value { p, _ := argString(call, 0) p = r.relPath(script, p) if !r.canRead(p) { denied(vm, "Path access denied") } unix, _ := call.Argument(1).ToBoolean() _, _, mt, err := fs.Stat(p) if err != nil { r.log("agi", "agi", fsErr("stat", p, err).Error()) return otto.FalseValue() } if unix { out, _ := vm.ToValue(mt.Unix()) return out } out, _ := vm.ToValue(mt.Format("2006-01-02 15:04:05")) return out }) vm.Set("_filelib_writeBinaryFile", func(call otto.FunctionCall) otto.Value { p, _ := argString(call, 0) p = r.relPath(script, p) if !r.canWrite(p) { denied(vm, "Path access denied") } h, _ := call.Argument(1).ToString() b, err := hex.DecodeString(h) if err != nil { return otto.FalseValue() } if err := fs.WriteFile(p, b); err != nil { return otto.FalseValue() } return otto.TrueValue() }) vm.Set("_filelib_readBinaryFile", func(call otto.FunctionCall) otto.Value { p, _ := argString(call, 0) p = r.relPath(script, p) if !r.canRead(p) { denied(vm, "Path access denied") } if !fs.Exists(p) { r.raise(errors.New("File not exists")) return otto.NullValue() } b, err := fs.ReadFile(p) if err != nil { return otto.NullValue() } out, _ := vm.ToValue(hex.EncodeToString(b)) return out }) vm.Run(` var filelib = {}; filelib.writeFile = _filelib_writeFile; filelib.readFile = _filelib_readFile; filelib.deleteFile = _filelib_deleteFile; filelib.walk = _filelib_walk; filelib.glob = _filelib_glob; filelib.aglob = _filelib_aglob; filelib.filesize = _filelib_filesize; filelib.fileExists = _filelib_fileExists; filelib.isDir = _filelib_isDir; filelib.md5 = _filelib_md5; filelib.mkdir = _filelib_mkdir; filelib.mtime = _filelib_mtime; filelib.rootName = _filelib_rname; filelib.readBinaryFile = _filelib_readBinaryFile; filelib.writeBinaryFile = _filelib_writeBinaryFile; filelib.readdir = function(path, sortmode){ var s = _filelib_readdir(path, sortmode); return JSON.parse(s); }; `) } // fsErr words a drive error like the os package does on a server. func fsErr(op, vpath string, err error) error { switch { case errors.Is(err, errNotExist): return errors.New(op + " " + vpath + ": The system cannot find the file specified.") case errors.Is(err, errNoRoot): return errors.New("unable to resolve virtual path " + vpath) } return errors.New(op + " " + vpath + ": " + err.Error()) } // sortModes are fssort.ValidSortModes. var sortModes = []string{"default", "reverse", "smallToLarge", "largeToSmall", "mostRecent", "leastRecent", "smart", "fileTypeAsce", "fileTypeDesc"} // sortMode resolves "user" (the File Manager's saved order, which the // playground does not have) and falls back to default for unknown modes. func (r *run) sortMode(mode, dir string) string { if mode == "user" { return "default" } if !containsString(sortModes, mode) { r.log("agi", "agi", "[AGI] Sort mode: "+mode+" not supported. Using default") return "default" } return mode } func sortEntries(list []Entry, mode string) []Entry { out := append([]Entry(nil), list...) less := map[string]func(a, b Entry) bool{ "reverse": func(a, b Entry) bool { return a.Name > b.Name }, "smallToLarge": func(a, b Entry) bool { return a.Size < b.Size }, "largeToSmall": func(a, b Entry) bool { return a.Size > b.Size }, "mostRecent": func(a, b Entry) bool { return a.Mtime.After(b.Mtime) }, "leastRecent": func(a, b Entry) bool { return a.Mtime.Before(b.Mtime) }, "smart": func(a, b Entry) bool { return naturalLess(a.Name, b.Name) }, "fileTypeAsce": func(a, b Entry) bool { return typeKey(a) < typeKey(b) }, "fileTypeDesc": func(a, b Entry) bool { return typeKey(a) > typeKey(b) }, }[mode] if less != nil { sort.SliceStable(out, func(i, j int) bool { return less(out[i], out[j]) }) } return out } func typeKey(e Entry) string { return strings.ToLower(path.Ext(e.Name)) + "/" + e.Name } // naturalLess orders "file2" before "file10". func naturalLess(a, b string) bool { a, b = strings.ToLower(a), strings.ToLower(b) for a != "" && b != "" { ca, cb := a[0], b[0] if isDigit(ca) && isDigit(cb) { na, ra := leadingNumber(a) nb, rb := leadingNumber(b) if len(na) != len(nb) { return len(na) < len(nb) } if na != nb { return na < nb } a, b = ra, rb continue } if ca != cb { return ca < cb } a, b = a[1:], b[1:] } return len(a) < len(b) } func isDigit(c byte) bool { return c >= '0' && c <= '9' } func leadingNumber(s string) (string, string) { i := 0 for i < len(s) && isDigit(s[i]) { i++ } n := strings.TrimLeft(s[:i], "0") return n, s[i:] }