oficina / docs Public

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

Plain git — no account needed to clone.

Download

Download this file

1package docs
2
3import (
4 "amadan.net/oficina/home/roster"
5 "compress/gzip"
6 "context"
7 "errors"
8 "fmt"
9 "html/template"
10 "io"
11 "log/slog"
12 "net/http"
13 "strconv"
14 "strings"
15 "time"
16 "unicode"
17
18 "github.com/google/uuid"
19 "gorm.io/gorm"
20
21 "amadan.net/oficina/estilo.git/chrome"
22 "amadan.net/oficina/estilo.git/googleimport"
23 estilomenu "amadan.net/oficina/estilo.git/menu"
24 "amadan.net/oficina/estilo.git/savestatus"
25 "amadan.net/rastrillo/rastrillo"
26 rauth "amadan.net/rastrillo/rastrillo/auth"
27
28 "github.com/carlosframework/docs/internal/core"
29 "github.com/carlosframework/docs/internal/export"
30)
31
32// maxUpdateBytes caps a single client-submitted Yjs update
33// (POST /d/{sqid}/updates). A single keystroke's update is tens of
34// bytes, and a whole seeded document (seed.go) is a few kilobytes —
35// a megabyte is far above anything a legitimate client ever sends in
36// one update, and far below anything that threatens this instance's
37// memory. http.MaxBytesReader enforces this before the body is read
38// into memory at all, not after — updatesPost wraps r.Body in one
39// before it ever calls io.ReadAll.
40const maxUpdateBytes = 1 << 20
41
42// handlers holds what the app's HTTP handlers need — rastrillo
43// SKILL.md's "one handler struct holding d.G", here Store (Task 2)
44// instead: this app reads and writes documents through Store, never
45// through a *gorm.DB of its own.
46type handlers struct {
47 // google is the Google Drive chooser's public configuration; its
48 // zero value is off (import.go).
49 google googleimport.Config
50 // imports holds a slot per import converting now (maxImportsAtOnce).
51 imports chan struct{}
52
53 requireCurrent func(http.Handler) http.Handler
54 homeEnabled bool
55 // homeLinked reports a local person's stored Home link (linkstore.Linked).
56 homeLinked func(context.Context, int64) (bool, error)
57
58 render *renderer
59 logger *slog.Logger
60 store *Store
61
62 // hub is the live-update fan-out (hub.go). It lives here rather
63 // than on Store on purpose: Store is persistence and knows nothing
64 // about transports, and doc_updates stays the plain append-only
65 // table the design spec's §4.3 insisted on when it rejected
66 // rastrillo/eventlog. The consequence is that a writer which does
67 // not go through updatesPost does not notify — today that is only
68 // sample seeding, which runs before any editor can be open.
69 hub *hub
70
71 // Live push (push.go; the live-push spec's slice 1b). livePush is
72 // $DOCS_LIVE_PUSH: off, a push=1 stream and every POST are exactly
73 // today's. pushFrameCache shares each document's recent rows, opened,
74 // between its streams. pushStats counts what the streams did.
75 livePush bool
76 pushFrameCache bool
77 pushRegistry *pushRegistry
78 late *lateAnswers
79 pushStats *pushStats
80 pushLeaseLead time.Duration // tests only; see leaseLead
81
82 // previews is the document list's thumbnail cache (preview.go).
83 // Here rather than on Store for the same reason hub is: Store is
84 // persistence, and a laid-out page of line boxes is presentation.
85 previews *previews
86
87 // streamHeartbeat and streamTTL override stream.go's own defaults.
88 // Zero means "use the default", so nothing but a test ever sets
89 // them — see heartbeatInterval/ttlInterval for why the seam
90 // exists at all.
91 streamHeartbeat time.Duration
92 streamTTL time.Duration
93
94 // isMember answers "is this address on the configured allowlist",
95 // as opposed to admitted by a grant. It gates the member-only powers
96 // — creating a document, and changing who reaches one — so that a
97 // guest reads and writes what they were granted and nothing else
98 // (suite §1 ruling 1, Docs §8.2, branch review finding 1).
99 //
100 // A func rather than the allowlist value because handlers has no
101 // business with the rest of that type, and because app.go must be the
102 // one place the two halves of admission are wired together.
103 isMember func(address string) bool
104
105 // oneShots parks a freshly minted public URL for exactly one render
106 // (oneshot.go). Here rather than on Store for the reason hub and
107 // previews are: Store is persistence, and this value is deliberately
108 // never persisted.
109 oneShots *oneShots
110
111 // origin is cfg.Origin, the app's own validated base URL (app.go's
112 // New refuses to boot without one outside development). The share
113 // page needs it to print a public link somebody can copy into a
114 // message: a relative path is not a thing you can paste to a person
115 // who is not already here.
116 //
117 // The configured origin rather than r.Host, deliberately. r.Host is
118 // attacker-controlled, and a link built from it is a link an
119 // attacker can aim somewhere else by sending the owner a request
120 // with a Host header of their choosing. csrf.Protect already trusts
121 // cfg.Origin for exactly this reason; this trusts the same value.
122 origin string
123
124 // peek reads the request's session without requiring one, for the
125 // chrome on routes no session guards (chrome.go's viewer). It never
126 // writes. directory is the hub directory origin behind the app
127 // switcher's "All apps", empty when none is configured.
128 peek func(*http.Request) (string, bool)
129 directory string
130 // auth is rastrillo's sign-in plugin: the door reads SigninState from
131 // it and writes PrepareSigninResponse through it (auth.go's signin).
132 auth *rauth.Auth
133 // rememberReturn keeps the page a sign-in began from for the local
134 // landing (signin_return.go, home_return.go): Home's return memory, or
135 // the standalone one.
136 rememberReturn func(http.ResponseWriter, string) bool
137 // returnPath reads that memory back, "/" when it holds nothing.
138 returnPath func(*http.Request) string
139 // homeIssuer is Home's issuer when Home is configured, "" otherwise:
140 // where the signed-out page's Forget chains to (auth.go's forget).
141 homeIssuer string
142}
143
144// listPage is GET /'s view data (spec §6.4). Title and the group
145// labels are resolved through rastrillo.T from Catalog (render.go);
146// a row's Title and When are the document's own data, not authored
147// copy, so list.html prints them directly rather than through T.
148//
149// CreateLabel backs the create button list.html
150// renders in its page header — present regardless of Groups, so it
151// reaches a person with no documents yet exactly as it reaches
152// everyone else (fix round 1: the original version of this screen
153// had no path to POST /documents at all outside a hand-typed curl).
154//
155// SignOutLabel backs the sign-out control in the shell bar's account
156// menu, which this screen fills with an "account" block — added in the fix round that deleted the development-only
157// stand-in identity: POST /signout (auth.go) always existed and
158// worked, but nothing on any page linked to it, which matters once
159// this is reachable at a real URL rather than only ever behind a
160// laptop's own access. A session lasts 30 days
161// (rastrillo/auth.DefaultSessionTTL); a page with no way to end one
162// on purpose is a real gap on something public, not a cosmetic one.
163type listPage struct {
164 Frame Frame
165 PartialCatalog string
166 HomeLinkLabel string
167
168 // CanCreate gates the create form in the list header. A guest is
169 // answered 403 by POST /documents, and a form whose only outcome is a
170 // bare error page is a control that exists to fail — the same defect
171 // as the editor a reader could type into. (Re-review, finding 3.)
172 CanCreate bool
173 // ImportLabel is the list's link to the import page (import.go),
174 // shown with the create form, to members only.
175 ImportLabel string
176
177 Title string
178 // Recent is the newest few documents, shown as their first pages
179 // across the top of the list; Groups is everything after them, as
180 // rows. See splitRecent.
181 Recent []docRow
182 Groups []docGroup
183 EmptyTitle string
184 EmptyBody string
185 CreateLabel string
186 SignOutLabel string
187
188 // Query is what was searched for, echoed back into the field so a
189 // result page is a page a person can edit and re-submit rather
190 // than one they have to retype into.
191 //
192 // Results is the ranked, ungrouped result list, used INSTEAD of
193 // Groups when Searching. Recency grouping is what an unfiltered
194 // list is for; grouping a ranked list under "Today" and "Earlier"
195 // would order the same rows twice, by two different rules, and
196 // show only the second.
197 Searching bool
198 Query string
199 Results []docRow
200 SearchLabel string
201 SearchPlace string
202 NoResultsHead string
203 NoResultsBody string
204 ClearLabel string
205
206 // JumpTo and JumpToScript back the keyboard palette
207 // (views/partials/jumpto.html), which every signed-in page
208 // carries so Control-K works from the list and from a document
209 // alike.
210 JumpTo jumpToView
211 JumpToScript string
212}
213
214// docGroup is one recency bucket ("Today", "This week", ...) and the
215// rows in it, in the order Store.List returned them — newest first.
216type docGroup struct {
217 Label string
218 Rows []docRow
219}
220
221// docRow is one document's row. Href points at the read-only view
222// (Task 4's GET /d/{sqid}, show below) — an ordinary link, so a click
223// works with no JavaScript.
224type docRow struct {
225 Href string
226 Title string
227 When string
228
229 // Thumb is the document's first page as line boxes (preview.go),
230 // drawn by list.html into the row's reserved 26x34 box. No bars
231 // means no thumbnail — an empty document, one whose structure
232 // could not be read, or one past a cold render's budget — and
233 // renders as the empty box the row has always shown.
234 Thumb thumbView
235
236 // SharedNote is set on a row the reader does not own — "Shared with
237 // you" — and empty on their own.
238 //
239 // The list used to be able to say nothing about whose a document was,
240 // because every row was the reader's; the comment on `list` said so
241 // and gave that as the reason. Sharing made it false, and a row that
242 // looks like yours and is not is the setup for opening somebody's
243 // document expecting to edit it. (Branch review, finding 9.)
244 SharedNote string
245}
246
247// owner uses the linked local person ID for Home sessions and the existing
248// address-to-person mapping for standalone authentication.
249func (h *handlers) owner(r *http.Request) (int64, error) {
250 actor, err := requestActor(r, h.store)
251 return actor.PersonID, err
252}
253
254// actor supplies the same local identity to ownership and address grants.
255func (h *handlers) actor(r *http.Request) (Actor, error) {
256 return requestActor(r, h.store)
257}
258
259// member reports whether the person on this request is a full member of
260// the instance rather than a guest admitted by a grant.
261//
262// A guest reaching a member-only route is answered 403 rather than 404.
263// The app answers 404 for documents, and for a good reason (§4.2: "not
264// yours" must not be distinguishable from "does not exist"), but there is
265// no document here to hide and nothing secret about the instance having
266// members — the guest was invited by one. Pretending POST /documents does
267// not exist would be a lie told for no gain.
268func (h *handlers) member(r *http.Request) bool {
269 if h.store.team != nil {
270 a, ok := r.Context().Value(accessContextKey{}).(*requestAccess)
271 return ok && a != nil && a.runtime == h.store.team && a.state() == roster.Member
272 }
273 id, err := requestActor(r, h.store)
274 if err != nil {
275 return false
276 }
277 return id.VerifiedAddress != nil && (h.isMember == nil || h.isMember(*id.VerifiedAddress))
278}
279
280// list serves GET /: the document list, spec §6.4 and Paul's four
281// rulings against it — newest first, grouped by recency, one row per
282// document. Cut, deliberately, not by oversight: no template
283// carousel, no "Owned by anyone"/"Last opened by me" filter chrome, no
284// grid/list/AZ/folder toggle, no commercial or platform chrome. The
285// row's 26×34 slot at its left edge (list.html's [docs-thumb]) now
286// holds a real rendering of the document's page one, drawn from the
287// PDF exporter's own layout through export.PageOne (preview.go). It
288// was reserved and deliberately empty until that was possible —
289// "reserved, not faked" — and the reservation did its job: the box is
290// the same box, so filling it reflowed nothing.
291//
292// What is drawn is where the text is, not the text: at this size a
293// glyph is a fraction of a pixel. Spec §11.4's raster pipeline is
294// still unbuilt and still what a larger thumbnail would need.
295//
296// A row shows title and when it was last touched, not who: List is
297// already scoped to the signed-in viewer's own documents (Store.List's
298// owner parameter), so every row's "who" is the same person reading
299// the page — rendering it would be inventing display data, not
300// showing real ownership.
301func (h *handlers) list(w http.ResponseWriter, r *http.Request) {
302 if wantsNative(r) {
303 h.nativeList(w, r)
304 return
305 }
306 // actor, not owner: this page answers "what can I reach", which
307 // since sharing landed is a wider question than "what is mine".
308 who, err := h.actor(r)
309 if err != nil {
310 h.logger.Error("docs: resolve signed-in person", "err", err)
311 h.fail(w, r, h.internalFailureStatus(), failStatus)
312 return
313 }
314
315 // The query is taken from the URL, so a search is a link: it can be
316 // bookmarked, reloaded, shared with yourself, and gone back to.
317 // That is also what makes the whole feature work with no
318 // JavaScript (spec §6.2) — the form is a GET and the page it lands
319 // on is an ordinary page.
320 query := strings.TrimSpace(r.URL.Query().Get("q"))
321 // This page shows the partial notice, so under Unknown its list may be
322 // empty: the empty state and the notice, not a 503.
323 h.acceptPartial(r)
324
325 data := listPage{
326 HomeLinkLabel: h.homeLinkLabel(r),
327 CanCreate: h.member(r),
328 Title: rastrillo.T(r, "docs.list.title"),
329 EmptyTitle: rastrillo.T(r, "docs.list.empty.title"),
330 EmptyBody: rastrillo.T(r, "docs.list.empty.body"),
331 CreateLabel: rastrillo.T(r, "docs.list.create.label"),
332 ImportLabel: rastrillo.T(r, "docs.list.import"),
333 SignOutLabel: rastrillo.T(r, "docs.signout.label"),
334 Query: query,
335 SearchLabel: rastrillo.T(r, "docs.list.search.label"),
336 SearchPlace: rastrillo.T(r, "docs.list.search.placeholder"),
337 NoResultsHead: rastrillo.T(r, "docs.list.search.none.title"),
338 NoResultsBody: rastrillo.T(r, "docs.list.search.none.body"),
339 ClearLabel: rastrillo.T(r, "docs.list.search.clear"),
340 JumpTo: newJumpToView(r),
341 JumpToScript: jumpToScriptPath(),
342 }
343 // The list is the app's root: its tab says just "Docs". A result page
344 // names what was searched for (spec §10).
345 var titleParts []string
346 if query != "" {
347 titleParts = []string{"“" + query + "”"}
348 }
349 data.Frame = h.frame(r, frameOptions{titleParts: titleParts})
350
351 if query != "" {
352 hits, err := h.store.SearchFor(r.Context(), who, query)
353 if err != nil {
354 h.logger.Error("docs: search documents", "err", err)
355 h.fail(w, r, h.internalFailureStatus(), failStatus)
356 return
357 }
358 now := time.Now().UTC()
359 data.Searching = true
360 data.PartialCatalog = h.partialCatalog(r)
361 thumb := h.thumbnailer(r.Context())
362 for _, d := range hits {
363 data.Results = append(data.Results, docRow{
364 SharedNote: sharedNote(r, d, who.PersonID),
365 Href: "/d/" + d.Sqid,
366 Title: d.Title,
367 When: formatWhen(now, d.UpdatedAt),
368 Thumb: thumb(d),
369 })
370 }
371 if err := h.render.page(w, r, "list", data); err != nil {
372 h.logger.Error("docs: render list", "err", err)
373 h.fail(w, r, h.internalFailureStatus(), failStatus)
374 }
375 return
376 }
377
378 docs, err := h.store.ListFor(r.Context(), who)
379 if err != nil {
380 h.logger.Error("docs: list documents", "err", err)
381 h.fail(w, r, h.internalFailureStatus(), failStatus)
382 return
383 }
384 data.PartialCatalog = h.partialCatalog(r)
385 data.Recent, data.Groups = splitRecent(groupByRecency(r, time.Now().UTC(), docs, h.thumbnailer(r.Context()), who.PersonID), recentShelf)
386 if err := h.render.page(w, r, "list", data); err != nil {
387 h.logger.Error("docs: render list", "err", err)
388 h.fail(w, r, h.internalFailureStatus(), failStatus)
389 }
390}
391
392// create serves POST /documents: a plain form post, no JavaScript
393// required (spec §6.2). It reads the permitted field by name —
394// rastrillo SKILL.md §4's "never bind a request body onto a GORM
395// model" — and Store.Create builds the row itself, so there is no
396// mass-assignment surface here at all. On success it redirects with
397// 303 See Other rather than the 302 a naive handler reaches for: a
398// visitor reloading the response, or a browser retrying the
399// navigation, replays the GET the redirect points at, never the POST
400// that created the document.
401func (h *handlers) create(w http.ResponseWriter, r *http.Request) {
402 // Member-only: a guest reads and writes what they were granted, and
403 // minting documents of their own is not that. Without this, one grant
404 // is a transitive key to the front door — the guest creates, shares,
405 // and admits the next person (branch review, finding 1).
406 if !h.requireMemberRequest(w, r, false) {
407 return
408 }
409 owner, err := h.owner(r)
410 if err != nil {
411 h.logger.Error("docs: resolve signed-in person", "err", err)
412 h.fail(w, r, h.internalFailureStatus(), failStatus)
413 return
414 }
415
416 r.Body = http.MaxBytesReader(w, r.Body, 16*1024)
417 if err := r.ParseForm(); err != nil {
418 h.fail(w, r, http.StatusBadRequest, failStatus)
419 return
420 }
421 token := r.PostFormValue("creation_token")
422 if token != "" {
423 parsed, err := uuid.Parse(token)
424 if err != nil {
425 h.fail(w, r, http.StatusBadRequest, failStatus)
426 return
427 }
428 token = parsed.String()
429 }
430 title := cleanTitle(r.PostFormValue("title"))
431 if len(title) > 1024 {
432 h.fail(w, r, http.StatusBadRequest, failStatus)
433 return
434 }
435 if title == "" {
436 title = rastrillo.T(r, "docs.document.untitled")
437 }
438
439 doc, err := h.store.CreateDraft(r.Context(), owner, title, token)
440 if err != nil {
441 h.logger.Error("docs: create document", "err", err)
442 h.fail(w, r, h.internalFailureStatus(), failStatus)
443 return
444 }
445 if wantsNative(r) {
446 nativeJSON(w, r, 201, map[string]any{"sqid": doc.Sqid, "title": doc.Title, "guid": doc.GUID})
447 return
448 }
449 http.Redirect(w, r, "/d/"+doc.Sqid, http.StatusSeeOther)
450}
451
452// showPage is GET /d/{sqid}'s view data (spec §6.1/§6.2). Title is the
453// document's own title — data, not authored copy, printed as-is the
454// same way docRow.Title is on the list. HTML is Store.HTML's rendered
455// replay of the CRDT's ProseMirror fragment through wazero, never a
456// database column; a document with no updates yet (a document just
457// created) replays to "", which views/show.html must render as an
458// ordinary empty canvas rather than erroring. It is template.HTML, not
459// string, so the template can emit it unescaped — Store.HTML's own
460// doc comment is where that "trusted markup" decision is made.
461type showPage struct {
462 Frame Frame
463 HomeLinkLabel string
464
465 // ImportReport is the import's report, shown once on arrival from
466 // POST /import (?imported=1); nil otherwise. CloseReport labels its
467 // close button.
468 ImportReport *reportView
469 CloseReport string
470
471 Title string
472 HTML template.HTML
473 SignOutLabel string // see listPage.SignOutLabel's own doc comment
474
475 // BackLabel is the document page's one route back to the list —
476 // the label on the shell bar's brand link, which views/show.html
477 // fills with a "brand" block (it was [docs-back], a breadcrumb in
478 // this page's own header, until the chrome moved to the topbar
479 // shell). Until it landed, GET /d/{sqid} offered no in-app
480 // navigation at all — its header held sign-out and nothing else — so a person who arrived by a
481 // bookmark or a mailed link, rather than by clicking through from
482 // GET /, had no way back to their own documents except the
483 // browser's back button, which that arrival gives them nothing to
484 // go back *to*.
485 //
486 // It deliberately reuses docs.list.title rather than adding a
487 // docs.show.back of its own: this is a breadcrumb naming its
488 // destination screen, and a breadcrumb that can drift from the
489 // title of the screen it points at is a translation bug waiting
490 // to happen in eleven locales nobody in this repo reads. One key,
491 // one string, and the link can never disagree with the page it
492 // leads to.
493 BackLabel string
494 Sqid string // views/show.html's [docs-editor] mount point's data-sqid, the editor bundle's own base for /d/{sqid}/updates
495
496 // CanShare and ShareLabel drive the share control views/show.html
497 // puts in the shell bar's "nav" block — which topbar.html renders
498 // inside [rst-shell-tail], immediately before the account
499 // disclosure. That is the position Paul asked for, and it is a slot
500 // the shell already owns; drawing a bar of our own to hold it is the
501 // chrome drift spec §10 says to watch for.
502 //
503 // CanShare is ownership, not readability. A grantee — a writer
504 // included, since no grant carries re-sharing — is not offered it,
505 // because sharePage is owner-only and answers them 404. Rendering a
506 // control that visibly fails is worse than rendering none: it reads
507 // as a broken app rather than as a boundary.
508 //
509 // ShareLabel reuses docs.share.title rather than adding a key of its
510 // own, for BackLabel's reason directly above: one string, so a
511 // control can never disagree with the page it leads to across
512 // eleven locales.
513 //
514 // It is a label rather than a glyph because rastrillo's icon set has
515 // no "share" in it. That set is a closed vocabulary of twelve, whose
516 // own comments argue each addition, and Icon renders an unknown slug
517 // as nothing at all — so {{icon "share"}} would have shipped an
518 // invisible control that no test of ours would have caught. A
519 // thirteenth icon is a rastrillo change, not a docs one.
520 CanShare bool
521 ShareLabel string
522
523 // CanWrite gates the editor: the ProseMirror mount point, its
524 // data-sqid, and the script that mounts it (views/show.html).
525 //
526 // A reader grantee reaches this page — GetFor admits them, and that is
527 // correct, they may read it. What was not correct was rendering them
528 // the owner's page: the bundle mounted, the toolbar enabled, and the
529 // document became contenteditable for somebody every write of whose
530 // the server refuses. The refusal worked; that is not the point. By
531 // the time the 404 arrives the person has typed a paragraph, and
532 // save-queue.mjs classifies a 4xx as permanent, drops the batch and
533 // keeps taking keystrokes. They lose the work, having been shown an
534 // editor. "It fails safely on the server" is not a defence when the
535 // cost is a person's work. (Branch review, finding 2.)
536 //
537 // So the editor is absent rather than disabled. A disabled editor is
538 // one CSS rule from being an editor again; an absent one has nothing
539 // to re-enable. views/public.html already demonstrates the shape.
540 CanWrite bool
541 EditorScript string // views/show.html's <script src>, from editorScriptPath() — never a literal, so it can never drift from what staticHandler actually serves
542
543 SaveStatus savestatus.Data
544
545 // See listPage's own fields: the palette is on every signed-in
546 // page, not only the list.
547 JumpTo jumpToView
548 JumpToScript string
549
550 // Toolbar is the formatting bar's copy (export.go's
551 // newToolbarView), rendered into show.html rather than written into
552 // the bundle, because every user-visible string is a catalog key.
553 // Fonts is the font gate (fontgate.go): the generated stylesheet,
554 // the preloads for exactly the faces this document is set in, and
555 // the list the gate script waits for before it shows the sheet.
556 //
557 // Menu is the menu bar's copy (menu.go's newMenuView). The two
558 // export links used to be four fields here, rendered as buttons
559 // pinned to the formatting bar's trailing end; they are items in
560 // the File menu now, and menu.go resolves their catalog keys
561 // itself, so those fields are gone rather than left set and unread.
562 Toolbar toolbarView
563 Menu menuView
564 Fonts fontGate
565
566 // Images is the editor's images (images_view.go): whether the ways
567 // in are drawn, and the strings the bundle says about a picture.
568 Images imagesView
569
570 // Large is the phone's large title and its subtitle (phone.go); More
571 // is ••• (menu.go's newMoreView), rendered into the compact bar's
572 // trail with Aa.
573 Large largeTitleView
574 More moreView
575
576 // ViewMode is "paged" or "infinite" (menu.go's viewMode, from the
577 // docs-view cookie), rendered onto [docs-canvas] so the first paint
578 // already matches the person's preference instead of reflowing when
579 // the deferred bundle runs. PageLabel is the page-number template
580 // the bundle stamps into each gap — copy, so it comes from the
581 // catalog here rather than being a literal in the bundle.
582 ViewMode string
583 PageLabel string
584
585 // Inspector is "open" or "closed" (menu.go's inspectorState, from the
586 // docs-inspector cookie), rendered onto the inspector and into the
587 // Format toggle's aria-expanded, for the same first-paint reason.
588 Inspector string
589
590 // Dialogs is the copy for the two <dialog>s Tools opens — word
591 // count and the shortcuts sheet. Server-rendered like everything
592 // else, so the bundle carries no strings of its own; it fills in
593 // numbers and rows.
594 Dialogs dialogView
595}
596
597// dialogView is the copy for the Tools menu's two dialogs.
598type dialogView struct {
599 WordCountTitle string
600 WordCountWords string
601 WordCountCharacters string
602 WordCountCharactersNoSpaces string
603 WordCountParagraphs string
604 WordCountSelection string
605 WordCountClose string
606
607 ShortcutsTitle string
608 ShortcutsClose string
609 // The bindings no menu item carries, so shortcuts.mjs cannot read
610 // them off the bar. Each is {Label, Keys}.
611 ShortcutsGroup string
612 ShortcutsExtra []shortcutRow
613}
614
615type shortcutRow struct {
616 Label string
617 Keys string
618}
619
620func newDialogView(r *http.Request) dialogView {
621 return dialogView{
622 WordCountTitle: rastrillo.T(r, "docs.editor.wordcount.title"),
623 WordCountWords: rastrillo.T(r, "docs.editor.wordcount.words"),
624 WordCountCharacters: rastrillo.T(r, "docs.editor.wordcount.characters"),
625 WordCountCharactersNoSpaces: rastrillo.T(r, "docs.editor.wordcount.charactersnospaces"),
626 WordCountParagraphs: rastrillo.T(r, "docs.editor.wordcount.paragraphs"),
627 WordCountSelection: rastrillo.T(r, "docs.editor.wordcount.selection"),
628 WordCountClose: rastrillo.T(r, "docs.editor.wordcount.close"),
629
630 ShortcutsTitle: rastrillo.T(r, "docs.editor.shortcuts.title"),
631 ShortcutsClose: rastrillo.T(r, "docs.editor.shortcuts.close"),
632 ShortcutsGroup: rastrillo.T(r, "docs.editor.shortcuts.editing"),
633 // Tab and Shift+Tab are repurposed inside the editable surface
634 // and appear in no menu; Backspace-after-autoformat and
635 // Shift+Enter are bindings with no control at all. They are the
636 // four a person is least likely to discover and most likely to
637 // need told.
638 ShortcutsExtra: []shortcutRow{
639 {rastrillo.T(r, "docs.editor.shortcuts.indent"), estilomenu.Shortcut(r, "Tab")},
640 {rastrillo.T(r, "docs.editor.shortcuts.outdent"), estilomenu.Shortcut(r, "Shift+Tab")},
641 {rastrillo.T(r, "docs.editor.shortcuts.undoformat"), estilomenu.Shortcut(r, "Backspace")},
642 {rastrillo.T(r, "docs.editor.shortcuts.linebreak"), estilomenu.Shortcut(r, "Shift+Enter")},
643 {rastrillo.T(r, "docs.editor.shortcuts.leave"), estilomenu.Shortcut(r, "Esc")},
644 },
645 }
646}
647
648// inspectorID is the inspector's id: the Format toggle's aria-controls.
649const inspectorID = "docs-inspector"
650
651// InspectorID is its value for the template.
652func (showPage) InspectorID() string { return inspectorID }
653
654// show serves GET /d/{sqid}: the document read-only, its title and
655// its CRDT content — rendered server-side as HTML through Store.HTML,
656// not plain text — inside a page-shaped canvas (views/show.html). An
657// unknown sqid and a sqid someone else owns 404 identically — spec
658// §4.2's contract that a document you cannot see is indistinguishable
659// from one that does not exist — because Store.GetFor's reader-scoped
660// query never distinguishes "no such row" from "not yours" in the
661// first place; there is no separate check here that could 403 by
662// mistake.
663func (h *handlers) show(w http.ResponseWriter, r *http.Request) {
664 sqid := r.PathValue("sqid")
665
666 actor, err := h.actor(r)
667 if err != nil {
668 h.logger.Error("docs: resolve signed-in person", "err", err)
669 h.fail(w, r, h.internalFailureStatus(), failStatus)
670 return
671 }
672
673 // GetFor, not Get: a grantee reads this page too. Get stays owner-only
674 // and is what the share and revoke paths use.
675 doc, err := h.store.GetFor(r.Context(), actor, sqid)
676 if err != nil {
677 if errors.Is(err, gorm.ErrRecordNotFound) {
678 h.fail(w, r, http.StatusNotFound, failDocument)
679 return
680 }
681 h.logger.Error("docs: get document", "sqid", sqid, "err", err)
682 h.fail(w, r, h.internalFailureStatus(), failStatus)
683 return
684 }
685
686 if wantsNative(r) {
687 nativeJSON(w, r, 200, map[string]any{"sqid": doc.Sqid, "title": doc.Title, "guid": doc.GUID, "can_share": doc.OwnerID == actor.PersonID && h.member(r), "can_write": h.store.CanWrite(r.Context(), actor, doc.ID)})
688 return
689 }
690 html, structureJSON, err := h.store.Page(r.Context(), doc)
691 if err != nil {
692 h.logger.Error("docs: document html", "sqid", sqid, "err", err)
693 h.fail(w, r, h.internalFailureStatus(), failStatus)
694 return
695 }
696 html = labelMissingImages(r, html)
697 // The faces come from the structure, without the title: on screen
698 // the title is in the bar, in the chrome's face.
699 structure, err := export.Parse("", structureJSON)
700 if err != nil {
701 h.logger.Error("docs: parse document structure", "sqid", sqid, "err", err)
702 h.fail(w, r, h.internalFailureStatus(), failStatus)
703 return
704 }
705 canWrite := h.store.CanWrite(r.Context(), actor, doc.ID)
706 canShare := doc.OwnerID == actor.PersonID && h.member(r)
707 hasReport := h.store.hasImportReport(r.Context(), doc.ID)
708
709 data := showPage{
710 HomeLinkLabel: h.homeLinkLabel(r),
711 Title: doc.Title,
712 HTML: html,
713 SignOutLabel: rastrillo.T(r, "docs.signout.label"),
714 BackLabel: rastrillo.T(r, "docs.list.title"),
715 Sqid: doc.Sqid,
716 CanShare: canShare,
717 CanWrite: canWrite,
718 ShareLabel: rastrillo.T(r, "docs.share.title"),
719 EditorScript: editorScriptPath(),
720 SaveStatus: savestatus.Data{Placement: "floating", Retrying: rastrillo.T(r, "docs.editor.status.retrying"), Failed: rastrillo.T(r, "docs.editor.status.failed")},
721 JumpTo: newJumpToView(r),
722 JumpToScript: jumpToScriptPath(),
723
724 Toolbar: newToolbarView(r),
725 Menu: newMenuView(r, doc.Sqid, h.member(r), canShare),
726 Large: newLargeTitleView(r, sharedNote(r, doc, actor.PersonID)),
727 More: newMoreView(r, doc.Sqid, moreCaps{Share: canShare, Write: canWrite, Delete: canShare, ImportReport: hasReport}),
728 Fonts: newFontGate(structure).withCopy(r),
729 ViewMode: viewMode(r),
730 Inspector: inspectorState(r),
731 PageLabel: rastrillo.T(r, "docs.editor.page.number"),
732 Dialogs: newDialogView(r),
733 Images: newImagesView(r, canWrite && h.store.ImagesReady()),
734 }
735 if data.Images.On {
736 data.Menu = withInsertMenu(r, data.Menu)
737 }
738 // The bar: the document's title, editable in place for a writer, and
739 // the owner's Share… (spec §5.1, §5.4).
740 chromeFor := frameOptions{titleParts: []string{doc.Title}, context: doc.Title}
741 if data.CanWrite {
742 chromeFor.edit = &chrome.TitleEdit{
743 Action: "/d/" + doc.Sqid + "/title",
744 Name: "title",
745 Value: doc.Title,
746 Label: rastrillo.T(r, "docs.chrome.title.label"),
747 Submit: rastrillo.T(r, "docs.chrome.title.rename"),
748 }
749 }
750 // The I2 header (spec 2026-11-11): the menu bar under the title and
751 // the undo/redo pair in the lead slot, both this app's own partials
752 // (views/partials/editor_bar.html); then the actions in the set's
753 // order, Format, the import report where there is one, and Share,
754 // the one primary, last before the account.
755 //
756 // Format is a toggle for the inspector (aria-controls), wide only:
757 // the inspector exists from 64rem. Its state is the docs-inspector
758 // cookie's, rendered here and onto the inspector, so the first paint
759 // is the final one; estilo renders it disabled, and brand/
760 // inspector.js enables it.
761 //
762 // A reader gets the menus and none of the formatting chrome: no
763 // undo/redo, no Format and (show.html) no inspector or strip. They
764 // cannot format, and a dead panel pushed their sheet left (review on
765 // #106).
766 // A reader's menu bar holds only what they can use: no editor
767 // commands, and no menu left empty by that (menu.go's readerMenu).
768 if !data.CanWrite {
769 data.Menu = readerMenu(data.Menu)
770 }
771 var err2 error
772 var formatIcon template.HTML
773 // The phone's compact bar (design/phone-web): Aa and ••• in its trail,
774 // the inline title in its title slot.
775 compact := &chrome.Compact{}
776 if compact.Trail, err2 = h.render.fragment("show", "docs-trail", data.More); err2 == nil {
777 state, tone := data.Large.Status.CurrentText(), data.Large.Status.CurrentState()
778 if !data.CanWrite {
779 state, tone = data.Large.ViewOnly, "viewonly"
780 }
781 compact.Title, err2 = h.render.fragment("show", "docs-inline-title", inlineTitleView{Title: doc.Title, Shared: data.Large.Shared, State: state, Tone: tone})
782 }
783 chromeFor.compact = compact
784 if err2 == nil {
785 chromeFor.menubar, err2 = h.render.fragment("show", "docs-menubar", data.Menu)
786 }
787 if err2 == nil && data.CanWrite {
788 if chromeFor.lead, err2 = h.render.fragment("show", "docs-history", data.Toolbar.history(true)); err2 == nil {
789 formatIcon, err2 = h.render.fragment("show", "docs-icon-format", nil)
790 }
791 }
792 if err2 != nil {
793 h.logger.Error("docs: render the editor's bar", "err", err2)
794 h.fail(w, r, h.internalFailureStatus(), failStatus)
795 return
796 }
797 if data.CanWrite {
798 chromeFor.actions = []chrome.Action{{
799 Item: estilomenu.Item{Controls: inspectorID, Expanded: data.Inspector == InspectorOpen, Label: rastrillo.T(r, "docs.editor.inspector.toggle")},
800 WideOnly: true,
801 Icon: formatIcon,
802 }}
803 }
804 // An imported document keeps its report one click away, for anybody
805 // who can read the document; it shows itself once on arrival.
806 if hasReport {
807 chromeFor.actions = append(chromeFor.actions, chrome.Action{Item: estilomenu.Item{Href: "/d/" + doc.Sqid + "/import-report", Label: rastrillo.T(r, "docs.import.report.open")}})
808 if r.URL.Query().Get("imported") == "1" {
809 rep, err := h.store.ImportReport(r.Context(), doc)
810 if err != nil {
811 h.logger.Error("docs: open import report", "doc_id", doc.ID, "err", err)
812 } else if rep != nil {
813 data.ImportReport = newReportView(r, doc.Sqid, rep)
814 data.CloseReport = rastrillo.T(r, "docs.import.report.close")
815 }
816 }
817 }
818 if data.CanShare {
819 chromeFor.actions = append(chromeFor.actions, chrome.Action{Item: estilomenu.Item{Href: "/d/" + doc.Sqid + "/share", Label: rastrillo.T(r, "docs.share.action")}, Primary: true})
820 }
821 data.Frame = h.frame(r, chromeFor)
822 if err := h.render.page(w, r, "show", data); err != nil {
823 h.logger.Error("docs: render show", "err", err)
824 h.fail(w, r, h.internalFailureStatus(), failStatus)
825 }
826}
827
828// maxLogBytes caps the concatenated update log GET /d/{sqid}/updates
829// will return. Per the design spec's own D2 note, this bound is what
830// a later snapshot/compaction plan removes; until then it must fail
831// LOUDLY (updatesGet logs the document and answers 500) rather than
832// silently truncate — a truncated log would hand the browser a
833// corrupt document that looks intact.
834const maxLogBytes = 8 << 20
835
836// getDocumentForUpdates is the reader-scoped lookup both
837// updatesGet and updatesPost share: it resolves the signed-in
838// person, then loads the document through Store.GetFor — already
839// reader-scoped and already 404-not-403 (its own doc comment) — so a
840// stranger's sqid returns exactly the same outcome as one that does
841// not exist. ok is false once a response has already been written
842// (404 or 500) and the caller must return immediately without doing
843// anything further.
844func (h *handlers) getDocumentForUpdates(w http.ResponseWriter, r *http.Request) (doc *Document, ok bool) {
845 sqid := r.PathValue("sqid")
846
847 actor, err := h.actor(r)
848 if err != nil {
849 h.logger.Error("docs: resolve signed-in person", "err", err)
850 h.fail(w, r, h.internalFailureStatus(), failStatus)
851 return nil, false
852 }
853
854 // Readable, not owned. This backs the stream, the updates GET and both
855 // exports, all of which a grantee may use. The updates POST authorizes
856 // separately in ApplyUpdate, where a reader is refused.
857 doc, err = h.store.GetFor(r.Context(), actor, sqid)
858 if err != nil {
859 if errors.Is(err, gorm.ErrRecordNotFound) {
860 h.fail(w, r, http.StatusNotFound, failDocument)
861 return nil, false
862 }
863 h.logger.Error("docs: get document", "sqid", sqid, "err", err)
864 h.fail(w, r, h.internalFailureStatus(), failStatus)
865 return nil, false
866 }
867 return doc, true
868}
869
870// updatesGet serves GET /d/{sqid}/updates: by default, the newest
871// usable snapshot (if any covers past `since`) followed by the tail
872// of doc_updates rows after it — snapshot-then-tail, not the raw log
873// (Task 6). `?raw=1` is the escape hatch that returns exactly the
874// doc_updates rows and nothing else, for a browser whose snapshot
875// will not decode; the server cannot detect that corruption itself
876// (it never calls into the core here), so the browser is the only
877// reader that can, and raw=1 is what lets it fall back to the one
878// source it can always trust. Reader-scoped exactly like show
879// (getDocumentForUpdates), and capped at maxLogBytes above.
880//
881// Why snapshot-then-tail loses nothing: a snapshot IS an ordinary Yjs
882// update, covering every row up to and including its own seq. The
883// browser's applyServerLog already loops Y.readUpdate over a
884// concatenated body, and Yjs integration is idempotent, so a client
885// asking `?since=5` that receives a snapshot reaching seq 256 has not
886// skipped rows 6-256 — the snapshot contains them. That is why no
887// client change is needed for the happy path; only raw=1 (wired up by
888// a later task) exists for the unhappy one.
889//
890// The size is summed and checked BEFORE anything is written to w:
891// writing the 200 status and a partial body first, then discovering
892// the cap is exceeded, would leave no way back except closing the
893// connection mid-response — indistinguishable, to a browser, from a
894// truncated document that looks intact. Failing before the first
895// byte goes out keeps that outcome impossible.
896func (h *handlers) updatesGet(w http.ResponseWriter, r *http.Request) {
897 doc, ok := h.getDocumentForUpdates(w, r)
898 if !ok {
899 return
900 }
901
902 since, ok := parseSince(w, r)
903 if !ok {
904 return
905 }
906
907 // raw=1 skips the snapshot lookup entirely and behaves exactly as
908 // this handler always has: doc_updates rows after `since`, nothing
909 // else. That is deliberate, not merely "don't bother fetching a
910 // snapshot we'd discard" — it is what makes raw=1 trustworthy as an
911 // escape hatch: its behavior does not depend on snapshot.go at all.
912 raw := r.URL.Query().Get("raw") == "1"
913
914 // A snapshot is an accelerator, never the source of truth (the
915 // snapshots design's D2, echoed in store.go's replay): if the
916 // lookup itself fails, this falls back to serving the plain log
917 // rather than 500ing a request the log alone can still answer.
918 var snapshot *DocSnapshot
919 if !raw {
920 snap, err := h.store.newestSnapshot(r.Context(), doc.ID)
921 if err != nil {
922 h.logger.Error("docs: load newest snapshot, serving the plain log instead", "sqid", doc.Sqid, "err", err)
923 } else if snap != nil && snap.Seq > since {
924 // A snapshot at or behind `since` buys nothing — the
925 // client already holds everything it covers — so it is
926 // only used when it actually advances the tail's start.
927 snapshot = snap
928 }
929 }
930
931 tailSince := since
932 if snapshot != nil {
933 tailSince = snapshot.Seq
934 }
935
936 var updates []DocUpdate
937 if err := h.store.db.WithContext(r.Context()).
938 Where("doc_id = ? AND seq > ?", doc.ID, tailSince).
939 Order("seq ASC").
940 Find(&updates).Error; err != nil {
941 h.logger.Error("docs: load update log", "sqid", doc.Sqid, "err", err)
942 http.Error(w, rastrillo.T(r, "docs.error.generic"), h.internalFailureStatus())
943 return
944 }
945
946 for i := range updates {
947 if err := h.store.openContentUpdate(doc.GUID, &updates[i]); err != nil {
948 h.logger.Error("docs: load update log", "sqid", doc.Sqid, "err", err)
949 http.Error(w, rastrillo.T(r, "docs.error.generic"), h.internalFailureStatus())
950 return
951 }
952 }
953
954 total := 0
955 if snapshot != nil {
956 total = len(snapshot.State)
957 }
958 for _, u := range updates {
959 total += len(u.UpdateBin)
960 }
961 if total > maxLogBytes {
962 h.logger.Error("docs: update log exceeds maxLogBytes", "sqid", doc.Sqid, "bytes", total, "cap", maxLogBytes)
963 http.Error(w, rastrillo.T(r, "docs.error.generic"), h.internalFailureStatus())
964 return
965 }
966
967 // Docs-Seq is derived from the bytes in hand — max(since, the
968 // highest seq actually being written) — and never from a second
969 // MAX(seq) query. See parseSince's own doc comment and the design's
970 // D2 for the update this loses if that is ever "simplified". A
971 // snapshot's own seq column is fine to fold in here even though it
972 // is not itself a doc_updates row: it travels with bytes (its
973 // State) that contain its whole prefix, so counting it is exactly
974 // as safe as counting the highest tail row's seq.
975 highest := since
976 if snapshot != nil && snapshot.Seq > highest {
977 highest = snapshot.Seq
978 }
979 for _, u := range updates {
980 if u.Seq > highest {
981 highest = u.Seq
982 }
983 }
984
985 w.Header().Set("Content-Type", "application/octet-stream")
986 w.Header().Set("Docs-Seq", strconv.FormatInt(highest, 10))
987 if h.livePush {
988 // A non-push client can check its cursor against the log's
989 // identity on its next fetch (§3.1, a rewound log), and learns the
990 // tag of the row its new cursor names, for a push stream's resume.
991 w.Header().Set("Docs-Log-Epoch", h.store.logEpoch)
992 if n := len(updates); n > 0 && updates[n-1].Seq == highest {
993 w.Header().Set("Docs-Seq-Tag", pushTag(highest, updates[n-1].UpdateBin))
994 } else if highest > 0 {
995 var row []DocUpdate
996 if err := h.store.db.WithContext(r.Context()).Where("doc_id = ? AND seq = ?", doc.ID, highest).Limit(1).Find(&row).Error; err == nil && len(row) == 1 && h.store.openContentUpdate(doc.GUID, &row[0]) == nil {
997 w.Header().Set("Docs-Seq-Tag", pushTag(highest, row[0].UpdateBin))
998 }
999 }
1000 }
1001 parts := make([][]byte, 0, len(updates)+1)
1002 if snapshot != nil {
1003 parts = append(parts, snapshot.State)
1004 }
1005 for _, u := range updates {
1006 parts = append(parts, u.UpdateBin)
1007 }
1008 if err := writeGuardedBody(w, r, 0, parts...); err != nil {
1009 h.logger.Error("docs: write update log", "err", err)
1010 }
1011}
1012
1013var (
1014 errUpdateTooLarge = errors.New("docs: posted update is larger than maxUpdateBytes")
1015 errUpdateEncoding = errors.New("docs: posted update has an unsupported Content-Encoding")
1016 errUpdateCorrupt = errors.New("docs: posted update is not valid gzip")
1017)
1018
1019// readPostedUpdate reads a posted update, gunzipping a body sent with
1020// Content-Encoding: gzip. The editor compresses a large save so that more
1021// of them fit a keepalive request's 64KiB, the one kind WebKit still sends
1022// while a link the page opened is loading (fixtures/save-queue.mjs). body
1023// is already under http.MaxBytesReader, which bounds what is read off the
1024// wire; the decompressed bytes are bounded by maxUpdateBytes again, so a
1025// small body cannot expand into a large one. Anything but gzip or none is
1026// refused rather than stored as if it were an update.
1027func readPostedUpdate(body io.Reader, encoding string) ([]byte, error) {
1028 switch strings.ToLower(strings.TrimSpace(encoding)) {
1029 case "", "identity":
1030 return io.ReadAll(body)
1031 case "gzip":
1032 default:
1033 return nil, errUpdateEncoding
1034 }
1035 var mbe *http.MaxBytesError
1036 zr, err := gzip.NewReader(body)
1037 if err != nil {
1038 if errors.As(err, &mbe) {
1039 return nil, err
1040 }
1041 return nil, fmt.Errorf("%w: %v", errUpdateCorrupt, err)
1042 }
1043 update, err := io.ReadAll(io.LimitReader(zr, maxUpdateBytes+1))
1044 if err != nil {
1045 if errors.As(err, &mbe) {
1046 return nil, err
1047 }
1048 return nil, fmt.Errorf("%w: %v", errUpdateCorrupt, err)
1049 }
1050 if len(update) > maxUpdateBytes {
1051 return nil, errUpdateTooLarge
1052 }
1053 return update, nil
1054}
1055
1056// updatesPost serves POST /d/{sqid}/updates: one new Yjs update from
1057// the browser's editor, applied through Store.ApplyUpdate — the
1058// point where a client's bytes first reach the CRDT core.
1059//
1060// r.Body is wrapped in http.MaxBytesReader before anything reads it,
1061// so an oversized body is refused (413) before it is buffered into
1062// memory at all, never after. A rejection from the core (bad bytes,
1063// not a database or programming error) is a 400: the client sent
1064// something the CRDT would not accept, and Store.ApplyUpdate's own
1065// doc comment guarantees nothing was persisted for it.
1066func (h *handlers) updatesPost(w http.ResponseWriter, r *http.Request) {
1067 doc, ok := h.getDocumentForUpdates(w, r)
1068 if !ok {
1069 return
1070 }
1071
1072 r.Body = http.MaxBytesReader(w, r.Body, maxUpdateBytes)
1073 update, err := readPostedUpdate(r.Body, r.Header.Get("Content-Encoding"))
1074 if err != nil {
1075 var mbe *http.MaxBytesError
1076 switch {
1077 case errors.As(err, &mbe), errors.Is(err, errUpdateTooLarge):
1078 http.Error(w, rastrillo.T(r, "docs.error.updatetoolarge"), http.StatusRequestEntityTooLarge)
1079 case errors.Is(err, errUpdateEncoding):
1080 http.Error(w, rastrillo.T(r, "docs.error.badupdate"), http.StatusUnsupportedMediaType)
1081 case errors.Is(err, errUpdateCorrupt):
1082 h.logger.Info("docs: reject posted update", "sqid", doc.Sqid, "err", err)
1083 http.Error(w, rastrillo.T(r, "docs.error.badupdate"), http.StatusBadRequest)
1084 default:
1085 h.logger.Error("docs: read posted update", "sqid", doc.Sqid, "err", err)
1086 http.Error(w, rastrillo.T(r, "docs.error.generic"), h.internalFailureStatus())
1087 }
1088 return
1089 }
1090
1091 actor, err := h.actor(r)
1092 if err != nil {
1093 h.logger.Error("docs: resolve actor for update", "sqid", doc.Sqid, "err", err)
1094 http.Error(w, rastrillo.T(r, "docs.error.generic"), h.internalFailureStatus())
1095 return
1096 }
1097
1098 applyCtx := r.Context()
1099 if h.livePush {
1100 // §5: a session over the rate waits here, before ApplyUpdate takes
1101 // the document's lock or the writer; too many waiting is a 503 the
1102 // clients retry. Never a 4xx: the web save queue drops a 4xx batch.
1103 if ok, busy := h.late.admit(r.Context(), h.hub.draining(), "person:"+strconv.FormatInt(actor.PersonID, 10), doc.ID); !ok {
1104 if busy || h.hub.isDraining() {
1105 w.Header().Set("Retry-After", "1")
1106 http.Error(w, rastrillo.T(r, "docs.error.generic"), http.StatusServiceUnavailable)
1107 }
1108 return
1109 }
1110 // §3.4: a Docs-Stream header from this session's own push stream on
1111 // this document is recorded with the row, inside its transaction.
1112 if o, ok := h.pushRegistry.origin(r, doc.ID, h.sessionBinding(r)); ok {
1113 applyCtx = context.WithValue(applyCtx, postOriginKey{}, o)
1114 }
1115 }
1116 seq, err := h.store.ApplyUpdate(applyCtx, doc, actor, update)
1117 if err != nil {
1118 // A reader posting an update gets the same 404 a stranger gets —
1119 // the same BODY too, which it did not used to be. This branch
1120 // answered http.NotFound ("404 page not found") while a stranger
1121 // got http.Error with the catalog's text, so the sentence above
1122 // and store.go's "refused identically" were both false. Harmless
1123 // as an oracle (a reader already knows the document exists) and
1124 // still worth fixing, because the comment was the thing being
1125 // relied on. (Branch review, finding 7f.)
1126 if errors.Is(err, ErrNotWritable) {
1127 http.Error(w, rastrillo.T(r, "docs.error.notfound"), http.StatusNotFound)
1128 return
1129 }
1130 if errors.Is(err, errTeamUnavailable) {
1131 http.Error(w, rastrillo.T(r, "docs.error.generic"), http.StatusServiceUnavailable)
1132 return
1133 }
1134 if updateIsClientFault(err) {
1135 // Info, not Error: a client sending bytes the core
1136 // cleanly rejects is an ordinary, expected outcome of
1137 // accepting arbitrary input over HTTP, not an operational
1138 // problem with this instance. Fix round 1 on Task 5: this
1139 // used to be the ONLY branch, so a real database or
1140 // wasm-rebuild failure was also reported to the client as
1141 // "your bytes were bad" and logged where nobody would
1142 // think to look for an outage.
1143 h.logger.Info("docs: reject posted update", "sqid", doc.Sqid, "err", err)
1144 http.Error(w, rastrillo.T(r, "docs.error.badupdate"), http.StatusBadRequest)
1145 return
1146 }
1147 h.logger.Error("docs: apply posted update", "sqid", doc.Sqid, "doc_id", doc.ID, "err", err)
1148 http.Error(w, rastrillo.T(r, "docs.error.generic"), h.internalFailureStatus())
1149 return
1150 }
1151
1152 // Both of these happen only on a nil error, which is what makes
1153 // the seq trustworthy (design D4). An error here can be returned
1154 // over an already-committed row — ApplyUpdate's trailing
1155 // updated_at bump lives outside its transaction — and in that case
1156 // the client retries, writes a duplicate row Yjs integrates
1157 // idempotently, and the broadcast happens on the retry instead.
1158 w.Header().Set("Docs-Seq", strconv.FormatInt(seq, 10))
1159 h.hub.broadcast(doc.ID, seq)
1160
1161 w.WriteHeader(http.StatusNoContent)
1162}
1163
1164// parseSince reads the ?since= cursor off a request: the highest seq
1165// the client already holds, so the response can carry only what came
1166// after it. Absent means 0, which asks for the whole log — what the
1167// editor's first load wants.
1168//
1169// A malformed or negative value is a 400 rather than a silent 0.
1170// Treating "banana" as "send everything" would answer an expensive
1171// question nobody asked, and would hide a client bug behind a
1172// response that looks fine; a client that cannot say where it is
1173// should be told so.
1174func parseSince(w http.ResponseWriter, r *http.Request) (int64, bool) {
1175 raw := r.URL.Query().Get("since")
1176 if raw == "" {
1177 return 0, true
1178 }
1179 since, err := strconv.ParseInt(raw, 10, 64)
1180 if err != nil || since < 0 {
1181 http.Error(w, rastrillo.T(r, "docs.error.badsince"), http.StatusBadRequest)
1182 return 0, false
1183 }
1184 return since, true
1185}
1186
1187// updateIsClientFault classifies a Store.ApplyUpdate error: true means
1188// the core looked at the bytes the client just posted and refused
1189// them — a 400, the client's problem, and unremarkable enough to log
1190// at Info. False means everything else: a database error, a replay
1191// failure reading this document's own history, or a trap whose
1192// recovery itself failed (core.Handle.Apply's plain errors.Join
1193// branch — the document may now be unusable, not merely this one
1194// update) — none of which the client caused, all of which deserve a
1195// 500 and an Error-level log an operator will actually see.
1196//
1197// errors.As(err, &ur) is the load-bearing check, not the three core
1198// checks after it: only Store.ApplyUpdate's own call to
1199// core.Handle.Apply for THIS update wraps its error in
1200// *updateRejection (store.go) — a failure replaying this document's
1201// existing log calls the exact same core.Handle.Apply and would
1202// satisfy core.Recovered/core.Rejected/ErrUpdateLogFull just as
1203// easily, but is never wrapped in *updateRejection, so it can never
1204// reach the 400 branch by accident.
1205func updateIsClientFault(err error) bool {
1206 var ur *updateRejection
1207 if !errors.As(err, &ur) {
1208 return false
1209 }
1210 return core.Recovered(err) || core.Rejected(err) || errors.Is(err, core.ErrUpdateLogFull)
1211}
1212
1213// sharedNote labels a row the reader does not own. Empty for their own
1214// documents: a list where every row carries a badge is a list where none
1215// of them reads as information.
1216func sharedNote(r *http.Request, d *Document, mine int64) string {
1217 if d.OwnerID == mine {
1218 return ""
1219 }
1220 // A team document reads as the team's, whether or not the reader also
1221 // holds a grant on it: that is the wider of the two, and the true one.
1222 if d.Visibility == VisibilityTeam {
1223 return rastrillo.T(r, "docs.list.team")
1224 }
1225 return rastrillo.T(r, "docs.list.shared")
1226}
1227
1228// groupByRecency buckets docs — already newest-first, per Store.List
1229// — into recency groups without re-sorting: consecutive documents
1230// that share a bucket join the same group, and a new bucket starts a
1231// new group the moment recencyBucket's key changes from the previous
1232// document's. That is safe only because recencyBucket is monotonic in
1233// time (a later document's bucket never sorts before an earlier
1234// one's) AND docs is ordered by the exact same clock this function
1235// buckets and displays by (UpdatedAt) — Store.List orders by
1236// `updated_at DESC`, not CreatedAt, specifically so that holds. Fix
1237// round 2's bug was ordering by one column while bucketing by
1238// another: they agreed only because nothing yet moved UpdatedAt away
1239// from CreatedAt, and the moment ApplyUpdate started bumping
1240// UpdatedAt, an order-by-CreatedAt list would have produced duplicate
1241// group labels ("Today … Yesterday … Today") the instant an older
1242// document got a new update. See store_test.go's
1243// TestListOrdersByUpdatedAt.
1244func groupByRecency(r *http.Request, now time.Time, docs []*Document, thumb func(*Document) thumbView, mine int64) []docGroup {
1245 var groups []docGroup
1246 var key string
1247 for _, d := range docs {
1248 k, labelKey := recencyBucket(now, d.UpdatedAt)
1249 if len(groups) == 0 || k != key {
1250 groups = append(groups, docGroup{Label: rastrillo.T(r, labelKey)})
1251 key = k
1252 }
1253 g := &groups[len(groups)-1]
1254 g.Rows = append(g.Rows, docRow{
1255 SharedNote: sharedNote(r, d, mine),
1256 Href: "/d/" + d.Sqid,
1257 Title: d.Title,
1258 When: formatWhen(now, d.UpdatedAt),
1259 Thumb: thumb(d),
1260 })
1261 }
1262 return groups
1263}
1264
1265// recentShelf is how many of the newest documents the list shows as
1266// pages rather than rows: one row of them on a desktop column.
1267const recentShelf = 5
1268
1269// splitRecent takes the first n rows across groups, in order, for the
1270// shelf of pages at the top of the list, and returns the groups that
1271// remain for the rows below it. A group whose rows all went to the
1272// shelf is dropped; one split by the shelf keeps its label, so the
1273// rows under "Today" are still today's.
1274func splitRecent(groups []docGroup, n int) ([]docRow, []docGroup) {
1275 var recent []docRow
1276 var rest []docGroup
1277 for _, g := range groups {
1278 take := min(n-len(recent), len(g.Rows))
1279 recent = append(recent, g.Rows[:take]...)
1280 if take < len(g.Rows) {
1281 rest = append(rest, docGroup{Label: g.Label, Rows: g.Rows[take:]})
1282 }
1283 }
1284 return recent, rest
1285}
1286
1287// recencyBucket returns a stable bucket key and the catalog key for
1288// its label, comparing calendar days in UTC — Document.CreatedAt and
1289// UpdatedAt are both stored in UTC (Store.Create), and there is no
1290// per-viewer time zone to convert to yet (a signed-in viewer exists
1291// now, but nothing stores their zone). time.Truncate(24*time.Hour)
1292// lines up with the calendar day specifically because both arguments
1293// are UTC: the day never shifts under DST the way it can in a zone
1294// that observes it.
1295func recencyBucket(now, t time.Time) (key, labelKey string) {
1296 days := int(now.Truncate(24*time.Hour).Sub(t.Truncate(24*time.Hour)).Hours() / 24)
1297 switch {
1298 case days <= 0:
1299 return "today", "docs.list.group.today"
1300 case days == 1:
1301 return "yesterday", "docs.list.group.yesterday"
1302 case days <= 6:
1303 return "week", "docs.list.group.week"
1304 default:
1305 return "earlier", "docs.list.group.earlier"
1306 }
1307}
1308
1309// formatWhen renders t for a row's trailing timestamp: a time of day
1310// for today, otherwise a date, with the year appended only once t
1311// falls in a year other than now's.
1312//
1313// This is English-only, hardcoded Go layout strings rather than
1314// something Intl-backed, matching this app's single declared locale
1315// (Locales, above). datetime.js's date fields get away with the
1316// browser's own Intl for exactly this reason; there is no Go-side
1317// equivalent wired up here, so a second locale needs this to move
1318// rather than simply gaining a catalog entry.
1319func formatWhen(now, t time.Time) string {
1320 if now.Truncate(24 * time.Hour).Equal(t.Truncate(24 * time.Hour)) {
1321 return t.Format("3:04 PM")
1322 }
1323 if now.Year() == t.Year() {
1324 return t.Format("Jan 2")
1325 }
1326 return t.Format("Jan 2, 2006")
1327}
1328
1329// cleanTitle makes a title one line of text, whatever sent it: newlines,
1330// tabs and every other control character (and the Unicode line and
1331// paragraph separators) become spaces, a run of spaces becomes one, and
1332// the ends are trimmed. A title is a heading, a list row and a file name;
1333// a newline in it is never something the person meant to keep (Fable on
1334// #179).
1335func cleanTitle(s string) string {
1336 return strings.Join(strings.FieldsFunc(s, func(r rune) bool {
1337 return unicode.IsSpace(r) || unicode.IsControl(r) || r == '\u2028' || r == '\u2029'
1338 }), " ")
1339}
1340
1341func (h *handlers) rename(w http.ResponseWriter, r *http.Request) {
1342 doc, ok := h.getDocumentForUpdates(w, r)
1343 if !ok {
1344 return
1345 }
1346 actor, err := h.actor(r)
1347 if err != nil {
1348 h.fail(w, r, h.internalFailureStatus(), failStatus)
1349 return
1350 }
1351 r.Body = http.MaxBytesReader(w, r.Body, 16*1024)
1352 if err := r.ParseForm(); err != nil {
1353 h.fail(w, r, http.StatusBadRequest, failStatus)
1354 return
1355 }
1356 title := cleanTitle(r.PostFormValue("title"))
1357 if title == "" {
1358 title = rastrillo.T(r, "docs.document.untitled")
1359 }
1360 if len(title) > 1024 {
1361 h.fail(w, r, http.StatusBadRequest, failStatus)
1362 return
1363 }
1364 if err := h.store.Rename(r.Context(), actor, doc, title); err != nil {
1365 if errors.Is(err, ErrNotWritable) || errors.Is(err, gorm.ErrRecordNotFound) {
1366 h.fail(w, r, http.StatusNotFound, failDocument)
1367 return
1368 }
1369 h.fail(w, r, h.internalFailureStatus(), failStatus)
1370 return
1371 }
1372 // The native apps rename with a fetch and read 204. The bar's title
1373 // field is a plain form, so a browser is sent back to the document,
1374 // 303 so a reload never re-posts.
1375 if wantsNative(r) {
1376 w.WriteHeader(http.StatusNoContent)
1377 return
1378 }
1379 http.Redirect(w, r, "/d/"+doc.Sqid, http.StatusSeeOther)
1380}
1381