A security review of the whole repo. The queries were already scoped, the
OIDC flow already did state and nonce and PKCE, the session tokens were
already stored as hashes. What it found was mostly the seam between the
code and the deployment — and one place where the deployment quietly
undid the code.
The one that matters: with any AUTHENTIK_* variable missing, Petal fell
back to resolving every request to the single `local` user. That is right
on a laptop and a catastrophe on a public host, and Phase 16 removed the
Traefik basic-auth gate that used to stand behind the mistake. A typo in
the client secret would have served her journals to the open internet and
said so only in a log line nobody reads. It now refuses to start, guarded
by default for any BASE_URL that isn't loopback.
Then the one that would have been fixed and wasn't: stored images now
serve under `default-src 'none'; sandbox`, so an SVG pasted into a
document can't run as a page on Petal's own origin. Traefik's
customresponseheaders *overwrites*, so the CSP declared in the compose
labels would have silently replaced that per-route policy in production.
The whole header block moved into the binary, where a route can tighten
its own and a test can prove it; only HSTS stays at the edge, where TLS
actually terminates.
The rest, smaller:
- PETAL_ALLOWED_SUBS empty means everyone authentik authenticates, and
authentik here fronts half a dozen applications. Still legal, now
said out loud every boot, and set in both env examples.
- LLM failures relayed err.Error() to the browser, which carries the
address of the inference box on the far side of the VPN. Logged
instead; the client only ever rendered "the helper is resting".
- Exports scheme-check their links. Escaping makes a URL safe to sit
in an attribute and says nothing about following it, and an export
is the one artifact here meant to leave. Writing the test found the
markdown image src, which I'd missed reading it.
- The draft rescue is namespaced per account and cleared on sign-out.
Everything else in localStorage is a preference; this is her unsaved
writing, sitting in a profile two people share.
- /auth/logout is POST-only. With SameSite=Lax a GET route lets any
page on the internet sign her out mid-draft.
- Image uploads get a per-account allowance and the TTS cache a size
cap. Both share the encrypted volume the database is on, and a full
disk is SQLite failing to write, not a feature degrading.
- The session cookie takes the __Host- prefix over https, so nothing
else under parodia.dev can plant one. Old cookies still resolve;
nobody is signed out to get there.
- npm audit: linkify-it and postcss.
Verified: go build, go vet, the full Go suite, tsc, 195 frontend tests,
npm audit clean. The startup guard and both CSPs checked against a
running server rather than only asserted.
Claude-Session: https://claude.ai/code/session_016y6gyuHkQXPiEuW8RGQyua
131 lines
4.4 KiB
Go
131 lines
4.4 KiB
Go
package suggestions
|
|
|
|
import (
|
|
"database/sql"
|
|
"encoding/json"
|
|
"errors"
|
|
"net/http"
|
|
"strings"
|
|
|
|
"github.com/go-chi/chi/v5"
|
|
|
|
"gitea.parodia.dev/drwily/petal/internal/auth"
|
|
"gitea.parodia.dev/drwily/petal/internal/httputil"
|
|
"gitea.parodia.dev/drwily/petal/internal/llm"
|
|
)
|
|
|
|
// chatRequest is the body the AskPetal panel posts: the full conversation so
|
|
// far. The suggestion context is loaded server-side and never trusted from the
|
|
// client (spec Note #10).
|
|
type chatRequest struct {
|
|
Messages []llm.Message `json:"messages"`
|
|
}
|
|
|
|
// chat streams an Ask Petal conversational reply over SSE. It loads the
|
|
// suggestion and its parent document's surrounding paragraph, injects them as
|
|
// the tutor system prompt, then relays the model's tokens to the browser as
|
|
// `data:` events. History persistence lives entirely in the client.
|
|
func (h *Handler) chat(w http.ResponseWriter, r *http.Request) {
|
|
sugID := chi.URLParam(r, "id")
|
|
|
|
var body chatRequest
|
|
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
|
httputil.ErrorJSON(w, http.StatusBadRequest, "invalid request body")
|
|
return
|
|
}
|
|
|
|
// One query for the suggestion fields and the parent document's plain text,
|
|
// scoped to the local user so a stray id can't read another user's doc.
|
|
var (
|
|
original, replacement, explanation, typ string
|
|
fromPos int
|
|
contentText string
|
|
pairLang string
|
|
)
|
|
err := h.DB.QueryRow(
|
|
`SELECT s.original, s.replacement, s.explanation, s.type, s.from_pos, d.content_text,
|
|
COALESCE(u.pair_lang, '')
|
|
FROM suggestions s
|
|
JOIN documents d ON d.id = s.doc_id
|
|
JOIN users u ON u.id = d.user_id
|
|
WHERE s.id = ? AND d.user_id = ?`,
|
|
sugID, auth.UserID(r.Context()),
|
|
).Scan(&original, &replacement, &explanation, &typ, &fromPos, &contentText, &pairLang)
|
|
if errors.Is(err, sql.ErrNoRows) {
|
|
httputil.ErrorJSON(w, http.StatusNotFound, "suggestion not found")
|
|
return
|
|
}
|
|
if err != nil {
|
|
httputil.ServerError(w, err)
|
|
return
|
|
}
|
|
|
|
paragraph := surroundingParagraph(contentText, fromPos)
|
|
systemPrompt := llm.AskPetalSystemPrompt(original, replacement, typ, explanation, paragraph, llm.LangFor(pairLang))
|
|
|
|
// SSE requires an unbuffered, flushable writer. chi's middleware writers pass
|
|
// Flush through; bail with a plain error if somehow they don't.
|
|
flusher, ok := w.(http.Flusher)
|
|
if !ok {
|
|
httputil.ServerError(w, errors.New("streaming unsupported"))
|
|
return
|
|
}
|
|
|
|
ch, err := llm.StreamAskPetal(r.Context(), h.Client, systemPrompt, body.Messages)
|
|
if err != nil {
|
|
// The stream never opened (e.g. LLM unreachable) — a normal JSON error is
|
|
// still appropriate since we haven't written SSE headers yet.
|
|
httputil.UpstreamError(w, "chat", err)
|
|
return
|
|
}
|
|
|
|
w.Header().Set("Content-Type", "text/event-stream")
|
|
w.Header().Set("Cache-Control", "no-cache")
|
|
w.Header().Set("Connection", "keep-alive")
|
|
w.Header().Set("X-Accel-Buffering", "no") // disable proxy buffering (e.g. nginx)
|
|
w.WriteHeader(http.StatusOK)
|
|
flusher.Flush()
|
|
|
|
for chunk := range ch {
|
|
writeSSE(w, "token", map[string]string{"text": chunk})
|
|
flusher.Flush()
|
|
}
|
|
// Signal a clean end so the client can stop reading without waiting on EOF.
|
|
writeSSE(w, "done", map[string]bool{"done": true})
|
|
flusher.Flush()
|
|
}
|
|
|
|
// writeSSE emits one named SSE event with a JSON data payload. JSON-encoding the
|
|
// data keeps token text (which may contain newlines) from breaking SSE framing.
|
|
func writeSSE(w http.ResponseWriter, event string, data any) {
|
|
payload, err := json.Marshal(data)
|
|
if err != nil {
|
|
return
|
|
}
|
|
_, _ = w.Write([]byte("event: " + event + "\ndata: "))
|
|
_, _ = w.Write(payload)
|
|
_, _ = w.Write([]byte("\n\n"))
|
|
}
|
|
|
|
// surroundingParagraph returns the paragraph of contentText containing the
|
|
// plain-text offset from. Tiptap flattens blocks with blank-line separators, so
|
|
// paragraphs are bounded by "\n\n". When the offset is unknown (original wasn't
|
|
// located, from == -1) it falls back to the latency-capped document so the tutor
|
|
// still has context to work with.
|
|
func surroundingParagraph(contentText string, from int) string {
|
|
if from < 0 || from > len(contentText) {
|
|
return strings.TrimSpace(llm.TruncateDoc(contentText))
|
|
}
|
|
start := strings.LastIndex(contentText[:from], "\n\n")
|
|
if start < 0 {
|
|
start = 0
|
|
} else {
|
|
start += 2
|
|
}
|
|
end := len(contentText)
|
|
if rel := strings.Index(contentText[from:], "\n\n"); rel >= 0 {
|
|
end = from + rel
|
|
}
|
|
return strings.TrimSpace(contentText[start:end])
|
|
}
|