oficina / slides Public

Presenting: ordered events, required press ids, token checked in tx

Review fix round 1 for the absolute position.

A stream now drops a position event whose seq is not above the newest
it has sent, so two presses publishing in the reverse of their commit
order cannot leave a page on the older position. Catch-up after a held
stream always sends the row.

Positional sessions require a press id (422 without). Every control
form renders a fresh one, and present.js sends a new id with each
press, including a form it submits in place. Legacy sessions still
take no id.

applyPress checks the request's token or signed-in presenter against
the row its transaction read, so a token replaced after the request
was let in drives nothing. The credits inventory follows present.js.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 8e89cecdbc2490f0a9bf314ac353b6be43efca75 parent 987fffa
8 files changed, +373 −43
  • internal/slides/credits/assets.json +1 −1
  • internal/slides/presentation.go +34 −5
  • internal/slides/presenting_position.go +73 −24
  • internal/slides/presenting_position_test.go +169 −0
  • internal/slides/static/present.js +20 −5
  • internal/slides/templates/present_controls.html +9 −3
  • internal/slidestest/present_position_test.go +64 −3
  • internal/slidestest/present_test.go +3 −2
diff --git a/internal/slides/credits/assets.json b/internal/slides/credits/assets.json
index 4fdf756..d31b8f9 100644
--- a/internal/slides/credits/assets.json
+++ b/internal/slides/credits/assets.json
@@ -68,7 +68,7 @@
"internal/slides/static/fonts/LiberationSerif-Regular.woff2": "922f544d0eabdf45ecd389b3bb35367e670b736e40851d01e53c150352c012f2",
"internal/slides/static/fontsgate.971e476eab8b8588.js": "971e476eab8b8588be520ac38eb823ab19beb2567db734555a7edc40d58567b2",
"internal/slides/static/fontshold.876f3d8d396da42f.js": "876f3d8d396da42f81954539f30b7200edfcde719d2920504707822f176a36ab",
- "internal/slides/static/present.js": "046810f3116893a781471a721a7d4992df5e4dc312591501416ff4a2859f829e",
+ "internal/slides/static/present.js": "abcb8ee91742624a48f2196b760cb5368ed9b3392dd4c82acff7b6c7e018c1fa",
"internal/slides/static/rastrillo.js": "13a8ca6fa9ac25833f6485ab50a521dff7bd811372025dc5141b96522b60098b",
"internal/slides/static/select.js": "e231bad4b964464addfacd52d2260d4bdc0a02938fc033a25fdd9cbeb3671be1",
"internal/slides/static/shell.js": "bdc4d635fb8f14ef7089f7f692290baea645b13543be36328e7667fe8aed2caf",
diff --git a/internal/slides/presentation.go b/internal/slides/presentation.go
index b56b1ef..1aec305 100644
--- a/internal/slides/presentation.go
+++ b/internal/slides/presentation.go
@@ -436,6 +436,10 @@ type commandButton struct {
Op string
Label string
Slide string
+ // Press is the press id the form sends (presenting_position.go),
+ // fresh on every render, so a form resubmitted by a reload counts
+ // once and each new page makes new presses.
+ Press string
}
// controls is the shared button block (templates/present_controls.html).
@@ -747,10 +751,10 @@ func (a *app) renderSurface(w http.ResponseWriter, r *http.Request, d Deck, p Pr
page.Controls = &controls{
Action: "/p/" + p.Sqid + "/command",
Token: opt.token,
- Buttons: []commandButton{
+ Buttons: withPressIDs([]commandButton{
{Op: "prev", Label: page.PrevLabel},
{Op: "next", Label: page.NextLabel},
- },
+ }),
}
page.NotesHref = "/p/" + p.Sqid + "/notes?t=" + url.QueryEscape(opt.token)
page.NotesLabel = rastrillo.T(r, "slides.present.notes.title")
@@ -969,12 +973,12 @@ func commandControls(r *http.Request, p Presentation, token string) *controls {
return &controls{
Action: "/p/" + p.Sqid + "/command",
Token: token,
- Buttons: []commandButton{
+ Buttons: withPressIDs([]commandButton{
{Op: "prev", Label: rastrillo.T(r, "slides.present.prev")},
{Op: "next", Label: rastrillo.T(r, "slides.present.next")},
{Op: "blackout", Label: blackout},
{Op: "end", Label: rastrillo.T(r, "slides.present.end")},
- },
+ }),
}
}
@@ -1247,6 +1251,23 @@ func (a *app) streamPresentation(w http.ResponseWriter, r *http.Request, p Prese
fl.Flush()
return true
}
+ // lastSeq is the newest position sequence this stream has sent. Two
+ // presses commit in order but publish from their own goroutines,
+ // so the older one's event can reach the hub second; an event at or
+ // below lastSeq is that, or a repeat, and is not sent. Sequence 0
+ // is a session begun before positions existed, or the ended event
+ // endPresentationsOf publishes, and always goes through.
+ var lastSeq int64
+ stale := func(e present.Event) bool {
+ if e.Seq == 0 {
+ return false
+ }
+ if e.Seq <= lastSeq {
+ return true
+ }
+ lastSeq = e.Seq
+ return false
+ }
// catchUp is what a held stream owes when the presenter's standing
// returns: the talk as it is now, read afresh.
catchUp := func() bool {
@@ -1254,7 +1275,12 @@ func (a *app) streamPresentation(w http.ResponseWriter, r *http.Request, p Prese
if err := a.db.G.WithContext(r.Context()).Take(&now, p.ID).Error; err != nil {
return false
}
- body, err := json.Marshal(eventFor(now))
+ // Sent whatever lastSeq says: an event dropped while the stream
+ // was held may have moved lastSeq without reaching the page,
+ // and the row is the newest there is.
+ e := eventFor(now)
+ lastSeq = max(lastSeq, e.Seq)
+ body, err := json.Marshal(e)
return err == nil && send("event: slide\ndata: "+string(body)+"\n\n")
}
write := func(text string) bool {
@@ -1274,6 +1300,9 @@ func (a *app) streamPresentation(w http.ResponseWriter, r *http.Request, p Prese
return send(text)
}
event := func(e present.Event) bool {
+ if stale(e) {
+ return true
+ }
body, err := json.Marshal(e)
if err != nil {
return false
diff --git a/internal/slides/presenting_position.go b/internal/slides/presenting_position.go
index abdca20..97f76de 100644
--- a/internal/slides/presenting_position.go
+++ b/internal/slides/presenting_position.go
@@ -15,6 +15,7 @@
package slides
import (
+ "crypto/rand"
"errors"
"net/http"
"regexp"
@@ -61,6 +62,10 @@ type positionAnswer struct {
// cookie being enough is why the app-wide origin check (app.go's
// csrf.Protect) matters here: another site cannot make the presenter's
// browser press.
+//
+// It answers for the row the request resolved. applyPress asks again,
+// of the row its transaction read (drivesRow), because the token can be
+// replaced in between.
func (a *app) mayDrive(r *http.Request, p Presentation, token string) bool {
if remoteTokenOK(p, token) {
return true
@@ -71,12 +76,42 @@ func (a *app) mayDrive(r *http.Request, p Presentation, token string) bool {
return a.presenterActor(r) == p.Actor
}
+// errNotDriver is a press whose credential no longer drives the session
+// by the time its transaction reads the row: the token was replaced
+// between the request being let in and the write.
+var errNotDriver = errors.New("slides: not entitled to drive this presentation")
+
+// drivesRow is mayDrive against a row already read, with the signed-in
+// actor already looked up: the check applyPress makes inside its
+// transaction.
+func drivesRow(p Presentation, token, actor string) bool {
+ return remoteTokenOK(p, token) || (actor != "" && actor == p.Actor)
+}
+
+// pressToken is the remote token a press carries: the form's field,
+// or a bearer for a caller that is not a browser.
+func pressToken(r *http.Request) string {
+ if token := r.PostFormValue("t"); token != "" {
+ return token
+ }
+ return bearerToken(r)
+}
+
+// newPressID is a press id for a rendered form: 26 base32 characters,
+// inside pressIDPattern.
+func newPressID() string { return rand.Text() }
+
+// withPressIDs gives each button a fresh press id.
+func withPressIDs(buttons []commandButton) []commandButton {
+ for i := range buttons {
+ buttons[i].Press = newPressID()
+ }
+ return buttons
+}
+
// presentPress is presentCommand for a Positional session.
func (a *app) presentPress(w http.ResponseWriter, r *http.Request, p Presentation) {
- token := r.PostFormValue("t")
- if token == "" {
- token = bearerToken(r)
- }
+ token := pressToken(r)
if !a.mayDrive(r, p, token) {
a.notFound(w, r)
return
@@ -90,6 +125,9 @@ func (a *app) presentPress(w http.ResponseWriter, r *http.Request, p Presentatio
answer, err := a.applyPress(r, p, cmd)
switch {
case err == nil:
+ case errors.Is(err, errNotDriver):
+ a.notFound(w, r)
+ return
case errors.Is(err, errPresentationEnded):
a.gone(w, r)
return
@@ -122,9 +160,10 @@ func (a *app) presentPress(w http.ResponseWriter, r *http.Request, p Presentatio
w.WriteHeader(http.StatusNoContent)
}
-// pressCommandFrom reads the form. A press id, a step or a mode that is
-// present but malformed is errBadCommand; the op itself is checked when
-// it is applied.
+// pressCommandFrom reads the form. A missing or malformed press id is
+// errBadCommand: without one a press resent cannot be told from a
+// second press. So is a step or a mode that is present but malformed;
+// the op itself is checked when it is applied.
func pressCommandFrom(r *http.Request) (pressCommand, error) {
cmd := pressCommand{
Op: r.PostFormValue("op"),
@@ -133,7 +172,7 @@ func pressCommandFrom(r *http.Request) (pressCommand, error) {
AtSlide: r.PostFormValue("at_slide"),
AtMode: r.PostFormValue("at_mode"),
}
- if cmd.Press != "" && !pressIDPattern.MatchString(cmd.Press) {
+ if !pressIDPattern.MatchString(cmd.Press) {
return pressCommand{}, errBadCommand
}
if raw := r.PostFormValue("at_step"); raw != "" {
@@ -160,9 +199,20 @@ func pressCommandFrom(r *http.Request) (pressCommand, error) {
// first statement to its commit, so two presses cannot interleave, and
// the second reads the row the first wrote. The deck is read on the
// same connection, so the position and deckSeq agree with each other.
+//
+// The request's credential is checked again against the row the
+// transaction read, before anything else: a token replaced after the
+// request was let in drives nothing (errNotDriver).
func (a *app) applyPress(r *http.Request, p Presentation, cmd pressCommand) (positionAnswer, error) {
ctx := r.Context()
now := time.Now().UTC()
+ token := pressToken(r)
+ // Looked up before the transaction, on the read pool: who is
+ // signed in does not change with the row, only the token can.
+ actor := ""
+ if p.Actor != "" {
+ actor = a.presenterActor(r)
+ }
var updated Presentation
var deckSeq int64
moved := false
@@ -174,24 +224,25 @@ func (a *app) applyPress(r *http.Request, p Presentation, cmd pressCommand) (pos
}
return err
}
+ if !drivesRow(cur, token, actor) {
+ return errNotDriver
+ }
var d Deck
if err := tx.Take(&d, cur.DeckID).Error; err != nil {
return err
}
deckSeq = d.Seq
- if cmd.Press != "" {
- var seen int64
- if err := tx.Model(&PresentationPress{}).
- Where("presentation_id = ? AND press_id = ?", cur.ID, cmd.Press).
- Count(&seen).Error; err != nil {
- return err
- }
- if seen > 0 {
- // Sent twice: where the talk is, and nothing else.
- updated = cur
- return nil
- }
+ var seen int64
+ if err := tx.Model(&PresentationPress{}).
+ Where("presentation_id = ? AND press_id = ?", cur.ID, cmd.Press).
+ Count(&seen).Error; err != nil {
+ return err
+ }
+ if seen > 0 {
+ // Sent twice: where the talk is, and nothing else.
+ updated = cur
+ return nil
}
h, view, err := a.openDeckOn(ctx, tx, d)
@@ -212,10 +263,8 @@ func (a *app) applyPress(r *http.Request, p Presentation, cmd pressCommand) (pos
if res.RowsAffected == 0 {
return errPresentationEnded
}
- if cmd.Press != "" {
- if err := rememberPress(tx, cur.ID, cmd.Press, now); err != nil {
- return err
- }
+ if err := rememberPress(tx, cur.ID, cmd.Press, now); err != nil {
+ return err
}
moved = true
return tx.Take(&updated, cur.ID).Error
diff --git a/internal/slides/presenting_position_test.go b/internal/slides/presenting_position_test.go
new file mode 100644
index 0000000..8a0680e
--- /dev/null
+++ b/internal/slides/presenting_position_test.go
@@ -0,0 +1,169 @@
+package slides
+
+import (
+ "bufio"
+ "context"
+ "crypto/rand"
+ "encoding/json"
+ "errors"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "strings"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/slides/internal/slides/present"
+)
+
+// presentingApp is an app with one deck and one Positional session on
+// it, written straight into the database, whose remote token is token.
+// The deck has no document yet, which is an empty talk: these tests are
+// about who may write and in what order, not where a press lands.
+func presentingApp(t *testing.T, token string) (*http.ServeMux, *app, Presentation) {
+ t.Helper()
+ mux, a, err := New(testDB(t), Config{Env: EnvDevelopment, Origin: "http://localhost:8091", Logger: quietLogger()})
+ if err != nil {
+ t.Fatalf("New: %v", err)
+ }
+ t.Cleanup(func() { a.Close() })
+ d := Deck{Sqid: "presentdk2", Title: "Talk", OwnerID: 1, Rung: "private"}
+ if err := a.db.G.Create(&d).Error; err != nil {
+ t.Fatalf("create a deck: %v", err)
+ }
+ p := Presentation{
+ Sqid: "presentss2", DeckID: d.ID, Actor: "person:1", Code: "ABCDEF",
+ RemoteTokenHash: hashRemoteToken(token), StartedAt: time.Now().UTC(),
+ Positional: true, Mode: "core", Seq: 3,
+ }
+ if err := a.db.G.Create(&p).Error; err != nil {
+ t.Fatalf("create a presentation: %v", err)
+ }
+ return mux, a, p
+}
+
+// pressRequestWith is a press as the phone posts it.
+func pressRequestWith(token, op string) *http.Request {
+ form := url.Values{"op": {op}, "t": {token}, "press": {rand.Text()}}
+ r := httptest.NewRequest(http.MethodPost, "/p/presentss2/command", strings.NewReader(form.Encode()))
+ r.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ return r
+}
+
+// TestATokenReplacedMidPressDrivesNothing: a press is let in on the
+// row its request resolved, the phone is re-paired before its
+// transaction runs, and the press must then move nothing. The
+// credential is checked again against the row the transaction reads.
+func TestATokenReplacedMidPressDrivesNothing(t *testing.T) {
+ const token = "the-phone-token-the-presenter-paired-first"
+ _, a, p := presentingApp(t, token)
+
+ // The same press path untouched works, so the refusal below is the
+ // replaced token and nothing else.
+ if _, err := a.applyPress(pressRequestWith(token, "next"), p, pressCommand{Op: "next", Press: rand.Text()}); err != nil {
+ t.Fatalf("a press with the paired token: %v", err)
+ }
+
+ r := pressRequestWith(token, "next")
+ if !a.mayDrive(r, p, token) {
+ t.Fatal("the paired token was not let in")
+ }
+ // Re-paired between the request being let in and its write.
+ if err := a.db.G.Model(&Presentation{}).Where("id = ?", p.ID).
+ Update("remote_token_hash", hashRemoteToken("a-new-phone-token")).Error; err != nil {
+ t.Fatalf("re-pair: %v", err)
+ }
+ _, err := a.applyPress(r, p, pressCommand{Op: "next", Press: rand.Text()})
+ if !errors.Is(err, errNotDriver) {
+ t.Errorf("a press whose token was replaced mid-flight: err %v, want errNotDriver", err)
+ }
+
+ var now Presentation
+ if err := a.db.G.Take(&now, p.ID).Error; err != nil {
+ t.Fatalf("reread the session: %v", err)
+ }
+ if now.Seq != 4 {
+ t.Errorf("after one press and one refused one the session is at seq %d, want 4", now.Seq)
+ }
+ var kept int64
+ if err := a.db.G.Model(&PresentationPress{}).Where("presentation_id = ?", p.ID).Count(&kept).Error; err != nil {
+ t.Fatalf("count press ids: %v", err)
+ }
+ if kept != 1 {
+ t.Errorf("the refused press left %d press ids, want only the first press's 1", kept)
+ }
+}
+
+// TestAStreamNeverGoesBackToAnOlderPress forces the interleaving two
+// presses can make: A commits first (seq 4), then B (seq 5), but B's
+// goroutine publishes before A's. The stream must leave its page at B,
+// never on A's older position.
+func TestAStreamNeverGoesBackToAnOlderPress(t *testing.T) {
+ mux, a, p := presentingApp(t, "token")
+ srv := httptest.NewServer(mux)
+ defer srv.Close()
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, srv.URL+"/p/"+p.Sqid+"/stream", nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ resp, err := http.DefaultClient.Do(req)
+ if err != nil {
+ t.Fatalf("open the stream: %v", err)
+ }
+ defer resp.Body.Close()
+ events := bufio.NewReader(resp.Body)
+ if e := readSlideEvent(t, events); e.Seq != 3 {
+ t.Fatalf("the connect event is %+v, want seq 3", e)
+ }
+
+ // Both committed, in order: the row holds B.
+ a2 := p
+ a2.SlideID, a2.Seq = "after-a", 4
+ b := p
+ b.SlideID, b.Seq = "after-b", 5
+ if err := a.db.G.Model(&Presentation{}).Where("id = ?", p.ID).
+ Updates(map[string]any{"slide_id": b.SlideID, "seq": b.Seq}).Error; err != nil {
+ t.Fatal(err)
+ }
+ // Published the other way round, then an end to fence the stream.
+ a.hub.Publish(p.Sqid, eventFor(b))
+ a.hub.Publish(p.Sqid, eventFor(a2))
+ a.hub.Publish(p.Sqid, present.Event{Ended: true})
+
+ var last present.Event
+ for {
+ e := readSlideEvent(t, events)
+ if e.Ended {
+ break
+ }
+ last = e
+ }
+ if last.Seq != 5 || last.SlideID != "after-b" {
+ t.Errorf("the stream left its page at %+v, want B's position (after-b, seq 5)", last)
+ }
+}
+
+// readSlideEvent reads the stream until its next `slide` event.
+func readSlideEvent(t *testing.T, r *bufio.Reader) present.Event {
+ t.Helper()
+ var name string
+ for {
+ line, err := r.ReadString('\n')
+ if err != nil {
+ t.Fatalf("read the stream: %v", err)
+ }
+ line = strings.TrimRight(line, "\r\n")
+ switch {
+ case strings.HasPrefix(line, "event: "):
+ name = strings.TrimPrefix(line, "event: ")
+ case strings.HasPrefix(line, "data: ") && name == "slide":
+ var e present.Event
+ if err := json.Unmarshal([]byte(strings.TrimPrefix(line, "data: ")), &e); err != nil {
+ t.Fatalf("the stream's event: %v", err)
+ }
+ return e
+ }
+ }
+}
diff --git a/internal/slides/static/present.js b/internal/slides/static/present.js
index 386010a..33bab7e 100644
--- a/internal/slides/static/present.js
+++ b/internal/slides/static/present.js
@@ -6,10 +6,10 @@
// audience's follow view — is complete without it: the buttons are
// forms, the pager is links, the follow view has a meta refresh.
//
-// It sends exactly what those forms send (op, t, slide, POSTed to
-// /p/{session}/command), so there is one protocol rather than two, and
-// only on a page rendered for whoever holds the remote: the token
-// arrives as data-remote-token, and a page without one cannot send.
+// It sends exactly what those forms send (op, t, slide and a press id,
+// POSTed to /p/{session}/command), so there is one protocol rather than
+// two, and only on a page rendered for whoever holds the remote: the
+// token arrives as data-remote-token, and a page without one cannot send.
//
// Every URL it reads comes down as an attribute (codex 5). The
// audience's follow view is served from a share link and stays there —
@@ -33,9 +33,21 @@
var note = document.querySelector('[slides-blackout]');
if (!streamHref) return;
+ // A press id: 16 random bytes, base64url (22 characters). A session
+ // with a position requires one with every press, so a press sent
+ // twice counts once; one begun before positions ignores it. Each
+ // press gets its own.
+ function pressID() {
+ var bytes = new Uint8Array(16);
+ crypto.getRandomValues(bytes);
+ var raw = '';
+ for (var i = 0; i < bytes.length; i++) raw += String.fromCharCode(bytes[i]);
+ return btoa(raw).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
+ }
+
function command(op, slide) {
if (!token || !session) return;
- var body = new URLSearchParams({ op: op, t: token });
+ var body = new URLSearchParams({ op: op, t: token, press: pressID() });
if (slide) body.set('slide', slide);
fetch('/p/' + session + '/command', {
method: 'POST',
@@ -238,6 +250,9 @@
e.preventDefault();
var fd = new FormData(form);
if (e.submitter && e.submitter.name) fd.append(e.submitter.name, e.submitter.value);
+ // The form's press id was rendered once with the page, and this
+ // page is not reloaded between presses: each submit is a new one.
+ if (fd.has('press')) fd.set('press', pressID());
var body = new URLSearchParams(fd);
page(form.action, {
method: 'POST',
diff --git a/internal/slides/templates/present_controls.html b/internal/slides/templates/present_controls.html
index ac2f822..76ac76c 100644
--- a/internal/slides/templates/present_controls.html
+++ b/internal/slides/templates/present_controls.html
@@ -15,9 +15,12 @@
Keys (the whole `controls` struct, presentation.go):
Action string — /p/{session}/command
Token string — the remote capability
- Buttons []{Op, Label, Slide} — one form each; Slide only for a
- goto, which nothing renders yet and which the handler
- accepts so a native remote has it. */}}
+ Buttons []{Op, Label, Slide, Press} — one form each; Slide only
+ for a goto, which nothing renders yet and which the
+ handler accepts so a native remote has it. Press is a
+ press id, fresh on every render: a session with a
+ position requires one, so a reloaded form counts once,
+ and present.js sends a new one for each press it makes. */}}
{{/* data-busy="false": the busy rule is for buttons that save something.
Next, Previous and Blackout save nothing — they are presenting
controls, and they stay instant (Paul, 2026-09-29). */}}
@@ -29,6 +32,9 @@
<input type="hidden" name="slide" value="{{.Slide}}">
{{- end}}
<input type="hidden" name="t" value="{{$.Token}}">
+ {{- if .Press}}
+ <input type="hidden" name="press" value="{{.Press}}">
+ {{- end}}
<button rst-btn type="submit" slides-op="{{.Op}}">{{.Label}}</button>
</form>
{{- end}}
diff --git a/internal/slidestest/present_position_test.go b/internal/slidestest/present_position_test.go
index 573e447..dfb9374 100644
--- a/internal/slidestest/present_position_test.go
+++ b/internal/slidestest/present_position_test.go
@@ -9,6 +9,7 @@ import (
"net/http"
"net/http/httptest"
"net/url"
+ "regexp"
"strings"
"sync"
"testing"
@@ -255,11 +256,19 @@ func TestAPressSentTwiceCountsOnce(t *testing.T) {
t.Errorf("the event after the repeat is seq %d, want the next press's seq %d", e.Seq, second.Seq)
}
- // A malformed press id is refused, and moves nothing.
+ // A malformed press id is refused, and so is a press with none:
+ // without an id a press sent twice would count twice.
+ _, _, before := rowPosition(t, a, session)
bad := url.Values{"op": {"next"}, "press": {"short"}}
if rec := pressRequest(t, a, session, token, bad, nil); rec.Code != http.StatusUnprocessableEntity {
t.Errorf("a press id of %q: status %d, want 422", "short", rec.Code)
}
+ if rec := pressRequest(t, a, session, token, url.Values{"op": {"next"}}, nil); rec.Code != http.StatusUnprocessableEntity {
+ t.Errorf("a press with no id: status %d, want 422", rec.Code)
+ }
+ if _, _, seq := rowPosition(t, a, session); seq != before {
+ t.Errorf("refused presses moved the sequence from %d to %d", before, seq)
+ }
// Sixty-four more presses push the first id out, and the table
// keeps sixty-four for the session.
@@ -274,7 +283,7 @@ func TestAPressSentTwiceCountsOnce(t *testing.T) {
if kept != 64 {
t.Errorf("the session keeps %d press ids, want 64", kept)
}
- _, _, before := rowPosition(t, a, session)
+ _, _, before = rowPosition(t, a, session)
if late := press(t, a, session, token, form, nil); late.Seq != before+1 {
t.Errorf("a press id older than the newest 64 answered seq %d, want it counted as new (%d)", late.Seq, before+1)
}
@@ -376,7 +385,7 @@ func TestTheSignedInPresenterMayDriveWithoutAToken(t *testing.T) {
t.Errorf("the presenter's press answered %+v, want steps step 1", got)
}
// And a form with no JSON asked for keeps the old answers.
- rec := post(t, a, "/p/"+session+"/command", url.Values{"op": {"next"}}, cookies...)
+ rec := post(t, a, "/p/"+session+"/command", op(t, "next"), cookies...)
if rec.Code != http.StatusSeeOther && rec.Code != http.StatusNoContent {
t.Errorf("the presenter's form press: status %d, want 303 or 204\n%s", rec.Code, rec.Body)
}
@@ -560,3 +569,55 @@ func TestTheFirstPressStartsTheTimer(t *testing.T) {
t.Error("the first press after a reset did not start the timer")
}
}
+
+// pressField finds the press ids on a page's control forms.
+var pressField = regexp.MustCompile(`name="press" value="([^"]*)"`)
+
+// TestEveryControlFormCarriesAFreshPressID: each control form carries a
+// press id, fresh on every render, so a form resubmitted by a reload
+// counts once and a page loaded again makes new presses.
+func TestEveryControlFormCarriesAFreshPressID(t *testing.T) {
+ a := newApp(t)
+ cookies := signedIn(t, a, allowedAddress)
+ session, token := startPresenting(t, a, stepsDeck(t, a, cookies), cookies)
+
+ seen := map[string]bool{}
+ for _, page := range []string{
+ "/p/" + session + "/remote?t=" + token,
+ "/p/" + session + "/remote?t=" + token,
+ "/p/" + session + "/notes?t=" + token,
+ "/p/" + session + "?t=" + token,
+ } {
+ body := mustGet(t, a, page, http.StatusOK, nil).Body.String()
+ forms := strings.Count(body, `<form method="post"`)
+ ids := pressField.FindAllStringSubmatch(body, -1)
+ if len(ids) != forms || forms == 0 {
+ t.Errorf("%s: %d control forms and %d press ids, want one each", page, forms, len(ids))
+ }
+ for _, m := range ids {
+ if !regexp.MustCompile(`^[A-Za-z0-9_-]{16,43}$`).MatchString(m[1]) {
+ t.Errorf("%s: press id %q is not one the server accepts", page, m[1])
+ }
+ if seen[m[1]] {
+ t.Errorf("%s: press id %q was rendered before", page, m[1])
+ }
+ seen[m[1]] = true
+ }
+ }
+
+ // The form as rendered is a press, and the same form again is not.
+ body := mustGet(t, a, "/p/"+session+"/remote?t="+token, http.StatusOK, nil).Body.String()
+ id := regexp.MustCompile(`value="next">\s*<input type="hidden" name="t" value="[^"]*">\s*<input type="hidden" name="press" value="([^"]*)"`).FindStringSubmatch(body)
+ if id == nil {
+ t.Fatalf("the remote's next form carries no press id:\n%s", body)
+ }
+ form := url.Values{"op": {"next"}, "t": {token}, "press": {id[1]}}
+ for range 2 {
+ if rec := post(t, a, "/p/"+session+"/command", form); rec.Code != http.StatusNoContent && rec.Code != http.StatusSeeOther {
+ t.Fatalf("posting the remote's next form: status %d", rec.Code)
+ }
+ }
+ if _, step, _ := rowPosition(t, a, session); step != 1 {
+ t.Errorf("the next form posted twice left the talk at step %d, want 1", step)
+ }
+}
diff --git a/internal/slidestest/present_test.go b/internal/slidestest/present_test.go
index 26b053c..44ab895 100644
--- a/internal/slidestest/present_test.go
+++ b/internal/slidestest/present_test.go
@@ -83,12 +83,13 @@ func pairThroughRow(t *testing.T, a *testApp, session string) string {
}
// command posts one remote command as the phone does: a form, with the
-// capability as a field. referer is sent when it is not empty, because
+// capability as a field and a fresh press id, as every rendered control
+// form carries one. referer is sent when it is not empty, because
// where the answer goes — 303 back, or 204 to a caller with no page to
// return to — is part of what these tests are about.
func command(t *testing.T, a *testApp, session, op, token, referer string, extra url.Values) *httptest.ResponseRecorder {
t.Helper()
- form := url.Values{"op": {op}, "t": {token}}
+ form := url.Values{"op": {op}, "t": {token}, "press": {newPressID(t)}}
for k, vs := range extra {
form[k] = vs
}