From 1805fcbd138c606241af2f6482aa575affa9f146 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 12 Oct 2026 14:52:12 +0000 Subject: [PATCH] Add JavaScript scripting: the sysop's own screens, on every terminal A script (scripts_dir/NAME.js, run by a menu's script:NAME, and logon.js after each login) draws the BBS's shared screens through ui (menus, tables, forms, panels, messages, the editor, confirmations), so one script works on text, RIP and 3270 terminals. It acts as its caller, with their access: msg (areas, messages, posting, mail), node (who's online, node messages, its activity), user, bbs; and keeps JSON values in data, for everyone or (data.user) for the caller, in the database (script_data). goja runs it in strict mode, with no files, network or processes. A watchdog stops a script that computes more than two seconds between screens (the caller's time at a screen is not counted); the caller hanging up ends a script whatever it catches; failures are logged and told (to a sysop, with why). Scripts are compiled once, again when changed; bbs check refuses scripts that do not compile and menus naming missing ones. goja is pinned to its June 2026 commit (the last that builds with Go 1.24; it is changing quickly now). scripts.sample has one-liners and a poll; both are tested, the one-liners on a text terminal and on a 3270 (s3270). That test found 3270 forms broken since the shared screens: the input field began under its label's last character, whose attribute byte erased it. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AFQhReUqUc7F5srk2hViqr --- bbs.conf.sample | 3 + cmd/bbs/main.go | 6 +- docs/wiki/Configuration.md | 1 + docs/wiki/Customization.md | 1 + docs/wiki/Development.md | 7 +- docs/wiki/Home.md | 1 + docs/wiki/Scripting.md | 87 +++++ docs/wiki/_Sidebar.md | 1 + go.mod | 4 + go.sum | 6 + internal/app/app.go | 20 ++ internal/bbs/bbs.go | 2 + internal/bbs/custom.go | 4 +- internal/script/api.go | 562 ++++++++++++++++++++++++++++++++ internal/script/engine.go | 125 +++++++ internal/script/run.go | 142 ++++++++ internal/script/script_test.go | 347 ++++++++++++++++++++ internal/server/config.go | 1 + internal/server/customconfig.go | 24 +- internal/server/script_test.go | 111 +++++++ internal/store/copy.go | 2 +- internal/store/scan.go | 7 + internal/store/schema.go | 7 + internal/store/scriptdata.go | 59 ++++ internal/store/store.go | 6 +- internal/store/store_test.go | 36 ++ internal/ui3270/view.go | 2 +- scripts.sample/README | 8 + scripts.sample/oneliners.js | 33 ++ scripts.sample/poll.js | 58 ++++ 30 files changed, 1665 insertions(+), 8 deletions(-) create mode 100644 docs/wiki/Scripting.md create mode 100644 internal/script/api.go create mode 100644 internal/script/engine.go create mode 100644 internal/script/run.go create mode 100644 internal/script/script_test.go create mode 100644 internal/server/script_test.go create mode 100644 internal/store/scriptdata.go create mode 100644 scripts.sample/README create mode 100644 scripts.sample/oneliners.js create mode 100644 scripts.sample/poll.js diff --git a/bbs.conf.sample b/bbs.conf.sample index 4b20412..797f6da 100644 --- a/bbs.conf.sample +++ b/bbs.conf.sample @@ -31,6 +31,9 @@ log = syslog ; those menus name; NAME.ans (ANSI, CP437), NAME.asc (text), NAME.3270. ; screens.sample has some to start from ;screens_dir = /etc/bbs/screens +; the sysop's JavaScript: NAME.js runs from a menu's script:NAME, logon.js +; after each login; scripts.sample has some to start from +;scripts_dir = /etc/bbs/scripts ; a caller pages the sysop and no sysop is on: tell them this way ({user}, ; {node} and {reason} filled in; no shell). E.g. a push by ntfy.sh: ;page_command = curl -s -d "{user} on node {node}: {reason}" https://ntfy.sh/my-bbs-pages diff --git a/cmd/bbs/main.go b/cmd/bbs/main.go index a897465..e68bd42 100644 --- a/cmd/bbs/main.go +++ b/cmd/bbs/main.go @@ -53,6 +53,7 @@ import ( "github.com/Neo-Desktop/bbs-sec/internal/gopher" "github.com/Neo-Desktop/bbs-sec/internal/news" "github.com/Neo-Desktop/bbs-sec/internal/nntp" + "github.com/Neo-Desktop/bbs-sec/internal/script" "github.com/Neo-Desktop/bbs-sec/internal/server" "github.com/Neo-Desktop/bbs-sec/internal/store" ) @@ -164,6 +165,9 @@ func main() { if cfg.Screens != nil { fmt.Println("screens:", cfg.Screens.Dir) } + if cfg.ScriptsDir != "" { + fmt.Printf("scripts: %s (%s)\n", cfg.ScriptsDir, strings.Join(script.For(cfg.ScriptsDir).Names(), ", ")) + } for _, m := range cfg.Menus { keys := "" for _, it := range m.Items { @@ -278,7 +282,7 @@ func serve(cfg *server.Config) int { b := bbs.New(cfg.Settings, st, lg) b.News = cfg.News b.Doors = cfg.Doors - b.Screens, b.Menus, b.Text = cfg.Screens, cfg.Menus, cfg.Text + b.Screens, b.Menus, b.Text, b.ScriptsDir = cfg.Screens, cfg.Menus, cfg.Text, cfg.ScriptsDir if b.Files, err = files.Open(st, cfg.FilesDir, cfg.MaxFileSize, cfg.UploadQuota); err != nil { lg.Printf("files: %v", err) return 1 diff --git a/docs/wiki/Configuration.md b/docs/wiki/Configuration.md index 39eae3b..a921c62 100644 --- a/docs/wiki/Configuration.md +++ b/docs/wiki/Configuration.md @@ -27,6 +27,7 @@ whether terminals are asked what they are: [Terminal identification](Terminal-Id | `[fido]`, `[binkp]`, `[link NAME]` | FidoNet: our address, the binkp mailer, links | [FidoNet](FidoNet) | | `[door NAME]` | a door program | [Doors](Doors) | | `screens_dir` (in `[general]`), `[menu NAME]`, `[strings]` | the sysop's screens, menus and prompts | [Customization](Customization) | +| `scripts_dir` (in `[general]`) | the sysop's JavaScript | [Scripting](Scripting) | | `[finger]`, `[gopher]` | the finger and gopher servers | [Finger and gopher](Finger-and-Gopher) | | `database` (in `[general]`) | SQLite's file, or a PostgreSQL, MySQL or MariaDB server | [Databases](Databases) | | `[level N]`, `new_user_level`, `validated_level` (in `[general]`) | access levels | [Access levels](Access-Levels) | diff --git a/docs/wiki/Customization.md b/docs/wiki/Customization.md index 6720dcb..672255b 100644 --- a/docs/wiki/Customization.md +++ b/docs/wiki/Customization.md @@ -120,6 +120,7 @@ begin comments), then what it does: | `menu:NAME` | another menu | | `screen:NAME` | show a screen | | `area:NAME` | straight into a message area | +| `script:NAME` | run a script of `scripts_dir` ([Scripting](Scripting)) | With `screen =`, a text terminal sees the screen (which shows the keys itself), and a 3270 the screen's `.3270` (or `.asc`, `.txt`) version if diff --git a/docs/wiki/Development.md b/docs/wiki/Development.md index 77dc939..027fc50 100644 --- a/docs/wiki/Development.md +++ b/docs/wiki/Development.md @@ -6,6 +6,7 @@ | `internal/server` | listeners, session headers, rlogin, SSH, telling 3270s from the rest | | `internal/telnet` | the server side of telnet: options, terminal type, window size, the handoff to go3270 | | `internal/view` | what the screens show, described once: menus, tables, messages, forms, panels, drafts | +| `internal/script` | the sysop's JavaScript (goja): screens of internal/view, the BBS as the caller, data kept, the time a script may compute | | `internal/app` | the screens after the login, for every front end: menus, areas, mail, files, who's online, the profile, validation, paging the sysop | | `internal/textui` | the text front end: the login, line editing, ANSI detection, paging, RIP menus; the screens as prompts and keys; chat, doors, transfers | | `internal/ui3270` | the 3270 front end: the logon, the screens as fields and PF keys on go3270; chat, IND$FILE, its graphics | @@ -132,7 +133,11 @@ The full-screen editor: its text (wrapping as typed and as given, a word too long for a line, joining lines by Backspace and Delete, moving over line ends, quoting, the line limit), and an SSH caller writing a post with the cursor keys, replying with lines from the quote window and -`/S`, then choosing the line editor; the file base (FILE_ID.DIZ in CP437 +`/S`, then choosing the line editor; scripts (screens, data kept for all +and for a user, posting with refusals caught, a runaway loop stopped and a +slow caller not, failures told to the sysop alone, a hang-up the script +cannot catch, exit, the sample poll, the configuration's checks, and the +sample one-liners on a text terminal and on a 3270 by s3270); the file base (FILE_ID.DIZ in CP437 with colors, a ZIP's and a tar.gz's listings, new files, finding by the DIZ's words, tagging by numbers, a batch of two by YMODEM, ratios and the day's limit together, the API's search and listings); the new scan's areas, messages to diff --git a/docs/wiki/Home.md b/docs/wiki/Home.md index 8d3408d..650bf7a 100644 --- a/docs/wiki/Home.md +++ b/docs/wiki/Home.md @@ -93,6 +93,7 @@ What there is: | [Configuration](Configuration) | `bbs.conf`: its sections, listeners | | [Access levels](Access-Levels) | levels, flags, what areas, doors and menus require, daily limits, validation | | [Customization](Customization) | screens (ANSI art, 3270), menus, prompts | +| [Scripting](Scripting) | the sysop's own screens in JavaScript, on every terminal | | [SSH](SSH) | the SSH listener, keys, host keys | | [Modem callers](Modem-Callers) | app_dmodem and modemmenu | | [TN3270](TN3270) | 3270 terminals, PF keys, 3270 graphics | diff --git a/docs/wiki/Scripting.md b/docs/wiki/Scripting.md new file mode 100644 index 0000000..c072255 --- /dev/null +++ b/docs/wiki/Scripting.md @@ -0,0 +1,87 @@ +The sysop's own screens and features, in JavaScript. A script draws the +same screens as the rest of the BBS (menus, tables, forms, panels, +messages, the editor), so it works on every terminal: a text terminal in +ANSI, ASCII or PETSCII, a RIP terminal (whose menus are buttons), and a +3270. It acts as its caller, with their access. + +``` +; bbs.conf +[general] +scripts_dir = /etc/bbs/scripts + +[menu main] +o = script:oneliners One-liners +p = script:poll Today's poll +``` + +`NAME.js` in `scripts_dir` is the script `script:NAME` runs (names are +lower case letters, digits, `_` and `-`). A `logon.js` there runs after +every login, before the menus. `bbs check` compiles every script and +refuses a configuration whose scripts do not compile or whose menus name +a script that is not there; a script changed while the BBS runs is +compiled again at its next run. `scripts.sample` has two to start from: +one-liners and a poll. + +## What a script is + +[goja](https://github.com/dop251/goja)'s JavaScript: ECMAScript 5.1 and +much of 6 (`let`, arrow functions, classes, `Map`, template strings), in +strict mode. A script has no files, network, processes or timers: only +the objects below. It may compute for two seconds between one screen and +the next (the caller's time at a screen is not counted); past that it is +stopped and the caller told. A script that fails is logged and the +caller told (a sysop is told why); the caller hanging up or going idle +ends it, whatever it catches. `exit()` ends it early. + +```js +// a guestbook in eight lines +var lines = data.get("lines") || []; +var k = ui.menu({title: "Guestbook", intro: lines.slice(-10), + items: [{key: "s", label: "Sign it"}, {key: "q", label: "Quit"}]}); +if (k === "S") { + var v = ui.form({title: "Sign", fields: [{name: "line", label: "Your words", width: 60}]}); + if (v && v.line) data.set("lines", lines.concat(user.name + ": " + v.line).slice(-100)); +} +``` + +## ui: the screens + +| | returns | | +|---|---|---| +| `ui.menu({title, intro, items: [{key, label}], prompt, screen})` | the key chosen (upper case), `""`, or `ui.BACK` (a 3270's PF3) | `intro`: lines before the items; `screen`: a display file in their place | +| `ui.table({title, note, columns: [{title, width, right, wide}], rows, empty, pick, prompt, actions, more, less})` | `{action, row, num, text}` | `rows`: arrays of cells, or `{num, cells, mark, hot}`; `pick` makes rows choosable (`action` is `ui.PICK`, `row` the index, -1 for a number not shown, `num` what was typed); `wide` columns only on screens of 60 columns or more; `more`/`less` say there are pages after and before (`ui.MORE`, `ui.LESS`) | +| `ui.message({where, from, to, subject, date, body, actions, default, quit})` | the action chosen | | +| `ui.form({title, intro, fields: [{name, label, prompt, width, secret, value}], submit})` | the values by name, or `null` if the caller gave up | one question a field on a text terminal, one screen on a 3270 | +| `ui.panel({title, lines, actions})` | the action chosen, `ui.BACK`, or `""` | | +| `ui.edit({title, to, subject, body, quote})` | `{to, subject, body}`, or `null` | the full-screen editor, the line editor or the 3270's; `quote` is for the quote window | +| `ui.confirm(question, default)` | true or false | | +| `ui.say(text, tone)` | | a line now (a 3270: on the next screen's message line) | +| `ui.show(title, lines)` | | lines until read | +| `ui.screen(name)` | whether there was one | a display file of `screens_dir` | +| `ui.kind`, `ui.pageSize`, `ui.narrow` | | `"text"` or `"3270"`; rows a table shows; under 60 columns | + +Lines are strings (`\n` makes more) or `{label, text, tone, bar}`: a +label and its value, a tone (`plain`, `dim`, `bright`, `good`, `bad`, +`warn`), a bar from 0 to 1. Actions are `{id, label, key, pf, short}`: a +text terminal's key, a 3270's PF key (an action without one is not on a +3270), `short` for the 3270's key line. On a text terminal `Q` (and Enter +on an empty prompt) goes back; on a 3270, PF3. + +## The BBS + +| | | +|---|---| +| `bbs.name`, `bbs.sysop`, `bbs.location`, `bbs.log(text)` | the system; a line in its log | +| `user.id`, `.name`, `.location`, `.level`, `.flags`, `.sysop`, `.calls`, `.posts`, `.since`, `.lastCall`, `user.has(require)` | the caller; `has` takes an [access requirement](Access-Levels) such as `"20 A"` (level 20 or more, and flag A) | +| `node.number`, `node.doing(text)`, `node.who()`, `node.message(n, text)` | the caller's node: what *Who's online* says they are doing; the nodes; a line to a node | +| `msg.areas()`, `msg.list(area, after, limit)`, `msg.get(id)` | the message areas the caller reads, their messages (up to 200 at a time, from after an id), one message (`null` if not theirs to read) | +| `msg.post(area, {to, subject, body, replyTo})`, `msg.mail({to, subject, body})` | post (the message's id) and mail, as the caller: refusals are thrown | +| `data.get(name)`, `data.set(name, value)`, `data.remove(name)`, `data.keys(prefix)` | what the script keeps for everyone: any JSON value up to 64 KB under a name of up to 100 characters, 1000 names | +| `data.user.get` ... | the same, for the caller alone (100 names) | +| `console.log(...)` | the BBS's log | + +What a script keeps is in the database (`script_data`), by the script's +name: a renamed script starts afresh. A user's data goes with their +account. + +**See also:** [Customization](Customization), [Development](Development#screens) diff --git a/docs/wiki/_Sidebar.md b/docs/wiki/_Sidebar.md index 6b28052..b0db750 100644 --- a/docs/wiki/_Sidebar.md +++ b/docs/wiki/_Sidebar.md @@ -7,6 +7,7 @@ - [Configuration](Configuration) - [Databases](Databases) - [Customization](Customization) +- [Scripting](Scripting) - [Access levels](Access-Levels) **Callers** diff --git a/go.mod b/go.mod index 2eb6c6e..49fa61c 100644 --- a/go.mod +++ b/go.mod @@ -23,7 +23,11 @@ require ( require ( filippo.io/edwards25519 v1.1.0 // indirect + github.com/dlclark/regexp2 v1.11.4 // indirect + github.com/dop251/goja v0.0.0-20260603125802-cfe4039cb6d7 // indirect github.com/dustin/go-humanize v1.0.1 // indirect + github.com/go-sourcemap/sourcemap v2.1.3+incompatible // indirect + github.com/google/pprof v0.0.0-20240409012703-83162a5b38cd // indirect github.com/google/uuid v1.6.0 // indirect github.com/hashicorp/errwrap v1.0.0 // indirect github.com/hashicorp/go-multierror v1.1.1 // indirect diff --git a/go.sum b/go.sum index 1fb99ac..53df093 100644 --- a/go.sum +++ b/go.sum @@ -7,10 +7,16 @@ github.com/coder/websocket v1.8.13/go.mod h1:LNVeNrXQZfe5qhS9ALED3uA+l5pPqvwXg3C github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/dlclark/regexp2 v1.11.4 h1:rPYF9/LECdNymJufQKmri9gV604RvvABwgOA8un7yAo= +github.com/dlclark/regexp2 v1.11.4/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8= +github.com/dop251/goja v0.0.0-20260603125802-cfe4039cb6d7 h1:g7JYcX9Y5RNJhrqpC/N/vHtp9BuFU1MVc4BO64scbKo= +github.com/dop251/goja v0.0.0-20260603125802-cfe4039cb6d7/go.mod h1:MxLav0peU43GgvwVgNbLAj1s/bSGboKkhuULvq/7hx4= github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY= github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto= github.com/fclairamb/ftpserverlib v0.30.0 h1:caB9sDn1Au//q0j2ev/icPn388qPuk4k1ajSvglDcMQ= github.com/fclairamb/ftpserverlib v0.30.0/go.mod h1:QmogtltTOgkihyKza0GNo37Mu4AEzbJ+sH6W9Y0MBIQ= +github.com/go-sourcemap/sourcemap v2.1.3+incompatible h1:W1iEw64niKVGogNgBN3ePyLFfuisuzeidWPMPWmECqU= +github.com/go-sourcemap/sourcemap v2.1.3+incompatible/go.mod h1:F8jJfvm2KbVjc5NqelyYJmf/v5J0dwNLS2mL4sNA1Jg= github.com/go-sql-driver/mysql v1.8.1 h1:LedoTUt/eveggdHS9qUFC1EFSa8bU2+1pZjSRpvNJ1Y= github.com/go-sql-driver/mysql v1.8.1/go.mod h1:wEBSXgmK//2ZFJyE+qWnIsVGmvmEKlqwuVSjsCm7DZg= github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU= diff --git a/internal/app/app.go b/internal/app/app.go index 68f4d84..0491c10 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -15,6 +15,7 @@ import ( "github.com/Neo-Desktop/bbs-sec/internal/bbs" "github.com/Neo-Desktop/bbs-sec/internal/door" "github.com/Neo-Desktop/bbs-sec/internal/screens" + "github.com/Neo-Desktop/bbs-sec/internal/script" "github.com/Neo-Desktop/bbs-sec/internal/store" "github.com/Neo-Desktop/bbs-sec/internal/view" ) @@ -93,6 +94,12 @@ func Run(b *bbs.BBS, n *bbs.Node, ui Frontend) error { return err } intro := s.welcome(shown) + // the sysop's logon script, before the menus + if b.ScriptsDir != "" && script.For(b.ScriptsDir).Has("logon") { + if err := s.runScript("logon"); err != nil { + return err + } + } if m := b.Menus["main"]; m != nil { return s.runMenu(m, 0, intro) } @@ -347,6 +354,8 @@ func (s *Session) do(it *bbs.MenuItem, depth int) error { s.UI.Say(view.Plain, "There is nothing to show.") } return err + case "script": + return s.runScript(it.Arg) case "area": a, err := s.B.Store.AreaByName(it.Arg) if err != nil || !s.B.CanRead(s.User, a) { @@ -358,6 +367,17 @@ func (s *Session) do(it *bbs.MenuItem, depth int) error { return nil } +// runScript runs a script of the sysop's for the caller. +func (s *Session) runScript(name string) error { + if s.B.ScriptsDir == "" { + s.UI.Say(view.Bad, "There are no scripts.") + return nil + } + err := script.For(s.B.ScriptsDir).Run(name, s.B, s.N, s.UI) + s.refresh() + return err +} + // doors: the list of doors, and into one func (s *Session) doors() error { if s.UI.Kind() == TN3270 { diff --git a/internal/bbs/bbs.go b/internal/bbs/bbs.go index c2d02eb..ea2a83f 100644 --- a/internal/bbs/bbs.go +++ b/internal/bbs/bbs.go @@ -122,6 +122,8 @@ type BBS struct { Screens *screens.Set Menus map[string]*Menu Text map[string]string + // ScriptsDir has the sysop's JavaScript ("": no scripts) + ScriptsDir string // Stats count logins, posts and the like Stats Stats diff --git a/internal/bbs/custom.go b/internal/bbs/custom.go index 01e0f8a..f5d7675 100644 --- a/internal/bbs/custom.go +++ b/internal/bbs/custom.go @@ -163,9 +163,9 @@ func ParseMenuItem(key, value string) (MenuItem, error) { if a, arg, ok := strings.Cut(action, ":"); ok { switch a { case "door", "menu", "area": - case "screen": + case "screen", "script": if !screens.ValidName(arg) { - return MenuItem{}, fmt.Errorf("%s: a screen's name is lower case letters, digits, _ and -", action) + return MenuItem{}, fmt.Errorf("%s: a %s's name is lower case letters, digits, _ and -", action, a) } default: return MenuItem{}, fmt.Errorf("%s: no such action", action) diff --git a/internal/script/api.go b/internal/script/api.go new file mode 100644 index 0000000..cf0c86e --- /dev/null +++ b/internal/script/api.go @@ -0,0 +1,562 @@ +package script + +import ( + "bytes" + "encoding/json" + "fmt" + "strconv" + "strings" + "time" + "unicode/utf8" + + "github.com/dop251/goja" + + "github.com/Neo-Desktop/bbs-sec/internal/bbs" + "github.com/Neo-Desktop/bbs-sec/internal/store" + "github.com/Neo-Desktop/bbs-sec/internal/view" +) + +// Limits on what scripts keep. +const ( + maxKey = 100 // a name's characters + maxValue = 64 << 10 // a value's bytes, as JSON + maxGlobalKeys = 1000 // names a script keeps for everyone + maxUserKeys = 100 // and for each user + maxList = 200 // messages a list gives +) + +// bind sets up the script's world. +func (r *run) bind() error { + vm := r.vm + set := func(name string, v any) { + if err := vm.Set(name, v); err != nil { + panic(err) + } + } + set("ui", r.uiObject()) + set("bbs", r.bbsObject()) + set("user", r.userObject()) + set("node", r.nodeObject()) + set("msg", r.msgObject()) + data := r.dataObject(0) + if u := r.n.User(); u != nil { + data.Set("user", r.dataObject(u.ID)) + } + set("data", data) + set("exit", func() { vm.Interrupt(errExit) }) + console := vm.NewObject() + console.Set("log", func(c goja.FunctionCall) goja.Value { + var parts []string + for _, a := range c.Arguments { + parts = append(parts, a.String()) + } + r.b.Log.Printf("node %d: script %s: %s", r.n.Num, r.name, bbs.Clean(strings.Join(parts, " "), 400)) + return goja.Undefined() + }) + set("console", console) + return nil +} + +// --- reading what a script gives + +// obj is a script's object as a map (nil if it is not one). +func obj(v goja.Value) map[string]any { + if v == nil || goja.IsUndefined(v) || goja.IsNull(v) { + return nil + } + m, _ := v.Export().(map[string]any) + return m +} + +func str(m map[string]any, k string) string { + switch v := m[k].(type) { + case nil: + return "" + case string: + return v + case time.Time: + return v.Format(time.RFC3339) + default: + return fmt.Sprint(v) + } +} + +func num(m map[string]any, k string) int { + switch v := m[k].(type) { + case int64: + return int(v) + case float64: + return int(v) + case string: + n, _ := strconv.Atoi(v) + return n + } + return 0 +} + +func flag(m map[string]any, k string) bool { + v, _ := m[k].(bool) + return v +} + +func list(v any) []any { + l, _ := v.([]any) + return l +} + +// key is an action's key: its first character. +func key(s string) rune { + r, _ := utf8.DecodeRuneInString(s) + return r +} + +var toneNames = map[string]view.Tone{"": view.Plain, "plain": view.Plain, "dim": view.Dim, + "bright": view.Bright, "good": view.Good, "bad": view.Bad, "warn": view.Warn} + +func tone(s string) view.Tone { return toneNames[strings.ToLower(s)] } + +// lines are a script's lines: strings, or {label, text, tone, bar}. +func lines(v any) []view.Line { + var out []view.Line + for _, l := range list(v) { + switch l := l.(type) { + case string: + for _, s := range strings.Split(l, "\n") { + out = append(out, view.L(bbs.Clean(s, 400))) + } + case map[string]any: + line := view.Line{Label: bbs.Clean(str(l, "label"), 40), Text: bbs.Clean(str(l, "text"), 400), + Tone: tone(str(l, "tone")), Bar: -1} + if b, ok := l["bar"].(float64); ok { + line.Bar = min(max(b, 0), 1) + } else if b, ok := l["bar"].(int64); ok { + line.Bar = min(max(float64(b), 0), 1) + } + out = append(out, line) + } + } + return out +} + +func actions(v any) []view.Action { + var out []view.Action + for _, a := range list(v) { + m, _ := a.(map[string]any) + if m == nil { + continue + } + pf := num(m, "pf") + if pf < 0 || pf > 24 { + pf = 0 + } + out = append(out, view.Action{ID: str(m, "id"), Label: bbs.Clean(str(m, "label"), 40), + Key: key(strings.ToUpper(str(m, "key"))), PF: pf, Short: bbs.Clean(str(m, "short"), 20)}) + } + return out +} + +func clean(s string) string { return bbs.Clean(s, 200) } + +// prompt is a prompt cleaned, keeping the space it ends in. +func prompt(s string) string { + if c := clean(s); c != "" && strings.HasSuffix(s, " ") { + return c + " " + } + return clean(s) +} + +// --- ui + +func (r *run) uiObject() *goja.Object { + vm := r.vm + o := vm.NewObject() + o.Set("kind", r.ui.Kind()) + o.Set("pageSize", r.ui.PageSize()) + o.Set("narrow", r.ui.Narrow()) + for k, v := range map[string]string{"BACK": view.Back, "PICK": view.Pick, "MORE": view.More, + "LESS": view.Less, "CMD": view.Cmd} { + o.Set(k, v) + } + + o.Set("menu", func(c goja.FunctionCall) goja.Value { + m := obj(c.Argument(0)) + vmenu := &view.Menu{Title: clean(str(m, "title")), Intro: lines(m["intro"]), Prompt: prompt(str(m, "prompt")), + Screen: str(m, "screen")} + for _, it := range list(m["items"]) { + im, _ := it.(map[string]any) + if k := strings.ToUpper(str(im, "key")); k != "" { + vmenu.Items = append(vmenu.Items, view.Item{Key: string(key(k)), Label: clean(str(im, "label"))}) + } + } + if len(vmenu.Items) == 0 { + r.throw("ui.menu: no items") + } + var k string + r.wait(func() (err error) { k, err = r.ui.Menu(vmenu); return }) + return vm.ToValue(k) + }) + + o.Set("table", func(c goja.FunctionCall) goja.Value { + m := obj(c.Argument(0)) + t := &view.Table{Title: clean(str(m, "title")), Note: lines(m["note"]), Empty: clean(str(m, "empty")), + Pick: clean(str(m, "pick")), Prompt: prompt(str(m, "prompt")), Actions: actions(m["actions"]), + More: flag(m, "more"), Less: flag(m, "less"), Command: clean(str(m, "command"))} + for _, col := range list(m["columns"]) { + cm, _ := col.(map[string]any) + t.Columns = append(t.Columns, view.Column{Title: clean(str(cm, "title")), + Width: min(max(num(cm, "width"), 0), 200), Right: flag(cm, "right"), Wide: flag(cm, "wide")}) + } + for i, row := range list(m["rows"]) { + var vr view.Row + switch row := row.(type) { + case []any: // the cells alone + for _, cell := range row { + vr.Cells = append(vr.Cells, clean(fmt.Sprint(cell))) + } + case map[string]any: + vr = view.Row{Num: clean(str(row, "num")), Mark: flag(row, "mark"), Hot: flag(row, "hot")} + for _, cell := range list(row["cells"]) { + vr.Cells = append(vr.Cells, clean(fmt.Sprint(cell))) + } + } + if vr.Num == "" && t.Pick != "" { + vr.Num = strconv.Itoa(i + 1) + } + t.Rows = append(t.Rows, vr) + } + var ch view.Choice + r.wait(func() (err error) { ch, err = r.ui.Table(t); return }) + res := vm.NewObject() + res.Set("action", ch.Action) + res.Set("row", ch.Row) + res.Set("num", ch.Num) + res.Set("text", ch.Text) + return res + }) + + o.Set("message", func(c goja.FunctionCall) goja.Value { + m := obj(c.Argument(0)) + vmsg := &view.Message{Where: clean(str(m, "where")), From: clean(str(m, "from")), To: clean(str(m, "to")), + Subject: clean(str(m, "subject")), Body: bbs.CleanBody(strings.Split(str(m, "body"), "\n")), + Actions: actions(m["actions"]), Default: str(m, "default"), Quit: str(m, "quit")} + if d, ok := m["date"].(time.Time); ok { + vmsg.Date = d + } else if d, err := time.Parse(time.RFC3339, str(m, "date")); err == nil { + vmsg.Date = d + } else { + vmsg.Date = time.Now() + } + var act string + r.wait(func() (err error) { act, err = r.ui.Message(vmsg); return }) + return vm.ToValue(act) + }) + + o.Set("form", func(c goja.FunctionCall) goja.Value { + m := obj(c.Argument(0)) + f := &view.Form{Title: clean(str(m, "title")), Intro: lines(m["intro"]), Submit: clean(str(m, "submit"))} + for _, fd := range list(m["fields"]) { + fm, _ := fd.(map[string]any) + name := str(fm, "name") + if name == "" { + r.throw("ui.form: a field without a name") + } + w := num(fm, "width") + if w <= 0 || w > 2048 { + w = 40 + } + label := clean(str(fm, "label")) + if label == "" { + label = name + } + f.Fields = append(f.Fields, view.Field{Name: name, Label: label, Prompt: prompt(str(fm, "prompt")), + Width: w, Secret: flag(fm, "secret"), Value: clean(str(fm, "value"))}) + } + if len(f.Fields) == 0 { + r.throw("ui.form: no fields") + } + var vals map[string]string + var ok bool + r.wait(func() (err error) { vals, ok, err = r.ui.Form(f); return }) + if !ok { + return goja.Null() + } + res := vm.NewObject() + for _, fd := range f.Fields { + res.Set(fd.Name, bbs.Clean(vals[fd.Name], fd.Width)) + } + return res + }) + + o.Set("panel", func(c goja.FunctionCall) goja.Value { + m := obj(c.Argument(0)) + p := &view.Panel{Title: clean(str(m, "title")), Lines: lines(m["lines"]), Actions: actions(m["actions"])} + var act string + r.wait(func() (err error) { act, err = r.ui.Panel(p); return }) + return vm.ToValue(act) + }) + + o.Set("edit", func(c goja.FunctionCall) goja.Value { + m := obj(c.Argument(0)) + var to, subject string + var body []string + d := &view.Draft{Title: clean(str(m, "title")), To: clean(str(m, "to")), Subject: clean(str(m, "subject")), + Send: func(t, s string, b []string) error { to, subject, body = t, s, b; return nil }} + if b := str(m, "body"); b != "" { + d.Body = strings.Split(b, "\n") + } + if q := str(m, "quote"); q != "" { + d.Quote = strings.Split(q, "\n") + } + if d.Title == "" { + d.Title = "Write" + } + var sent bool + r.wait(func() (err error) { sent, err = r.ui.Edit(d); return }) + if !sent { + return goja.Null() + } + res := vm.NewObject() + res.Set("to", bbs.Clean(to, bbs.MaxMailToLen)) + res.Set("subject", bbs.Clean(subject, bbs.MaxSubjectLen)) + res.Set("body", bbs.CleanBody(body)) + return res + }) + + o.Set("confirm", func(question string, def bool) bool { + var ok bool + r.wait(func() (err error) { ok, err = r.ui.Confirm(clean(question), def); return }) + return ok + }) + o.Set("say", func(text, tn string) { + r.ui.Say(tone(tn), bbs.Clean(text, 400)) + }) + o.Set("show", func(c goja.FunctionCall) goja.Value { + title := clean(c.Argument(0).String()) + ls := lines(c.Argument(1).Export()) + r.wait(func() error { return r.ui.Show(title, ls) }) + return goja.Undefined() + }) + o.Set("screen", func(name string) bool { + var shown bool + r.wait(func() (err error) { shown, err = r.ui.ShowScreen(name, true); return }) + return shown + }) + return o +} + +// --- the BBS, the caller, their node + +func (r *run) bbsObject() *goja.Object { + o := r.vm.NewObject() + o.Set("name", r.b.Name) + o.Set("sysop", r.b.Sysop) + o.Set("location", r.b.Location) + o.Set("log", func(text string) { + r.b.Log.Printf("node %d: script %s: %s", r.n.Num, r.name, bbs.Clean(text, 400)) + }) + return o +} + +func (r *run) userObject() *goja.Object { + o := r.vm.NewObject() + u := r.n.Refresh() + if u == nil { + return o + } + o.Set("id", u.ID) + o.Set("name", u.Name) + o.Set("location", u.Location) + o.Set("level", u.Level) + o.Set("flags", u.Flags) + o.Set("sysop", u.Sysop) + o.Set("calls", u.Logins) + o.Set("posts", u.Posts) + o.Set("since", u.Created.Format(time.RFC3339)) + if !u.LastLogin.IsZero() { + o.Set("lastCall", u.LastLogin.Format(time.RFC3339)) + } + o.Set("has", func(req string) bool { + rq, err := bbs.ParseRequire(req) + if err != nil { + r.throw("user.has: %v", err) + } + return rq.Allows(r.n.Refresh()) + }) + return o +} + +func (r *run) nodeObject() *goja.Object { + o := r.vm.NewObject() + o.Set("number", r.n.Num) + o.Set("doing", func(text string) { r.n.Doing(bbs.Clean(text, 60)) }) + o.Set("who", func() []map[string]any { + var out []map[string]any + for _, n := range r.b.Nodes() { + out = append(out, map[string]any{"node": n.Num, "user": n.User, "via": n.Via, + "minutes": int(time.Since(n.Since).Minutes()), "doing": n.Activity}) + } + return out + }) + o.Set("message", func(num int, text string) { + if err := r.n.Message(num, text); err != nil { + r.throw("%v", err) + } + }) + return o +} + +// --- messages and mail, with the caller's access + +func messageOut(m *store.Message) map[string]any { + return map[string]any{"id": m.ID, "area": m.AreaID, "from": m.From, "to": m.To, "subject": m.Subject, + "body": m.Body, "date": m.Created.Format(time.RFC3339), "replyTo": m.ReplyTo} +} + +func (r *run) area(id int64) *store.Area { + a, err := r.b.Store.Area(id) + if err != nil || !r.b.CanRead(r.n.User(), a) { + r.throw("there is no area %d", id) + } + return a +} + +// body is a script's body: a string, or lines. +func body(v any) []string { + switch v := v.(type) { + case string: + return strings.Split(v, "\n") + case []any: + var out []string + for _, l := range v { + out = append(out, fmt.Sprint(l)) + } + return out + } + return nil +} + +func (r *run) msgObject() *goja.Object { + o := r.vm.NewObject() + o.Set("areas", func() []map[string]any { + as, err := r.b.AreasFor(r.n.User()) + if err != nil { + r.throw("%v", err) + } + out := []map[string]any{} + for _, a := range as { + out = append(out, map[string]any{"id": a.ID, "name": a.Name, "description": a.Description, + "messages": a.Messages, "new": a.New, "canPost": r.b.CanPost(r.n.User(), a.Area)}) + } + return out + }) + o.Set("list", func(area int64, after int64, limit int) []map[string]any { + a := r.area(area) + if limit <= 0 || limit > maxList { + limit = 50 + } + ms, err := r.b.Store.Messages(a.ID, after, limit) + if err != nil { + r.throw("%v", err) + } + out := []map[string]any{} + for _, m := range ms { + out = append(out, messageOut(m)) + } + return out + }) + o.Set("get", func(id int64) goja.Value { + m, err := r.b.Store.Message(id) + if err != nil { + return goja.Null() + } + if a, err := r.b.Store.Area(m.AreaID); err != nil || !r.b.CanRead(r.n.User(), a) { + return goja.Null() + } + return r.vm.ToValue(messageOut(m)) + }) + o.Set("post", func(area int64, msg goja.Value) int64 { + a := r.area(area) + m := obj(msg) + id, err := r.n.Post(a, str(m, "to"), str(m, "subject"), body(m["body"]), int64(num(m, "replyTo"))) + if err != nil { + r.throw("%v", err) + } + return id + }) + o.Set("mail", func(msg goja.Value) { + m := obj(msg) + if err := r.n.SendMail(str(m, "to"), str(m, "subject"), body(m["body"]), 0); err != nil { + r.throw("%v", err) + } + }) + return o +} + +// --- data the script keeps: for everyone (user 0), or for a user + +func (r *run) checkKey(k string) { + if k == "" || utf8.RuneCountInString(k) > maxKey || !utf8.ValidString(k) { + r.throw("a name is 1 to %d characters", maxKey) + } +} + +func (r *run) dataObject(user int64) *goja.Object { + o := r.vm.NewObject() + most := maxGlobalKeys + if user != 0 { + most = maxUserKeys + } + o.Set("get", func(k string) goja.Value { + r.checkKey(k) + v, ok, err := r.b.Store.ScriptGet(r.name, user, k) + if err != nil { + r.throw("%v", err) + } + if !ok { + return goja.Undefined() + } + var x any + if json.Unmarshal([]byte(v), &x) != nil { + return goja.Undefined() + } + return r.vm.ToValue(x) + }) + o.Set("set", func(k string, v goja.Value) { + r.checkKey(k) + var buf bytes.Buffer + enc := json.NewEncoder(&buf) + enc.SetEscapeHTML(false) + if err := enc.Encode(v.Export()); err != nil { + r.throw("data.set: %v", err) + } + b := bytes.TrimSuffix(buf.Bytes(), []byte("\n")) + if len(b) > maxValue { + r.throw("data.set: the value is over %d bytes", maxValue) + } + if _, had, _ := r.b.Store.ScriptGet(r.name, user, k); !had { + if n, _ := r.b.Store.ScriptCount(r.name, user); n >= most { + r.throw("data.set: that is the %d names a script keeps", most) + } + } + if err := r.b.Store.ScriptSet(r.name, user, k, string(b)); err != nil { + r.throw("%v", err) + } + }) + o.Set("remove", func(k string) { + r.checkKey(k) + if err := r.b.Store.ScriptDelete(r.name, user, k); err != nil { + r.throw("%v", err) + } + }) + o.Set("keys", func(prefix string) []string { + ks, err := r.b.Store.ScriptNames(r.name, user, prefix, most) + if err != nil { + r.throw("%v", err) + } + if ks == nil { + ks = []string{} + } + return ks + }) + return o +} diff --git a/internal/script/engine.go b/internal/script/engine.go new file mode 100644 index 0000000..c60ec3b --- /dev/null +++ b/internal/script/engine.go @@ -0,0 +1,125 @@ +// Package script runs the sysop's JavaScript (ECMAScript 5.1 and much of +// 6, by goja) as part of the BBS: a script draws the shared screens of +// internal/view, so it works on every terminal the BBS has (text, RIP, +// 3270), and acts on the BBS as its caller, with their access. +// +// A script has no files, network or processes: only what the API here +// gives. It may compute for Limit between one screen and the next before +// it is stopped. +package script + +import ( + "errors" + "fmt" + "os" + "path/filepath" + "regexp" + "sort" + "strings" + "sync" + "time" + + "github.com/dop251/goja" +) + +// DefaultLimit is how long a script may compute between screens. +const DefaultLimit = 2 * time.Second + +// maxSource is the largest script read. +const maxSource = 1 << 20 + +var namePattern = regexp.MustCompile(`^[a-z0-9][a-z0-9_-]{0,31}$`) + +// ValidName: a script's name is 1 to 32 lower case letters, digits, _ and +// -, starting with a letter or digit; it is NAME.js in the directory. +func ValidName(name string) bool { return namePattern.MatchString(name) } + +// ErrNoScript: there is no script of that name. +var ErrNoScript = errors.New("there is no such script") + +// Engine runs the scripts of a directory, compiling each once (and again +// when it changes). +type Engine struct { + Dir string + Limit time.Duration + + mu sync.Mutex + cache map[string]compiled +} + +type compiled struct { + mod time.Time + size int64 + prog *goja.Program +} + +var engines sync.Map // dir: *Engine + +// For is the engine of a directory, shared by every session. +func For(dir string) *Engine { + e, _ := engines.LoadOrStore(dir, &Engine{Dir: dir, Limit: DefaultLimit, cache: map[string]compiled{}}) + return e.(*Engine) +} + +func (e *Engine) path(name string) string { return filepath.Join(e.Dir, name+".js") } + +// Has: the directory has the script. +func (e *Engine) Has(name string) bool { + if !ValidName(name) { + return false + } + fi, err := os.Stat(e.path(name)) + return err == nil && fi.Mode().IsRegular() +} + +// Names are the scripts in the directory. +func (e *Engine) Names() []string { + ms, _ := filepath.Glob(filepath.Join(e.Dir, "*.js")) + var out []string + for _, m := range ms { + if n := strings.TrimSuffix(filepath.Base(m), ".js"); ValidName(n) { + out = append(out, n) + } + } + sort.Strings(out) + return out +} + +// program is the script compiled. +func (e *Engine) program(name string) (*goja.Program, error) { + if !ValidName(name) { + return nil, ErrNoScript + } + p := e.path(name) + fi, err := os.Stat(p) + if err != nil || !fi.Mode().IsRegular() { + return nil, ErrNoScript + } + e.mu.Lock() + c, ok := e.cache[name] + e.mu.Unlock() + if ok && c.mod.Equal(fi.ModTime()) && c.size == fi.Size() { + return c.prog, nil + } + if fi.Size() > maxSource { + return nil, fmt.Errorf("%s.js is larger than %d bytes", name, maxSource) + } + src, err := os.ReadFile(p) + if err != nil { + return nil, err + } + prog, err := goja.Compile(name+".js", string(src), true) + if err != nil { + return nil, err + } + e.mu.Lock() + e.cache[name] = compiled{mod: fi.ModTime(), size: fi.Size(), prog: prog} + e.mu.Unlock() + return prog, nil +} + +// Check compiles a script, saying what is wrong with it. +func (e *Engine) Check(name string) error { + _, err := e.program(name) + return err +} diff --git a/internal/script/run.go b/internal/script/run.go new file mode 100644 index 0000000..ff573ed --- /dev/null +++ b/internal/script/run.go @@ -0,0 +1,142 @@ +package script + +import ( + "errors" + "fmt" + "strings" + "sync/atomic" + "time" + + "github.com/dop251/goja" + + "github.com/Neo-Desktop/bbs-sec/internal/bbs" + "github.com/Neo-Desktop/bbs-sec/internal/view" +) + +// UI is what a script draws on: the caller's front end. +type UI interface { + view.UI + Kind() string + ShowScreen(name string, wait bool) (bool, error) +} + +// How a run ends, other than by its end. +var ( + errExit = errors.New("exit") + errTooLong = errors.New("the script computed too long") +) + +// run is a script running for a caller. +type run struct { + name string + b *bbs.BBS + n *bbs.Node + ui UI + vm *goja.Runtime + + busy atomic.Int64 // when the script began computing (0: it waits on a screen) + fatal error // the caller went (the front end's error): the run ends with it +} + +// Run runs a script for the caller on node n. It returns the front end's +// errors (the caller hung up, idled): a script's own failure is logged and +// told to the caller, and is not an error of the session. +func (e *Engine) Run(name string, b *bbs.BBS, n *bbs.Node, ui UI) error { + prog, err := e.program(name) + if err != nil { + b.Log.Printf("node %d: script %s: %v", n.Num, name, err) + ui.Say(view.Bad, "The script "+name+" would not run.") + return nil + } + r := &run{name: name, b: b, n: n, ui: ui, vm: goja.New()} + r.vm.SetMaxCallStackSize(1000) + r.vm.SetFieldNameMapper(goja.TagFieldNameMapper("json", true)) + if err := r.bind(); err != nil { + return err + } + limit := e.Limit + if limit <= 0 { + limit = DefaultLimit + } + done := make(chan struct{}) + go r.watch(limit, done) + r.busy.Store(time.Now().UnixNano()) + _, err = r.vm.RunProgram(prog) + close(done) + return r.end(err) +} + +// watch stops the script when it has computed for limit without a screen. +func (r *run) watch(limit time.Duration, done chan struct{}) { + t := time.NewTicker(limit / 20) + defer t.Stop() + for { + select { + case <-done: + return + case now := <-t.C: + if since := r.busy.Load(); since != 0 && now.UnixNano()-since > int64(limit) { + r.vm.Interrupt(errTooLong) + return + } + } + } +} + +// wait is a screen: the time the caller takes is not the script's. +func (r *run) wait(f func() error) { + r.busy.Store(0) + err := f() + r.busy.Store(time.Now().UnixNano()) + if err != nil { + // the caller went: the script ends, whatever it catches + r.fatal = err + r.vm.Interrupt(err) + panic(r.vm.NewGoError(err)) + } +} + +// end is how the run ended, for the session. +func (r *run) end(err error) error { + if r.fatal != nil { + return r.fatal + } + if err == nil { + return nil + } + var ie *goja.InterruptedError + if errors.As(err, &ie) { + switch ie.Value() { + case errExit: + return nil + case errTooLong: + r.b.Log.Printf("node %d: script %s: stopped: computed longer than allowed between screens", r.n.Num, r.name) + r.ui.Say(view.Bad, "The script "+r.name+" took too long and was stopped.") + return nil + } + } + msg := err.Error() + var ex *goja.Exception + if errors.As(err, &ex) { + msg = ex.String() + } + msg = strings.TrimSpace(msg) + r.b.Log.Printf("node %d: script %s: %s", r.n.Num, r.name, msg) + if u := r.n.User(); u != nil && u.Sysop { + r.ui.Say(view.Bad, "The script "+r.name+" failed: "+firstLine(msg)) + } else { + r.ui.Say(view.Bad, "The script "+r.name+" failed.") + } + return nil +} + +func firstLine(s string) string { + s, _, _ = strings.Cut(s, "\n") + return s +} + +// throw is a JavaScript error, for a script's mistake (a bad argument, a +// refusal): it may catch it. +func (r *run) throw(format string, a ...any) { + panic(r.vm.NewGoError(fmt.Errorf(format, a...))) +} diff --git a/internal/script/script_test.go b/internal/script/script_test.go new file mode 100644 index 0000000..d281073 --- /dev/null +++ b/internal/script/script_test.go @@ -0,0 +1,347 @@ +package script + +import ( + "bytes" + "errors" + "io" + "log" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/Neo-Desktop/bbs-sec/internal/bbs" + "github.com/Neo-Desktop/bbs-sec/internal/store" + "github.com/Neo-Desktop/bbs-sec/internal/view" +) + +// fake is a front end answering from a script of answers. +type fake struct { + t *testing.T + answers []any + shown []string + said []string + delay time.Duration // each screen takes this long to answer + fail error // each screen fails so +} + +func (f *fake) next() any { + if f.delay > 0 { + time.Sleep(f.delay) + } + if len(f.answers) == 0 { + f.t.Fatalf("out of answers; shown %q", f.shown) + } + a := f.answers[0] + f.answers = f.answers[1:] + return a +} + +func (f *fake) PageSize() int { return 10 } +func (f *fake) Narrow() bool { return false } +func (f *fake) Kind() string { return "text" } +func (f *fake) Menu(m *view.Menu) (string, error) { + var ks []string + for _, it := range m.Items { + ks = append(ks, it.Key+"="+it.Label) + } + f.shown = append(f.shown, "menu "+m.Title+": "+strings.Join(ks, " ")) + if f.fail != nil { + return "", f.fail + } + return f.next().(string), nil +} +func (f *fake) Table(t *view.Table) (view.Choice, error) { + var rows []string + for _, r := range t.Rows { + rows = append(rows, r.Num+":"+strings.Join(r.Cells, "|")) + } + f.shown = append(f.shown, "table "+t.Title+": "+strings.Join(rows, "; ")) + return f.next().(view.Choice), nil +} +func (f *fake) Message(m *view.Message) (string, error) { + f.shown = append(f.shown, "message "+m.Subject+": "+m.Body) + return f.next().(string), nil +} +func (f *fake) Form(fm *view.Form) (map[string]string, bool, error) { + f.shown = append(f.shown, "form "+fm.Title) + v, _ := f.next().(map[string]string) + return v, v != nil, nil +} +func (f *fake) Panel(p *view.Panel) (string, error) { + var ls []string + for _, l := range p.Lines { + ls = append(ls, l.Label+l.Text) + } + f.shown = append(f.shown, "panel "+p.Title+": "+strings.Join(ls, "; ")) + return f.next().(string), nil +} +func (f *fake) Edit(d *view.Draft) (bool, error) { + f.shown = append(f.shown, "edit "+d.Title) + b, _ := f.next().([]string) + if b == nil { + return false, nil + } + return true, d.Send(d.To, d.Subject, b) +} +func (f *fake) Confirm(q string, def bool) (bool, error) { + f.shown = append(f.shown, "confirm "+q) + return f.next().(bool), nil +} +func (f *fake) Say(tn view.Tone, msg string) { f.said = append(f.said, msg) } +func (f *fake) Show(title string, ls []view.Line) error { + var out []string + for _, l := range ls { + out = append(out, l.Label+l.Text) + } + f.shown = append(f.shown, "show "+title+": "+strings.Join(out, "; ")) + return nil +} +func (f *fake) ShowScreen(name string, wait bool) (bool, error) { return false, nil } + +type world struct { + b *bbs.BBS + alice *bbs.Node + sysop *bbs.Node + e *Engine + logged *bytes.Buffer +} + +func setup(t *testing.T, scripts map[string]string) *world { + t.Helper() + store.BcryptCost = 4 + st, err := store.Open(filepath.Join(t.TempDir(), "bbs.db")) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { st.Close() }) + logged := &bytes.Buffer{} + b := bbs.New(bbs.Defaults(), st, log.New(logged, "", 0)) + st.CreateArea("General", "Talk", false) + st.CreateArea("News", "From the sysop", true) + w := &world{b: b, logged: logged} + for _, u := range []struct { + name string + sysop bool + n **bbs.Node + }{{"alice", false, &w.alice}, {"sysop", true, &w.sysop}} { + us, err := st.CreateUser(u.name, "password1", "Here", u.sysop) + if err != nil { + t.Fatal(err) + } + n, err := b.Enter(&bbs.Caller{Via: "test"}, nil) + if err != nil { + t.Fatal(err) + } + n.SetUser(us) + *u.n = n + } + dir := t.TempDir() + for name, src := range scripts { + os.WriteFile(filepath.Join(dir, name+".js"), []byte(src), 0644) + } + w.e = &Engine{Dir: dir, Limit: 300 * time.Millisecond, cache: map[string]compiled{}} + return w +} + +func (w *world) run(t *testing.T, name string, n *bbs.Node, answers ...any) (*fake, error) { + t.Helper() + f := &fake{t: t, answers: answers} + err := w.e.Run(name, w.b, n, f) + return f, err +} + +func has(t *testing.T, what string, all []string, want string) { + t.Helper() + for _, s := range all { + if strings.Contains(s, want) { + return + } + } + t.Errorf("no %q among the %s: %q", want, what, all) +} + +const oneliners = ` +var lines = data.get("lines") || []; +for (;;) { + var k = ui.menu({title: "One-liners", intro: lines.slice(-5), + items: [{key: "a", label: "Add one"}, {key: "q", label: "Quit"}]}); + if (k !== "A") break; + var v = ui.form({title: "Add a line", fields: [{name: "line", label: "Your line", width: 60}]}); + if (v && v.line) { + lines.push(user.name + ": " + v.line); + data.set("lines", lines.slice(-20)); + data.user.set("count", (data.user.get("count") || 0) + 1); + ui.say("Added.", "good"); + } +} +` + +func TestScreensAndData(t *testing.T) { + w := setup(t, map[string]string{"oneliners": oneliners}) + f, err := w.run(t, "oneliners", w.alice, "A", map[string]string{"line": "hello "}, "Q") + if err != nil { + t.Fatal(err) + } + has(t, "screens", f.shown, "menu One-liners: A=Add one Q=Quit") + has(t, "said", f.said, "Added.") + f, err = w.run(t, "oneliners", w.sysop, "Q") + if err != nil { + t.Fatal(err) + } + if v, _, _ := w.b.Store.ScriptGet("oneliners", 0, "lines"); v != `["alice: hello "]` { + t.Errorf("kept %s", v) + } + if v, _, _ := w.b.Store.ScriptGet("oneliners", w.alice.User().ID, "count"); v != "1" { + t.Errorf("alice's count %s", v) + } + if _, ok, _ := w.b.Store.ScriptGet("oneliners", w.sysop.User().ID, "count"); ok { + t.Error("the sysop's count") + } +} + +func TestTablesMessagesAndPosting(t *testing.T) { + w := setup(t, map[string]string{"news": ` +var areas = msg.areas(); +var c = ui.table({title: "Areas", pick: "Area number", + columns: [{title: "Area", width: 20}, {title: "Msgs", width: 5, right: true}], + rows: areas.map(function (a) { return [a.name, a.messages]; })}); +if (c.action === ui.PICK) { + var a = areas[c.row]; + var d = ui.edit({title: "Post in " + a.name, to: "All", subject: "From a script"}); + if (d) { + var id = msg.post(a.id, {to: d.to, subject: d.subject, body: d.body}); + var m = msg.get(id); + ui.message({where: a.name, from: m.from, to: m.to, subject: m.subject, body: m.body, date: m.date, + actions: [{id: "next", label: "Next", key: "n", pf: 11}]}); + } + try { + msg.post(areas[1].id, {subject: "x", body: "y"}); + } catch (e) { + ui.say("Refused: " + e.message, "bad"); + } + ui.show("You", [{label: "Name:", text: user.name}, {label: "Level:", text: String(user.level)}, + "two\nlines", {label: "Share", text: "3", bar: 0.5}]); +} +`}) + f, err := w.run(t, "news", w.alice, view.Choice{Action: view.Pick, Row: 0}, []string{"Line one", "Line two"}, "next") + if err != nil { + t.Fatal(err) + } + has(t, "screens", f.shown, "table Areas: 1:General|0; 2:News|0") + has(t, "screens", f.shown, "message From a script: Line one\nLine two") + has(t, "said", f.said, "Refused: only the sysop posts here") + has(t, "screens", f.shown, "show You: Name:alice; Level:20; two; lines; Share3") + m, err := w.b.Store.Message(1) + if err != nil || m.From != "alice" { + t.Errorf("posted %+v %v", m, err) + } +} + +func TestRunaway(t *testing.T) { + w := setup(t, map[string]string{"loop": `for (;;) {}`, "slow": ` +var k = ui.menu({title: "Slow", items: [{key: "x", label: "X"}]}); +ui.say("got " + k); +`}) + f, err := w.run(t, "loop", w.alice) + if err != nil { + t.Fatal(err) + } + has(t, "said", f.said, "The script loop took too long and was stopped.") + // the time the caller takes is theirs + f = &fake{t: t, answers: []any{"X"}, delay: 500 * time.Millisecond} + if err := w.e.Run("slow", w.b, w.alice, f); err != nil { + t.Fatal(err) + } + has(t, "said", f.said, "got X") +} + +func TestFailures(t *testing.T) { + w := setup(t, map[string]string{ + "bad": `null.x = 1;`, + "syntax": `function (`, + "catch": `try { ui.menu({title: "M", items: [{key: "a", label: "A"}]}); } catch (e) {} for (;;) { ui.say("again"); }`, + "exit": `ui.say("one"); exit(); ui.say("two");`, + "keys": `try { data.set("", 1); } catch (e) { ui.say(e.message); } data.set("k", {a: [1, 2]}); ui.say(JSON.stringify(data.get("k")) + " " + data.keys("").join(","));`, + }) + f, err := w.run(t, "bad", w.alice) + if err != nil { + t.Fatal(err) + } + has(t, "said", f.said, "The script bad failed.") + f, _ = w.run(t, "bad", w.sysop) + has(t, "said", f.said, "The script bad failed: TypeError: Cannot convert undefined or null to object") + if !strings.Contains(w.logged.String(), "script bad: TypeError") { + t.Errorf("log: %s", w.logged) + } + if err := w.e.Check("syntax"); err == nil { + t.Error("syntax error passed") + } + f, _ = w.run(t, "syntax", w.alice) + has(t, "said", f.said, "The script syntax would not run.") + + // the caller going ends the script, whatever it catches + f = &fake{t: t, fail: io.EOF} + if err := w.e.Run("catch", w.b, w.alice, f); !errors.Is(err, io.EOF) { + t.Errorf("hung up: %v", err) + } + if len(f.said) > 1 { + t.Errorf("went on: %q", f.said) + } + + f, err = w.run(t, "exit", w.alice) + if err != nil || strings.Join(f.said, ",") != "one" { + t.Errorf("exit: %v %q", err, f.said) + } + f, _ = w.run(t, "keys", w.alice) + if strings.Join(f.said, "|") != `a name is 1 to 100 characters|{"a":[1,2]} k` { + t.Errorf("data: %q", f.said) + } + f, _ = w.run(t, "nosuch", w.alice) + has(t, "said", f.said, "The script nosuch would not run.") + if ValidName("../etc") || ValidName("Upper") || !ValidName("one-liners_2") { + t.Error("names") + } + if strings.Join(w.e.Names(), " ") != "bad catch exit keys syntax" { + t.Errorf("names %v", w.e.Names()) + } +} + +// TestPollSample: the sample poll, a vote and a new question. +func TestPollSample(t *testing.T) { + w := setup(t, nil) + w.e.Dir = filepath.Join("..", "..", "scripts.sample") + f, err := w.run(t, "poll", w.alice, view.Choice{Action: view.Pick, Row: 2}) + if err != nil { + t.Fatal(err) + } + has(t, "screens", f.shown, "table Which terminal do you call with?: 1:An ANSI terminal; 2:A Commodore; 3:A 3270") + has(t, "said", f.said, "Your vote is counted.") + has(t, "screens", f.shown, "show Poll results: Which terminal do you call with?; ; An ANSI terminal0; A Commodore0; A 32701") + // a second call: no second vote + f, _ = w.run(t, "poll", w.alice) + if strings.Contains(strings.Join(f.shown, "\n"), "table") { + t.Errorf("voted twice: %q", f.shown) + } + f, err = w.run(t, "poll", w.sysop, view.Choice{Action: view.Back}, true, + map[string]string{"q": "Tea or coffee?", "a": "Tea | Coffee |"}) + if err != nil { + t.Fatal(err) + } + has(t, "said", f.said, "The new poll is up.") + f, _ = w.run(t, "poll", w.alice, view.Choice{Action: view.Pick, Row: 1}) + has(t, "screens", f.shown, "table Tea or coffee?: 1:Tea; 2:Coffee") + has(t, "screens", f.shown, "Tea0; Coffee1; ; 1 vote") +} + +func TestES6AndRequire(t *testing.T) { + w := setup(t, map[string]string{"es6": "class A { constructor(n) { this.n = n; } twice() { return this.n * 2; } }\n" + + "let m = new Map([[1, 'one']]);\n" + + "const f = (x) => `${x}!`;\n" + + "ui.say(f(new A(21).twice()) + ' ' + m.get(1) + ' ' + user.has('20') + ' ' + user.has('30') + ' ' + user.has('S'));"}) + f, err := w.run(t, "es6", w.alice) + if err != nil || strings.Join(f.said, "") != "42! one true false false" { + t.Errorf("%v %q", err, f.said) + } +} diff --git a/internal/server/config.go b/internal/server/config.go index adc1442..bd10891 100644 --- a/internal/server/config.go +++ b/internal/server/config.go @@ -46,6 +46,7 @@ type Config struct { Doors []*door.Door Finger *finger.Settings // nil: no finger server Screens *screens.Set // nil: no screens of the sysop's + ScriptsDir string // "": no scripts Menus map[string]*bbs.Menu Text map[string]string // [strings] HTTP *api.Settings // nil: no HTTP API diff --git a/internal/server/customconfig.go b/internal/server/customconfig.go index 7f9004c..7b29e6f 100644 --- a/internal/server/customconfig.go +++ b/internal/server/customconfig.go @@ -10,9 +10,11 @@ import ( "github.com/Neo-Desktop/bbs-sec/internal/bbs" "github.com/Neo-Desktop/bbs-sec/internal/config" "github.com/Neo-Desktop/bbs-sec/internal/screens" + "github.com/Neo-Desktop/bbs-sec/internal/script" ) -// customSections reads screens_dir, the [menu NAME]s and [strings]. +// customSections reads screens_dir, scripts_dir, the [menu NAME]s and +// [strings]. func (c *Config) customSections(cf *config.File) error { if dir := cf.Get("general", "").String("screens_dir", ""); dir != "" { if fi, err := os.Stat(dir); err != nil || !fi.IsDir() { @@ -20,6 +22,19 @@ func (c *Config) customSections(cf *config.File) error { } c.Screens = &screens.Set{Dir: dir} } + if dir := cf.Get("general", "").String("scripts_dir", ""); dir != "" { + if fi, err := os.Stat(dir); err != nil || !fi.IsDir() { + return fmt.Errorf("[general] scripts_dir %s is not a directory", dir) + } + c.ScriptsDir = dir + // what is there compiles, so that a mistake shows now, not to a caller + e := script.For(dir) + for _, name := range e.Names() { + if err := e.Check(name); err != nil { + return fmt.Errorf("scripts_dir: %s.js: %v", name, err) + } + } + } c.Menus = map[string]*bbs.Menu{} for _, s := range cf.All("menu") { m, err := menu(s) @@ -51,6 +66,13 @@ func (c *Config) customSections(cf *config.File) error { if c.Screens == nil { return fmt.Errorf("[menu %s] %s: screen:%s, but no screens_dir", m.Name, it.Key, it.Arg) } + case "script": + if c.ScriptsDir == "" { + return fmt.Errorf("[menu %s] %s: script:%s, but no scripts_dir", m.Name, it.Key, it.Arg) + } + if !script.For(c.ScriptsDir).Has(it.Arg) { + return fmt.Errorf("[menu %s] %s: there is no %s.js in %s", m.Name, it.Key, it.Arg, c.ScriptsDir) + } } } if m.Screen != "" && c.Screens == nil { diff --git a/internal/server/script_test.go b/internal/server/script_test.go new file mode 100644 index 0000000..c5a7b41 --- /dev/null +++ b/internal/server/script_test.go @@ -0,0 +1,111 @@ +package server + +import ( + "os" + "os/exec" + "path/filepath" + "strings" + "testing" + + "github.com/Neo-Desktop/bbs-sec/internal/bbs" + "github.com/Neo-Desktop/bbs-sec/internal/ui3270" +) + +// withScripts gives a BBS the sample scripts and a menu with them. +func withScripts(t *testing.T) func(*bbs.BBS, string) { + return func(b *bbs.BBS, top string) { + dir, err := filepath.Abs(filepath.Join("..", "..", "scripts.sample")) + if err != nil { + t.Fatal(err) + } + b.ScriptsDir = dir + item := func(k, v string) bbs.MenuItem { + it, err := bbs.ParseMenuItem(k, v) + if err != nil { + t.Fatal(err) + } + return it + } + b.Menus = map[string]*bbs.Menu{"main": {Name: "main", Title: "Main", Items: []bbs.MenuItem{ + item("o", "script:oneliners One-liners"), item("p", "script:poll Poll"), item("g", "logoff Goodbye")}}} + } +} + +// TestScriptOnBoth: the sample one-liners script on a text terminal and a +// 3270: the same screens, drawn by each. +func TestScriptOnBoth(t *testing.T) { + addr := freeTCP(t) + e := startFull(t, ui3270.Graphics{}, nil, withScripts(t), + &Listener{Name: "modem", Kind: "raw", Address: "modem.sock", ANSI: "no"}, + &Listener{Name: "telnet", Kind: "telnet", Address: addr, TN3270: true}) + d := login(e, "alice", "alicepass1") + d.send("O") + d.expect("One-liners") + d.expect("No one has left a line yet.") + d.expect("[A]dd a line, [Q]uit: ") + d.send("A") + d.expect("Your line (Enter to give up): ") + d.send("hello from a text terminal\r") + d.expect("Added.") + d.expect("alice: hello from a text terminal") + d.expect("[A]dd a line, [Q]uit: ") + d.send("Q") + d.expect("Command: ") + + if _, err := exec.LookPath("s3270"); err != nil { + t.Skip("no s3270") + } + script := strings.Join([]string{ + "Connect(" + addr + ")", "Wait(10,InputField)", + `String("sysop")`, "Tab()", `String("sysoppass1")`, "Enter()", "Wait(5,InputField)", + `String("o")`, "Enter()", "Wait(5,InputField)", "Ascii()", + "PF(5)", "Wait(5,InputField)", "Ascii()", + `String("and one from a 3270")`, "Enter()", "Wait(5,InputField)", "Ascii()", + "PF(3)", "Wait(5,InputField)", "Quit()", ""}, "\n") + cmd := exec.Command("s3270", "-model", "3279-2") + cmd.Stdin = strings.NewReader(script) + out, err := cmd.CombinedOutput() + if err != nil { + t.Fatalf("s3270: %v\n%s", err, out) + } + for _, want := range []string{"PF5=Add PF3=Back", "alice:", "hello from a text terminal", "Your line", + "Added.", "sysop:", "and one from a 3270"} { + if !strings.Contains(string(out), want) { + t.Errorf("the 3270 did not show %q:\n%s", want, out) + } + } + v, _, _ := e.b.Store.ScriptGet("oneliners", 0, "lines") + if !strings.Contains(v, `"text":"and one from a 3270"`) || !strings.Contains(v, `"who":"sysop"`) { + t.Errorf("kept %s", v) + } +} + +func TestScriptsConfig(t *testing.T) { + dir := t.TempDir() + scripts := filepath.Join(dir, "scripts") + os.Mkdir(scripts, 0755) + os.WriteFile(filepath.Join(scripts, "hello.js"), []byte(`ui.say("hi");`), 0644) + load := func(body string) (*Config, error) { + p := filepath.Join(dir, "bbs.conf") + os.WriteFile(p, []byte("[listen telnet]\ntype = telnet\naddress = :2300\n"+body), 0600) + return Load(p) + } + c, err := load("[general]\nscripts_dir = " + scripts + "\n[menu main]\nh = script:hello Hello\n") + if err != nil || c.ScriptsDir != scripts || c.Menus["main"].Items[0].Action != "script" { + t.Fatalf("%+v %v", c, err) + } + for body, want := range map[string]string{ + "[menu main]\nh = script:hello Hello\n": "no scripts_dir", + "[general]\nscripts_dir = " + scripts + "\n[menu main]\nh = script:nope N\n": "there is no nope.js", + "[general]\nscripts_dir = " + scripts + "\n[menu main]\nh = script:../x X\n": "a script's name", + "[general]\nscripts_dir = " + filepath.Join(dir, "nope") + "\n": "is not a directory", + } { + if _, err := load(body); err == nil || !strings.Contains(err.Error(), want) { + t.Errorf("%q: %v, want %q", body, err, want) + } + } + os.WriteFile(filepath.Join(scripts, "broken.js"), []byte(`function (`), 0644) + if _, err := load("[general]\nscripts_dir = " + scripts + "\n"); err == nil || !strings.Contains(err.Error(), "broken.js") { + t.Errorf("a broken script: %v", err) + } +} diff --git a/internal/store/copy.go b/internal/store/copy.go index 053549d..75ec188 100644 --- a/internal/store/copy.go +++ b/internal/store/copy.go @@ -9,7 +9,7 @@ import ( // copyOrder is the tables in an order their references allow. var copyOrder = []string{"users", "areas", "messages", "lastread", "scan_off", "mail", "file_areas", "files", - "history", "peer_groups", "peer_push", "netmail_out", "api_tokens", "ssh_keys"} + "history", "peer_groups", "peer_push", "netmail_out", "api_tokens", "ssh_keys", "script_data"} var columnPat = regexp.MustCompile(`(?m)^\s*("?\w+"?)\s+(\{\w+\})`) diff --git a/internal/store/scan.go b/internal/store/scan.go index ff9a499..558526c 100644 --- a/internal/store/scan.go +++ b/internal/store/scan.go @@ -54,6 +54,13 @@ func (s *Store) MessagesTo(name string, limit int) ([]*Message, error) { ORDER BY id DESC LIMIT ?`, name, limit) } +// likePrefix makes text a LIKE pattern that matches what begins with it, +// in its case. +func likePrefix(text string) string { + r := strings.NewReplacer("!", "!!", "%", "!%", "_", "!_") + return r.Replace(text) + "%" +} + // likeEscape makes text a LIKE pattern that matches it anywhere. func likeEscape(text string) string { r := strings.NewReplacer("!", "!!", "%", "!%", "_", "!_") diff --git a/internal/store/schema.go b/internal/store/schema.go index e6aad7d..57204d8 100644 --- a/internal/store/schema.go +++ b/internal/store/schema.go @@ -67,6 +67,13 @@ CREATE TABLE IF NOT EXISTS scan_off ( area_id {int} NOT NULL REFERENCES areas(id) ON DELETE CASCADE, PRIMARY KEY (user_id, area_id) )`, ` +CREATE TABLE IF NOT EXISTS script_data ( + script {key} NOT NULL, + user_id {int} NOT NULL DEFAULT 0, + name {key} NOT NULL, + value {text} NOT NULL, + PRIMARY KEY (script, user_id, name) +)`, ` CREATE TABLE IF NOT EXISTS mail ( id {id}, from_id {int} NOT NULL, diff --git a/internal/store/scriptdata.go b/internal/store/scriptdata.go new file mode 100644 index 0000000..584513f --- /dev/null +++ b/internal/store/scriptdata.go @@ -0,0 +1,59 @@ +package store + +import ( + "database/sql" + "errors" +) + +// Script data: what scripts keep, by script, and for a user (0: for all). + +// ScriptGet is a script's value of name (ok false if it has none). +func (s *Store) ScriptGet(script string, user int64, name string) (string, bool, error) { + var v string + err := s.db.QueryRow(`SELECT value FROM script_data WHERE script = ? AND user_id = ? AND name = ?`, + script, user, name).Scan(&v) + if errors.Is(err, sql.ErrNoRows) { + return "", false, nil + } + return v, err == nil, err +} + +// ScriptSet keeps a script's value of name. +func (s *Store) ScriptSet(script string, user int64, name, value string) error { + _, err := s.db.Exec(`INSERT INTO script_data (script, user_id, name, value) VALUES (?, ?, ?, ?) + ON CONFLICT (script, user_id, name) DO UPDATE SET value = excluded.value`, script, user, name, value) + return err +} + +// ScriptDelete forgets a script's value of name. +func (s *Store) ScriptDelete(script string, user int64, name string) error { + _, err := s.db.Exec(`DELETE FROM script_data WHERE script = ? AND user_id = ? AND name = ?`, script, user, name) + return err +} + +// ScriptNames are a script's names beginning with prefix, in order, at +// most limit. +func (s *Store) ScriptNames(script string, user int64, prefix string, limit int) ([]string, error) { + rows, err := s.db.Query(`SELECT name FROM script_data WHERE script = ? AND user_id = ? AND name LIKE ? ESCAPE '!' + ORDER BY name LIMIT ?`, script, user, likePrefix(prefix), limit) + if err != nil { + return nil, err + } + defer rows.Close() + var out []string + for rows.Next() { + var n string + if err := rows.Scan(&n); err != nil { + return nil, err + } + out = append(out, n) + } + return out, rows.Err() +} + +// ScriptCount is how many values a script keeps for a user (or all). +func (s *Store) ScriptCount(script string, user int64) (int, error) { + var n int + err := s.db.QueryRow(`SELECT COUNT(*) FROM script_data WHERE script = ? AND user_id = ?`, script, user).Scan(&n) + return n, err +} diff --git a/internal/store/store.go b/internal/store/store.go index d9718c4..c34121b 100644 --- a/internal/store/store.go +++ b/internal/store/store.go @@ -293,7 +293,11 @@ func (s *Store) SetLocked(id int64, locked bool) error { // DeleteUser removes an account and its mail; its messages stay. func (s *Store) DeleteUser(id int64) error { - return s.exec1(`DELETE FROM users WHERE id = ?`, id) + if err := s.exec1(`DELETE FROM users WHERE id = ?`, id); err != nil { + return err + } + _, err := s.db.Exec(`DELETE FROM script_data WHERE user_id = ?`, id) + return err } // LoggedIn counts a login. diff --git a/internal/store/store_test.go b/internal/store/store_test.go index e07e818..9f834b8 100644 --- a/internal/store/store_test.go +++ b/internal/store/store_test.go @@ -384,3 +384,39 @@ func TestFilesFound(t *testing.T) { t.Errorf("long %q", f.LongDesc) } } + +func TestScriptData(t *testing.T) { + s := open(t) + u, _ := s.CreateUser("alice", "password1", "", false) + if _, ok, err := s.ScriptGet("one", 0, "x"); ok || err != nil { + t.Fatalf("none: %v %v", ok, err) + } + for _, kv := range [][2]string{{"line_1", "a"}, {"line_2", "b"}, {"line%3", "c"}, {"other", "d"}, {"line_1", "A"}} { + if err := s.ScriptSet("one", 0, kv[0], kv[1]); err != nil { + t.Fatal(err) + } + } + s.ScriptSet("one", u.ID, "line_1", "mine") + s.ScriptSet("two", 0, "line_1", "theirs") + if v, ok, _ := s.ScriptGet("one", 0, "line_1"); !ok || v != "A" { + t.Errorf("get %q", v) + } + if v, _, _ := s.ScriptGet("one", u.ID, "line_1"); v != "mine" { + t.Errorf("the user's %q", v) + } + names, err := s.ScriptNames("one", 0, "line_", 10) + if err != nil || strings.Join(names, " ") != "line_1 line_2" { + t.Errorf("names %v %v", names, err) + } + if names, _ := s.ScriptNames("one", 0, "", 2); len(names) != 2 { + t.Errorf("limit %v", names) + } + s.ScriptDelete("one", 0, "other") + if n, _ := s.ScriptCount("one", 0); n != 3 { + t.Errorf("count %d", n) + } + s.DeleteUser(u.ID) + if n, _ := s.ScriptCount("one", u.ID); n != 0 { + t.Errorf("a deleted user's: %d", n) + } +} diff --git a/internal/ui3270/view.go b/internal/ui3270/view.go index 20cbba4..127f058 100644 --- a/internal/ui3270/view.go +++ b/internal/ui3270/view.go @@ -399,7 +399,7 @@ func (u *ui) Form(f *view.Form) (map[string]string, bool, error) { break } scr = append(scr, u.text(row, 2, fmt.Sprintf("%-16s ===>", bbs.Trunc(fd.Label, 16)), go3270.Turquoise, false)) - fs, next := u.field(row, 23, fd.Width, fd.Name, fd.Secret) + fs, next := u.field(row, 24, fd.Width, fd.Name, fd.Secret) // the label ends at 23 inputs = append(inputs, fs...) row = next } diff --git a/scripts.sample/README b/scripts.sample/README new file mode 100644 index 0000000..dea03d3 --- /dev/null +++ b/scripts.sample/README @@ -0,0 +1,8 @@ +Sample scripts for scripts_dir: copy them there and give them menu items. + + oneliners.js the last lines callers left, and one of yours + poll.js a poll: a vote each, the results as bars + +A logon.js there runs after every login, before the menus. + +See the wiki's Scripting page for what a script can do. diff --git a/scripts.sample/oneliners.js b/scripts.sample/oneliners.js new file mode 100644 index 0000000..ea13b10 --- /dev/null +++ b/scripts.sample/oneliners.js @@ -0,0 +1,33 @@ +// One-liners: the last lines callers left, and one of yours. +// +// A menu item runs it: o = script:oneliners One-liners +// It works on every terminal: text, RIP and 3270. + +var MOST = 15; // lines kept + +function show() { + var lines = data.get("lines") || []; + var shown = lines.length ? lines.map(function (l) { + return {label: l.who + ":", text: l.text}; + }) : ["No one has left a line yet."]; + return ui.panel({ + title: "One-liners", + lines: shown, + actions: [{id: "add", label: "Add a line", key: "a", pf: 5, short: "Add"}] + }); +} + +for (;;) { + node.doing("Reading one-liners"); + if (show() !== "add") break; + var v = ui.form({ + title: "Your one-liner", + fields: [{name: "text", label: "Your line", prompt: "Your line (Enter to give up): ", width: 60}], + submit: "Add" + }); + if (!v || !v.text) continue; + var lines = data.get("lines") || []; + lines.push({who: user.name, text: v.text, when: new Date().toISOString()}); + data.set("lines", lines.slice(-MOST)); + ui.say("Added.", "good"); +} diff --git a/scripts.sample/poll.js b/scripts.sample/poll.js new file mode 100644 index 0000000..86a04f1 --- /dev/null +++ b/scripts.sample/poll.js @@ -0,0 +1,58 @@ +// A poll: one question, a vote each, the results as bars. +// +// The sysop sets the question from the script itself (S on its screen). +// A menu item runs it: p = script:poll Today's poll + +var poll = data.get("poll") || {question: "Which terminal do you call with?", + answers: ["An ANSI terminal", "A Commodore", "A 3270", "Something else"]}; +var votes = data.get("votes") || {}; + +function results() { + var total = 0, i; + for (i = 0; i < poll.answers.length; i++) total += votes[i] || 0; + var lines = [{text: poll.question, tone: "bright"}, ""]; + for (i = 0; i < poll.answers.length; i++) { + var n = votes[i] || 0; + lines.push({label: poll.answers[i], text: String(n), bar: total ? n / total : 0}); + } + lines.push("", total + (total === 1 ? " vote" : " votes")); + ui.show("Poll results", lines); +} + +function vote() { + var c = ui.table({ + title: poll.question, + pick: "Your answer", + columns: [{title: "Answer"}], + rows: poll.answers.map(function (a) { return [a]; }) + }); + if (c.action !== ui.PICK || c.row < 0) return; + votes[c.row] = (votes[c.row] || 0) + 1; + data.set("votes", votes); + data.user.set("voted", poll.question); + ui.say("Your vote is counted.", "good"); +} + +function setQuestion() { + var v = ui.form({ + title: "A new poll", + fields: [{name: "q", label: "Question", width: 70}, + {name: "a", label: "Answers", prompt: "Answers (separated by |): ", width: 200}] + }); + if (!v || !v.q || !v.a) return; + var answers = v.a.split("|").map(function (s) { return s.trim(); }).filter(Boolean); + if (answers.length < 2) { + ui.say("A poll needs two answers or more.", "bad"); + return; + } + poll = {question: v.q, answers: answers}; + votes = {}; + data.set("poll", poll); + data.set("votes", votes); + ui.say("The new poll is up.", "good"); +} + +node.doing("At the poll"); +if (data.user.get("voted") !== poll.question) vote(); +results(); +if (user.sysop && ui.confirm("Set a new question?", false)) setQuestion();