engine.go 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901
  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: ArozOS only logs it, and the function then
  292. // returns false. The playground shows the log line in the console.
  293. func (r *run) raise(err error) {
  294. if err != nil {
  295. r.log("agi", "agi", "[AGI] Runtime Error "+err.Error())
  296. }
  297. }
  298. func (r *run) call(lib, fn, args, result, rule string) {
  299. r.mu.Lock()
  300. r.res.Calls = append(r.res.Calls, Call{T: r.ms(), Lib: lib, Fn: fn, Args: args, Result: result, Rule: rule})
  301. r.mu.Unlock()
  302. }
  303. // exec runs code on vm and turns exit(), the time limit and script errors
  304. // into the result.
  305. func (r *run) exec(vm *otto.Otto, code string) {
  306. defer func() {
  307. if caught := recover(); caught != nil {
  308. switch caught {
  309. case errExitcall:
  310. r.res.Exited = true
  311. r.res.ContentType = "" // exit() leaves the type to the browser
  312. r.res.Response = vmString(vm, "HTTP_RESP")
  313. case errTimeout:
  314. r.res.Status = 503
  315. r.res.Error = &ScriptError{Kind: "timeout", Message: fmt.Sprintf("Script stopped after %d s (the playground's time limit)", r.req.TimeoutSec)}
  316. default:
  317. r.res.Status = 500
  318. r.res.Error = &ScriptError{Kind: "error", Message: fmt.Sprint("VM crash: ", caught)}
  319. }
  320. }
  321. }()
  322. if _, err := vm.Run(code); err != nil {
  323. r.res.Status = 500
  324. se := &ScriptError{Kind: "error", Message: err.Error()}
  325. if oe, ok := err.(*otto.Error); ok {
  326. se.Stack = oe.String()
  327. }
  328. r.res.Error = se
  329. 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()))
  330. return
  331. }
  332. r.res.Response = vmString(vm, "HTTP_RESP")
  333. r.res.ContentType = vmString(vm, "HTTP_HEADER")
  334. }
  335. func vmString(vm *otto.Otto, name string) string {
  336. v, err := vm.Get(name)
  337. if err != nil {
  338. return ""
  339. }
  340. s, _ := v.ToString()
  341. if s == "undefined" && v.IsUndefined() {
  342. return ""
  343. }
  344. return s
  345. }
  346. // newVM builds a VM the way ExecuteAGIScript does: the standard library,
  347. // the user functions and requirelib(). child marks an execd() script.
  348. func (r *run) newVM(script string, child bool, source string) *otto.Otto {
  349. vm := otto.New()
  350. vm.Interrupt = make(chan func(), 1)
  351. r.mu.Lock()
  352. r.vms = append(r.vms, vm)
  353. if r.stopped {
  354. vm.Interrupt <- func() { panic(errTimeout) }
  355. }
  356. r.mu.Unlock()
  357. if source == "" {
  358. source = "script"
  359. }
  360. r.injectStandard(vm, script, source)
  361. r.injectUser(vm, script, source)
  362. return vm
  363. }
  364. func (r *run) injectStandard(vm *otto.Otto, script, source string) {
  365. webapp := strings.HasPrefix(script, "web:/")
  366. vm.Set("BUILD_VERSION", "playground")
  367. vm.Set("INTERNAL_VERSION", "playground")
  368. vm.Set("LOADED_MODULES", r.loadedModules())
  369. vm.Set("LOADED_STORAGES", map[string]interface{}{"Owner": "system", "OtherPermission": "readonly", "Storages": r.vroots()})
  370. vm.Set("__FILE__", r.scriptFile(script))
  371. vm.Set("HTTP_RESP", "")
  372. vm.Set("HTTP_HEADER", "text/plain")
  373. vm.Set("EXECUTION_ID", newUUID())
  374. vm.Set("_agi_console_log", func(call otto.FunctionCall) otto.Value {
  375. parts := make([]string, 0, len(call.ArgumentList))
  376. for _, a := range call.ArgumentList {
  377. s, _ := a.ToString()
  378. parts = append(parts, s)
  379. }
  380. r.log(source, "log", strings.Join(parts, " "))
  381. return otto.UndefinedValue()
  382. })
  383. vm.Run(`var console = { log: _agi_console_log, warn: _agi_console_log, error: _agi_console_log, info: _agi_console_log };`)
  384. vm.Set("sendResp", func(call otto.FunctionCall) otto.Value {
  385. s, _ := call.Argument(0).ToString()
  386. vm.Set("HTTP_RESP", s)
  387. return otto.Value{}
  388. })
  389. vm.Set("echo", func(call otto.FunctionCall) otto.Value {
  390. s, _ := call.Argument(0).ToString()
  391. vm.Set("HTTP_RESP", vmString(vm, "HTTP_RESP")+s)
  392. return otto.Value{}
  393. })
  394. vm.Set("sendOK", func(call otto.FunctionCall) otto.Value {
  395. vm.Set("HTTP_RESP", "ok")
  396. return otto.Value{}
  397. })
  398. vm.Set("_sendJSONResp", func(call otto.FunctionCall) otto.Value {
  399. s, _ := call.Argument(0).ToString()
  400. vm.Set("HTTP_HEADER", "application/json")
  401. vm.Set("HTTP_RESP", s)
  402. return otto.Value{}
  403. })
  404. vm.Run(`
  405. sendJSONResp = function(object){
  406. if (typeof(object) === "object"){
  407. _sendJSONResp(JSON.stringify(object));
  408. }else{
  409. _sendJSONResp(object);
  410. }
  411. }
  412. `)
  413. vm.Set("addNightlyTask", func(call otto.FunctionCall) otto.Value {
  414. p, _ := call.Argument(0).ToString()
  415. if ext := path.Ext(p); ext != ".agi" && ext != ".js" {
  416. return otto.FalseValue()
  417. }
  418. r.log("agi", "agi", "Nightly task registered: "+p+" (ArozOS runs it every night; the playground only records it)")
  419. return otto.TrueValue()
  420. })
  421. r.injectDB(vm)
  422. vm.Set("registerModule", func(call otto.FunctionCall) otto.Value {
  423. s, _ := call.Argument(0).ToString()
  424. var cfg map[string]interface{}
  425. if err := json.Unmarshal([]byte(s), &cfg); err != nil {
  426. r.raise(err)
  427. return otto.FalseValue()
  428. }
  429. if webapp {
  430. // Relative paths become paths from the web root, as on a server.
  431. dir := strings.SplitN(strings.TrimPrefix(script, "web:/"), "/", 2)[0]
  432. for _, f := range []string{"IconPath", "StartDir", "LaunchFWDir", "LaunchEmb"} {
  433. if v, ok := cfg[f].(string); ok && v != "" && !strings.HasPrefix(v, dir+"/") && !path.IsAbs(v) {
  434. cfg[f] = path.Join(dir, v)
  435. }
  436. }
  437. }
  438. b, _ := json.Marshal(cfg)
  439. r.mu.Lock()
  440. r.res.Modules = append(r.res.Modules, b)
  441. r.mu.Unlock()
  442. r.log("agi", "agi", fmt.Sprintf("Module registered: %v", cfg["Name"]))
  443. return otto.Value{}
  444. })
  445. vm.Set("registerExtensionIcon", func(call otto.FunctionCall) otto.Value {
  446. ext, _ := call.Argument(0).ToString()
  447. icon, _ := call.Argument(1).ToString()
  448. if ext == "" || ext == "undefined" || icon == "" || icon == "undefined" {
  449. return otto.FalseValue()
  450. }
  451. r.log("agi", "agi", "Extension icon registered: "+ext+" -> "+icon)
  452. return otto.TrueValue()
  453. })
  454. if webapp {
  455. vm.Set("requirepkg", func(call otto.FunctionCall) otto.Value {
  456. r.raise(errors.New("requirepkg has been deprecated in agi v3.0"))
  457. return otto.FalseValue()
  458. })
  459. vm.Set("execpkg", func(call otto.FunctionCall) otto.Value {
  460. r.raise(errors.New("execpkg has been deprecated in agi v3.0"))
  461. return otto.FalseValue()
  462. })
  463. vm.Set("includes", func(call otto.FunctionCall) otto.Value {
  464. name, err := call.Argument(0).ToString()
  465. if err != nil {
  466. r.raise(err)
  467. return otto.FalseValue()
  468. }
  469. if path.Base(script) == path.Base(name) {
  470. r.raise(errors.New("*AGI* Self calling is not allowed"))
  471. return otto.FalseValue()
  472. }
  473. target := Clean(path.Join(path.Dir(script), name))
  474. b, err := r.fs.ReadFile(target)
  475. if err != nil {
  476. r.raise(errors.New("*AGI* Target path not exists!"))
  477. return otto.FalseValue()
  478. }
  479. if _, err := vm.Run(string(b)); err != nil {
  480. r.log("agi", "agi", "Script Execution Failed: "+err.Error())
  481. r.raise(err)
  482. return otto.FalseValue()
  483. }
  484. return otto.TrueValue()
  485. })
  486. }
  487. vm.Set("delay", func(call otto.FunctionCall) otto.Value {
  488. ms, err := call.Argument(0).ToInteger()
  489. if err != nil {
  490. r.raise(err)
  491. return otto.FalseValue()
  492. }
  493. if r.ws != nil && r.ws.pumps(vm) {
  494. r.ws.pump(vm, time.Duration(ms)*time.Millisecond)
  495. } else {
  496. time.Sleep(time.Duration(ms) * time.Millisecond)
  497. }
  498. return otto.TrueValue()
  499. })
  500. vm.Set("exit", func(call otto.FunctionCall) otto.Value {
  501. select {
  502. case vm.Interrupt <- func() { panic(errExitcall) }:
  503. default:
  504. }
  505. return otto.NullValue()
  506. })
  507. }
  508. // reservedTables are refused by the DB functions, as in src/agi.go.
  509. var reservedTables = []string{"auth", "permisson", "register", "desktop"}
  510. func (r *run) tableOK(name string, mustExist bool) bool {
  511. if containsString(reservedTables, name) {
  512. return false
  513. }
  514. if mustExist {
  515. r.mu.Lock()
  516. _, ok := r.state.DB[name]
  517. r.mu.Unlock()
  518. return ok
  519. }
  520. return true
  521. }
  522. func (r *run) injectDB(vm *otto.Otto) {
  523. vm.Set("newDBTableIfNotExists", func(call otto.FunctionCall) otto.Value {
  524. t, err := call.Argument(0).ToString()
  525. if err != nil {
  526. r.raise(err)
  527. return otto.FalseValue()
  528. }
  529. if !r.tableOK(t, false) {
  530. return otto.FalseValue()
  531. }
  532. r.mu.Lock()
  533. if r.state.DB[t] == nil {
  534. r.state.DB[t] = map[string]string{}
  535. }
  536. r.mu.Unlock()
  537. return otto.TrueValue()
  538. })
  539. vm.Set("DBTableExists", func(call otto.FunctionCall) otto.Value {
  540. t, _ := call.Argument(0).ToString()
  541. r.mu.Lock()
  542. _, ok := r.state.DB[t]
  543. r.mu.Unlock()
  544. return boolValue(ok)
  545. })
  546. vm.Set("dropDBTable", func(call otto.FunctionCall) otto.Value {
  547. t, _ := call.Argument(0).ToString()
  548. if !r.tableOK(t, true) {
  549. return otto.FalseValue()
  550. }
  551. r.mu.Lock()
  552. delete(r.state.DB, t)
  553. r.mu.Unlock()
  554. return otto.TrueValue()
  555. })
  556. vm.Set("writeDBItem", func(call otto.FunctionCall) otto.Value {
  557. t, _ := call.Argument(0).ToString()
  558. if !r.tableOK(t, true) {
  559. return otto.FalseValue()
  560. }
  561. k, _ := call.Argument(1).ToString()
  562. v, _ := call.Argument(2).ToString()
  563. r.mu.Lock()
  564. r.state.DB[t][k] = v
  565. r.mu.Unlock()
  566. return otto.TrueValue()
  567. })
  568. vm.Set("readDBItem", func(call otto.FunctionCall) otto.Value {
  569. t, _ := call.Argument(0).ToString()
  570. k, _ := call.Argument(1).ToString()
  571. if !r.tableOK(t, true) {
  572. return otto.FalseValue()
  573. }
  574. r.mu.Lock()
  575. v := r.state.DB[t][k]
  576. r.mu.Unlock()
  577. out, _ := vm.ToValue(v)
  578. return out
  579. })
  580. vm.Set("listDBTable", func(call otto.FunctionCall) otto.Value {
  581. t, _ := call.Argument(0).ToString()
  582. if !r.tableOK(t, true) {
  583. return otto.FalseValue()
  584. }
  585. r.mu.Lock()
  586. cp := map[string]string{}
  587. for k, v := range r.state.DB[t] {
  588. cp[k] = v
  589. }
  590. r.mu.Unlock()
  591. out, err := vm.ToValue(cp)
  592. if err != nil {
  593. return otto.NullValue()
  594. }
  595. return out
  596. })
  597. vm.Set("deleteDBItem", func(call otto.FunctionCall) otto.Value {
  598. t, _ := call.Argument(0).ToString()
  599. k, _ := call.Argument(1).ToString()
  600. if !r.tableOK(t, true) {
  601. return otto.FalseValue()
  602. }
  603. r.mu.Lock()
  604. delete(r.state.DB[t], k)
  605. r.mu.Unlock()
  606. return otto.TrueValue()
  607. })
  608. }
  609. // canRead / canWrite: the user may use user:/ and tmp:/. web:/ is not a
  610. // drive (scripts cannot reach ./web through filelib on a server either).
  611. func (r *run) canRead(vpath string) bool {
  612. return strings.HasPrefix(Clean(vpath), "user:/") || strings.HasPrefix(Clean(vpath), "tmp:/")
  613. }
  614. func (r *run) canWrite(vpath string) bool { return r.canRead(vpath) }
  615. func (r *run) vroots() []map[string]interface{} {
  616. return []map[string]interface{}{
  617. {"UUID": "user", "Name": "User", "Path": "user:/", "Hierarchy": "user", "ReadOnly": false, "Filesystem": "virtual"},
  618. {"UUID": "tmp", "Name": "tmp", "Path": "tmp:/", "Hierarchy": "user", "ReadOnly": false, "Filesystem": "virtual"},
  619. }
  620. }
  621. func (r *run) loadedModules() []map[string]interface{} {
  622. return []map[string]interface{}{
  623. {"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}},
  624. {"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"},
  625. }
  626. }
  627. func (r *run) injectUser(vm *otto.Otto, script, source string) {
  628. u := r.req.User
  629. vm.Set("USERNAME", u.Username)
  630. vm.Set("USERICON", "img/desktop/system_icon/user.svg")
  631. vm.Set("USERQUOTA_TOTAL", u.QuotaTotal)
  632. vm.Set("USERQUOTA_USED", r.fs.UsedBytes("user"))
  633. vm.Set("USER_VROOTS", r.vroots())
  634. modules := u.Modules
  635. if modules == nil {
  636. modules = []string{"Playground", "File Manager"}
  637. }
  638. vm.Set("USER_MODULES", modules)
  639. for _, name := range []string{"decodeVirtualPath", "decodeAbsoluteVirtualPath", "encodeRealPath"} {
  640. name := name
  641. vm.Set(name, func(call otto.FunctionCall) otto.Value {
  642. r.log("agi", "agi", "Call to deprecated function "+name)
  643. return otto.FalseValue()
  644. })
  645. }
  646. vm.Set("pathCanWrite", func(call otto.FunctionCall) otto.Value {
  647. p, _ := call.Argument(0).ToString()
  648. return boolValue(r.canWrite(p))
  649. })
  650. vm.Set("getUserPermissionGroup", func(call otto.FunctionCall) otto.Value {
  651. groups := []map[string]interface{}{}
  652. for _, g := range u.Groups {
  653. groups = append(groups, map[string]interface{}{
  654. "Name": g, "IsAdmin": u.Admin && g == "administrator", "DefaultInterfaceModule": "Desktop",
  655. "DefaultStorageQuota": u.QuotaTotal, "AccessibleModules": modules,
  656. })
  657. }
  658. b, _ := json.Marshal(groups)
  659. out, _ := vm.ToValue(string(b))
  660. return out
  661. })
  662. vm.Set("userIsAdmin", func(call otto.FunctionCall) otto.Value { return boolValue(u.Admin) })
  663. adminOnly := func(name string) bool {
  664. if !u.Admin {
  665. r.raise(errors.New("Permission Denied: " + name + " require admin permission"))
  666. return false
  667. }
  668. return true
  669. }
  670. vm.Set("userExists", func(call otto.FunctionCall) otto.Value {
  671. if !adminOnly("userExists") {
  672. return otto.FalseValue()
  673. }
  674. name, err := call.Argument(0).ToString()
  675. if err != nil || name == "undefined" {
  676. r.raise(errors.New("username is undefined"))
  677. return otto.NullValue()
  678. }
  679. r.mu.Lock()
  680. defer r.mu.Unlock()
  681. return boolValue(containsString(r.state.Users, name))
  682. })
  683. vm.Set("createUser", func(call otto.FunctionCall) otto.Value {
  684. if !adminOnly("createUser") {
  685. return otto.FalseValue()
  686. }
  687. name, _ := call.Argument(0).ToString()
  688. pass, _ := call.Argument(1).ToString()
  689. group, _ := call.Argument(2).ToString()
  690. switch {
  691. case name == "undefined" || name == "":
  692. r.raise(errors.New("username is undefined"))
  693. return otto.FalseValue()
  694. case pass == "undefined":
  695. r.raise(errors.New("password is undefined"))
  696. return otto.FalseValue()
  697. case group == "undefined":
  698. r.raise(errors.New("defaultGroup is undefined"))
  699. return otto.FalseValue()
  700. case group != "administrator" && group != "user":
  701. r.raise(errors.New(group + " user-group not exists"))
  702. return otto.FalseValue()
  703. }
  704. r.mu.Lock()
  705. defer r.mu.Unlock()
  706. if containsString(r.state.Users, name) {
  707. r.raise(errors.New("Username already exists"))
  708. return otto.FalseValue()
  709. }
  710. r.state.Users = append(r.state.Users, name)
  711. return otto.TrueValue()
  712. })
  713. vm.Set("editUser", func(call otto.FunctionCall) otto.Value {
  714. adminOnly("editUser")
  715. return otto.FalseValue()
  716. })
  717. vm.Set("removeUser", func(call otto.FunctionCall) otto.Value {
  718. if !adminOnly("removeUser") {
  719. return otto.FalseValue()
  720. }
  721. name, err := call.Argument(0).ToString()
  722. if err != nil || name == "undefined" {
  723. r.raise(errors.New("username is undefined"))
  724. return otto.FalseValue()
  725. }
  726. r.mu.Lock()
  727. defer r.mu.Unlock()
  728. for i, n := range r.state.Users {
  729. if n == name {
  730. r.state.Users = append(r.state.Users[:i], r.state.Users[i+1:]...)
  731. return otto.TrueValue()
  732. }
  733. }
  734. r.raise(errors.New(name + " not exists"))
  735. return otto.FalseValue()
  736. })
  737. vm.Set("requirelib", func(call otto.FunctionCall) otto.Value {
  738. name, err := call.Argument(0).ToString()
  739. if err != nil {
  740. r.raise(err)
  741. return otto.NullValue()
  742. }
  743. if r.loadLib(vm, name, script) {
  744. return otto.TrueValue()
  745. }
  746. r.log("agi", "agi", "Lib not found: "+name)
  747. return otto.FalseValue()
  748. })
  749. vm.Set("execd", func(call otto.FunctionCall) otto.Value {
  750. name, err := call.Argument(0).ToString()
  751. if err != nil {
  752. r.raise(err)
  753. return otto.FalseValue()
  754. }
  755. payload, _ := call.Argument(1).ToString()
  756. target := Clean(path.Join(path.Dir(script), name))
  757. b, err := r.fs.ReadFile(target)
  758. if err != nil {
  759. r.raise(errors.New("[AGI] Target path not exists!"))
  760. return otto.FalseValue()
  761. }
  762. r.kids.Add(1)
  763. go func() {
  764. defer r.kids.Done()
  765. // The child keeps the parent's script path, as on a server.
  766. child := r.newVM(script, true, "execd:"+path.Base(target))
  767. child.Set("PARENT_DETACHED", true)
  768. child.Set("PARENT_PAYLOAD", payload)
  769. defer func() {
  770. if caught := recover(); caught != nil && caught != errExitcall && caught != errTimeout {
  771. r.log("execd:"+path.Base(target), "error", fmt.Sprint("VM crash: ", caught))
  772. }
  773. }()
  774. if _, err := child.Run(string(b)); err != nil {
  775. r.log("agi", "agi", "Script Execution Failed: "+err.Error())
  776. r.raise(err)
  777. }
  778. }()
  779. return otto.TrueValue()
  780. })
  781. }
  782. // injectRequest sets what the HTTP request carries: POST fields as globals
  783. // for a WebApp script, getPara/postPara/readBody for a serverless one.
  784. func (r *run) injectRequest(vm *otto.Otto) {
  785. q := r.req
  786. if r.mode() == "webapp" {
  787. if strings.Contains(q.ContentType, "application/json") {
  788. fields := map[string]interface{}{}
  789. json.Unmarshal([]byte(q.Body), &fields)
  790. for k, v := range fields {
  791. vm.Set(k, v)
  792. }
  793. vm.Set("POST_data", q.Body)
  794. } else if q.Method == "POST" || q.Method == "PUT" || q.Method == "PATCH" {
  795. keys := make([]string, 0, len(q.Form))
  796. for k := range q.Form {
  797. keys = append(keys, k)
  798. }
  799. sort.Strings(keys)
  800. for _, k := range keys {
  801. vm.Set(k, q.Form[k])
  802. }
  803. }
  804. return
  805. }
  806. vm.Set("REQ_METHOD", q.Method)
  807. vm.Set("getPara", func(call otto.FunctionCall) otto.Value {
  808. k, _ := call.Argument(0).ToString()
  809. if v, ok := q.Query[k]; ok && k != "" {
  810. out, _ := vm.ToValue(v)
  811. return out
  812. }
  813. return otto.NullValue()
  814. })
  815. vm.Set("postPara", func(call otto.FunctionCall) otto.Value {
  816. k, _ := call.Argument(0).ToString()
  817. if v, ok := q.Form[k]; ok && k != "" {
  818. out, _ := vm.ToValue(v)
  819. return out
  820. }
  821. return otto.NullValue()
  822. })
  823. vm.Set("readBody", func(call otto.FunctionCall) otto.Value {
  824. body := q.Body
  825. if body == "" && len(q.Form) > 0 {
  826. body = encodeForm(q.Form)
  827. }
  828. out, _ := vm.ToValue(body)
  829. return out
  830. })
  831. }
  832. func boolValue(b bool) otto.Value {
  833. if b {
  834. return otto.TrueValue()
  835. }
  836. return otto.FalseValue()
  837. }
  838. func containsString(list []string, s string) bool {
  839. for _, v := range list {
  840. if v == s {
  841. return true
  842. }
  843. }
  844. return false
  845. }