// Package scratchpad is Scratchpad, the small app Base installs to prove // install, identity and uninstall: one shared note and a line saying who // you are signed in as. // // Access rule (CARLOS app spec 1.7: each app decides what a person may do): // anyone the configured Base vouches for may read and write the note. A // valid assertion from BASE_APP_ISSUER is the whole test; there are no // roles, and every member of that Base sees and edits the same note. package scratchpad import ( "context" "database/sql" "embed" "errors" "io/fs" "log/slog" "net/http" "strconv" "time" "github.com/go-chi/chi/v5" "amadan.net/rastrillo/rastrillo/csrf" "amadan.net/rastrillo/rastrillo/db" "amadan.net/rastrillo/rastrillo/migrate" "amadan.net/rastrillo/rastrillo/sessions" "amadan.net/oficina/base/internal/consumer" "amadan.net/oficina/base/internal/look" ) //go:embed migrations/*.sql var migrationFS embed.FS //go:embed templates/*.html var templateFS embed.FS // Schema is Scratchpad's own table. var Schema = migrate.MustFromFS(migrationFS, "scratchpad") // BootSchema is everything Scratchpad's database needs. var BootSchema = migrate.Merge(sessions.Schema, consumer.Schema, Schema) const ( // maxNote bounds the note, in bytes. maxNote = 64 * 1024 // sessionTTL is how long a sign-in lasts here. It outlives Base being // down for a while, and a person Base removes is gone within a day. sessionTTL = 12 * time.Hour ) type app struct { home string // Base's Home, where the wordmark links db *sql.DB pages *look.Renderer logger *slog.Logger } // App builds Scratchpad's router. d must have BootSchema applied. func App(d *db.DB, cfg consumer.Config, logger *slog.Logger) (http.Handler, error) { if d == nil || cfg.Verifier == nil { return nil, errors.New("scratchpad: a database and a Config from consumer.Load are required") } if logger == nil { logger = slog.Default() } if cfg.Logger == nil { cfg.Logger = logger } sess, err := sessions.New(sessions.Config{DB: d.Writer(), Origin: cfg.Origin, TTL: sessionTTL, SigninPath: consumer.StartPath, Logger: logger}) if err != nil { return nil, err } sub, err := fs.Sub(templateFS, "templates") if err != nil { return nil, err } pages, err := look.NewRenderer(sub, nil) if err != nil { return nil, err } a := &app{home: cfg.Issuer + "/", db: d.Writer(), pages: pages, logger: logger} r := chi.NewRouter() // Base's form posts the assertion cross-origin; that one handler checks // for Base's exact Origin itself. r.Use(csrf.Protect(cfg.Origin, csrf.Exempt(consumer.AssertionPath))) consumer.Mount(r, d.Writer(), cfg, sess) r.Get("/static/fonts/*", look.FontHandler().ServeHTTP) r.Get("/static/*", look.Assets.Handler().ServeHTTP) r.Group(func(r chi.Router) { r.Use(consumer.Require) r.Get("/", a.notes) r.Post("/", a.save) }) return r, nil } type notesPage struct { Home, Name, Base, Note string Revision int64 // the revision the form edits // Conflict is set when a save was refused because someone saved first: // Note is then the refused text and Saved the note as it stands. Conflict bool Saved string } // current reads the note and its revision; no note yet is "" at revision 0. func current(ctx context.Context, q interface { QueryRowContext(context.Context, string, ...any) *sql.Row }) (string, int64, error) { var note string var rev int64 err := q.QueryRowContext(ctx, `SELECT body, revision FROM notes WHERE id = 1`).Scan(¬e, &rev) if errors.Is(err, sql.ErrNoRows) { return "", 0, nil } return note, rev, err } func (a *app) notes(w http.ResponseWriter, r *http.Request) { _, name, base, _ := consumer.Person(r) note, rev, err := current(r.Context(), a.db) if err != nil { a.logger.Error("scratchpad: reading the note", "err", err) http.Error(w, "unavailable", http.StatusServiceUnavailable) return } a.page(w, http.StatusOK, notesPage{Name: name, Base: base, Note: note, Revision: rev}) } func (a *app) page(w http.ResponseWriter, status int, p notesPage) { p.Home = a.home if err := a.pages.PageStatus(w, status, "notes", p); err != nil { a.logger.Error("scratchpad: render", "err", err) http.Error(w, "something went wrong", http.StatusInternalServerError) } } // save replaces the shared note, then sends the browser back to it. The form // says which revision it edited; if someone has saved since, nothing is // written and the page comes back with the person's text still in it. func (a *app) save(w http.ResponseWriter, r *http.Request) { sub, name, base, _ := consumer.Person(r) r.Body = http.MaxBytesReader(w, r.Body, 4*maxNote) // form encoding can triple a byte if err := r.ParseForm(); err != nil { http.Error(w, "The note is too long.", http.StatusRequestEntityTooLarge) return } note := r.PostForm.Get("note") if len(note) > maxNote { http.Error(w, "The note is too long.", http.StatusRequestEntityTooLarge) return } // A missing or malformed revision edited nothing in particular: it is // treated as stale, never as permission to overwrite. edited, err := strconv.ParseInt(r.PostForm.Get("revision"), 10, 64) if err != nil { edited = -1 } saved, rev, stale, err := a.write(r.Context(), note, sub, edited) if err != nil { a.logger.Error("scratchpad: saving the note", "err", err) http.Error(w, "unavailable", http.StatusServiceUnavailable) return } if stale { a.page(w, http.StatusConflict, notesPage{Name: name, Base: base, Note: note, Revision: rev, Conflict: true, Saved: saved}) return } http.Redirect(w, r, "/", http.StatusSeeOther) } // write saves note if the stored revision is still edited. Otherwise it // writes nothing and reports stale with the note and revision as they are. func (a *app) write(ctx context.Context, note, by string, edited int64) (saved string, rev int64, stale bool, err error) { tx, err := a.db.BeginTx(ctx, nil) if err != nil { return "", 0, false, err } defer tx.Rollback() saved, rev, err = current(ctx, tx) if err != nil { return "", 0, false, err } if rev != edited { return saved, rev, true, nil } if _, err := tx.ExecContext(ctx, `INSERT INTO notes (id, body, updated_by, updated_at, revision) VALUES (1, ?, ?, ?, ?) ON CONFLICT (id) DO UPDATE SET body = excluded.body, updated_by = excluded.updated_by, updated_at = excluded.updated_at, revision = excluded.revision`, note, by, time.Now().Unix(), rev+1); err != nil { return "", 0, false, err } return note, rev + 1, false, tx.Commit() }