package playground import ( "crypto/md5" "encoding/base64" "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)) } // denied is Gateway.raisePermissionDenied: it logs and throws PermissionDenied func (r *run) denied(vm *otto.Otto, vpath string) { r.raise(vm, "PermissionDenied", errors.New("Path access denied: "+vpath)) } 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 } // optString is getOttoStringArg: "" for an argument that is missing or null func optString(call otto.FunctionCall, i int) string { a := call.Argument(i) if a.IsUndefined() || a.IsNull() { return "" } s, err := a.ToString() if err != nil { return "" } return s } // decodeBinary is decodeBinaryContent: hex (default) or base64, which may // carry a data URL prefix func decodeBinary(content, encoding string) ([]byte, error) { switch strings.ToLower(strings.TrimSpace(encoding)) { case "", "hex": b, err := hex.DecodeString(content) if err != nil { return nil, errors.New("content is not valid hex: " + err.Error()) } return b, nil case "base64": content = strings.TrimSpace(content) if strings.HasPrefix(content, "data:") { comma := strings.Index(content, ",") if comma < 0 { return nil, errors.New("content is not valid base64: data URL without a comma") } content = content[comma+1:] } b, err := base64.StdEncoding.DecodeString(content) if err != nil { return nil, errors.New("content is not valid base64: " + err.Error()) } return b, nil } return nil, errors.New("unsupported encoding " + encoding + " (use hex or base64)") } // encodeBinary is encodeBinaryContent func encodeBinary(b []byte, encoding string) (string, error) { switch strings.ToLower(strings.TrimSpace(encoding)) { case "", "hex": return hex.EncodeToString(b), nil case "base64": return base64.StdEncoding.EncodeToString(b), nil } return "", errors.New("unsupported encoding " + encoding + " (use hex or base64)") } // knownRoot is whether a path is on one of the playground's drives func knownRoot(vpath string) bool { c := Clean(vpath) return strings.HasPrefix(c, "user:/") || strings.HasPrefix(c, "tmp:/") || strings.HasPrefix(c, "web:/") } func (r *run) injectFilelib(vm *otto.Otto, script string) { fs := r.fs raise := func(err error) otto.Value { return r.raise(vm, "FileLibError", err) } //resolve rewrites a relative path and checks the user may read (or write) it resolve := func(call otto.FunctionCall, i int, write bool) string { p, _ := argString(call, i) p = r.relPath(script, p) if (write && !r.canWrite(p)) || (!write && !r.canRead(p)) { r.denied(vm, p) } return p } //writeUser is writeUserFile: the quota counts the file being replaced as free writeUser := func(p string, b []byte) error { if q := r.req.User.QuotaTotal; q >= 0 { used := fs.UsedBytes("user") if _, size, _, err := fs.Stat(p); err == nil { used -= size } if used+int64(len(b)) > q { return errors.New("storage quota full") } } if err := fs.WriteFile(p, b); err != nil { return fsErr("open", p, err) } return nil } vm.Set("_filelib_writeFile", func(call otto.FunctionCall) otto.Value { p := resolve(call, 0, true) content, _ := call.Argument(1).ToString() if err := writeUser(p, []byte(content)); err != nil { return raise(err) } return otto.TrueValue() }) vm.Set("_filelib_deleteFile", func(call otto.FunctionCall) otto.Value { p := resolve(call, 0, true) if !fs.Exists(p) { return raise(errors.New("File not exists: " + p)) } //A folder that is not empty stays, and that is an error if err := fs.Remove(p); err != nil { return raise(fsErr("remove", p, err)) } return otto.TrueValue() }) vm.Set("_filelib_readFile", func(call otto.FunctionCall) otto.Value { p := resolve(call, 0, false) b, err := fs.ReadFile(p) if err != nil { return raise(fsErr("open", p, err)) } out, _ := vm.ToValue(string(b)) return out }) vm.Set("_filelib_walk", func(call otto.FunctionCall) otto.Value { p := resolve(call, 0, false) mode := optString(call, 1) if !fs.Exists(p) { return raise(fsErr("lstat", p, errNotExist)) } list, err := fs.Walk(p) if err != nil { return raise(fsErr("lstat", p, err)) } 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 := optString(call, 1) if sortMode == "" { sortMode = "default" } if !advanced && (path.Clean(pattern) == "/" || path.Clean(pattern) == ".") { out, _ := vm.ToValue([]string{"user:/", "tmp:/"}) return out } pattern = r.relPath(script, pattern) if !r.canRead(pattern) { r.denied(vm, pattern) } sortMode = r.sortMode(sortMode, path.Dir(pattern)) list, err := fs.Glob(pattern) if err != nil { return raise(err) } 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 := resolve(call, 0, false) sortMode := optString(call, 1) if sortMode == "" { sortMode = "default" } sortMode = r.sortMode(sortMode, p) list, err := fs.ReadDir(p) if err != nil { return raise(fsErr("open", p, err)) } 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 := resolve(call, 0, false) _, size, _, err := fs.Stat(p) if err != nil { return raise(fsErr("stat", p, err)) } out, _ := vm.ToValue(size) return out }) //fileExists and isDir answer a question: false is an answer, not a failure vm.Set("_filelib_fileExists", func(call otto.FunctionCall) otto.Value { p := resolve(call, 0, false) return boolValue(knownRoot(p) && fs.Exists(p)) }) vm.Set("_filelib_isDir", func(call otto.FunctionCall) otto.Value { p := resolve(call, 0, false) return boolValue(fs.Exists(p) && fs.IsDir(p)) }) vm.Set("_filelib_mkdir", func(call otto.FunctionCall) otto.Value { p := resolve(call, 0, true) if err := fs.MkdirAll(p); err != nil { return raise(fsErr("mkdir", p, err)) } return otto.TrueValue() }) vm.Set("_filelib_md5", func(call otto.FunctionCall) otto.Value { p := resolve(call, 0, false) b, err := fs.ReadFile(p) if err != nil { return raise(fsErr("open", p, err)) } 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 raise(fsErr("open", p, errNoRoot)) }) vm.Set("_filelib_mtime", func(call otto.FunctionCall) otto.Value { p := resolve(call, 0, false) unix, _ := call.Argument(1).ToBoolean() _, _, mt, err := fs.Stat(p) if err != nil { return raise(fsErr("stat", p, err)) } 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 := resolve(call, 0, true) content, _ := call.Argument(1).ToString() b, err := decodeBinary(content, optString(call, 2)) if err != nil { return raise(err) } if err := writeUser(p, b); err != nil { return raise(err) } return otto.TrueValue() }) vm.Set("_filelib_readBinaryFile", func(call otto.FunctionCall) otto.Value { p := resolve(call, 0, false) if !fs.Exists(p) { return raise(errors.New("File not exists: " + p)) } b, err := fs.ReadFile(p) if err != nil { return raise(fsErr("open", p, err)) } encoded, err := encodeBinary(b, optString(call, 1)) if err != nil { return raise(err) } out, _ := vm.ToValue(encoded) 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:] }