oficina / meet Public

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

Plain git — no account needed to clone.

Download

Download this file

1package calls
2
3// HTML error pages (shared chrome spec §3). Before this an unknown URL
4// answered chi's plain-text "404 page not found", with or without
5// Accept: text/html, and the handled error pages were titled "Something
6// went wrong" whatever had happened, a 404 included.
7//
8// Which answers are pages is decided by the request, not the route: a
9// page is rendered only when Accept names text/html, as every browser
10// navigation and form post does. The room's own fetches (the stream,
11// signal, ICE and info), the native app's JSON and the share form's JSON
12// answer never ask for HTML, so they keep plain answers. room.js reads
13// those by status (readRefusal), and the statuses are unchanged.
14//
15// A meeting that is missing, ended, or not yours is the same 404
16// (AGENTS.md: a row that isn't yours 404s, never 403s).
17
18import (
19 "fmt"
20 "net/http"
21 "net/url"
22 "runtime/debug"
23 "strings"
24
25 "amadan.net/oficina/estilo.git/chrome"
26 "amadan.net/rastrillo/rastrillo"
27 "github.com/go-chi/chi/v5"
28)
29
30// errorKind says which row of spec §3.2 a failure is.
31type errorKind int
32
33const (
34 // kindRoute: nothing here for you — an unknown address, or a page
35 // this session may not open (a guest outside /m/, a non-member on
36 // Settings). Both are "we can't find that page": which of the two it
37 // is must not be readable from outside.
38 kindRoute errorKind = iota
39 // kindMeeting: the meeting (or its invitation, or a peer in it) is
40 // missing, ended, or not shared with you.
41 kindMeeting
42 // kindStatus: the page for the status itself (5xx).
43 kindStatus
44 // kindTeam: team mode's retryable 503, when the roster could not be
45 // read within its lease (team_answers.go).
46 kindTeam
47)
48
49// errorWords is one row of §3.2: the title part, the heading, the body.
50type errorWords struct {
51 title, heading, body string
52}
53
54func errorCopy(status int, kind errorKind) errorWords {
55 switch {
56 case kind == kindTeam:
57 return errorWords{"Try again in a moment", "We couldn’t check your team access", "Calls couldn’t confirm you’re on this team just now. Try again in a moment."}
58 case status == http.StatusNotFound && kind == kindMeeting:
59 return errorWords{"Meeting not available", "This meeting isn’t available", "It may have ended, or it hasn’t been shared with you."}
60 case status == http.StatusNotFound:
61 return errorWords{"Page not found", "We can’t find that page", "The link may be out of date, or the page may have moved."}
62 case status == http.StatusForbidden:
63 return errorWords{"No access", "You don’t have access to this page", "Ask whoever runs this team if you think you should."}
64 case status == http.StatusServiceUnavailable:
65 return errorWords{"Calls is unavailable", "Calls is unavailable right now", "Try again in a few minutes."}
66 }
67 return errorWords{"Something went wrong", "Something went wrong", "Try again in a moment. If it keeps happening, quote the reference below."}
68}
69
70// wantsHTML reports whether the request asked for a page.
71func wantsHTML(r *http.Request) bool {
72 return strings.Contains(r.Header.Get("Accept"), "text/html")
73}
74
75// plainError is the answer to a request that did not ask for a page.
76func plainError(w http.ResponseWriter, status int) {
77 w.Header().Set("Cache-Control", "no-store")
78 http.Error(w, http.StatusText(status), status)
79}
80
81// ErrorPage answers status for a handler: a meeting-shaped 404 (almost
82// every handled 404 in Calls is about a meeting or its invitation), the
83// 5xx page with the reference rastrillo minted for the log line, or
84// plain text for a request that did not ask for a page. It is also
85// rastrillo.Options.ErrorPage, for panics outside the router.
86func (a *app) ErrorPage(w http.ResponseWriter, r *http.Request, status int, ref string) {
87 a.errorPage(w, r, status, kindMeeting, ref)
88}
89
90// notFound is the route-shaped 404: the router's own, and the guards'.
91func (a *app) notFound(w http.ResponseWriter, r *http.Request) {
92 a.errorPage(w, r, http.StatusNotFound, kindRoute, "")
93}
94
95// errorPage renders the page inside the normal layout, with the
96// viewer's own chrome (read optionally: an error page never signs
97// anybody out or creates anything).
98func (a *app) errorPage(w http.ResponseWriter, r *http.Request, status int, kind errorKind, ref string) {
99 if !wantsHTML(r) {
100 plainError(w, status)
101 return
102 }
103 c := errorCopy(status, kind)
104 page := chrome.ErrorPage{
105 Status: status,
106 Title: c.heading,
107 Body: c.body,
108 Home: chrome.Link{Href: "/", Label: "Go to Calls"},
109 }
110 // Try again is the same URL, and only for a GET: re-sending a POST
111 // from an error page is the one thing it must never do.
112 if status >= 500 && r.Method == http.MethodGet {
113 page.Home = chrome.Link{Href: r.URL.RequestURI(), Label: "Try again"}
114 }
115 if ref != "" {
116 page.Ref, page.RefLabel = ref, "Reference:"
117 }
118 if back := sameOriginReferer(r, a.cfg.Origin); back != "" && status < 500 {
119 page.Back = &chrome.Link{Href: back, Label: "Back"}
120 }
121 var buf strings.Builder
122 data := a.page(r, titled(c.title), map[string]any{"Error": page})
123 if err := pages["errors"].ExecuteTemplate(&buf, "layout", data); err != nil {
124 a.logger.Error("calls: render error page", "err", err)
125 plainError(w, status)
126 return
127 }
128 w.Header().Set("Cache-Control", "no-store")
129 w.Header().Set("Content-Type", "text/html; charset=utf-8")
130 w.WriteHeader(status)
131 _, _ = w.Write([]byte(buf.String()))
132}
133
134// sameOriginReferer is the page a person came from, when it is this app
135// and not this page: rastrillo's rule for the error page's Back link. An
136// unchecked Referer is an open redirect with better manners.
137func sameOriginReferer(r *http.Request, origin string) string {
138 raw := r.Header.Get("Referer")
139 if raw == "" || origin == "" {
140 return ""
141 }
142 u, err := url.Parse(raw)
143 if err != nil || u.User != nil || u.Scheme+"://"+u.Host != origin {
144 return ""
145 }
146 back := u.EscapedPath()
147 if u.RawQuery != "" {
148 back += "?" + u.RawQuery
149 }
150 // Never an invitation path: the Back link would copy the capability
151 // into this page.
152 if strings.HasPrefix(back, "/j/") {
153 return ""
154 }
155 if !strings.HasPrefix(back, "/") || strings.HasPrefix(back, "//") || back == r.URL.RequestURI() {
156 return ""
157 }
158 return back
159}
160
161// methodNotAllowed is the router's MethodNotAllowed. A GET or HEAD to a
162// path that only takes a POST (somebody opening /signout from history)
163// is the same 404 page as an unknown route: to a person there is no
164// page there. Any other method gets 405 in plain text, with the Allow
165// header set here — chi's default sets it, a custom handler does not.
166func (a *app) methodNotAllowed(routes chi.Routes) http.HandlerFunc {
167 return func(w http.ResponseWriter, r *http.Request) {
168 var allowed []string
169 for _, m := range []string{http.MethodGet, http.MethodHead, http.MethodPost, http.MethodPut, http.MethodPatch, http.MethodDelete} {
170 if routes.Match(chi.NewRouteContext(), m, r.URL.Path) {
171 allowed = append(allowed, m)
172 }
173 }
174 get := false
175 for _, m := range allowed {
176 get = get || m == http.MethodGet
177 }
178 if (r.Method == http.MethodGet || r.Method == http.MethodHead) && !get {
179 a.notFound(w, r)
180 return
181 }
182 w.Header().Set("Allow", strings.Join(allowed, ", "))
183 http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed)
184 }
185}
186
187// routePattern is the matched route, "/m/{sqid}" rather than the path it
188// matched: safe to log whatever the path held (/j/ is a capability).
189func routePattern(r *http.Request) string {
190 if rc := chi.RouteContext(r.Context()); rc != nil && rc.RoutePattern() != "" {
191 return rc.RoutePattern()
192 }
193 return "(unrouted)"
194}
195
196// recoverToErrorPage turns a panic in a handler into the 500 page with a
197// reference, logged with the stack under the same reference. The page
198// reads the session itself, so it shows the viewer's own chrome
199// wherever in the router the panic happened. Panics outside the router
200// reach rastrillo.Serve's own recoverer through Options.ErrorPage.
201func (a *app) recoverToErrorPage(next http.Handler) http.Handler {
202 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
203 defer func() {
204 v := recover()
205 if v == nil {
206 return
207 }
208 if v == http.ErrAbortHandler {
209 panic(v)
210 }
211 ref := rastrillo.NewRef()
212 // The value is logged as its type only: a panic raised with a
213 // meeting title in it would be a leak of its own.
214 a.logger.Error("calls: panic", "ref", ref, "route", routePattern(r), "panic", fmt.Sprintf("%T", v), "stack", string(debug.Stack()))
215 a.errorPage(w, r, http.StatusInternalServerError, kindStatus, ref)
216 }()
217 next.ServeHTTP(w, r)
218 })
219}
220