feat: members-only Usenet (NNTP) + Forgejo git provisioning + founding-lifetime $99

WIP feature branch: NNTPS news server, per-member Forgejo accounts on email
confirm, and founding-lifetime pricing tier.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
Anthony Ettinger 2026-06-14 14:26:23 +00:00
parent 2a9d841ddb
commit 3b6b9a4a78
20 changed files with 2842 additions and 2 deletions

261
internal/news/backend.go Normal file
View file

@ -0,0 +1,261 @@
// Package news implements the members-only Usenet (NNTP) server that backs
// news.<host> for AgentBBS members (free and paid alike). The RFC 3977 protocol
// engine is the vendored internal/news/nntpd (a patched go-nntp/server); the
// nntp.Article/Group wire types come from github.com/dustin/go-nntp. Articles
// live in the shared SQLite store. See docs/news.md.
//
// Access control: the NNTP handlers themselves do not gate reads, so the network
// is made members-only inside the backend. The anonymous backend refuses every
// data method with "authorization required"; AUTHINFO swaps in an authenticated
// backend bound to the member. Membership IS the credential — the password is
// ignored (this is a private, TLS-only net), exactly like the co-located IRC
// network.
package news
import (
"crypto/rand"
"encoding/hex"
"fmt"
"io"
"net/textproto"
"strconv"
"strings"
"time"
"github.com/dustin/go-nntp"
"github.com/profullstack/agentbbs/internal/news/nntpd"
"github.com/profullstack/agentbbs/internal/store"
)
// NewsStore is the slice of the store the NNTP backend needs.
type NewsStore interface {
UserByName(name string) (store.User, bool, error)
EnsureNewsGroup(name, description string) error
NewsGroups() ([]store.NewsGroup, error)
NewsGroup(name string) (store.NewsGroup, bool, error)
NewsArticleByNum(group string, num int64) (store.NewsArticle, bool, error)
NewsArticleByMsgID(msgID string) (store.NewsArticle, bool, error)
NewsArticlesRange(group string, from, to int64) ([]store.NewsArticle, error)
InsertNewsArticle(a store.NewsArticle) (store.NewsArticle, error)
}
// backend implements nntpd.Backend. A backend with user=="" is the
// anonymous (pre-auth) backend; AUTHINFO returns an authenticated copy.
type backend struct {
st NewsStore
host string
user string // BBS member name; "" until authenticated
}
func (b *backend) authed() bool { return b.user != "" }
// Authorized reports whether this session may proceed without AUTHINFO.
func (b *backend) Authorized() bool { return b.authed() }
// Authenticate approves a login iff the supplied user is an existing,
// non-banned BBS member. The password is ignored (membership is the credential).
func (b *backend) Authenticate(user, _ string) (nntpd.Backend, error) {
name := strings.ToLower(strings.TrimSpace(user))
if name == "" {
return nil, nntpd.ErrAuthRejected
}
u, ok, err := b.st.UserByName(name)
if err != nil {
return nil, nntpd.ErrAuthRejected
}
if !ok || u.Banned {
return nil, nntpd.ErrAuthRejected
}
return &backend{st: b.st, host: b.host, user: u.Name}, nil
}
// AllowPost reports whether POST is accepted: members only.
func (b *backend) AllowPost() bool { return b.authed() }
func (b *backend) ListGroups(int) ([]*nntp.Group, error) {
if !b.authed() {
return nil, nntpd.ErrAuthRequired
}
gs, err := b.st.NewsGroups()
if err != nil {
return nil, err
}
out := make([]*nntp.Group, 0, len(gs))
for _, g := range gs {
out = append(out, toNNTPGroup(g))
}
return out, nil
}
func (b *backend) GetGroup(name string) (*nntp.Group, error) {
if !b.authed() {
return nil, nntpd.ErrAuthRequired
}
g, ok, err := b.st.NewsGroup(name)
if err != nil {
return nil, err
}
if !ok {
return nil, nntpd.ErrNoSuchGroup
}
return toNNTPGroup(g), nil
}
func (b *backend) GetArticle(group *nntp.Group, id string) (*nntp.Article, error) {
if !b.authed() {
return nil, nntpd.ErrAuthRequired
}
if strings.HasPrefix(id, "<") {
a, ok, err := b.st.NewsArticleByMsgID(id)
if err != nil {
return nil, err
}
if !ok {
return nil, nntpd.ErrInvalidMessageID
}
return b.toNNTPArticle(a), nil
}
if group == nil {
return nil, nntpd.ErrNoGroupSelected
}
num, err := strconv.ParseInt(id, 10, 64)
if err != nil {
return nil, nntpd.ErrInvalidArticleNumber
}
a, ok, err := b.st.NewsArticleByNum(group.Name, num)
if err != nil {
return nil, err
}
if !ok {
return nil, nntpd.ErrInvalidArticleNumber
}
return b.toNNTPArticle(a), nil
}
func (b *backend) GetArticles(group *nntp.Group, from, to int64) ([]nntpd.NumberedArticle, error) {
if !b.authed() {
return nil, nntpd.ErrAuthRequired
}
if group == nil {
return nil, nntpd.ErrNoGroupSelected
}
rows, err := b.st.NewsArticlesRange(group.Name, from, to)
if err != nil {
return nil, err
}
out := make([]nntpd.NumberedArticle, 0, len(rows))
for _, a := range rows {
out = append(out, nntpd.NumberedArticle{Num: a.Num, Article: b.toNNTPArticle(a)})
}
return out, nil
}
// Post stores a member's article into every existing target group named in its
// Newsgroups header. The From header is stamped to the authenticated member so
// posts cannot be forged; client-supplied From/Path are ignored.
func (b *backend) Post(article *nntp.Article) error {
if !b.authed() {
return nntpd.ErrPostingNotPermitted
}
body, err := io.ReadAll(article.Body)
if err != nil {
return nntpd.ErrPostingFailed
}
groups := splitGroups(article.Header.Get("Newsgroups"))
if len(groups) == 0 {
return nntpd.ErrPostingFailed
}
from := fmt.Sprintf("%s <%s@%s>", b.user, b.user, b.host)
date := strings.TrimSpace(article.Header.Get("Date"))
if date == "" {
date = time.Now().UTC().Format(time.RFC1123Z)
}
msgID := strings.TrimSpace(article.Header.Get("Message-Id"))
if msgID == "" {
msgID = b.newMessageID()
}
bodyStr := string(body)
posted := 0
for _, g := range groups {
grp, ok, err := b.st.NewsGroup(g)
if err != nil {
return nntpd.ErrPostingFailed
}
if !ok || !grp.Posting {
continue // skip unknown / read-only groups (cross-post tolerant)
}
a := store.NewsArticle{
Group: g,
MsgID: msgID,
Subject: strings.TrimSpace(article.Header.Get("Subject")),
From: from,
Refs: strings.TrimSpace(article.Header.Get("References")),
Date: date,
Body: bodyStr,
Lines: strings.Count(bodyStr, "\n"),
Bytes: len(bodyStr),
}
if _, err := b.st.InsertNewsArticle(a); err != nil {
return nntpd.ErrPostingFailed
}
posted++
}
if posted == 0 {
return nntpd.ErrNotWanted
}
return nil
}
func (b *backend) newMessageID() string {
var rnd [8]byte
_, _ = rand.Read(rnd[:])
return fmt.Sprintf("<%d.%s@%s>", time.Now().UnixNano(), hex.EncodeToString(rnd[:]), b.host)
}
func toNNTPGroup(g store.NewsGroup) *nntp.Group {
posting := nntp.PostingPermitted
if !g.Posting {
posting = nntp.PostingNotPermitted
}
return &nntp.Group{
Name: g.Name,
Description: g.Description,
Count: g.Count,
Low: g.Low,
High: g.High,
Posting: posting,
}
}
// toNNTPArticle reconstructs the wire article (headers + body) from a stored row.
func (b *backend) toNNTPArticle(a store.NewsArticle) *nntp.Article {
h := textproto.MIMEHeader{}
h.Set("Subject", a.Subject)
h.Set("From", a.From)
h.Set("Date", a.Date)
h.Set("Newsgroups", a.Group)
h.Set("Message-Id", a.MsgID)
if a.Refs != "" {
h.Set("References", a.Refs)
}
h.Set("Path", b.host)
return &nntp.Article{
Header: h,
Body: strings.NewReader(a.Body),
Bytes: a.Bytes,
Lines: a.Lines,
}
}
// splitGroups parses a Newsgroups header ("a.b, c.d") into trimmed names.
func splitGroups(v string) []string {
var out []string
for _, p := range strings.Split(v, ",") {
if g := strings.TrimSpace(p); g != "" {
out = append(out, g)
}
}
return out
}

View file

@ -0,0 +1,171 @@
package news
import (
"errors"
"io"
"net/textproto"
"strings"
"testing"
"github.com/dustin/go-nntp"
"github.com/profullstack/agentbbs/internal/news/nntpd"
"github.com/profullstack/agentbbs/internal/store"
)
// fakeStore is an in-memory NewsStore for backend tests.
type fakeStore struct {
users map[string]store.User
groups map[string]store.NewsGroup
articles []store.NewsArticle
}
func newFakeStore() *fakeStore {
return &fakeStore{
users: map[string]store.User{
"alice": {ID: 1, Name: "alice"},
"bob": {ID: 2, Name: "bob", Banned: true},
},
groups: map[string]store.NewsGroup{
"pfs.general": {Name: "pfs.general", Posting: true},
"pfs.locked": {Name: "pfs.locked", Posting: false},
},
}
}
func (f *fakeStore) UserByName(name string) (store.User, bool, error) {
u, ok := f.users[name]
return u, ok, nil
}
func (f *fakeStore) EnsureNewsGroup(name, desc string) error {
if _, ok := f.groups[name]; !ok {
f.groups[name] = store.NewsGroup{Name: name, Description: desc, Posting: true}
}
return nil
}
func (f *fakeStore) NewsGroups() ([]store.NewsGroup, error) {
var out []store.NewsGroup
for _, g := range f.groups {
out = append(out, g)
}
return out, nil
}
func (f *fakeStore) NewsGroup(name string) (store.NewsGroup, bool, error) {
g, ok := f.groups[name]
return g, ok, nil
}
func (f *fakeStore) NewsArticleByNum(group string, num int64) (store.NewsArticle, bool, error) {
for _, a := range f.articles {
if a.Group == group && a.Num == num {
return a, true, nil
}
}
return store.NewsArticle{}, false, nil
}
func (f *fakeStore) NewsArticleByMsgID(id string) (store.NewsArticle, bool, error) {
for _, a := range f.articles {
if a.MsgID == id {
return a, true, nil
}
}
return store.NewsArticle{}, false, nil
}
func (f *fakeStore) NewsArticlesRange(group string, from, to int64) ([]store.NewsArticle, error) {
var out []store.NewsArticle
for _, a := range f.articles {
if a.Group == group && a.Num >= from && a.Num <= to {
out = append(out, a)
}
}
return out, nil
}
func (f *fakeStore) InsertNewsArticle(a store.NewsArticle) (store.NewsArticle, error) {
var max int64
for _, x := range f.articles {
if x.Group == a.Group && x.Num > max {
max = x.Num
}
}
a.Num = max + 1
f.articles = append(f.articles, a)
return a, nil
}
func TestAnonymousBackendRefusesData(t *testing.T) {
b := &backend{st: newFakeStore(), host: "news.h"}
if b.Authorized() || b.AllowPost() {
t.Fatal("anonymous backend must not be authorized or allowed to post")
}
if _, err := b.ListGroups(-1); !errors.Is(err, nntpd.ErrAuthRequired) {
t.Fatalf("ListGroups should require auth, got %v", err)
}
if _, err := b.GetGroup("pfs.general"); !errors.Is(err, nntpd.ErrAuthRequired) {
t.Fatalf("GetGroup should require auth, got %v", err)
}
if _, err := b.GetArticle(&nntp.Group{Name: "pfs.general"}, "1"); !errors.Is(err, nntpd.ErrAuthRequired) {
t.Fatalf("GetArticle should require auth, got %v", err)
}
}
func TestAuthenticate(t *testing.T) {
b := &backend{st: newFakeStore(), host: "news.h"}
if _, err := b.Authenticate("nobody", "x"); !errors.Is(err, nntpd.ErrAuthRejected) {
t.Fatalf("unknown user must be rejected, got %v", err)
}
if _, err := b.Authenticate("bob", "x"); !errors.Is(err, nntpd.ErrAuthRejected) {
t.Fatalf("banned user must be rejected, got %v", err)
}
nb, err := b.Authenticate("Alice", "anything") // case-insensitive, password ignored
if err != nil {
t.Fatalf("valid member rejected: %v", err)
}
ab, ok := nb.(*backend)
if !ok || !ab.Authorized() || !ab.AllowPost() || ab.user != "alice" {
t.Fatalf("authed backend wrong: %+v ok=%v", ab, ok)
}
}
func TestPostStampsFromAndNumbers(t *testing.T) {
fs := newFakeStore()
ab := &backend{st: fs, host: "news.h", user: "alice"}
mkArticle := func(groups, subject, body string) *nntp.Article {
h := textproto.MIMEHeader{}
h.Set("Newsgroups", groups)
h.Set("Subject", subject)
h.Set("From", "forged <evil@elsewhere>") // must be ignored
return &nntp.Article{Header: h, Body: strings.NewReader(body)}
}
if err := ab.Post(mkArticle("pfs.general", "Hi", "hello\nworld\n")); err != nil {
t.Fatalf("post: %v", err)
}
if len(fs.articles) != 1 {
t.Fatalf("expected 1 stored article, got %d", len(fs.articles))
}
got := fs.articles[0]
if got.From != "alice <alice@news.h>" {
t.Fatalf("From not stamped to member: %q", got.From)
}
if got.Num != 1 || got.Subject != "Hi" || got.MsgID == "" {
t.Fatalf("stored article wrong: %+v", got)
}
// Posting only to a locked/unknown group yields ErrNotWanted.
if err := ab.Post(mkArticle("pfs.locked, no.such.group", "x", "y")); !errors.Is(err, nntpd.ErrNotWanted) {
t.Fatalf("post to locked/unknown should be not-wanted, got %v", err)
}
// A retrieved article reconstructs headers and body.
art, err := ab.GetArticle(&nntp.Group{Name: "pfs.general"}, "1")
if err != nil {
t.Fatalf("get article: %v", err)
}
if art.Header.Get("From") != "alice <alice@news.h>" || art.Header.Get("Subject") != "Hi" {
t.Fatalf("reconstructed headers wrong: %+v", art.Header)
}
body, _ := io.ReadAll(art.Body)
if string(body) != "hello\nworld\n" {
t.Fatalf("reconstructed body wrong: %q", body)
}
}

View file

@ -0,0 +1,435 @@
// Package nntpd is a vendored, lightly patched copy of
// github.com/dustin/go-nntp/server (MIT, Dustin Sallings). Two changes make it
// a faithful, members-only Usenet server:
//
// 1. AUTHINFO USER/PASS now return RFC 4643 response codes (381 "password
// required" then 281 "authentication accepted"). Upstream returned 350/250,
// which neither the matching go-nntp client nor standard newsreaders
// (slrn, tin) accept — so authentication was effectively broken.
// 2. The per-command and drop-connection logging is routed through an optional
// Server.ErrLog and the noisy "Got cmd" line is dropped (a public server on
// a small box should not log every protocol verb).
//
// Everything else is upstream. The Backend interface is unchanged, so backends
// written against go-nntp/server work here verbatim.
package nntpd
import (
"fmt"
"io"
"log"
"math"
"net"
"net/textproto"
"strconv"
"strings"
"github.com/dustin/go-nntp"
)
// An NNTPError is a coded NNTP error message.
type NNTPError struct {
Code int
Msg string
}
// Sentinel errors, returned by backends and rendered to the client.
var (
ErrNoSuchGroup = &NNTPError{411, "No such newsgroup"}
ErrNoGroupSelected = &NNTPError{412, "No newsgroup selected"}
ErrInvalidMessageID = &NNTPError{430, "No article with that message-id"}
ErrInvalidArticleNumber = &NNTPError{423, "No article with that number"}
ErrNoCurrentArticle = &NNTPError{420, "Current article number is invalid"}
ErrUnknownCommand = &NNTPError{500, "Unknown command"}
ErrSyntax = &NNTPError{501, "not supported, or syntax error"}
ErrPostingNotPermitted = &NNTPError{440, "Posting not permitted"}
ErrPostingFailed = &NNTPError{441, "posting failed"}
ErrNotWanted = &NNTPError{435, "Article not wanted"}
ErrAuthRequired = &NNTPError{450, "authorization required"}
ErrAuthRejected = &NNTPError{452, "authorization rejected"}
ErrNotAuthenticated = &NNTPError{480, "authentication required"}
)
func (e *NNTPError) Error() string { return fmt.Sprintf("%d %s", e.Code, e.Msg) }
// Handler is a low-level protocol handler.
type Handler func(args []string, s *session, c *textproto.Conn) error
// NumberedArticle ties an article to its per-group sequence number.
type NumberedArticle struct {
Num int64
Article *nntp.Article
}
// Backend provides the data and does the work.
type Backend interface {
ListGroups(max int) ([]*nntp.Group, error)
GetGroup(name string) (*nntp.Group, error)
GetArticle(group *nntp.Group, id string) (*nntp.Article, error)
GetArticles(group *nntp.Group, from, to int64) ([]NumberedArticle, error)
Authorized() bool
// Authenticate validates the credentials and optionally returns a
// replacement backend for this session (nil keeps the current one).
Authenticate(user, pass string) (Backend, error)
AllowPost() bool
Post(article *nntp.Article) error
}
type session struct {
server *Server
backend Backend
group *nntp.Group
}
// Server is an NNTP server handle.
type Server struct {
Handlers map[string]Handler
Backend Backend
// ErrLog, when non-nil, receives connection-level errors. Protocol verbs
// are never logged (a public server should not log every command).
ErrLog *log.Logger
group *nntp.Group
}
// NewServer builds a server bound to a backend.
func NewServer(backend Backend) *Server {
rv := Server{
Handlers: make(map[string]Handler),
Backend: backend,
}
rv.Handlers[""] = handleDefault
rv.Handlers["quit"] = handleQuit
rv.Handlers["group"] = handleGroup
rv.Handlers["list"] = handleList
rv.Handlers["head"] = handleHead
rv.Handlers["body"] = handleBody
rv.Handlers["article"] = handleArticle
rv.Handlers["post"] = handlePost
rv.Handlers["ihave"] = handleIHave
rv.Handlers["capabilities"] = handleCap
rv.Handlers["mode"] = handleMode
rv.Handlers["authinfo"] = handleAuthInfo
rv.Handlers["newgroups"] = handleNewGroups
rv.Handlers["over"] = handleOver
rv.Handlers["xover"] = handleOver
return &rv
}
func (s *Server) logf(format string, args ...any) {
if s.ErrLog != nil {
s.ErrLog.Printf(format, args...)
}
}
func (s *session) dispatchCommand(cmd string, args []string, c *textproto.Conn) error {
handler, found := s.server.Handlers[strings.ToLower(cmd)]
if !found {
handler = s.server.Handlers[""]
}
return handler(args, s, c)
}
// Process handles a single NNTP connection.
func (s *Server) Process(nc net.Conn) {
defer nc.Close()
c := textproto.NewConn(nc)
sess := &session{server: s, backend: s.Backend, group: nil}
_ = c.PrintfLine("200 Hello!")
for {
l, err := c.ReadLine()
if err != nil {
return
}
cmd := strings.Split(l, " ")
args := []string{}
if len(cmd) > 1 {
args = cmd[1:]
}
err = sess.dispatchCommand(cmd[0], args, c)
if err != nil {
if _, isNNTPError := err.(*NNTPError); err == io.EOF {
return
} else if isNNTPError {
_ = c.PrintfLine("%s", err.Error())
} else {
s.logf("dropping conn: %v", err)
return
}
}
}
}
func parseRange(spec string) (low, high int64) {
if spec == "" {
return 0, math.MaxInt64
}
parts := strings.Split(spec, "-")
if len(parts) == 1 {
h, err := strconv.ParseInt(parts[0], 10, 64)
if err != nil {
h = math.MaxInt64
}
return 0, h
}
l, _ := strconv.ParseInt(parts[0], 10, 64)
h, err := strconv.ParseInt(parts[1], 10, 64)
if err != nil {
h = math.MaxInt64
}
return l, h
}
func handleOver(args []string, s *session, c *textproto.Conn) error {
if s.group == nil {
return ErrNoGroupSelected
}
spec := ""
if len(args) > 0 {
spec = args[0]
}
from, to := parseRange(spec)
articles, err := s.backend.GetArticles(s.group, from, to)
if err != nil {
return err
}
_ = c.PrintfLine("224 here it comes")
dw := c.DotWriter()
defer dw.Close()
for _, a := range articles {
fmt.Fprintf(dw, "%d\t%s\t%s\t%s\t%s\t%s\t%d\t%d\n", a.Num,
a.Article.Header.Get("Subject"),
a.Article.Header.Get("From"),
a.Article.Header.Get("Date"),
a.Article.Header.Get("Message-Id"),
a.Article.Header.Get("References"),
a.Article.Bytes, a.Article.Lines)
}
return nil
}
func handleListOverviewFmt(c *textproto.Conn) error {
if err := c.PrintfLine("215 Order of fields in overview database."); err != nil {
return err
}
dw := c.DotWriter()
defer dw.Close()
_, err := fmt.Fprintln(dw, `Subject:
From:
Date:
Message-ID:
References:
:bytes
:lines`)
return err
}
func handleList(args []string, s *session, c *textproto.Conn) error {
ltype := "active"
if len(args) > 0 {
ltype = strings.ToLower(args[0])
}
if ltype == "overview.fmt" {
return handleListOverviewFmt(c)
}
groups, err := s.backend.ListGroups(-1)
if err != nil {
return err
}
_ = c.PrintfLine("215 list of newsgroups follows")
dw := c.DotWriter()
defer dw.Close()
for _, g := range groups {
switch ltype {
case "active":
fmt.Fprintf(dw, "%s %d %d %v\r\n", g.Name, g.High, g.Low, g.Posting)
case "newsgroups":
fmt.Fprintf(dw, "%s %s\r\n", g.Name, g.Description)
}
}
return nil
}
func handleNewGroups(args []string, s *session, c *textproto.Conn) error {
_ = c.PrintfLine("231 list of newsgroups follows")
_ = c.PrintfLine(".")
return nil
}
func handleDefault(args []string, s *session, c *textproto.Conn) error {
return ErrUnknownCommand
}
func handleQuit(args []string, s *session, c *textproto.Conn) error {
_ = c.PrintfLine("205 bye")
return io.EOF
}
func handleGroup(args []string, s *session, c *textproto.Conn) error {
if len(args) < 1 {
return ErrNoSuchGroup
}
group, err := s.backend.GetGroup(args[0])
if err != nil {
return err
}
s.group = group
_ = c.PrintfLine("211 %d %d %d %s", group.Count, group.Low, group.High, group.Name)
return nil
}
func (s *session) getArticle(args []string) (*nntp.Article, error) {
if len(args) == 0 {
return nil, ErrNoCurrentArticle
}
if strings.HasPrefix(args[0], "<") {
return s.backend.GetArticle(s.group, args[0])
}
if s.group == nil {
return nil, ErrNoGroupSelected
}
return s.backend.GetArticle(s.group, args[0])
}
func handleHead(args []string, s *session, c *textproto.Conn) error {
article, err := s.getArticle(args)
if err != nil {
return err
}
_ = c.PrintfLine("221 1 %s", article.MessageID())
dw := c.DotWriter()
defer dw.Close()
for k, v := range article.Header {
fmt.Fprintf(dw, "%s: %s\r\n", k, v[0])
}
return nil
}
func handleBody(args []string, s *session, c *textproto.Conn) error {
article, err := s.getArticle(args)
if err != nil {
return err
}
_ = c.PrintfLine("222 1 %s", article.MessageID())
dw := c.DotWriter()
defer dw.Close()
_, err = io.Copy(dw, article.Body)
return err
}
func handleArticle(args []string, s *session, c *textproto.Conn) error {
article, err := s.getArticle(args)
if err != nil {
return err
}
_ = c.PrintfLine("220 1 %s", article.MessageID())
dw := c.DotWriter()
defer dw.Close()
for k, v := range article.Header {
fmt.Fprintf(dw, "%s: %s\r\n", k, v[0])
}
fmt.Fprintln(dw, "")
_, err = io.Copy(dw, article.Body)
return err
}
func handlePost(args []string, s *session, c *textproto.Conn) error {
if !s.backend.AllowPost() {
return ErrPostingNotPermitted
}
_ = c.PrintfLine("340 Go ahead")
var err error
var article nntp.Article
article.Header, err = c.ReadMIMEHeader()
if err != nil {
return ErrPostingFailed
}
article.Body = c.DotReader()
if err = s.backend.Post(&article); err != nil {
return err
}
_ = c.PrintfLine("240 article received OK")
return nil
}
func handleIHave(args []string, s *session, c *textproto.Conn) error {
if !s.backend.AllowPost() {
return ErrNotWanted
}
article, err := s.backend.GetArticle(nil, args[0])
if article != nil {
return ErrNotWanted
}
_ = c.PrintfLine("335 send it")
article = &nntp.Article{}
article.Header, err = c.ReadMIMEHeader()
if err != nil {
return ErrPostingFailed
}
article.Body = c.DotReader()
if err = s.backend.Post(article); err != nil {
return err
}
_ = c.PrintfLine("235 article received OK")
return nil
}
func handleCap(args []string, s *session, c *textproto.Conn) error {
_ = c.PrintfLine("101 Capability list:")
dw := c.DotWriter()
defer dw.Close()
fmt.Fprintf(dw, "VERSION 2\n")
fmt.Fprintf(dw, "READER\n")
fmt.Fprintf(dw, "AUTHINFO USER\n")
if s.backend.AllowPost() {
fmt.Fprintf(dw, "POST\n")
fmt.Fprintf(dw, "IHAVE\n")
}
fmt.Fprintf(dw, "OVER\n")
fmt.Fprintf(dw, "XOVER\n")
fmt.Fprintf(dw, "LIST ACTIVE NEWSGROUPS OVERVIEW.FMT\n")
return nil
}
func handleMode(args []string, s *session, c *textproto.Conn) error {
if s.backend.AllowPost() {
_ = c.PrintfLine("200 Posting allowed")
} else {
_ = c.PrintfLine("201 Posting prohibited")
}
return nil
}
// handleAuthInfo implements RFC 4643 AUTHINFO USER/PASS (381 then 281).
func handleAuthInfo(args []string, s *session, c *textproto.Conn) error {
if len(args) < 2 {
return ErrSyntax
}
if strings.ToLower(args[0]) != "user" {
return ErrSyntax
}
if s.backend.Authorized() {
return c.PrintfLine("281 already authenticated")
}
if err := c.PrintfLine("381 Password required"); err != nil {
return err
}
a, err := c.ReadLine()
if err != nil {
return err
}
parts := strings.SplitN(a, " ", 3)
if len(parts) < 3 || strings.ToLower(parts[0]) != "authinfo" || strings.ToLower(parts[1]) != "pass" {
return ErrSyntax
}
b, err := s.backend.Authenticate(args[1], parts[2])
if err != nil {
return err
}
if b != nil {
s.backend = b
}
return c.PrintfLine("281 authentication accepted")
}

114
internal/news/reader.go Normal file
View file

@ -0,0 +1,114 @@
package news
import (
"fmt"
"io"
"sort"
"strconv"
"strings"
"github.com/dustin/go-nntp"
nntpclient "github.com/dustin/go-nntp/client"
)
// Reader is a thin NNTP client used by the in-BBS `news@` TUI. It dials the
// loopback listener and authenticates as the member, so it exercises the same
// server path (auth, From-stamping, numbering) as external newsreaders.
type Reader struct {
c *nntpclient.Client
user string
}
// Dial connects to the loopback NNTP server at addr and authenticates as user.
// The password is ignored by the server (membership is the credential).
func Dial(addr, user string) (*Reader, error) {
c, err := nntpclient.New("tcp", addr)
if err != nil {
return nil, err
}
if _, err := c.Authenticate(user, "-"); err != nil {
_ = c.Close()
return nil, fmt.Errorf("auth: %w", err)
}
return &Reader{c: c, user: user}, nil
}
// Close ends the NNTP session.
func (r *Reader) Close() error { return r.c.Close() }
// User is the authenticated member name.
func (r *Reader) User() string { return r.user }
// Groups lists the available newsgroups, name-sorted.
func (r *Reader) Groups() ([]nntp.Group, error) {
gs, err := r.c.List("active")
if err != nil {
return nil, err
}
sort.Slice(gs, func(i, j int) bool { return gs[i].Name < gs[j].Name })
return gs, nil
}
// Select makes group current and returns its bounds.
func (r *Reader) Select(name string) (nntp.Group, error) { return r.c.Group(name) }
// Overview is one row of a group's article overview.
type Overview struct {
Num int64
Subject string
From string
Date string
MsgID string
Refs string
}
// Overview fetches the overview rows for [low,high] in the current group.
func (r *Reader) Overview(low, high int64) ([]Overview, error) {
if high < low || high == 0 {
return nil, nil
}
lines, err := r.c.Over(fmt.Sprintf("%d-%d", low, high))
if err != nil {
return nil, err
}
out := make([]Overview, 0, len(lines))
for _, l := range lines {
f := strings.Split(l, "\t")
if len(f) < 6 {
continue
}
num, _ := strconv.ParseInt(f[0], 10, 64)
out = append(out, Overview{
Num: num, Subject: f[1], From: f[2], Date: f[3], MsgID: f[4], Refs: f[5],
})
}
return out, nil
}
// Article returns the full article (headers and body) for a number in the
// current group.
func (r *Reader) Article(num int64) (string, error) {
_, _, rd, err := r.c.Article(strconv.FormatInt(num, 10))
if err != nil {
return "", err
}
b, err := io.ReadAll(rd)
if err != nil {
return "", err
}
return string(b), nil
}
// Post submits an article to group with the given subject/body. References ties
// a reply to its parent (its Message-ID). The server stamps the From header.
func (r *Reader) Post(group, subject, references, body string) error {
var b strings.Builder
fmt.Fprintf(&b, "Newsgroups: %s\r\n", group)
fmt.Fprintf(&b, "Subject: %s\r\n", subject)
if references != "" {
fmt.Fprintf(&b, "References: %s\r\n", references)
}
b.WriteString("\r\n")
b.WriteString(strings.ReplaceAll(body, "\n", "\r\n"))
return r.c.Post(strings.NewReader(b.String()))
}

164
internal/news/server.go Normal file
View file

@ -0,0 +1,164 @@
package news
import (
"context"
"crypto/tls"
"fmt"
"net"
"os"
"strings"
"sync"
"time"
"github.com/profullstack/agentbbs/internal/news/nntpd"
)
// DefaultAddr is the loopback plaintext listener the in-BBS `news@` reader dials.
// The public surface is the TLS (NNTPS) listener; see ServeTLS.
const DefaultAddr = "127.0.0.1:1119"
// DefaultGroups are seeded on first boot if AGENTBBS_NEWS_GROUPS is unset.
var DefaultGroups = []GroupSpec{
{"pfs.announce", "Official announcements (read-mostly)"},
{"pfs.general", "General discussion for members"},
{"pfs.agents", "For and about AI agents on the BBS"},
{"pfs.support", "Help, questions, and bug reports"},
}
// GroupSpec is a newsgroup to seed.
type GroupSpec struct{ Name, Description string }
// Server hosts the members-only NNTP network over the shared store.
type Server struct {
st NewsStore
srv *nntpd.Server
host string
}
// New builds a news Server. host is the public hostname used in Message-IDs and
// stamped From addresses (e.g. "news.profullstack.com").
func New(st NewsStore, host string) *Server {
return &Server{
st: st,
srv: nntpd.NewServer(&backend{st: st, host: host}),
host: host,
}
}
// SeedGroups ensures the given groups exist. A nil/empty slice seeds
// DefaultGroups. Idempotent.
func (s *Server) SeedGroups(groups []GroupSpec) error {
if len(groups) == 0 {
groups = DefaultGroups
}
for _, g := range groups {
if err := s.st.EnsureNewsGroup(g.Name, g.Description); err != nil {
return err
}
}
return nil
}
// ParseGroups turns the AGENTBBS_NEWS_GROUPS env value into GroupSpecs. Each
// entry is "name" or "name:description", comma- or whitespace-separated.
func ParseGroups(s string) []GroupSpec {
var out []GroupSpec
for _, field := range strings.FieldsFunc(s, func(r rune) bool { return r == ',' || r == '\n' }) {
field = strings.TrimSpace(field)
if field == "" {
continue
}
name, desc, _ := strings.Cut(field, ":")
out = append(out, GroupSpec{Name: strings.TrimSpace(name), Description: strings.TrimSpace(desc)})
}
return out
}
// Serve accepts connections on ln until ctx is cancelled. The anonymous backend
// is immutable and AUTHINFO swaps only the per-session backend, so one Server is
// safe to share across all connections.
func (s *Server) Serve(ctx context.Context, ln net.Listener) error {
go func() { <-ctx.Done(); _ = ln.Close() }()
for {
conn, err := ln.Accept()
if err != nil {
if ctx.Err() != nil {
return nil
}
return err
}
go s.srv.Process(conn)
}
}
// ServeLoopback listens for plaintext NNTP on addr (loopback only — it carries
// no TLS, so it must never be a public interface).
func (s *Server) ServeLoopback(ctx context.Context, addr string) error {
ln, err := net.Listen("tcp", addr)
if err != nil {
return err
}
return s.Serve(ctx, ln)
}
// ServeTLS listens for NNTPS on addr using the certificate at certFile/keyFile,
// reloading it from disk when it changes (so Caddy cert renewals are picked up
// without a restart).
func (s *Server) ServeTLS(ctx context.Context, addr, certFile, keyFile string) error {
k := &certKeeper{certFile: certFile, keyFile: keyFile}
if _, err := k.get(); err != nil {
return fmt.Errorf("load news TLS cert: %w", err)
}
ln, err := tls.Listen("tcp", addr, &tls.Config{
MinVersion: tls.VersionTLS12,
GetCertificate: func(*tls.ClientHelloInfo) (*tls.Certificate, error) { return k.get() },
})
if err != nil {
return err
}
return s.Serve(ctx, ln)
}
// certKeeper loads a TLS keypair from disk and reloads it when either file's
// modification time changes.
type certKeeper struct {
certFile, keyFile string
mu sync.Mutex
cert *tls.Certificate
modSum int64
checked time.Time
}
func (k *certKeeper) get() (*tls.Certificate, error) {
k.mu.Lock()
defer k.mu.Unlock()
// Re-stat at most every 30s to keep the handshake hot path cheap.
if k.cert != nil && time.Since(k.checked) < 30*time.Second {
return k.cert, nil
}
k.checked = time.Now()
sum := statSum(k.certFile) ^ statSum(k.keyFile)
if k.cert != nil && sum == k.modSum {
return k.cert, nil
}
cert, err := tls.LoadX509KeyPair(k.certFile, k.keyFile)
if err != nil {
if k.cert != nil {
return k.cert, nil // keep serving the last good cert on a transient read error
}
return nil, err
}
k.cert, k.modSum = &cert, sum
return k.cert, nil
}
func statSum(path string) int64 {
fi, err := os.Stat(path)
if err != nil {
return 0
}
return fi.ModTime().UnixNano() ^ fi.Size()
}

View file

@ -0,0 +1,111 @@
package news
import (
"context"
"net"
"path/filepath"
"strings"
"testing"
nntpclient "github.com/dustin/go-nntp/client"
"github.com/profullstack/agentbbs/internal/store"
)
// startServer brings up a news Server over an ephemeral loopback listener and
// returns its address. The server stops when the test ends.
func startServer(t *testing.T) (string, store.Store) {
t.Helper()
st, err := store.Open(filepath.Join(t.TempDir(), "t.db"))
if err != nil {
t.Fatalf("open store: %v", err)
}
t.Cleanup(func() { _ = st.Close() })
ns := New(st, "news.test")
if err := ns.SeedGroups(nil); err != nil {
t.Fatalf("seed: %v", err)
}
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatalf("listen: %v", err)
}
ctx, cancel := context.WithCancel(context.Background())
t.Cleanup(cancel)
go func() { _ = ns.Serve(ctx, ln) }()
return ln.Addr().String(), st
}
func TestServerEndToEnd(t *testing.T) {
addr, st := startServer(t)
if _, err := st.EnsureUser("alice", "member", "SHA256:a"); err != nil {
t.Fatalf("ensure user: %v", err)
}
// A non-member cannot authenticate.
if _, err := Dial(addr, "intruder"); err == nil {
t.Fatal("non-member should not be able to connect")
}
// An unauthenticated raw client must not be able to LIST (members-only).
raw, err := nntpclient.New("tcp", addr)
if err != nil {
t.Fatalf("raw dial: %v", err)
}
if _, err := raw.List("active"); err == nil {
t.Fatal("unauthenticated LIST must be refused")
}
_ = raw.Close()
// A member connects, posts, and reads it back.
r, err := Dial(addr, "alice")
if err != nil {
t.Fatalf("member dial: %v", err)
}
defer r.Close()
if err := r.Post("pfs.general", "First post", "", "Hello, Usenet.\n"); err != nil {
t.Fatalf("post: %v", err)
}
groups, err := r.Groups()
if err != nil {
t.Fatalf("groups: %v", err)
}
var general bool
for _, g := range groups {
if g.Name == "pfs.general" {
general = true
}
}
if !general {
t.Fatalf("pfs.general not listed: %+v", groups)
}
g, err := r.Select("pfs.general")
if err != nil {
t.Fatalf("select: %v", err)
}
if g.High < 1 {
t.Fatalf("expected at least one article, high=%d", g.High)
}
ov, err := r.Overview(g.Low, g.High)
if err != nil {
t.Fatalf("overview: %v", err)
}
if len(ov) != 1 || ov[0].Subject != "First post" {
t.Fatalf("overview wrong: %+v", ov)
}
// From is stamped to the member, not anything client-supplied.
if !strings.Contains(ov[0].From, "alice") {
t.Fatalf("From not stamped: %q", ov[0].From)
}
art, err := r.Article(ov[0].Num)
if err != nil {
t.Fatalf("article: %v", err)
}
if !strings.Contains(art, "Hello, Usenet.") || !strings.Contains(art, "Subject: First post") {
t.Fatalf("article body/headers wrong: %q", art)
}
}

435
internal/news/tui.go Normal file
View file

@ -0,0 +1,435 @@
package news
import (
"fmt"
"strings"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/lipgloss"
"github.com/charmbracelet/ssh"
"github.com/dustin/go-nntp"
)
var (
nTitle = lipgloss.NewStyle().Bold(true).Foreground(lipgloss.Color("#c084fc"))
nSel = lipgloss.NewStyle().Foreground(lipgloss.Color("#0b1020")).Background(lipgloss.Color("#38bdf8"))
nMeta = lipgloss.NewStyle().Foreground(lipgloss.Color("241"))
nFrom = lipgloss.NewStyle().Foreground(lipgloss.Color("#4ade80"))
nErr = lipgloss.NewStyle().Foreground(lipgloss.Color("203"))
nHint = lipgloss.NewStyle().Foreground(lipgloss.Color("244"))
)
// RunReader connects the member to the loopback NNTP server and drives the
// newsreader TUI over the SSH session until they leave.
func RunReader(s ssh.Session, addr, user string) error {
ptyReq, winCh, hasPty := s.Pty()
if !hasPty {
_, _ = s.Write([]byte("news needs a terminal (ssh -t news@<host>)\r\n"))
return nil
}
r, err := Dial(addr, user)
if err != nil {
return err
}
m := &model{r: r, width: ptyReq.Window.Width, height: ptyReq.Window.Height, mode: modeGroups}
p := tea.NewProgram(m, tea.WithInput(s), tea.WithOutput(s), tea.WithAltScreen())
go func() {
for w := range winCh {
p.Send(tea.WindowSizeMsg{Width: w.Width, Height: w.Height})
}
}()
_, runErr := p.Run()
_ = r.Close()
return runErr
}
type mode int
const (
modeGroups mode = iota
modeThreads
modeArticle
modeCompose
)
type model struct {
r *Reader
mode mode
groups []nntp.Group
gSel int
group nntp.Group
threads []Overview
tSel int
article string
aScroll int
// compose
cField int // 0=subject, 1=body
cSubject string
cBody string
cRefs string
status string
width, height int
}
// async message types
type groupsMsg struct {
groups []nntp.Group
err error
}
type threadsMsg struct {
group nntp.Group
threads []Overview
err error
}
type articleMsg struct {
text string
err error
}
type postedMsg struct{ err error }
func (m *model) Init() tea.Cmd { return m.loadGroups }
func (m *model) loadGroups() tea.Msg {
gs, err := m.r.Groups()
return groupsMsg{groups: gs, err: err}
}
func (m *model) loadThreads(name string) tea.Cmd {
return func() tea.Msg {
g, err := m.r.Select(name)
if err != nil {
return threadsMsg{err: err}
}
ov, err := m.r.Overview(g.Low, g.High)
return threadsMsg{group: g, threads: ov, err: err}
}
}
func (m *model) loadArticle(num int64) tea.Cmd {
return func() tea.Msg {
txt, err := m.r.Article(num)
return articleMsg{text: txt, err: err}
}
}
func (m *model) submitPost() tea.Cmd {
group, subject, refs, body := m.group.Name, strings.TrimSpace(m.cSubject), m.cRefs, m.cBody
return func() tea.Msg {
if subject == "" {
subject = "(no subject)"
}
return postedMsg{err: m.r.Post(group, subject, refs, body)}
}
}
func (m *model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
switch msg := msg.(type) {
case tea.WindowSizeMsg:
m.width, m.height = msg.Width, msg.Height
case groupsMsg:
if msg.err != nil {
m.status = "groups: " + msg.err.Error()
} else {
m.groups = msg.groups
}
case threadsMsg:
if msg.err != nil {
m.status = "open group: " + msg.err.Error()
m.mode = modeGroups
} else {
m.group, m.threads, m.tSel, m.mode = msg.group, msg.threads, 0, modeThreads
}
case articleMsg:
if msg.err != nil {
m.status = "open article: " + msg.err.Error()
} else {
m.article, m.aScroll, m.mode = msg.text, 0, modeArticle
}
case postedMsg:
if msg.err != nil {
m.status = "post failed: " + msg.err.Error()
return m, nil
}
m.status = "posted to " + m.group.Name
m.mode = modeThreads
return m, m.loadThreads(m.group.Name)
case tea.KeyMsg:
return m.handleKey(msg)
}
return m, nil
}
func (m *model) handleKey(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
if m.mode == modeCompose {
return m.composeKey(msg)
}
switch msg.String() {
case "ctrl+c":
return m, tea.Quit
}
switch m.mode {
case modeGroups:
switch msg.String() {
case "q", "esc":
return m, tea.Quit
case "up", "k":
if m.gSel > 0 {
m.gSel--
}
case "down", "j":
if m.gSel < len(m.groups)-1 {
m.gSel++
}
case "enter", "right", "l":
if len(m.groups) > 0 {
return m, m.loadThreads(m.groups[m.gSel].Name)
}
}
case modeThreads:
switch msg.String() {
case "q", "esc", "left", "h":
m.mode = modeGroups
case "up", "k":
if m.tSel > 0 {
m.tSel--
}
case "down", "j":
if m.tSel < len(m.threads)-1 {
m.tSel++
}
case "enter", "right", "l":
if len(m.threads) > 0 {
return m, m.loadArticle(m.threads[m.tSel].Num)
}
case "p":
m.startCompose("", "")
}
case modeArticle:
switch msg.String() {
case "q", "esc", "left", "h":
m.mode = modeThreads
case "up", "k":
if m.aScroll > 0 {
m.aScroll--
}
case "down", "j":
m.aScroll++
case "r":
cur := m.threads[m.tSel]
subj := cur.Subject
if !strings.HasPrefix(strings.ToLower(subj), "re:") {
subj = "Re: " + subj
}
refs := strings.TrimSpace(cur.Refs + " " + cur.MsgID)
m.startCompose(subj, refs)
}
}
return m, nil
}
func (m *model) startCompose(subject, refs string) {
m.mode = modeCompose
m.cField = 0
m.cSubject = subject
m.cBody = ""
m.cRefs = refs
}
func (m *model) composeKey(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
switch msg.String() {
case "esc":
m.mode = modeThreads
m.status = "compose cancelled"
return m, nil
case "ctrl+s":
return m, m.submitPost()
case "tab":
m.cField = (m.cField + 1) % 2
return m, nil
}
if m.cField == 0 { // subject
switch msg.String() {
case "enter":
m.cField = 1
case "backspace":
if len(m.cSubject) > 0 {
m.cSubject = m.cSubject[:len(m.cSubject)-1]
}
default:
if msg.Type == tea.KeyRunes || msg.String() == " " {
m.cSubject += string(msg.Runes)
}
}
return m, nil
}
// body
switch msg.String() {
case "enter":
m.cBody += "\n"
case "backspace":
if len(m.cBody) > 0 {
m.cBody = m.cBody[:len(m.cBody)-1]
}
default:
if msg.Type == tea.KeyRunes || msg.String() == " " {
m.cBody += string(msg.Runes)
}
}
return m, nil
}
func (m *model) View() string {
switch m.mode {
case modeGroups:
return m.viewGroups()
case modeThreads:
return m.viewThreads()
case modeArticle:
return m.viewArticle()
case modeCompose:
return m.viewCompose()
}
return ""
}
func (m *model) rows() int {
r := m.height - 4
if r < 3 {
r = 3
}
return r
}
func (m *model) frame(header, body, hint string) string {
status := ""
if m.status != "" {
status = "\n" + nMeta.Render(m.status)
}
return lipgloss.NewStyle().Padding(0, 1).Render(
nTitle.Render(header) + "\n\n" + body + status + "\n\n" + nHint.Render(hint))
}
func (m *model) viewGroups() string {
var b strings.Builder
for i, g := range m.groups {
line := fmt.Sprintf("%-24s %5d articles", g.Name, g.High)
if i == m.gSel {
line = nSel.Render("› " + line)
} else {
line = " " + line
}
b.WriteString(line + "\n")
}
if len(m.groups) == 0 {
b.WriteString(nMeta.Render("no groups yet"))
}
return m.frame("news@ "+m.r.User()+" — newsgroups", b.String(),
"↑/↓ move · enter open · q quit")
}
func (m *model) viewThreads() string {
var b strings.Builder
start, rows := scrollStart(m.tSel, len(m.threads), m.rows())
for i := start; i < len(m.threads) && i < start+rows; i++ {
t := m.threads[i]
line := fmt.Sprintf("%-50s %s", truncate(t.Subject, 50), nFrom.Render(shortFrom(t.From)))
if i == m.tSel {
line = nSel.Render("› ") + line
} else {
line = " " + line
}
b.WriteString(line + "\n")
}
if len(m.threads) == 0 {
b.WriteString(nMeta.Render("no articles — press p to post the first one"))
}
return m.frame("news@ — "+m.group.Name, b.String(),
"↑/↓ move · enter read · p post · esc groups")
}
func (m *model) viewArticle() string {
lines := strings.Split(strings.ReplaceAll(m.article, "\r\n", "\n"), "\n")
rows := m.rows()
if m.aScroll > len(lines)-1 {
m.aScroll = max(0, len(lines)-1)
}
end := m.aScroll + rows
if end > len(lines) {
end = len(lines)
}
body := strings.Join(lines[m.aScroll:end], "\n")
return m.frame("news@ — "+m.group.Name, body,
"↑/↓ scroll · r reply · esc back")
}
func (m *model) viewCompose() string {
subjLabel, bodyLabel := " Subject: ", " Body:"
if m.cField == 0 {
subjLabel = nSel.Render("› Subject: ")
} else {
bodyLabel = nSel.Render("› Body:")
}
cursor := ""
if m.cField == 0 {
cursor = "█"
}
body := subjLabel + m.cSubject + cursor + "\n" + bodyLabel + "\n"
bodyText := m.cBody
if m.cField == 1 {
bodyText += "█"
}
body += indent(bodyText)
header := "compose → " + m.group.Name
if m.cRefs != "" {
header = "reply → " + m.group.Name
}
return m.frame(header, body, "tab switch field · ctrl+s send · esc cancel")
}
func scrollStart(sel, n, rows int) (int, int) {
if n <= rows {
return 0, rows
}
start := sel - rows/2
if start < 0 {
start = 0
}
if start > n-rows {
start = n - rows
}
return start, rows
}
func truncate(s string, n int) string {
if len(s) <= n {
return s
}
if n <= 1 {
return s[:n]
}
return s[:n-1] + "…"
}
// shortFrom renders just the display name (or local part) of a From header.
func shortFrom(from string) string {
if i := strings.IndexByte(from, '<'); i > 0 {
return strings.TrimSpace(from[:i])
}
if i := strings.IndexByte(from, '@'); i > 0 {
return from[:i]
}
return from
}
func indent(s string) string {
var b strings.Builder
for _, l := range strings.Split(s, "\n") {
b.WriteString(" " + l + "\n")
}
return b.String()
}