oficina / slides Public

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

Plain git — no account needed to clone.

Download

Download this file

1// share.go is the read-only share link: minting one, listing them,
2// revoking one, and the unauthenticated screen a token opens.
3//
4// It is calendar's feed pattern (its calendar design §6, spec §5 here),
5// and the two rules that make it safe are worth stating where they are
6// implemented rather than only in the model's comment:
7//
8// - Only the SHA-256 of the token is stored. The token is 32 bytes of
9// randomness, so there is no dictionary to defend against and no
10// salt to add; what an unsalted hash buys is that resolving a URL
11// is one indexed read.
12// - Because only the hash is stored, the URL can be shown exactly
13// once — at the moment of minting. The page says so there, rather
14// than letting somebody find out by coming back for it.
15//
16// A missing token and a revoked one get the same 404. Anything else
17// would let a stranger with a guess learn that a link had once been
18// real.
19package slides
20
21import (
22 "crypto/rand"
23 "crypto/sha256"
24 "encoding/base64"
25 "encoding/hex"
26 "encoding/json"
27 "errors"
28 "fmt"
29 "io"
30 "net/http"
31 "strconv"
32 "time"
33
34 "github.com/go-chi/chi/v5"
35 "gorm.io/gorm"
36
37 "amadan.net/rastrillo/rastrillo"
38
39 "amadan.net/oficina/slides/internal/slides/present"
40)
41
42// shareTokenBytes is how much randomness a share link carries. Thirty
43// two bytes is 256 bits, which is not guessable by anything, and
44// base64url makes it 43 characters of URL — long enough that nobody
45// will type it and short enough to paste into a chat window.
46const shareTokenBytes = 32
47
48// newShareToken mints one. base64url without padding, so the token is
49// URL-safe with nothing to escape and nothing to trim.
50func newShareToken() (string, error) {
51 raw := make([]byte, shareTokenBytes)
52 if _, err := rand.Read(raw); err != nil {
53 return "", fmt.Errorf("slides: generate share token: %w", err)
54 }
55 return base64.RawURLEncoding.EncodeToString(raw), nil
56}
57
58// hashShareToken is the stored form: SHA-256 hex, unsalted, for the
59// reason in this file's own comment.
60func hashShareToken(token string) string {
61 sum := sha256.Sum256([]byte(token))
62 return hex.EncodeToString(sum[:])
63}
64
65// shareURL is the whole link as a person will paste it. a.cfg.Origin,
66// not the request's Host: the origin is what the app resolved at boot
67// and refused to start without (config.go), so a link minted behind a
68// proxy that lies about Host is still the URL that works.
69func (a *app) shareURL(token string) string {
70 return a.cfg.Origin + "/s/" + token
71}
72
73// --- GET /d/{sqid}/share ---
74
75type shareRow struct {
76 // Name is the link's name when it has one: a follow-along code's
77 // link is Audience (qrlink.go). Every other link has none.
78 Name string
79 Created string
80 Views string
81 StatusLabel string
82 StatusTone string
83 RevokeAction string
84 RevokeLabel string
85 RevokeAria string
86 Revoked bool
87}
88
89type sharePage struct {
90 shell
91 Title string
92 DeckTitle string
93
94 // Who can open the deck: the rung (spec §5), on this page because
95 // it is the deck's general access, and Docs puts that under Share.
96 // Rungs is the form, for somebody who may change it
97 // (mayChangeRung); a roster owner on an orphan may share it but not
98 // move it, and reads the rung as text instead (AccessCurrent).
99 AccessHeading string
100 AccessLegend string
101 AccessAction string
102 AccessSubmit string
103 AccessError string
104 Rungs []choiceOption
105 AccessCurrent string
106 AccessCurrentDesc string
107 AccessFixed string
108
109 LinksHeading string
110 Lead string
111 WarningTitle string
112 Warning string
113 BackHref string
114 BackLabel string
115 Action string
116 CreateLabel string
117
118 // NewURL is the link this request minted, shown once and never
119 // again. Empty on every visit that did not just create one.
120 NewURL string
121 NewTitle string
122 NewHint string
123 NewLabel string
124 CopyHint string
125
126 Links []shareRow
127 EmptyTitle string
128 EmptyBody string
129}
130
131// deckShare serves GET /d/{sqid}/share: this deck's links, what each
132// one has been used for, and the one form that makes another.
133//
134// The owner's alone. A team member can read the deck, and handing them
135// the power to mint an unauthenticated read capability for it is a
136// different decision from letting them read it — one the owner made
137// when they raised the rung, and not one they made for the whole
138// internet.
139func (a *app) deckShare(w http.ResponseWriter, r *http.Request) {
140 u, ok := a.viewer(w, r)
141 if !ok {
142 return
143 }
144 d, ok := a.ownedDeckFor(w, r, u, a.mayShareDeck)
145 if !ok {
146 return
147 }
148 a.renderSharePage(w, r, u, d, r.URL.Query().Get("new"), d.Rung, "")
149}
150
151// renderSharePage draws the share page. rung is the rung the access form
152// shows chosen (the deck's own, or what a refused POST asked for), and
153// accessErr the sentence under it when the POST was refused.
154func (a *app) renderSharePage(w http.ResponseWriter, r *http.Request, u User, d Deck, newToken, rung, accessErr string) {
155 var links []ShareLink
156 if err := a.db.G.WithContext(r.Context()).
157 Where("deck_id = ?", d.ID).
158 Order("created_at DESC, id DESC").Find(&links).Error; err != nil {
159 a.fail(w, r, "list share links", err)
160 return
161 }
162
163 base := "/d/" + d.Sqid
164 page := sharePage{
165 shell: a.shellFor(r, u, sharePageFrame(r, d)),
166 Title: rastrillo.T(r, "slides.share.title"),
167 DeckTitle: d.Title,
168 LinksHeading: rastrillo.T(r, "slides.share.links"),
169 Lead: rastrillo.T(r, "slides.share.lead"),
170 WarningTitle: rastrillo.T(r, "slides.share.warning.title"),
171 Warning: rastrillo.T(r, "slides.share.warning"),
172 BackHref: base,
173 BackLabel: rastrillo.T(r, "slides.deck.back"),
174 Action: base + "/share",
175 CreateLabel: rastrillo.T(r, "slides.share.create"),
176 EmptyTitle: rastrillo.T(r, "slides.share.empty.title"),
177 EmptyBody: rastrillo.T(r, "slides.share.empty.body"),
178 Links: make([]shareRow, 0, len(links)),
179
180 AccessHeading: rastrillo.T(r, "slides.deck.rung.legend"),
181 AccessLegend: rastrillo.T(r, "slides.deck.rung.legend"),
182 AccessError: accessErr,
183 }
184 if a.mayChangeRung(r.Context(), u, d) {
185 page.AccessAction = base + "/share/access"
186 page.AccessSubmit = rastrillo.T(r, "slides.share.access.submit")
187 page.Rungs = rungOptions(r, rung)
188 } else {
189 page.AccessCurrent = rungLabel(r, d.Rung)
190 if d.Rung == rungPrivate || d.Rung == rungGranted || d.Rung == rungTeam {
191 page.AccessCurrentDesc = rastrillo.T(r, "slides.rung."+d.Rung+".desc")
192 }
193 page.AccessFixed = rastrillo.T(r, "slides.share.access.fixed")
194 }
195 if newToken != "" {
196 page.NewURL = a.shareURL(newToken)
197 page.NewTitle = rastrillo.T(r, "slides.share.new.title")
198 page.NewHint = rastrillo.T(r, "slides.share.new.body")
199 page.NewLabel = rastrillo.T(r, "slides.share.new.label")
200 page.CopyHint = rastrillo.T(r, "slides.share.new.copy")
201 }
202 for _, l := range links {
203 when := whenWords(r, l.CreatedAt)
204 row := shareRow{
205 Created: rastrillo.Tf(r, "slides.share.row.created", "when", when),
206 Views: viewWords(r, l.Views),
207 Revoked: l.RevokedAt != nil,
208 RevokeAction: fmt.Sprintf("%s/share/%d/revoke", base, l.ID),
209 RevokeLabel: rastrillo.T(r, "slides.share.revoke"),
210 // A share link has no name — the URL is shown once and
211 // never again — so the date it was made is the only thing
212 // that tells one row from another. agents.html's rule
213 // ("Revoke" repeated down a list says which nothing),
214 // applied with the only handle this list has.
215 RevokeAria: rastrillo.Tf(r, "slides.share.revoke.aria", "when", when),
216 }
217 if l.Audience {
218 row.Name = rastrillo.T(r, "slides.share.audience.name")
219 }
220 if row.Revoked {
221 row.StatusLabel = rastrillo.T(r, "slides.share.revoked")
222 row.StatusTone = "neutral"
223 } else {
224 row.StatusLabel = rastrillo.T(r, "slides.share.active")
225 row.StatusTone = "positive"
226 }
227 page.Links = append(page.Links, row)
228 }
229 render(w, "share", page)
230}
231
232// viewWords is a link's use, as words. Two keys because English has two
233// forms and the catalog has no plural machinery — the same shape
234// decks.go's rowSub uses.
235func viewWords(r *http.Request, n int64) string {
236 switch n {
237 case 0:
238 return rastrillo.T(r, "slides.share.row.views.none")
239 case 1:
240 return rastrillo.T(r, "slides.share.row.views.one")
241 default:
242 return rastrillo.Tf(r, "slides.share.row.views", "n", n)
243 }
244}
245
246// --- POST /d/{sqid}/share ---
247
248// mintShareLink serves POST /d/{sqid}/share: one token, its hash
249// stored, and a 303 back to the share page carrying the token so it can
250// be shown once.
251//
252// The token rides in the redirect's query string, which is calendar's
253// shape too. It is a real cost — a URL with a live capability in it
254// lands in the browser's history and in any proxy log between here and
255// the person — and it is bounded: the redirect is same-origin, the
256// page it lands on is the owner's own, and there is no third party to
257// leak a Referer to. The alternative, a flash cookie, moves the same
258// secret into a different log.
259func (a *app) mintShareLink(w http.ResponseWriter, r *http.Request) {
260 u, ok := a.viewer(w, r)
261 if !ok {
262 return
263 }
264 d, ok := a.ownedDeckFor(w, r, u, a.mayShareDeck)
265 if !ok {
266 return
267 }
268
269 token, ok := a.createShareLink(w, r, u, d, false)
270 if !ok {
271 return
272 }
273 http.Redirect(w, r, "/d/"+d.Sqid+"/share?new="+token, http.StatusSeeOther)
274}
275
276// createShareLink makes one link on d for u — a fresh token, only its
277// hash stored, under the member guard — and returns the token, which
278// nothing can show again. The share page's form and the follow-along
279// code's request (qrlink.go) both make their links here, so the two can
280// never differ in what they store. audience marks the code's.
281func (a *app) createShareLink(w http.ResponseWriter, r *http.Request, u User, d Deck, audience bool) (string, bool) {
282 token, err := newShareToken()
283 if err != nil {
284 a.fail(w, r, "mint a share token", err)
285 return "", false
286 }
287 link := ShareLink{
288 DeckID: d.ID,
289 TokenHash: hashShareToken(token),
290 Actor: actorFor(u),
291 Audience: audience,
292 CreatedAt: time.Now().UTC(),
293 }
294 if err := a.guarded(r.Context(), a.memberGuard(r.Context(), u), func(db *gorm.DB) error { return db.Create(&link).Error }); err != nil {
295 if a.guardRefused(w, r, err) {
296 return "", false
297 }
298 a.fail(w, r, "create share link", err)
299 return "", false
300 }
301 return token, true
302}
303
304// --- POST /d/{sqid}/share/access ---
305
306// saveDeckAccess serves POST /d/{sqid}/share/access: who can open the
307// deck, the rung. It used to be one field of the settings form; it is on
308// the share page now, beside the links, as general access is in Docs.
309//
310// The owner's alone (mayChangeRung): a roster owner on an orphan may
311// share it but not move its rung, because making it private hides it
312// from everybody, them included (team_owner.go). Only the row changes —
313// the rung is not part of the document — under the member guard, inside
314// the writer transaction, as every owner action is.
315func (a *app) saveDeckAccess(w http.ResponseWriter, r *http.Request) {
316 u, ok := a.viewer(w, r)
317 if !ok {
318 return
319 }
320 d, ok := a.ownedDeckFor(w, r, u, a.mayChangeRung)
321 if !ok {
322 return
323 }
324 rung := r.PostFormValue("rung")
325 if !validRung(rung) {
326 w.WriteHeader(http.StatusUnprocessableEntity)
327 a.renderSharePage(w, r, u, d, "", rung, rastrillo.T(r, "slides.deck.rung.invalid"))
328 return
329 }
330 if rung != d.Rung {
331 err := a.guarded(r.Context(), a.memberGuard(r.Context(), u), func(db *gorm.DB) error {
332 // UpdateColumn: who can open a deck is not an edit of it,
333 // so the list's "edited 2 hours ago" does not move.
334 return db.Model(&Deck{}).Where("id = ? AND owner_id = ?", d.ID, d.OwnerID).
335 UpdateColumn("rung", rung).Error
336 })
337 if a.guardRefused(w, r, err) {
338 return
339 }
340 if err != nil {
341 a.fail(w, r, "change a deck's rung", err)
342 return
343 }
344 }
345 http.Redirect(w, r, "/d/"+d.Sqid+"/share", http.StatusSeeOther)
346}
347
348// --- POST /d/{sqid}/share/{id}/revoke ---
349
350// revokeShareLink serves POST /d/{sqid}/share/{id}/revoke.
351//
352// Scoped by deck as well as by id, so an id belonging to another deck
353// is a 404 rather than a revocation somebody was not entitled to make;
354// the deck itself is already one this person may share (ownedDeckFor).
355//
356// Revoking twice is not an error. The URL is off either way, and a
357// second POST from a double-clicked button should not look like a
358// failure.
359func (a *app) revokeShareLink(w http.ResponseWriter, r *http.Request) {
360 u, ok := a.viewer(w, r)
361 if !ok {
362 return
363 }
364 d, ok := a.ownedDeckFor(w, r, u, a.mayShareDeck)
365 if !ok {
366 return
367 }
368 id, err := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64)
369 if err != nil {
370 a.notFound(w, r)
371 return
372 }
373
374 now := time.Now().UTC()
375 // revoked_at IS NULL in the WHERE, so a second POST cannot move the
376 // timestamp: when a link was turned off is a fact about it, and a
377 // double-clicked button must not rewrite it.
378 var revoked int64
379 err = a.guarded(r.Context(), a.memberGuard(r.Context(), u), func(db *gorm.DB) error {
380 res := db.Model(&ShareLink{}).
381 Where("id = ? AND deck_id = ? AND revoked_at IS NULL", id, d.ID).
382 Update("revoked_at", now)
383 revoked = res.RowsAffected
384 return res.Error
385 })
386 if a.guardRefused(w, r, err) {
387 return
388 }
389 if err != nil {
390 a.fail(w, r, "revoke share link", err)
391 return
392 }
393 if revoked == 0 {
394 // Either the link is already revoked — in which case the URL is
395 // off, the person got what they asked for, and an error page
396 // would be a lie — or the id is not this deck's, which is a 404
397 // like every other row that is not yours.
398 var n int64
399 if err := a.db.G.WithContext(r.Context()).Model(&ShareLink{}).
400 Where("id = ? AND deck_id = ?", id, d.ID).Count(&n).Error; err != nil {
401 a.fail(w, r, "check a share link", err)
402 return
403 }
404 if n == 0 {
405 a.notFound(w, r)
406 return
407 }
408 http.Redirect(w, r, "/d/"+d.Sqid+"/share", http.StatusSeeOther)
409 return
410 }
411 // The row carries the actor who minted it, not the one who revoked
412 // it — the model has one actor column and this screen is the
413 // owner's alone, so the two are the same person in every path that
414 // exists today. Logged rather than left unrecorded, so the day a
415 // second person can reach this screen there is a trail.
416 a.logger.Info("slides: share link revoked",
417 "deck", d.Sqid, "link", id, "actor", actorFor(u))
418 http.Redirect(w, r, "/d/"+d.Sqid+"/share", http.StatusSeeOther)
419}
420
421// --- GET /s/{token} ---
422
423// sharedDeck serves the share link itself, outside the session group:
424// the whole point of the capability is that it works for somebody who
425// has no account here.
426//
427// It renders the same viewer every other reader gets (viewer.go), in
428// link mode — no notes, no owner screens, no filmstrip link into
429// anything but another slide.
430func (a *app) sharedDeck(w http.ResponseWriter, r *http.Request) {
431 token := chi.URLParam(r, "token")
432 d, link, ok := a.deckForShareLink(w, r, token)
433 if !ok {
434 return
435 }
436
437 // Best effort, and deliberately outside the render path's error
438 // handling: a deck that will not load is a real problem, and a
439 // view count one short is not. Counted on resolution rather than
440 // on a successful render, so the number means "the link was
441 // opened" — which is the question the share page is asking.
442 if err := a.db.G.WithContext(r.Context()).Model(&ShareLink{}).
443 Where("id = ?", link.ID).
444 Update("views", gorm.Expr("views + 1")).Error; err != nil {
445 a.logger.Error("slides: count a share link view", "link", link.ID, "err", err)
446 }
447
448 // Following the presenter (spec §3.4). The share link is the whole
449 // capability here too — really, and not only for this one request
450 // (codex 5): the audience never learns the session's own address,
451 // never mind the remote's, so ?follow=1 is a flag on the link they
452 // already hold rather than a second URL to hand out, and every
453 // later read they make comes back through here or through
454 // /s/{token}/stream, both of which resolve the token again.
455 //
456 // Nothing to follow is a redirect back to the deck, not an error:
457 // the talk finishing while somebody was watching is the ordinary
458 // end of a session, and the honest answer is the deck they can
459 // still read.
460 if r.URL.Query().Get("follow") == "1" {
461 if p, live := a.liveSessionFor(r, d.ID); live {
462 a.followPresenter(w, r, d, p, "/s/"+token)
463 return
464 }
465 http.Redirect(w, r, "/s/"+token, http.StatusSeeOther)
466 return
467 }
468
469 // A stranger's page: the brand is plain text and "Sign in" carries
470 // no return path, because this path is the capability.
471 a.renderViewer(w, r, d, modeLink, "/s/"+token, a.publicShell(r, frame{parts: []string{d.Title}, context: d.Title, public: true}))
472}
473
474// --- GET /s/{token}/stream ---
475
476// sharedStream is the audience's SSE feed for whatever talk is live on
477// this deck — the presentation stream, behind the share link instead of
478// behind the session sqid (codex 5).
479//
480// It exists so that a follower's stream is a thing their own link can
481// be revoked out of. The events are the session's own, unchanged; what
482// differs is who is allowed to hear them and for how long. The link is
483// re-resolved before every write, so revoking it ends the stream within
484// one event or one heartbeat rather than at the end of the talk.
485//
486// Nothing to follow is not an error. A talk that finished while
487// somebody was watching gets one `ended` event, which is exactly what
488// the script does with a talk that ends any other way: reload, and
489// land on the deck they can still read.
490func (a *app) sharedStream(w http.ResponseWriter, r *http.Request) {
491 token := chi.URLParam(r, "token")
492 d, _, ok := a.deckForShareLink(w, r, token)
493 if !ok {
494 return
495 }
496 p, live := a.liveSessionFor(r, d.ID)
497 if !live {
498 a.endedStream(w, r)
499 return
500 }
501 a.streamPresentation(w, r, p, func() bool {
502 return a.shareLinkLive(r, token)
503 })
504}
505
506// shareLinkLive re-asks the one question deckForShareLink asks: is
507// this token still a link nobody has revoked. One indexed read, and no
508// answer written — the caller is mid-stream and has nothing to say to
509// a client but "goodbye".
510//
511// A database error reads as "not live", because failing closed on a
512// capability check is the only direction that is ever safe: the cost is
513// a follower whose page reconnects, and the alternative is a revoked
514// link that keeps working through a blip.
515func (a *app) shareLinkLive(r *http.Request, token string) bool {
516 if token == "" {
517 return false
518 }
519 var n int64
520 if err := a.db.G.WithContext(r.Context()).Model(&ShareLink{}).
521 Where("token_hash = ? AND revoked_at IS NULL", hashShareToken(token)).
522 Count(&n).Error; err != nil {
523 a.logger.Error("slides: re-check a share link mid-stream", "err", err)
524 return false
525 }
526 return n > 0
527}
528
529// endedStream is one SSE event saying the talk is over, and then the
530// end of the response. The same shape presentStream's own connect
531// event has, so the script has one thing to understand rather than two.
532func (a *app) endedStream(w http.ResponseWriter, r *http.Request) {
533 fl, ok := w.(http.Flusher)
534 if !ok {
535 a.fail(w, r, "stream: the ResponseWriter does not flush", nil)
536 return
537 }
538 w.Header().Set("Content-Type", "text/event-stream")
539 w.Header().Set("Cache-Control", "no-store")
540 w.WriteHeader(http.StatusOK)
541 body, err := json.Marshal(present.Event{Ended: true})
542 if err != nil {
543 return
544 }
545 _, _ = io.WriteString(w, "event: slide\ndata: "+string(body)+"\n\n")
546 fl.Flush()
547}
548
549// deckForShareLink resolves a share token to the deck it opens and the
550// link row itself, answering 404 for a token that is missing, revoked
551// or malformed.
552//
553// Split out of sharedDeck because the asset route (assets.go) is the
554// second thing a share link has to be able to reach: the page renders
555// its images under /s/{token}/assets, so the picture is behind exactly
556// the capability the page is, and there is one lookup rather than two
557// that could come to different conclusions about a revoked link.
558func (a *app) deckForShareLink(w http.ResponseWriter, r *http.Request, token string) (Deck, ShareLink, bool) {
559 if token == "" {
560 a.notFound(w, r)
561 return Deck{}, ShareLink{}, false
562 }
563 var link ShareLink
564 err := a.db.G.WithContext(r.Context()).
565 Where("token_hash = ? AND revoked_at IS NULL", hashShareToken(token)).
566 Take(&link).Error
567 switch {
568 case err == nil:
569 case errors.Is(err, gorm.ErrRecordNotFound):
570 // Missing and revoked are the same answer. Not 410: a gone
571 // tells a stranger the URL they guessed was once real.
572 a.notFound(w, r)
573 return Deck{}, ShareLink{}, false
574 default:
575 a.fail(w, r, "resolve share link", err)
576 return Deck{}, ShareLink{}, false
577 }
578
579 var d Deck
580 if err := a.db.G.WithContext(r.Context()).Take(&d, link.DeckID).Error; err != nil {
581 if errors.Is(err, gorm.ErrRecordNotFound) {
582 a.notFound(w, r)
583 return Deck{}, ShareLink{}, false
584 }
585 a.fail(w, r, "load a shared deck", err)
586 return Deck{}, ShareLink{}, false
587 }
588 return d, link, true
589}
590
591// sharePageFrame is the share page's chrome. Appearance returns to the
592// bare path: this page's query can carry the one-time link (?new=), and
593// reflecting a query into the page would print it again.
594func sharePageFrame(r *http.Request, d Deck) frame {
595 f := onDeck(rastrillo.T(r, "slides.share.title"), d.Title)
596 f.ret = "/d/" + d.Sqid + "/share"
597 return f
598}
599