oficina / memoria Public

Clone
git clone https://amadan.net/oficina/memoria

Plain git — no account needed to clone.

Download

Download this file

1package memoria
2
3import (
4 "encoding/json"
5 "errors"
6 "github.com/google/uuid"
7 "io"
8 "net/http"
9 "strings"
10
11 nativeauth "amadan.net/rastrillo/native/server"
12 "amadan.net/rastrillo/rastrillo/sessions"
13
14 // The one import left on rastrillo's pre-move path, on purpose:
15 // rastrillo/native's server (2a5d07b, and its main) still takes a
16 // github.com/carlosframework/rastrillo *sessions.Sessions. Both
17 // sessions packages read and write the same sessions table, so a
18 // session native sign-in mints is an ordinary session to the app
19 // (native_exchange_test.go). Move this to
20 // amadan.net/rastrillo/rastrillo/sessions when native/server moves.
21 presessions "github.com/carlosframework/rastrillo/sessions"
22)
23
24func (a *app) wireNative(origin string) error {
25 cfg := sessions.Config{DB: a.db.Writer(), Origin: origin, SigninPath: "/signin", Logger: a.logger}
26 s, e := sessions.New(cfg)
27 if e != nil {
28 return e
29 }
30 a.sess = s
31 // The same table, cookie and origin, through the type native/server
32 // takes. The app itself reads sessions through a.sess only.
33 pre, e := presessions.New(presessions.Config{DB: cfg.DB, Origin: cfg.Origin, SigninPath: cfg.SigninPath, Logger: cfg.Logger})
34 if e != nil {
35 return e
36 }
37 a.native = nativeauth.New(pre, origin, "Memoria", a.requireSession)
38 return nil
39}
40func nativeJSON(w http.ResponseWriter, v any) {
41 w.Header().Set("Content-Type", "application/json")
42 w.Header().Set("Cache-Control", "no-store")
43 _ = json.NewEncoder(w).Encode(v)
44}
45func (a *app) nativeSession(w http.ResponseWriter, r *http.Request) {
46 nativeJSON(w, map[string]string{"app": "memoria"})
47}
48func (a *app) nativeSearch(w http.ResponseWriter, r *http.Request) {
49 asker, ok := a.asker(r)
50 if !ok {
51 http.Error(w, "Sign in again", 401)
52 return
53 }
54 r.Body = http.MaxBytesReader(w, r.Body, 8192)
55 var in struct {
56 Query string `json:"query"`
57 }
58 d := json.NewDecoder(r.Body)
59 d.DisallowUnknownFields()
60 if d.Decode(&in) != nil || d.Decode(new(any)) != io.EOF || len(in.Query) > 2048 {
61 http.Error(w, "Use a shorter query", 400)
62 return
63 }
64 in.Query = strings.TrimSpace(in.Query)
65 if in.Query == "" {
66 http.Error(w, "Enter something to search for", 400)
67 return
68 }
69 // WithoutFacts: this response has no field for the fact box, so building
70 // one would call the model (§8.9) and send passages for an answer the
71 // native client never receives.
72 found, err := a.store.SearchWithoutFacts(r.Context(), asker, in.Query, 25)
73 if err != nil {
74 http.Error(w, "Search is unavailable. Try again.", 503)
75 return
76 }
77 // A JSON list has nowhere to say it is partial, so in team mode a
78 // standing that lapsed while it was built is the retryable 503 (Paul,
79 // 2026-10-28), never a short list read as the whole answer.
80 if a.teamPartial(r) {
81 a.teamUnavailable(w, r)
82 return
83 }
84 // Search resolves every hit and asks the owning app for this person's current
85 // permission. Never use Summaries or Body to bypass that decision for native UI.
86 type result struct {
87 ID int64 `json:"id"`
88 DocumentID int64 `json:"document_id"`
89 Ordinal int `json:"ordinal"`
90 Title string `json:"title"`
91 Heading string `json:"heading"`
92 Text string `json:"text"`
93 Source string `json:"source"`
94 Path string `json:"path"`
95 }
96 out := make([]result, 0, len(found.Results))
97 for _, v := range found.Results {
98 out = append(out, result{v.ChunkID, v.DocumentID, v.Ordinal, v.Title, v.Heading, strings.NewReplacer("<mark>", "", "</mark>", "").Replace(v.Snippet), v.Source, v.Path})
99 }
100 notices := found.Notices
101 if notices == nil {
102 notices = []string{}
103 }
104 nativeJSON(w, map[string]any{"results": out, "notices": notices})
105}
106
107// nativeNote creates a distinct team note, even when its title matches another.
108//
109// client_id is the note's idempotency key, minted once per draft by the
110// client. Without it the server minted a fresh key per REQUEST, so a save
111// that committed but whose response was lost (timeout, a phone asleep)
112// showed as an error, and pressing Save again made a second copy (B10).
113// With it, a replay of the same draft lands on the same (source, key)
114// and Store.Ingest's same-key-same-body path answers with the first id
115// and changes nothing. A replay whose draft was edited in between revises
116// that note rather than adding another beside it, which is the point: it
117// is still one draft.
118//
119// It must be a canonical, non-nil UUID, and it is canonicalised before use, so "A1…" and
120// "a1…" are one key and a free-form string cannot choose its own key.
121// Absent, the server mints one as before, so older clients keep working
122// — and keep the old duplicate-on-retry behaviour.
123func (a *app) nativeNote(w http.ResponseWriter, r *http.Request) {
124 r.Body = http.MaxBytesReader(w, r.Body, 3<<20)
125 var in struct {
126 Title string `json:"title"`
127 Body string `json:"body"`
128 ClientID string `json:"client_id"`
129 }
130 d := json.NewDecoder(r.Body)
131 d.DisallowUnknownFields()
132 if d.Decode(&in) != nil || d.Decode(new(any)) != io.EOF || len(in.Title) > 512 || len(in.Body) > 2<<20 || strings.TrimSpace(in.Title) == "" || strings.TrimSpace(in.Body) == "" {
133 http.Error(w, "Use a title and a note no larger than 2 MiB", 400)
134 return
135 }
136 key := uuid.NewString()
137 if in.ClientID != "" {
138 parsed, err := uuid.Parse(in.ClientID)
139 // uuid.Nil parses and is 36 characters, but it is the value a
140 // struct default or a failed decode produces: every such client
141 // would converge on one note that revises forever.
142 if err != nil || len(in.ClientID) != 36 || parsed == uuid.Nil {
143 http.Error(w, "The note's client id is not a UUID", 400)
144 return
145 }
146 key = parsed.String()
147 }
148 id, err := a.store.Ingest(r.Context(), IngestSpec{Source: "paste", Key: "native-" + key, Title: strings.TrimSpace(in.Title), Body: in.Body})
149 if a.guardRefused(w, r, err) {
150 return
151 }
152 if err != nil && !errors.Is(err, ErrIndexLag) {
153 http.Error(w, "The note could not be confirmed", 500)
154 return
155 }
156 nativeJSON(w, map[string]any{"id": id, "indexed": err == nil})
157}
158
159// nativeApprovalStyle is the CSP source for the one <style> element on
160// rastrillo/native's approval page (/native/authorize, server auth.go's
161// approval template, at the pin in go.mod). That page is the native
162// kit's, not ours: its whole stylesheet is inline, and rastrillo
163// fb806a2's default style-src refuses it, which left the card, spacing
164// and button unstyled (Astra on #27, P2). Its stylesheet holds no
165// template action, so it is one fixed string and one hash.
166//
167// Allowed by hash, on that route only, rather than 'unsafe-inline'
168// anywhere: the hash admits exactly that stylesheet, and every other page
169// keeps rastrillo's strict policy. TestNativeApprovalStyleIsTheHashedOne
170// re-hashes the served <style> on every run, so a native bump that
171// changes the CSS fails in CI instead of shipping an unstyled page. The
172// lasting fix is upstream: an external stylesheet in native/server.
173const nativeApprovalStyle = "'sha256-zliDvO3z4TJ7/8VeNbSfTcTmu729BtmpmXEY89IdRBI='"
174
175// nativeApprovalCSP adds nativeApprovalStyle to the style-src of the
176// policy already on the response. rastrillo's security headers run first
177// and set it, so this edits the policy production really sends, and a
178// tightening of rastrillo's default reaches this route too. A policy that
179// already allows inline styles is left alone: adding a hash to it would
180// void its 'unsafe-inline' (Home mode's connect.FormPolicy). No policy at
181// all (the bare router in tests) is left alone too.
182func nativeApprovalCSP(next http.HandlerFunc) http.HandlerFunc {
183 return func(w http.ResponseWriter, r *http.Request) {
184 h := w.Header()
185 if p := h.Get("Content-Security-Policy"); p != "" {
186 h.Set("Content-Security-Policy", withStyleSource(p, nativeApprovalStyle))
187 }
188 next(w, r)
189 }
190}
191
192// withStyleSource appends source to policy's style-src, or adds a
193// style-src of 'self' and source when it has none. A style-src that
194// allows 'unsafe-inline' is returned unchanged.
195func withStyleSource(policy, source string) string {
196 parts := strings.Split(policy, ";")
197 for i, d := range parts {
198 f := strings.Fields(d)
199 if len(f) == 0 || f[0] != "style-src" {
200 continue
201 }
202 for _, s := range f[1:] {
203 if s == "'unsafe-inline'" {
204 return policy
205 }
206 }
207 parts[i] = strings.TrimRight(d, " ") + " " + source
208 return strings.Join(parts, ";")
209 }
210 return policy + "; style-src 'self' " + source
211}
212