Files
davidandClaude Opus 5.5 cd2dc6145b Sign-ins finish only in the browser that started them
A Core sign-in, and a posting account's or Search Console's OAuth sign-in,
now sets a short-lived cookie whose hash the flow keeps on the server. The
callback refuses one without it (constant-time compare), clears the cookie
either way, and the flow is used up regardless. This stops login CSRF: a
callback URL brought to another browser signs nobody in.

The cookie uses the __Host- prefix over https, so its Path is "/".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-04 08:07:21 -07:00

636 lines
21 KiB
Go

package web
import (
"context"
"encoding/json"
"html"
"net/http"
"net/url"
"strings"
"time"
"supermarket/internal/ai"
linkedinapi "supermarket/internal/api/linkedin"
"supermarket/internal/api/twitter"
"supermarket/internal/oauth"
"supermarket/internal/posting"
"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.noteCheck("ai", result)
s.fragment(w, r, "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, r, "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"
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 above), 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},
{"LinkedIn page", secrets.LinkedInPageClientID, "Client ID",
"A second LinkedIn app, linked to the company page, with the Community Management API approved by LinkedIn (it must be the app's only product). Its Auth tab has the ID.", linkedInApps},
{"LinkedIn page", secrets.LinkedInPageClientSecret, "Client secret",
"On the same Auth tab, under the client ID.", linkedInApps},
{"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.setSecrets(r, 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
Page *pageSetup // the company page's choices, for the LinkedIn page
Accounts []*posting.Account
}
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 {
var names []string
for _, f := range accountFields {
names = append(names, f.Name)
}
set := s.secretState(names...)
accts := s.postingAccounts()
netOf := map[string]string{"x": posting.X, "linkedin": posting.LinkedIn, liPageProvider: posting.LinkedInPage}
connect := func(provider, token, setup, note string, ready bool, account func(string) string) *connectInfo {
c := &connectInfo{Provider: provider, Redirect: s.callbackURL(provider), Setup: setup, Note: note, Ready: ready}
for _, a := range accts {
if a.Network == netOf[provider] {
c.Accounts = append(c.Accounts, a)
if a.Owner == 0 && !c.Signed {
c.Signed, c.Account, c.At = true, a.Name, a.Created
}
}
}
return c
}
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", liPageNetwork, "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 liPageNetwork:
n.Connect = connect(liPageProvider, secrets.LinkedInPageAccessToken, "In the page app's Auth settings, add this redirect URL:",
"Posts can then go out as the company page instead of you; each LinkedIn draft says which.",
set[secrets.LinkedInPageClientID] && set[secrets.LinkedInPageClientSecret], func(a string) string { return a })
n.Connect.Expiry = s.linkedInPageExpiry()
n.Connect.Page = s.pageSetup()
}
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, r, "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")
// Admins connect the company's accounts (and Search Console); anyone
// with Content may connect their own posting account.
v := viewerOf(r)
forUser := int64(0)
if r.URL.Query().Get("for") == "me" && v.User != nil {
if provider == "google" || provider == liPageProvider || !v.Member.Can("content", true) {
s.forbidden(w, r)
return
}
forUser = v.User.ID
} else if !v.Member.Admin() {
s.forbidden(w, r)
return
}
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 liPageProvider:
id := s.Secrets.Get(secrets.LinkedInPageClientID)
if id == "" || !s.Secrets.Has(secrets.LinkedInPageClientSecret) {
http.Error(w, "Save the LinkedIn page app's client ID and secret first.", http.StatusBadRequest)
return
}
authURL, p, err = oauth.LinkedInStartScopes(liPageProvider, id, s.callbackURL(liPageProvider), s.liPageScopes())
case "google":
id := s.Secrets.Get(secrets.GoogleClientID)
if id == "" || !s.Secrets.Has(secrets.GoogleClientSecret) {
http.Error(w, "Save Google's client ID and secret first.", http.StatusBadRequest)
return
}
authURL, p, err = oauth.GoogleStart(id, s.callbackURL("google"))
default:
http.NotFound(w, r)
return
}
if err != nil {
s.serverError(w, err)
return
}
p.For, p.Team = forUser, s.team()
if p.Browser, err = s.bindFlow(w, oauthFlowCookie, oauthTTL); err != nil {
s.serverError(w, err)
return
}
// Kept in the database: the callback may reach another copy of the app.
if err := s.DB.PutJSON(oauthFlowKey+p.State, p); err != nil {
s.serverError(w, err)
return
}
s.forgetOldOAuthFlows()
s.Log.Info("oauth: sign-in started", "provider", provider, "redirect_uri", p.RedirectURI)
http.Redirect(w, r, authURL, http.StatusSeeOther)
}
// OAuth sign-ins under way are kept as settings, by state.
const oauthFlowKey = "oauth:flow:"
// takeOAuthFlow reads and removes the sign-in a callback's state names: a
// state is good for one callback, even if two copies of the app get it.
func (s *Server) takeOAuthFlow(state string) *oauth.Pending {
if state == "" {
return nil
}
var p oauth.Pending
if ok, err := s.DB.GetJSON(oauthFlowKey+state, &p); !ok || err != nil {
return nil
}
res, err := s.DB.Exec(`DELETE FROM settings WHERE key = ?`, oauthFlowKey+state)
if err != nil {
return nil
}
if n, _ := res.RowsAffected(); n != 1 {
return nil // the other copy took it
}
return &p
}
// forgetOldOAuthFlows removes sign-ins never finished.
func (s *Server) forgetOldOAuthFlows() {
rows, err := s.DB.Query(`SELECT key, value FROM settings WHERE key LIKE 'oauth:flow:%'`)
if err != nil {
return
}
var old []string
for rows.Next() {
var key, raw string
var p oauth.Pending
if rows.Scan(&key, &raw) == nil && (json.Unmarshal([]byte(raw), &p) != nil || time.Since(p.Started) > oauthTTL) {
old = append(old, key)
}
}
rows.Close()
for _, k := range old {
s.DB.Exec(`DELETE FROM settings WHERE key = ?`, k)
}
}
func (s *Server) oauthCallback(w http.ResponseWriter, r *http.Request) {
provider := r.PathValue("provider")
q := r.URL.Query()
p := s.takeOAuthFlow(q.Get("state"))
back, nav := "/settings/accounts", "settings/accounts"
if provider == "google" {
back, nav = "/settings/search", "settings/search"
}
if p != nil && p.For != 0 {
back, nav = "/settings/account#posting", "settings/account"
}
browser := ""
if p != nil {
browser = p.Browser
}
// Only in the browser that started it (the cookie is cleared either way).
if !s.flowFromThisBrowser(w, r, oauthFlowCookie, browser) {
s.Log.Warn("oauth: callback from another browser", "provider", provider)
redirect(w, r, back, "oauth-expired")
return
}
if p == nil || p.Provider != provider || time.Since(p.Started) > oauthTTL || (p.Team != 0 && p.Team != s.team()) {
s.Log.Warn("oauth: callback with an unknown or expired state", "provider", provider)
redirect(w, r, back, "oauth-expired")
return
}
// The same person who started it: the company's sign-ins need an
// admin, a person's own the person.
v := viewerOf(r)
if (p.For != 0 && (v.User == nil || v.User.ID != p.For)) || (p.For == 0 && !v.Member.Admin()) {
s.forbidden(w, r)
return
}
who := int64(0)
if v.User != nil {
who = v.User.ID
}
// saveAccount keeps a posting account's sign-in.
saveAccount := func(network, name, external, access, refresh string, expires time.Time) error {
a := &posting.Account{Network: network, Name: name, External: external, Owner: p.For, CreatedBy: who, Expires: expires}
if err := posting.Save(s.DB, s.Secrets, a, access, refresh, time.Now()); err != nil {
return err
}
s.recordConnection(r, network, true)
return nil
}
ownMsg := func(msg string) string {
if p.For != 0 {
return "own-account-connected"
}
return msg
}
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: nav, Error: msg,
Data: map[string]string{"Back": back}})
}
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 "google":
res, err := oauth.GoogleExchange(ctx, s.Secrets.Get(secrets.GoogleClientID), s.Secrets.Get(secrets.GoogleClientSecret), code, p)
if err != nil {
fail(err.Error())
return
}
if res.RefreshToken == "" {
fail("Google sent no refresh token, so Supermarket couldn't read Search Console on its own. Remove Supermarket's access in your Google account's security settings, then connect again.")
return
}
email, err := oauth.GoogleEmail(ctx, res.AccessToken)
if err != nil {
s.Log.Warn("google: couldn't read the account's email", "err", err)
}
if err := s.setSecrets(r, map[string]string{secrets.GoogleRefreshToken: res.RefreshToken}); err != nil {
fail("Signed in, but couldn't save the token: " + err.Error())
return
}
s.setGoogleToken(res)
if err := s.saveConnection("google", Connection{Account: email, At: time.Now()}); err != nil {
s.Log.Error("saving connection", "err", err)
}
redirect(w, r, "/settings/search", "google-connected")
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)
}
name := "@" + account
if account == "" {
name = "X account"
}
if err := saveAccount(posting.X, name, account, res.AccessToken, res.RefreshToken, time.Time{}); err != nil {
fail("Signed in, but couldn't save the token: " + err.Error())
return
}
redirect(w, r, back, ownMsg("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
}
life := res.ExpiresIn
if life <= 0 {
life = linkedInTokenLife
}
name := "LinkedIn member"
if v.User != nil {
name = v.User.Name
if name == "" {
name = v.User.Email
}
}
if err := saveAccount(posting.LinkedIn, name, urn, res.AccessToken, "", time.Now().Add(life)); err != nil {
fail("Signed in, but couldn't save the token: " + err.Error())
return
}
redirect(w, r, back, ownMsg("li-connected"))
case liPageProvider:
res, err := oauth.LinkedInExchange(ctx, s.Secrets.Get(secrets.LinkedInPageClientID), s.Secrets.Get(secrets.LinkedInPageClientSecret), code, p)
if err != nil {
fail(err.Error())
return
}
life := res.ExpiresIn
if life <= 0 {
life = linkedInTokenLife
}
_, listErr := s.pageOrgs(ctx, res.AccessToken)
if listErr != nil {
s.Log.Warn("linkedin page: couldn't list the pages", "err", listErr)
}
name, urn := "the company page", ""
if o := s.liPage(); o != nil {
name, urn = o.Name, o.URN
}
// One page sign-in for the company: a new one replaces it.
if old, _ := posting.Company(s.DB, posting.LinkedInPage); old != nil && old.External != urn {
_ = posting.Rename(s.DB, old.ID, name, urn)
}
if err := saveAccount(posting.LinkedInPage, name, urn, res.AccessToken, "", time.Now().Add(life)); err != nil {
fail("Signed in, but couldn't save the token: " + err.Error())
return
}
redirect(w, r, "/settings/accounts", "li-page-connected")
default:
http.NotFound(w, r)
}
}