libfile.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487
  1. package playground
  2. import (
  3. "crypto/md5"
  4. "encoding/base64"
  5. "encoding/hex"
  6. "encoding/json"
  7. "errors"
  8. "path"
  9. "sort"
  10. "strings"
  11. "github.com/robertkrimen/otto"
  12. )
  13. // loadLib is requirelib(): it injects a library into vm and reports whether
  14. // the name is known.
  15. func (r *run) loadLib(vm *otto.Otto, name, script string) bool {
  16. switch name {
  17. case "filelib":
  18. r.injectFilelib(vm, script)
  19. case "imagelib":
  20. r.injectImagelib(vm, script)
  21. case "ziplib":
  22. r.injectZiplib(vm)
  23. case "appdata":
  24. r.injectAppdata(vm)
  25. case "sysinfo":
  26. r.injectSysinfo(vm)
  27. case "share":
  28. r.injectShare(vm)
  29. case "notification":
  30. r.injectNotification(vm, script)
  31. case "scheduler":
  32. r.injectScheduler(vm, script)
  33. case "websocket":
  34. r.injectWebsocket(vm)
  35. case "http":
  36. r.injectHTTP(vm)
  37. case "llm":
  38. r.injectLLM(vm, script)
  39. case "cnn":
  40. r.injectCNN(vm, script)
  41. case "sqlite":
  42. r.injectSQLite(vm, script)
  43. default:
  44. fns, ok := r.req.Catalog[name]
  45. if !ok {
  46. return false
  47. }
  48. r.injectGeneric(vm, name, fns)
  49. }
  50. return true
  51. }
  52. // NativeLibs are the libraries the playground runs for real (on the drive)
  53. // or through its service mocks; anything else in api.json is a generic mock.
  54. var NativeLibs = []string{"filelib", "imagelib", "ziplib", "appdata", "sysinfo", "share", "notification", "scheduler", "websocket", "http", "llm", "cnn", "sqlite"}
  55. // relPath is RelativeVpathRewrite: a path without a root is relative to the
  56. // script, but only for a script on a drive (a WebApp script has no drive, so
  57. // the path is used as it is and then fails).
  58. func (r *run) relPath(script, vpath string) string {
  59. if strings.Contains(vpath, ":/") || strings.HasSuffix(vpath, ":") {
  60. return vpath
  61. }
  62. if strings.HasPrefix(script, "web:/") {
  63. return vpath
  64. }
  65. return Clean(path.Join(path.Dir(script), vpath))
  66. }
  67. // denied is Gateway.raisePermissionDenied: it logs and throws PermissionDenied
  68. func (r *run) denied(vm *otto.Otto, vpath string) {
  69. r.raise(vm, "PermissionDenied", errors.New("Path access denied: "+vpath))
  70. }
  71. func argString(call otto.FunctionCall, i int) (string, bool) {
  72. a := call.Argument(i)
  73. if a.IsUndefined() {
  74. return "undefined", false
  75. }
  76. s, err := a.ToString()
  77. return s, err == nil
  78. }
  79. // optString is getOttoStringArg: "" for an argument that is missing or null
  80. func optString(call otto.FunctionCall, i int) string {
  81. a := call.Argument(i)
  82. if a.IsUndefined() || a.IsNull() {
  83. return ""
  84. }
  85. s, err := a.ToString()
  86. if err != nil {
  87. return ""
  88. }
  89. return s
  90. }
  91. // decodeBinary is decodeBinaryContent: hex (default) or base64, which may
  92. // carry a data URL prefix
  93. func decodeBinary(content, encoding string) ([]byte, error) {
  94. switch strings.ToLower(strings.TrimSpace(encoding)) {
  95. case "", "hex":
  96. b, err := hex.DecodeString(content)
  97. if err != nil {
  98. return nil, errors.New("content is not valid hex: " + err.Error())
  99. }
  100. return b, nil
  101. case "base64":
  102. content = strings.TrimSpace(content)
  103. if strings.HasPrefix(content, "data:") {
  104. comma := strings.Index(content, ",")
  105. if comma < 0 {
  106. return nil, errors.New("content is not valid base64: data URL without a comma")
  107. }
  108. content = content[comma+1:]
  109. }
  110. b, err := base64.StdEncoding.DecodeString(content)
  111. if err != nil {
  112. return nil, errors.New("content is not valid base64: " + err.Error())
  113. }
  114. return b, nil
  115. }
  116. return nil, errors.New("unsupported encoding " + encoding + " (use hex or base64)")
  117. }
  118. // encodeBinary is encodeBinaryContent
  119. func encodeBinary(b []byte, encoding string) (string, error) {
  120. switch strings.ToLower(strings.TrimSpace(encoding)) {
  121. case "", "hex":
  122. return hex.EncodeToString(b), nil
  123. case "base64":
  124. return base64.StdEncoding.EncodeToString(b), nil
  125. }
  126. return "", errors.New("unsupported encoding " + encoding + " (use hex or base64)")
  127. }
  128. // knownRoot is whether a path is on one of the playground's drives
  129. func knownRoot(vpath string) bool {
  130. c := Clean(vpath)
  131. return strings.HasPrefix(c, "user:/") || strings.HasPrefix(c, "tmp:/") || strings.HasPrefix(c, "web:/")
  132. }
  133. func (r *run) injectFilelib(vm *otto.Otto, script string) {
  134. fs := r.fs
  135. raise := func(err error) otto.Value {
  136. return r.raise(vm, "FileLibError", err)
  137. }
  138. //resolve rewrites a relative path and checks the user may read (or write) it
  139. resolve := func(call otto.FunctionCall, i int, write bool) string {
  140. p, _ := argString(call, i)
  141. p = r.relPath(script, p)
  142. if (write && !r.canWrite(p)) || (!write && !r.canRead(p)) {
  143. r.denied(vm, p)
  144. }
  145. return p
  146. }
  147. //writeUser is writeUserFile: the quota counts the file being replaced as free
  148. writeUser := func(p string, b []byte) error {
  149. if q := r.req.User.QuotaTotal; q >= 0 {
  150. used := fs.UsedBytes("user")
  151. if _, size, _, err := fs.Stat(p); err == nil {
  152. used -= size
  153. }
  154. if used+int64(len(b)) > q {
  155. return errors.New("storage quota full")
  156. }
  157. }
  158. if err := fs.WriteFile(p, b); err != nil {
  159. return fsErr("open", p, err)
  160. }
  161. return nil
  162. }
  163. vm.Set("_filelib_writeFile", func(call otto.FunctionCall) otto.Value {
  164. p := resolve(call, 0, true)
  165. content, _ := call.Argument(1).ToString()
  166. if err := writeUser(p, []byte(content)); err != nil {
  167. return raise(err)
  168. }
  169. return otto.TrueValue()
  170. })
  171. vm.Set("_filelib_deleteFile", func(call otto.FunctionCall) otto.Value {
  172. p := resolve(call, 0, true)
  173. if !fs.Exists(p) {
  174. return raise(errors.New("File not exists: " + p))
  175. }
  176. //A folder that is not empty stays, and that is an error
  177. if err := fs.Remove(p); err != nil {
  178. return raise(fsErr("remove", p, err))
  179. }
  180. return otto.TrueValue()
  181. })
  182. vm.Set("_filelib_readFile", func(call otto.FunctionCall) otto.Value {
  183. p := resolve(call, 0, false)
  184. b, err := fs.ReadFile(p)
  185. if err != nil {
  186. return raise(fsErr("open", p, err))
  187. }
  188. out, _ := vm.ToValue(string(b))
  189. return out
  190. })
  191. vm.Set("_filelib_walk", func(call otto.FunctionCall) otto.Value {
  192. p := resolve(call, 0, false)
  193. mode := optString(call, 1)
  194. if !fs.Exists(p) {
  195. return raise(fsErr("lstat", p, errNotExist))
  196. }
  197. list, err := fs.Walk(p)
  198. if err != nil {
  199. return raise(fsErr("lstat", p, err))
  200. }
  201. results := []string{}
  202. for _, e := range list {
  203. if (mode == "file" && e.Dir) || (mode == "folder" && !e.Dir) {
  204. continue
  205. }
  206. results = append(results, e.Vpath)
  207. }
  208. out, _ := vm.ToValue(results)
  209. return out
  210. })
  211. glob := func(advanced bool) func(call otto.FunctionCall) otto.Value {
  212. return func(call otto.FunctionCall) otto.Value {
  213. pattern, _ := argString(call, 0)
  214. sortMode := optString(call, 1)
  215. if sortMode == "" {
  216. sortMode = "default"
  217. }
  218. if !advanced && (path.Clean(pattern) == "/" || path.Clean(pattern) == ".") {
  219. out, _ := vm.ToValue([]string{"user:/", "tmp:/"})
  220. return out
  221. }
  222. pattern = r.relPath(script, pattern)
  223. if !r.canRead(pattern) {
  224. r.denied(vm, pattern)
  225. }
  226. sortMode = r.sortMode(sortMode, path.Dir(pattern))
  227. list, err := fs.Glob(pattern)
  228. if err != nil {
  229. return raise(err)
  230. }
  231. list = sortEntries(list, sortMode)
  232. results := []string{}
  233. for _, e := range list {
  234. if !isHiddenPath(e.Vpath) {
  235. results = append(results, e.Vpath)
  236. }
  237. }
  238. out, _ := vm.ToValue(results)
  239. return out
  240. }
  241. }
  242. vm.Set("_filelib_glob", glob(false))
  243. vm.Set("_filelib_aglob", glob(true))
  244. vm.Set("_filelib_readdir", func(call otto.FunctionCall) otto.Value {
  245. p := resolve(call, 0, false)
  246. sortMode := optString(call, 1)
  247. if sortMode == "" {
  248. sortMode = "default"
  249. }
  250. sortMode = r.sortMode(sortMode, p)
  251. list, err := fs.ReadDir(p)
  252. if err != nil {
  253. return raise(fsErr("open", p, err))
  254. }
  255. if sortMode != "default" {
  256. list = sortEntries(list, sortMode)
  257. }
  258. type info struct {
  259. Filename string
  260. Filepath string
  261. Ext string
  262. Filesize int64
  263. Modtime int64
  264. IsDir bool
  265. }
  266. results := []info{}
  267. for _, e := range list {
  268. if strings.HasPrefix(e.Name, ".") {
  269. continue
  270. }
  271. results = append(results, info{e.Name, e.Vpath, path.Ext(e.Name), e.Size, e.Mtime.Unix(), e.Dir})
  272. }
  273. b, _ := json.Marshal(results)
  274. out, _ := vm.ToValue(string(b))
  275. return out
  276. })
  277. vm.Set("_filelib_filesize", func(call otto.FunctionCall) otto.Value {
  278. p := resolve(call, 0, false)
  279. _, size, _, err := fs.Stat(p)
  280. if err != nil {
  281. return raise(fsErr("stat", p, err))
  282. }
  283. out, _ := vm.ToValue(size)
  284. return out
  285. })
  286. //fileExists and isDir answer a question: false is an answer, not a failure
  287. vm.Set("_filelib_fileExists", func(call otto.FunctionCall) otto.Value {
  288. p := resolve(call, 0, false)
  289. return boolValue(knownRoot(p) && fs.Exists(p))
  290. })
  291. vm.Set("_filelib_isDir", func(call otto.FunctionCall) otto.Value {
  292. p := resolve(call, 0, false)
  293. return boolValue(fs.Exists(p) && fs.IsDir(p))
  294. })
  295. vm.Set("_filelib_mkdir", func(call otto.FunctionCall) otto.Value {
  296. p := resolve(call, 0, true)
  297. if err := fs.MkdirAll(p); err != nil {
  298. return raise(fsErr("mkdir", p, err))
  299. }
  300. return otto.TrueValue()
  301. })
  302. vm.Set("_filelib_md5", func(call otto.FunctionCall) otto.Value {
  303. p := resolve(call, 0, false)
  304. b, err := fs.ReadFile(p)
  305. if err != nil {
  306. return raise(fsErr("open", p, err))
  307. }
  308. sum := md5.Sum(b)
  309. out, _ := vm.ToValue(hex.EncodeToString(sum[:]))
  310. return out
  311. })
  312. vm.Set("_filelib_rname", func(call otto.FunctionCall) otto.Value {
  313. p, _ := argString(call, 0)
  314. p = r.relPath(script, p)
  315. switch {
  316. case strings.HasPrefix(Clean(p), "user:/"):
  317. out, _ := vm.ToValue("User")
  318. return out
  319. case strings.HasPrefix(Clean(p), "tmp:/"):
  320. out, _ := vm.ToValue("tmp")
  321. return out
  322. }
  323. return raise(fsErr("open", p, errNoRoot))
  324. })
  325. vm.Set("_filelib_mtime", func(call otto.FunctionCall) otto.Value {
  326. p := resolve(call, 0, false)
  327. unix, _ := call.Argument(1).ToBoolean()
  328. _, _, mt, err := fs.Stat(p)
  329. if err != nil {
  330. return raise(fsErr("stat", p, err))
  331. }
  332. if unix {
  333. out, _ := vm.ToValue(mt.Unix())
  334. return out
  335. }
  336. out, _ := vm.ToValue(mt.Format("2006-01-02 15:04:05"))
  337. return out
  338. })
  339. vm.Set("_filelib_writeBinaryFile", func(call otto.FunctionCall) otto.Value {
  340. p := resolve(call, 0, true)
  341. content, _ := call.Argument(1).ToString()
  342. b, err := decodeBinary(content, optString(call, 2))
  343. if err != nil {
  344. return raise(err)
  345. }
  346. if err := writeUser(p, b); err != nil {
  347. return raise(err)
  348. }
  349. return otto.TrueValue()
  350. })
  351. vm.Set("_filelib_readBinaryFile", func(call otto.FunctionCall) otto.Value {
  352. p := resolve(call, 0, false)
  353. if !fs.Exists(p) {
  354. return raise(errors.New("File not exists: " + p))
  355. }
  356. b, err := fs.ReadFile(p)
  357. if err != nil {
  358. return raise(fsErr("open", p, err))
  359. }
  360. encoded, err := encodeBinary(b, optString(call, 1))
  361. if err != nil {
  362. return raise(err)
  363. }
  364. out, _ := vm.ToValue(encoded)
  365. return out
  366. })
  367. vm.Run(`
  368. var filelib = {};
  369. filelib.writeFile = _filelib_writeFile;
  370. filelib.readFile = _filelib_readFile;
  371. filelib.deleteFile = _filelib_deleteFile;
  372. filelib.walk = _filelib_walk;
  373. filelib.glob = _filelib_glob;
  374. filelib.aglob = _filelib_aglob;
  375. filelib.filesize = _filelib_filesize;
  376. filelib.fileExists = _filelib_fileExists;
  377. filelib.isDir = _filelib_isDir;
  378. filelib.md5 = _filelib_md5;
  379. filelib.mkdir = _filelib_mkdir;
  380. filelib.mtime = _filelib_mtime;
  381. filelib.rootName = _filelib_rname;
  382. filelib.readBinaryFile = _filelib_readBinaryFile;
  383. filelib.writeBinaryFile = _filelib_writeBinaryFile;
  384. filelib.readdir = function(path, sortmode){
  385. var s = _filelib_readdir(path, sortmode);
  386. return JSON.parse(s);
  387. };
  388. `)
  389. }
  390. // fsErr words a drive error like the os package does on a server.
  391. func fsErr(op, vpath string, err error) error {
  392. switch {
  393. case errors.Is(err, errNotExist):
  394. return errors.New(op + " " + vpath + ": The system cannot find the file specified.")
  395. case errors.Is(err, errNoRoot):
  396. return errors.New("unable to resolve virtual path " + vpath)
  397. }
  398. return errors.New(op + " " + vpath + ": " + err.Error())
  399. }
  400. // sortModes are fssort.ValidSortModes.
  401. var sortModes = []string{"default", "reverse", "smallToLarge", "largeToSmall", "mostRecent", "leastRecent", "smart", "fileTypeAsce", "fileTypeDesc"}
  402. // sortMode resolves "user" (the File Manager's saved order, which the
  403. // playground does not have) and falls back to default for unknown modes.
  404. func (r *run) sortMode(mode, dir string) string {
  405. if mode == "user" {
  406. return "default"
  407. }
  408. if !containsString(sortModes, mode) {
  409. r.log("agi", "agi", "[AGI] Sort mode: "+mode+" not supported. Using default")
  410. return "default"
  411. }
  412. return mode
  413. }
  414. func sortEntries(list []Entry, mode string) []Entry {
  415. out := append([]Entry(nil), list...)
  416. less := map[string]func(a, b Entry) bool{
  417. "reverse": func(a, b Entry) bool { return a.Name > b.Name },
  418. "smallToLarge": func(a, b Entry) bool { return a.Size < b.Size },
  419. "largeToSmall": func(a, b Entry) bool { return a.Size > b.Size },
  420. "mostRecent": func(a, b Entry) bool { return a.Mtime.After(b.Mtime) },
  421. "leastRecent": func(a, b Entry) bool { return a.Mtime.Before(b.Mtime) },
  422. "smart": func(a, b Entry) bool { return naturalLess(a.Name, b.Name) },
  423. "fileTypeAsce": func(a, b Entry) bool { return typeKey(a) < typeKey(b) },
  424. "fileTypeDesc": func(a, b Entry) bool { return typeKey(a) > typeKey(b) },
  425. }[mode]
  426. if less != nil {
  427. sort.SliceStable(out, func(i, j int) bool { return less(out[i], out[j]) })
  428. }
  429. return out
  430. }
  431. func typeKey(e Entry) string {
  432. return strings.ToLower(path.Ext(e.Name)) + "/" + e.Name
  433. }
  434. // naturalLess orders "file2" before "file10".
  435. func naturalLess(a, b string) bool {
  436. a, b = strings.ToLower(a), strings.ToLower(b)
  437. for a != "" && b != "" {
  438. ca, cb := a[0], b[0]
  439. if isDigit(ca) && isDigit(cb) {
  440. na, ra := leadingNumber(a)
  441. nb, rb := leadingNumber(b)
  442. if len(na) != len(nb) {
  443. return len(na) < len(nb)
  444. }
  445. if na != nb {
  446. return na < nb
  447. }
  448. a, b = ra, rb
  449. continue
  450. }
  451. if ca != cb {
  452. return ca < cb
  453. }
  454. a, b = a[1:], b[1:]
  455. }
  456. return len(a) < len(b)
  457. }
  458. func isDigit(c byte) bool { return c >= '0' && c <= '9' }
  459. func leadingNumber(s string) (string, string) {
  460. i := 0
  461. for i < len(s) && isDigit(s[i]) {
  462. i++
  463. }
  464. n := strings.TrimLeft(s[:i], "0")
  465. return n, s[i:]
  466. }