oficina / base Public

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

Plain git — no account needed to clone.

Download

Download this file

1// Package scratchpad is Scratchpad, the small app Base installs to prove
2// install, identity and uninstall: one shared note and a line saying who
3// you are signed in as.
4//
5// Access rule (CARLOS app spec 1.7: each app decides what a person may do):
6// anyone the configured Base vouches for may read and write the note. A
7// valid assertion from BASE_APP_ISSUER is the whole test; there are no
8// roles, and every member of that Base sees and edits the same note.
9package scratchpad
10
11import (
12 "context"
13 "database/sql"
14 "embed"
15 "errors"
16 "io/fs"
17 "log/slog"
18 "net/http"
19 "strconv"
20 "time"
21
22 "github.com/go-chi/chi/v5"
23
24 "amadan.net/rastrillo/rastrillo/csrf"
25 "amadan.net/rastrillo/rastrillo/db"
26 "amadan.net/rastrillo/rastrillo/migrate"
27 "amadan.net/rastrillo/rastrillo/sessions"
28
29 "amadan.net/oficina/base/internal/consumer"
30 "amadan.net/oficina/base/internal/look"
31)
32
33//go:embed migrations/*.sql
34var migrationFS embed.FS
35
36//go:embed templates/*.html
37var templateFS embed.FS
38
39// Schema is Scratchpad's own table.
40var Schema = migrate.MustFromFS(migrationFS, "scratchpad")
41
42// BootSchema is everything Scratchpad's database needs.
43var BootSchema = migrate.Merge(sessions.Schema, consumer.Schema, Schema)
44
45const (
46 // maxNote bounds the note, in bytes.
47 maxNote = 64 * 1024
48 // sessionTTL is how long a sign-in lasts here. It outlives Base being
49 // down for a while, and a person Base removes is gone within a day.
50 sessionTTL = 12 * time.Hour
51)
52
53type app struct {
54 home string // Base's Home, where the wordmark links
55 db *sql.DB
56 pages *look.Renderer
57 logger *slog.Logger
58}
59
60// App builds Scratchpad's router. d must have BootSchema applied.
61func App(d *db.DB, cfg consumer.Config, logger *slog.Logger) (http.Handler, error) {
62 if d == nil || cfg.Verifier == nil {
63 return nil, errors.New("scratchpad: a database and a Config from consumer.Load are required")
64 }
65 if logger == nil {
66 logger = slog.Default()
67 }
68 if cfg.Logger == nil {
69 cfg.Logger = logger
70 }
71 sess, err := sessions.New(sessions.Config{DB: d.Writer(), Origin: cfg.Origin, TTL: sessionTTL,
72 SigninPath: consumer.StartPath, Logger: logger})
73 if err != nil {
74 return nil, err
75 }
76 sub, err := fs.Sub(templateFS, "templates")
77 if err != nil {
78 return nil, err
79 }
80 pages, err := look.NewRenderer(sub, nil)
81 if err != nil {
82 return nil, err
83 }
84 a := &app{home: cfg.Issuer + "/", db: d.Writer(), pages: pages, logger: logger}
85
86 r := chi.NewRouter()
87 // Base's form posts the assertion cross-origin; that one handler checks
88 // for Base's exact Origin itself.
89 r.Use(csrf.Protect(cfg.Origin, csrf.Exempt(consumer.AssertionPath)))
90 consumer.Mount(r, d.Writer(), cfg, sess)
91 r.Get("/static/fonts/*", look.FontHandler().ServeHTTP)
92 r.Get("/static/*", look.Assets.Handler().ServeHTTP)
93 r.Group(func(r chi.Router) {
94 r.Use(consumer.Require)
95 r.Get("/", a.notes)
96 r.Post("/", a.save)
97 })
98 return r, nil
99}
100
101type notesPage struct {
102 Home, Name, Base, Note string
103 Revision int64 // the revision the form edits
104 // Conflict is set when a save was refused because someone saved first:
105 // Note is then the refused text and Saved the note as it stands.
106 Conflict bool
107 Saved string
108}
109
110// current reads the note and its revision; no note yet is "" at revision 0.
111func current(ctx context.Context, q interface {
112 QueryRowContext(context.Context, string, ...any) *sql.Row
113}) (string, int64, error) {
114 var note string
115 var rev int64
116 err := q.QueryRowContext(ctx, `SELECT body, revision FROM notes WHERE id = 1`).Scan(&note, &rev)
117 if errors.Is(err, sql.ErrNoRows) {
118 return "", 0, nil
119 }
120 return note, rev, err
121}
122
123func (a *app) notes(w http.ResponseWriter, r *http.Request) {
124 _, name, base, _ := consumer.Person(r)
125 note, rev, err := current(r.Context(), a.db)
126 if err != nil {
127 a.logger.Error("scratchpad: reading the note", "err", err)
128 http.Error(w, "unavailable", http.StatusServiceUnavailable)
129 return
130 }
131 a.page(w, http.StatusOK, notesPage{Name: name, Base: base, Note: note, Revision: rev})
132}
133
134func (a *app) page(w http.ResponseWriter, status int, p notesPage) {
135 p.Home = a.home
136 if err := a.pages.PageStatus(w, status, "notes", p); err != nil {
137 a.logger.Error("scratchpad: render", "err", err)
138 http.Error(w, "something went wrong", http.StatusInternalServerError)
139 }
140}
141
142// save replaces the shared note, then sends the browser back to it. The form
143// says which revision it edited; if someone has saved since, nothing is
144// written and the page comes back with the person's text still in it.
145func (a *app) save(w http.ResponseWriter, r *http.Request) {
146 sub, name, base, _ := consumer.Person(r)
147 r.Body = http.MaxBytesReader(w, r.Body, 4*maxNote) // form encoding can triple a byte
148 if err := r.ParseForm(); err != nil {
149 http.Error(w, "The note is too long.", http.StatusRequestEntityTooLarge)
150 return
151 }
152 note := r.PostForm.Get("note")
153 if len(note) > maxNote {
154 http.Error(w, "The note is too long.", http.StatusRequestEntityTooLarge)
155 return
156 }
157 // A missing or malformed revision edited nothing in particular: it is
158 // treated as stale, never as permission to overwrite.
159 edited, err := strconv.ParseInt(r.PostForm.Get("revision"), 10, 64)
160 if err != nil {
161 edited = -1
162 }
163 saved, rev, stale, err := a.write(r.Context(), note, sub, edited)
164 if err != nil {
165 a.logger.Error("scratchpad: saving the note", "err", err)
166 http.Error(w, "unavailable", http.StatusServiceUnavailable)
167 return
168 }
169 if stale {
170 a.page(w, http.StatusConflict, notesPage{Name: name, Base: base, Note: note, Revision: rev, Conflict: true, Saved: saved})
171 return
172 }
173 http.Redirect(w, r, "/", http.StatusSeeOther)
174}
175
176// write saves note if the stored revision is still edited. Otherwise it
177// writes nothing and reports stale with the note and revision as they are.
178func (a *app) write(ctx context.Context, note, by string, edited int64) (saved string, rev int64, stale bool, err error) {
179 tx, err := a.db.BeginTx(ctx, nil)
180 if err != nil {
181 return "", 0, false, err
182 }
183 defer tx.Rollback()
184 saved, rev, err = current(ctx, tx)
185 if err != nil {
186 return "", 0, false, err
187 }
188 if rev != edited {
189 return saved, rev, true, nil
190 }
191 if _, err := tx.ExecContext(ctx, `INSERT INTO notes (id, body, updated_by, updated_at, revision) VALUES (1, ?, ?, ?, ?)
192 ON CONFLICT (id) DO UPDATE SET body = excluded.body, updated_by = excluded.updated_by,
193 updated_at = excluded.updated_at, revision = excluded.revision`,
194 note, by, time.Now().Unix(), rev+1); err != nil {
195 return "", 0, false, err
196 }
197 return note, rev + 1, false, tx.Commit()
198}
199