mirror of
https://github.com/D-Modem/bbs.git
synced 2026-11-28 17:38:04 -08:00
Add an HTTP API with JSON and protobuf WebSockets
[http] serves a REST API under /api/v1 (accounts, message areas, mail, file areas with uploads and ranged downloads, chat rooms, paging, and sysop administration including FidoNet polls and news syncs), with server-sent events and two WebSocket endpoints speaking the bbs.v1 protocol from proto/bbs.proto: JSON text frames at /api/v1/ws and binary protobuf at /api/v1/ws/proto. Stream clients get a real node, so web users chat with terminal callers, get node messages and page the sysop. Tokens are login sessions or API keys (bbs token add/list/revoke), stored as SHA-256 hashes, with scopes. TLS by default, per-token and per-address rate limits, strict bodies, one CORS origin at most, Prometheus metrics on their own address, and an OpenAPI 3.1 document checked against the routes. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01AFQhReUqUc7F5srk2hViqr
This commit is contained in:
29 files changed
+5318
-17
No files matched your search
@@ -23,7 +23,12 @@ install: bbs
|
||||
doors-image:
|
||||
docker build -t bbs-dosemu2 doors/dosemu2
|
||||
|
||||
# regenerates internal/api/pb from proto/bbs.proto (needs protoc and
|
||||
# protoc-gen-go; the generated code is committed)
|
||||
proto:
|
||||
protoc --go_out=. --go_opt=module=github.com/Neo-Desktop/bbs-sec proto/bbs.proto
|
||||
|
||||
clean:
|
||||
rm -f bbs
|
||||
|
||||
.PHONY: all bbs test install clean doors-image
|
||||
.PHONY: all bbs test install clean doors-image proto
|
||||
@@ -66,6 +66,7 @@ What there is:
|
||||
and the usual drop files, or any Linux program, for text callers
|
||||
- [chat](https://github.com/Neo-Desktop/bbs-sec/wiki/Chat-and-Paging): rooms, messages to a node, paging the sysop
|
||||
- [finger and gopher](https://github.com/Neo-Desktop/bbs-sec/wiki/Finger-and-Gopher): who is on, and chosen areas in gopherspace
|
||||
- [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
|
||||
- new users sign themselves up (or not: `new_users = no`)
|
||||
- SQLite storage, one file
|
||||
@@ -108,6 +109,7 @@ The documentation is in the [wiki](https://github.com/Neo-Desktop/bbs-sec/wiki/)
|
||||
| [FidoNet](https://github.com/Neo-Desktop/bbs-sec/wiki/FidoNet) | echomail, netmail, binkp |
|
||||
| [Chat and paging](https://github.com/Neo-Desktop/bbs-sec/wiki/Chat-and-Paging) | chat rooms, node messages, paging the sysop |
|
||||
| [Finger and gopher](https://github.com/Neo-Desktop/bbs-sec/wiki/Finger-and-Gopher) | who is on, and the BBS in gopherspace |
|
||||
| [HTTP API](https://github.com/Neo-Desktop/bbs-sec/wiki/HTTP-API) | REST, events, WebSockets in JSON and protobuf, tokens, metrics |
|
||||
| [Security](https://github.com/Neo-Desktop/bbs-sec/wiki/Security) | what is guarded, and how |
|
||||
| [Development](https://github.com/Neo-Desktop/bbs-sec/wiki/Development) | the source's layout, the tests |
|
||||
|
||||
|
||||
@@ -128,6 +128,27 @@ address = 127.0.0.1:2513
|
||||
;socket_mode = 0660
|
||||
;socket_group = asterisk
|
||||
|
||||
; The HTTP API (REST, server-sent events, and WebSockets in JSON and
|
||||
; protobuf): see docs/wiki/HTTP-API.md. Tokens: POST /api/v1/login, or
|
||||
; bbs token add USER -scope read,post. Without this section there is none
|
||||
;[http]
|
||||
;address = :8443
|
||||
; TLS is the default; tls = no only on 127.0.0.1 behind a proxy that has it
|
||||
;cert_file = /etc/bbs/tls/cert.pem
|
||||
;key_file = /etc/bbs/tls/key.pem
|
||||
; anonymous callers may see /system and /who
|
||||
;anonymous = yes
|
||||
; one browser origin allowed to call it (no *)
|
||||
;cors = https://www.example.org
|
||||
; Prometheus metrics, on an address of their own (keep it private)
|
||||
;metrics = 127.0.0.1:9100
|
||||
;max_per_ip = 20
|
||||
; requests a second per token (or per IP without one), and the burst
|
||||
;rate = 10
|
||||
;burst = 20
|
||||
; how long a /login session lasts
|
||||
;session_hours = 24
|
||||
|
||||
; 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
|
||||
|
||||
+147
-14
@@ -14,6 +14,9 @@
|
||||
// bbs [-config FILE] news sync [PEER]
|
||||
// bbs [-config FILE] area echo AREA TAG|-
|
||||
// bbs [-config FILE] fido poll|scan|toss [LINK]
|
||||
// bbs [-config FILE] token add USER [-scope read,post,...] [-expires DAYS] [-name NAME]
|
||||
// bbs [-config FILE] token list [USER]
|
||||
// bbs [-config FILE] token revoke ID
|
||||
// bbs [-config FILE] filearea add NAME [DESCRIPTION] [-sysop-upload]
|
||||
// bbs [-config FILE] filearea del|list [NAME]
|
||||
// bbs [-config FILE] file add AREA PATH [DESCRIPTION] [-as NAME]
|
||||
@@ -33,15 +36,19 @@ import (
|
||||
"os"
|
||||
"os/signal"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"golang.org/x/term"
|
||||
|
||||
"github.com/Neo-Desktop/bbs-sec/internal/api"
|
||||
"github.com/Neo-Desktop/bbs-sec/internal/bbs"
|
||||
"github.com/Neo-Desktop/bbs-sec/internal/fido"
|
||||
"github.com/Neo-Desktop/bbs-sec/internal/files"
|
||||
"github.com/Neo-Desktop/bbs-sec/internal/finger"
|
||||
"github.com/Neo-Desktop/bbs-sec/internal/ftn"
|
||||
"github.com/Neo-Desktop/bbs-sec/internal/ftp"
|
||||
"github.com/Neo-Desktop/bbs-sec/internal/gopher"
|
||||
"github.com/Neo-Desktop/bbs-sec/internal/news"
|
||||
@@ -66,6 +73,10 @@ func usage() {
|
||||
bbs [-config FILE] area echo AREA TAG|- make an area a FidoNet echo (- : not one)
|
||||
bbs [-config FILE] fido poll [LINK] call links (with a host) now
|
||||
bbs [-config FILE] fido scan|toss [LINK] pack new mail, or take in what came
|
||||
bbs [-config FILE] token add USER [-scope read,post,mail,chat,files,sysop]
|
||||
[-expires DAYS] [-name NAME] an API key (printed once)
|
||||
bbs [-config FILE] token list [USER]
|
||||
bbs [-config FILE] token revoke ID
|
||||
bbs [-config FILE] filearea add NAME [DESCRIPTION] [-sysop-upload]
|
||||
bbs [-config FILE] filearea del NAME
|
||||
bbs [-config FILE] filearea list
|
||||
@@ -146,6 +157,13 @@ func main() {
|
||||
}
|
||||
fmt.Printf("[menu %s] %q, keys %s\n", m.Name, m.Title, keys)
|
||||
}
|
||||
if h := cfg.HTTP; h != nil {
|
||||
fmt.Printf("http: %s, tls %v, anonymous %v", h.Address, h.TLS, h.Anonymous)
|
||||
if h.Metrics != "" {
|
||||
fmt.Printf(", metrics on %s", h.Metrics)
|
||||
}
|
||||
fmt.Println()
|
||||
}
|
||||
if cfg.Finger != nil {
|
||||
fmt.Printf("finger: %s (online %v, users %v)\n", cfg.Finger.Address, cfg.Finger.Online, cfg.Finger.Users)
|
||||
}
|
||||
@@ -183,6 +201,8 @@ func main() {
|
||||
newsCmd(cfg, args)
|
||||
case "fido":
|
||||
fidoCmd(cfg, args)
|
||||
case "token":
|
||||
tokenCmd(cfg, args)
|
||||
case "filearea":
|
||||
fileAreaCmd(cfg, args)
|
||||
case "file":
|
||||
@@ -279,8 +299,9 @@ func serve(cfg *server.Config) int {
|
||||
}
|
||||
}()
|
||||
}
|
||||
var fd *fido.Fido
|
||||
if cfg.Fido != nil {
|
||||
fd, err := fido.New(b, *cfg.Fido)
|
||||
fd, err = fido.New(b, *cfg.Fido)
|
||||
if err != nil {
|
||||
lg.Printf("fido: %v", err)
|
||||
return 1
|
||||
@@ -298,6 +319,18 @@ func serve(cfg *server.Config) int {
|
||||
}
|
||||
go fd.Run(ctx)
|
||||
}
|
||||
if cfg.HTTP != nil {
|
||||
as := &api.Server{B: b, S: *cfg.HTTP, Fido: fd, Peers: cfg.Peers}
|
||||
if len(cfg.Peers) > 0 || cfg.NNTP != nil {
|
||||
as.News = svc
|
||||
}
|
||||
go func() {
|
||||
if err := as.Run(ctx); err != nil {
|
||||
lg.Printf("%v", err)
|
||||
stop()
|
||||
}
|
||||
}()
|
||||
}
|
||||
if cfg.FTP != nil {
|
||||
fs, err := ftp.New(b, *cfg.FTP)
|
||||
if err != nil {
|
||||
@@ -519,7 +552,7 @@ func areaCmd(cfg *server.Config, args []string) {
|
||||
tag := strings.ToUpper(words[2])
|
||||
if tag == "-" {
|
||||
tag = ""
|
||||
} else if !validEchoTag(tag) {
|
||||
} else if !ftn.ValidTag(tag) {
|
||||
fatal(errors.New("an echo tag is letters, digits and . _ - (FSX_GEN), up to 60"))
|
||||
}
|
||||
if err := st.SetEchoTag(a.ID, tag); err != nil {
|
||||
@@ -701,18 +734,6 @@ func newsCmd(cfg *server.Config, args []string) {
|
||||
}
|
||||
}
|
||||
|
||||
func validEchoTag(tag string) bool {
|
||||
if tag == "" || len(tag) > 60 {
|
||||
return false
|
||||
}
|
||||
for _, c := range tag {
|
||||
if !(c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || strings.ContainsRune("._-!$&+", c)) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func fidoCmd(cfg *server.Config, args []string) {
|
||||
words, _ := split(args)
|
||||
if len(words) == 0 || len(words) > 2 {
|
||||
@@ -778,3 +799,115 @@ func fidoCmd(cfg *server.Config, args []string) {
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
func tokenCmd(cfg *server.Config, args []string) {
|
||||
if len(args) == 0 {
|
||||
usage()
|
||||
}
|
||||
st := open(cfg)
|
||||
defer st.Close()
|
||||
switch args[0] {
|
||||
case "add":
|
||||
var user, name string
|
||||
scopes, days := "read,post,mail,chat,files", 0
|
||||
for i := 1; i < len(args); i++ {
|
||||
a := args[i]
|
||||
val := func() string {
|
||||
if i+1 >= len(args) {
|
||||
usage()
|
||||
}
|
||||
i++
|
||||
return args[i]
|
||||
}
|
||||
switch a {
|
||||
case "-scope", "-scopes":
|
||||
scopes = val()
|
||||
case "-expires":
|
||||
n, err := strconv.Atoi(val())
|
||||
if err != nil || n < 0 {
|
||||
fatal(errors.New("-expires: a number of days"))
|
||||
}
|
||||
days = n
|
||||
case "-name":
|
||||
name = val()
|
||||
default:
|
||||
if user != "" || strings.HasPrefix(a, "-") {
|
||||
usage()
|
||||
}
|
||||
user = a
|
||||
}
|
||||
}
|
||||
if user == "" {
|
||||
usage()
|
||||
}
|
||||
u, err := st.UserByName(user)
|
||||
if err != nil {
|
||||
fatal(fmt.Errorf("%s: %w", user, err))
|
||||
}
|
||||
sc, err := api.ParseScopes(scopes)
|
||||
if err != nil {
|
||||
fatal(err)
|
||||
}
|
||||
if strings.Contains(" "+sc+" ", " sysop ") && !u.Sysop {
|
||||
fatal(errors.New("the sysop scope is for sysops"))
|
||||
}
|
||||
if name == "" {
|
||||
name = "key"
|
||||
}
|
||||
secret, hash := api.NewToken()
|
||||
t := &store.Token{UserID: u.ID, Name: bbs.Clean(name, 60), Hash: hash, Scopes: sc}
|
||||
if days > 0 {
|
||||
t.Expires = time.Now().Add(time.Duration(days) * 24 * time.Hour)
|
||||
}
|
||||
id, err := st.AddToken(t)
|
||||
if err != nil {
|
||||
fatal(err)
|
||||
}
|
||||
fmt.Printf("token %d for %s (%s)", id, u.Name, sc)
|
||||
if days > 0 {
|
||||
fmt.Printf(", until %s", t.Expires.Format("2006-01-02"))
|
||||
}
|
||||
fmt.Printf(":\n%s\n(it is shown this once)\n", secret)
|
||||
case "list":
|
||||
var uid int64
|
||||
if len(args) == 2 {
|
||||
u, err := st.UserByName(args[1])
|
||||
if err != nil {
|
||||
fatal(fmt.Errorf("%s: %w", args[1], err))
|
||||
}
|
||||
uid = u.ID
|
||||
}
|
||||
ts, err := st.Tokens(uid)
|
||||
if err != nil {
|
||||
fatal(err)
|
||||
}
|
||||
for _, t := range ts {
|
||||
kind := "key"
|
||||
if t.Session {
|
||||
kind = "session"
|
||||
}
|
||||
exp, last := "never", "never"
|
||||
if !t.Expires.IsZero() {
|
||||
exp = t.Expires.Format("2006-01-02 15:04")
|
||||
}
|
||||
if !t.LastUsed.IsZero() {
|
||||
last = t.LastUsed.Format("2006-01-02 15:04")
|
||||
}
|
||||
fmt.Printf("%4d %-16s %-8s %-30s expires %s, used %s %s\n", t.ID, t.User, kind, t.Scopes, exp, last, t.Name)
|
||||
}
|
||||
case "revoke":
|
||||
if len(args) != 2 {
|
||||
usage()
|
||||
}
|
||||
id, err := strconv.ParseInt(args[1], 10, 64)
|
||||
if err != nil {
|
||||
usage()
|
||||
}
|
||||
if err := st.RevokeToken(id, 0); err != nil {
|
||||
fatal(fmt.Errorf("token %d: %w", id, err))
|
||||
}
|
||||
fmt.Println("revoked", id)
|
||||
default:
|
||||
usage()
|
||||
}
|
||||
}
|
||||
@@ -25,6 +25,7 @@ yes`), and with `trust_user = yes` take the caller as logged in already: see
|
||||
| `[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) |
|
||||
| `[http]` | the HTTP API, its WebSockets 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) |
|
||||
|
||||
`bbs check` reads the file and says what it found, with a warning for
|
||||
|
||||
@@ -18,6 +18,8 @@
|
||||
| `doors/dosemu2` | the Docker image DOS doors run in: dosemu2, its FOSSIL on COM1 |
|
||||
| `internal/finger` | the finger server |
|
||||
| `internal/gopher` | the gopher server |
|
||||
| `internal/api` | the HTTP API: REST, server-sent events, WebSockets, metrics, OpenAPI |
|
||||
| `proto` | the WebSocket protocol, `bbs.v1` (`make proto` regenerates `internal/api/pb`) |
|
||||
| `internal/tcpserv` | what finger and gopher share: limits, timeouts |
|
||||
| `internal/screens` | the sysop's display files: finding them, @-codes, 3270 color tags |
|
||||
| `internal/xfer` | XMODEM, YMODEM, ZMODEM and Kermit, both ways |
|
||||
@@ -72,5 +74,10 @@ and what it refuses; a text caller through an ANSI logon (CP437 as it
|
||||
is), the strings, a welcome screen, the sysop's menus and submenus, a
|
||||
screen with a pause and a goodbye screen; and a 3270 (s3270) through a
|
||||
colored logon screen, welcome, the sysop's main menu and a screen.
|
||||
The HTTP API: logins, tokens and scopes, every REST endpoint and its
|
||||
refusals, rate limits, the OpenAPI document against the routes, server-sent
|
||||
events and node messages, both WebSockets (auth by header and by first
|
||||
message, chat between them, paging and answering, mail events, bad
|
||||
frames, refused origins and tokens) and the metrics.
|
||||
|
||||
**See also:** [Building](Building)
|
||||
@@ -0,0 +1,202 @@
|
||||
The BBS has an HTTP API for programs and web front ends: REST for
|
||||
accounts, message areas, mail and files; server-sent events; and
|
||||
WebSockets for chat, in JSON or protobuf. A web client is a node like
|
||||
any other: it shows in *Who's online*, chats with terminal callers, gets
|
||||
node messages and can page the sysop.
|
||||
|
||||
It is on when `bbs.conf` has an `[http]` section:
|
||||
|
||||
```ini
|
||||
[http]
|
||||
address = :8443
|
||||
cert_file = /etc/bbs/tls/cert.pem
|
||||
key_file = /etc/bbs/tls/key.pem
|
||||
;cors = https://www.example.org
|
||||
;metrics = 127.0.0.1:9100
|
||||
```
|
||||
|
||||
| setting | default | |
|
||||
|---|---|---|
|
||||
| `address` | `:8443` | where it listens |
|
||||
| `tls` | `yes` | TLS needs `cert_file` and `key_file`. `tls = no` is for `127.0.0.1` behind a proxy that has TLS; `bbs check` warns about it on any other address |
|
||||
| `anonymous` | `yes` | `/system` and `/who` without a token |
|
||||
| `cors` | (none) | one browser origin allowed to call the API (no `*`); WebSockets are accepted only from it and the API's own host |
|
||||
| `metrics` | (none) | an address for Prometheus metrics, `/metrics` (keep it private) |
|
||||
| `max_per_ip` | `20` | connections at once from one address |
|
||||
| `rate`, `burst` | `10`, `20` | requests a second per token (per address without one), and how many may come at once |
|
||||
| `session_hours` | `24` | how long a login's token lasts |
|
||||
|
||||
The OpenAPI 3.1 description is at `/api/v1/openapi.json`.
|
||||
|
||||
## Tokens and scopes
|
||||
|
||||
Every request but `/login`, `/openapi.json` and (when `anonymous = yes`)
|
||||
`/system` and `/who` needs a token: `Authorization: Bearer bbs_...`.
|
||||
|
||||
- A **session**: `POST /api/v1/login` with `{"name": ..., "password": ...}`
|
||||
(and `"scopes"`, to have fewer) returns `{"token": ..., "expires": ...}`.
|
||||
`POST /api/v1/logout` ends it.
|
||||
- An **API key**, for a program: `bbs token add alice -scope read,post
|
||||
-expires 90 -name "my bot"` prints it once. `bbs token list [USER]` and
|
||||
`bbs token revoke ID` manage them, and users see and revoke their own at
|
||||
`/api/v1/me/tokens`.
|
||||
|
||||
Only a hash of a token is kept. A locked user's tokens stop working.
|
||||
|
||||
| scope | allows |
|
||||
|---|---|
|
||||
| `read` | the account, users, message areas and messages, last read |
|
||||
| `post` | posting |
|
||||
| `mail` | reading, sending and deleting mail |
|
||||
| `chat` | the event stream, WebSockets, node messages, paging |
|
||||
| `files` | file areas, uploading and downloading |
|
||||
| `sysop` | `/admin/...` (only for a sysop's tokens) |
|
||||
|
||||
## REST
|
||||
|
||||
All under `/api/v1`, JSON in and out (but uploads and downloads).
|
||||
Errors are `{"error": "...", "code": "..."}`.
|
||||
|
||||
| | | scope |
|
||||
|---|---|---|
|
||||
| `POST /login`, `POST /logout` | a session token; ending it | (none), any |
|
||||
| `GET /system` | the name, sysop, counts, features | anonymous |
|
||||
| `GET /who` | who is online | anonymous |
|
||||
| `GET`, `PATCH /me` | your account; change your location or password | read |
|
||||
| `GET /me/tokens`, `DELETE /me/tokens/{id}` | your tokens; revoke one | any |
|
||||
| `GET /users`, `/users/{name}` | users | read |
|
||||
| `GET /areas`, `/areas/{id}` | message areas, with your unread | read |
|
||||
| `GET /areas/{id}/messages?after=&limit=&body=no` | messages after an id (200 at most) | read |
|
||||
| `POST /areas/{id}/messages` | post: `{"subject", "body", "reply_to"}` | post |
|
||||
| `PUT /areas/{id}/lastread` | mark read up to a message | read |
|
||||
| `GET /messages/{id}` | a message | read |
|
||||
| `GET /mail`, `GET`, `DELETE /mail/{id}` | your inbox; a mail (marked read); delete it | mail |
|
||||
| `POST /mail` | send: to a user, or `Name@zone:net/node` as netmail | mail |
|
||||
| `GET /fileareas`, `/fileareas/{id}/files`, `/files/{id}` | file areas and files | files |
|
||||
| `POST /fileareas/{id}/files?name=&description=` | upload: the body is the file | files |
|
||||
| `GET /files/{id}/content` | download (ranges work) | files |
|
||||
| `GET /chat/rooms` | chat rooms in use | chat |
|
||||
| `POST /nodes/{n}/message`, `POST /page` | a line to a node; page the sysop (both need an open stream) | chat |
|
||||
| `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/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 |
|
||||
|
||||
```sh
|
||||
TOKEN=$(curl -s https://bbs.example.org:8443/api/v1/login \
|
||||
-d '{"name":"alice","password":"..."}' | jq -r .token)
|
||||
curl -s -H "Authorization: Bearer $TOKEN" https://bbs.example.org:8443/api/v1/areas
|
||||
curl -s -H "Authorization: Bearer $TOKEN" https://bbs.example.org:8443/api/v1/areas/1/messages \
|
||||
-d '{"subject":"Hello","body":"From curl."}'
|
||||
```
|
||||
|
||||
## Streams and nodes
|
||||
|
||||
The event stream and each WebSocket take a node, as a caller does
|
||||
(`Via` is `web`): it counts against `max_nodes`, shows in *Who's online*,
|
||||
and gets the node's events: lines said in its chat room, node messages,
|
||||
pages (for sysops), new mail and notices. The node goes when the
|
||||
connection does. `POST /nodes/{n}/message`, `/page` and answering a
|
||||
page are done from the token's open stream (409 without one).
|
||||
|
||||
### Server-sent events
|
||||
|
||||
`GET /api/v1/events` (with the `Authorization` header; a browser does
|
||||
this with `fetch`, as `EventSource` cannot send headers) starts with
|
||||
`event: welcome` (its node and user), then sends each event as
|
||||
`event: said` (`emoted`, `joined`, `left`, `private`, `paged`, `notice`,
|
||||
`mail`) with the event as JSON in `data:`, and a comment every 25
|
||||
seconds to keep it open.
|
||||
|
||||
## WebSockets
|
||||
|
||||
Two endpoints speak the same protocol, `bbs.v1`, defined in
|
||||
[`proto/bbs.proto`](https://github.com/Neo-Desktop/bbs-sec/blob/HEAD/proto/bbs.proto):
|
||||
|
||||
| endpoint | subprotocol | frames |
|
||||
|---|---|---|
|
||||
| `/api/v1/ws` | `bbs.v1.json` | text: protobuf's JSON mapping (lowerCamelCase fields, enums by name, RFC 3339 times) |
|
||||
| `/api/v1/ws/proto` | `bbs.v1.proto` | binary: protobuf |
|
||||
|
||||
The client sends `ClientMessage`s with an `id` of its choosing; each is
|
||||
answered by `ServerMessage`s with that `id`: `ok` (with `room` when the
|
||||
client's room changed), `error` (`code` and `message`), or what was asked
|
||||
for. Events and the welcome come with id 0.
|
||||
|
||||
A browser cannot set headers on a WebSocket, so unless the upgrade had an
|
||||
`Authorization` header the first message must be `auth`, within 10
|
||||
seconds. The token needs the `chat` scope.
|
||||
|
||||
| request | answer |
|
||||
|---|---|
|
||||
| `auth {token}` | `welcome {bbs, user, node, scopes}` |
|
||||
| `join {room}` | `lines` (the room's last lines), then `ok {room}` |
|
||||
| `leave {}` | `ok` |
|
||||
| `say {text, emote}` | `ok`; the room gets the line |
|
||||
| `nodeMessage {node, text}` | `ok` |
|
||||
| `page {reason}` | `ok {room}`: the private room to wait in (the client is put in it) |
|
||||
| `answer {node}` | sysops: `lines`, `ok {room}` |
|
||||
| `command {line}` | a line as typed in chat (`/who`, `/rooms`, `/msg`, `/join` ...): `lines`, `ok` |
|
||||
| `who {}` | `nodes {nodes: [{node, user, via, since, doing}]}` |
|
||||
| `rooms {}` | `rooms {rooms: [{name, users}]}` |
|
||||
| `ping {}` | `pong` |
|
||||
|
||||
A session in JSON (`>` from the client):
|
||||
|
||||
```
|
||||
> {"id":1,"auth":{"token":"bbs_..."}}
|
||||
{"welcome":{"bbs":"The BBS","user":"alice","node":3,"scopes":["read","post","mail","chat","files"]}}
|
||||
> {"id":2,"join":{"room":"main"}}
|
||||
{"id":2,"lines":{"lines":["bob: hi all"]}}
|
||||
{"id":2,"ok":{"room":"main"}}
|
||||
> {"id":3,"say":{"text":"hello from the web"}}
|
||||
{"id":3,"ok":{}}
|
||||
{"event":{"kind":"SAID","room":"main","from":"alice","node":3,"text":"hello from the web","time":"2026-10-11T12:00:00Z","line":"alice: hello from the web"}}
|
||||
{"event":{"kind":"SAID","room":"main","from":"bob","node":1,"text":"welcome!","time":"2026-10-11T12:00:04Z","line":"bob: welcome!"}}
|
||||
```
|
||||
|
||||
Clients of the protobuf endpoint generate code from `proto/bbs.proto`
|
||||
(`protoc --go_out=...`, `--python_out=...` and so on). In JavaScript:
|
||||
|
||||
```js
|
||||
const ws = new WebSocket("wss://bbs.example.org:8443/api/v1/ws", "bbs.v1.json");
|
||||
ws.onopen = () => ws.send(JSON.stringify({id: 1, auth: {token}}));
|
||||
ws.onmessage = (m) => {
|
||||
const msg = JSON.parse(m.data);
|
||||
if (msg.welcome) ws.send(JSON.stringify({id: 2, join: {room: "main"}}));
|
||||
if (msg.event) console.log(msg.event.line);
|
||||
};
|
||||
```
|
||||
|
||||
The server pings every 30 seconds. Frames are at most 16 KB; a frame
|
||||
that does not read is answered by an error, and the same limits as on a
|
||||
terminal apply (200 characters a line, 8 lines in 10 seconds).
|
||||
|
||||
## Metrics
|
||||
|
||||
With `metrics = 127.0.0.1:9100`, `/metrics` there has, in Prometheus's
|
||||
text format: `bbs_nodes`, `bbs_nodes_by_via{via}`, `bbs_max_nodes`,
|
||||
`bbs_users`, `bbs_messages`, `bbs_logins_total`,
|
||||
`bbs_login_failures_total`, `bbs_posts_total`, `bbs_mail_total`,
|
||||
`bbs_pages_total`, `bbs_chat_lines_total`, `bbs_pages_waiting` and
|
||||
`bbs_fido_outbound_files{link}`.
|
||||
|
||||
## Security
|
||||
|
||||
- TLS by default; tokens never go in URLs (only in the `Authorization`
|
||||
header or a WebSocket's first message).
|
||||
- Tokens are 32 random bytes; only their SHA-256 is stored. A wrong
|
||||
token waits as a wrong password does, and failed logins are logged and
|
||||
counted like a terminal's.
|
||||
- Rate limits per token (per address without one), connections per
|
||||
address, JSON bodies at most 64 KB with unknown fields refused,
|
||||
uploads limited as on the BBS.
|
||||
- No CORS unless one origin is named; WebSockets from origins other than
|
||||
it and the API's own host are refused. Responses carry `nosniff` and `no-store`.
|
||||
- What web clients say and post is cleaned as a terminal caller's is.
|
||||
|
||||
**See also:** [Chat and paging](Chat-and-Paging), [Security](Security), [Configuration](Configuration)
|
||||
@@ -64,6 +64,7 @@ What there is:
|
||||
and the usual drop files, or any Linux program, for text callers
|
||||
- [chat](Chat-and-Paging): rooms, messages to a node, paging the sysop
|
||||
- [finger and gopher](Finger-and-Gopher): who is on, and chosen areas in gopherspace
|
||||
- [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
|
||||
- new users sign themselves up (or not: `new_users = no`)
|
||||
- SQLite storage, one file
|
||||
@@ -87,6 +88,7 @@ What there is:
|
||||
| [FidoNet](FidoNet) | echomail, netmail, binkp |
|
||||
| [Chat and paging](Chat-and-Paging) | chat rooms, node messages, paging the sysop |
|
||||
| [Finger and gopher](Finger-and-Gopher) | who is on, and the BBS in gopherspace |
|
||||
| [HTTP API](HTTP-API) | REST, events, WebSockets in JSON and protobuf, tokens, metrics |
|
||||
| [Security](Security) | what is guarded, and how |
|
||||
| [Development](Development) | the source's layout, the tests |
|
||||
|
||||
|
||||
@@ -53,6 +53,12 @@
|
||||
check` warns when they do), and its selectors are database records, not
|
||||
paths. Both limit connections at once and from one address, and time
|
||||
out.
|
||||
- The HTTP API: TLS by default (`bbs check` warns when it is off on an
|
||||
address others reach); tokens of 32 random bytes kept only as hashes,
|
||||
never in URLs, limited by scope (`sysop` only for sysops), expiring
|
||||
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.
|
||||
- Screens: display files are read only from `screens_dir`, by names of
|
||||
letters, digits, `_` and `-` (no paths), at most 256 KB. The values of
|
||||
@-codes are cleaned, so no escape sequence gets into a screen through
|
||||
|
||||
@@ -20,6 +20,7 @@
|
||||
- [FidoNet](FidoNet)
|
||||
- [Chat and paging](Chat-and-Paging)
|
||||
- [Finger and gopher](Finger-and-Gopher)
|
||||
- [HTTP API](HTTP-API)
|
||||
|
||||
**More**
|
||||
- [Security](Security)
|
||||
|
||||
@@ -5,14 +5,17 @@ go 1.24.0
|
||||
toolchain go1.24.7
|
||||
|
||||
require (
|
||||
github.com/coder/websocket v1.8.13
|
||||
github.com/fclairamb/ftpserverlib v0.30.0
|
||||
github.com/jlaffaye/ftp v0.2.0
|
||||
github.com/racingmars/go3270 v0.9.13
|
||||
github.com/spf13/afero v1.15.0
|
||||
golang.org/x/crypto v0.31.0
|
||||
golang.org/x/image v0.23.0
|
||||
golang.org/x/sys v0.40.0
|
||||
golang.org/x/term v0.27.0
|
||||
golang.org/x/text v0.28.0
|
||||
google.golang.org/protobuf v1.36.6
|
||||
modernc.org/sqlite v1.33.1
|
||||
)
|
||||
|
||||
@@ -25,7 +28,6 @@ require (
|
||||
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||
github.com/ncruces/go-strftime v0.1.9 // indirect
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
|
||||
golang.org/x/sys v0.40.0 // indirect
|
||||
modernc.org/gc/v3 v3.0.0-20240107210532-573471604cb6 // indirect
|
||||
modernc.org/libc v1.55.3 // indirect
|
||||
modernc.org/mathutil v1.6.0 // indirect
|
||||
|
||||
@@ -1,11 +1,15 @@
|
||||
github.com/Neo-Desktop/go3270-sec v0.9.14-0.20261010180804-750b72ee6b2f h1:Bt6G332gAcwKuDK+WBYMx6MgAsAbjEwBPb0fSxwQch8=
|
||||
github.com/Neo-Desktop/go3270-sec v0.9.14-0.20261010180804-750b72ee6b2f/go.mod h1:JCzKbsCGdevsd+2iLMRw3Cd+Wk7vmBeGlnfHmeJEcsU=
|
||||
github.com/coder/websocket v1.8.13 h1:f3QZdXy7uGVz+4uCJy2nTZyM0yTBj8yANEHhqlXZ9FE=
|
||||
github.com/coder/websocket v1.8.13/go.mod h1:LNVeNrXQZfe5qhS9ALED3uA+l5pPqvwXg3CKoDBB2gs=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
|
||||
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
|
||||
github.com/fclairamb/ftpserverlib v0.30.0 h1:caB9sDn1Au//q0j2ev/icPn388qPuk4k1ajSvglDcMQ=
|
||||
github.com/fclairamb/ftpserverlib v0.30.0/go.mod h1:QmogtltTOgkihyKza0GNo37Mu4AEzbJ+sH6W9Y0MBIQ=
|
||||
github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU=
|
||||
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||
github.com/google/pprof v0.0.0-20240409012703-83162a5b38cd h1:gbpYu9NMq8jhDVbvlGkMFWCjLFlqqEZjEmObmhUy6Vo=
|
||||
github.com/google/pprof v0.0.0-20240409012703-83162a5b38cd/go.mod h1:kf6iHlnVGwgKolg33glAes7Yg/8iWP8ukqeldJSO7jw=
|
||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||
@@ -49,6 +53,10 @@ golang.org/x/text v0.28.0 h1:rhazDwis8INMIwQ4tpjLDzUhx6RlXqZNPEM0huQojng=
|
||||
golang.org/x/text v0.28.0/go.mod h1:U8nCwOR8jO/marOQ0QbDiOngZVEBB7MAiitBuMjXiNU=
|
||||
golang.org/x/tools v0.35.0 h1:mBffYraMEf7aa0sB+NuKnuCy8qI/9Bughn8dC2Gu5r0=
|
||||
golang.org/x/tools v0.35.0/go.mod h1:NKdj5HkL/73byiZSJjqJgKn3ep7KjFkBOkR/Hps3VPw=
|
||||
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4=
|
||||
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
google.golang.org/protobuf v1.36.6 h1:z1NpPI8ku2WgiWnf+t9wTPsn6eP1L7ksHUlkfLvd9xY=
|
||||
google.golang.org/protobuf v1.36.6/go.mod h1:jduwjTPXsFjZGTmRluh+L6NjiWu7pchiJ2/5YcXBHnY=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
modernc.org/cc/v4 v4.21.4 h1:3Be/Rdo1fpr8GrQ7IVw9OHtplU4gWbb+wNgeoBMmGLQ=
|
||||
|
||||
@@ -0,0 +1,427 @@
|
||||
// Package api is the BBS over HTTP: a JSON API under /api/v1, a stream of
|
||||
// events (server-sent events), WebSockets in JSON and protobuf, and
|
||||
// Prometheus metrics. It acts through the BBS as callers do: the same
|
||||
// checks, the same cleaning, the same logs.
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/Neo-Desktop/bbs-sec/internal/bbs"
|
||||
"github.com/Neo-Desktop/bbs-sec/internal/fido"
|
||||
"github.com/Neo-Desktop/bbs-sec/internal/nntp"
|
||||
"github.com/Neo-Desktop/bbs-sec/internal/store"
|
||||
)
|
||||
|
||||
// Scopes a token may have.
|
||||
var Scopes = []string{"read", "post", "mail", "chat", "files", "sysop"}
|
||||
|
||||
// Settings are the [http] section's.
|
||||
type Settings struct {
|
||||
Address string
|
||||
TLS bool
|
||||
CertFile string
|
||||
KeyFile string
|
||||
Anonymous bool // /system and /who without a token
|
||||
CORS string // an origin allowed to call from a browser ("": none)
|
||||
Metrics string // the metrics' own address ("": none)
|
||||
MaxPerIP int // connections at once from one address
|
||||
Rate float64 // requests a second, per token (and per address before a login)
|
||||
Burst int // and at once
|
||||
SessionTTL time.Duration // of a login's token
|
||||
MaxBody int64 // bytes of a JSON request
|
||||
}
|
||||
|
||||
// Server serves the API.
|
||||
type Server struct {
|
||||
B *bbs.BBS
|
||||
S Settings
|
||||
Fido *fido.Fido // nil: no FidoNet
|
||||
News *nntp.Service // nil: no news
|
||||
Peers []*nntp.Peer // the news peers
|
||||
Ctx context.Context // the server's, for work started by a request
|
||||
|
||||
mu sync.Mutex
|
||||
limits map[string]*bucket
|
||||
streams map[int64][]*bbs.Node // a token's open streams' nodes
|
||||
perIP map[string]int
|
||||
}
|
||||
|
||||
// Token is a token's secret, and its hash as stored.
|
||||
func NewToken() (secret, hash string) {
|
||||
var b [32]byte
|
||||
rand.Read(b[:])
|
||||
secret = "bbs_" + base64.RawURLEncoding.EncodeToString(b[:])
|
||||
return secret, HashToken(secret)
|
||||
}
|
||||
|
||||
// HashToken is how a token is kept.
|
||||
func HashToken(secret string) string {
|
||||
h := sha256.Sum256([]byte(secret))
|
||||
return hex.EncodeToString(h[:])
|
||||
}
|
||||
|
||||
// ParseScopes checks a list of scopes (commas or spaces).
|
||||
func ParseScopes(s string) (string, error) {
|
||||
var out []string
|
||||
for _, f := range strings.FieldsFunc(s, func(r rune) bool { return r == ',' || r == ' ' }) {
|
||||
f = strings.ToLower(f)
|
||||
ok := false
|
||||
for _, k := range Scopes {
|
||||
ok = ok || f == k
|
||||
}
|
||||
if !ok {
|
||||
return "", fmt.Errorf("%q is not a scope (%s)", f, strings.Join(Scopes, ", "))
|
||||
}
|
||||
out = append(out, f)
|
||||
}
|
||||
if len(out) == 0 {
|
||||
return "", errors.New("no scopes")
|
||||
}
|
||||
return strings.Join(out, " "), nil
|
||||
}
|
||||
|
||||
// who is a request's caller: a token's user, or nobody.
|
||||
type who struct {
|
||||
user *store.User
|
||||
token *store.Token
|
||||
scopes map[string]bool
|
||||
}
|
||||
|
||||
func (w *who) has(scope string) bool { return w != nil && w.scopes[scope] }
|
||||
|
||||
type ctxKey struct{}
|
||||
|
||||
func whoOf(r *http.Request) *who {
|
||||
w, _ := r.Context().Value(ctxKey{}).(*who)
|
||||
return w
|
||||
}
|
||||
|
||||
// apiError is an error's JSON.
|
||||
type apiError struct {
|
||||
Error string `json:"error"`
|
||||
Code string `json:"code"`
|
||||
}
|
||||
|
||||
var codes = map[int]string{
|
||||
http.StatusBadRequest: "bad_request", http.StatusUnauthorized: "unauthorized",
|
||||
http.StatusForbidden: "forbidden", http.StatusNotFound: "not_found",
|
||||
http.StatusConflict: "conflict", http.StatusTooManyRequests: "too_many",
|
||||
http.StatusRequestEntityTooLarge: "too_large", http.StatusServiceUnavailable: "unavailable",
|
||||
http.StatusInternalServerError: "internal", http.StatusMethodNotAllowed: "bad_method",
|
||||
}
|
||||
|
||||
func writeJSON(w http.ResponseWriter, status int, v any) {
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
w.WriteHeader(status)
|
||||
enc := json.NewEncoder(w)
|
||||
enc.SetEscapeHTML(false)
|
||||
enc.Encode(v)
|
||||
}
|
||||
|
||||
func fail(w http.ResponseWriter, status int, msg string) {
|
||||
writeJSON(w, status, apiError{Error: msg, Code: codes[status]})
|
||||
}
|
||||
|
||||
// decode reads a JSON request body, no bigger than the limit, with no
|
||||
// fields the type has not.
|
||||
func (s *Server) decode(w http.ResponseWriter, r *http.Request, v any) bool {
|
||||
r.Body = http.MaxBytesReader(w, r.Body, s.S.MaxBody)
|
||||
dec := json.NewDecoder(r.Body)
|
||||
dec.DisallowUnknownFields()
|
||||
if err := dec.Decode(v); err != nil {
|
||||
var mb *http.MaxBytesError
|
||||
if errors.As(err, &mb) {
|
||||
fail(w, http.StatusRequestEntityTooLarge, "the request is too big")
|
||||
} else {
|
||||
fail(w, http.StatusBadRequest, "bad JSON: "+err.Error())
|
||||
}
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// bucket is a rate limit's token bucket.
|
||||
type bucket struct {
|
||||
tokens float64
|
||||
last time.Time
|
||||
}
|
||||
|
||||
// allow takes one from key's bucket.
|
||||
func (s *Server) allow(key string) bool {
|
||||
if s.S.Rate <= 0 {
|
||||
return true
|
||||
}
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
now := time.Now()
|
||||
b := s.limits[key]
|
||||
if b == nil {
|
||||
if len(s.limits) > 100000 {
|
||||
s.limits = map[string]*bucket{}
|
||||
}
|
||||
b = &bucket{tokens: float64(s.S.Burst), last: now}
|
||||
s.limits[key] = b
|
||||
}
|
||||
b.tokens = min(float64(s.S.Burst), b.tokens+now.Sub(b.last).Seconds()*s.S.Rate)
|
||||
b.last = now
|
||||
if b.tokens < 1 {
|
||||
return false
|
||||
}
|
||||
b.tokens--
|
||||
return true
|
||||
}
|
||||
|
||||
func hostOf(r *http.Request) string {
|
||||
h, _, err := net.SplitHostPort(r.RemoteAddr)
|
||||
if err != nil {
|
||||
return r.RemoteAddr
|
||||
}
|
||||
return h
|
||||
}
|
||||
|
||||
// authenticate finds the request's token: "Authorization: Bearer ...".
|
||||
func (s *Server) authenticate(r *http.Request) (*who, error) {
|
||||
h := r.Header.Get("Authorization")
|
||||
if h == "" {
|
||||
return nil, nil
|
||||
}
|
||||
secret, ok := strings.CutPrefix(h, "Bearer ")
|
||||
if !ok {
|
||||
return nil, errors.New("Authorization must be Bearer")
|
||||
}
|
||||
return s.byToken(strings.TrimSpace(secret))
|
||||
}
|
||||
|
||||
var errBadToken = errors.New("no such token, or it has expired")
|
||||
|
||||
// byToken finds who a token is.
|
||||
func (s *Server) byToken(secret string) (*who, error) {
|
||||
if !strings.HasPrefix(secret, "bbs_") || len(secret) > 100 {
|
||||
return nil, errBadToken
|
||||
}
|
||||
t, err := s.B.Store.TokenByHash(HashToken(secret))
|
||||
if err != nil {
|
||||
return nil, errBadToken
|
||||
}
|
||||
u, err := s.B.Store.UserByID(t.UserID)
|
||||
if err != nil || u.Locked {
|
||||
return nil, errBadToken
|
||||
}
|
||||
s.B.Store.TouchToken(t.ID)
|
||||
w := &who{user: u, token: t, scopes: map[string]bool{}}
|
||||
for _, sc := range strings.Fields(t.Scopes) {
|
||||
// sysop needs a sysop, whatever the token says
|
||||
if sc != "sysop" || u.Sysop {
|
||||
w.scopes[sc] = true
|
||||
}
|
||||
}
|
||||
return w, nil
|
||||
}
|
||||
|
||||
// route is a handler and what it needs: a scope ("": none, "any": a
|
||||
// login), or anonymous access by the settings.
|
||||
type route struct {
|
||||
scope string
|
||||
anon bool // without a token when [http] anonymous = yes
|
||||
h func(http.ResponseWriter, *http.Request)
|
||||
}
|
||||
|
||||
func (s *Server) wrap(rt route) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
defer func() {
|
||||
if v := recover(); v != nil {
|
||||
s.B.Log.Printf("http %s %s: panic: %v", r.Method, r.URL.Path, v)
|
||||
fail(w, http.StatusInternalServerError, "something went wrong")
|
||||
}
|
||||
}()
|
||||
s.cors(w, r)
|
||||
wh, err := s.authenticate(r)
|
||||
key := "ip:" + hostOf(r)
|
||||
if wh != nil {
|
||||
key = fmt.Sprintf("token:%d", wh.token.ID)
|
||||
}
|
||||
if !s.allow(key) {
|
||||
w.Header().Set("Retry-After", "1")
|
||||
fail(w, http.StatusTooManyRequests, "too many requests: slow down")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
time.Sleep(s.B.FailDelay)
|
||||
fail(w, http.StatusUnauthorized, err.Error())
|
||||
return
|
||||
}
|
||||
switch {
|
||||
case wh == nil && rt.anon && s.S.Anonymous:
|
||||
case wh == nil && rt.scope != "":
|
||||
w.Header().Set("WWW-Authenticate", `Bearer realm="bbs"`)
|
||||
fail(w, http.StatusUnauthorized, "a token is needed (Authorization: Bearer ...)")
|
||||
return
|
||||
case wh == nil && rt.anon:
|
||||
fail(w, http.StatusUnauthorized, "a token is needed (Authorization: Bearer ...)")
|
||||
return
|
||||
case rt.scope != "" && rt.scope != "any" && !wh.has(rt.scope):
|
||||
fail(w, http.StatusForbidden, "the token has no "+rt.scope+" scope")
|
||||
return
|
||||
}
|
||||
ctx := context.WithValue(r.Context(), ctxKey{}, wh)
|
||||
rt.h(w, r.WithContext(ctx))
|
||||
}
|
||||
}
|
||||
|
||||
// cors answers a browser on the allowed origin.
|
||||
func (s *Server) cors(w http.ResponseWriter, r *http.Request) {
|
||||
if s.S.CORS == "" || r.Header.Get("Origin") != s.S.CORS {
|
||||
return
|
||||
}
|
||||
h := w.Header()
|
||||
h.Set("Access-Control-Allow-Origin", s.S.CORS)
|
||||
h.Set("Access-Control-Allow-Headers", "Authorization, Content-Type")
|
||||
h.Set("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE")
|
||||
h.Set("Access-Control-Max-Age", "600")
|
||||
h.Add("Vary", "Origin")
|
||||
}
|
||||
|
||||
// Handler is the API's routes.
|
||||
func (s *Server) Handler() http.Handler {
|
||||
if s.limits == nil {
|
||||
s.limits = map[string]*bucket{}
|
||||
s.streams = map[int64][]*bbs.Node{}
|
||||
s.perIP = map[string]int{}
|
||||
}
|
||||
if s.S.MaxBody == 0 {
|
||||
s.S.MaxBody = 64 << 10
|
||||
}
|
||||
if s.Ctx == nil {
|
||||
s.Ctx = context.Background()
|
||||
}
|
||||
mux := http.NewServeMux()
|
||||
for pattern, rt := range s.routes() {
|
||||
mux.Handle(pattern, s.wrap(rt))
|
||||
}
|
||||
mux.HandleFunc("OPTIONS /api/", func(w http.ResponseWriter, r *http.Request) {
|
||||
s.cors(w, r)
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
})
|
||||
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
|
||||
fail(w, http.StatusNotFound, "no such endpoint: see /api/v1/openapi.json")
|
||||
})
|
||||
return securityHeaders(mux)
|
||||
}
|
||||
|
||||
func securityHeaders(h http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("X-Content-Type-Options", "nosniff")
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
h.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
// limitListener holds connections from one address to a number.
|
||||
type limitListener struct {
|
||||
net.Listener
|
||||
s *Server
|
||||
}
|
||||
|
||||
type limitConn struct {
|
||||
net.Conn
|
||||
s *Server
|
||||
host string
|
||||
once sync.Once
|
||||
}
|
||||
|
||||
func (l *limitListener) Accept() (net.Conn, error) {
|
||||
for {
|
||||
c, err := l.Listener.Accept()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
h, _, _ := net.SplitHostPort(c.RemoteAddr().String())
|
||||
l.s.mu.Lock()
|
||||
if l.s.S.MaxPerIP > 0 && l.s.perIP[h] >= l.s.S.MaxPerIP {
|
||||
l.s.mu.Unlock()
|
||||
c.Close()
|
||||
continue
|
||||
}
|
||||
l.s.perIP[h]++
|
||||
l.s.mu.Unlock()
|
||||
return &limitConn{Conn: c, s: l.s, host: h}, nil
|
||||
}
|
||||
}
|
||||
|
||||
func (c *limitConn) Close() error {
|
||||
c.once.Do(func() {
|
||||
c.s.mu.Lock()
|
||||
if c.s.perIP[c.host]--; c.s.perIP[c.host] <= 0 {
|
||||
delete(c.s.perIP, c.host)
|
||||
}
|
||||
c.s.mu.Unlock()
|
||||
})
|
||||
return c.Conn.Close()
|
||||
}
|
||||
|
||||
// Run serves until ctx is done.
|
||||
func (s *Server) Run(ctx context.Context) error {
|
||||
ln, err := net.Listen("tcp", s.S.Address)
|
||||
if err != nil {
|
||||
return fmt.Errorf("http: %w", err)
|
||||
}
|
||||
return s.Serve(ctx, ln)
|
||||
}
|
||||
|
||||
// Serve serves on ln until ctx is done.
|
||||
func (s *Server) Serve(ctx context.Context, ln net.Listener) error {
|
||||
s.Ctx = ctx
|
||||
h := s.Handler()
|
||||
hs := &http.Server{Handler: h, ReadHeaderTimeout: 10 * time.Second, IdleTimeout: 2 * time.Minute,
|
||||
MaxHeaderBytes: 16 << 10, ErrorLog: s.B.Log,
|
||||
BaseContext: func(net.Listener) context.Context { return ctx }}
|
||||
go func() {
|
||||
<-ctx.Done()
|
||||
sh, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
hs.Shutdown(sh)
|
||||
}()
|
||||
go s.expire(ctx)
|
||||
if s.S.Metrics != "" {
|
||||
go s.serveMetrics(ctx)
|
||||
}
|
||||
l := &limitListener{Listener: ln, s: s}
|
||||
s.B.Log.Printf("http: listening on %s (tls %v)", ln.Addr(), s.S.TLS)
|
||||
var err error
|
||||
if s.S.TLS {
|
||||
err = hs.ServeTLS(l, s.S.CertFile, s.S.KeyFile)
|
||||
} else {
|
||||
err = hs.Serve(l)
|
||||
}
|
||||
if errors.Is(err, http.ErrServerClosed) {
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// expire forgets old sessions now and then.
|
||||
func (s *Server) expire(ctx context.Context) {
|
||||
t := time.NewTicker(time.Hour)
|
||||
defer t.Stop()
|
||||
for {
|
||||
s.B.Store.ExpireTokens()
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-t.C:
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,577 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/coder/websocket"
|
||||
"google.golang.org/protobuf/encoding/protojson"
|
||||
"google.golang.org/protobuf/proto"
|
||||
|
||||
"github.com/Neo-Desktop/bbs-sec/internal/api/pb"
|
||||
"github.com/Neo-Desktop/bbs-sec/internal/bbs"
|
||||
"github.com/Neo-Desktop/bbs-sec/internal/files"
|
||||
"github.com/Neo-Desktop/bbs-sec/internal/store"
|
||||
)
|
||||
|
||||
type site struct {
|
||||
t *testing.T
|
||||
b *bbs.BBS
|
||||
s *Server
|
||||
ts *httptest.Server
|
||||
logs *bytes.Buffer
|
||||
}
|
||||
|
||||
func setup(t *testing.T, set Settings) *site {
|
||||
t.Helper()
|
||||
store.BcryptCost = 4
|
||||
dir := t.TempDir()
|
||||
st, err := store.Open(filepath.Join(dir, "bbs.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { st.Close() })
|
||||
logs := &bytes.Buffer{}
|
||||
s := bbs.Defaults()
|
||||
s.Name, s.FailDelay = "Test BBS", 0
|
||||
b := bbs.New(s, st, log.New(logs, "", 0))
|
||||
st.CreateUser("alice", "alicepass1", "Here", false)
|
||||
st.CreateUser("bob", "bobpass123", "", false)
|
||||
st.CreateUser("sysop", "sysoppass1", "", true)
|
||||
st.CreateArea("General", "Talk", false)
|
||||
st.CreateArea("News", "From the sysop", true)
|
||||
st.CreateFileArea("Uploads", "Files", false)
|
||||
if b.Files, err = files.Open(st, filepath.Join(dir, "files"), 1<<20, 0); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if set.SessionTTL == 0 {
|
||||
set.SessionTTL = time.Hour
|
||||
}
|
||||
set.Anonymous = true
|
||||
srv := &Server{B: b, S: set}
|
||||
ts := httptest.NewServer(srv.Handler())
|
||||
t.Cleanup(ts.Close)
|
||||
return &site{t: t, b: b, s: srv, ts: ts, logs: logs}
|
||||
}
|
||||
|
||||
// do makes a request: its status and JSON body.
|
||||
func (s *site) do(method, path, token string, body any) (int, map[string]any, []any) {
|
||||
s.t.Helper()
|
||||
var rd io.Reader
|
||||
switch b := body.(type) {
|
||||
case nil:
|
||||
case string:
|
||||
rd = strings.NewReader(b)
|
||||
case []byte:
|
||||
rd = bytes.NewReader(b)
|
||||
default:
|
||||
j, _ := json.Marshal(b)
|
||||
rd = bytes.NewReader(j)
|
||||
}
|
||||
req, _ := http.NewRequest(method, s.ts.URL+path, rd)
|
||||
if token != "" {
|
||||
req.Header.Set("Authorization", "Bearer "+token)
|
||||
}
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
s.t.Fatal(err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
raw, _ := io.ReadAll(resp.Body)
|
||||
var m map[string]any
|
||||
var a []any
|
||||
if json.Unmarshal(raw, &m) != nil {
|
||||
json.Unmarshal(raw, &a)
|
||||
}
|
||||
return resp.StatusCode, m, a
|
||||
}
|
||||
|
||||
func (s *site) login(name, pw string) string {
|
||||
s.t.Helper()
|
||||
code, m, _ := s.do("POST", "/api/v1/login", "", map[string]any{"name": name, "password": pw})
|
||||
if code != 200 {
|
||||
s.t.Fatalf("login %s: %d %v", name, code, m)
|
||||
}
|
||||
return m["token"].(string)
|
||||
}
|
||||
|
||||
// key makes an API key of the scopes for a user.
|
||||
func (s *site) key(name, scopes string) string {
|
||||
u, _ := s.b.Store.UserByName(name)
|
||||
secret, hash := NewToken()
|
||||
s.b.Store.AddToken(&store.Token{UserID: u.ID, Name: "test", Hash: hash, Scopes: scopes})
|
||||
return secret
|
||||
}
|
||||
|
||||
func TestREST(t *testing.T) {
|
||||
s := setup(t, Settings{})
|
||||
if code, m, _ := s.do("GET", "/api/v1/system", "", nil); code != 200 || m["name"] != "Test BBS" || m["users"] != 3.0 {
|
||||
t.Fatalf("system: %d %v", code, m)
|
||||
}
|
||||
if code, _, _ := s.do("POST", "/api/v1/login", "", map[string]any{"name": "alice", "password": "wrong"}); code != 401 {
|
||||
t.Errorf("wrong password: %d", code)
|
||||
}
|
||||
alice := s.login("alice", "alicepass1")
|
||||
bob := s.login("bob", "bobpass123")
|
||||
if code, m, _ := s.do("GET", "/api/v1/me", alice, nil); code != 200 || m["user"].(map[string]any)["name"] != "alice" {
|
||||
t.Fatalf("me: %d %v", code, m)
|
||||
}
|
||||
for _, c := range []struct {
|
||||
token string
|
||||
want int
|
||||
}{{"", 401}, {"bbs_nope", 401}, {"Basic x", 401}} {
|
||||
if code, _, _ := s.do("GET", "/api/v1/me", c.token, nil); code != c.want {
|
||||
t.Errorf("me with %q: %d", c.token, code)
|
||||
}
|
||||
}
|
||||
|
||||
// areas and messages
|
||||
_, _, areas := s.do("GET", "/api/v1/areas", alice, nil)
|
||||
if len(areas) != 2 || areas[1].(map[string]any)["can_post"] != false {
|
||||
t.Fatalf("areas %v", areas)
|
||||
}
|
||||
code, m, _ := s.do("POST", "/api/v1/areas/1/messages", alice, map[string]any{"subject": "Hi \x1b[2J", "body": "line one\r\nline two"})
|
||||
if code != 201 || m["subject"] != "Hi [2J" || m["body"] != "line one\nline two" || m["from"] != "alice" {
|
||||
t.Fatalf("post: %d %v", code, m)
|
||||
}
|
||||
if code, m, _ := s.do("POST", "/api/v1/areas/2/messages", alice, map[string]any{"subject": "x", "body": "y"}); code != 403 {
|
||||
t.Errorf("post to a sysop area: %d %v", code, m)
|
||||
}
|
||||
if code, _, _ := s.do("POST", "/api/v1/areas/1/messages", alice, map[string]any{"subject": "x", "body": "y", "extra": 1}); code != 400 {
|
||||
t.Errorf("unknown field: %d", code)
|
||||
}
|
||||
if code, _, _ := s.do("POST", "/api/v1/areas/1/messages", alice, strings.Repeat("x", 70<<10)); code != 413 && code != 400 {
|
||||
t.Errorf("too big: %d", code)
|
||||
}
|
||||
s.do("POST", "/api/v1/areas/1/messages", bob, map[string]any{"subject": "Re: Hi", "body": "hello", "reply_to": 1})
|
||||
code, m, _ = s.do("GET", "/api/v1/areas/1/messages?limit=1", alice, nil)
|
||||
if code != 200 || len(m["messages"].([]any)) != 1 || m["next"] != "/api/v1/areas/1/messages?after=1&limit=1" {
|
||||
t.Fatalf("page: %v", m)
|
||||
}
|
||||
if code, m, _ = s.do("GET", "/api/v1/messages/2", alice, nil); m["reply_to"] != 1.0 {
|
||||
t.Errorf("message: %v", m)
|
||||
}
|
||||
if code, m, _ = s.do("PUT", "/api/v1/areas/1/lastread", alice, map[string]any{"id": 1}); m["unread"] != 1.0 {
|
||||
t.Errorf("lastread: %d %v", code, m)
|
||||
}
|
||||
|
||||
// mail
|
||||
if code, m, _ = s.do("POST", "/api/v1/mail", alice, map[string]any{"to": "bob", "subject": "Psst", "body": "for you"}); code != 202 {
|
||||
t.Fatalf("mail: %d %v", code, m)
|
||||
}
|
||||
if code, m, _ = s.do("POST", "/api/v1/mail", alice, map[string]any{"to": "nobody", "subject": "x", "body": "y"}); code != 400 {
|
||||
t.Errorf("mail to nobody: %d", code)
|
||||
}
|
||||
_, _, in := s.do("GET", "/api/v1/mail", bob, nil)
|
||||
if len(in) != 1 || in[0].(map[string]any)["read"] != false {
|
||||
t.Fatalf("inbox %v", in)
|
||||
}
|
||||
if _, m, _ = s.do("GET", "/api/v1/mail/1", bob, nil); m["body"] != "for you" || m["read"] != true {
|
||||
t.Errorf("mail: %v", m)
|
||||
}
|
||||
if code, _, _ = s.do("GET", "/api/v1/mail/1", alice, nil); code != 404 {
|
||||
t.Errorf("another's mail: %d", code)
|
||||
}
|
||||
if code, _, _ = s.do("DELETE", "/api/v1/mail/1", bob, nil); code != 204 {
|
||||
t.Errorf("delete: %d", code)
|
||||
}
|
||||
|
||||
// scopes
|
||||
readOnly := s.key("alice", "read")
|
||||
if code, m, _ = s.do("POST", "/api/v1/areas/1/messages", readOnly, map[string]any{"subject": "x", "body": "y"}); code != 403 {
|
||||
t.Errorf("read-only post: %d %v", code, m)
|
||||
}
|
||||
if code, _, _ = s.do("GET", "/api/v1/mail", readOnly, nil); code != 403 {
|
||||
t.Errorf("read-only mail: %d", code)
|
||||
}
|
||||
// a key that says sysop for a non-sysop has no sysop
|
||||
fake := s.key("alice", "read sysop")
|
||||
if code, _, _ = s.do("GET", "/api/v1/admin/pages", fake, nil); code != 403 {
|
||||
t.Errorf("non-sysop with a sysop key: %d", code)
|
||||
}
|
||||
|
||||
// files
|
||||
code, m, _ = s.do("POST", "/api/v1/fileareas/1/files?name=hello.txt&description=Greeting", alice, []byte("hello, world\n"))
|
||||
if code != 201 || m["size"] != 13.0 {
|
||||
t.Fatalf("upload: %d %v", code, m)
|
||||
}
|
||||
for q, want := range map[string]int{"../x": 400, "hello.txt": 409} {
|
||||
if code, _, _ = s.do("POST", "/api/v1/fileareas/1/files?name="+q, alice, []byte("x")); code != want {
|
||||
t.Errorf("upload %s: %d", q, code)
|
||||
}
|
||||
}
|
||||
if code, _, _ = s.do("POST", "/api/v1/fileareas/1/files?name=big.bin", alice, make([]byte, 2<<20)); code != 413 {
|
||||
t.Errorf("too big upload: %d", code)
|
||||
}
|
||||
req, _ := http.NewRequest("GET", s.ts.URL+"/api/v1/files/1/content", nil)
|
||||
req.Header.Set("Authorization", "Bearer "+alice)
|
||||
req.Header.Set("Range", "bytes=7-")
|
||||
resp, _ := http.DefaultClient.Do(req)
|
||||
got, _ := io.ReadAll(resp.Body)
|
||||
resp.Body.Close()
|
||||
if resp.StatusCode != 206 || string(got) != "world\n" {
|
||||
t.Errorf("range download: %d %q", resp.StatusCode, got)
|
||||
}
|
||||
|
||||
// sysop
|
||||
sys := s.login("sysop", "sysoppass1")
|
||||
if code, _, _ = s.do("POST", "/api/v1/admin/users", alice, map[string]any{"name": "carol", "password": "carolpass1"}); code != 403 {
|
||||
t.Errorf("alice adds a user: %d", code)
|
||||
}
|
||||
if code, m, _ = s.do("POST", "/api/v1/admin/users", sys, map[string]any{"name": "carol", "password": "carolpass1"}); code != 201 {
|
||||
t.Fatalf("add user: %d %v", code, m)
|
||||
}
|
||||
carol := s.login("carol", "carolpass1")
|
||||
if code, m, _ = s.do("PATCH", "/api/v1/admin/users/carol", sys, map[string]any{"locked": true}); code != 200 || m["locked"] != true {
|
||||
t.Fatalf("lock: %d %v", code, m)
|
||||
}
|
||||
if code, _, _ = s.do("GET", "/api/v1/me", carol, nil); code != 401 {
|
||||
t.Errorf("a locked user's token: %d", code)
|
||||
}
|
||||
if code, m, _ = s.do("PATCH", "/api/v1/admin/areas/1", sys, map[string]any{"newsgroup": "Bad Name"}); code != 400 {
|
||||
t.Errorf("bad newsgroup: %d %v", code, m)
|
||||
}
|
||||
if code, m, _ = s.do("PATCH", "/api/v1/admin/areas/1", sys, map[string]any{"newsgroup": "bbs.general", "echo_tag": "test_echo"}); code != 200 || m["echo_tag"] != "TEST_ECHO" {
|
||||
t.Errorf("area: %d %v", code, m)
|
||||
}
|
||||
|
||||
// tokens and logout
|
||||
_, _, toks := s.do("GET", "/api/v1/me/tokens", alice, nil)
|
||||
if len(toks) != 3 {
|
||||
t.Errorf("alice's tokens: %v", toks)
|
||||
}
|
||||
if code, _, _ = s.do("POST", "/api/v1/logout", alice, nil); code != 204 {
|
||||
t.Errorf("logout: %d", code)
|
||||
}
|
||||
if code, _, _ = s.do("GET", "/api/v1/me", alice, nil); code != 401 {
|
||||
t.Errorf("after logout: %d", code)
|
||||
}
|
||||
if strings.Contains(s.logs.String(), "bbs_") {
|
||||
t.Error("a token in the log")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRateAndOpenAPI(t *testing.T) {
|
||||
s := setup(t, Settings{Rate: 1, Burst: 3})
|
||||
n429 := 0
|
||||
for i := 0; i < 6; i++ {
|
||||
if code, _, _ := s.do("GET", "/api/v1/system", "", nil); code == 429 {
|
||||
n429++
|
||||
}
|
||||
}
|
||||
if n429 < 2 {
|
||||
t.Errorf("%d of 6 limited", n429)
|
||||
}
|
||||
// every route is in the document, and only they
|
||||
doc := map[string]bool{}
|
||||
for _, o := range ops {
|
||||
doc[o.method+" "+o.path] = true
|
||||
}
|
||||
for p := range s.s.routes() {
|
||||
if !doc[p] {
|
||||
t.Errorf("%s is not in the OpenAPI document", p)
|
||||
}
|
||||
delete(doc, p)
|
||||
}
|
||||
for p := range doc {
|
||||
t.Errorf("the OpenAPI document has %s, which is not a route", p)
|
||||
}
|
||||
b, err := json.Marshal(document())
|
||||
if err != nil || !bytes.Contains(b, []byte(`"openapi":"3.1.0"`)) {
|
||||
t.Errorf("document: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// wsClient is a WebSocket client in either encoding.
|
||||
type wsClient struct {
|
||||
t *testing.T
|
||||
c *websocket.Conn
|
||||
binary bool
|
||||
id uint32
|
||||
queue []*pb.ServerMessage
|
||||
}
|
||||
|
||||
func (s *site) ws(binary bool, token string, header bool) *wsClient {
|
||||
s.t.Helper()
|
||||
u := "ws" + strings.TrimPrefix(s.ts.URL, "http") + "/api/v1/ws"
|
||||
sub := ProtoJSON
|
||||
if binary {
|
||||
u += "/proto"
|
||||
sub = ProtoBinary
|
||||
}
|
||||
opts := &websocket.DialOptions{Subprotocols: []string{sub}}
|
||||
if header && token != "" {
|
||||
opts.HTTPHeader = http.Header{"Authorization": {"Bearer " + token}}
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
c, resp, err := websocket.Dial(ctx, u, opts)
|
||||
if err != nil {
|
||||
s.t.Fatalf("dial: %v", err)
|
||||
}
|
||||
if resp.Header.Get("Sec-WebSocket-Protocol") != sub {
|
||||
s.t.Errorf("subprotocol %q", resp.Header.Get("Sec-WebSocket-Protocol"))
|
||||
}
|
||||
w := &wsClient{t: s.t, c: c, binary: binary}
|
||||
s.t.Cleanup(func() { c.CloseNow() })
|
||||
if !header {
|
||||
w.send(&pb.ClientMessage{Request: &pb.ClientMessage_Auth{Auth: &pb.Auth{Token: token}}})
|
||||
}
|
||||
return w
|
||||
}
|
||||
|
||||
func (w *wsClient) send(m *pb.ClientMessage) uint32 {
|
||||
w.t.Helper()
|
||||
w.id++
|
||||
m.Id = w.id
|
||||
var b []byte
|
||||
typ := websocket.MessageText
|
||||
if w.binary {
|
||||
b, _ = proto.Marshal(m)
|
||||
typ = websocket.MessageBinary
|
||||
} else {
|
||||
b, _ = protojson.Marshal(m)
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
if err := w.c.Write(ctx, typ, b); err != nil {
|
||||
w.t.Fatal(err)
|
||||
}
|
||||
return w.id
|
||||
}
|
||||
|
||||
func (w *wsClient) recv() *pb.ServerMessage {
|
||||
w.t.Helper()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
typ, b, err := w.c.Read(ctx)
|
||||
if err != nil {
|
||||
w.t.Fatalf("read: %v", err)
|
||||
}
|
||||
m := &pb.ServerMessage{}
|
||||
if w.binary {
|
||||
if typ != websocket.MessageBinary {
|
||||
w.t.Fatal("a text frame on the protobuf endpoint")
|
||||
}
|
||||
err = proto.Unmarshal(b, m)
|
||||
} else {
|
||||
if typ != websocket.MessageText {
|
||||
w.t.Fatal("a binary frame on the JSON endpoint")
|
||||
}
|
||||
err = protojson.Unmarshal(b, m)
|
||||
}
|
||||
if err != nil {
|
||||
w.t.Fatal(err)
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
// until reads until a message matches (keeping none of the others).
|
||||
func (w *wsClient) until(what string, ok func(*pb.ServerMessage) bool) *pb.ServerMessage {
|
||||
w.t.Helper()
|
||||
for i := 0; i < 50; i++ {
|
||||
if m := w.recv(); ok(m) {
|
||||
return m
|
||||
}
|
||||
}
|
||||
w.t.Fatalf("no %s", what)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (w *wsClient) event(kind pb.Event_Kind) *pb.Event {
|
||||
w.t.Helper()
|
||||
return w.until(kind.String(), func(m *pb.ServerMessage) bool { return m.GetEvent().GetKind() == kind }).GetEvent()
|
||||
}
|
||||
|
||||
func (w *wsClient) reply(id uint32) *pb.ServerMessage {
|
||||
w.t.Helper()
|
||||
return w.until("a reply", func(m *pb.ServerMessage) bool {
|
||||
return m.Id == id && (m.GetOk() != nil || m.GetError() != nil || m.GetNodes() != nil || m.GetPong() != nil || m.GetRooms() != nil)
|
||||
})
|
||||
}
|
||||
|
||||
func TestWebSockets(t *testing.T) {
|
||||
s := setup(t, Settings{})
|
||||
alice := s.ws(false, s.login("alice", "alicepass1"), false) // JSON, Auth message
|
||||
sysop := s.ws(true, s.login("sysop", "sysoppass1"), true) // protobuf, header
|
||||
if w := alice.recv().GetWelcome(); w == nil || w.User != "alice" || w.Bbs != "Test BBS" {
|
||||
t.Fatalf("alice's welcome: %v", w)
|
||||
}
|
||||
if w := sysop.recv().GetWelcome(); w == nil || w.User != "sysop" {
|
||||
t.Fatalf("sysop's welcome: %v", w)
|
||||
}
|
||||
// both are nodes, as "web"
|
||||
id := alice.send(&pb.ClientMessage{Request: &pb.ClientMessage_Who{Who: &pb.Who{}}})
|
||||
if nl := alice.reply(id).GetNodes(); len(nl.GetNodes()) != 2 || nl.Nodes[0].Via != "web" {
|
||||
t.Fatalf("who: %v", nl)
|
||||
}
|
||||
|
||||
// chat: the protobuf client and the JSON one in a room
|
||||
id = sysop.send(&pb.ClientMessage{Request: &pb.ClientMessage_Join{Join: &pb.JoinRoom{Room: "main"}}})
|
||||
if r := sysop.reply(id).GetOk(); r.GetRoom() != "main" {
|
||||
t.Fatalf("join: %v", r)
|
||||
}
|
||||
id = alice.send(&pb.ClientMessage{Request: &pb.ClientMessage_Join{Join: &pb.JoinRoom{Room: "main"}}})
|
||||
alice.reply(id)
|
||||
if e := sysop.event(pb.Event_JOINED); e.From != "alice" {
|
||||
t.Errorf("joined: %v", e)
|
||||
}
|
||||
alice.send(&pb.ClientMessage{Request: &pb.ClientMessage_Say{Say: &pb.Say{Text: "hello from JSON \x1b[31m"}}})
|
||||
if e := sysop.event(pb.Event_SAID); e.Text != "hello from JSON [31m" || e.Line != "alice: hello from JSON [31m" || e.Time == nil {
|
||||
t.Errorf("said: %v", e)
|
||||
}
|
||||
sysop.send(&pb.ClientMessage{Request: &pb.ClientMessage_Say{Say: &pb.Say{Text: "waves", Emote: true}}})
|
||||
if e := alice.event(pb.Event_EMOTED); e.From != "sysop" {
|
||||
t.Errorf("emoted: %v", e)
|
||||
}
|
||||
id = alice.send(&pb.ClientMessage{Request: &pb.ClientMessage_Command{Command: &pb.ChatCommand{Line: "/who"}}})
|
||||
if l := alice.until("lines", func(m *pb.ServerMessage) bool { return m.Id == id && m.GetLines() != nil }).GetLines(); len(l.Lines) != 1 || !strings.HasPrefix(l.Lines[0], "In main:") {
|
||||
t.Errorf("/who: %v", l)
|
||||
}
|
||||
// a command only sysops have
|
||||
id = alice.send(&pb.ClientMessage{Request: &pb.ClientMessage_Command{Command: &pb.ChatCommand{Line: "/busy"}}})
|
||||
if e := alice.reply(id).GetError(); e.GetCode() != "forbidden" {
|
||||
t.Errorf("/busy: %v", e)
|
||||
}
|
||||
|
||||
// paging: alice pages, the sysop answers
|
||||
id = alice.send(&pb.ClientMessage{Request: &pb.ClientMessage_Page{Page: &pb.Page{Reason: "help"}}})
|
||||
r := alice.reply(id)
|
||||
if !strings.HasPrefix(r.GetOk().GetRoom(), "sysop-") {
|
||||
t.Fatalf("page: %v", r)
|
||||
}
|
||||
if e := sysop.event(pb.Event_PAGED); e.From != "alice" || e.Text != "help" {
|
||||
t.Errorf("paged: %v", e)
|
||||
}
|
||||
id = sysop.send(&pb.ClientMessage{Request: &pb.ClientMessage_Answer{Answer: &pb.AnswerPage{}}})
|
||||
if r := sysop.reply(id).GetOk(); !strings.HasPrefix(r.GetRoom(), "sysop-") {
|
||||
t.Fatalf("answer: %v", r)
|
||||
}
|
||||
if e := alice.event(pb.Event_NOTICE); !strings.Contains(e.Text, "answered your page") {
|
||||
t.Errorf("notice: %v", e)
|
||||
}
|
||||
sysop.send(&pb.ClientMessage{Request: &pb.ClientMessage_Say{Say: &pb.Say{Text: "how can I help?"}}})
|
||||
if e := alice.event(pb.Event_SAID); e.From != "sysop" {
|
||||
t.Errorf("in the page's room: %v", e)
|
||||
}
|
||||
|
||||
// mail comes as an event
|
||||
bob := s.login("bob", "bobpass123")
|
||||
s.do("POST", "/api/v1/mail", bob, map[string]any{"to": "alice", "subject": "Hello", "body": "x"})
|
||||
if e := alice.event(pb.Event_MAIL); e.From != "bob" || e.Text != "Hello" {
|
||||
t.Errorf("mail: %v", e)
|
||||
}
|
||||
|
||||
// bad input: not a ClientMessage, the wrong kind of frame
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
alice.c.Write(ctx, websocket.MessageText, []byte(`{"nope": 1}`))
|
||||
if e := alice.until("an error", func(m *pb.ServerMessage) bool { return m.GetError() != nil }).GetError(); e.Code != "bad_request" {
|
||||
t.Errorf("bad message: %v", e)
|
||||
}
|
||||
sysop.c.Write(ctx, websocket.MessageText, []byte(`{}`))
|
||||
if e := sysop.until("an error", func(m *pb.ServerMessage) bool { return m.GetError() != nil }).GetError(); e.Code != "bad_request" {
|
||||
t.Errorf("text on proto: %v", e)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWebSocketRefusals(t *testing.T) {
|
||||
s := setup(t, Settings{})
|
||||
// a bad token
|
||||
w := s.ws(false, "bbs_wrong", false)
|
||||
if e := w.recv().GetError(); e.GetCode() != "unauthorized" {
|
||||
t.Errorf("bad token: %v", e)
|
||||
}
|
||||
// a token without chat
|
||||
w = s.ws(true, s.key("alice", "read"), false)
|
||||
if e := w.recv().GetError(); e.GetCode() != "forbidden" {
|
||||
t.Errorf("no chat scope: %v", e)
|
||||
}
|
||||
// no auth first
|
||||
w = s.ws(false, "", true)
|
||||
w.send(&pb.ClientMessage{Request: &pb.ClientMessage_Ping{Ping: &pb.Ping{}}})
|
||||
if e := w.recv().GetError(); e.GetCode() != "unauthorized" {
|
||||
t.Errorf("ping before auth: %v", e)
|
||||
}
|
||||
// all lines busy
|
||||
s.b.MaxNodes = 0
|
||||
w = s.ws(false, s.login("alice", "alicepass1"), true)
|
||||
if e := w.recv().GetError(); e.GetCode() != "unavailable" {
|
||||
t.Errorf("busy: %v", e)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEventsAndNodeMessages(t *testing.T) {
|
||||
s := setup(t, Settings{})
|
||||
alice := s.login("alice", "alicepass1")
|
||||
bob := s.login("bob", "bobpass123")
|
||||
// a node message needs a stream
|
||||
if code, _, _ := s.do("POST", "/api/v1/nodes/1/message", bob, map[string]any{"text": "hi"}); code != 409 {
|
||||
t.Errorf("no stream: %d", code)
|
||||
}
|
||||
req, _ := http.NewRequest("GET", s.ts.URL+"/api/v1/events", nil)
|
||||
req.Header.Set("Authorization", "Bearer "+alice)
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil || resp.Header.Get("Content-Type") != "text/event-stream" {
|
||||
t.Fatalf("events: %v %v", err, resp.Header)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
rd := bufio.NewReader(resp.Body)
|
||||
line := func() string {
|
||||
l, err := rd.ReadString('\n')
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return strings.TrimRight(l, "\n")
|
||||
}
|
||||
for l := line(); !strings.HasPrefix(l, "data: {\"node\":1"); l = line() {
|
||||
}
|
||||
// bob opens a WebSocket (his node) and messages alice's node
|
||||
w := s.ws(false, bob, true)
|
||||
w.recv()
|
||||
if code, m, _ := s.do("POST", "/api/v1/nodes/1/message", bob, map[string]any{"text": "over here"}); code != 202 {
|
||||
t.Fatalf("node message: %d %v", code, m)
|
||||
}
|
||||
var ev, data string
|
||||
for ev == "" || data == "" {
|
||||
l := line()
|
||||
if v, ok := strings.CutPrefix(l, "event: "); ok {
|
||||
ev = v
|
||||
}
|
||||
if v, ok := strings.CutPrefix(l, "data: "); ok && ev != "" {
|
||||
data = v
|
||||
}
|
||||
}
|
||||
e := &pb.Event{}
|
||||
if ev != "private" || protojson.Unmarshal([]byte(data), e) != nil || e.From != "bob" || e.Text != "over here" {
|
||||
t.Errorf("event %q %q", ev, data)
|
||||
}
|
||||
// who's online shows them both, as web
|
||||
_, _, who := s.do("GET", "/api/v1/who", "", nil)
|
||||
if len(who) != 2 {
|
||||
t.Errorf("who: %v", who)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMetrics(t *testing.T) {
|
||||
s := setup(t, Settings{})
|
||||
s.login("alice", "alicepass1")
|
||||
rec := httptest.NewRecorder()
|
||||
s.s.metrics(rec, httptest.NewRequest("GET", "/metrics", nil))
|
||||
body := rec.Body.String()
|
||||
for _, want := range []string{"bbs_users 3\n", "bbs_logins_total 1\n", "# TYPE bbs_posts_total counter", "bbs_nodes 0\n"} {
|
||||
if !strings.Contains(body, want) {
|
||||
t.Errorf("no %q in\n%s", want, body)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/http"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// metrics writes the Prometheus text format.
|
||||
func (s *Server) metrics(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "text/plain; version=0.0.4; charset=utf-8")
|
||||
var b strings.Builder
|
||||
put := func(name, kind, help string, v any, labels ...string) {
|
||||
if help != "" {
|
||||
fmt.Fprintf(&b, "# HELP %s %s\n# TYPE %s %s\n", name, help, name, kind)
|
||||
}
|
||||
l := ""
|
||||
if len(labels) == 2 {
|
||||
l = fmt.Sprintf(`{%s=%q}`, labels[0], labels[1])
|
||||
}
|
||||
fmt.Fprintf(&b, "%s%s %v\n", name, l, v)
|
||||
}
|
||||
nodes := s.B.Nodes()
|
||||
byVia := map[string]int{}
|
||||
for _, n := range nodes {
|
||||
byVia[strings.Fields(n.Via + " ?")[0]]++
|
||||
}
|
||||
put("bbs_nodes", "gauge", "Nodes in use.", len(nodes))
|
||||
vias := make([]string, 0, len(byVia))
|
||||
for v := range byVia {
|
||||
vias = append(vias, v)
|
||||
}
|
||||
sort.Strings(vias)
|
||||
for i, v := range vias {
|
||||
help := ""
|
||||
if i == 0 {
|
||||
help = "Nodes in use by how the caller came."
|
||||
}
|
||||
put("bbs_nodes_by_via", "gauge", help, byVia[v], "via", v)
|
||||
}
|
||||
put("bbs_max_nodes", "gauge", "Nodes there are.", s.B.MaxNodes)
|
||||
if us, err := s.B.Store.Users(); err == nil {
|
||||
put("bbs_users", "gauge", "User accounts.", len(us))
|
||||
}
|
||||
if as, err := s.B.Store.Areas(); err == nil {
|
||||
total := 0
|
||||
for _, a := range as {
|
||||
total += a.Messages
|
||||
}
|
||||
put("bbs_messages", "gauge", "Messages in the areas.", total)
|
||||
}
|
||||
st := &s.B.Stats
|
||||
put("bbs_logins_total", "counter", "Logins since the start.", st.Logins.Load())
|
||||
put("bbs_login_failures_total", "counter", "Failed logins since the start.", st.LoginFailures.Load())
|
||||
put("bbs_posts_total", "counter", "Messages posted here since the start.", st.Posts.Load())
|
||||
put("bbs_mail_sent_total", "counter", "Mail sent since the start.", st.Mail.Load())
|
||||
put("bbs_pages_total", "counter", "Pages of the sysop since the start.", st.Pages.Load())
|
||||
put("bbs_chat_lines_total", "counter", "Lines said in chat since the start.", st.ChatLines.Load())
|
||||
put("bbs_pages_waiting", "gauge", "Callers paging the sysop now.", len(s.B.Pages()))
|
||||
if s.Fido != nil {
|
||||
for i, l := range s.Fido.S.Links {
|
||||
help := ""
|
||||
if i == 0 {
|
||||
help = "Files waiting for a FidoNet link."
|
||||
}
|
||||
put("bbs_fido_outbound_files", "gauge", help, s.Fido.Outbound(l), "link", l.Name)
|
||||
}
|
||||
}
|
||||
w.Write([]byte(b.String()))
|
||||
}
|
||||
|
||||
// serveMetrics serves /metrics on its own address.
|
||||
func (s *Server) serveMetrics(ctx context.Context) {
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("GET /metrics", s.metrics)
|
||||
ln, err := net.Listen("tcp", s.S.Metrics)
|
||||
if err != nil {
|
||||
s.B.Log.Printf("http: metrics: %v", err)
|
||||
return
|
||||
}
|
||||
hs := &http.Server{Handler: mux, ReadHeaderTimeout: 10 * time.Second, ErrorLog: s.B.Log}
|
||||
go func() {
|
||||
<-ctx.Done()
|
||||
hs.Close()
|
||||
}()
|
||||
s.B.Log.Printf("http: metrics on %s", ln.Addr())
|
||||
hs.Serve(ln)
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// op describes an endpoint for the OpenAPI document.
|
||||
type op struct {
|
||||
method, path, summary, scope string
|
||||
body, resp string // schema names ("": none)
|
||||
status int
|
||||
}
|
||||
|
||||
var ops = []op{
|
||||
{"POST", "/api/v1/login", "Log in: a session token", "", "Login", "Session", 200},
|
||||
{"POST", "/api/v1/logout", "End this session", "any", "", "", 204},
|
||||
{"GET", "/api/v1/system", "The system: name, sysop, counts, features", "anonymous", "", "System", 200},
|
||||
{"GET", "/api/v1/who", "Who is online", "anonymous", "", "Nodes", 200},
|
||||
{"GET", "/api/v1/me", "Your account", "read", "", "Me", 200},
|
||||
{"PATCH", "/api/v1/me", "Change your location or password", "read", "PatchMe", "Me", 200},
|
||||
{"GET", "/api/v1/me/tokens", "Your tokens (keys and sessions)", "any", "", "Tokens", 200},
|
||||
{"DELETE", "/api/v1/me/tokens/{id}", "Revoke a token of yours", "any", "", "", 204},
|
||||
{"GET", "/api/v1/users", "The users", "read", "", "Users", 200},
|
||||
{"GET", "/api/v1/users/{name}", "A user", "read", "", "User", 200},
|
||||
{"GET", "/api/v1/areas", "Message areas, with your unread", "read", "", "Areas", 200},
|
||||
{"GET", "/api/v1/areas/{id}", "A message area", "read", "", "Area", 200},
|
||||
{"GET", "/api/v1/areas/{id}/messages", "Messages after an id (?after=, ?limit= up to 200, ?body=no)", "read", "", "MessagePage", 200},
|
||||
{"POST", "/api/v1/areas/{id}/messages", "Post a message", "post", "NewMessage", "Message", 201},
|
||||
{"PUT", "/api/v1/areas/{id}/lastread", "Mark read up to a message", "read", "LastRead", "Area", 200},
|
||||
{"GET", "/api/v1/messages/{id}", "A message", "read", "", "Message", 200},
|
||||
{"GET", "/api/v1/mail", "Your inbox", "mail", "", "Messages", 200},
|
||||
{"GET", "/api/v1/mail/{id}", "A mail of yours (marked read)", "mail", "", "Message", 200},
|
||||
{"DELETE", "/api/v1/mail/{id}", "Delete a mail of yours", "mail", "", "", 204},
|
||||
{"POST", "/api/v1/mail", "Send mail (to a user, or Name@zone:net/node)", "mail", "NewMessage", "Sent", 202},
|
||||
{"GET", "/api/v1/fileareas", "File areas", "files", "", "FileAreas", 200},
|
||||
{"GET", "/api/v1/fileareas/{id}/files", "An area's files", "files", "", "Files", 200},
|
||||
{"POST", "/api/v1/fileareas/{id}/files", "Upload: the body is the file (?name=, ?description=)", "files", "Binary", "File", 201},
|
||||
{"GET", "/api/v1/files/{id}", "A file's details", "files", "", "File", 200},
|
||||
{"GET", "/api/v1/files/{id}/content", "Download (Range works)", "files", "", "Binary", 200},
|
||||
{"GET", "/api/v1/chat/rooms", "Chat rooms in use", "chat", "", "Rooms", 200},
|
||||
{"POST", "/api/v1/nodes/{n}/message", "A line to one node (needs an open stream)", "chat", "Text", "Sent", 202},
|
||||
{"POST", "/api/v1/page", "Page the sysop (needs an open stream)", "chat", "PageReq", "PageRes", 200},
|
||||
{"GET", "/api/v1/events", "Server-sent events: the stream's node's events", "chat or read", "", "EventStream", 200},
|
||||
{"GET", "/api/v1/ws", "WebSocket, JSON (subprotocol bbs.v1.json): see proto/bbs.proto", "chat", "", "", 101},
|
||||
{"GET", "/api/v1/ws/proto", "WebSocket, protobuf (subprotocol bbs.v1.proto): see proto/bbs.proto", "chat", "", "", 101},
|
||||
{"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},
|
||||
{"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},
|
||||
{"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},
|
||||
{"GET", "/api/v1/admin/news", "News: peers and newsgroups", "sysop", "", "Object", 200},
|
||||
{"POST", "/api/v1/admin/news/sync", "Sync with the news peers now", "sysop", "", "Object", 202},
|
||||
{"GET", "/api/v1/openapi.json", "This document", "", "", "Object", 200},
|
||||
}
|
||||
|
||||
func obj(props map[string]any, required ...string) map[string]any {
|
||||
o := map[string]any{"type": "object", "properties": props}
|
||||
if len(required) > 0 {
|
||||
o["required"] = required
|
||||
}
|
||||
return o
|
||||
}
|
||||
|
||||
var (
|
||||
str = map[string]any{"type": "string"}
|
||||
num = map[string]any{"type": "integer"}
|
||||
boo = map[string]any{"type": "boolean"}
|
||||
date = map[string]any{"type": "string", "format": "date-time"}
|
||||
)
|
||||
|
||||
func ref(name string) map[string]any { return map[string]any{"$ref": "#/components/schemas/" + name} }
|
||||
func arr(name string) map[string]any { return map[string]any{"type": "array", "items": ref(name)} }
|
||||
|
||||
var schemas = map[string]any{
|
||||
"Error": obj(map[string]any{"error": str, "code": str}, "error", "code"),
|
||||
"Login": obj(map[string]any{"name": str, "password": str, "scopes": str}, "name", "password"),
|
||||
"Session": obj(map[string]any{"token": str, "expires": date, "user": str, "scopes": map[string]any{"type": "array", "items": str}}),
|
||||
"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}),
|
||||
"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}),
|
||||
"Users": arr("User"),
|
||||
"Me": obj(map[string]any{"user": ref("User"), "unread_mail": num, "scopes": map[string]any{"type": "array", "items": str}}),
|
||||
"PatchMe": obj(map[string]any{"location": str, "old_password": str, "new_password": str}),
|
||||
"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}),
|
||||
"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"),
|
||||
"MessagePage": obj(map[string]any{"messages": arr("Message"), "next": str}),
|
||||
"NewMessage": obj(map[string]any{"to": str, "subject": str, "body": str, "reply_to": num}, "subject", "body"),
|
||||
"LastRead": obj(map[string]any{"id": num}, "id"),
|
||||
"Sent": obj(map[string]any{"sent": boo}),
|
||||
"FileAreas": map[string]any{"type": "array", "items": obj(map[string]any{"id": num, "name": str, "description": str, "sysop_upload": boo, "files": num, "can_upload": boo})},
|
||||
"File": obj(map[string]any{"id": num, "area": num, "name": str, "description": str, "size": num, "sha256": str, "uploader": str, "created": date, "downloads": num}),
|
||||
"Files": arr("File"),
|
||||
"Binary": map[string]any{"type": "string", "format": "binary"},
|
||||
"Rooms": map[string]any{"type": "array", "items": obj(map[string]any{"name": str, "users": map[string]any{"type": "array", "items": str}})},
|
||||
"Text": obj(map[string]any{"text": str}, "text"),
|
||||
"PageReq": obj(map[string]any{"reason": str}, "reason"),
|
||||
"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}),
|
||||
"NewArea": obj(map[string]any{"name": str, "description": str, "sysop_only": boo}, "name"),
|
||||
"PatchArea": obj(map[string]any{"newsgroup": str, "echo_tag": 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"},
|
||||
}
|
||||
|
||||
// document is the OpenAPI 3.1 description.
|
||||
func document() map[string]any {
|
||||
paths := map[string]any{}
|
||||
for _, o := range ops {
|
||||
p, _ := paths[o.path].(map[string]any)
|
||||
if p == nil {
|
||||
p = map[string]any{}
|
||||
paths[o.path] = p
|
||||
}
|
||||
resp := map[string]any{"description": http.StatusText(o.status)}
|
||||
if o.resp != "" {
|
||||
ct := "application/json"
|
||||
if o.resp == "Binary" {
|
||||
ct = "application/octet-stream"
|
||||
} else if o.resp == "EventStream" {
|
||||
ct = "text/event-stream"
|
||||
}
|
||||
resp["content"] = map[string]any{ct: map[string]any{"schema": ref(o.resp)}}
|
||||
}
|
||||
e := map[string]any{"summary": o.summary,
|
||||
"responses": map[string]any{
|
||||
itoa(o.status): resp,
|
||||
"default": map[string]any{"description": "an error", "content": map[string]any{"application/json": map[string]any{"schema": ref("Error")}}},
|
||||
}}
|
||||
switch o.scope {
|
||||
case "", "anonymous":
|
||||
e["security"] = []any{map[string]any{}, map[string]any{"bearer": []any{}}}
|
||||
default:
|
||||
e["security"] = []any{map[string]any{"bearer": []any{}}}
|
||||
e["description"] = "Scope: " + o.scope + "."
|
||||
}
|
||||
if o.body != "" {
|
||||
ct := "application/json"
|
||||
if o.body == "Binary" {
|
||||
ct = "application/octet-stream"
|
||||
}
|
||||
e["requestBody"] = map[string]any{"required": true, "content": map[string]any{ct: map[string]any{"schema": ref(o.body)}}}
|
||||
}
|
||||
var params []any
|
||||
for _, seg := range strings.Split(o.path, "/") {
|
||||
if strings.HasPrefix(seg, "{") {
|
||||
params = append(params, map[string]any{"name": strings.Trim(seg, "{}"), "in": "path", "required": true, "schema": str})
|
||||
}
|
||||
}
|
||||
if params != nil {
|
||||
e["parameters"] = params
|
||||
}
|
||||
p[strings.ToLower(o.method)] = e
|
||||
}
|
||||
return map[string]any{
|
||||
"openapi": "3.1.0",
|
||||
"info": map[string]any{"title": "bbs-sec API", "version": "1",
|
||||
"description": "The BBS over HTTP. Tokens: POST /api/v1/login, or bbs token add. WebSockets: proto/bbs.proto."},
|
||||
"paths": paths,
|
||||
"components": map[string]any{"schemas": schemas, "securitySchemes": map[string]any{"bearer": map[string]any{"type": "http", "scheme": "bearer"}}},
|
||||
}
|
||||
}
|
||||
|
||||
func itoa(n int) string { return strconv.Itoa(n) }
|
||||
|
||||
func (s *Server) openapi(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, http.StatusOK, document())
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,984 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/Neo-Desktop/bbs-sec/internal/bbs"
|
||||
"github.com/Neo-Desktop/bbs-sec/internal/files"
|
||||
"github.com/Neo-Desktop/bbs-sec/internal/ftn"
|
||||
"github.com/Neo-Desktop/bbs-sec/internal/news"
|
||||
"github.com/Neo-Desktop/bbs-sec/internal/store"
|
||||
)
|
||||
|
||||
func (s *Server) routes() map[string]route {
|
||||
return map[string]route{
|
||||
"POST /api/v1/login": {h: s.login},
|
||||
"POST /api/v1/logout": {scope: "any", h: s.logout},
|
||||
"GET /api/v1/system": {anon: true, h: s.system},
|
||||
"GET /api/v1/who": {anon: true, h: s.who},
|
||||
|
||||
"GET /api/v1/me": {scope: "read", h: s.me},
|
||||
"PATCH /api/v1/me": {scope: "read", h: s.patchMe},
|
||||
"GET /api/v1/me/tokens": {scope: "any", h: s.myTokens},
|
||||
"DELETE /api/v1/me/tokens/{id}": {scope: "any", h: s.revokeMine},
|
||||
"GET /api/v1/users": {scope: "read", h: s.users},
|
||||
"GET /api/v1/users/{name}": {scope: "read", h: s.user},
|
||||
|
||||
"GET /api/v1/areas": {scope: "read", h: s.areas},
|
||||
"GET /api/v1/areas/{id}": {scope: "read", h: s.area},
|
||||
"GET /api/v1/areas/{id}/messages": {scope: "read", h: s.messages},
|
||||
"POST /api/v1/areas/{id}/messages": {scope: "post", h: s.post},
|
||||
"PUT /api/v1/areas/{id}/lastread": {scope: "read", h: s.lastRead},
|
||||
"GET /api/v1/messages/{id}": {scope: "read", h: s.message},
|
||||
|
||||
"GET /api/v1/mail": {scope: "mail", h: s.mail},
|
||||
"GET /api/v1/mail/{id}": {scope: "mail", h: s.mailOne},
|
||||
"DELETE /api/v1/mail/{id}": {scope: "mail", h: s.mailDelete},
|
||||
"POST /api/v1/mail": {scope: "mail", h: s.sendMail},
|
||||
|
||||
"GET /api/v1/fileareas": {scope: "files", h: s.fileAreas},
|
||||
"GET /api/v1/fileareas/{id}/files": {scope: "files", h: s.files},
|
||||
"POST /api/v1/fileareas/{id}/files": {scope: "files", h: s.upload},
|
||||
"GET /api/v1/files/{id}": {scope: "files", h: s.file},
|
||||
"GET /api/v1/files/{id}/content": {scope: "files", h: s.download},
|
||||
|
||||
"GET /api/v1/chat/rooms": {scope: "chat", h: s.rooms},
|
||||
"POST /api/v1/nodes/{n}/message": {scope: "chat", h: s.nodeMessage},
|
||||
"POST /api/v1/page": {scope: "chat", h: s.page},
|
||||
"GET /api/v1/events": {scope: "any", h: s.events},
|
||||
"GET /api/v1/ws": {h: s.wsJSON},
|
||||
"GET /api/v1/ws/proto": {h: s.wsProto},
|
||||
|
||||
"GET /api/v1/admin/pages": {scope: "sysop", h: s.pages},
|
||||
"POST /api/v1/admin/pages/{node}/answer": {scope: "sysop", h: s.answer},
|
||||
"POST /api/v1/admin/users": {scope: "sysop", h: s.addUser},
|
||||
"PATCH /api/v1/admin/users/{name}": {scope: "sysop", h: s.patchUser},
|
||||
"POST /api/v1/admin/areas": {scope: "sysop", h: s.addArea},
|
||||
"PATCH /api/v1/admin/areas/{id}": {scope: "sysop", h: s.patchArea},
|
||||
"POST /api/v1/admin/nodes/{n}/kick": {scope: "sysop", h: s.kick},
|
||||
"GET /api/v1/admin/fido": {scope: "sysop", h: s.fido},
|
||||
"POST /api/v1/admin/fido/poll": {scope: "sysop", h: s.fidoPoll},
|
||||
"GET /api/v1/admin/news": {scope: "sysop", h: s.news},
|
||||
"POST /api/v1/admin/news/sync": {scope: "sysop", h: s.newsSync},
|
||||
|
||||
"GET /api/v1/openapi.json": {h: s.openapi},
|
||||
}
|
||||
}
|
||||
|
||||
// --- shapes
|
||||
|
||||
type userJSON struct {
|
||||
Name string `json:"name"`
|
||||
Location string `json:"location,omitempty"`
|
||||
Sysop bool `json:"sysop"`
|
||||
Created time.Time `json:"created"`
|
||||
LastLogin *time.Time `json:"last_login,omitempty"`
|
||||
Calls int `json:"calls"`
|
||||
Posts int `json:"posts"`
|
||||
Node int `json:"node,omitempty"` // online on, now
|
||||
Locked bool `json:"locked,omitempty"`
|
||||
}
|
||||
|
||||
func (s *Server) userOut(u *store.User) userJSON {
|
||||
j := userJSON{Name: u.Name, Location: u.Location, Sysop: u.Sysop, Created: u.Created,
|
||||
Calls: u.Logins, Posts: u.Posts, Locked: u.Locked}
|
||||
if !u.LastLogin.IsZero() {
|
||||
t := u.LastLogin
|
||||
j.LastLogin = &t
|
||||
}
|
||||
for _, n := range s.B.Nodes() {
|
||||
if strings.EqualFold(n.User, u.Name) {
|
||||
j.Node = n.Num
|
||||
}
|
||||
}
|
||||
return j
|
||||
}
|
||||
|
||||
type nodeJSON struct {
|
||||
Node int `json:"node"`
|
||||
User string `json:"user"`
|
||||
Via string `json:"via"`
|
||||
Since time.Time `json:"since"`
|
||||
Doing string `json:"doing"`
|
||||
}
|
||||
|
||||
type areaJSON struct {
|
||||
ID int64 `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Description string `json:"description"`
|
||||
SysopOnly bool `json:"sysop_only"`
|
||||
Newsgroup string `json:"newsgroup,omitempty"`
|
||||
EchoTag string `json:"echo_tag,omitempty"`
|
||||
Messages int `json:"messages"`
|
||||
FirstID int64 `json:"first_id"`
|
||||
LastID int64 `json:"last_id"`
|
||||
Unread int `json:"unread"`
|
||||
LastRead int64 `json:"last_read"`
|
||||
CanPost bool `json:"can_post"`
|
||||
}
|
||||
|
||||
type messageJSON struct {
|
||||
ID int64 `json:"id"`
|
||||
Area int64 `json:"area,omitempty"`
|
||||
From string `json:"from"`
|
||||
To string `json:"to"`
|
||||
Subject string `json:"subject"`
|
||||
Body string `json:"body,omitempty"`
|
||||
ReplyTo int64 `json:"reply_to,omitempty"`
|
||||
Created time.Time `json:"created"`
|
||||
MessageID string `json:"message_id,omitempty"`
|
||||
FTNMsgID string `json:"ftn_msgid,omitempty"`
|
||||
Read *bool `json:"read,omitempty"` // mail
|
||||
}
|
||||
|
||||
func msgOut(m *store.Message, body bool) messageJSON {
|
||||
j := messageJSON{ID: m.ID, Area: m.AreaID, From: m.From, To: m.To, Subject: m.Subject,
|
||||
ReplyTo: m.ReplyTo, Created: m.Created, MessageID: m.MessageID, FTNMsgID: m.FTNMsgID}
|
||||
if body {
|
||||
j.Body = m.Body
|
||||
}
|
||||
return j
|
||||
}
|
||||
|
||||
func mailOut(m *store.Message, body bool) messageJSON {
|
||||
j := msgOut(m, body)
|
||||
j.Area, j.MessageID = 0, ""
|
||||
r := m.Read
|
||||
j.Read = &r
|
||||
return j
|
||||
}
|
||||
|
||||
type fileJSON struct {
|
||||
ID int64 `json:"id"`
|
||||
Area int64 `json:"area"`
|
||||
Name string `json:"name"`
|
||||
Description string `json:"description"`
|
||||
Size int64 `json:"size"`
|
||||
SHA256 string `json:"sha256"`
|
||||
Uploader string `json:"uploader"`
|
||||
Created time.Time `json:"created"`
|
||||
Downloads int `json:"downloads"`
|
||||
}
|
||||
|
||||
func fileOut(f *store.File) fileJSON {
|
||||
return fileJSON{f.ID, f.AreaID, f.Name, f.Description, f.Size, f.SHA256, f.Uploader, f.Created, f.Downloads}
|
||||
}
|
||||
|
||||
// --- helpers
|
||||
|
||||
func pathID(r *http.Request, name string) (int64, bool) {
|
||||
n, err := strconv.ParseInt(r.PathValue(name), 10, 64)
|
||||
return n, err == nil && n > 0
|
||||
}
|
||||
|
||||
func (s *Server) agent(r *http.Request) *bbs.Node {
|
||||
return s.B.Agent(whoOf(r).user, "api")
|
||||
}
|
||||
|
||||
// lines splits a body into lines for the BBS's editor's checks.
|
||||
func lines(body string) []string {
|
||||
return strings.Split(strings.ReplaceAll(body, "\r\n", "\n"), "\n")
|
||||
}
|
||||
|
||||
// --- login
|
||||
|
||||
func (s *Server) login(w http.ResponseWriter, r *http.Request) {
|
||||
var req struct {
|
||||
Name string `json:"name"`
|
||||
Password string `json:"password"`
|
||||
Scopes string `json:"scopes"`
|
||||
}
|
||||
if !s.decode(w, r, &req) {
|
||||
return
|
||||
}
|
||||
u, err := s.B.Authenticate("http", "ip:"+hostOf(r), req.Name, req.Password)
|
||||
if err != nil {
|
||||
fail(w, http.StatusUnauthorized, err.Error())
|
||||
return
|
||||
}
|
||||
scopes := "read post mail chat files"
|
||||
if u.Sysop {
|
||||
scopes += " sysop"
|
||||
}
|
||||
if req.Scopes != "" {
|
||||
if scopes, err = ParseScopes(req.Scopes); err != nil {
|
||||
fail(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
}
|
||||
secret, hash := NewToken()
|
||||
exp := time.Now().Add(s.S.SessionTTL)
|
||||
if _, err := s.B.Store.AddToken(&store.Token{UserID: u.ID, Name: "login from " + hostOf(r), Hash: hash,
|
||||
Scopes: scopes, Session: true, Expires: exp}); err != nil {
|
||||
fail(w, http.StatusInternalServerError, "the system is in trouble")
|
||||
return
|
||||
}
|
||||
s.B.Store.LoggedIn(u.ID)
|
||||
s.B.Stats.Logins.Add(1)
|
||||
s.B.Log.Printf("http: %s logged in from %s", u.Name, hostOf(r))
|
||||
writeJSON(w, http.StatusOK, map[string]any{"token": secret, "expires": exp, "user": u.Name,
|
||||
"scopes": strings.Fields(scopes)})
|
||||
}
|
||||
|
||||
func (s *Server) logout(w http.ResponseWriter, r *http.Request) {
|
||||
wh := whoOf(r)
|
||||
if !wh.token.Session {
|
||||
fail(w, http.StatusBadRequest, "an API key is revoked with DELETE /api/v1/me/tokens/{id}, not logout")
|
||||
return
|
||||
}
|
||||
s.B.Store.RevokeToken(wh.token.ID, wh.user.ID)
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
// --- the system
|
||||
|
||||
func (s *Server) system(w http.ResponseWriter, r *http.Request) {
|
||||
us, _ := s.B.Store.Users()
|
||||
areas, _ := s.B.Store.Areas()
|
||||
msgs := 0
|
||||
for _, a := range areas {
|
||||
msgs += a.Messages
|
||||
}
|
||||
on := 0
|
||||
for _, n := range s.B.Nodes() {
|
||||
if n.User != "" {
|
||||
on++
|
||||
}
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"name": s.B.Name, "sysop": s.B.Sysop, "location": s.B.Location, "motd": s.B.MOTDText(),
|
||||
"users": len(us), "messages": msgs, "areas": len(areas), "online": on,
|
||||
"max_nodes": s.B.MaxNodes, "new_users": s.B.NewUsers,
|
||||
"features": map[string]bool{"files": s.B.Files != nil, "fido": s.Fido != nil, "news": s.News != nil,
|
||||
"doors": len(s.B.Doors) > 0, "netmail": s.B.Netmail != nil},
|
||||
"version": "bbs-sec/1"})
|
||||
}
|
||||
|
||||
func (s *Server) who(w http.ResponseWriter, r *http.Request) {
|
||||
out := []nodeJSON{}
|
||||
for _, n := range s.B.Nodes() {
|
||||
if n.User == "" {
|
||||
continue
|
||||
}
|
||||
out = append(out, nodeJSON{n.Num, n.User, n.Via, n.Since, n.Activity})
|
||||
}
|
||||
writeJSON(w, http.StatusOK, out)
|
||||
}
|
||||
|
||||
// --- me and users
|
||||
|
||||
func (s *Server) me(w http.ResponseWriter, r *http.Request) {
|
||||
u, err := s.B.Store.UserByID(whoOf(r).user.ID)
|
||||
if err != nil {
|
||||
fail(w, http.StatusNotFound, "no such user")
|
||||
return
|
||||
}
|
||||
j := s.userOut(u)
|
||||
unread, _ := s.B.Store.UnreadMail(u.ID)
|
||||
writeJSON(w, http.StatusOK, map[string]any{"user": j, "unread_mail": unread,
|
||||
"scopes": strings.Fields(whoOf(r).token.Scopes)})
|
||||
}
|
||||
|
||||
func (s *Server) patchMe(w http.ResponseWriter, r *http.Request) {
|
||||
var req struct {
|
||||
Location *string `json:"location"`
|
||||
OldPassword string `json:"old_password"`
|
||||
NewPassword string `json:"new_password"`
|
||||
}
|
||||
if !s.decode(w, r, &req) {
|
||||
return
|
||||
}
|
||||
u := whoOf(r).user
|
||||
if req.Location != nil {
|
||||
s.B.Store.SetLocation(u.ID, bbs.Clean(*req.Location, bbs.MaxLocationLen))
|
||||
}
|
||||
if req.NewPassword != "" {
|
||||
if err := s.agent(r).ChangePassword(req.OldPassword, req.NewPassword); err != nil {
|
||||
fail(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
}
|
||||
s.me(w, r)
|
||||
}
|
||||
|
||||
func (s *Server) myTokens(w http.ResponseWriter, r *http.Request) {
|
||||
ts, _ := s.B.Store.Tokens(whoOf(r).user.ID)
|
||||
out := []map[string]any{}
|
||||
for _, t := range ts {
|
||||
m := map[string]any{"id": t.ID, "name": t.Name, "scopes": strings.Fields(t.Scopes),
|
||||
"session": t.Session, "created": t.Created, "current": t.ID == whoOf(r).token.ID}
|
||||
if !t.Expires.IsZero() {
|
||||
m["expires"] = t.Expires
|
||||
}
|
||||
if !t.LastUsed.IsZero() {
|
||||
m["last_used"] = t.LastUsed
|
||||
}
|
||||
out = append(out, m)
|
||||
}
|
||||
writeJSON(w, http.StatusOK, out)
|
||||
}
|
||||
|
||||
func (s *Server) revokeMine(w http.ResponseWriter, r *http.Request) {
|
||||
id, ok := pathID(r, "id")
|
||||
if !ok || s.B.Store.RevokeToken(id, whoOf(r).user.ID) != nil {
|
||||
fail(w, http.StatusNotFound, "no such token of yours")
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
func (s *Server) users(w http.ResponseWriter, r *http.Request) {
|
||||
us, err := s.B.Store.Users()
|
||||
if err != nil {
|
||||
fail(w, http.StatusInternalServerError, "the system is in trouble")
|
||||
return
|
||||
}
|
||||
sysop := whoOf(r).user.Sysop
|
||||
out := []userJSON{}
|
||||
for _, u := range us {
|
||||
if !u.Locked || sysop {
|
||||
out = append(out, s.userOut(u))
|
||||
}
|
||||
}
|
||||
writeJSON(w, http.StatusOK, out)
|
||||
}
|
||||
|
||||
func (s *Server) user(w http.ResponseWriter, r *http.Request) {
|
||||
u, err := s.B.Store.UserByName(r.PathValue("name"))
|
||||
if err != nil || u.Locked && !whoOf(r).user.Sysop {
|
||||
fail(w, http.StatusNotFound, "no such user")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, s.userOut(u))
|
||||
}
|
||||
|
||||
// --- message areas
|
||||
|
||||
func (s *Server) areaOut(r *http.Request, a *store.Area) areaJSON {
|
||||
u := whoOf(r).user
|
||||
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)}
|
||||
}
|
||||
|
||||
func (s *Server) areas(w http.ResponseWriter, r *http.Request) {
|
||||
as, err := s.B.Store.Areas()
|
||||
if err != nil {
|
||||
fail(w, http.StatusInternalServerError, "the system is in trouble")
|
||||
return
|
||||
}
|
||||
out := []areaJSON{}
|
||||
for _, a := range as {
|
||||
out = append(out, s.areaOut(r, a))
|
||||
}
|
||||
writeJSON(w, http.StatusOK, out)
|
||||
}
|
||||
|
||||
func (s *Server) areaByPath(w http.ResponseWriter, r *http.Request) *store.Area {
|
||||
id, ok := pathID(r, "id")
|
||||
if !ok {
|
||||
fail(w, http.StatusNotFound, "no such area")
|
||||
return nil
|
||||
}
|
||||
a, err := s.B.Store.Area(id)
|
||||
if err != nil {
|
||||
fail(w, http.StatusNotFound, "no such area")
|
||||
return nil
|
||||
}
|
||||
return a
|
||||
}
|
||||
|
||||
func (s *Server) area(w http.ResponseWriter, r *http.Request) {
|
||||
if a := s.areaByPath(w, r); a != nil {
|
||||
writeJSON(w, http.StatusOK, s.areaOut(r, a))
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) messages(w http.ResponseWriter, r *http.Request) {
|
||||
a := s.areaByPath(w, r)
|
||||
if a == nil {
|
||||
return
|
||||
}
|
||||
after, _ := strconv.ParseInt(r.URL.Query().Get("after"), 10, 64)
|
||||
limit, err := strconv.Atoi(r.URL.Query().Get("limit"))
|
||||
if err != nil || limit <= 0 || limit > 200 {
|
||||
limit = 50
|
||||
}
|
||||
body := r.URL.Query().Get("body") != "no"
|
||||
ms, err := s.B.Store.Messages(a.ID, max(after, 0), limit)
|
||||
if err != nil {
|
||||
fail(w, http.StatusInternalServerError, "the system is in trouble")
|
||||
return
|
||||
}
|
||||
out := []messageJSON{}
|
||||
for _, m := range ms {
|
||||
out = append(out, msgOut(m, body))
|
||||
}
|
||||
resp := map[string]any{"messages": out}
|
||||
if len(ms) == limit {
|
||||
resp["next"] = fmt.Sprintf("/api/v1/areas/%d/messages?after=%d&limit=%d", a.ID, ms[len(ms)-1].ID, limit)
|
||||
}
|
||||
writeJSON(w, http.StatusOK, resp)
|
||||
}
|
||||
|
||||
func (s *Server) message(w http.ResponseWriter, r *http.Request) {
|
||||
id, ok := pathID(r, "id")
|
||||
if !ok {
|
||||
fail(w, http.StatusNotFound, "no such message")
|
||||
return
|
||||
}
|
||||
m, err := s.B.Store.Message(id)
|
||||
if err != nil {
|
||||
fail(w, http.StatusNotFound, "no such message")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, msgOut(m, true))
|
||||
}
|
||||
|
||||
func (s *Server) post(w http.ResponseWriter, r *http.Request) {
|
||||
a := s.areaByPath(w, r)
|
||||
if a == nil {
|
||||
return
|
||||
}
|
||||
var req struct {
|
||||
To string `json:"to"`
|
||||
Subject string `json:"subject"`
|
||||
Body string `json:"body"`
|
||||
ReplyTo int64 `json:"reply_to"`
|
||||
}
|
||||
if !s.decode(w, r, &req) {
|
||||
return
|
||||
}
|
||||
if req.ReplyTo != 0 {
|
||||
if p, err := s.B.Store.Message(req.ReplyTo); err != nil || p.AreaID != a.ID {
|
||||
fail(w, http.StatusBadRequest, "reply_to is not a message of this area")
|
||||
return
|
||||
}
|
||||
}
|
||||
if !bbs.CanPost(whoOf(r).user, a) {
|
||||
fail(w, http.StatusForbidden, "only the sysop posts here")
|
||||
return
|
||||
}
|
||||
id, err := s.agent(r).Post(a, req.To, req.Subject, lines(req.Body), req.ReplyTo)
|
||||
if err != nil {
|
||||
fail(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
m, _ := s.B.Store.Message(id)
|
||||
w.Header().Set("Location", fmt.Sprintf("/api/v1/messages/%d", id))
|
||||
writeJSON(w, http.StatusCreated, msgOut(m, true))
|
||||
}
|
||||
|
||||
func (s *Server) lastRead(w http.ResponseWriter, r *http.Request) {
|
||||
a := s.areaByPath(w, r)
|
||||
if a == nil {
|
||||
return
|
||||
}
|
||||
var req struct {
|
||||
ID int64 `json:"id"`
|
||||
}
|
||||
if !s.decode(w, r, &req) {
|
||||
return
|
||||
}
|
||||
if req.ID < 0 || req.ID > a.LastID {
|
||||
fail(w, http.StatusBadRequest, "id: from 0 to the area's last")
|
||||
return
|
||||
}
|
||||
s.B.Store.SetLastRead(whoOf(r).user.ID, a.ID, req.ID)
|
||||
writeJSON(w, http.StatusOK, s.areaOut(r, a))
|
||||
}
|
||||
|
||||
// --- mail
|
||||
|
||||
func (s *Server) mail(w http.ResponseWriter, r *http.Request) {
|
||||
in, err := s.B.Store.Inbox(whoOf(r).user.ID)
|
||||
if err != nil {
|
||||
fail(w, http.StatusInternalServerError, "the system is in trouble")
|
||||
return
|
||||
}
|
||||
out := []messageJSON{}
|
||||
for _, m := range in {
|
||||
out = append(out, mailOut(m, false))
|
||||
}
|
||||
writeJSON(w, http.StatusOK, out)
|
||||
}
|
||||
|
||||
func (s *Server) mailOne(w http.ResponseWriter, r *http.Request) {
|
||||
id, ok := pathID(r, "id")
|
||||
u := whoOf(r).user
|
||||
m, err := s.B.Store.Mail(u.ID, id)
|
||||
if !ok || err != nil {
|
||||
fail(w, http.StatusNotFound, "no such mail")
|
||||
return
|
||||
}
|
||||
s.B.Store.MarkMailRead(u.ID, id)
|
||||
m.Read = true
|
||||
writeJSON(w, http.StatusOK, mailOut(m, true))
|
||||
}
|
||||
|
||||
func (s *Server) mailDelete(w http.ResponseWriter, r *http.Request) {
|
||||
id, ok := pathID(r, "id")
|
||||
if !ok || s.B.Store.DeleteMail(whoOf(r).user.ID, id) != nil {
|
||||
fail(w, http.StatusNotFound, "no such mail")
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
func (s *Server) sendMail(w http.ResponseWriter, r *http.Request) {
|
||||
var req struct {
|
||||
To string `json:"to"`
|
||||
Subject string `json:"subject"`
|
||||
Body string `json:"body"`
|
||||
ReplyTo int64 `json:"reply_to"`
|
||||
}
|
||||
if !s.decode(w, r, &req) {
|
||||
return
|
||||
}
|
||||
if err := s.agent(r).SendMail(req.To, req.Subject, lines(req.Body), req.ReplyTo); err != nil {
|
||||
fail(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusAccepted, map[string]any{"sent": true})
|
||||
}
|
||||
|
||||
// --- files
|
||||
|
||||
func (s *Server) noFiles(w http.ResponseWriter) bool {
|
||||
if s.B.Files == nil {
|
||||
fail(w, http.StatusNotFound, "there are no file areas")
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (s *Server) fileAreas(w http.ResponseWriter, r *http.Request) {
|
||||
if s.noFiles(w) {
|
||||
return
|
||||
}
|
||||
fas, _ := s.B.Store.FileAreas()
|
||||
out := []map[string]any{}
|
||||
for _, fa := range fas {
|
||||
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)})
|
||||
}
|
||||
writeJSON(w, http.StatusOK, out)
|
||||
}
|
||||
|
||||
func (s *Server) fileAreaByPath(w http.ResponseWriter, r *http.Request) *store.FileArea {
|
||||
if s.noFiles(w) {
|
||||
return nil
|
||||
}
|
||||
id, ok := pathID(r, "id")
|
||||
fa, err := s.B.Store.FileArea(id)
|
||||
if !ok || err != nil {
|
||||
fail(w, http.StatusNotFound, "no such file area")
|
||||
return nil
|
||||
}
|
||||
return fa
|
||||
}
|
||||
|
||||
func (s *Server) files(w http.ResponseWriter, r *http.Request) {
|
||||
fa := s.fileAreaByPath(w, r)
|
||||
if fa == nil {
|
||||
return
|
||||
}
|
||||
fs, _ := s.B.Store.Files(fa.ID)
|
||||
out := []fileJSON{}
|
||||
for _, f := range fs {
|
||||
out = append(out, fileOut(f))
|
||||
}
|
||||
writeJSON(w, http.StatusOK, out)
|
||||
}
|
||||
|
||||
func (s *Server) fileByPath(w http.ResponseWriter, r *http.Request) *store.File {
|
||||
if s.noFiles(w) {
|
||||
return nil
|
||||
}
|
||||
id, ok := pathID(r, "id")
|
||||
f, err := s.B.Store.FileByID(id)
|
||||
if !ok || err != nil {
|
||||
fail(w, http.StatusNotFound, "no such file")
|
||||
return nil
|
||||
}
|
||||
return f
|
||||
}
|
||||
|
||||
func (s *Server) file(w http.ResponseWriter, r *http.Request) {
|
||||
if f := s.fileByPath(w, r); f != nil {
|
||||
writeJSON(w, http.StatusOK, fileOut(f))
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) download(w http.ResponseWriter, r *http.Request) {
|
||||
f := s.fileByPath(w, r)
|
||||
if f == nil {
|
||||
return
|
||||
}
|
||||
fh, err := s.B.Files.OpenFile(f)
|
||||
if err != nil {
|
||||
fail(w, http.StatusNotFound, "the file is missing")
|
||||
return
|
||||
}
|
||||
defer fh.Close()
|
||||
w.Header().Set("Content-Type", "application/octet-stream")
|
||||
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)
|
||||
}
|
||||
http.ServeContent(w, r, f.Name, f.Created, fh)
|
||||
}
|
||||
|
||||
// upload: the body is the file; ?name= and &description=.
|
||||
func (s *Server) upload(w http.ResponseWriter, r *http.Request) {
|
||||
fa := s.fileAreaByPath(w, r)
|
||||
if fa == nil {
|
||||
return
|
||||
}
|
||||
u := whoOf(r).user
|
||||
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
|
||||
switch {
|
||||
case errors.Is(err, files.ErrDenied):
|
||||
status = http.StatusForbidden
|
||||
case errors.Is(err, files.ErrExists):
|
||||
status = http.StatusConflict
|
||||
case errors.Is(err, files.ErrQuota):
|
||||
status = http.StatusTooManyRequests
|
||||
}
|
||||
fail(w, status, err.Error())
|
||||
return
|
||||
}
|
||||
if _, err := io.Copy(up, r.Body); err != nil {
|
||||
up.Abort()
|
||||
status := http.StatusBadRequest
|
||||
if errors.Is(err, files.ErrTooLarge) || errors.Is(err, files.ErrQuota) {
|
||||
status = http.StatusRequestEntityTooLarge
|
||||
}
|
||||
fail(w, status, err.Error())
|
||||
return
|
||||
}
|
||||
f, err := up.Commit()
|
||||
if err != nil {
|
||||
fail(w, http.StatusConflict, err.Error())
|
||||
return
|
||||
}
|
||||
s.B.Log.Printf("http: %s uploaded %q (%d bytes) to %s", u.Name, f.Name, f.Size, fa.Name)
|
||||
w.Header().Set("Location", fmt.Sprintf("/api/v1/files/%d", f.ID))
|
||||
writeJSON(w, http.StatusCreated, fileOut(f))
|
||||
}
|
||||
|
||||
// --- chat (what needs a node needs an open stream: /events or /ws)
|
||||
|
||||
func (s *Server) streamNode(w http.ResponseWriter, r *http.Request) *bbs.Node {
|
||||
s.mu.Lock()
|
||||
ns := s.streams[whoOf(r).token.ID]
|
||||
s.mu.Unlock()
|
||||
if len(ns) == 0 {
|
||||
fail(w, http.StatusConflict, "open a stream first (/api/v1/events or /api/v1/ws): it is your node")
|
||||
return nil
|
||||
}
|
||||
return ns[len(ns)-1]
|
||||
}
|
||||
|
||||
func (s *Server) rooms(w http.ResponseWriter, r *http.Request) {
|
||||
out := []map[string]any{}
|
||||
for _, ro := range s.B.Agent(whoOf(r).user, "api").Rooms() {
|
||||
out = append(out, map[string]any{"name": ro.Name, "users": ro.Users})
|
||||
}
|
||||
writeJSON(w, http.StatusOK, out)
|
||||
}
|
||||
|
||||
func (s *Server) nodeMessage(w http.ResponseWriter, r *http.Request) {
|
||||
n := s.streamNode(w, r)
|
||||
if n == nil {
|
||||
return
|
||||
}
|
||||
to, err := strconv.Atoi(r.PathValue("n"))
|
||||
var req struct {
|
||||
Text string `json:"text"`
|
||||
}
|
||||
if err != nil || !s.decode(w, r, &req) {
|
||||
if err != nil {
|
||||
fail(w, http.StatusNotFound, "no such node")
|
||||
}
|
||||
return
|
||||
}
|
||||
if err := n.Message(to, req.Text); err != nil {
|
||||
status := http.StatusBadRequest
|
||||
if errors.Is(err, bbs.ErrNoNode) {
|
||||
status = http.StatusNotFound
|
||||
} else if errors.Is(err, bbs.ErrFlood) {
|
||||
status = http.StatusTooManyRequests
|
||||
}
|
||||
fail(w, status, err.Error())
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusAccepted, map[string]any{"sent": true})
|
||||
}
|
||||
|
||||
func (s *Server) page(w http.ResponseWriter, r *http.Request) {
|
||||
n := s.streamNode(w, r)
|
||||
if n == nil {
|
||||
return
|
||||
}
|
||||
var req struct {
|
||||
Reason string `json:"reason"`
|
||||
}
|
||||
if !s.decode(w, r, &req) {
|
||||
return
|
||||
}
|
||||
room, told, err := n.PageSysop(req.Reason)
|
||||
if err != nil {
|
||||
fail(w, http.StatusTooManyRequests, err.Error())
|
||||
return
|
||||
}
|
||||
if told > 0 {
|
||||
n.JoinRoom(room)
|
||||
} else {
|
||||
n.CancelPage()
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"told": told, "room": room, "waiting": told > 0})
|
||||
}
|
||||
|
||||
// --- admin
|
||||
|
||||
func (s *Server) pages(w http.ResponseWriter, r *http.Request) {
|
||||
out := []map[string]any{}
|
||||
for _, p := range s.B.Pages() {
|
||||
out = append(out, map[string]any{"node": p.Node, "user": p.User, "reason": p.Reason, "since": p.Since})
|
||||
}
|
||||
writeJSON(w, http.StatusOK, out)
|
||||
}
|
||||
|
||||
func (s *Server) answer(w http.ResponseWriter, r *http.Request) {
|
||||
n := s.streamNode(w, r)
|
||||
if n == nil {
|
||||
return
|
||||
}
|
||||
num, _ := strconv.Atoi(r.PathValue("node"))
|
||||
_, node, err := n.Answer(num)
|
||||
if err != nil {
|
||||
fail(w, http.StatusNotFound, err.Error())
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"node": node, "room": n.Room()})
|
||||
}
|
||||
|
||||
func (s *Server) addUser(w http.ResponseWriter, r *http.Request) {
|
||||
var req struct {
|
||||
Name string `json:"name"`
|
||||
Password string `json:"password"`
|
||||
Location string `json:"location"`
|
||||
Sysop bool `json:"sysop"`
|
||||
}
|
||||
if !s.decode(w, r, &req) {
|
||||
return
|
||||
}
|
||||
if msg := bbs.ValidName(req.Name); msg != "" {
|
||||
fail(w, http.StatusBadRequest, msg)
|
||||
return
|
||||
}
|
||||
if msg := bbs.ValidPassword(req.Password, req.Name); msg != "" {
|
||||
fail(w, http.StatusBadRequest, msg)
|
||||
return
|
||||
}
|
||||
u, err := s.B.Store.CreateUser(req.Name, req.Password, bbs.Clean(req.Location, bbs.MaxLocationLen), req.Sysop)
|
||||
if errors.Is(err, store.ErrExists) {
|
||||
fail(w, http.StatusConflict, "that name is taken")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
fail(w, http.StatusInternalServerError, "the system is in trouble")
|
||||
return
|
||||
}
|
||||
s.B.Log.Printf("http: %s added user %s", whoOf(r).user.Name, u.Name)
|
||||
writeJSON(w, http.StatusCreated, s.userOut(u))
|
||||
}
|
||||
|
||||
func (s *Server) patchUser(w http.ResponseWriter, r *http.Request) {
|
||||
u, err := s.B.Store.UserByName(r.PathValue("name"))
|
||||
if err != nil {
|
||||
fail(w, http.StatusNotFound, "no such user")
|
||||
return
|
||||
}
|
||||
var req struct {
|
||||
Locked *bool `json:"locked"`
|
||||
Sysop *bool `json:"sysop"`
|
||||
Password *string `json:"password"`
|
||||
Location *string `json:"location"`
|
||||
}
|
||||
if !s.decode(w, r, &req) {
|
||||
return
|
||||
}
|
||||
if req.Password != nil {
|
||||
if msg := bbs.ValidPassword(*req.Password, u.Name); msg != "" {
|
||||
fail(w, http.StatusBadRequest, msg)
|
||||
return
|
||||
}
|
||||
s.B.Store.SetPassword(u.ID, *req.Password)
|
||||
}
|
||||
if req.Locked != nil {
|
||||
s.B.Store.SetLocked(u.ID, *req.Locked)
|
||||
}
|
||||
if req.Sysop != nil {
|
||||
s.B.Store.SetSysop(u.ID, *req.Sysop)
|
||||
}
|
||||
if req.Location != nil {
|
||||
s.B.Store.SetLocation(u.ID, bbs.Clean(*req.Location, bbs.MaxLocationLen))
|
||||
}
|
||||
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))
|
||||
}
|
||||
|
||||
func (s *Server) addArea(w http.ResponseWriter, r *http.Request) {
|
||||
var req struct {
|
||||
Name string `json:"name"`
|
||||
Description string `json:"description"`
|
||||
SysopOnly bool `json:"sysop_only"`
|
||||
}
|
||||
if !s.decode(w, r, &req) {
|
||||
return
|
||||
}
|
||||
name := bbs.Clean(req.Name, 30)
|
||||
if name == "" {
|
||||
fail(w, http.StatusBadRequest, "a name")
|
||||
return
|
||||
}
|
||||
a, err := s.B.Store.CreateArea(name, bbs.Clean(req.Description, 60), req.SysopOnly)
|
||||
if errors.Is(err, store.ErrExists) {
|
||||
fail(w, http.StatusConflict, "there is an area of that name")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
fail(w, http.StatusInternalServerError, "the system is in trouble")
|
||||
return
|
||||
}
|
||||
a, _ = s.B.Store.Area(a.ID)
|
||||
writeJSON(w, http.StatusCreated, s.areaOut(r, a))
|
||||
}
|
||||
|
||||
func (s *Server) patchArea(w http.ResponseWriter, r *http.Request) {
|
||||
a := s.areaByPath(w, r)
|
||||
if a == nil {
|
||||
return
|
||||
}
|
||||
var req struct {
|
||||
Newsgroup *string `json:"newsgroup"`
|
||||
EchoTag *string `json:"echo_tag"`
|
||||
}
|
||||
if !s.decode(w, r, &req) {
|
||||
return
|
||||
}
|
||||
if req.Newsgroup != nil {
|
||||
if *req.Newsgroup != "" && !news.ValidGroup(*req.Newsgroup) {
|
||||
fail(w, http.StatusBadRequest, "a newsgroup name is lower case words with dots: bbs.general")
|
||||
return
|
||||
}
|
||||
if err := s.B.Store.SetNewsgroup(a.ID, *req.Newsgroup); err != nil {
|
||||
fail(w, http.StatusConflict, err.Error())
|
||||
return
|
||||
}
|
||||
}
|
||||
if req.EchoTag != nil {
|
||||
tag := strings.ToUpper(*req.EchoTag)
|
||||
if tag != "" && !ftn.ValidTag(tag) {
|
||||
fail(w, http.StatusBadRequest, "an echo tag is letters, digits and . _ - (FSX_GEN), up to 60")
|
||||
return
|
||||
}
|
||||
if err := s.B.Store.SetEchoTag(a.ID, tag); err != nil {
|
||||
fail(w, http.StatusConflict, err.Error())
|
||||
return
|
||||
}
|
||||
}
|
||||
a, _ = s.B.Store.Area(a.ID)
|
||||
writeJSON(w, http.StatusOK, s.areaOut(r, a))
|
||||
}
|
||||
|
||||
func (s *Server) kick(w http.ResponseWriter, r *http.Request) {
|
||||
n, err := strconv.Atoi(r.PathValue("n"))
|
||||
if err != nil || s.B.Kick(n) != nil {
|
||||
fail(w, http.StatusNotFound, "no one is on that node")
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
func (s *Server) fido(w http.ResponseWriter, r *http.Request) {
|
||||
if s.Fido == nil {
|
||||
fail(w, http.StatusNotFound, "the BBS is not on FidoNet")
|
||||
return
|
||||
}
|
||||
var addrs []string
|
||||
for _, a := range s.Fido.S.Addrs {
|
||||
addrs = append(addrs, a.String())
|
||||
}
|
||||
links := []map[string]any{}
|
||||
for _, l := range s.Fido.S.Links {
|
||||
links = append(links, map[string]any{"name": l.Name, "address": l.Addr.String(), "host": l.Host,
|
||||
"echoes": l.Echoes, "route": l.Route, "waiting": s.Fido.Outbound(l)})
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"addresses": addrs, "links": links})
|
||||
}
|
||||
|
||||
func (s *Server) fidoPoll(w http.ResponseWriter, r *http.Request) {
|
||||
if s.Fido == nil {
|
||||
fail(w, http.StatusNotFound, "the BBS is not on FidoNet")
|
||||
return
|
||||
}
|
||||
called := []string{}
|
||||
for _, l := range s.Fido.S.Links {
|
||||
if l.Host != "" {
|
||||
called = append(called, l.Name)
|
||||
go func() {
|
||||
if err := s.Fido.Call(s.Ctx, l); err != nil {
|
||||
s.B.Log.Printf("fido: calling %s: %v", l.Name, err)
|
||||
}
|
||||
}()
|
||||
}
|
||||
}
|
||||
writeJSON(w, http.StatusAccepted, map[string]any{"calling": called})
|
||||
}
|
||||
|
||||
func (s *Server) news(w http.ResponseWriter, r *http.Request) {
|
||||
if s.News == nil {
|
||||
fail(w, http.StatusNotFound, "no news")
|
||||
return
|
||||
}
|
||||
peers := []map[string]any{}
|
||||
for _, p := range s.Peers {
|
||||
peers = append(peers, map[string]any{"name": p.Name, "address": p.Address, "groups": p.Groups,
|
||||
"pull": p.Pull, "push": p.Push})
|
||||
}
|
||||
groups := []string{}
|
||||
if as, err := s.B.Store.Newsgroups(); err == nil {
|
||||
for _, a := range as {
|
||||
groups = append(groups, a.Newsgroup)
|
||||
}
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"peers": peers, "newsgroups": groups})
|
||||
}
|
||||
|
||||
func (s *Server) newsSync(w http.ResponseWriter, r *http.Request) {
|
||||
if s.News == nil {
|
||||
fail(w, http.StatusNotFound, "no news")
|
||||
return
|
||||
}
|
||||
names := []string{}
|
||||
for _, p := range s.Peers {
|
||||
names = append(names, p.Name)
|
||||
go s.News.Sync(p)
|
||||
}
|
||||
writeJSON(w, http.StatusAccepted, map[string]any{"syncing": names})
|
||||
}
|
||||
@@ -0,0 +1,423 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/coder/websocket"
|
||||
"google.golang.org/protobuf/encoding/protojson"
|
||||
"google.golang.org/protobuf/proto"
|
||||
"google.golang.org/protobuf/types/known/timestamppb"
|
||||
|
||||
"github.com/Neo-Desktop/bbs-sec/internal/api/pb"
|
||||
"github.com/Neo-Desktop/bbs-sec/internal/bbs"
|
||||
)
|
||||
|
||||
// Subprotocols of the WebSocket endpoints.
|
||||
const (
|
||||
ProtoJSON = "bbs.v1.json"
|
||||
ProtoBinary = "bbs.v1.proto"
|
||||
)
|
||||
|
||||
var kinds = map[bbs.EventKind]pb.Event_Kind{
|
||||
bbs.Said: pb.Event_SAID, bbs.Emoted: pb.Event_EMOTED, bbs.Joined: pb.Event_JOINED,
|
||||
bbs.Left: pb.Event_LEFT, bbs.Private: pb.Event_PRIVATE, bbs.Paged: pb.Event_PAGED,
|
||||
bbs.Notice: pb.Event_NOTICE, bbs.Mail: pb.Event_MAIL,
|
||||
}
|
||||
|
||||
func pbEvent(e bbs.Event) *pb.Event {
|
||||
return &pb.Event{Kind: kinds[e.Kind], Room: e.Room, From: e.From, Node: int32(e.Node),
|
||||
Text: e.Text, Time: timestamppb.New(e.Time), Line: e.String()}
|
||||
}
|
||||
|
||||
// openStream gives a stream's client a node of its own: in who's online
|
||||
// (as "web"), in chat, reached by node messages and pages.
|
||||
func (s *Server) openStream(r *http.Request, wh *who) (*bbs.Node, func(), error) {
|
||||
host := hostOf(r)
|
||||
n, err := s.B.Enter(&bbs.Caller{Via: "web", Listener: "http", Remote: host, Source: "ip:" + host}, nil)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
n.SetUser(wh.user)
|
||||
n.Doing("Web client")
|
||||
id := wh.token.ID
|
||||
s.mu.Lock()
|
||||
s.streams[id] = append(s.streams[id], n)
|
||||
s.mu.Unlock()
|
||||
s.B.Log.Printf("node %d: %s on the web (%s)", n.Num, wh.user.Name, host)
|
||||
return n, func() {
|
||||
s.mu.Lock()
|
||||
ns := s.streams[id]
|
||||
for i, x := range ns {
|
||||
if x == n {
|
||||
ns = append(ns[:i], ns[i+1:]...)
|
||||
break
|
||||
}
|
||||
}
|
||||
if len(ns) == 0 {
|
||||
delete(s.streams, id)
|
||||
} else {
|
||||
s.streams[id] = ns
|
||||
}
|
||||
s.mu.Unlock()
|
||||
n.Leave()
|
||||
s.B.Log.Printf("node %d: gone (web)", n.Num)
|
||||
}, nil
|
||||
}
|
||||
|
||||
// events is the event stream: server-sent events, each an Event in the
|
||||
// WebSocket's JSON.
|
||||
func (s *Server) events(w http.ResponseWriter, r *http.Request) {
|
||||
wh := whoOf(r)
|
||||
if !wh.has("chat") && !wh.has("read") {
|
||||
fail(w, http.StatusForbidden, "the token has no chat or read scope")
|
||||
return
|
||||
}
|
||||
rc := http.NewResponseController(w)
|
||||
n, done, err := s.openStream(r, wh)
|
||||
if err != nil {
|
||||
fail(w, http.StatusServiceUnavailable, err.Error())
|
||||
return
|
||||
}
|
||||
defer done()
|
||||
h := w.Header()
|
||||
h.Set("Content-Type", "text/event-stream")
|
||||
h.Set("X-Accel-Buffering", "no")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
fmt.Fprintf(w, "retry: 5000\nevent: welcome\ndata: {\"node\":%d,\"user\":%q}\n\n", n.Num, wh.user.Name)
|
||||
if rc.Flush() != nil {
|
||||
return
|
||||
}
|
||||
beat := time.NewTicker(25 * time.Second)
|
||||
defer beat.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-r.Context().Done():
|
||||
return
|
||||
case <-beat.C:
|
||||
fmt.Fprint(w, ": still here\n\n")
|
||||
case <-n.Wake():
|
||||
for _, e := range n.Pending() {
|
||||
b, _ := protojson.Marshal(pbEvent(e))
|
||||
fmt.Fprintf(w, "event: %s\ndata: %s\n\n", strings.ToLower(kinds[e.Kind].String()), b)
|
||||
}
|
||||
}
|
||||
if rc.Flush() != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) wsJSON(w http.ResponseWriter, r *http.Request) { s.ws(w, r, false) }
|
||||
func (s *Server) wsProto(w http.ResponseWriter, r *http.Request) { s.ws(w, r, true) }
|
||||
|
||||
// wsConn is a WebSocket client: its encoding, and one writer at a time.
|
||||
type wsConn struct {
|
||||
c *websocket.Conn
|
||||
binary bool
|
||||
mu sync.Mutex
|
||||
}
|
||||
|
||||
func (wc *wsConn) send(ctx context.Context, m *pb.ServerMessage) error {
|
||||
var b []byte
|
||||
var err error
|
||||
typ := websocket.MessageText
|
||||
if wc.binary {
|
||||
b, err = proto.Marshal(m)
|
||||
typ = websocket.MessageBinary
|
||||
} else {
|
||||
b, err = protojson.MarshalOptions{EmitUnpopulated: false}.Marshal(m)
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
wc.mu.Lock()
|
||||
defer wc.mu.Unlock()
|
||||
ctx, cancel := context.WithTimeout(ctx, 30*time.Second)
|
||||
defer cancel()
|
||||
return wc.c.Write(ctx, typ, b)
|
||||
}
|
||||
|
||||
func (wc *wsConn) read(ctx context.Context) (*pb.ClientMessage, error) {
|
||||
typ, b, err := wc.c.Read(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
m := &pb.ClientMessage{}
|
||||
if wc.binary {
|
||||
if typ != websocket.MessageBinary {
|
||||
return nil, errBadFrame
|
||||
}
|
||||
err = proto.Unmarshal(b, m)
|
||||
} else {
|
||||
if typ != websocket.MessageText {
|
||||
return nil, errBadFrame
|
||||
}
|
||||
err = protojson.Unmarshal(b, m)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%w: %v", errBadMessage, err)
|
||||
}
|
||||
return m, nil
|
||||
}
|
||||
|
||||
var (
|
||||
errBadFrame = errors.New("wrong kind of frame for this endpoint")
|
||||
errBadMessage = errors.New("not a ClientMessage")
|
||||
)
|
||||
|
||||
func errMsg(id uint32, code, msg string) *pb.ServerMessage {
|
||||
return &pb.ServerMessage{Id: id, Body: &pb.ServerMessage_Error{Error: &pb.Error{Code: code, Message: msg}}}
|
||||
}
|
||||
|
||||
func okMsg(id uint32, room string) *pb.ServerMessage {
|
||||
return &pb.ServerMessage{Id: id, Body: &pb.ServerMessage_Ok{Ok: &pb.Ok{Room: room}}}
|
||||
}
|
||||
|
||||
func linesMsg(id uint32, ls []string) *pb.ServerMessage {
|
||||
return &pb.ServerMessage{Id: id, Body: &pb.ServerMessage_Lines{Lines: &pb.Lines{Lines: ls}}}
|
||||
}
|
||||
|
||||
// codeOf is an error's code for the client.
|
||||
func codeOf(err error) string {
|
||||
switch {
|
||||
case errors.Is(err, bbs.ErrFlood):
|
||||
return "too_many"
|
||||
case errors.Is(err, bbs.ErrNoNode):
|
||||
return "not_found"
|
||||
case errors.Is(err, bbs.ErrNotInRoom):
|
||||
return "conflict"
|
||||
case errors.Is(err, bbs.ErrNotYours):
|
||||
return "forbidden"
|
||||
}
|
||||
return "bad_request"
|
||||
}
|
||||
|
||||
func (s *Server) ws(w http.ResponseWriter, r *http.Request, binary bool) {
|
||||
sub := ProtoJSON
|
||||
if binary {
|
||||
sub = ProtoBinary
|
||||
}
|
||||
opts := &websocket.AcceptOptions{Subprotocols: []string{sub}}
|
||||
if s.S.CORS != "" {
|
||||
if u, err := url.Parse(s.S.CORS); err == nil {
|
||||
opts.OriginPatterns = []string{u.Host}
|
||||
}
|
||||
}
|
||||
wh := whoOf(r)
|
||||
c, err := websocket.Accept(w, r, opts)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer c.CloseNow()
|
||||
c.SetReadLimit(16 << 10)
|
||||
wc := &wsConn{c: c, binary: binary}
|
||||
ctx := r.Context()
|
||||
|
||||
// who: from the upgrade's Authorization, or the first message
|
||||
if wh == nil {
|
||||
actx, cancel := context.WithTimeout(ctx, 10*time.Second)
|
||||
m, err := wc.read(actx)
|
||||
cancel()
|
||||
if err != nil {
|
||||
c.Close(websocket.StatusPolicyViolation, "authenticate first")
|
||||
return
|
||||
}
|
||||
auth := m.GetAuth()
|
||||
if auth == nil {
|
||||
wc.send(ctx, errMsg(m.Id, "unauthorized", "the first message must be an Auth"))
|
||||
c.Close(websocket.StatusPolicyViolation, "authenticate first")
|
||||
return
|
||||
}
|
||||
if !s.allow("ip:" + hostOf(r)) {
|
||||
c.Close(websocket.StatusTryAgainLater, "too many requests")
|
||||
return
|
||||
}
|
||||
if wh, err = s.byToken(auth.Token); err != nil {
|
||||
time.Sleep(s.B.FailDelay)
|
||||
wc.send(ctx, errMsg(m.Id, "unauthorized", err.Error()))
|
||||
c.Close(websocket.StatusPolicyViolation, "unauthorized")
|
||||
return
|
||||
}
|
||||
}
|
||||
if !wh.has("chat") {
|
||||
wc.send(ctx, errMsg(0, "forbidden", "the token has no chat scope"))
|
||||
c.Close(websocket.StatusPolicyViolation, "forbidden")
|
||||
return
|
||||
}
|
||||
n, done, err := s.openStream(r, wh)
|
||||
if err != nil {
|
||||
wc.send(ctx, errMsg(0, "unavailable", err.Error()))
|
||||
c.Close(websocket.StatusTryAgainLater, "busy")
|
||||
return
|
||||
}
|
||||
defer done()
|
||||
var scopes []string
|
||||
for k := range wh.scopes {
|
||||
scopes = append(scopes, k)
|
||||
}
|
||||
if err := wc.send(ctx, &pb.ServerMessage{Body: &pb.ServerMessage_Welcome{Welcome: &pb.Welcome{
|
||||
Bbs: s.B.Name, User: wh.user.Name, Node: int32(n.Num), Scopes: scopes}}}); err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
// events as they come, and pings to see the client is there
|
||||
ctx, cancel := context.WithCancel(ctx)
|
||||
defer cancel()
|
||||
go func() {
|
||||
ping := time.NewTicker(30 * time.Second)
|
||||
defer ping.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-ping.C:
|
||||
pctx, pc := context.WithTimeout(ctx, 20*time.Second)
|
||||
err := c.Ping(pctx)
|
||||
pc()
|
||||
if err != nil {
|
||||
cancel()
|
||||
return
|
||||
}
|
||||
case <-n.Wake():
|
||||
for _, e := range n.Pending() {
|
||||
if wc.send(ctx, &pb.ServerMessage{Body: &pb.ServerMessage_Event{Event: pbEvent(e)}}) != nil {
|
||||
cancel()
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
key := fmt.Sprintf("token:%d", wh.token.ID)
|
||||
for {
|
||||
m, err := wc.read(ctx)
|
||||
if err != nil {
|
||||
if errors.Is(err, errBadMessage) || errors.Is(err, errBadFrame) {
|
||||
wc.send(ctx, errMsg(0, "bad_request", err.Error()))
|
||||
continue
|
||||
}
|
||||
return
|
||||
}
|
||||
if !s.allow(key) {
|
||||
wc.send(ctx, errMsg(m.Id, "too_many", "too many requests: slow down"))
|
||||
continue
|
||||
}
|
||||
for _, out := range s.dispatch(n, wh, m) {
|
||||
if wc.send(ctx, out) != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// dispatch does a client's request: the answers to send.
|
||||
func (s *Server) dispatch(n *bbs.Node, wh *who, m *pb.ClientMessage) []*pb.ServerMessage {
|
||||
id := m.Id
|
||||
fails := func(err error) []*pb.ServerMessage { return []*pb.ServerMessage{errMsg(id, codeOf(err), err.Error())} }
|
||||
ok := []*pb.ServerMessage{okMsg(id, "")}
|
||||
switch req := m.Request.(type) {
|
||||
case *pb.ClientMessage_Auth:
|
||||
return []*pb.ServerMessage{errMsg(id, "bad_request", "already logged in")}
|
||||
case *pb.ClientMessage_Ping:
|
||||
return []*pb.ServerMessage{{Id: id, Body: &pb.ServerMessage_Pong{Pong: &pb.Pong{}}}}
|
||||
case *pb.ClientMessage_Join:
|
||||
hist, err := n.JoinRoom(req.Join.Room)
|
||||
if err != nil {
|
||||
return fails(err)
|
||||
}
|
||||
n.Doing("Web chat in " + n.Room())
|
||||
var ls []string
|
||||
for _, e := range hist {
|
||||
ls = append(ls, e.String())
|
||||
}
|
||||
return []*pb.ServerMessage{linesMsg(id, ls), okMsg(id, n.Room())}
|
||||
case *pb.ClientMessage_Leave:
|
||||
n.LeaveRoom()
|
||||
n.Doing("Web client")
|
||||
return ok
|
||||
case *pb.ClientMessage_Say:
|
||||
if err := n.Say(req.Say.Text, req.Say.Emote); err != nil {
|
||||
return fails(err)
|
||||
}
|
||||
return ok
|
||||
case *pb.ClientMessage_NodeMessage:
|
||||
if err := n.Message(int(req.NodeMessage.Node), req.NodeMessage.Text); err != nil {
|
||||
return fails(err)
|
||||
}
|
||||
return ok
|
||||
case *pb.ClientMessage_Page:
|
||||
room, told, err := n.PageSysop(req.Page.Reason)
|
||||
if err != nil {
|
||||
return []*pb.ServerMessage{errMsg(id, "too_many", err.Error())}
|
||||
}
|
||||
if told == 0 {
|
||||
n.CancelPage()
|
||||
return []*pb.ServerMessage{errMsg(id, "unavailable", "the sysop is not available just now")}
|
||||
}
|
||||
n.JoinRoom(room)
|
||||
return []*pb.ServerMessage{okMsg(id, room)}
|
||||
case *pb.ClientMessage_Answer:
|
||||
if !wh.has("sysop") {
|
||||
return []*pb.ServerMessage{errMsg(id, "forbidden", "answering pages is for sysops")}
|
||||
}
|
||||
hist, _, err := n.Answer(int(req.Answer.Node))
|
||||
if err != nil {
|
||||
return fails(err)
|
||||
}
|
||||
var ls []string
|
||||
for _, e := range hist {
|
||||
ls = append(ls, e.String())
|
||||
}
|
||||
return []*pb.ServerMessage{linesMsg(id, ls), okMsg(id, n.Room())}
|
||||
case *pb.ClientMessage_Command:
|
||||
line := strings.TrimSpace(req.Command.Line)
|
||||
if strings.HasPrefix(strings.ToLower(line), "/answer") || strings.HasPrefix(strings.ToLower(line), "/a ") ||
|
||||
strings.ToLower(line) == "/a" || strings.HasPrefix(strings.ToLower(line), "/busy") {
|
||||
if !wh.has("sysop") {
|
||||
return []*pb.ServerMessage{errMsg(id, "forbidden", "that is for sysops")}
|
||||
}
|
||||
}
|
||||
before := n.Room()
|
||||
out, leave, err := n.ChatCommand(line)
|
||||
if leave {
|
||||
n.LeaveRoom()
|
||||
}
|
||||
res := []*pb.ServerMessage{}
|
||||
if len(out) > 0 {
|
||||
res = append(res, linesMsg(id, out))
|
||||
}
|
||||
if err != nil {
|
||||
return append(res, errMsg(id, codeOf(err), err.Error()))
|
||||
}
|
||||
room := ""
|
||||
if n.Room() != before {
|
||||
room = n.Room()
|
||||
}
|
||||
return append(res, okMsg(id, room))
|
||||
case *pb.ClientMessage_Who:
|
||||
nl := &pb.NodeList{}
|
||||
for _, x := range s.B.Nodes() {
|
||||
if x.User == "" {
|
||||
continue
|
||||
}
|
||||
nl.Nodes = append(nl.Nodes, &pb.NodeInfo{Node: int32(x.Num), User: x.User, Via: x.Via,
|
||||
Since: timestamppb.New(x.Since), Doing: x.Activity})
|
||||
}
|
||||
return []*pb.ServerMessage{{Id: id, Body: &pb.ServerMessage_Nodes{Nodes: nl}}}
|
||||
case *pb.ClientMessage_Rooms:
|
||||
rl := &pb.RoomList{}
|
||||
for _, ro := range n.Rooms() {
|
||||
rl.Rooms = append(rl.Rooms, &pb.Room{Name: ro.Name, Users: ro.Users})
|
||||
}
|
||||
return []*pb.ServerMessage{{Id: id, Body: &pb.ServerMessage_Rooms{Rooms: rl}}}
|
||||
}
|
||||
return []*pb.ServerMessage{errMsg(id, "bad_request", "no request in the message")}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package bbs
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/Neo-Desktop/bbs-sec/internal/store"
|
||||
)
|
||||
|
||||
// Stats count what the BBS has done since it started (for metrics).
|
||||
type Stats struct {
|
||||
Logins, LoginFailures, Posts, Mail, Pages, ChatLines atomic.Int64
|
||||
}
|
||||
|
||||
// Agent is a node that is no line: what an API client does by one request
|
||||
// (post, send mail) goes through it, as a caller's would, without its
|
||||
// taking a node.
|
||||
func (b *BBS) Agent(u *store.User, via string) *Node {
|
||||
return &Node{Num: 0, Caller: &Caller{Via: via}, Since: time.Now(), b: b, user: u, activity: via}
|
||||
}
|
||||
|
||||
// Kick throws the caller on a node off.
|
||||
func (b *BBS) Kick(num int) error {
|
||||
b.mu.Lock()
|
||||
n := b.nodes[num]
|
||||
b.mu.Unlock()
|
||||
if n == nil {
|
||||
return ErrNoNode
|
||||
}
|
||||
if n.kick == nil {
|
||||
return errors.New("that node cannot be thrown off")
|
||||
}
|
||||
b.Log.Printf("node %d: thrown off", num)
|
||||
n.kick()
|
||||
return nil
|
||||
}
|
||||
|
||||
// NodeOf finds the node of a number.
|
||||
func (b *BBS) NodeOf(num int) *Node { return b.node(num) }
|
||||
|
||||
// tellMail tells the nodes of a user of a new mail.
|
||||
func (b *BBS) tellMail(to int64, from, subject string) {
|
||||
b.mu.Lock()
|
||||
var ns []*Node
|
||||
for _, n := range b.nodes {
|
||||
if n.user != nil && n.user.ID == to {
|
||||
ns = append(ns, n)
|
||||
}
|
||||
}
|
||||
b.mu.Unlock()
|
||||
for _, n := range ns {
|
||||
n.deliver(Event{Kind: Mail, From: from, Text: subject, Time: time.Now()})
|
||||
}
|
||||
}
|
||||
@@ -112,6 +112,8 @@ type BBS struct {
|
||||
Screens *screens.Set
|
||||
Menus map[string]*Menu
|
||||
Text map[string]string
|
||||
// Stats count logins, posts and the like
|
||||
Stats Stats
|
||||
|
||||
mu sync.Mutex
|
||||
nodes map[int]*Node
|
||||
@@ -310,6 +312,7 @@ func (b *BBS) Authenticate(who, source, name, pw string) (*store.User, error) {
|
||||
u, err := b.Store.CheckPassword(name, pw)
|
||||
if errors.Is(err, store.ErrNotFound) {
|
||||
b.failed(source)
|
||||
b.Stats.LoginFailures.Add(1)
|
||||
b.Log.Printf("%s: %s: failed login as %q", who, source, Clean(name, MaxNameLen))
|
||||
time.Sleep(b.FailDelay)
|
||||
return nil, ErrBadLogin
|
||||
@@ -354,6 +357,7 @@ func (n *Node) loggedIn(u *store.User, how string) (*store.User, error) {
|
||||
return nil, err
|
||||
}
|
||||
n.SetUser(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,
|
||||
n.Caller.Describe(), n.Caller.Remote)
|
||||
@@ -435,6 +439,7 @@ func (n *Node) Post(a *store.Area, to, subject string, body []string, replyTo in
|
||||
n.b.MakeArticle(u, a, m)
|
||||
id, err := n.b.Store.Post(m)
|
||||
if err == nil {
|
||||
n.b.Stats.Posts.Add(1)
|
||||
n.b.Log.Printf("node %d: %s posted #%d in %s", n.Num, u.Name, id, a.Name)
|
||||
}
|
||||
return id, err
|
||||
@@ -467,6 +472,8 @@ func (n *Node) SendMail(to, subject string, body []string, replyTo int64) error
|
||||
if _, err := n.b.Store.SendMail(m); err != nil {
|
||||
return err
|
||||
}
|
||||
n.b.Stats.Mail.Add(1)
|
||||
n.b.tellMail(rcpt.ID, u.Name, m.Subject)
|
||||
n.b.Log.Printf("node %d: %s sent mail to %s", n.Num, u.Name, rcpt.Name)
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -23,6 +23,7 @@ const (
|
||||
Private // a message to this node alone
|
||||
Paged // a caller pages the sysop (to sysops)
|
||||
Notice // from the system
|
||||
Mail // a new mail for the caller
|
||||
)
|
||||
|
||||
// Event is something for a node to show its caller.
|
||||
@@ -48,6 +49,8 @@ func (e Event) String() string {
|
||||
return "<- " + e.From + " left"
|
||||
case Private:
|
||||
return fmt.Sprintf("Message from %s (node %d): %s", e.From, e.Node, e.Text)
|
||||
case Mail:
|
||||
return "New mail from " + e.From + ": " + e.Text
|
||||
case Paged:
|
||||
s := fmt.Sprintf("%s (node %d) is paging you", e.From, e.Node)
|
||||
if e.Text != "" {
|
||||
@@ -272,6 +275,7 @@ func (n *Node) Say(text string, emote bool) error {
|
||||
if emote {
|
||||
e.Kind = Emoted
|
||||
}
|
||||
n.b.Stats.ChatLines.Add(1)
|
||||
h := n.b.hub()
|
||||
h.mu.Lock()
|
||||
r := h.rooms[name]
|
||||
@@ -393,6 +397,7 @@ func (n *Node) PageSysop(reason string) (string, int, error) {
|
||||
told++
|
||||
}
|
||||
}
|
||||
n.b.Stats.Pages.Add(1)
|
||||
n.b.Log.Printf("node %d: %s paged the sysop (%d told): %s", n.Num, u.Name, told, reason)
|
||||
if told == 0 && len(n.b.PageCommand) > 0 {
|
||||
n.b.runPageCommand(u.Name, n.Num, reason)
|
||||
|
||||
@@ -288,3 +288,15 @@ func (f *Fido) waiting(l *Link) bool {
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// Outbound counts the files waiting for a link.
|
||||
func (f *Fido) Outbound(l *Link) int {
|
||||
n := 0
|
||||
ents, _ := os.ReadDir(f.outbound(l))
|
||||
for _, e := range ents {
|
||||
if e.Type().IsRegular() && !strings.HasPrefix(e.Name(), ".") {
|
||||
n++
|
||||
}
|
||||
}
|
||||
return n
|
||||
}
|
||||
@@ -151,3 +151,17 @@ func FormatNet2D(prefix string, addrs []Net2D, width int) []string {
|
||||
}
|
||||
return lines
|
||||
}
|
||||
|
||||
// ValidTag checks an echo tag: letters, digits and ._-!$&+, upper case, up
|
||||
// to 60.
|
||||
func ValidTag(tag string) bool {
|
||||
if tag == "" || len(tag) > 60 {
|
||||
return false
|
||||
}
|
||||
for _, c := range tag {
|
||||
if !(c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || strings.ContainsRune("._-!$&+", c)) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
@@ -3,6 +3,7 @@ package server
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"github.com/Neo-Desktop/bbs-sec/internal/api"
|
||||
"net"
|
||||
"os"
|
||||
"strconv"
|
||||
@@ -45,6 +46,7 @@ type Config struct {
|
||||
Screens *screens.Set // nil: no screens of the sysop's
|
||||
Menus map[string]*bbs.Menu
|
||||
Text map[string]string // [strings]
|
||||
HTTP *api.Settings // nil: no HTTP API
|
||||
Gopher *gopher.Settings // nil: no gopher server
|
||||
Database string
|
||||
Log string // syslog, stderr, none, or a file
|
||||
@@ -92,6 +94,9 @@ func Load(path string) (*Config, error) {
|
||||
if err := c.doorSections(cf); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := c.httpSection(cf.Get("http", "")); err != nil {
|
||||
return nil, fmt.Errorf("[http] %w", err)
|
||||
}
|
||||
if err := c.customSections(cf); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -119,7 +124,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":
|
||||
case "general", "listen", "ftp", "news", "nntp", "peer", "fido", "binkp", "link", "door", "finger", "gopher", "menu", "strings", "http":
|
||||
default:
|
||||
return nil, fmt.Errorf("line %d: unknown section [%s]", s.Line, s.Kind)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/Neo-Desktop/bbs-sec/internal/api"
|
||||
"github.com/Neo-Desktop/bbs-sec/internal/config"
|
||||
)
|
||||
|
||||
// httpSection reads [http].
|
||||
func (c *Config) httpSection(s *config.Section) error {
|
||||
if s == nil {
|
||||
return nil
|
||||
}
|
||||
h := &api.Settings{Address: s.String("address", ":8443")}
|
||||
host, _, err := net.SplitHostPort(h.Address)
|
||||
if err != nil {
|
||||
return fmt.Errorf("address: %v", err)
|
||||
}
|
||||
if h.TLS, err = s.Bool("tls", true); err != nil {
|
||||
return err
|
||||
}
|
||||
h.CertFile, h.KeyFile = s.String("cert_file", ""), s.String("key_file", "")
|
||||
if h.TLS && (h.CertFile == "" || h.KeyFile == "") {
|
||||
return errors.New("cert_file and key_file are needed for TLS (or tls = no, behind a proxy that has it)")
|
||||
}
|
||||
if !h.TLS {
|
||||
if ip := net.ParseIP(host); host == "" || ip == nil || !ip.IsLoopback() {
|
||||
c.Warnings = append(c.Warnings, "[http] tls = no on an address others reach: tokens and passwords go in the clear")
|
||||
}
|
||||
}
|
||||
if h.Anonymous, err = s.Bool("anonymous", true); err != nil {
|
||||
return err
|
||||
}
|
||||
if h.CORS = s.String("cors", ""); h.CORS != "" {
|
||||
u, err := url.Parse(h.CORS)
|
||||
if err != nil || u.Scheme == "" || u.Host == "" || u.Path != "" || strings.Contains(h.CORS, "*") {
|
||||
return errors.New("cors: one origin, like https://www.example.org (no *)")
|
||||
}
|
||||
}
|
||||
if h.Metrics = s.String("metrics", ""); h.Metrics != "" {
|
||||
if _, _, err := net.SplitHostPort(h.Metrics); err != nil {
|
||||
return fmt.Errorf("metrics: %v", err)
|
||||
}
|
||||
}
|
||||
if h.MaxPerIP, err = s.Int("max_per_ip", 20, 0, 10000); err != nil {
|
||||
return err
|
||||
}
|
||||
rate := s.String("rate", "10")
|
||||
if h.Rate, err = strconv.ParseFloat(rate, 64); err != nil || h.Rate < 0 || h.Rate > 10000 {
|
||||
return fmt.Errorf("rate: %q is not requests a second (0: no limit)", rate)
|
||||
}
|
||||
if h.Burst, err = s.Int("burst", 20, 1, 100000); err != nil {
|
||||
return err
|
||||
}
|
||||
hours, err := s.Int("session_hours", 24, 1, 24*90)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
h.SessionTTL = time.Duration(hours) * time.Hour
|
||||
c.HTTP = h
|
||||
return nil
|
||||
}
|
||||
@@ -32,6 +32,9 @@ func migrate(db *sql.DB) error {
|
||||
}
|
||||
}
|
||||
}
|
||||
if _, err := db.Exec(tokenSchema); err != nil {
|
||||
return err
|
||||
}
|
||||
_, err := db.Exec(`
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS areas_newsgroup ON areas(newsgroup) WHERE newsgroup IS NOT NULL;
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS messages_message_id ON messages(message_id) WHERE message_id IS NOT NULL;
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"errors"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Token is an API token: a key a user made, or a login's session. Only
|
||||
// its hash is kept.
|
||||
type Token struct {
|
||||
ID int64
|
||||
UserID int64
|
||||
User string // the user's name (read)
|
||||
Name string
|
||||
Hash string
|
||||
Scopes string // space separated
|
||||
Session bool
|
||||
Created time.Time
|
||||
Expires time.Time // zero: never
|
||||
LastUsed time.Time
|
||||
}
|
||||
|
||||
const tokenSchema = `
|
||||
CREATE TABLE IF NOT EXISTS api_tokens (
|
||||
id INTEGER PRIMARY KEY,
|
||||
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
name TEXT NOT NULL,
|
||||
hash TEXT NOT NULL UNIQUE,
|
||||
scopes TEXT NOT NULL,
|
||||
session INTEGER NOT NULL DEFAULT 0,
|
||||
created INTEGER NOT NULL,
|
||||
expires INTEGER NOT NULL DEFAULT 0,
|
||||
last_used INTEGER NOT NULL DEFAULT 0
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS api_tokens_user ON api_tokens(user_id);
|
||||
`
|
||||
|
||||
// AddToken records a token.
|
||||
func (s *Store) AddToken(t *Token) (int64, error) {
|
||||
exp := int64(0)
|
||||
if !t.Expires.IsZero() {
|
||||
exp = t.Expires.Unix()
|
||||
}
|
||||
res, err := s.db.Exec(`INSERT INTO api_tokens (user_id, name, hash, scopes, session, created, expires)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?)`, t.UserID, t.Name, t.Hash, t.Scopes, t.Session, now(), exp)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return res.LastInsertId()
|
||||
}
|
||||
|
||||
const tokenCols = `t.id, t.user_id, u.name, t.name, t.hash, t.scopes, t.session, t.created, t.expires, t.last_used`
|
||||
|
||||
func scanToken(row interface{ Scan(...any) error }) (*Token, error) {
|
||||
var t Token
|
||||
var created, expires, last int64
|
||||
err := row.Scan(&t.ID, &t.UserID, &t.User, &t.Name, &t.Hash, &t.Scopes, &t.Session, &created, &expires, &last)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
t.Created, t.Expires, t.LastUsed = unix(created), unix(expires), unix(last)
|
||||
return &t, err
|
||||
}
|
||||
|
||||
// TokenByHash finds a token, if it has not expired.
|
||||
func (s *Store) TokenByHash(hash string) (*Token, error) {
|
||||
return scanToken(s.db.QueryRow(`SELECT `+tokenCols+` FROM api_tokens t JOIN users u ON u.id = t.user_id
|
||||
WHERE t.hash = ? AND (t.expires = 0 OR t.expires > ?)`, hash, now()))
|
||||
}
|
||||
|
||||
// TouchToken notes a token's use.
|
||||
func (s *Store) TouchToken(id int64) error {
|
||||
_, err := s.db.Exec(`UPDATE api_tokens SET last_used = ? WHERE id = ?`, now(), id)
|
||||
return err
|
||||
}
|
||||
|
||||
// Tokens lists the tokens (of a user, or all if user is 0), sessions too.
|
||||
func (s *Store) Tokens(user int64) ([]*Token, error) {
|
||||
q := `SELECT ` + tokenCols + ` FROM api_tokens t JOIN users u ON u.id = t.user_id`
|
||||
args := []any{}
|
||||
if user != 0 {
|
||||
q += ` WHERE t.user_id = ?`
|
||||
args = append(args, user)
|
||||
}
|
||||
rows, err := s.db.Query(q+` ORDER BY t.id`, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []*Token
|
||||
for rows.Next() {
|
||||
t, err := scanToken(rows)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, t)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// RevokeToken deletes a token (of a user, or anyone's if user is 0).
|
||||
func (s *Store) RevokeToken(id, user int64) error {
|
||||
if user == 0 {
|
||||
return s.exec1(`DELETE FROM api_tokens WHERE id = ?`, id)
|
||||
}
|
||||
return s.exec1(`DELETE FROM api_tokens WHERE id = ? AND user_id = ?`, id, user)
|
||||
}
|
||||
|
||||
// ExpireTokens deletes the tokens past their time.
|
||||
func (s *Store) ExpireTokens() error {
|
||||
_, err := s.db.Exec(`DELETE FROM api_tokens WHERE expires != 0 AND expires <= ?`, now())
|
||||
return err
|
||||
}
|
||||
+166
@@ -0,0 +1,166 @@
|
||||
// The BBS's WebSocket protocol, bbs.v1. The same messages go both ways
|
||||
// on two endpoints:
|
||||
//
|
||||
// /api/v1/ws JSON text frames: protobuf's JSON mapping (lowerCamelCase
|
||||
// fields, enums by name, timestamps in RFC 3339)
|
||||
// /api/v1/ws/proto binary frames: protobuf
|
||||
//
|
||||
// The client sends ClientMessages; the server answers each with a
|
||||
// ServerMessage of the same id (Ok, Error, or what was asked for), and sends
|
||||
// Events (id 0) as they come. Unless the upgrade request had an
|
||||
// Authorization header, the first message must be an Auth.
|
||||
syntax = "proto3";
|
||||
|
||||
package bbs.v1;
|
||||
|
||||
import "google/protobuf/timestamp.proto";
|
||||
|
||||
option go_package = "github.com/Neo-Desktop/bbs-sec/internal/api/pb";
|
||||
|
||||
message ClientMessage {
|
||||
uint32 id = 1; // chosen by the client, echoed in the answer
|
||||
oneof request {
|
||||
Auth auth = 2;
|
||||
JoinRoom join = 3;
|
||||
LeaveRoom leave = 4;
|
||||
Say say = 5;
|
||||
NodeMessage node_message = 6;
|
||||
Page page = 7;
|
||||
AnswerPage answer = 8;
|
||||
ChatCommand command = 9;
|
||||
Ping ping = 10;
|
||||
Who who = 11;
|
||||
ListRooms rooms = 12;
|
||||
}
|
||||
}
|
||||
|
||||
// Auth: an API token (an API key, or a login's session token).
|
||||
message Auth {
|
||||
string token = 1;
|
||||
}
|
||||
|
||||
// JoinRoom: into a chat room (out of the one before); answered by Lines
|
||||
// (the room's last lines), then Ok with the room.
|
||||
message JoinRoom {
|
||||
string room = 1;
|
||||
}
|
||||
|
||||
message LeaveRoom {}
|
||||
|
||||
// Say: a line in the room (emote: as /me).
|
||||
message Say {
|
||||
string text = 1;
|
||||
bool emote = 2;
|
||||
}
|
||||
|
||||
// NodeMessage: a line to the caller on one node.
|
||||
message NodeMessage {
|
||||
int32 node = 1;
|
||||
string text = 2;
|
||||
}
|
||||
|
||||
// Page: page the sysop; Ok's room is the private room to wait in (the
|
||||
// client is taken into it).
|
||||
message Page {
|
||||
string reason = 1;
|
||||
}
|
||||
|
||||
// AnswerPage: a sysop answers a page (node 0: the one waiting longest).
|
||||
message AnswerPage {
|
||||
int32 node = 1;
|
||||
}
|
||||
|
||||
// ChatCommand: a line as typed in chat on a terminal (/who, /rooms,
|
||||
// /msg ...); answered by Lines.
|
||||
message ChatCommand {
|
||||
string line = 1;
|
||||
}
|
||||
|
||||
message Ping {}
|
||||
|
||||
// Who: the nodes online; answered by NodeList.
|
||||
message Who {}
|
||||
|
||||
// ListRooms: the chat rooms in use; answered by RoomList.
|
||||
message ListRooms {}
|
||||
|
||||
message ServerMessage {
|
||||
uint32 id = 1; // the request's; 0 for events and the welcome
|
||||
oneof body {
|
||||
Welcome welcome = 2;
|
||||
Ok ok = 3;
|
||||
Error error = 4;
|
||||
Event event = 5;
|
||||
NodeList nodes = 6;
|
||||
Pong pong = 7;
|
||||
Lines lines = 8;
|
||||
RoomList rooms = 9;
|
||||
}
|
||||
}
|
||||
|
||||
// Welcome: sent once the client is logged in.
|
||||
message Welcome {
|
||||
string bbs = 1;
|
||||
string user = 2;
|
||||
int32 node = 3;
|
||||
repeated string scopes = 4;
|
||||
}
|
||||
|
||||
message Ok {
|
||||
string room = 1; // the room the client is in now, if that changed
|
||||
}
|
||||
|
||||
message Error {
|
||||
string code = 1; // unauthorized, forbidden, bad_request, not_found, too_many, conflict
|
||||
string message = 2;
|
||||
}
|
||||
|
||||
// Event: something for the client: a line in its room, a message to its
|
||||
// node, a page (to sysops), a new mail, a notice.
|
||||
message Event {
|
||||
enum Kind {
|
||||
KIND_UNSPECIFIED = 0;
|
||||
SAID = 1;
|
||||
EMOTED = 2;
|
||||
JOINED = 3;
|
||||
LEFT = 4;
|
||||
PRIVATE = 5;
|
||||
PAGED = 6;
|
||||
NOTICE = 7;
|
||||
MAIL = 8;
|
||||
}
|
||||
Kind kind = 1;
|
||||
string room = 2;
|
||||
string from = 3;
|
||||
int32 node = 4;
|
||||
string text = 5;
|
||||
google.protobuf.Timestamp time = 6;
|
||||
string line = 7; // the event as a terminal shows it
|
||||
}
|
||||
|
||||
message NodeInfo {
|
||||
int32 node = 1;
|
||||
string user = 2;
|
||||
string via = 3;
|
||||
google.protobuf.Timestamp since = 4;
|
||||
string doing = 5;
|
||||
}
|
||||
|
||||
message NodeList {
|
||||
repeated NodeInfo nodes = 1;
|
||||
}
|
||||
|
||||
message Pong {}
|
||||
|
||||
message Lines {
|
||||
repeated string lines = 1;
|
||||
}
|
||||
|
||||
message Room {
|
||||
string name = 1;
|
||||
repeated string users = 2;
|
||||
}
|
||||
|
||||
message RoomList {
|
||||
repeated Room rooms = 1;
|
||||
}
|
||||
Reference in new issue
Block a user