Brings back posting, which Phase 0 removed with the terminal interface. - Content page: per inventory entry, fetch its X account, X hashtag search, YouTube channel and RSS/Atom feeds (new), then select, dismiss or restore the fetched items, which are kept in the database. - Writing: one AI call returns a draft per channel (X and LinkedIn), prompted from the company profile, the entry's relationship, talking points and mention policy, and each channel's rules. Fetched text is quoted as untrusted. An over-long X draft gets one request to shorten. - Drafts page: edit with a live length counter that counts like X, then publish each draft on its own. A draft is claimed before posting so it can't go out twice; failures are kept on the draft for a retry; X tokens are refreshed and saved. - Migration 2 adds content_items and drafts, and turns queued posts into drafts for the platforms they hadn't reached. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
257 lines
9.8 KiB
Go
257 lines
9.8 KiB
Go
package web
|
|
|
|
import (
|
|
"bytes"
|
|
"encoding/json"
|
|
"io"
|
|
"log/slog"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"net/url"
|
|
"path/filepath"
|
|
"strings"
|
|
"testing"
|
|
|
|
"supermarket/internal/bridge"
|
|
"supermarket/internal/core"
|
|
"supermarket/internal/db"
|
|
"supermarket/internal/inventory"
|
|
"supermarket/internal/mcpserver"
|
|
"supermarket/internal/profile"
|
|
"supermarket/internal/secrets"
|
|
)
|
|
|
|
const testToken = "0123456789abcdef0123456789abcdef"
|
|
|
|
func newTestServer(t *testing.T, c *core.Core) (*Server, http.Handler) {
|
|
t.Helper()
|
|
dir := t.TempDir()
|
|
d, err := db.Open(filepath.Join(dir, "app.db"))
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
t.Cleanup(func() { d.Close() })
|
|
sec, err := secrets.Open(filepath.Join(dir, "secrets.json"))
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
s := &Server{
|
|
DB: d, Secrets: sec, Core: c, DataDir: dir,
|
|
PublicURL: "http://localhost:8470", Version: "test", MCPToken: testToken,
|
|
MCP: mcpserver.Handler(d, testToken, "test"),
|
|
Log: slog.New(slog.NewTextHandler(io.Discard, nil)),
|
|
}
|
|
h, err := s.Handler()
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
return s, h
|
|
}
|
|
|
|
func do(h http.Handler, method, target string, body io.Reader, hdr map[string]string) *httptest.ResponseRecorder {
|
|
req := httptest.NewRequest(method, target, body)
|
|
req.Host = "localhost:8470"
|
|
for k, v := range hdr {
|
|
req.Header.Set(k, v)
|
|
}
|
|
rec := httptest.NewRecorder()
|
|
h.ServeHTTP(rec, req)
|
|
return rec
|
|
}
|
|
|
|
func postForm(h http.Handler, target string, form url.Values) *httptest.ResponseRecorder {
|
|
return do(h, http.MethodPost, target, strings.NewReader(form.Encode()), map[string]string{
|
|
"Content-Type": "application/x-www-form-urlencoded",
|
|
"Origin": "http://localhost:8470",
|
|
})
|
|
}
|
|
|
|
func TestEveryPageRenders(t *testing.T) {
|
|
for _, c := range []*core.Core{nil, {Domain: "example.com", Email: "pat@example.com", Name: "Pat"}} {
|
|
s, h := newTestServer(t, c)
|
|
// Some data, so templates' non-empty branches run too.
|
|
if err := profile.Save(s.DB, &profile.Profile{Name: "Acme", Description: "Widgets.",
|
|
Products: []profile.Product{{Name: "Widget", Benefits: []string{"fast"}}},
|
|
Websites: []profile.Website{{URL: "https://acme.example", Repo: "r"}}}); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
e := &inventory.Entry{Name: "Rival", Relationship: "competitor", Hashtags: []string{"rival"}}
|
|
if err := inventory.Save(s.DB, e); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := bridge.Record(s.DB, bridge.Checkin{Agent: "hermes", MCPHubTools: []string{"espocrm_create_lead"}}); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := s.Secrets.Set(map[string]string{secrets.XAccessToken: "tok"}); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
|
|
for _, path := range []string{"/", "/?msg=saved", "/profile", "/inventory", "/inventory?relationship=partner",
|
|
"/inventory/new", "/inventory/1", "/inventory/import", "/inventory/export",
|
|
"/settings/ai", "/settings/credentials", "/core", "/static/app.css", "/static/htmx.min.js", "/healthz",
|
|
"/content", "/content/1", "/content/1?dismissed=1", "/drafts", "/drafts?msg=drafted"} {
|
|
rec := do(h, http.MethodGet, path, nil, nil)
|
|
if rec.Code != http.StatusOK {
|
|
t.Errorf("core=%v GET %s: %d %s", c != nil, path, rec.Code, rec.Body.String())
|
|
}
|
|
}
|
|
if rec := do(h, http.MethodGet, "/inventory/999", nil, nil); rec.Code != http.StatusNotFound {
|
|
t.Errorf("missing entry: %d", rec.Code)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestGuardRejectsForeignHostsAndCrossSitePosts(t *testing.T) {
|
|
_, h := newTestServer(t, nil)
|
|
|
|
req := httptest.NewRequest(http.MethodGet, "/", nil)
|
|
req.Host = "evil.example:8470" // DNS rebinding
|
|
rec := httptest.NewRecorder()
|
|
h.ServeHTTP(rec, req)
|
|
if rec.Code != http.StatusMisdirectedRequest {
|
|
t.Errorf("foreign Host: got %d", rec.Code)
|
|
}
|
|
|
|
form := url.Values{"name": {"Acme"}, "description": {"x"}}
|
|
rec = do(h, http.MethodPost, "/profile", strings.NewReader(form.Encode()), map[string]string{
|
|
"Content-Type": "application/x-www-form-urlencoded",
|
|
"Origin": "https://evil.example",
|
|
})
|
|
if rec.Code != http.StatusForbidden {
|
|
t.Errorf("cross-origin POST: got %d", rec.Code)
|
|
}
|
|
rec = do(h, http.MethodPost, "/profile", strings.NewReader(form.Encode()), map[string]string{
|
|
"Content-Type": "application/x-www-form-urlencoded",
|
|
"Sec-Fetch-Site": "cross-site",
|
|
})
|
|
if rec.Code != http.StatusForbidden {
|
|
t.Errorf("cross-site POST without Origin: got %d", rec.Code)
|
|
}
|
|
if rec := postForm(h, "/profile", form); rec.Code != http.StatusSeeOther {
|
|
t.Errorf("same-origin POST: got %d %s", rec.Code, rec.Body.String())
|
|
}
|
|
}
|
|
|
|
func TestProfileAndInventoryForms(t *testing.T) {
|
|
s, h := newTestServer(t, nil)
|
|
|
|
form := url.Values{
|
|
"name": {" Acme "}, "description": {"We make widgets."}, "keywords": {"widgets\n\nwidget software\nWidgets"},
|
|
"product_name": {"Widget", ""}, "product_url": {"https://a.example/w", ""},
|
|
"product_description": {"A widget", ""}, "product_pricing": {"$5", ""}, "product_benefits": {"cheap\nfast", ""},
|
|
"website_url": {"https://acme.example/", ""}, "website_repo": {"https://gitea.example/acme/site.git", ""},
|
|
"website_branch": {"", ""}, "website_plausible": {"", ""}, "website_gsc": {"", ""}, "website_bing": {"", ""},
|
|
"account_x": {"@acme"}, "subreddits": {"r/selfhosted\n/r/homelab"},
|
|
}
|
|
if rec := postForm(h, "/profile", form); rec.Code != http.StatusSeeOther {
|
|
t.Fatalf("save profile: %d %s", rec.Code, rec.Body.String())
|
|
}
|
|
p, _ := profile.Load(s.DB)
|
|
if p.Name != "Acme" || len(p.Products) != 1 || len(p.Products[0].Benefits) != 2 {
|
|
t.Errorf("profile products: %+v", p)
|
|
}
|
|
if len(p.Keywords) != 2 {
|
|
t.Errorf("keywords should be de-duplicated case-insensitively: %q", p.Keywords)
|
|
}
|
|
if len(p.Websites) != 1 || p.Websites[0].URL != "https://acme.example" || p.Websites[0].Branch != "main" {
|
|
t.Errorf("websites: %+v", p.Websites)
|
|
}
|
|
if p.Accounts.X != "acme" || strings.Join(p.Accounts.Subreddits, ",") != "selfhosted,homelab" {
|
|
t.Errorf("accounts: %+v", p.Accounts)
|
|
}
|
|
|
|
// Missing description: the form comes back with an error, nothing saved.
|
|
rec := postForm(h, "/profile", url.Values{"name": {"Other"}})
|
|
if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), "required") {
|
|
t.Errorf("invalid profile: %d", rec.Code)
|
|
}
|
|
|
|
entry := url.Values{"name": {"Rival"}, "relationship": {"competitor"}, "hashtags": {"rival, #Other"}, "twitter_handle": {"@rival"}}
|
|
if rec := postForm(h, "/inventory/save", entry); rec.Code != http.StatusSeeOther {
|
|
t.Fatalf("save entry: %d %s", rec.Code, rec.Body.String())
|
|
}
|
|
entries, _ := inventory.List(s.DB, "competitor")
|
|
if len(entries) != 1 || entries[0].TwitterHandle != "rival" || entries[0].MentionPolicy != "category" ||
|
|
strings.Join(entries[0].Hashtags, " ") != "#rival #Other" {
|
|
t.Fatalf("entry: %+v", entries)
|
|
}
|
|
// Same name, different case: refused.
|
|
rec = postForm(h, "/inventory/save", url.Values{"name": {"RIVAL"}, "relationship": {"partner"}})
|
|
if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), "already has that name") {
|
|
t.Errorf("duplicate: %d", rec.Code)
|
|
}
|
|
|
|
rec = postForm(h, "/inventory/import", url.Values{"example": {"federated"}, "relationship": {"watch"}})
|
|
if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), "21 added") {
|
|
t.Errorf("import example: %d %s", rec.Code, rec.Body.String())
|
|
}
|
|
partners, _ := inventory.List(s.DB, "partner")
|
|
if len(partners) != 21 {
|
|
t.Errorf("example entries are partners: got %d", len(partners))
|
|
}
|
|
|
|
if rec := postForm(h, "/inventory/1/delete", nil); rec.Code != http.StatusSeeOther {
|
|
t.Errorf("delete: %d", rec.Code)
|
|
}
|
|
}
|
|
|
|
func TestCredentialsKeepAndRemove(t *testing.T) {
|
|
s, h := newTestServer(t, nil)
|
|
postForm(h, "/settings/credentials", url.Values{secrets.AnthropicAPIKey: {" sk-1 "}, secrets.YouTubeAPIKey: {"yt"}})
|
|
// Empty field keeps the value; remove clears it.
|
|
postForm(h, "/settings/credentials", url.Values{secrets.AnthropicAPIKey: {""}, "remove:" + secrets.YouTubeAPIKey: {"on"}})
|
|
if got := s.Secrets.Get(secrets.AnthropicAPIKey); got != "sk-1" {
|
|
t.Errorf("anthropic key = %q", got)
|
|
}
|
|
if s.Secrets.Has(secrets.YouTubeAPIKey) {
|
|
t.Error("youtube key should be removed")
|
|
}
|
|
page := do(h, http.MethodGet, "/settings/credentials", nil, nil).Body.String()
|
|
if strings.Contains(page, "sk-1") {
|
|
t.Error("the credentials page must never show a saved value")
|
|
}
|
|
}
|
|
|
|
func TestOAuthCallbackRejectsUnknownState(t *testing.T) {
|
|
_, h := newTestServer(t, nil)
|
|
rec := do(h, http.MethodGet, "/auth/x/callback?state=nope&code=c", nil, nil)
|
|
if rec.Code != http.StatusSeeOther || !strings.Contains(rec.Header().Get("Location"), "oauth-expired") {
|
|
t.Errorf("got %d %s", rec.Code, rec.Header().Get("Location"))
|
|
}
|
|
}
|
|
|
|
func TestMCPNeedsTokenAndChecksIn(t *testing.T) {
|
|
s, h := newTestServer(t, nil)
|
|
call := func(token string, body any) *httptest.ResponseRecorder {
|
|
raw, _ := json.Marshal(body)
|
|
hdr := map[string]string{"Content-Type": "application/json", "Accept": "application/json, text/event-stream"}
|
|
if token != "" {
|
|
hdr["Authorization"] = "Bearer " + token
|
|
}
|
|
return do(h, http.MethodPost, "/mcp", bytes.NewReader(raw), hdr)
|
|
}
|
|
list := map[string]any{"jsonrpc": "2.0", "id": 1, "method": "tools/list"}
|
|
if rec := call("", list); rec.Code != http.StatusUnauthorized {
|
|
t.Errorf("no token: %d", rec.Code)
|
|
}
|
|
if rec := call("wrong", list); rec.Code != http.StatusUnauthorized {
|
|
t.Errorf("wrong token: %d", rec.Code)
|
|
}
|
|
rec := call(testToken, list)
|
|
if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), "bridge_checkin") {
|
|
t.Fatalf("tools/list: %d %s", rec.Code, rec.Body.String())
|
|
}
|
|
|
|
rec = call(testToken, map[string]any{"jsonrpc": "2.0", "id": 2, "method": "tools/call", "params": map[string]any{
|
|
"name": "bridge_checkin",
|
|
"arguments": map[string]any{"agent": "hermes", "mcphub_tools": []string{"espocrm_list_leads"}},
|
|
}})
|
|
if rec.Code != http.StatusOK || strings.Contains(rec.Body.String(), `"isError":true`) {
|
|
t.Fatalf("checkin: %d %s", rec.Code, rec.Body.String())
|
|
}
|
|
last, err := bridge.Last(s.DB)
|
|
if err != nil || last == nil || last.Agent != "hermes" || len(last.MCPHubTools) != 1 {
|
|
t.Fatalf("checkin not recorded: %+v %v", last, err)
|
|
}
|
|
}
|