engine.go 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909
  1. package playground
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "path"
  7. "sort"
  8. "strings"
  9. "sync"
  10. "time"
  11. "github.com/robertkrimen/otto"
  12. )
  13. // Request is one run: the script, the request that calls it, the signed-in
  14. // user, the stored state (database, shares, tasks) and the mocked services.
  15. type Request struct {
  16. Script string `json:"script"` // vpath of the script, web:/... or user:/...
  17. Code string `json:"code"` // the editor's text; read from the drive when empty
  18. Method string `json:"method"`
  19. Query map[string]string `json:"query"`
  20. Form map[string]string `json:"form"`
  21. Body string `json:"body"`
  22. ContentType string `json:"contentType"`
  23. User User `json:"user"`
  24. State State `json:"state"`
  25. Mocks Mocks `json:"mocks"`
  26. TimeoutSec int `json:"timeoutSec"`
  27. Files []File `json:"files"`
  28. // Catalog lists the functions of libraries the playground cannot run,
  29. // from api.json ("git" -> ["git.status", ...]); they become mocks.
  30. Catalog map[string][]string `json:"catalog"`
  31. // Live receives WebSocket frames typed in the page while the script runs.
  32. Live <-chan WSIn `json:"-"`
  33. }
  34. // User is the account the script runs as.
  35. type User struct {
  36. Username string `json:"username"`
  37. Admin bool `json:"admin"`
  38. Groups []string `json:"groups"`
  39. QuotaTotal int64 `json:"quotaTotal"` // bytes, -1 for unlimited
  40. Modules []string `json:"modules"`
  41. }
  42. // State is what outlives a run: the system database, shares, scheduled
  43. // tasks, other accounts and the llm usage board. The page keeps it.
  44. type State struct {
  45. DB map[string]map[string]string `json:"db"`
  46. Shares []Share `json:"shares"`
  47. Tasks []Task `json:"tasks"`
  48. Users []string `json:"users"`
  49. LLMUsage LLMUsage `json:"llmUsage"`
  50. Jobs map[string]json.RawMessage `json:"jobs,omitempty"` // cnn async jobs
  51. }
  52. type Share struct {
  53. UUID string `json:"uuid"`
  54. Vpath string `json:"vpath"`
  55. Owner string `json:"owner"`
  56. Permission string `json:"permission"`
  57. ExpireAt int64 `json:"expireAt,omitempty"`
  58. }
  59. type Task struct {
  60. Name string `json:"name"`
  61. App string `json:"app"`
  62. Interval int64 `json:"interval"`
  63. Description string `json:"description"`
  64. Script string `json:"script"`
  65. Owner string `json:"owner"`
  66. }
  67. type LLMUsage struct {
  68. TotalTokens int64 `json:"totalTokens"`
  69. TotalRequests int64 `json:"totalRequests"`
  70. PerModel map[string]int64 `json:"perModel"`
  71. }
  72. // Result is what the page shows after a run.
  73. type Result struct {
  74. Mode string `json:"mode"` // "webapp" or "serverless"
  75. Status int `json:"status"`
  76. ContentType string `json:"contentType"`
  77. Headers map[string]string `json:"headers,omitempty"`
  78. Response string `json:"response"`
  79. Error *ScriptError `json:"error,omitempty"`
  80. Exited bool `json:"exited,omitempty"`
  81. Console []LogLine `json:"console"`
  82. Calls []Call `json:"calls"`
  83. Written []File `json:"written"`
  84. Removed []string `json:"removed"`
  85. State State `json:"state"`
  86. WS []WSFrame `json:"ws,omitempty"`
  87. Upgraded bool `json:"upgraded,omitempty"`
  88. Notifications []Notification `json:"notifications,omitempty"`
  89. Modules []json.RawMessage `json:"modules,omitempty"` // registerModule() calls
  90. DurationMs int64 `json:"durationMs"`
  91. }
  92. type ScriptError struct {
  93. Kind string `json:"kind"` // "error", "timeout"
  94. Message string `json:"message"`
  95. Stack string `json:"stack,omitempty"`
  96. }
  97. // LogLine is a console.log() line or a message ArozOS would write to the
  98. // server log (errors that make a function return false, for example).
  99. type LogLine struct {
  100. T int64 `json:"t"` // ms since the run started
  101. Source string `json:"source"`
  102. Level string `json:"level"` // "log", "warn", "error", "agi"
  103. Text string `json:"text"`
  104. }
  105. // Call records one call to a mocked service.
  106. type Call struct {
  107. T int64 `json:"t"`
  108. Lib string `json:"lib"`
  109. Fn string `json:"fn"`
  110. Args string `json:"args"`
  111. Result string `json:"result"`
  112. Rule string `json:"rule,omitempty"` // which mock answered
  113. }
  114. type Notification struct {
  115. To string `json:"to"`
  116. Title string `json:"title"`
  117. Message string `json:"message"`
  118. Priority string `json:"priority"`
  119. }
  120. // Hooks stream what happens while the script runs; both may be nil.
  121. type Hooks struct {
  122. Log func(LogLine)
  123. WS func(WSFrame)
  124. }
  125. var (
  126. errExitcall = errors.New("exit")
  127. errTimeout = errors.New("timeout")
  128. )
  129. // run is the state of one Run, shared by the script and its execd children.
  130. type run struct {
  131. req *Request
  132. hooks Hooks
  133. fs *memFS
  134. start time.Time
  135. mu sync.Mutex
  136. res *Result
  137. state State
  138. ws *wsConn
  139. headers map[string]string
  140. status int
  141. kids sync.WaitGroup
  142. vms []*otto.Otto // every VM of the run, so the time limit stops them all
  143. stopped bool
  144. }
  145. // Run executes the script and returns what a browser would receive, plus
  146. // everything the playground shows around it.
  147. func Run(req Request, hooks Hooks) *Result {
  148. r := &run{
  149. req: &req,
  150. hooks: hooks,
  151. fs: newMemFS(req.Files),
  152. start: time.Now(),
  153. res: &Result{Status: 200},
  154. state: req.State,
  155. headers: map[string]string{},
  156. }
  157. r.normalize()
  158. res := r.res
  159. res.Mode = r.mode()
  160. code := req.Code
  161. if code == "" {
  162. b, err := r.fs.ReadFile(req.Script)
  163. if err != nil {
  164. res.Status = 500
  165. res.Error = &ScriptError{Kind: "error", Message: "500 - Internal Server Error: Script not exists"}
  166. return r.finish()
  167. }
  168. code = string(b)
  169. }
  170. if ext := path.Ext(req.Script); ext != ".agi" && ext != ".js" {
  171. res.Status = 403
  172. res.Error = &ScriptError{Kind: "error", Message: "AGI script must have file extension of .agi or .js"}
  173. return r.finish()
  174. }
  175. vm := r.newVM(req.Script, false, "")
  176. r.injectRequest(vm)
  177. timeout := time.Duration(req.TimeoutSec) * time.Second
  178. timer := time.AfterFunc(timeout, r.stopAll)
  179. defer timer.Stop()
  180. r.exec(vm, code)
  181. // execd() children run on after the parent returns, as on a server;
  182. // wait for them (within the time limit) so their output is shown.
  183. done := make(chan struct{})
  184. go func() { r.kids.Wait(); close(done) }()
  185. select {
  186. case <-done:
  187. case <-time.After(time.Until(r.start.Add(timeout))):
  188. r.log("agi", "warn", "execd() scripts still running at the time limit; their output is cut off")
  189. }
  190. if r.ws != nil {
  191. r.ws.shutdown()
  192. }
  193. return r.finish()
  194. }
  195. func (r *run) normalize() {
  196. q := r.req
  197. if q.Method == "" {
  198. q.Method = "POST"
  199. }
  200. if q.TimeoutSec <= 0 || q.TimeoutSec > 300 {
  201. q.TimeoutSec = 30
  202. }
  203. if q.User.Username == "" {
  204. q.User.Username = "developer"
  205. }
  206. if q.User.Groups == nil {
  207. if q.User.Admin {
  208. q.User.Groups = []string{"administrator"}
  209. } else {
  210. q.User.Groups = []string{"user"}
  211. }
  212. }
  213. if q.User.QuotaTotal == 0 {
  214. q.User.QuotaTotal = -1
  215. }
  216. q.Script = Clean(q.Script)
  217. if r.state.DB == nil {
  218. r.state.DB = map[string]map[string]string{}
  219. }
  220. if r.state.LLMUsage.PerModel == nil {
  221. r.state.LLMUsage.PerModel = map[string]int64{}
  222. }
  223. if r.state.Jobs == nil {
  224. r.state.Jobs = map[string]json.RawMessage{}
  225. }
  226. if !containsString(r.state.Users, q.User.Username) {
  227. r.state.Users = append([]string{q.User.Username}, r.state.Users...)
  228. }
  229. }
  230. // mode is "webapp" for a script in the WebApp folder (run through
  231. // /system/ajgi/interface) and "serverless" for one on a user drive (run as
  232. // an external endpoint or from the File Manager).
  233. func (r *run) mode() string {
  234. if strings.HasPrefix(r.req.Script, "web:/") {
  235. return "webapp"
  236. }
  237. return "serverless"
  238. }
  239. // scriptFile is __FILE__: the path relative to the server root for a WebApp
  240. // script ("web/App/x.agi"), the vpath for a script on a drive.
  241. func (r *run) scriptFile(vpath string) string {
  242. if strings.HasPrefix(vpath, "web:/") {
  243. return "web/" + strings.TrimPrefix(vpath, "web:/")
  244. }
  245. return vpath
  246. }
  247. func (r *run) finish() *Result {
  248. res := r.res
  249. res.Written, res.Removed = r.fs.Changes()
  250. if res.Written == nil {
  251. res.Written = []File{}
  252. }
  253. if res.Console == nil {
  254. res.Console = []LogLine{}
  255. }
  256. if res.Calls == nil {
  257. res.Calls = []Call{}
  258. }
  259. if r.status != 0 {
  260. res.Status = r.status
  261. }
  262. if len(r.headers) > 0 {
  263. res.Headers = r.headers
  264. }
  265. res.State = r.state
  266. res.DurationMs = time.Since(r.start).Milliseconds()
  267. return res
  268. }
  269. // stopAll interrupts the script and every execd() child at the time limit.
  270. func (r *run) stopAll() {
  271. r.mu.Lock()
  272. defer r.mu.Unlock()
  273. r.stopped = true
  274. for _, vm := range r.vms {
  275. select {
  276. case vm.Interrupt <- func() { panic(errTimeout) }:
  277. default:
  278. }
  279. }
  280. }
  281. func (r *run) ms() int64 { return time.Since(r.start).Milliseconds() }
  282. func (r *run) log(source, level, text string) {
  283. l := LogLine{T: r.ms(), Source: source, Level: level, Text: text}
  284. r.mu.Lock()
  285. r.res.Console = append(r.res.Console, l)
  286. r.mu.Unlock()
  287. if r.hooks.Log != nil {
  288. r.hooks.Log(l)
  289. }
  290. }
  291. // raise is Gateway.RaiseError: it logs the error and throws it into the
  292. // script as an Error named name (FileLibError, ZipLibError, ...), which the
  293. // script may catch. The playground shows the log line in the console.
  294. // Call it only from a native function on the VM's own goroutine.
  295. // locked runs change while holding r.mu and returns its error. Raise only
  296. // after it returns: raise logs, and logging takes r.mu.
  297. func (r *run) locked(change func() error) error {
  298. r.mu.Lock()
  299. defer r.mu.Unlock()
  300. return change()
  301. }
  302. func (r *run) raise(vm *otto.Otto, name string, err error) otto.Value {
  303. if err == nil {
  304. err = errors.New("unknown error")
  305. }
  306. r.log("agi", "agi", "[AGI] "+name+": "+err.Error())
  307. panic(vm.MakeCustomError(name, err.Error()))
  308. }
  309. func (r *run) call(lib, fn, args, result, rule string) {
  310. r.mu.Lock()
  311. r.res.Calls = append(r.res.Calls, Call{T: r.ms(), Lib: lib, Fn: fn, Args: args, Result: result, Rule: rule})
  312. r.mu.Unlock()
  313. }
  314. // exec runs code on vm and turns exit(), the time limit and script errors
  315. // into the result.
  316. func (r *run) exec(vm *otto.Otto, code string) {
  317. defer func() {
  318. if caught := recover(); caught != nil {
  319. switch caught {
  320. case errExitcall:
  321. r.res.Exited = true
  322. r.res.ContentType = "" // exit() leaves the type to the browser
  323. r.res.Response = vmString(vm, "HTTP_RESP")
  324. case errTimeout:
  325. r.res.Status = 503
  326. r.res.Error = &ScriptError{Kind: "timeout", Message: fmt.Sprintf("Script stopped after %d s (the playground's time limit)", r.req.TimeoutSec)}
  327. default:
  328. r.res.Status = 500
  329. r.res.Error = &ScriptError{Kind: "error", Message: fmt.Sprint("VM crash: ", caught)}
  330. }
  331. }
  332. }()
  333. if _, err := vm.Run(code); err != nil {
  334. r.res.Status = 500
  335. se := &ScriptError{Kind: "error", Message: err.Error()}
  336. if oe, ok := err.(*otto.Error); ok {
  337. se.Stack = oe.String()
  338. }
  339. r.res.Error = se
  340. 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()))
  341. return
  342. }
  343. r.res.Response = vmString(vm, "HTTP_RESP")
  344. r.res.ContentType = vmString(vm, "HTTP_HEADER")
  345. }
  346. func vmString(vm *otto.Otto, name string) string {
  347. v, err := vm.Get(name)
  348. if err != nil {
  349. return ""
  350. }
  351. s, _ := v.ToString()
  352. if s == "undefined" && v.IsUndefined() {
  353. return ""
  354. }
  355. return s
  356. }
  357. // newVM builds a VM the way ExecuteAGIScript does: the standard library,
  358. // the user functions and requirelib(). child marks an execd() script.
  359. func (r *run) newVM(script string, child bool, source string) *otto.Otto {
  360. vm := otto.New()
  361. vm.Interrupt = make(chan func(), 1)
  362. r.mu.Lock()
  363. r.vms = append(r.vms, vm)
  364. if r.stopped {
  365. vm.Interrupt <- func() { panic(errTimeout) }
  366. }
  367. r.mu.Unlock()
  368. if source == "" {
  369. source = "script"
  370. }
  371. r.injectStandard(vm, script, source)
  372. r.injectUser(vm, script, source)
  373. return vm
  374. }
  375. func (r *run) injectStandard(vm *otto.Otto, script, source string) {
  376. webapp := strings.HasPrefix(script, "web:/")
  377. vm.Set("BUILD_VERSION", "playground")
  378. vm.Set("INTERNAL_VERSION", "playground")
  379. vm.Set("LOADED_MODULES", r.loadedModules())
  380. vm.Set("LOADED_STORAGES", map[string]interface{}{"Owner": "system", "OtherPermission": "readonly", "Storages": r.vroots()})
  381. vm.Set("__FILE__", r.scriptFile(script))
  382. vm.Set("HTTP_RESP", "")
  383. vm.Set("HTTP_HEADER", "text/plain")
  384. vm.Set("EXECUTION_ID", newUUID())
  385. vm.Set("_agi_console_log", func(call otto.FunctionCall) otto.Value {
  386. parts := make([]string, 0, len(call.ArgumentList))
  387. for _, a := range call.ArgumentList {
  388. s, _ := a.ToString()
  389. parts = append(parts, s)
  390. }
  391. r.log(source, "log", strings.Join(parts, " "))
  392. return otto.UndefinedValue()
  393. })
  394. vm.Run(`var console = { log: _agi_console_log, warn: _agi_console_log, error: _agi_console_log, info: _agi_console_log };`)
  395. vm.Set("sendResp", func(call otto.FunctionCall) otto.Value {
  396. s, _ := call.Argument(0).ToString()
  397. vm.Set("HTTP_RESP", s)
  398. return otto.Value{}
  399. })
  400. vm.Set("echo", func(call otto.FunctionCall) otto.Value {
  401. s, _ := call.Argument(0).ToString()
  402. vm.Set("HTTP_RESP", vmString(vm, "HTTP_RESP")+s)
  403. return otto.Value{}
  404. })
  405. vm.Set("sendOK", func(call otto.FunctionCall) otto.Value {
  406. vm.Set("HTTP_RESP", "ok")
  407. return otto.Value{}
  408. })
  409. vm.Set("_sendJSONResp", func(call otto.FunctionCall) otto.Value {
  410. s, _ := call.Argument(0).ToString()
  411. vm.Set("HTTP_HEADER", "application/json")
  412. vm.Set("HTTP_RESP", s)
  413. return otto.Value{}
  414. })
  415. vm.Run(`
  416. sendJSONResp = function(object){
  417. if (typeof(object) === "object"){
  418. _sendJSONResp(JSON.stringify(object));
  419. }else{
  420. _sendJSONResp(object);
  421. }
  422. }
  423. `)
  424. vm.Set("addNightlyTask", func(call otto.FunctionCall) otto.Value {
  425. p, _ := call.Argument(0).ToString()
  426. if ext := path.Ext(p); ext != ".agi" && ext != ".js" {
  427. return r.raise(vm, "AGIError", errors.New("not an AGI script: "+p))
  428. }
  429. r.log("agi", "agi", "Nightly task registered: "+p+" (ArozOS runs it every night; the playground only records it)")
  430. return otto.TrueValue()
  431. })
  432. r.injectDB(vm)
  433. vm.Set("registerModule", func(call otto.FunctionCall) otto.Value {
  434. s, _ := call.Argument(0).ToString()
  435. var cfg map[string]interface{}
  436. if err := json.Unmarshal([]byte(s), &cfg); err != nil {
  437. return r.raise(vm, "AGIError", err)
  438. }
  439. if webapp {
  440. // Relative paths become paths from the web root, as on a server.
  441. dir := strings.SplitN(strings.TrimPrefix(script, "web:/"), "/", 2)[0]
  442. for _, f := range []string{"IconPath", "StartDir", "LaunchFWDir", "LaunchEmb"} {
  443. if v, ok := cfg[f].(string); ok && v != "" && !strings.HasPrefix(v, dir+"/") && !path.IsAbs(v) {
  444. cfg[f] = path.Join(dir, v)
  445. }
  446. }
  447. }
  448. b, _ := json.Marshal(cfg)
  449. r.mu.Lock()
  450. r.res.Modules = append(r.res.Modules, b)
  451. r.mu.Unlock()
  452. r.log("agi", "agi", fmt.Sprintf("Module registered: %v", cfg["Name"]))
  453. return otto.Value{}
  454. })
  455. vm.Set("registerExtensionIcon", func(call otto.FunctionCall) otto.Value {
  456. ext, _ := call.Argument(0).ToString()
  457. icon, _ := call.Argument(1).ToString()
  458. if ext == "" || ext == "undefined" {
  459. return r.raise(vm, "AGIError", errors.New("registerExtensionIcon: extension not given"))
  460. }
  461. if icon == "" || icon == "undefined" {
  462. return r.raise(vm, "AGIError", errors.New("registerExtensionIcon: icon path not given"))
  463. }
  464. r.log("agi", "agi", "Extension icon registered: "+ext+" -> "+icon)
  465. return otto.TrueValue()
  466. })
  467. if webapp {
  468. vm.Set("requirepkg", func(call otto.FunctionCall) otto.Value {
  469. return r.raise(vm, "AGIError", errors.New("requirepkg has been deprecated in agi v3.0"))
  470. })
  471. vm.Set("execpkg", func(call otto.FunctionCall) otto.Value {
  472. return r.raise(vm, "AGIError", errors.New("execpkg has been deprecated in agi v3.0"))
  473. })
  474. vm.Set("includes", func(call otto.FunctionCall) otto.Value {
  475. name, err := call.Argument(0).ToString()
  476. if err != nil {
  477. return r.raise(vm, "AGIError", err)
  478. }
  479. if path.Base(script) == path.Base(name) {
  480. return r.raise(vm, "AGIError", errors.New("includes: a script cannot include itself"))
  481. }
  482. target := Clean(path.Join(path.Dir(script), name))
  483. b, err := r.fs.ReadFile(target)
  484. if err != nil {
  485. return r.raise(vm, "AGIError", errors.New("includes: script not found: "+name))
  486. }
  487. if _, err := vm.Run(string(b)); err != nil {
  488. return r.raise(vm, "AGIError", fmt.Errorf("includes: %s failed: %s", name, err.Error()))
  489. }
  490. return otto.TrueValue()
  491. })
  492. }
  493. vm.Set("delay", func(call otto.FunctionCall) otto.Value {
  494. ms, err := call.Argument(0).ToInteger()
  495. if err != nil {
  496. return r.raise(vm, "AGIError", err)
  497. }
  498. if r.ws != nil && r.ws.pumps(vm) {
  499. r.ws.pump(vm, time.Duration(ms)*time.Millisecond)
  500. } else {
  501. time.Sleep(time.Duration(ms) * time.Millisecond)
  502. }
  503. return otto.TrueValue()
  504. })
  505. vm.Set("exit", func(call otto.FunctionCall) otto.Value {
  506. select {
  507. case vm.Interrupt <- func() { panic(errExitcall) }:
  508. default:
  509. }
  510. return otto.NullValue()
  511. })
  512. }
  513. // reservedTables are refused by the DB functions, as in src/agi.go.
  514. var reservedTables = []string{"auth", "permisson", "register", "desktop"}
  515. // tableErr is Gateway.checkDBTable: a reserved table, or one that must exist
  516. // and does not, is an error the DB functions throw
  517. func (r *run) tableErr(name string, mustExist bool) error {
  518. if containsString(reservedTables, name) {
  519. return errors.New("database table " + name + " is reserved by the system")
  520. }
  521. if mustExist && !r.tableExists(name) {
  522. return errors.New("database table " + name + " does not exist")
  523. }
  524. return nil
  525. }
  526. func (r *run) tableExists(name string) bool {
  527. r.mu.Lock()
  528. defer r.mu.Unlock()
  529. _, ok := r.state.DB[name]
  530. return ok
  531. }
  532. func (r *run) injectDB(vm *otto.Otto) {
  533. vm.Set("newDBTableIfNotExists", func(call otto.FunctionCall) otto.Value {
  534. t, err := call.Argument(0).ToString()
  535. if err != nil {
  536. return r.raise(vm, "AGIError", err)
  537. }
  538. if err := r.tableErr(t, false); err != nil {
  539. return r.raise(vm, "AGIError", err)
  540. }
  541. r.mu.Lock()
  542. if r.state.DB[t] == nil {
  543. r.state.DB[t] = map[string]string{}
  544. }
  545. r.mu.Unlock()
  546. return otto.TrueValue()
  547. })
  548. vm.Set("DBTableExists", func(call otto.FunctionCall) otto.Value {
  549. t, _ := call.Argument(0).ToString()
  550. r.mu.Lock()
  551. _, ok := r.state.DB[t]
  552. r.mu.Unlock()
  553. return boolValue(ok)
  554. })
  555. vm.Set("dropDBTable", func(call otto.FunctionCall) otto.Value {
  556. t, _ := call.Argument(0).ToString()
  557. if err := r.tableErr(t, true); err != nil {
  558. return r.raise(vm, "AGIError", err)
  559. }
  560. r.mu.Lock()
  561. delete(r.state.DB, t)
  562. r.mu.Unlock()
  563. return otto.TrueValue()
  564. })
  565. vm.Set("writeDBItem", func(call otto.FunctionCall) otto.Value {
  566. t, _ := call.Argument(0).ToString()
  567. if err := r.tableErr(t, true); err != nil {
  568. return r.raise(vm, "AGIError", err)
  569. }
  570. k, _ := call.Argument(1).ToString()
  571. v, _ := call.Argument(2).ToString()
  572. r.mu.Lock()
  573. r.state.DB[t][k] = v
  574. r.mu.Unlock()
  575. return otto.TrueValue()
  576. })
  577. vm.Set("readDBItem", func(call otto.FunctionCall) otto.Value {
  578. t, _ := call.Argument(0).ToString()
  579. k, _ := call.Argument(1).ToString()
  580. //A table that does not exist yet holds nothing: false, not an error
  581. if err := r.tableErr(t, false); err != nil {
  582. return r.raise(vm, "AGIError", err)
  583. }
  584. if !r.tableExists(t) {
  585. return otto.FalseValue()
  586. }
  587. r.mu.Lock()
  588. v := r.state.DB[t][k]
  589. r.mu.Unlock()
  590. out, _ := vm.ToValue(v)
  591. return out
  592. })
  593. vm.Set("listDBTable", func(call otto.FunctionCall) otto.Value {
  594. t, _ := call.Argument(0).ToString()
  595. if err := r.tableErr(t, false); err != nil {
  596. return r.raise(vm, "AGIError", err)
  597. }
  598. if !r.tableExists(t) {
  599. return otto.FalseValue()
  600. }
  601. r.mu.Lock()
  602. cp := map[string]string{}
  603. for k, v := range r.state.DB[t] {
  604. cp[k] = v
  605. }
  606. r.mu.Unlock()
  607. out, err := vm.ToValue(cp)
  608. if err != nil {
  609. return r.raise(vm, "AGIError", err)
  610. }
  611. return out
  612. })
  613. vm.Set("deleteDBItem", func(call otto.FunctionCall) otto.Value {
  614. t, _ := call.Argument(0).ToString()
  615. k, _ := call.Argument(1).ToString()
  616. if err := r.tableErr(t, true); err != nil {
  617. return r.raise(vm, "AGIError", err)
  618. }
  619. r.mu.Lock()
  620. delete(r.state.DB[t], k)
  621. r.mu.Unlock()
  622. return otto.TrueValue()
  623. })
  624. }
  625. // canRead / canWrite: the user may use user:/ and tmp:/. web:/ is not a
  626. // drive (scripts cannot reach ./web through filelib on a server either).
  627. func (r *run) canRead(vpath string) bool {
  628. return strings.HasPrefix(Clean(vpath), "user:/") || strings.HasPrefix(Clean(vpath), "tmp:/")
  629. }
  630. func (r *run) canWrite(vpath string) bool { return r.canRead(vpath) }
  631. func (r *run) vroots() []map[string]interface{} {
  632. return []map[string]interface{}{
  633. {"UUID": "user", "Name": "User", "Path": "user:/", "Hierarchy": "user", "ReadOnly": false, "Filesystem": "virtual"},
  634. {"UUID": "tmp", "Name": "tmp", "Path": "tmp:/", "Hierarchy": "user", "ReadOnly": false, "Filesystem": "virtual"},
  635. }
  636. }
  637. func (r *run) loadedModules() []map[string]interface{} {
  638. return []map[string]interface{}{
  639. {"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}},
  640. {"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"},
  641. }
  642. }
  643. func (r *run) injectUser(vm *otto.Otto, script, source string) {
  644. u := r.req.User
  645. vm.Set("USERNAME", u.Username)
  646. vm.Set("USERICON", "img/desktop/system_icon/user.svg")
  647. vm.Set("USERQUOTA_TOTAL", u.QuotaTotal)
  648. vm.Set("USERQUOTA_USED", r.fs.UsedBytes("user"))
  649. vm.Set("USER_VROOTS", r.vroots())
  650. modules := u.Modules
  651. if modules == nil {
  652. modules = []string{"Playground", "File Manager"}
  653. }
  654. vm.Set("USER_MODULES", modules)
  655. for _, name := range []string{"decodeVirtualPath", "decodeAbsoluteVirtualPath", "encodeRealPath"} {
  656. name := name
  657. vm.Set(name, func(call otto.FunctionCall) otto.Value {
  658. r.log("agi", "agi", "Call to deprecated function "+name)
  659. return otto.FalseValue()
  660. })
  661. }
  662. vm.Set("pathCanWrite", func(call otto.FunctionCall) otto.Value {
  663. p, _ := call.Argument(0).ToString()
  664. return boolValue(r.canWrite(p))
  665. })
  666. vm.Set("getUserPermissionGroup", func(call otto.FunctionCall) otto.Value {
  667. groups := []map[string]interface{}{}
  668. for _, g := range u.Groups {
  669. groups = append(groups, map[string]interface{}{
  670. "Name": g, "IsAdmin": u.Admin && g == "administrator", "DefaultInterfaceModule": "Desktop",
  671. "DefaultStorageQuota": u.QuotaTotal, "AccessibleModules": modules,
  672. })
  673. }
  674. b, _ := json.Marshal(groups)
  675. out, _ := vm.ToValue(string(b))
  676. return out
  677. })
  678. vm.Set("userIsAdmin", func(call otto.FunctionCall) otto.Value { return boolValue(u.Admin) })
  679. //adminOnly throws for a user who is not an administrator
  680. adminOnly := func(name string) {
  681. if !u.Admin {
  682. r.raise(vm, "AGIError", errors.New("Permission Denied: "+name+" require admin permission"))
  683. }
  684. }
  685. vm.Set("userExists", func(call otto.FunctionCall) otto.Value {
  686. adminOnly("userExists")
  687. name, err := call.Argument(0).ToString()
  688. if err != nil || name == "undefined" {
  689. return r.raise(vm, "AGIError", errors.New("username is undefined"))
  690. }
  691. r.mu.Lock()
  692. defer r.mu.Unlock()
  693. return boolValue(containsString(r.state.Users, name))
  694. })
  695. vm.Set("createUser", func(call otto.FunctionCall) otto.Value {
  696. adminOnly("createUser")
  697. name, _ := call.Argument(0).ToString()
  698. pass, _ := call.Argument(1).ToString()
  699. group, _ := call.Argument(2).ToString()
  700. switch {
  701. case name == "undefined" || name == "":
  702. return r.raise(vm, "AGIError", errors.New("username is undefined"))
  703. case pass == "undefined":
  704. return r.raise(vm, "AGIError", errors.New("password is undefined"))
  705. case group == "undefined":
  706. return r.raise(vm, "AGIError", errors.New("defaultGroup is undefined"))
  707. case group != "administrator" && group != "user":
  708. return r.raise(vm, "AGIError", errors.New(group+" user-group not exists"))
  709. }
  710. err := r.locked(func() error {
  711. if containsString(r.state.Users, name) {
  712. return errors.New("Username already exists")
  713. }
  714. r.state.Users = append(r.state.Users, name)
  715. return nil
  716. })
  717. if err != nil {
  718. return r.raise(vm, "AGIError", err)
  719. }
  720. return otto.TrueValue()
  721. })
  722. vm.Set("editUser", func(call otto.FunctionCall) otto.Value {
  723. adminOnly("editUser")
  724. return otto.FalseValue()
  725. })
  726. vm.Set("removeUser", func(call otto.FunctionCall) otto.Value {
  727. adminOnly("removeUser")
  728. name, err := call.Argument(0).ToString()
  729. if err != nil || name == "undefined" {
  730. return r.raise(vm, "AGIError", errors.New("username is undefined"))
  731. }
  732. err = r.locked(func() error {
  733. for i, n := range r.state.Users {
  734. if n == name {
  735. r.state.Users = append(r.state.Users[:i], r.state.Users[i+1:]...)
  736. return nil
  737. }
  738. }
  739. return errors.New(name + " not exists")
  740. })
  741. if err != nil {
  742. return r.raise(vm, "AGIError", err)
  743. }
  744. return otto.TrueValue()
  745. })
  746. vm.Set("requirelib", func(call otto.FunctionCall) otto.Value {
  747. name, err := call.Argument(0).ToString()
  748. if err != nil {
  749. return r.raise(vm, "AGIError", err)
  750. }
  751. if r.loadLib(vm, name, script) {
  752. return otto.TrueValue()
  753. }
  754. r.log("agi", "agi", "Lib not found: "+name)
  755. return otto.FalseValue()
  756. })
  757. vm.Set("execd", func(call otto.FunctionCall) otto.Value {
  758. name, err := call.Argument(0).ToString()
  759. if err != nil {
  760. return r.raise(vm, "AGIError", err)
  761. }
  762. payload, _ := call.Argument(1).ToString()
  763. target := Clean(path.Join(path.Dir(script), name))
  764. b, err := r.fs.ReadFile(target)
  765. if err != nil {
  766. return r.raise(vm, "AGIError", errors.New("execd: script not found: "+name))
  767. }
  768. r.kids.Add(1)
  769. go func() {
  770. defer r.kids.Done()
  771. // The child keeps the parent's script path, as on a server.
  772. child := r.newVM(script, true, "execd:"+path.Base(target))
  773. child.Set("PARENT_DETACHED", true)
  774. child.Set("PARENT_PAYLOAD", payload)
  775. defer func() {
  776. if caught := recover(); caught != nil && caught != errExitcall && caught != errTimeout {
  777. r.log("execd:"+path.Base(target), "error", fmt.Sprint("VM crash: ", caught))
  778. }
  779. }()
  780. //Nothing waits for a detached script, so its error is only logged
  781. if _, err := child.Run(string(b)); err != nil {
  782. r.log("agi", "agi", "[AGI] Detached script "+path.Base(target)+" failed: "+err.Error())
  783. }
  784. }()
  785. return otto.TrueValue()
  786. })
  787. }
  788. // injectRequest sets what the HTTP request carries: POST fields as globals
  789. // for a WebApp script, getPara/postPara/readBody for a serverless one.
  790. func (r *run) injectRequest(vm *otto.Otto) {
  791. q := r.req
  792. if r.mode() == "webapp" {
  793. if strings.Contains(q.ContentType, "application/json") {
  794. fields := map[string]interface{}{}
  795. json.Unmarshal([]byte(q.Body), &fields)
  796. for k, v := range fields {
  797. vm.Set(k, v)
  798. }
  799. vm.Set("POST_data", q.Body)
  800. } else if q.Method == "POST" || q.Method == "PUT" || q.Method == "PATCH" {
  801. keys := make([]string, 0, len(q.Form))
  802. for k := range q.Form {
  803. keys = append(keys, k)
  804. }
  805. sort.Strings(keys)
  806. for _, k := range keys {
  807. vm.Set(k, q.Form[k])
  808. }
  809. }
  810. return
  811. }
  812. vm.Set("REQ_METHOD", q.Method)
  813. vm.Set("getPara", func(call otto.FunctionCall) otto.Value {
  814. k, _ := call.Argument(0).ToString()
  815. if v, ok := q.Query[k]; ok && k != "" {
  816. out, _ := vm.ToValue(v)
  817. return out
  818. }
  819. return otto.NullValue()
  820. })
  821. vm.Set("postPara", func(call otto.FunctionCall) otto.Value {
  822. k, _ := call.Argument(0).ToString()
  823. if v, ok := q.Form[k]; ok && k != "" {
  824. out, _ := vm.ToValue(v)
  825. return out
  826. }
  827. return otto.NullValue()
  828. })
  829. vm.Set("readBody", func(call otto.FunctionCall) otto.Value {
  830. body := q.Body
  831. if body == "" && len(q.Form) > 0 {
  832. body = encodeForm(q.Form)
  833. }
  834. out, _ := vm.ToValue(body)
  835. return out
  836. })
  837. }
  838. func boolValue(b bool) otto.Value {
  839. if b {
  840. return otto.TrueValue()
  841. }
  842. return otto.FalseValue()
  843. }
  844. func containsString(list []string, s string) bool {
  845. for _, v := range list {
  846. if v == s {
  847. return true
  848. }
  849. }
  850. return false
  851. }