Add access levels: levels, flags, requirements, limits, validation

Users have a level (0-255) and flags (A-Z).  [level N] sections say what
a range of levels may do: time online a day (warned at 5 and 1 minutes,
hung up at the end; doors' limits cut to what is left), downloads a day
(counted by every way: the BBS, 3270, FTP, the API), and whether they
may post, mail (else only the sysop), chat, page, download, upload and
open doors.

Requirements ("30 F !X", "sysop") are put on message areas (reading and
posting), file areas (downloading and uploading), doors, menus and menu
items ("x = menu:extras Extras | 50 X").  They are checked in the core,
so the text BBS, 3270s, FTP, NNTP and the API keep them alike: an area a
user may not read is not listed, opened or found by number or
Message-ID.

New users start at new_user_level and are told they wait; the sysop
validates them on the BBS (V on the main menu), by bbs user
waiting/validate/level/flags, or by PATCH /api/v1/admin/users.  Users
see their access in the profile and /api/v1/me; no one changes their
own.  Drop files carry the caller's level.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AFQhReUqUc7F5srk2hViqr
This commit is contained in:
Claude committed 2026-10-12 08:49:46 +00:00
1 parent f832430916
commit b41f59ec55
43 files changed
+1660 -111

No files matched your search

+2
View File
@@ -72,6 +72,7 @@ What there is:
- [a web terminal](https://github.com/Neo-Desktop/bbs-sec/wiki/HTTP-API#the-web-terminal): the BBS in a browser (xterm.js, built in)
- [an HTTP API](https://github.com/Neo-Desktop/bbs-sec/wiki/HTTP-API): REST, server-sent events, and WebSockets (JSON or protobuf) where web clients chat with terminal callers; Prometheus metrics
- [customization](https://github.com/Neo-Desktop/bbs-sec/wiki/Customization): ANSI art and 3270 screens, menus of the sysop's, @-codes, the prompts' words
- [access levels](https://github.com/Neo-Desktop/bbs-sec/wiki/Access-Levels): levels and flags, areas, doors and menus that require them, time and download limits a day, new users validated by the sysop
- new users sign themselves up (or not: `new_users = no`)
- SQLite storage, one file
@@ -102,6 +103,7 @@ The documentation is in the [wiki](https://github.com/Neo-Desktop/bbs-sec/wiki/)
| [Running](https://github.com/Neo-Desktop/bbs-sec/wiki/Running) | first start, systemd, the defaults |
| [Administration](https://github.com/Neo-Desktop/bbs-sec/wiki/Administration) | the bbs command: users, areas, files, mail exchange |
| [Configuration](https://github.com/Neo-Desktop/bbs-sec/wiki/Configuration) | bbs.conf: its sections, listeners |
| [Access levels](https://github.com/Neo-Desktop/bbs-sec/wiki/Access-Levels) | levels, flags, what areas, doors and menus require, daily limits, validation |
| [Customization](https://github.com/Neo-Desktop/bbs-sec/wiki/Customization) | screens (ANSI art, 3270), menus, prompts |
| [SSH](https://github.com/Neo-Desktop/bbs-sec/wiki/SSH) | the SSH listener, keys, host keys |
| [Modem callers](https://github.com/Neo-Desktop/bbs-sec/wiki/Modem-Callers) | app_dmodem and modemmenu |
+17
View File
@@ -174,6 +174,23 @@ address = 127.0.0.1:2513
; the web terminal at /terminal: the BBS in a browser (xterm.js, built in)
;terminal = yes
; Access levels: a user's level (0-255) gets what the [level] at or
; below it says; areas, doors and menus may require a level and flags
; (bbs area require, require = in [door] and [menu]). See
; docs/wiki/Access-Levels.md. Without any, nothing is limited
;[general]: new_user_level = 20, validated_level = 20
;[level 10]
;name = New user
;time = 30
;downloads = 2
;post = no
;mail = no
;chat = no
;[level 20]
;name = Member
;time = 120
;downloads = 20
; The FTP server for the file areas: users log in with their BBS name and
; password; each file area is a directory. bbs filearea add NAME makes
; one. Without this section there is no FTP server
+97 -1
View File
@@ -65,9 +65,14 @@ func usage() {
bbs [-config FILE] user add NAME [-sysop]
bbs [-config FILE] user passwd|lock|unlock|sysop|unsysop|del NAME
bbs [-config FILE] user list
bbs [-config FILE] user level NAME N access level, 0-255
bbs [-config FILE] user flags NAME +AB -C access flags (or AB: exactly those)
bbs [-config FILE] user validate NAME to validated_level
bbs [-config FILE] user waiting users under validated_level
bbs [-config FILE] area add NAME [DESCRIPTION] [-sysop-only]
bbs [-config FILE] area del NAME
bbs [-config FILE] area list
bbs [-config FILE] area require AREA READ POST access requirements ("30 F", sysop, -: none)
bbs [-config FILE] area newsgroup AREA GROUP|- (- : not a newsgroup)
bbs [-config FILE] news sync [PEER] exchange articles with peers now
bbs [-config FILE] area echo AREA TAG|- make an area a FidoNet echo (- : not one)
@@ -83,6 +88,7 @@ func usage() {
bbs [-config FILE] filearea add NAME [DESCRIPTION] [-sysop-upload]
bbs [-config FILE] filearea del NAME
bbs [-config FILE] filearea list
bbs [-config FILE] filearea require AREA DOWNLOAD UPLOAD
bbs [-config FILE] file add AREA PATH [DESCRIPTION] (as the first sysop)
bbs [-config FILE] file list AREA
bbs [-config FILE] file del AREA NAME
@@ -419,6 +425,24 @@ func split(args []string) (words []string, flags map[string]bool) {
}
func userCmd(cfg *server.Config, args []string) {
if len(args) >= 3 && args[0] == "flags" {
// -C is an edit here, not an option
st := open(cfg)
defer st.Close()
u, err := st.UserByName(args[1])
if err != nil {
fatal(fmt.Errorf("%s: %w", args[1], err))
}
fl, err := bbs.EditFlags(u.Flags, strings.Join(args[2:], " "))
if err != nil {
fatal(err)
}
if err := st.SetFlags(u.ID, fl); err != nil {
fatal(err)
}
fmt.Printf("%s: flags %q\n", u.Name, fl)
return
}
words, flags := split(args)
if len(words) == 0 {
usage()
@@ -441,7 +465,35 @@ func userCmd(cfg *server.Config, args []string) {
if u.External {
tags = append(tags, "external")
}
fmt.Printf("%-24s %5d calls %5d posts %s\n", u.Name, u.Logins, u.Posts, strings.Join(tags, " "))
if u.Flags != "" {
tags = append(tags, "flags "+u.Flags)
}
fmt.Printf("%-24s level %3d %5d calls %5d posts %s\n", u.Name, u.Level, u.Logins, u.Posts, strings.Join(tags, " "))
}
return
}
if words[0] == "level" && len(words) == 3 {
u, err := st.UserByName(words[1])
if err != nil {
fatal(fmt.Errorf("%s: %w", words[1], err))
}
l, err := strconv.Atoi(words[2])
if err != nil || l < 0 || l > bbs.MaxLevel {
fatal(fmt.Errorf("a level is 0 to %d", bbs.MaxLevel))
}
if err := st.SetLevel(u.ID, l); err != nil {
fatal(err)
}
fmt.Printf("%s: level %d\n", u.Name, l)
return
}
if words[0] == "waiting" {
us, err := st.UsersBelow(cfg.Settings.ValidatedLevel)
if err != nil {
fatal(err)
}
for _, u := range us {
fmt.Printf("%-24s level %3d since %s %s\n", u.Name, u.Level, u.Created.Format("2006-01-02"), u.Location)
}
return
}
@@ -479,6 +531,8 @@ func userCmd(cfg *server.Config, args []string) {
err = st.SetSysop(u.ID, false)
case "del":
err = st.DeleteUser(u.ID)
case "validate":
err = st.SetLevel(u.ID, max(u.Level, cfg.Settings.ValidatedLevel))
default:
usage()
}
@@ -512,6 +566,9 @@ func areaCmd(cfg *server.Config, args []string) {
if a.EchoTag != "" {
only += " [echo " + a.EchoTag + "]"
}
if a.ReadReq != "" || a.PostReq != "" {
only += fmt.Sprintf(" (read %q, post %q)", a.ReadReq, a.PostReq)
}
fmt.Printf("%-20s %5d messages %s%s\n", a.Name, a.Messages, a.Description, only)
}
case "add":
@@ -527,6 +584,19 @@ func areaCmd(cfg *server.Config, args []string) {
fatal(err)
}
fmt.Println("added", a.Name)
case "require":
if len(words) != 4 {
usage()
}
a, err := st.AreaByName(words[1])
if err != nil {
fatal(fmt.Errorf("%s: %w", words[1], err))
}
read, post := requireArg(words[2]), requireArg(words[3])
if err := st.SetAreaRequire(a.ID, read, post); err != nil {
fatal(err)
}
fmt.Printf("%s: read %q, post %q\n", a.Name, read, post)
case "newsgroup":
if len(words) != 3 {
usage()
@@ -625,6 +695,19 @@ func fileAreaCmd(cfg *server.Config, args []string) {
fatal(err)
}
fmt.Println("added", a.Name)
case "require":
if len(words) != 4 {
usage()
}
a, err := st.FileAreaByName(words[1])
if err != nil {
fatal(fmt.Errorf("%s: %w", words[1], err))
}
dl, ul := requireArg(words[2]), requireArg(words[3])
if err := st.SetFileAreaRequire(a.ID, dl, ul); err != nil {
fatal(err)
}
fmt.Printf("%s: download %q, upload %q\n", a.Name, dl, ul)
case "del":
if len(words) != 2 {
usage()
@@ -1002,3 +1085,16 @@ func sshKeyCmd(cfg *server.Config, args []string) {
usage()
}
}
// requireArg is an access requirement given on the command line ("-":
// none), checked.
func requireArg(s string) string {
if s == "-" {
return ""
}
r, err := bbs.ParseRequire(s)
if err != nil {
fatal(err)
}
return r.String()
}
+96
View File
@@ -0,0 +1,96 @@
Every user has an **access level** (0 to 255) and **flags** (letters A to
Z). The sysop says what each level may do, and what message areas, file
areas, doors and menus require. Sysops pass every check.
Without any of it nothing changes: a user's level is 20 and nothing
requires more.
## Levels
```ini
[general]
new_user_level = 10 ; a new account's level
validated_level = 20 ; what validating a user raises them to
[level 10]
name = New user
time = 30 ; minutes online a day (0: no limit)
downloads = 2 ; files a day (0: no limit)
post = no
mail = no ; still to the sysop: to ask for validation
chat = no
[level 20]
name = Member
time = 120
downloads = 20
[level 90]
name = Trusted
```
A user's level gets what the `[level]` at or below it says: level 35 above
gets `[level 20]`'s. A level under every `[level]` has no limits. Each
`[level]` may say:
| | default | |
|---|---|---|
| `name` | `Level N` | shown in the profile and to the API |
| `time` | `0` | minutes online a day; the caller is warned at 5 and 1 minutes left and hung up at the end (and gets at least a minute of a call, to read and log off). A door's time limit is cut to what is left |
| `downloads` | `0` | files a day, by any way (the BBS, FTP, 3270, the API) |
| `post` | `yes` | post in message areas |
| `mail` | `yes` | mail other users (and netmail); without it, only the sysop |
| `chat` | `yes` | chat rooms (a page's private room is the page's) |
| `page` | `yes` | page the sysop |
| `download`, `upload` | `yes` | files |
| `doors` | `yes` | doors |
The day is the server's local day; time and downloads start again at
midnight.
## Requirements
What an area, a door or a menu requires is written as terms that must all
hold:
| term | |
|---|---|
| `30` | level 30 or higher |
| `F`, `FB` | has flag F (and B) |
| `!X` | does not have flag X |
| `sysop` | sysops only |
`30 F !X` is level 30 or more, with F, without X. Nothing is anyone
logged in. A locked user meets none.
| where | how | |
|---|---|---|
| message area | `bbs area require AREA READ POST` | who sees it (in lists, newsgroups by NNTP, the API) and who posts |
| file area | `bbs filearea require AREA DOWNLOAD UPLOAD` | an area is listed to those who may do either |
| door | `require = 30 L` in its `[door]` | |
| menu | `require = 50` in its `[menu]` | to be taken into it |
| menu item | `x = menu:extras Extras \| 50 X` | the item is shown only to those who meet what follows `\|` |
`-` on the command line is none: `bbs area require General - 20`.
## Validation
New users start at `new_user_level`; their welcome says they wait for the
sysop's validation, and they may mail the sysop even when their level may
not mail. The sysop validates them:
- on the BBS: `V` on the main menu (*Validate users (N)*) goes through
those waiting: validate, set another level, lock, skip;
- by the command: `bbs user waiting`, `bbs user validate NAME`,
`bbs user level NAME N`, `bbs user flags NAME +AB -C`;
- by the API: `PATCH /api/v1/admin/users/{name}` with `level` and
`flags` (`"AB"`, or an edit `"+A -B"`).
Users see their own level, flags, time left and downloads in their
profile (and at `GET /api/v1/me`, `access`); others see neither. No one
changes their own.
Drop files give doors the caller's level as their security level (255 for
sysops).
**See also:** [Administration](Administration), [Configuration](Configuration), [Security](Security)
+13
View File
@@ -13,6 +13,19 @@ bbs user sysop NAME # and unsysop
bbs user del NAME # their mail goes; their messages stay
```
## Access
```
bbs user level NAME N # 0-255
bbs user flags NAME +AB -C # or AB: exactly those
bbs user waiting # under validated_level
bbs user validate NAME
bbs area require AREA READ POST # "30 F", sysop, - for none
bbs filearea require AREA DOWNLOAD UPLOAD
```
See [Access levels](Access-Levels).
## SSH keys
```
+1
View File
@@ -28,6 +28,7 @@ whether terminals are asked what they are: [Terminal identification](Terminal-Id
| `[door NAME]` | a door program | [Doors](Doors) |
| `screens_dir` (in `[general]`), `[menu NAME]`, `[strings]` | the sysop's screens, menus and prompts | [Customization](Customization) |
| `[finger]`, `[gopher]` | the finger and gopher servers | [Finger and gopher](Finger-and-Gopher) |
| `[level N]`, `new_user_level`, `validated_level` (in `[general]`) | access levels | [Access levels](Access-Levels) |
| `[http]` | the HTTP API, its WebSockets, the web terminal and metrics | [HTTP API](HTTP-API) |
| `page_command` (in `[general]`) | telling the sysop of a page when they are not on | [Chat and paging](Chat-and-Paging) |
+8 -1
View File
@@ -99,7 +99,14 @@ a Commodore found while logging in: by DEL typed in the name, by a shifted lette
commands and their escaping, the menu scene; a RIP terminal found by its
answer, given a .rip screen, menus as buttons, the scene cleared on a
choice and a pause before the next; an ANSI terminal without RIP given
none of it. Terminal identification: the answers of DEC's terminals and
none of it. Access levels: requirements read and written back, met and
not (flags, !flags, sysop, locked users), flag edits; levels found for a
user; areas hidden and posting refused by level and by flags, mail only to
the sysop, chat and paging refused, the day's downloads counted and
limited, doors, validation; the day's time running out (warned, hung up,
counted); a new user waiting and validated by the sysop on the BBS; the
API (no user raises their own level, levels and flags seen only by
sysops and the user, area requirements); the configuration. Terminal identification: the answers of DEC's terminals and
of emulators (VT100 to VT525, xterm old and new, VTE, tmux, SyncTERM,
PuTTY, the Linux console, a VT52) read into names, levels, sixel and
monochrome; DEC Special Graphics and Latin-1 output, escapes passing
+3 -3
View File
@@ -63,7 +63,7 @@ Errors are `{"error": "...", "code": "..."}`.
| `POST /login`, `POST /logout` | a session token; ending it | (none), any |
| `GET /system` | the name, sysop, counts, features | anonymous |
| `GET /who` | who is online (with each `terminal`, as it said what it is) | anonymous |
| `GET`, `PATCH /me` | your account; change your location or password | read |
| `GET`, `PATCH /me` | your account and access; change your location or password | read |
| `GET /me/tokens`, `DELETE /me/tokens/{id}` | your tokens; revoke one | any |
| `GET /me/keys` | your SSH keys | read |
| `POST /me/keys`, `DELETE /me/keys/{id}` | add an SSH key (`{"key": "ssh-ed25519 ..."}`, from a login's session only); delete one | any |
@@ -83,8 +83,8 @@ Errors are `{"error": "...", "code": "..."}`.
| `GET /events` | server-sent events | chat or read |
| `GET /ws`, `GET /ws/proto` | WebSockets | chat |
| `GET /admin/pages`, `POST /admin/pages/{node}/answer` | pages waiting; answer one (node 0: the longest waiting) | sysop |
| `POST /admin/users`, `PATCH /admin/users/{name}` | add a user; lock, unlock, make sysop, set password | sysop |
| `POST /admin/areas`, `PATCH /admin/areas/{id}` | add an area; set its newsgroup or echo tag | sysop |
| `POST /admin/users`, `PATCH /admin/users/{name}` | add a user; lock, unlock, make sysop, set password, `level`, `flags` | sysop |
| `POST /admin/areas`, `PATCH /admin/areas/{id}` | add an area; set its newsgroup, echo tag, `read_require`, `post_require` | sysop |
| `POST /admin/nodes/{n}/kick` | throw a caller off | sysop |
| `GET /admin/fido`, `POST /admin/fido/poll` | FidoNet links and outbound; call them now | sysop |
| `GET /admin/news`, `POST /admin/news/sync` | news peers; sync now | sysop |
+2
View File
@@ -70,6 +70,7 @@ What there is:
- [a web terminal](HTTP-API#the-web-terminal): the BBS in a browser (xterm.js, built in)
- [an HTTP API](HTTP-API): REST, server-sent events, and WebSockets (JSON or protobuf) where web clients chat with terminal callers; Prometheus metrics
- [customization](Customization): ANSI art and 3270 screens, menus of the sysop's, @-codes, the prompts' words
- [access levels](Access-Levels): levels and flags, areas, doors and menus that require them, time and download limits a day, new users validated by the sysop
- new users sign themselves up (or not: `new_users = no`)
- SQLite storage, one file
@@ -81,6 +82,7 @@ What there is:
| [Running](Running) | first start, systemd, the defaults |
| [Administration](Administration) | the `bbs` command: users, areas, files, mail exchange |
| [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 |
| [SSH](SSH) | the SSH listener, keys, host keys |
| [Modem callers](Modem-Callers) | app_dmodem and modemmenu |
+6
View File
@@ -67,6 +67,12 @@
and revocable; rate limits per token and per address; JSON bodies
limited and strict; one CORS origin at most, and WebSockets only from
it and the API's own host. Metrics are on an address of their own.
- Access levels: checked in the BBS's core, so the text BBS, 3270s, FTP,
NNTP and the API keep them alike; an area a user may not read is not
listed, opened, or found by a message's number or Message-ID; no user
changes their own level or flags (`PATCH /api/v1/me` refuses them; only
sysops' tokens reach `/admin`); a requirement that does not read shuts
everyone but the sysop out.
- The web terminal: the page's scripts only from the BBS (a Content
Security Policy: no inline scripts, no other hosts, no framing); its
WebSocket only from the BBS's own pages (or the `cors` origin), with
+1
View File
@@ -6,6 +6,7 @@
- [Administration](Administration)
- [Configuration](Configuration)
- [Customization](Customization)
- [Access levels](Access-Levels)
**Callers**
- [SSH](SSH)
+60
View File
@@ -614,3 +614,63 @@ func TestSSHKeys(t *testing.T) {
t.Fatalf("after delete: %v", ks)
}
}
// TestAccess: levels and requirements through the API; a user cannot
// change their own access.
func TestAccess(t *testing.T) {
s := setup(t, Settings{})
s.b.ValidatedLevel = 20
alice, sysop := s.login("alice", "alicepass1"), s.login("sysop", "sysoppass1")
// no raising one's own level or flags
for _, body := range []map[string]any{{"level": 255}, {"flags": "ABC"}} {
if code, m, _ := s.do("PATCH", "/api/v1/me", alice, body); code != 400 {
t.Fatalf("PATCH /me %v: %d %v", body, code, m)
}
}
if code, _, _ := s.do("PATCH", "/api/v1/admin/users/alice", alice, map[string]any{"level": 255}); code != 403 {
t.Fatalf("alice as admin: %d", code)
}
_, me, _ := s.do("GET", "/api/v1/me", alice, nil)
if acc := me["access"].(map[string]any); acc["level"] != 20.0 || acc["validated"] != true {
t.Fatalf("access: %v", acc)
}
// a sysop sets them
code, m, _ := s.do("PATCH", "/api/v1/admin/users/alice", sysop, map[string]any{"level": 5, "flags": "+F"})
if code != 200 || m["level"] != 5.0 || m["flags"] != "F" {
t.Fatalf("set: %d %v", code, m)
}
if code, _, _ := s.do("PATCH", "/api/v1/admin/users/alice", sysop, map[string]any{"level": 300}); code != 400 {
t.Fatalf("level 300: %d", code)
}
// level and flags are the user's and the sysop's to see
bob := s.login("bob", "bobpass123")
if _, u, _ := s.do("GET", "/api/v1/users/alice", bob, nil); u["level"] != nil || u["flags"] != nil {
t.Errorf("bob sees alice's access: %v", u)
}
if _, u, _ := s.do("GET", "/api/v1/users/alice", alice, nil); u["level"] != 5.0 {
t.Errorf("alice's own: %v", u)
}
// an area for level 20: hidden from alice, its messages too
_, _, list := s.do("GET", "/api/v1/areas", alice, nil)
before := len(list)
_, _, all := s.do("GET", "/api/v1/areas", sysop, nil)
id := int(all[0].(map[string]any)["id"].(float64))
code, m, _ = s.do("PATCH", fmt.Sprintf("/api/v1/admin/areas/%d", id), sysop,
map[string]any{"read_require": "20", "post_require": "20 F"})
if code != 200 || m["read_require"] != "20" {
t.Fatalf("require: %d %v", code, m)
}
if code, _, _ := s.do("PATCH", fmt.Sprintf("/api/v1/admin/areas/%d", id), sysop, map[string]any{"read_require": "300"}); code != 400 {
t.Fatalf("a bad requirement: %d", code)
}
_, _, list = s.do("GET", "/api/v1/areas", alice, nil)
if len(list) != before-1 {
t.Errorf("alice sees %d areas, was %d", len(list), before)
}
if code, _, _ := s.do("GET", fmt.Sprintf("/api/v1/areas/%d/messages", id), alice, nil); code != 404 {
t.Errorf("alice read a hidden area: %d", code)
}
if code, _, _ := s.do("POST", fmt.Sprintf("/api/v1/areas/%d/messages", id), bob, map[string]any{"subject": "s", "body": "b"}); code != 403 {
t.Errorf("bob posted without F: %d", code)
}
}
+7 -7
View File
@@ -51,9 +51,9 @@ var ops = []op{
{"GET", "/api/v1/admin/pages", "Callers paging the sysop", "sysop", "", "Pages", 200},
{"POST", "/api/v1/admin/pages/{node}/answer", "Answer a page (needs an open stream; node 0: the longest waiting)", "sysop", "", "PageRes", 200},
{"POST", "/api/v1/admin/users", "Add a user", "sysop", "NewUser", "User", 201},
{"PATCH", "/api/v1/admin/users/{name}", "Lock, unlock, make sysop, set password or location", "sysop", "PatchUser", "User", 200},
{"PATCH", "/api/v1/admin/users/{name}", "Lock, unlock, make sysop, set password, location, level or flags", "sysop", "PatchUser", "User", 200},
{"POST", "/api/v1/admin/areas", "Add a message area", "sysop", "NewArea", "Area", 201},
{"PATCH", "/api/v1/admin/areas/{id}", "Set an area's newsgroup or echo tag (\"\": none)", "sysop", "PatchArea", "Area", 200},
{"PATCH", "/api/v1/admin/areas/{id}", "Set an area's newsgroup, echo tag or access requirements (\"\": none)", "sysop", "PatchArea", "Area", 200},
{"POST", "/api/v1/admin/nodes/{n}/kick", "Throw a caller off", "sysop", "", "", 204},
{"GET", "/api/v1/admin/fido", "FidoNet: addresses, links, files waiting", "sysop", "", "Object", 200},
{"POST", "/api/v1/admin/fido/poll", "Call the FidoNet links now", "sysop", "", "Object", 202},
@@ -87,15 +87,15 @@ var schemas = map[string]any{
"System": obj(map[string]any{"name": str, "sysop": str, "location": str, "motd": str, "users": num, "messages": num, "areas": num, "online": num, "features": map[string]any{"type": "object"}}),
"Node": obj(map[string]any{"node": num, "user": str, "via": str, "since": date, "doing": str, "terminal": str}),
"Nodes": arr("Node"),
"User": obj(map[string]any{"name": str, "location": str, "sysop": boo, "created": date, "last_login": date, "calls": num, "posts": num, "node": num, "locked": boo}),
"User": obj(map[string]any{"name": str, "location": str, "sysop": boo, "created": date, "last_login": date, "calls": num, "posts": num, "node": num, "locked": boo, "level": num, "flags": str}),
"Users": arr("User"),
"Me": obj(map[string]any{"user": ref("User"), "unread_mail": num, "scopes": map[string]any{"type": "array", "items": str}}),
"Me": obj(map[string]any{"user": ref("User"), "unread_mail": num, "access": map[string]any{"type": "object"}, "scopes": map[string]any{"type": "array", "items": str}}),
"PatchMe": obj(map[string]any{"location": str, "old_password": str, "new_password": str}),
"SSHKey": obj(map[string]any{"id": num, "type": str, "fingerprint": str, "comment": str, "key": str, "created": date, "last_used": date}),
"SSHKeys": arr("SSHKey"),
"NewSSHKey": obj(map[string]any{"key": str}, "key"),
"Tokens": map[string]any{"type": "array", "items": obj(map[string]any{"id": num, "name": str, "scopes": map[string]any{"type": "array", "items": str}, "session": boo, "created": date, "expires": date, "last_used": date, "current": boo})},
"Area": obj(map[string]any{"id": num, "name": str, "description": str, "sysop_only": boo, "newsgroup": str, "echo_tag": str, "messages": num, "first_id": num, "last_id": num, "unread": num, "last_read": num, "can_post": boo}),
"Area": obj(map[string]any{"id": num, "name": str, "description": str, "sysop_only": boo, "newsgroup": str, "echo_tag": str, "messages": num, "first_id": num, "last_id": num, "unread": num, "last_read": num, "can_post": boo, "read_require": str, "post_require": str}),
"Areas": arr("Area"),
"Message": obj(map[string]any{"id": num, "area": num, "from": str, "to": str, "subject": str, "body": str, "reply_to": num, "created": date, "message_id": str, "ftn_msgid": str, "read": boo}),
"Messages": arr("Message"),
@@ -113,9 +113,9 @@ var schemas = map[string]any{
"PageRes": obj(map[string]any{"told": num, "room": str, "waiting": boo, "node": num}),
"Pages": map[string]any{"type": "array", "items": obj(map[string]any{"node": num, "user": str, "reason": str, "since": date})},
"NewUser": obj(map[string]any{"name": str, "password": str, "location": str, "sysop": boo}, "name", "password"),
"PatchUser": obj(map[string]any{"locked": boo, "sysop": boo, "password": str, "location": str}),
"PatchUser": obj(map[string]any{"locked": boo, "sysop": boo, "password": str, "location": str, "level": num, "flags": str}),
"NewArea": obj(map[string]any{"name": str, "description": str, "sysop_only": boo}, "name"),
"PatchArea": obj(map[string]any{"newsgroup": str, "echo_tag": str}),
"PatchArea": obj(map[string]any{"newsgroup": str, "echo_tag": str, "read_require": str, "post_require": str}),
"EventStream": map[string]any{"type": "string", "description": "text/event-stream: events welcome, said, emoted, joined, left, private, paged, notice, mail; data is the Event of proto/bbs.proto in its JSON"},
"Object": map[string]any{"type": "object"},
}
+113 -13
View File
@@ -86,6 +86,19 @@ type userJSON struct {
Posts int `json:"posts"`
Node int `json:"node,omitempty"` // online on, now
Locked bool `json:"locked,omitempty"`
Level *int `json:"level,omitempty"` // to sysops and the user
Flags string `json:"flags,omitempty"`
}
// userView is a user as the request's user may see them: their access
// only to sysops and themselves.
func (s *Server) userView(r *http.Request, u *store.User) userJSON {
j := s.userOut(u)
if me := whoOf(r).user; me != nil && (me.Sysop || me.ID == u.ID) {
level := u.Level
j.Level, j.Flags = &level, u.Flags
}
return j
}
func (s *Server) userOut(u *store.User) userJSON {
@@ -125,6 +138,8 @@ type areaJSON struct {
Unread int `json:"unread"`
LastRead int64 `json:"last_read"`
CanPost bool `json:"can_post"`
ReadReq string `json:"read_require,omitempty"`
PostReq string `json:"post_require,omitempty"`
}
type messageJSON struct {
@@ -283,9 +298,21 @@ func (s *Server) me(w http.ResponseWriter, r *http.Request) {
fail(w, http.StatusNotFound, "no such user")
return
}
j := s.userOut(u)
j := s.userView(r, u)
unread, _ := s.B.Store.UnreadMail(u.ID)
writeJSON(w, http.StatusOK, map[string]any{"user": j, "unread_mail": unread,
lvl := s.B.LevelOf(u)
access := map[string]any{"level": u.Level, "name": lvl.Name, "flags": u.Flags,
"downloads_today": u.DownloadsToday(), "minutes_today": u.TimeToday() / 60,
"post": lvl.Post, "mail": lvl.Mail, "chat": lvl.Chat, "page": lvl.Page,
"download": lvl.Download, "upload": lvl.Upload, "doors": lvl.Doors,
"validated": u.Sysop || u.Level >= s.B.ValidatedLevel}
if lvl.Downloads > 0 {
access["downloads_per_day"] = lvl.Downloads
}
if lvl.Time > 0 {
access["minutes_per_day"] = int(lvl.Time.Minutes())
}
writeJSON(w, http.StatusOK, map[string]any{"user": j, "unread_mail": unread, "access": access,
"scopes": strings.Fields(whoOf(r).token.Scopes)})
}
@@ -403,7 +430,7 @@ func (s *Server) users(w http.ResponseWriter, r *http.Request) {
out := []userJSON{}
for _, u := range us {
if !u.Locked || sysop {
out = append(out, s.userOut(u))
out = append(out, s.userView(r, u))
}
}
writeJSON(w, http.StatusOK, out)
@@ -415,7 +442,7 @@ func (s *Server) user(w http.ResponseWriter, r *http.Request) {
fail(w, http.StatusNotFound, "no such user")
return
}
writeJSON(w, http.StatusOK, s.userOut(u))
writeJSON(w, http.StatusOK, s.userView(r, u))
}
// --- message areas
@@ -425,7 +452,7 @@ func (s *Server) areaOut(r *http.Request, a *store.Area) areaJSON {
unread, _ := s.B.Store.NewCount(u.ID, a.ID)
last, _ := s.B.Store.LastRead(u.ID, a.ID)
return areaJSON{a.ID, a.Name, a.Description, a.SysopOnly, a.Newsgroup, a.EchoTag, a.Messages,
a.FirstID, a.LastID, unread, last, bbs.CanPost(u, a)}
a.FirstID, a.LastID, unread, last, s.B.CanPost(u, a), a.ReadReq, a.PostReq}
}
func (s *Server) areas(w http.ResponseWriter, r *http.Request) {
@@ -436,7 +463,9 @@ func (s *Server) areas(w http.ResponseWriter, r *http.Request) {
}
out := []areaJSON{}
for _, a := range as {
out = append(out, s.areaOut(r, a))
if s.B.CanRead(whoOf(r).user, a) {
out = append(out, s.areaOut(r, a))
}
}
writeJSON(w, http.StatusOK, out)
}
@@ -448,7 +477,7 @@ func (s *Server) areaByPath(w http.ResponseWriter, r *http.Request) *store.Area
return nil
}
a, err := s.B.Store.Area(id)
if err != nil {
if err != nil || !s.B.CanRead(whoOf(r).user, a) {
fail(w, http.StatusNotFound, "no such area")
return nil
}
@@ -495,6 +524,11 @@ func (s *Server) message(w http.ResponseWriter, r *http.Request) {
return
}
m, err := s.B.Store.Message(id)
if err == nil {
if a, err2 := s.B.Store.Area(m.AreaID); err2 != nil || !s.B.CanRead(whoOf(r).user, a) {
err = store.ErrNotFound
}
}
if err != nil {
fail(w, http.StatusNotFound, "no such message")
return
@@ -522,7 +556,7 @@ func (s *Server) post(w http.ResponseWriter, r *http.Request) {
return
}
}
if !bbs.CanPost(whoOf(r).user, a) {
if !s.B.CanPost(whoOf(r).user, a) {
fail(w, http.StatusForbidden, "only the sysop posts here")
return
}
@@ -625,10 +659,14 @@ func (s *Server) fileAreas(w http.ResponseWriter, r *http.Request) {
}
fas, _ := s.B.Store.FileAreas()
out := []map[string]any{}
u := whoOf(r).user
for _, fa := range fas {
if !s.B.CanDownload(u, fa) && !s.B.CanUpload(u, fa) {
continue
}
out = append(out, map[string]any{"id": fa.ID, "name": fa.Name, "description": fa.Description,
"sysop_upload": fa.SysopUpload, "files": fa.Files,
"can_upload": files.CanUpload(whoOf(r).user, fa)})
"can_download": s.B.CanDownload(u, fa), "can_upload": s.B.CanUpload(u, fa)})
}
writeJSON(w, http.StatusOK, out)
}
@@ -639,7 +677,8 @@ func (s *Server) fileAreaByPath(w http.ResponseWriter, r *http.Request) *store.F
}
id, ok := pathID(r, "id")
fa, err := s.B.Store.FileArea(id)
if !ok || err != nil {
u := whoOf(r).user
if !ok || err != nil || !s.B.CanDownload(u, fa) && !s.B.CanUpload(u, fa) {
fail(w, http.StatusNotFound, "no such file area")
return nil
}
@@ -665,6 +704,12 @@ func (s *Server) fileByPath(w http.ResponseWriter, r *http.Request) *store.File
}
id, ok := pathID(r, "id")
f, err := s.B.Store.FileByID(id)
if ok && err == nil {
fa, err2 := s.B.Store.FileArea(f.AreaID)
if u := whoOf(r).user; err2 != nil || !s.B.CanDownload(u, fa) && !s.B.CanUpload(u, fa) {
err = store.ErrNotFound
}
}
if !ok || err != nil {
fail(w, http.StatusNotFound, "no such file")
return nil
@@ -683,6 +728,19 @@ func (s *Server) download(w http.ResponseWriter, r *http.Request) {
if f == nil {
return
}
u := whoOf(r).user
if fa, err := s.B.Store.FileArea(f.AreaID); err != nil {
fail(w, http.StatusNotFound, "no such file")
return
} else if r.Header.Get("Range") == "" {
if err := s.B.MayDownload(u, fa); err != nil {
fail(w, http.StatusForbidden, err.Error())
return
}
} else if !s.B.CanDownload(u, fa) {
fail(w, http.StatusForbidden, bbs.ErrNotAllowed.Error())
return
}
fh, err := s.B.Files.OpenFile(f)
if err != nil {
fail(w, http.StatusNotFound, "the file is missing")
@@ -693,7 +751,7 @@ func (s *Server) download(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Disposition", `attachment; filename="`+f.Name+`"`)
w.Header().Set("Digest", "sha-256="+f.SHA256)
if r.Header.Get("Range") == "" {
s.B.Store.CountDownload(f.ID)
s.B.Downloaded(u, f)
}
http.ServeContent(w, r, f.Name, f.Created, fh)
}
@@ -705,6 +763,10 @@ func (s *Server) upload(w http.ResponseWriter, r *http.Request) {
return
}
u := whoOf(r).user
if !s.B.CanUpload(u, fa) {
fail(w, http.StatusForbidden, "your access does not allow uploading here")
return
}
up, err := s.B.Files.Upload(u, fa, r.URL.Query().Get("name"), bbs.Clean(r.URL.Query().Get("description"), 60))
if err != nil {
status := http.StatusBadRequest
@@ -863,7 +925,7 @@ func (s *Server) addUser(w http.ResponseWriter, r *http.Request) {
return
}
s.B.Log.Printf("http: %s added user %s", whoOf(r).user.Name, u.Name)
writeJSON(w, http.StatusCreated, s.userOut(u))
writeJSON(w, http.StatusCreated, s.userView(r, u))
}
func (s *Server) patchUser(w http.ResponseWriter, r *http.Request) {
@@ -877,6 +939,8 @@ func (s *Server) patchUser(w http.ResponseWriter, r *http.Request) {
Sysop *bool `json:"sysop"`
Password *string `json:"password"`
Location *string `json:"location"`
Level *int `json:"level"`
Flags *string `json:"flags"` // "AB", or an edit: "+A -B"
}
if !s.decode(w, r, &req) {
return
@@ -897,9 +961,24 @@ func (s *Server) patchUser(w http.ResponseWriter, r *http.Request) {
if req.Location != nil {
s.B.Store.SetLocation(u.ID, bbs.Clean(*req.Location, bbs.MaxLocationLen))
}
if req.Level != nil {
if *req.Level < 0 || *req.Level > bbs.MaxLevel {
fail(w, http.StatusBadRequest, "a level is 0 to 255")
return
}
s.B.Store.SetLevel(u.ID, *req.Level)
}
if req.Flags != nil {
fl, err := bbs.EditFlags(u.Flags, *req.Flags)
if err != nil {
fail(w, http.StatusBadRequest, err.Error())
return
}
s.B.Store.SetFlags(u.ID, fl)
}
s.B.Log.Printf("http: %s changed user %s", whoOf(r).user.Name, u.Name)
u, _ = s.B.Store.UserByID(u.ID)
writeJSON(w, http.StatusOK, s.userOut(u))
writeJSON(w, http.StatusOK, s.userView(r, u))
}
func (s *Server) addArea(w http.ResponseWriter, r *http.Request) {
@@ -937,6 +1016,8 @@ func (s *Server) patchArea(w http.ResponseWriter, r *http.Request) {
var req struct {
Newsgroup *string `json:"newsgroup"`
EchoTag *string `json:"echo_tag"`
ReadReq *string `json:"read_require"`
PostReq *string `json:"post_require"`
}
if !s.decode(w, r, &req) {
return
@@ -962,6 +1043,25 @@ func (s *Server) patchArea(w http.ResponseWriter, r *http.Request) {
return
}
}
if req.ReadReq != nil || req.PostReq != nil {
read, post := a.ReadReq, a.PostReq
if req.ReadReq != nil {
read = *req.ReadReq
}
if req.PostReq != nil {
post = *req.PostReq
}
for _, q := range []string{read, post} {
if _, err := bbs.ParseRequire(q); err != nil {
fail(w, http.StatusBadRequest, err.Error())
return
}
}
if err := s.B.Store.SetAreaRequire(a.ID, read, post); err != nil {
fail(w, http.StatusInternalServerError, "the system is in trouble")
return
}
}
a, _ = s.B.Store.Area(a.ID)
writeJSON(w, http.StatusOK, s.areaOut(r, a))
}
+291
View File
@@ -0,0 +1,291 @@
package bbs
import (
"errors"
"fmt"
"sort"
"strconv"
"strings"
"time"
"github.com/Neo-Desktop/bbs-sec/internal/door"
"github.com/Neo-Desktop/bbs-sec/internal/files"
"github.com/Neo-Desktop/bbs-sec/internal/store"
)
// MaxLevel is the highest access level.
const MaxLevel = 255
// ErrNotAllowed: the user's access does not allow it.
var ErrNotAllowed = errors.New("your access does not allow that")
// Require is an access requirement: a level at least, flags to have and
// flags not to have, or the sysop. Sysops meet every one.
type Require struct {
Level int
Has string // flags all needed
Lacks string // flags none of which may be had
Sysop bool
}
// ParseRequire reads a requirement: terms separated by spaces, all of
// which must hold: a number (that level or higher), letters (those flags),
// !letters (none of those flags), "sysop". "" is anyone.
func ParseRequire(s string) (Require, error) {
var r Require
for _, f := range strings.Fields(s) {
switch {
case strings.EqualFold(f, "sysop"):
r.Sysop = true
case f[0] >= '0' && f[0] <= '9':
n, err := strconv.Atoi(f)
if err != nil || n < 0 || n > MaxLevel {
return Require{}, fmt.Errorf("%q: a level is 0 to %d", f, MaxLevel)
}
r.Level = max(r.Level, n)
case f[0] == '!':
fl, ok := flagSet(f[1:])
if !ok || fl == "" {
return Require{}, fmt.Errorf("%q: flags are letters A to Z", f)
}
r.Lacks = mergeFlags(r.Lacks, fl)
default:
fl, ok := flagSet(f)
if !ok {
return Require{}, fmt.Errorf("%q: not a level, flags, !flags or sysop", f)
}
r.Has = mergeFlags(r.Has, fl)
}
}
return r, nil
}
// MustRequire reads a requirement known to be good ("" if not).
func MustRequire(s string) Require {
r, err := ParseRequire(s)
if err != nil {
return Require{Sysop: true} // a bad one shuts everyone but the sysop out
}
return r
}
// String writes the requirement as ParseRequire reads it.
func (r Require) String() string {
var parts []string
if r.Sysop {
parts = append(parts, "sysop")
}
if r.Level > 0 {
parts = append(parts, strconv.Itoa(r.Level))
}
if r.Has != "" {
parts = append(parts, r.Has)
}
if r.Lacks != "" {
parts = append(parts, "!"+r.Lacks)
}
return strings.Join(parts, " ")
}
// Allows reports whether u meets the requirement (nil, a caller not
// logged in, meets only the empty one).
func (r Require) Allows(u *store.User) bool {
if u != nil && u.Sysop {
return true
}
if u == nil {
return r == Require{}
}
if r.Sysop || u.Locked || u.Level < r.Level {
return false
}
for _, c := range r.Has {
if !strings.ContainsRune(u.Flags, c) {
return false
}
}
for _, c := range r.Lacks {
if strings.ContainsRune(u.Flags, c) {
return false
}
}
return true
}
// flagSet is flags as kept: upper case letters, each once, in order.
func flagSet(s string) (string, bool) {
var seen [26]bool
for _, c := range strings.ToUpper(s) {
if c < 'A' || c > 'Z' {
return "", false
}
seen[c-'A'] = true
}
var b strings.Builder
for i, ok := range seen {
if ok {
b.WriteByte(byte('A' + i))
}
}
return b.String(), true
}
func mergeFlags(a, b string) string {
s, _ := flagSet(a + b)
return s
}
// EditFlags changes flags by an edit: "+AB -C" adds A and B and takes C
// away; letters with no sign are the flags (all of them); "" is none.
func EditFlags(flags, edit string) (string, error) {
edit = strings.TrimSpace(edit)
if edit == "" {
return "", nil // none
}
if edit[0] != '+' && edit[0] != '-' {
fl, ok := flagSet(edit)
if !ok {
return "", errors.New("flags are letters A to Z")
}
return fl, nil
}
have := map[rune]bool{}
for _, c := range flags {
have[c] = true
}
sign := '+'
for _, c := range strings.ToUpper(edit) {
switch {
case c == '+' || c == '-':
sign = c
case c == ' ':
case c >= 'A' && c <= 'Z':
have[c] = sign == '+'
default:
return "", errors.New("flags are letters A to Z, after + or -")
}
}
var b strings.Builder
for c := 'A'; c <= 'Z'; c++ {
if have[c] {
b.WriteRune(c)
}
}
return b.String(), nil
}
// Level is what a range of access levels may do ([level N]): from Num up
// to the next.
type Level struct {
Num int
Name string
Time time.Duration // online a day (0: no limit)
Downloads int // files a day (0: no limit)
Post bool // in message areas
Mail bool // mail to users other than sysops
Chat bool
Page bool // the sysop
Download bool
Upload bool
Doors bool
}
// AllowAll is a level with no limits.
func AllowAll(num int, name string) Level {
return Level{Num: num, Name: name, Post: true, Mail: true, Chat: true, Page: true,
Download: true, Upload: true, Doors: true}
}
// SortLevels orders levels by their numbers.
func SortLevels(ls []Level) { sort.Slice(ls, func(i, j int) bool { return ls[i].Num < ls[j].Num }) }
// LevelOf is what u's level may do: the [level] at or below it; sysops,
// and users under no [level], have no limits.
func (b *BBS) LevelOf(u *store.User) Level {
if u == nil {
return Level{Name: "not logged in"}
}
if u.Sysop {
return AllowAll(u.Level, "Sysop")
}
var out *Level
for i := range b.Levels {
if b.Levels[i].Num <= u.Level {
out = &b.Levels[i]
}
}
if out == nil {
return AllowAll(u.Level, fmt.Sprintf("Level %d", u.Level))
}
l := *out
return l
}
// CanRead reports whether u may read area a.
func (b *BBS) CanRead(u *store.User, a *store.Area) bool {
return u != nil && MustRequire(a.ReadReq).Allows(u)
}
// CanPost reports whether u may post in area a.
func (b *BBS) CanPost(u *store.User, a *store.Area) bool {
if u == nil || !b.CanRead(u, a) {
return false
}
if u.Sysop {
return true
}
return !a.SysopOnly && b.LevelOf(u).Post && MustRequire(a.PostReq).Allows(u)
}
// CanDownload reports whether u may download from file area a (the daily
// limit aside: see MayDownload).
func (b *BBS) CanDownload(u *store.User, a *store.FileArea) bool {
return u != nil && !u.Locked && b.LevelOf(u).Download && MustRequire(a.DownloadReq).Allows(u)
}
// CanUpload reports whether u may upload into file area a.
func (b *BBS) CanUpload(u *store.User, a *store.FileArea) bool {
return files.CanUpload(u, a) && b.LevelOf(u).Upload && MustRequire(a.UploadReq).Allows(u)
}
// MayDownload says why u may not download from a now, nil if they may.
func (b *BBS) MayDownload(u *store.User, a *store.FileArea) error {
if !b.CanDownload(u, a) {
return ErrNotAllowed
}
if l := b.LevelOf(u); l.Downloads > 0 && u.DownloadsToday() >= l.Downloads {
return fmt.Errorf("that is your %d downloads for today", l.Downloads)
}
return nil
}
// Downloaded counts a download of f by u (u nil: anonymous, as gopher's).
func (b *BBS) Downloaded(u *store.User, f *store.File) {
b.Store.CountDownload(f.ID)
if u != nil && u.ID != 0 {
b.Store.CountUserDownload(u.ID)
u.DLCount, u.DLDay = u.DownloadsToday()+1, store.Today()
}
}
// CanDoor reports whether u may open door d.
func (b *BBS) CanDoor(u *store.User, d *door.Door) bool {
if u == nil {
return false
}
if u.Sysop {
return true
}
return !d.SysopOnly && b.LevelOf(u).Doors && MustRequire(d.Require).Allows(u)
}
// Validate raises a waiting user to the validated level (no lower than
// they are).
func (b *BBS) Validate(u *store.User, by string) error {
level := max(b.ValidatedLevel, u.Level)
if err := b.Store.SetLevel(u.ID, level); err != nil {
return err
}
b.Log.Printf("%s validated %s (level %d)", by, u.Name, level)
return nil
}
+214
View File
@@ -0,0 +1,214 @@
package bbs
import (
"strings"
"testing"
"time"
"github.com/Neo-Desktop/bbs-sec/internal/door"
"github.com/Neo-Desktop/bbs-sec/internal/store"
)
func TestRequire(t *testing.T) {
alice := &store.User{ID: 1, Level: 30, Flags: "AF"}
low := &store.User{ID: 2, Level: 10}
sysop := &store.User{ID: 3, Sysop: true}
locked := &store.User{ID: 4, Level: 99, Locked: true}
for _, c := range []struct {
req string
alice, low, sysop, lock bool
}{
{"", true, true, true, false}, // a locked user meets nothing
{"20", true, false, true, false},
{"30 F", true, false, true, false},
{"fa", true, false, true, false},
{"20 B", false, false, true, false},
{"!F", false, true, true, false},
{"10 !B", true, true, true, false},
{"sysop", false, false, true, false},
} {
r, err := ParseRequire(c.req)
if err != nil {
t.Fatalf("%q: %v", c.req, err)
}
if r.Allows(alice) != c.alice || r.Allows(low) != c.low || r.Allows(sysop) != c.sysop || r.Allows(locked) != c.lock {
t.Errorf("%q (%s): alice %v low %v sysop %v locked %v", c.req, r, r.Allows(alice), r.Allows(low), r.Allows(sysop), r.Allows(locked))
}
if r2, _ := ParseRequire(r.String()); r2 != r {
t.Errorf("%q: %q reads back as %+v", c.req, r.String(), r2)
}
}
for _, bad := range []string{"256", "-1", "A1", "!", "!7", "9x"} {
if _, err := ParseRequire(bad); err == nil {
t.Errorf("%q taken", bad)
}
}
if MustRequire("bad!").Allows(alice) || !MustRequire("bad!").Allows(sysop) {
t.Error("a bad requirement lets users in")
}
if (Require{}).Allows(nil) != true || MustRequire("1").Allows(nil) {
t.Error("no user")
}
for _, c := range []struct{ have, edit, want string }{
{"AC", "+B -C", "AB"}, {"AC", "zy", "YZ"}, {"", "+a+b", "AB"}, {"ABC", "-", "ABC"}, {"ABC", "", ""},
} {
if got, err := EditFlags(c.have, c.edit); err != nil || got != c.want {
t.Errorf("%q %q: %q %v", c.have, c.edit, got, err)
}
}
if _, err := EditFlags("", "+1"); err == nil {
t.Error("+1 taken")
}
}
func levelBBS(t *testing.T) (*BBS, map[string]*Node) {
b, nodes := chatBBS(t)
b.NewUserLevel, b.ValidatedLevel = 10, 20
newbie := AllowAll(10, "New")
newbie.Post, newbie.Mail, newbie.Chat = false, false, false
newbie.Time, newbie.Downloads = 30*time.Minute, 1
b.Levels = []Level{newbie, AllowAll(20, "Member")}
b.Levels[1].Downloads = 3
for name, n := range nodes {
u := n.User()
u.Level = map[string]int{"alice": 10, "bob": 20, "sysop": 0}[name]
b.Store.SetLevel(u.ID, u.Level)
}
return b, nodes
}
func TestLevels(t *testing.T) {
b, nodes := levelBBS(t)
alice, bob, sysop := nodes["alice"].User(), nodes["bob"].User(), nodes["sysop"].User()
if l := b.LevelOf(alice); l.Name != "New" || l.Post || l.Chat {
t.Errorf("alice: %+v", l)
}
if l := b.LevelOf(bob); l.Name != "Member" || !l.Post || l.Downloads != 3 {
t.Errorf("bob: %+v", l)
}
if l := b.LevelOf(&store.User{Level: 5}); l.Name != "Level 5" || !l.Post {
t.Errorf("under every level: %+v", l)
}
if l := b.LevelOf(sysop); l.Name != "Sysop" || l.Time != 0 {
t.Errorf("sysop: %+v", l)
}
gen, _ := b.Store.CreateArea("General", "", false)
mem, _ := b.Store.CreateArea("Members", "", false)
b.Store.SetAreaRequire(mem.ID, "20", "20 M")
mem, _ = b.Store.Area(mem.ID)
areas := func(u *store.User) string {
as, _ := b.AreasFor(u)
var names []string
for _, a := range as {
names = append(names, a.Name)
}
return strings.Join(names, ",")
}
if areas(alice) != "General" || areas(bob) != "General,Members" || areas(sysop) != "General,Members" {
t.Errorf("areas: %s / %s / %s", areas(alice), areas(bob), areas(sysop))
}
// alice's level may not post; bob may read Members but not post there without M
if _, err := nodes["alice"].Post(gen, "", "hi", []string{"x"}, 0); err == nil {
t.Error("alice posted")
}
if _, err := nodes["bob"].Post(mem, "", "hi", []string{"x"}, 0); err == nil {
t.Error("bob posted without M")
}
bob.Flags = "M"
if _, err := nodes["bob"].Post(mem, "", "hi", []string{"x"}, 0); err != nil {
t.Errorf("bob with M: %v", err)
}
// mail: alice only to the sysop
if err := nodes["alice"].SendMail("bob", "hi", []string{"x"}, 0); err == nil {
t.Error("alice mailed bob")
}
if err := nodes["alice"].SendMail("sysop", "validate me", []string{"please"}, 0); err != nil {
t.Errorf("alice to the sysop: %v", err)
}
// chat and paging
if _, err := nodes["alice"].JoinRoom("main"); err != ErrNotAllowed {
t.Errorf("alice chatted: %v", err)
}
b.Levels[0].Page = false
if _, _, err := nodes["alice"].PageSysop("hi"); err != ErrNotAllowed {
t.Errorf("alice paged: %v", err)
}
// files: download limits a day
fa, _ := b.Store.CreateFileArea("Uploads", "", false)
b.Store.SetFileAreaRequire(fa.ID, "", "20")
fa, _ = b.Store.FileArea(fa.ID)
if !b.CanDownload(alice, fa) || b.CanUpload(alice, fa) || !b.CanUpload(bob, fa) {
t.Error("file area access")
}
f := &store.File{ID: 99}
if err := b.MayDownload(alice, fa); err != nil {
t.Fatal(err)
}
b.Downloaded(alice, f)
if err := b.MayDownload(alice, fa); err == nil || !strings.Contains(err.Error(), "1 downloads") {
t.Errorf("a second download: %v", err)
}
if fresh, _ := b.Store.UserByID(alice.ID); fresh.DownloadsToday() != 1 {
t.Errorf("downloads today: %d", fresh.DownloadsToday())
}
// doors
d := &door.Door{Name: "lord", Require: "20"}
if b.CanDoor(alice, d) || !b.CanDoor(bob, d) {
t.Error("door access")
}
// validation
if err := b.Validate(alice, "test"); err != nil {
t.Fatal(err)
}
if fresh, _ := b.Store.UserByID(alice.ID); fresh.Level != 20 {
t.Errorf("validated: %d", fresh.Level)
}
if w, _ := b.Store.UsersBelow(20); len(w) != 0 {
t.Errorf("waiting: %v", w)
}
}
// TestTimeLimit: a call's time counts against the day; at its end the
// caller is warned and hung up.
func TestTimeLimit(t *testing.T) {
b, _ := levelBBS(t)
minCallTime = 300 * time.Millisecond
t.Cleanup(func() { minCallTime = time.Minute })
b.Levels[0].Time = 100 * time.Millisecond
kicked := make(chan bool, 1)
n, err := b.Enter(&Caller{Via: "test"}, func() { kicked <- true })
if err != nil {
t.Fatal(err)
}
if _, err := n.Login("alice", "password1"); err != nil {
t.Fatal(err)
}
if left, ok := n.TimeLeft(); !ok || left > 300*time.Millisecond {
t.Errorf("time left: %v %v", left, ok)
}
select {
case <-kicked:
case <-time.After(5 * time.Second):
t.Fatal("not hung up")
}
es := n.Pending()
if len(es) == 0 || !strings.Contains(es[len(es)-1].Text, "time is up") {
t.Errorf("events: %v", es)
}
n.Leave()
if u, _ := b.Store.UserByName("alice"); u.TimeToday() < 2 {
// at least the 2 seconds the hang up waits
t.Errorf("time today: %d", u.TimeToday())
}
// a sysop has no limit
s, _ := b.Enter(&Caller{Via: "test"}, nil)
s.Login("sysop", "password1")
if _, ok := s.TimeLeft(); ok {
t.Error("a sysop's time is limited")
}
s.Leave()
}
+44 -22
View File
@@ -37,23 +37,29 @@ type Settings struct {
ThrottleFails int // failures from one source ...
ThrottleTime time.Duration // ... within this lock it out for this
PageCommand []string // run when a page finds no sysop on
Levels []Level // [level N], by number
NewUserLevel int // a new user's level
ValidatedLevel int // a validated user's
}
// Defaults are the settings without a configuration.
func Defaults() Settings {
return Settings{
Name: "Go BBS",
Sysop: "Sysop",
Banner: "",
Goodbye: "Thanks for calling.",
NewUsers: true,
MaxNodes: 32,
Attempts: 3,
FailDelay: 3 * time.Second,
LoginTimeout: 2 * time.Minute,
IdleTimeout: 10 * time.Minute,
ThrottleFails: 10,
ThrottleTime: 10 * time.Minute,
Name: "Go BBS",
Sysop: "Sysop",
Banner: "",
Goodbye: "Thanks for calling.",
NewUsers: true,
NewUserLevel: 20,
ValidatedLevel: 20,
MaxNodes: 32,
Attempts: 3,
FailDelay: 3 * time.Second,
LoginTimeout: 2 * time.Minute,
IdleTimeout: 10 * time.Minute,
ThrottleFails: 10,
ThrottleTime: 10 * time.Minute,
}
}
@@ -147,6 +153,7 @@ type Node struct {
kick func()
chatOnce sync.Once
cs *chatState
clock *clock // the day's time limit, for a caller logged in
}
// ErrBusy: every node is taken.
@@ -172,6 +179,7 @@ func (b *BBS) Enter(c *Caller, kick func()) (*Node, error) {
// Leave gives the node back.
func (n *Node) Leave() {
n.stopClock()
n.leaveChat()
n.b.mu.Lock()
delete(n.b.nodes, n.Num)
@@ -384,6 +392,7 @@ func (n *Node) loggedIn(u *store.User, how string) (*store.User, error) {
return nil, err
}
n.SetUser(u)
n.startClock(u)
n.b.Stats.Logins.Add(1)
n.Doing("Main menu")
n.b.Log.Printf("node %d: %s logged in (%s, %s from %s)", n.Num, u.Name, how,
@@ -413,6 +422,10 @@ func (n *Node) Register(name, pw, location string) (*store.User, error) {
if err != nil {
return nil, err
}
if err := b.Store.SetLevel(u.ID, b.NewUserLevel); err != nil {
return nil, err
}
u.Level = b.NewUserLevel
// a new account counts against the source like a failure, so that
// one caller cannot make thousands
b.failed(n.Caller.Source)
@@ -437,19 +450,17 @@ func (b *BBS) MOTDText() string {
return text
}
// CanPost reports whether u may post in area a.
func CanPost(u *store.User, a *store.Area) bool {
return !a.SysopOnly || u.Sysop
}
// Post cleans and posts a message.
func (n *Node) Post(a *store.Area, to, subject string, body []string, replyTo int64) (int64, error) {
u := n.User()
if u == nil {
return 0, errors.New("not logged in")
}
if !CanPost(u, a) {
return 0, errors.New("only the sysop posts here")
if !n.b.CanPost(u, a) {
if a.SysopOnly {
return 0, errors.New("only the sysop posts here")
}
return 0, errors.New("your access does not allow posting here")
}
m := &store.Message{AreaID: a.ID, FromID: u.ID, From: u.Name,
To: Clean(to, MaxNameLen), Subject: Clean(subject, MaxSubjectLen),
@@ -478,7 +489,11 @@ func (n *Node) SendMail(to, subject string, body []string, replyTo int64) error
if u == nil {
return errors.New("not logged in")
}
mail := n.b.LevelOf(u).Mail
if name, addr, ok := SplitNetmail(to); ok {
if !mail {
return errors.New("your access allows mail only to the sysop")
}
return n.sendNetmail(u, name, addr, subject, body, replyTo)
}
rcpt, err := n.b.Store.UserByName(strings.TrimSpace(to))
@@ -488,6 +503,10 @@ func (n *Node) SendMail(to, subject string, body []string, replyTo int64) error
if err != nil {
return err
}
// a user who may not mail may still write to the sysop (to be validated)
if !mail && !rcpt.Sysop {
return errors.New("your access allows mail only to the sysop")
}
m := &store.Message{FromID: u.ID, From: u.Name, ToID: rcpt.ID, To: rcpt.Name,
Subject: Clean(subject, MaxSubjectLen), Body: CleanBody(body), ReplyTo: replyTo}
if m.Subject == "" {
@@ -566,13 +585,16 @@ func (b *BBS) AreasFor(u *store.User) ([]AreaNew, error) {
if err != nil {
return nil, err
}
out := make([]AreaNew, len(areas))
for i, a := range areas {
out := make([]AreaNew, 0, len(areas))
for _, a := range areas {
if !b.CanRead(u, a) {
continue
}
n, err := b.Store.NewCount(u.ID, a.ID)
if err != nil {
return nil, err
}
out[i] = AreaNew{a, n}
out = append(out, AreaNew{a, n})
}
return out, nil
}
+7
View File
@@ -176,6 +176,10 @@ func (n *Node) JoinRoom(name string) ([]Event, error) {
if strings.HasPrefix(name, "sysop-") && name != pageRoom(n.Num) && !u.Sysop {
return nil, ErrNotYours
}
// the room a page waits in is the page's, not chat
if name != pageRoom(n.Num) && !n.b.LevelOf(u).Chat {
return nil, ErrNotAllowed
}
if n.Room() == name {
return nil, nil
}
@@ -372,6 +376,9 @@ func (n *Node) PageSysop(reason string) (string, int, error) {
if u == nil {
return "", 0, errors.New("not logged in")
}
if !n.b.LevelOf(u).Page {
return "", 0, ErrNotAllowed
}
reason = Clean(reason, 60)
cs := n.chat()
cs.mu.Lock()
+83
View File
@@ -0,0 +1,83 @@
package bbs
import (
"fmt"
"sync"
"time"
"github.com/Neo-Desktop/bbs-sec/internal/store"
)
// minCallTime is the least a call is given, however little of the day is
// left: to read what came, and log off.
var minCallTime = time.Minute
// clock keeps a call's time against the user's day: it warns as the end
// nears, and hangs up at it.
type clock struct {
mu sync.Mutex
start time.Time
userID int64
end time.Time // zero: no limit
timers []*time.Timer
}
// startClock starts counting the call against u's day, with the limit of
// their level.
func (n *Node) startClock(u *store.User) {
c := &clock{start: time.Now(), userID: u.ID}
if limit := n.b.LevelOf(u).Time; limit > 0 {
left := limit - time.Duration(u.TimeToday())*time.Second
left = max(left, minCallTime)
c.end = c.start.Add(left)
for _, w := range []time.Duration{5 * time.Minute, time.Minute} {
if left > w {
w := w
c.timers = append(c.timers, time.AfterFunc(left-w, func() {
n.deliver(Event{Kind: Notice, Text: fmt.Sprintf("%d minute(s) left today.", int(w.Minutes())), Time: time.Now()})
}))
}
}
c.timers = append(c.timers, time.AfterFunc(left, func() {
n.deliver(Event{Kind: Notice, Text: "Your time is up for today.", Time: time.Now()})
n.b.Log.Printf("node %d: %s's time is up", n.Num, u.Name)
time.AfterFunc(2*time.Second, func() {
if n.kick != nil {
n.kick()
}
})
}))
}
n.b.mu.Lock()
n.clock = c
n.b.mu.Unlock()
}
// stopClock adds the call's time to the user's day.
func (n *Node) stopClock() {
n.b.mu.Lock()
c := n.clock
n.clock = nil
n.b.mu.Unlock()
if c == nil {
return
}
c.mu.Lock()
defer c.mu.Unlock()
for _, t := range c.timers {
t.Stop()
}
n.b.Store.AddTime(c.userID, int(time.Since(c.start).Seconds()))
}
// TimeLeft is the time the caller has left today; ok false if there is no
// limit.
func (n *Node) TimeLeft() (left time.Duration, ok bool) {
n.b.mu.Lock()
c := n.clock
n.b.mu.Unlock()
if c == nil || c.end.IsZero() {
return 0, false
}
return max(time.Until(c.end), 0), true
}
+29 -10
View File
@@ -6,23 +6,38 @@ import (
"time"
"github.com/Neo-Desktop/bbs-sec/internal/screens"
"github.com/Neo-Desktop/bbs-sec/internal/store"
)
// MenuItem is a key of a sysop's menu and what it does.
type MenuItem struct {
Key string // one character, upper case
Action string // see MenuActions; or door, menu, screen, area with Arg
Arg string
Label string // with @-codes
Key string // one character, upper case
Action string // see MenuActions; or door, menu, screen, area with Arg
Arg string
Label string // with @-codes
Require string // the access requirement ("": anyone)
}
// Menu is a sysop's menu ([menu NAME]); "main" replaces the built-in one.
type Menu struct {
Name string
Title string // with @-codes
Screen string // a display file shown instead of the item list ("": none)
Prompt string // ("": the command prompt)
Items []MenuItem
Name string
Title string // with @-codes
Screen string // a display file shown instead of the item list ("": none)
Prompt string // ("": the command prompt)
Items []MenuItem
Require string // to be taken into it ("": anyone)
}
// MenuFor is m with only the items u may choose.
func (b *BBS) MenuFor(m *Menu, u *store.User) *Menu {
out := *m
out.Items = nil
for _, it := range m.Items {
if MustRequire(it.Require).Allows(u) {
out.Items = append(out.Items, it)
}
}
return &out
}
// MenuActions are what a menu item may do by itself; door:NAME,
@@ -139,8 +154,12 @@ func ParseMenuItem(key, value string) (MenuItem, error) {
if len(k) != 1 || k[0] < '!' || k[0] > '~' {
return MenuItem{}, fmt.Errorf("%q: a menu key is one character", key)
}
value, req, _ := strings.Cut(value, "|")
if _, err := ParseRequire(req); err != nil {
return MenuItem{}, fmt.Errorf("%s: %v", key, err)
}
action, label, _ := strings.Cut(strings.TrimSpace(value), " ")
it := MenuItem{Key: string(k), Label: strings.TrimSpace(label)}
it := MenuItem{Key: string(k), Label: strings.TrimSpace(label), Require: strings.TrimSpace(req)}
if a, arg, ok := strings.Cut(action, ":"); ok {
switch a {
case "door", "menu", "area":
+9 -3
View File
@@ -37,6 +37,7 @@ type Door struct {
Charset string
TimeLimit time.Duration
SysopOnly bool
Require string // the access requirement ("": anyone)
Single bool // one caller at a time
PTY bool // run it on a pseudo-terminal, not pipes
Cleanup []string // run after it (expanded), e.g. docker rm -f
@@ -141,7 +142,12 @@ func (d *Door) Run(line Line, in *Info, utf8Term bool, idle time.Duration, logf
}
defer d.mu.Unlock()
}
in.TimeLeft = d.TimeLimit
// the door's limit, or the caller's time left today if less
limit := d.TimeLimit
if in.TimeLeft > 0 && (limit == 0 || in.TimeLeft < limit) {
limit = in.TimeLeft
}
in.TimeLeft = limit
in.CommType = d.CommType
if in.ComPort == 0 {
in.ComPort = 1
@@ -269,7 +275,7 @@ func (d *Door) Run(line Line, in *Info, utf8Term bool, idle time.Duration, logf
}()
// the caller's input to the door
deadline := time.Now().Add(d.TimeLimit)
deadline := time.Now().Add(limit)
lastKey := time.Now()
buf := make([]byte, 1024)
var pending []byte // a UTF-8 character cut in two
@@ -283,7 +289,7 @@ func (d *Door) Run(line Line, in *Info, utf8Term bool, idle time.Duration, logf
continue
default:
}
if d.TimeLimit > 0 && time.Now().After(deadline) {
if limit > 0 && time.Now().After(deadline) {
res.TimeUp = true
stop()
break
+8 -3
View File
@@ -35,8 +35,9 @@ type Info struct {
LastLogin time.Time
ANSI bool
Rows, Cols int
Baud int // the caller's line; 38400 for a network caller
TimeLeft time.Duration
Baud int // the caller's line; 38400 for a network caller
TimeLeft time.Duration // the caller's today (0: no limit; the door's own is less)
Level int // the caller's access level (0: 30)
BBSName string
SysopName string
ComPort int // the door's COM port: 1
@@ -44,11 +45,15 @@ type Info struct {
Now time.Time
}
// security is the level drop files give: 255 for sysops, 30 for others.
// security is the level drop files give: 255 for sysops, the caller's
// access level for others (30 if not said).
func (in *Info) security() int {
if in.Sysop {
return 255
}
if in.Level > 0 {
return in.Level
}
return 30
}
+14 -4
View File
@@ -228,6 +228,11 @@ var (
func (fs *fileSystem) anonymous() bool { return fs.user.ID == 0 }
// sees: an area the user may download from or upload into
func (fs *fileSystem) sees(a *store.FileArea) bool {
return fs.s.B.CanDownload(fs.user, a) || !fs.anonymous() && fs.s.B.CanUpload(fs.user, a)
}
// resolve splits a path into its area and file (nil for /, file nil for an
// area's directory).
func (fs *fileSystem) resolve(name string) (*store.FileArea, *store.File, error) {
@@ -240,7 +245,7 @@ func (fs *fileSystem) resolve(name string) (*store.FileArea, *store.File, error)
return nil, nil, os.ErrNotExist
}
a, err := fs.s.B.Store.FileAreaByName(parts[0])
if errors.Is(err, store.ErrNotFound) {
if errors.Is(err, store.ErrNotFound) || err == nil && !fs.sees(a) {
return nil, nil, os.ErrNotExist
} else if err != nil {
return nil, nil, err
@@ -310,7 +315,9 @@ func (fs *fileSystem) ReadDir(name string) ([]os.FileInfo, error) {
return nil, err
}
for _, a := range areas {
out = append(out, areaInfo(a))
if fs.sees(a) {
out = append(out, areaInfo(a))
}
}
return out, nil
}
@@ -335,6 +342,9 @@ func (fs *fileSystem) GetHandle(name string, flags int, offset int64) (ftpserver
if f == nil {
return nil, errors.New("not a file")
}
if err := fs.s.B.MayDownload(fs.user, a); err != nil {
return nil, fmt.Errorf("%w: %v", os.ErrPermission, err)
}
r, err := fs.s.B.Files.OpenFile(f)
if err != nil {
return nil, err
@@ -355,7 +365,7 @@ func (fs *fileSystem) GetHandle(name string, flags int, offset int64) (ftpserver
if offset != 0 || flags&os.O_APPEND != 0 {
return nil, fmt.Errorf("%w: uploads cannot be resumed or appended to", os.ErrPermission)
}
if fs.anonymous() {
if fs.anonymous() || !fs.s.B.CanUpload(fs.user, a) {
return nil, os.ErrPermission
}
up, err := fs.s.B.Files.Upload(fs.user, a, path.Base(path.Clean("/"+name)), "")
@@ -391,7 +401,7 @@ func (d *download) Write([]byte) (int, error) { return 0, os.ErrPermission }
func (d *download) Close() error {
if d.read > 0 {
d.fs.s.B.Store.CountDownload(d.f.ID)
d.fs.s.B.Downloaded(d.fs.user, d.f)
d.fs.s.B.Log.Printf("%s: %s downloaded %q (%d bytes)", d.fs.who, d.fs.user.Name, d.f.Name, d.read)
}
return d.file.Close()
+27 -4
View File
@@ -436,13 +436,31 @@ func (ss *session) authinfo(args []string) {
}
}
// groups are the newsgroups (areas that are)
// groups are the newsgroups (areas that are) this reader may see
func (ss *session) groups() []*store.Area {
gs, err := ss.s.Svc.B.Store.Newsgroups()
if err != nil {
return nil
}
return gs
var out []*store.Area
for _, a := range gs {
if ss.visible(a) {
out = append(out, a)
}
}
return out
}
// visible: a peer sees every newsgroup; a reader those their access lets
// them read; a reader not logged in those that need nothing
func (ss *session) visible(a *store.Area) bool {
switch {
case ss.peer != nil:
return true
case ss.user != nil:
return ss.s.Svc.B.CanRead(ss.user, a)
}
return a.ReadReq == ""
}
func status(a *store.Area, post bool) string {
@@ -508,7 +526,7 @@ func (ss *session) groupCmd(args []string, list bool) {
}
} else {
a, err := ss.s.Svc.B.Store.AreaByNewsgroup(args[0])
if err != nil {
if err != nil || !ss.visible(a) {
ss.reply(411, "No such newsgroup")
return
}
@@ -597,7 +615,7 @@ func (ss *session) selectArticle(args []string) (*store.Message, int64, bool) {
if len(args) > 0 && strings.HasPrefix(args[0], "<") {
m, err := st.MessageByMessageID(args[0])
if err == nil {
if a, err := st.Area(m.AreaID); err == nil && a.Newsgroup != "" {
if a, err := st.Area(m.AreaID); err == nil && a.Newsgroup != "" && ss.visible(a) {
return m, 0, true
}
}
@@ -688,6 +706,11 @@ func (ss *session) selectRange(args []string) ([]*store.Message, bool, bool) {
st := ss.s.Svc.B.Store
if len(args) > 0 && strings.HasPrefix(args[0], "<") {
m, err := st.MessageByMessageID(args[0])
if err == nil {
if a, err2 := st.Area(m.AreaID); err2 != nil || !ss.visible(a) {
err = store.ErrNotFound
}
}
if err != nil || m.MessageID == "" {
ss.reply(430, "No article with that message-id")
return nil, false, false
+2 -2
View File
@@ -155,8 +155,8 @@ func (s *Service) PostLocal(raw []byte, u *store.User) (*store.Message, error) {
if area == nil {
return nil, ErrNotHere
}
if !bbs.CanPost(u, area) {
return nil, fmt.Errorf("%w: only the sysop posts in %s", ErrRejected, area.Newsgroup)
if !s.B.CanPost(u, area) {
return nil, fmt.Errorf("%w: you may not post in %s", ErrRejected, area.Newsgroup)
}
m := s.message(a, area)
if strings.TrimSpace(news.Subject(a)) == "" {
+128
View File
@@ -0,0 +1,128 @@
package server
import (
"os"
"path/filepath"
"strings"
"testing"
"time"
"github.com/Neo-Desktop/bbs-sec/internal/bbs"
)
// TestValidation: a new user starts at new_user_level, may not chat or
// post and is told they wait; the sysop validates them from the BBS; then
// they may.
func TestValidation(t *testing.T) {
e := start(t, func(s *bbs.Settings) {
s.NewUserLevel, s.ValidatedLevel = 10, 20
newbie := bbs.AllowAll(10, "New user")
newbie.Post, newbie.Chat, newbie.Mail = false, false, false
newbie.Time = 30 * time.Minute
s.Levels = []bbs.Level{newbie, bbs.AllowAll(20, "Member")}
}, &Listener{Name: "modem", Kind: "raw", Address: "modem.sock", ANSI: "no"})
members, _ := e.b.Store.CreateArea("Members", "For members", false)
e.b.Store.SetAreaRequire(members.ID, "20", "")
d := e.dial("modem.sock")
d.expect("Name (or NEW): ")
d.send("new\r")
d.expect("give up): ")
d.send("Zed\r")
d.expect("Password (8 or more characters): ")
d.send("zedpassword\rzedpassword\r")
d.expect("calling from? ")
d.send("Mars\r")
d.expect("Welcome, Zed.")
d.expect("You have 30 minutes today.")
d.expect("waits for the sysop's validation")
d.expect("Command: ")
if strings.Contains(string(d.got), "[C] Chat") {
t.Errorf("chat offered: %q", d.got)
}
d.send("M")
d.expect("General")
d.expect("Area number")
if strings.Contains(string(d.got), "Members") {
t.Errorf("Members shown: %q", d.got)
}
d.send("Q\r")
d.expect("Command: ")
d.send("P")
d.expect("Access: level 10 (New user)")
d.expect("Today: 30 minutes left")
d.send("Q")
d.expect("Command: ")
s := login(e, "sysop", "sysoppass1")
s.send("V")
s.expect("Zed")
s.expect("[V]alidate (level 20)")
s.send("V")
s.expect("Validated.")
s.expect("No one else is waiting.")
if u, _ := e.b.Store.UserByName("zed"); u.Level != 20 {
t.Errorf("level %d", u.Level)
}
// Zed's next menu has what members have
d.send("\r")
d.expect("[C] Chat")
d.send("M")
d.expect("Members")
}
func TestLevelConfig(t *testing.T) {
load := func(body string) (*Config, error) {
p := filepath.Join(t.TempDir(), "bbs.conf")
os.WriteFile(p, []byte("[listen t]\ntype = telnet\naddress = :2300\n"+body), 0600)
return Load(p)
}
c, err := load(`[general]
new_user_level = 10
validated_level = 20
[level 20]
name = Member
time = 120
downloads = 20
[level 10]
name = New user
post = no
mail = no
[door lord]
command = /bin/true
require = 30 L
[menu main]
title = Main
m = areas Message areas
x = menu:extra Extras | 50 X
g = logoff Goodbye
[menu extra]
require = 50
w = who Who
`)
if err != nil {
t.Fatal(err)
}
s := c.Settings
if s.NewUserLevel != 10 || s.ValidatedLevel != 20 || len(s.Levels) != 2 || s.Levels[0].Name != "New user" ||
s.Levels[0].Post || !s.Levels[0].Chat || s.Levels[1].Time != 120*time.Minute || s.Levels[1].Downloads != 20 {
t.Errorf("%+v", s)
}
if c.Doors[0].Require != "30 L" || c.Menus["extra"].Require != "50" || c.Menus["main"].Items[1].Require != "50 X" {
t.Errorf("requires: %q %q %+v", c.Doors[0].Require, c.Menus["extra"].Require, c.Menus["main"].Items)
}
for body, want := range map[string]string{
"[level 300]\n": "[level 300]",
"[level x]\n": "[level x]",
"[level 10]\n[level 10]\n": "given twice",
"[level 10]\ntime = -1\n": "time",
"[general]\nnew_user_level = 30\nvalidated_level = 20\n": "below",
"[door d]\ncommand = /bin/true\nrequire = 9x\n": "require",
"[menu main]\nm = areas Areas | !\n": "flags",
} {
if _, err := load(body); err == nil || !strings.Contains(err.Error(), want) {
t.Errorf("%q: %v", body, err)
}
}
}
+4 -1
View File
@@ -92,6 +92,9 @@ func Load(path string) (*Config, error) {
if err := c.infoSections(cf); err != nil {
return nil, err
}
if err := c.levelSections(cf); err != nil {
return nil, err
}
if err := c.doorSections(cf); err != nil {
return nil, err
}
@@ -128,7 +131,7 @@ func Load(path string) (*Config, error) {
}
for _, s := range cf.Sections {
switch s.Kind {
case "general", "listen", "ftp", "news", "nntp", "peer", "fido", "binkp", "link", "door", "finger", "gopher", "menu", "strings", "http":
case "general", "listen", "ftp", "news", "nntp", "peer", "fido", "binkp", "link", "door", "finger", "gopher", "menu", "strings", "http", "level":
default:
return nil, fmt.Errorf("line %d: unknown section [%s]", s.Line, s.Kind)
}
+5 -2
View File
@@ -84,14 +84,17 @@ func menu(s *config.Section) (*bbs.Menu, error) {
return nil, errors.New("a menu needs a name: [menu main]")
}
m := &bbs.Menu{Name: name, Title: s.String("title", s.Name), Screen: s.String("screen", ""),
Prompt: s.String("prompt", "")}
Prompt: s.String("prompt", ""), Require: s.String("require", "")}
if _, err := bbs.ParseRequire(m.Require); err != nil {
return nil, fmt.Errorf("require: %v", err)
}
if m.Screen != "" && !screens.ValidName(m.Screen) {
return nil, errors.New("screen: a screen's name is lower case letters, digits, _ and -")
}
seen := map[string]bool{}
for _, k := range s.Keys() {
switch k {
case "title", "screen", "prompt":
case "title", "screen", "prompt", "require":
continue
}
it, err := bbs.ParseMenuItem(k, s.String(k, ""))
+5
View File
@@ -7,6 +7,7 @@ import (
"strings"
"time"
"github.com/Neo-Desktop/bbs-sec/internal/bbs"
"github.com/Neo-Desktop/bbs-sec/internal/config"
"github.com/Neo-Desktop/bbs-sec/internal/door"
)
@@ -69,6 +70,10 @@ func doorSection(s *config.Section) (*door.Door, error) {
if d.SysopOnly, err = s.Bool("sysop_only", false); err != nil {
return nil, err
}
d.Require = s.String("require", "")
if _, err := bbs.ParseRequire(d.Require); err != nil {
return nil, fmt.Errorf("require: %v", err)
}
if d.Single, err = s.Bool("single", false); err != nil {
return nil, err
}
+70
View File
@@ -0,0 +1,70 @@
package server
import (
"fmt"
"strconv"
"time"
"github.com/Neo-Desktop/bbs-sec/internal/bbs"
"github.com/Neo-Desktop/bbs-sec/internal/config"
)
// levelSections reads [level N] and [general]'s new_user_level and
// validated_level.
func (c *Config) levelSections(cf *config.File) error {
s := &c.Settings
g := cf.Get("general", "")
var err error
if s.NewUserLevel, err = g.Int("new_user_level", s.NewUserLevel, 0, bbs.MaxLevel); err != nil {
return fmt.Errorf("[general] %w", err)
}
if s.ValidatedLevel, err = g.Int("validated_level", max(s.ValidatedLevel, s.NewUserLevel), 0, bbs.MaxLevel); err != nil {
return fmt.Errorf("[general] %w", err)
}
if s.ValidatedLevel < s.NewUserLevel {
return fmt.Errorf("[general] validated_level (%d) is below new_user_level (%d)", s.ValidatedLevel, s.NewUserLevel)
}
seen := map[int]bool{}
for _, sec := range cf.All("level") {
l, err := level(sec)
if err != nil {
return fmt.Errorf("[level %s] %w", sec.Name, err)
}
if seen[l.Num] {
return fmt.Errorf("[level %s] given twice", sec.Name)
}
seen[l.Num] = true
s.Levels = append(s.Levels, l)
}
bbs.SortLevels(s.Levels)
if len(s.Levels) > 0 && s.Levels[0].Num > 0 {
c.Warnings = append(c.Warnings, fmt.Sprintf("levels under %d have no [level]: no limits", s.Levels[0].Num))
}
return nil
}
func level(sec *config.Section) (bbs.Level, error) {
n, err := strconv.Atoi(sec.Name)
if err != nil || n < 0 || n > bbs.MaxLevel {
return bbs.Level{}, fmt.Errorf("a level is a number, 0 to %d: [level 20]", bbs.MaxLevel)
}
l := bbs.AllowAll(n, sec.String("name", "Level "+sec.Name))
mins, err := sec.Int("time", 0, 0, 24*60)
if err != nil {
return l, err
}
l.Time = time.Duration(mins) * time.Minute
if l.Downloads, err = sec.Int("downloads", 0, 0, 100000); err != nil {
return l, err
}
for _, b := range []struct {
key string
p *bool
}{{"post", &l.Post}, {"mail", &l.Mail}, {"chat", &l.Chat}, {"page", &l.Page},
{"download", &l.Download}, {"upload", &l.Upload}, {"doors", &l.Doors}} {
if *b.p, err = sec.Bool(b.key, true); err != nil {
return l, err
}
}
return l, nil
}
+79
View File
@@ -0,0 +1,79 @@
package store
import "time"
// Today is the day as the daily counts keep it: YYYYMMDD, local time.
func Today() int {
y, m, d := time.Now().Date()
return y*10000 + int(m)*100 + d
}
// SetLevel sets a user's access level.
func (s *Store) SetLevel(id int64, level int) error {
return s.exec1(`UPDATE users SET level = ? WHERE id = ?`, level, id)
}
// SetFlags sets a user's access flags.
func (s *Store) SetFlags(id int64, flags string) error {
return s.exec1(`UPDATE users SET flags = ? WHERE id = ?`, flags, id)
}
// AddTime adds to a user's time online today (a new day starts at 0).
func (s *Store) AddTime(id int64, secs int) error {
day := Today()
return s.exec1(`UPDATE users SET time_used = CASE WHEN time_day = ? THEN time_used + ? ELSE ? END,
time_day = ? WHERE id = ?`, day, secs, secs, day, id)
}
// CountUserDownload counts a download of the user's today.
func (s *Store) CountUserDownload(id int64) error {
day := Today()
return s.exec1(`UPDATE users SET dl_count = CASE WHEN dl_day = ? THEN dl_count + 1 ELSE 1 END,
dl_day = ? WHERE id = ?`, day, day, id)
}
// TimeToday is the user's time online today, in seconds.
func (u *User) TimeToday() int {
if u.TimeDay != Today() {
return 0
}
return u.TimeUsed
}
// DownloadsToday is the user's downloads today.
func (u *User) DownloadsToday() int {
if u.DLDay != Today() {
return 0
}
return u.DLCount
}
// SetAreaRequire sets what reading and posting in an area require.
func (s *Store) SetAreaRequire(id int64, read, post string) error {
return s.exec1(`UPDATE areas SET read_req = ?, post_req = ? WHERE id = ?`, read, post, id)
}
// SetFileAreaRequire sets what downloading and uploading in a file area
// require.
func (s *Store) SetFileAreaRequire(id int64, download, upload string) error {
return s.exec1(`UPDATE file_areas SET download_req = ?, upload_req = ? WHERE id = ?`, download, upload, id)
}
// UsersBelow lists the users whose level is under level (and are not
// sysops or locked): those waiting to be validated.
func (s *Store) UsersBelow(level int) ([]*User, error) {
rows, err := s.db.Query(`SELECT `+userCols+` FROM users WHERE level < ? AND sysop = 0 AND locked = 0 ORDER BY id`, level)
if err != nil {
return nil, err
}
defer rows.Close()
var out []*User
for rows.Next() {
u, _, err := scanUser(rows)
if err != nil {
return nil, err
}
out = append(out, u)
}
return out, rows.Err()
}
+10
View File
@@ -19,6 +19,16 @@ func migrate(db *sql.DB) error {
{"messages", "ftn_msgid", "TEXT"},
{"messages", "ftn", "BLOB"},
{"mail", "ftn_msgid", "TEXT"},
{"users", "level", "INTEGER NOT NULL DEFAULT 20"},
{"users", "flags", "TEXT NOT NULL DEFAULT ''"},
{"users", "time_day", "INTEGER NOT NULL DEFAULT 0"},
{"users", "time_used", "INTEGER NOT NULL DEFAULT 0"},
{"users", "dl_day", "INTEGER NOT NULL DEFAULT 0"},
{"users", "dl_count", "INTEGER NOT NULL DEFAULT 0"},
{"areas", "read_req", "TEXT NOT NULL DEFAULT ''"},
{"areas", "post_req", "TEXT NOT NULL DEFAULT ''"},
{"file_areas", "download_req", "TEXT NOT NULL DEFAULT ''"},
{"file_areas", "upload_req", "TEXT NOT NULL DEFAULT ''"},
}
for _, a := range add {
var n int
+17 -6
View File
@@ -39,6 +39,11 @@ type User struct {
LastLogin time.Time
Logins int
Posts int
Level int // access level, 0-255
Flags string // access flags, letters A-Z
// today's (TimeDay, YYYYMMDD) time online in seconds, and downloads
TimeDay, TimeUsed int
DLDay, DLCount int
}
// Area is a message area.
@@ -47,6 +52,8 @@ type Area struct {
Name string
Description string
SysopOnly bool // only sysops post
ReadReq string // the access requirement to read it ("": anyone)
PostReq string // and to post
Newsgroup string // its newsgroup ("": not one)
EchoTag string // its FidoNet echo ("": not one)
Messages int
@@ -213,14 +220,15 @@ func HashPassword(pw string) (string, error) {
return string(h), err
}
const userCols = `id, name, password, location, sysop, locked, created, last_login, logins, posts`
const userCols = `id, name, password, location, sysop, locked, created, last_login, logins, posts,
level, flags, time_day, time_used, dl_day, dl_count`
func scanUser(row interface{ Scan(...any) error }) (*User, string, error) {
var u User
var pw string
var created, last int64
err := row.Scan(&u.ID, &u.Name, &pw, &u.Location, &u.Sysop, &u.Locked,
&created, &last, &u.Logins, &u.Posts)
&created, &last, &u.Logins, &u.Posts, &u.Level, &u.Flags, &u.TimeDay, &u.TimeUsed, &u.DLDay, &u.DLCount)
if errors.Is(err, sql.ErrNoRows) {
return nil, "", ErrNotFound
}
@@ -368,6 +376,7 @@ func (s *Store) DeleteArea(id int64) error {
}
const areaQuery = `SELECT a.id, a.name, a.description, a.sysop_only, COALESCE(a.newsgroup, ''), COALESCE(a.echotag, ''),
a.read_req, a.post_req,
(SELECT COUNT(*) FROM messages m WHERE m.area_id = a.id),
(SELECT COALESCE(MIN(m.id), 0) FROM messages m WHERE m.area_id = a.id),
(SELECT COALESCE(MAX(m.id), 0) FROM messages m WHERE m.area_id = a.id)
@@ -375,7 +384,7 @@ const areaQuery = `SELECT a.id, a.name, a.description, a.sysop_only, COALESCE(a.
func scanArea(row interface{ Scan(...any) error }) (*Area, error) {
var a Area
err := row.Scan(&a.ID, &a.Name, &a.Description, &a.SysopOnly, &a.Newsgroup, &a.EchoTag, &a.Messages,
err := row.Scan(&a.ID, &a.Name, &a.Description, &a.SysopOnly, &a.Newsgroup, &a.EchoTag, &a.ReadReq, &a.PostReq, &a.Messages,
&a.FirstID, &a.LastID)
if errors.Is(err, sql.ErrNoRows) {
return nil, ErrNotFound
@@ -605,7 +614,9 @@ type FileArea struct {
ID int64
Name string
Description string
SysopUpload bool // only sysops upload
SysopUpload bool // only sysops upload
DownloadReq string // the access requirement to download ("": anyone)
UploadReq string // and to upload
Files int
Bytes int64
}
@@ -651,14 +662,14 @@ func (s *Store) DeleteFileArea(id int64) error {
return s.exec1(`DELETE FROM file_areas WHERE id = ?`, id)
}
const fileAreaQuery = `SELECT a.id, a.name, a.description, a.sysop_upload,
const fileAreaQuery = `SELECT a.id, a.name, a.description, a.sysop_upload, a.download_req, a.upload_req,
(SELECT COUNT(*) FROM files f WHERE f.area_id = a.id),
(SELECT COALESCE(SUM(f.size), 0) FROM files f WHERE f.area_id = a.id)
FROM file_areas a`
func scanFileArea(row interface{ Scan(...any) error }) (*FileArea, error) {
var a FileArea
err := row.Scan(&a.ID, &a.Name, &a.Description, &a.SysopUpload, &a.Files, &a.Bytes)
err := row.Scan(&a.ID, &a.Name, &a.Description, &a.SysopUpload, &a.DownloadReq, &a.UploadReq, &a.Files, &a.Bytes)
if errors.Is(err, sql.ErrNoRows) {
return nil, ErrNotFound
}
+61
View File
@@ -0,0 +1,61 @@
package textui
import (
"fmt"
"strconv"
"github.com/Neo-Desktop/bbs-sec/internal/bbs"
)
// validate: the sysop goes through the users waiting to be validated.
func (s *session) validate() error {
t := s.t
waiting, err := s.b.Store.UsersBelow(s.b.ValidatedLevel)
if err != nil {
return err
}
for _, w := range waiting {
t.Println("")
t.Println(t.C(Cyan, w.Name) + t.C(Dim, fmt.Sprintf(" from %q, since %s, %d calls, level %d",
w.Location, w.Created.Format("2006-01-02"), w.Logins, w.Level)))
t.Print(fmt.Sprintf("[V]alidate (level %d), [L]evel..., [K] lock, [S]kip, [Q]uit: ", s.b.ValidatedLevel))
k, err := t.Key()
if err != nil {
return err
}
t.Println(string(k))
by := fmt.Sprintf("node %d: %s", s.n.Num, s.user.Name)
switch k {
case 'V':
if err := s.b.Validate(w, by); err != nil {
return err
}
t.Println(t.C(Green, "Validated."))
case 'L':
n, err := t.Input("Level (0-255): ", 3)
if err != nil {
return err
}
l, err := strconv.Atoi(n)
if err != nil || l < 0 || l > bbs.MaxLevel {
t.Println(t.C(Red, "That is not a level."))
continue
}
if err := s.b.Store.SetLevel(w.ID, l); err != nil {
return err
}
s.b.Log.Printf("%s set %s's level to %d", by, w.Name, l)
t.Println(t.C(Green, "Done."))
case 'K':
if err := s.b.Store.SetLocked(w.ID, true); err != nil {
return err
}
s.b.Log.Printf("%s locked %s", by, w.Name)
t.Println(t.C(Green, "Locked."))
case 'Q', '\r':
return nil
}
}
t.Println("No one else is waiting.")
return nil
}
+9 -3
View File
@@ -77,10 +77,11 @@ func (s *session) logoff() error {
// runMenu runs a menu of the sysop's until it is left (back) or the
// caller logs off.
func (s *session) runMenu(m *bbs.Menu, depth int) error {
func (s *session) runMenu(full *bbs.Menu, depth int) error {
vars := s.n.Vars()
for {
s.user = s.n.Refresh()
m := s.b.MenuFor(full, s.user)
title := screens.String(m.Title, vars)
s.n.Doing(title)
shown := false
@@ -159,7 +160,12 @@ func (s *session) do(it *bbs.MenuItem, depth int) error {
t.Println("Menus nest too deep.")
return nil
}
return s.runMenu(s.b.Menus[strings.ToLower(it.Arg)], depth+1)
sub := s.b.Menus[strings.ToLower(it.Arg)]
if !bbs.MustRequire(sub.Require).Allows(s.user) {
t.Println(t.C(Red, "That menu is not for you."))
return nil
}
return s.runMenu(sub, depth+1)
case "screen":
shown, err := s.screen(it.Arg)
if err != nil {
@@ -172,7 +178,7 @@ func (s *session) do(it *bbs.MenuItem, depth int) error {
return t.Pause()
case "area":
a, err := s.b.Store.AreaByName(it.Arg)
if err != nil {
if err != nil || !s.b.CanRead(s.user, a) {
t.Println(t.C(Red, "There is no area "+it.Arg+"."))
return nil
}
+10 -3
View File
@@ -18,7 +18,7 @@ func (s *session) doorsFor() []*door.Door {
return nil // doors are ANSI programs
}
for _, d := range s.b.Doors {
if !d.SysopOnly || s.user.Sysop {
if s.b.CanDoor(s.user, d) {
out = append(out, d)
}
}
@@ -71,7 +71,11 @@ func (s *session) doors() error {
func (s *session) openDoor(d *door.Door) error {
t := s.t
u := s.n.Refresh()
t.Println(t.C(Green, fmt.Sprintf("Opening %s (%d minutes)...", d.Name, int(d.TimeLimit/time.Minute))))
limit := d.TimeLimit
if left, ok := s.n.TimeLeft(); ok && (limit == 0 || left < limit) {
limit = left
}
t.Println(t.C(Green, fmt.Sprintf("Opening %s (%d minutes)...", d.Name, int(limit/time.Minute))))
port, err := t.Port()
if err != nil {
return err
@@ -79,7 +83,10 @@ func (s *session) openDoor(d *door.Door) error {
in := &door.Info{Node: s.n.Num, UserID: u.ID, UserName: u.Name, Location: u.Location,
Sysop: u.Sysop, Logins: u.Logins, Posts: u.Posts, LastLogin: u.LastLogin,
ANSI: t.ANSI, Rows: t.Rows, Cols: t.Cols, Baud: baud(s.c),
BBSName: s.b.Name, SysopName: s.b.Sysop}
BBSName: s.b.Name, SysopName: s.b.Sysop, Level: u.Level}
if left, ok := s.n.TimeLeft(); ok {
in.TimeLeft = max(left, time.Minute)
}
s.n.Doing("In " + d.Name)
s.b.Log.Printf("node %d: %s opened door %s", s.n.Num, u.Name, d.Name)
res, err := d.Run(port, in, t.UTF8, t.Idle, func(f string, a ...any) {
+9 -3
View File
@@ -16,10 +16,16 @@ func (s *session) fileAreas() error {
t := s.t
for {
s.n.Doing("File areas")
areas, err := s.b.Store.FileAreas()
all, err := s.b.Store.FileAreas()
if err != nil {
return err
}
var areas []*store.FileArea
for _, a := range all {
if s.b.CanDownload(s.user, a) || s.b.CanUpload(s.user, a) {
areas = append(areas, a)
}
}
t.Println("")
t.Println(t.C(Cyan, "File areas"))
if len(areas) == 0 {
@@ -82,11 +88,11 @@ func (s *session) fileArea(a *store.FileArea) error {
lines = append(lines, " No files here yet.")
}
t.Page(lines)
if s.b.FTPAddress != "" && files.CanUpload(s.user, a) {
if s.b.FTPAddress != "" && s.b.CanUpload(s.user, a) {
t.Println(t.C(Dim, "Upload by FTP into /"+a.Name+"/."))
}
prompt := "\nNumber for its details (and download), "
if files.CanUpload(s.user, a) {
if s.b.CanUpload(s.user, a) {
prompt += "[U]pload, "
}
cmd, err := t.Input(prompt+"[Q]uit: ", 6)
+15 -3
View File
@@ -51,6 +51,10 @@ func startHint(p *xfer.Protocol, upload bool) string {
// download sends a file.
func (s *session) download(a *store.FileArea, f *store.File) error {
t := s.t
if err := s.b.MayDownload(s.user, a); err != nil {
t.Println(t.C(Red, capital(err.Error())+"."))
return nil
}
p, err := s.chooseProtocol()
if err != nil || p == nil {
return err
@@ -75,7 +79,7 @@ func (s *session) download(a *store.FileArea, f *store.File) error {
t.Println(t.C(Red, "The transfer failed: "+err.Error()+"."))
return nil
}
s.b.Store.CountDownload(f.ID)
s.b.Downloaded(s.user, f)
s.b.Log.Printf("node %d: %s downloaded %q by %s (%d bytes, %v)", s.n.Num, s.user.Name, f.Name,
p.Name, f.Size, time.Since(start).Round(time.Second))
t.Println(t.C(Green, "Sent "+f.Name+"."))
@@ -131,8 +135,8 @@ func safeName(name string) string {
// upload receives files into an area.
func (s *session) upload(a *store.FileArea) error {
t := s.t
if !files.CanUpload(s.user, a) {
t.Println(t.C(Red, "Only the sysop uploads here."))
if !s.b.CanUpload(s.user, a) {
t.Println(t.C(Red, "Your access does not allow uploading here."))
return nil
}
p, err := s.chooseProtocol()
@@ -208,3 +212,11 @@ func (s *session) upload(a *store.FileArea) error {
}
return nil
}
// capital is s with its first letter upper case (an error as a sentence).
func capital(s string) string {
if s == "" {
return s
}
return strings.ToUpper(s[:1]) + s[1:]
}
+47 -7
View File
@@ -309,6 +309,12 @@ func (s *session) welcome() {
t.Println(t.C(Dim, "Your last call was "+u.LastLogin.Format("2006-01-02 15:04")+"."))
}
}
if left, ok := s.n.TimeLeft(); ok {
t.Println(t.C(Dim, fmt.Sprintf("You have %d minutes today.", int(left.Round(time.Minute).Minutes()))))
}
if !u.Sysop && u.Level < s.b.ValidatedLevel {
t.Println(t.C(Yellow, "Your account waits for the sysop's validation; mail the sysop if you like."))
}
if motd := s.b.MOTDText(); motd != "" {
t.Println("")
var lines []string
@@ -351,7 +357,18 @@ func (s *session) mainMenu() error {
chat += fmt.Sprintf(" (%d paging)", len(ps))
}
}
items = append(items, choice{"C", chat}, choice{"S", "Page the sysop"})
lvl := s.b.LevelOf(u)
if lvl.Chat {
items = append(items, choice{"C", chat})
}
if lvl.Page {
items = append(items, choice{"S", "Page the sysop"})
}
if u.Sysop && s.b.ValidatedLevel > s.b.NewUserLevel {
if w, _ := s.b.Store.UsersBelow(s.b.ValidatedLevel); len(w) > 0 {
items = append(items, choice{"V", fmt.Sprintf("Validate users (%d)", len(w))})
}
}
items = append(items, choice{"G", "Goodbye"})
k, err := s.menu("Main menu", items, "\n"+s.str("command_prompt"), true)
if err != nil {
@@ -369,9 +386,17 @@ func (s *session) mainMenu() error {
err = s.fileAreas()
}
case 'C':
err = s.chat("")
if lvl.Chat {
err = s.chat("")
}
case 'S':
err = s.page()
if lvl.Page {
err = s.page()
}
case 'V':
if u.Sysop {
err = s.validate()
}
case 'D':
if len(s.doorsFor()) > 0 {
err = s.doors()
@@ -510,7 +535,7 @@ func (s *session) area(a *store.Area) error {
}
t.Printf("%s%s: %d messages, %d new\n", t.C(Cyan, a.Name), group, a.Messages, nw)
menu := "[R]ead new, [L]ist, [#] read a number, "
if bbs.CanPost(s.user, a) {
if s.b.CanPost(s.user, a) {
menu += "[P]ost, "
}
cmd, err := t.Input(menu+"[Q]uit: ", 10)
@@ -529,7 +554,7 @@ func (s *session) area(a *store.Area) error {
return err
}
case "P":
if bbs.CanPost(s.user, a) {
if s.b.CanPost(s.user, a) {
if err := s.post(a, "All", "", nil, 0); err != nil {
return err
}
@@ -650,7 +675,7 @@ func (s *session) read(a *store.Area, m *store.Message) (bool, error) {
s.b.Store.SetLastRead(s.user.ID, a.ID, m.ID)
canDelete := s.user.Sysop || s.user.ID == m.FromID
prompt := "\n[N]ext, [P]revious, "
if bbs.CanPost(s.user, a) {
if s.b.CanPost(s.user, a) {
prompt += "[R]eply, "
}
prompt += "[M]ail reply, "
@@ -683,7 +708,7 @@ func (s *session) read(a *store.Area, m *store.Message) (bool, error) {
}
m = prev
case 'R':
if bbs.CanPost(s.user, a) {
if s.b.CanPost(s.user, a) {
if err := s.post(a, m.From, bbs.ReplySubject(m.Subject),
bbs.Quote(m.From, m.Body, 8), m.ID); err != nil {
return false, err
@@ -1020,6 +1045,21 @@ func (s *session) profile() error {
t.Printf(" Name: %s\n", u.Name)
t.Printf(" From: %s\n", u.Location)
t.Printf(" Member: since %s, %d calls, %d posts\n", u.Created.Format("2006-01-02"), u.Logins, u.Posts)
lvl := s.b.LevelOf(u)
access := fmt.Sprintf("level %d (%s)", u.Level, lvl.Name)
if u.Flags != "" {
access += ", flags " + u.Flags
}
t.Printf(" Access: %s\n", access)
if left, ok := s.n.TimeLeft(); ok {
t.Printf(" Today: %d minutes left", int(left.Round(time.Minute).Minutes()))
} else {
t.Printf(" Today: no time limit")
}
if lvl.Downloads > 0 {
t.Printf(", %d of %d downloads", u.DownloadsToday(), lvl.Downloads)
}
t.Println("")
onOff := map[bool]string{true: "on", false: "off"}
menu := "\n[L]ocation, [A]NSI on/off, [8]-bit UTF-8 on/off, [S]ixel on/off, [R]IP on/off, "
ident := ""
+8 -3
View File
@@ -111,11 +111,12 @@ func (u *ui) bye() {
// runMenu runs a menu of the sysop's until it is left (back) or the
// caller logs off.
func (u *ui) runMenu(m *bbs.Menu, depth int) error {
func (u *ui) runMenu(full *bbs.Menu, depth int) error {
msg := ""
vars := u.n.Vars()
for {
u.user = u.n.Refresh()
m := u.b.MenuFor(full, u.user)
title := screens.String(m.Title, vars)
u.n.Doing(title)
scr := u.frame(title, "Enter=Select PF3=Back", msg)
@@ -223,7 +224,11 @@ func (u *ui) do(it *bbs.MenuItem, depth int) (string, error) {
if depth >= 10 {
return "Menus nest too deep.", nil
}
return "", u.runMenu(u.b.Menus[strings.ToLower(it.Arg)], depth+1)
sub := u.b.Menus[strings.ToLower(it.Arg)]
if !bbs.MustRequire(sub.Require).Allows(u.user) {
return "That menu is not for you.", nil
}
return "", u.runMenu(sub, depth+1)
case "screen":
shown, err := u.screen(it.Arg)
if !shown {
@@ -232,7 +237,7 @@ func (u *ui) do(it *bbs.MenuItem, depth int) (string, error) {
return "", err
case "area":
a, err := u.b.Store.AreaByName(it.Arg)
if err != nil {
if err != nil || !u.b.CanRead(u.user, a) {
return "There is no area " + it.Arg + ".", nil
}
return "", u.area(a)
+8 -2
View File
@@ -15,10 +15,16 @@ func (u *ui) fileAreas() error {
top := 0
for {
u.n.Doing("File areas")
areas, err := u.b.Store.FileAreas()
all, err := u.b.Store.FileAreas()
if err != nil {
return err
}
var areas []*store.FileArea
for _, a := range all {
if u.b.CanDownload(u.user, a) || u.b.CanUpload(u.user, a) {
areas = append(areas, a)
}
}
tb := &table{title: "File areas", top: top,
heading: fmt.Sprintf("%-20s %-38s %5s %9s", "Area", "Description", "Files", "Size"),
keys: "Type S by an area, Enter PF3=Back PF7=Up PF8=Down"}
@@ -51,7 +57,7 @@ func (u *ui) fileAreas() error {
func (u *ui) fileArea(a *store.FileArea) error {
top := 0
msg := ""
if u.b.FTPAddress != "" && files.CanUpload(u.user, a) {
if u.b.FTPAddress != "" && u.b.CanUpload(u.user, a) {
msg = "Upload by FTP into /" + a.Name + "/, or with your emulator's file transfer"
}
for {
+17 -1
View File
@@ -52,6 +52,10 @@ func (u *ui) indFile(a *store.FileArea, ind *go3270.IndFile) (string, error) {
if err != nil {
return end(transNoFile)
}
if err := u.b.MayDownload(u.user, a); err != nil {
end(transDenied)
return capital(err.Error()) + ".", nil
}
r, err := u.b.Files.OpenFile(f)
if err != nil {
return end(transRead)
@@ -67,7 +71,7 @@ func (u *ui) indFile(a *store.FileArea, ind *go3270.IndFile) (string, error) {
}
return end(transRead)
}
u.b.Store.CountDownload(f.ID)
u.b.Downloaded(u.user, f)
u.b.Log.Printf("node %d: %s downloaded %q by IND$FILE (%d bytes, %v)", u.n.Num, u.user.Name,
f.Name, n, time.Since(start).Round(time.Second))
return end(transOK)
@@ -79,6 +83,10 @@ func (u *ui) indFile(a *store.FileArea, ind *go3270.IndFile) (string, error) {
if files.ValidName(name) != "" {
return end(transBadName)
}
if !u.b.CanUpload(u.user, a) {
end(transDenied)
return "Your access does not allow uploading here.", nil
}
up, err := u.b.Files.Upload(u.user, a, name, "")
switch {
case errors.Is(err, files.ErrDenied), errors.Is(err, files.ErrQuota):
@@ -106,3 +114,11 @@ func (u *ui) indFile(a *store.FileArea, ind *go3270.IndFile) (string, error) {
u.user.Name, f.Name, a.Name, f.Size, f.SHA256)
return end(transOK)
}
// capital is s with its first letter upper case (an error as a sentence).
func capital(s string) string {
if s == "" {
return s
}
return strings.ToUpper(s[:1]) + s[1:]
}
+4 -4
View File
@@ -571,7 +571,7 @@ func (u *ui) area(a *store.Area) error {
return err
}
keys := "S+Enter=Read PF3=Back PF5=Read new PF7=Up PF8=Down"
if bbs.CanPost(u.user, a) {
if u.b.CanPost(u.user, a) {
keys += " PF6=Post"
}
tb := &table{title: a.Name, keys: keys,
@@ -605,7 +605,7 @@ func (u *ui) area(a *store.Area) error {
return err
}
case go3270.AIDPF6:
if bbs.CanPost(u.user, a) {
if u.b.CanPost(u.user, a) {
if msg, err = u.post(a, "All", "", nil, 0); err != nil {
return err
}
@@ -678,7 +678,7 @@ func (u *ui) read(a *store.Area, m *store.Message) error {
u.b.Store.SetLastRead(u.user.ID, a.ID, m.ID)
canDelete := u.user.Sysop || u.user.ID == m.FromID
keys := "PF3=Back PF7/8=Scroll PF10=Prev PF11=Next"
if bbs.CanPost(u.user, a) {
if u.b.CanPost(u.user, a) {
keys += " PF4=Reply"
}
keys += " PF5=Mail"
@@ -713,7 +713,7 @@ func (u *ui) read(a *store.Area, m *store.Message) error {
}
m, off = nm, 0
case go3270.AIDPF4:
if bbs.CanPost(u.user, a) {
if u.b.CanPost(u.user, a) {
if msg, err = u.post(a, m.From, bbs.ReplySubject(m.Subject),
bbs.Quote(m.From, m.Body, 6), m.ID); err != nil {
return err