Files
supermarket/internal/web/settings.go
davidandClaude Opus 5.5 9c62680927 Remind before LinkedIn's sign-in expires, and stop posting once it has
LinkedIn tokens last 60 days and can't be renewed without signing in
again. The expiry LinkedIn reports is now recorded (60 days from sign-in
for older connections). The LinkedIn card says until when; from two
weeks before, the Overview, the Inbox and the card remind you, with a
Reconnect button. Once expired, LinkedIn counts as not connected, due
posts come back to the Inbox saying why, and a 401 from LinkedIn reads
"reconnect LinkedIn" instead of the raw error.

Also fixes a leftover "Settings → Credentials" in a publish error.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 11:43:59 -07:00

484 lines
16 KiB
Go

package web
import (
"context"
"html"
"net/http"
"net/url"
"strings"
"time"
"supermarket/internal/ai"
linkedinapi "supermarket/internal/api/linkedin"
"supermarket/internal/api/reddit"
"supermarket/internal/api/twitter"
"supermarket/internal/oauth"
"supermarket/internal/secrets"
)
// --- AI provider ---
// Anthropic models offered in the model field. Any model ID can be typed.
var anthropicModels = []string{"claude-opus-5-5", "claude-sonnet-5-5", "claude-haiku-5-5", "claude-fable-5-2"}
var efforts = []string{"low", "medium", "high", "xhigh", "max"}
func (s *Server) aiPage(w http.ResponseWriter, r *http.Request) {
cfg, err := ai.LoadConfig(s.DB)
if err != nil {
s.serverError(w, err)
return
}
s.renderAI(w, r, cfg, "")
}
func (s *Server) renderAI(w http.ResponseWriter, r *http.Request, cfg ai.Config, errMsg string) {
s.render(w, r, "ai", page{Title: "AI", Nav: "settings/ai", Error: errMsg, Data: map[string]any{
"Cfg": cfg,
"AnthropicModels": anthropicModels,
"Efforts": efforts,
"Tasks": ai.Tasks,
"Servers": s.aiServers(),
"HasAnthropicKey": s.Secrets.Has(secrets.AnthropicAPIKey),
"Keys": aiKeys,
"Set": s.secretState(secrets.AnthropicAPIKey, secrets.OpenAIAPIKey),
"Shared": ai.LoadShared(),
}})
}
func aiFromForm(r *http.Request) ai.Config {
f := r.PostForm
cfg := ai.Config{
Provider: f.Get("provider"),
Model: strings.TrimSpace(f.Get("model")),
BaseURL: ai.NormalizeBaseURL(f.Get("base_url")),
Effort: f.Get("effort"),
TaskModels: map[string]string{},
}
for _, t := range ai.Tasks {
if m := strings.TrimSpace(f.Get("task_" + t.ID)); m != "" {
cfg.TaskModels[t.ID] = m
}
}
if cfg.Provider != ai.ProviderOpenAI {
cfg.Provider = ai.ProviderAnthropic
cfg.BaseURL = ""
} else {
cfg.Effort = ""
}
return cfg
}
func (s *Server) aiSave(w http.ResponseWriter, r *http.Request) {
if err := r.ParseForm(); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
// Keys first: they're kept even if the rest of the form needs fixing.
if err := s.saveSecrets(r, aiKeys); err != nil {
s.serverError(w, err)
return
}
cfg := aiFromForm(r)
switch {
case cfg.Model == "":
s.renderAI(w, r, cfg, "Choose a model.")
return
case cfg.Provider == ai.ProviderOpenAI && cfg.BaseURL == "":
s.renderAI(w, r, cfg, "Enter the server's address.")
return
}
if err := ai.SaveConfig(s.DB, cfg); err != nil {
s.serverError(w, err)
return
}
redirect(w, r, "/settings/ai", "saved")
}
// aiTest sends a short prompt with the form's (unsaved) settings and shows
// the reply. htmx swaps the result into the page.
func (s *Server) aiTest(w http.ResponseWriter, r *http.Request) {
if err := r.ParseForm(); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
cfg := aiFromForm(r)
result := map[string]any{}
client, err := ai.New(cfg, s.Secrets)
if err == nil {
ctx, cancel := context.WithTimeout(r.Context(), 2*time.Minute)
defer cancel()
start := time.Now()
var reply string
reply, err = client.Generate(ctx, ai.Request{
Prompt: "Reply with one short sentence confirming you can help write marketing copy.",
MaxTokens: 2000,
})
result["Reply"] = reply
result["Took"] = time.Since(start).Round(100 * time.Millisecond).String()
}
if err != nil {
result["Error"] = err.Error()
}
s.fragment(w, "ai", "test-result", result)
}
// aiModels lists an OpenAI-compatible server's models (htmx fragment).
func (s *Server) aiModels(w http.ResponseWriter, r *http.Request) {
base := r.URL.Query().Get("base_url")
data := map[string]any{}
if strings.TrimSpace(base) == "" {
data["Error"] = "Enter the server's address first."
} else {
ctx, cancel := context.WithTimeout(r.Context(), 15*time.Second)
defer cancel()
models, err := ai.ListModels(ctx, base, s.Secrets.Get(secrets.OpenAIAPIKey))
if err != nil {
data["Error"] = err.Error()
}
data["Models"] = models
}
s.fragment(w, "ai", "model-list", data)
}
// --- Secrets forms ---
// secretField is one secret a settings form edits. Saved values are never
// shown: an empty field keeps what's saved. Link is where to get it; Help
// says where on that page.
type secretField struct {
Group, Name, Label, Help, Link string
}
// Where each key is found. Developer portals move; these were checked on
// 2026-11-21.
const (
xConsole = "https://console.x.com"
linkedInApps = "https://www.linkedin.com/developers/apps"
redditApps = "https://www.reddit.com/prefs/apps"
googleCreds = "https://console.cloud.google.com/apis/credentials"
anthropicKeys = "https://platform.claude.com/settings/keys"
)
// aiKeys are edited on the AI tab.
var aiKeys = []secretField{
{"anthropic", secrets.AnthropicAPIKey, "Anthropic API key",
"In the Claude Console, Settings → API keys → Create key. It's shown once: copy it straight here.", anthropicKeys},
{"openai", secrets.OpenAIAPIKey, "API key for the server",
"Only if your server asks for one (Ollama and LM Studio don't). It's in the server's or service's settings.", ""},
}
// accountFields are edited on the Social accounts tab, by network.
var accountFields = []secretField{
{"X", secrets.XBearerToken, "Bearer token",
"For reading posts; needs an X API plan with read access. In the X Developer Console, open your app → Keys and tokens → Bearer token.", xConsole},
{"X", secrets.XClientID, "OAuth 2.0 client ID",
"For posting. In your app, set up User authentication (read and write; type Web App; the callback URL below), then Keys and tokens → OAuth 2.0 Client ID.", xConsole},
{"X", secrets.XClientSecret, "OAuth 2.0 client secret",
"Next to the client ID, under Keys and tokens. Only a confidential client (Web App) has one; leave empty for a public client.", xConsole},
{"LinkedIn", secrets.LinkedInClientID, "Client ID",
"Create an app (it needs a LinkedIn company page), add the products Share on LinkedIn and Sign In with LinkedIn using OpenID Connect, then open the Auth tab.", linkedInApps},
{"LinkedIn", secrets.LinkedInClientSecret, "Client secret",
"On the same Auth tab, under the client ID.", linkedInApps},
{"Reddit", secrets.RedditClientID, "Client ID",
"Create app → choose \"web app\" and enter the redirect URI below. The client ID is the string under the app's name.", redditApps},
{"Reddit", secrets.RedditClientSecret, "Client secret",
"On the same app, next to \"secret\".", redditApps},
{"YouTube", secrets.YouTubeAPIKey, "API key",
"Free. In Google Cloud, enable the YouTube Data API v3 for a project, then Credentials → Create credentials → API key. For reading channels' videos.", googleCreds},
}
// saveSecrets stores what was typed into these fields. An empty field keeps
// the saved value; "remove:<name>" clears it.
func (s *Server) saveSecrets(r *http.Request, fields []secretField) error {
updates := map[string]string{}
for _, f := range fields {
if r.PostForm.Get("remove:"+f.Name) == "on" {
updates[f.Name] = ""
continue
}
if v := strings.TrimSpace(r.PostForm.Get(f.Name)); v != "" {
updates[f.Name] = v
}
}
if len(updates) == 0 {
return nil
}
return s.Secrets.Set(updates)
}
// --- Social accounts ---
// network is one card on the Social accounts tab: its keys, and the sign-in
// that lets Supermarket post as you.
type network struct {
Name string
Fields []secretField
Connect *connectInfo // nil: read-only, no sign-in
Set map[string]bool // which secrets are saved
Saved bool // just saved: say so on the card
}
type connectInfo struct {
Provider string // the /auth/{provider} path segment
Redirect string // the callback URL to register with the network
Setup string // where to register it
Ready bool // the keys the sign-in needs are saved
Signed bool // a token is saved
Account string
At time.Time
Note string
Expiry *Expiry // when the sign-in runs out, for LinkedIn
}
func (s *Server) accountsPage(w http.ResponseWriter, r *http.Request) {
s.render(w, r, "accounts", page{Title: "Social accounts", Nav: "settings/accounts", Data: map[string]any{
"Networks": s.networks(),
}})
}
// networks are the cards on the Social accounts tab, as things stand.
func (s *Server) networks() []network {
names := []string{secrets.XAccessToken, secrets.LinkedInAccessToken, secrets.RedditAccessToken}
for _, f := range accountFields {
names = append(names, f.Name)
}
set := s.secretState(names...)
conns := s.connections()
connect := func(provider, token, setup, note string, ready bool, account func(string) string) *connectInfo {
c := conns[provider]
return &connectInfo{Provider: provider, Redirect: s.callbackURL(provider),
Setup: setup, Note: note, Ready: ready, Signed: set[token], Account: account(c.Account), At: c.At}
}
at := func(prefix string) func(string) string {
return func(a string) string {
if a == "" {
return ""
}
return prefix + a
}
}
var nets []network
for _, name := range []string{"X", "LinkedIn", "Reddit", "YouTube"} {
n := network{Name: name, Set: set}
for _, f := range accountFields {
if f.Group == name {
n.Fields = append(n.Fields, f)
}
}
switch name {
case "X":
n.Connect = connect("x", secrets.XAccessToken, "In the X developer portal, add this callback URL to your app:", "",
set[secrets.XClientID], at("@"))
case "LinkedIn":
n.Connect = connect("linkedin", secrets.LinkedInAccessToken, "In your LinkedIn app's Auth settings, add this redirect URL:", "",
set[secrets.LinkedInClientID] && set[secrets.LinkedInClientSecret], func(string) string { return "" })
n.Connect.Expiry = s.linkedInExpiry()
case "Reddit":
n.Connect = connect("reddit", secrets.RedditAccessToken, "At reddit.com/prefs/apps, create a web app with this redirect URI:",
"Reddit's API terms need approval for commercial use: Supermarket is meant for a few hand-approved posts, not volume.",
set[secrets.RedditClientID] && set[secrets.RedditClientSecret], at("u/"))
}
nets = append(nets, n)
}
return nets
}
func (s *Server) accountsSave(w http.ResponseWriter, r *http.Request) {
if err := r.ParseForm(); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if err := s.saveSecrets(r, accountFields); err != nil {
s.serverError(w, err)
return
}
// From the page (htmx): send back just that network's card, so the page
// doesn't reload and lose its place. Without JavaScript: reload.
if r.Header.Get("HX-Request") == "true" {
for _, n := range s.networks() {
if n.Name == r.PostForm.Get("network") {
n.Saved = true
s.fragment(w, "accounts", "network", n)
return
}
}
}
redirect(w, r, "/settings/accounts", "saved")
}
// --- OAuth ---
// callbackURL is where a network sends the browser back after sign-in, as
// registered in the network's developer settings. X refuses "localhost" in
// callback URLs and asks for 127.0.0.1 instead, which reaches the same app.
func (s *Server) callbackURL(provider string) string {
base := s.PublicURL
if provider == "x" {
if u, err := url.Parse(base); err == nil && strings.EqualFold(u.Hostname(), "localhost") {
port := u.Port()
u.Host = "127.0.0.1"
if port != "" {
u.Host += ":" + port
}
base = u.String()
}
}
return strings.TrimSuffix(base, "/") + "/auth/" + provider + "/callback"
}
const oauthTTL = 15 * time.Minute
func (s *Server) oauthStart(w http.ResponseWriter, r *http.Request) {
provider := r.PathValue("provider")
var (
authURL string
p *oauth.Pending
err error
)
switch provider {
case "x":
id := s.Secrets.Get(secrets.XClientID)
if id == "" {
http.Error(w, "Save X's OAuth client ID first.", http.StatusBadRequest)
return
}
authURL, p, err = oauth.XStart(id, s.callbackURL("x"))
case "linkedin":
id := s.Secrets.Get(secrets.LinkedInClientID)
if id == "" || !s.Secrets.Has(secrets.LinkedInClientSecret) {
http.Error(w, "Save LinkedIn's client ID and secret first.", http.StatusBadRequest)
return
}
authURL, p, err = oauth.LinkedInStart(id, s.callbackURL("linkedin"))
case "reddit":
id := s.Secrets.Get(secrets.RedditClientID)
if id == "" || !s.Secrets.Has(secrets.RedditClientSecret) {
http.Error(w, "Save Reddit's client ID and secret first.", http.StatusBadRequest)
return
}
authURL, p, err = oauth.RedditStart(id, s.callbackURL("reddit"))
default:
http.NotFound(w, r)
return
}
if err != nil {
s.serverError(w, err)
return
}
s.mu.Lock()
for state, old := range s.pending {
if time.Since(old.Started) > oauthTTL {
delete(s.pending, state)
}
}
s.pending[p.State] = p
s.mu.Unlock()
s.Log.Info("oauth: sign-in started", "provider", provider, "redirect_uri", p.RedirectURI)
http.Redirect(w, r, authURL, http.StatusSeeOther)
}
func (s *Server) oauthCallback(w http.ResponseWriter, r *http.Request) {
provider := r.PathValue("provider")
q := r.URL.Query()
s.mu.Lock()
p := s.pending[q.Get("state")]
delete(s.pending, q.Get("state")) // a state is good for one callback
s.mu.Unlock()
if p == nil || p.Provider != provider || time.Since(p.Started) > oauthTTL {
s.Log.Warn("oauth: callback with an unknown or expired state", "provider", provider)
redirect(w, r, "/settings/accounts", "oauth-expired")
return
}
fail := func(msg string) {
s.Log.Warn("oauth: sign-in failed", "provider", provider, "reason", msg)
s.render(w, r, "message", page{Title: "Sign-in failed", Nav: "settings/accounts", Error: msg,
Data: map[string]string{"Back": "/settings/accounts"}})
}
if e := q.Get("error"); e != "" {
// Some providers (LinkedIn) send the description HTML-escaped;
// unescape it so the page doesn't show &quot;.
fail("The provider said: " + e + " " + html.UnescapeString(q.Get("error_description")))
return
}
code := q.Get("code")
if code == "" {
fail("The provider sent no authorization code.")
return
}
ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second)
defer cancel()
switch provider {
case "x":
res, err := oauth.XExchange(ctx, s.Secrets.Get(secrets.XClientID), s.Secrets.Get(secrets.XClientSecret), code, p)
if err != nil {
fail(err.Error())
return
}
account := ""
if name, err := twitter.New("", res.AccessToken, 0).VerifyCredentials(ctx); err == nil {
account = name
} else {
s.Log.Warn("x: couldn't verify the new token", "err", err)
}
if err := s.Secrets.Set(map[string]string{secrets.XAccessToken: res.AccessToken, secrets.XRefreshToken: res.RefreshToken}); err != nil {
fail("Signed in, but couldn't save the token: " + err.Error())
return
}
if err := s.saveConnection("x", Connection{Account: account, At: time.Now()}); err != nil {
s.Log.Error("saving connection", "err", err)
}
redirect(w, r, "/settings/accounts", "x-connected")
case "linkedin":
res, err := oauth.LinkedInExchange(ctx, s.Secrets.Get(secrets.LinkedInClientID), s.Secrets.Get(secrets.LinkedInClientSecret), code, p)
if err != nil {
fail(err.Error())
return
}
urn, err := linkedinapi.GetAuthorURN(ctx, res.AccessToken)
if err != nil {
fail("Signed in, but couldn't find your LinkedIn member ID: " + err.Error())
return
}
if err := s.Secrets.Set(map[string]string{secrets.LinkedInAccessToken: res.AccessToken, secrets.LinkedInAuthorURN: urn}); err != nil {
fail("Signed in, but couldn't save the token: " + err.Error())
return
}
life := res.ExpiresIn
if life <= 0 {
life = linkedInTokenLife
}
now := time.Now()
if err := s.saveConnection("linkedin", Connection{Account: urn, At: now, Expires: now.Add(life)}); err != nil {
s.Log.Error("saving connection", "err", err)
}
redirect(w, r, "/settings/accounts", "li-connected")
case "reddit":
res, err := oauth.RedditExchange(ctx, s.Secrets.Get(secrets.RedditClientID), s.Secrets.Get(secrets.RedditClientSecret),
s.redditUserAgent(), code, p)
if err != nil {
fail(err.Error())
return
}
name, err := reddit.New(res.AccessToken, s.redditUserAgent(), nil).Me(ctx)
if err != nil {
fail("Signed in, but couldn't read the Reddit account's name: " + err.Error())
return
}
if err := s.Secrets.Set(map[string]string{secrets.RedditAccessToken: res.AccessToken,
secrets.RedditRefreshToken: res.RefreshToken, secrets.RedditUsername: name}); err != nil {
fail("Signed in, but couldn't save the token: " + err.Error())
return
}
s.forgetRedditHistory()
if err := s.saveConnection("reddit", Connection{Account: name, At: time.Now()}); err != nil {
s.Log.Error("saving connection", "err", err)
}
redirect(w, r, "/settings/accounts", "reddit-connected")
default:
http.NotFound(w, r)
}
}