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 "database/sql"
5 "encoding/json"
6 "log/slog"
7 "net/http"
8 "strings"
9 "time"
10
11 "amadan.net/oficina/home/connect"
12 "amadan.net/rastrillo/rastrillo"
13 "amadan.net/rastrillo/rastrillo/sessions"
14
15 // The one import left on rastrillo's pre-move path, on purpose:
16 // rastrillo/native's server (2a5d07b, and its main) still takes a
17 // github.com/carlosframework/rastrillo *sessions.Sessions. Both
18 // sessions packages read and write the same sessions table, so a
19 // session native sign-in mints is an ordinary session to the app
20 // (native_exchange_test.go). Move this to
21 // amadan.net/rastrillo/rastrillo/sessions when native/server moves;
22 // TestNoPreMoveRastrillo forbids every other import of the old path.
23 presessions "github.com/carlosframework/rastrillo/sessions"
24)
25
26// newNativeSessions is the sessions handle rastrillo/native's server
27// approves and mints with, over the app's own database.
28func newNativeSessions(db *sql.DB, origin string, logger *slog.Logger) (*presessions.Sessions, error) {
29 return presessions.New(presessions.Config{DB: db, Origin: origin, SigninPath: "/signin", Logger: logger})
30}
31
32// nativeApprover is the require rastrillo/native's browser approval runs
33// (/native/authorize, and /native/exchange's re-check of the approved
34// cookie): requireCurrent, with a native or native-web session refused as
35// signed out. The exchange mints a copy of the approving session, same
36// method and a fresh created_at, so a native session that could approve
37// would renew itself past connect.NativeLifetime with no Home grant behind
38// it, outliving a revoked grant or "Sign out all devices". Only a browser
39// sign-in approves another device (native_approval_test.go). Streams and
40// the sign-in return keep requireCurrent itself.
41func nativeApprover(require func(http.Handler) http.Handler) func(http.Handler) http.Handler {
42 return func(next http.Handler) http.Handler {
43 return require(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
44 s, ok := sessions.Current(r)
45 if !ok || s.Method == connect.NativeMethod || s.Method == connect.NativeWebMethod {
46 http.Error(w, rastrillo.T(r, "docs.error.generic"), http.StatusUnauthorized)
47 return
48 }
49 next.ServeHTTP(w, r)
50 }))
51 }
52}
53
54func wantsNative(r *http.Request) bool {
55 return strings.Contains(r.Header.Get("Accept"), "application/json")
56}
57
58func nativeJSON(w http.ResponseWriter, r *http.Request, status int, value any) {
59 body, err := json.Marshal(value)
60 if err != nil {
61 http.Error(w, rastrillo.T(r, "docs.error.generic"), http.StatusInternalServerError)
62 return
63 }
64 w.Header().Set("Content-Type", "application/json")
65 w.Header().Set("Cache-Control", "no-store")
66 w.Header().Add("Vary", "Accept")
67 _ = writeGuardedBody(w, r, status, body)
68}
69
70func (h *handlers) nativeList(w http.ResponseWriter, r *http.Request) {
71 actor, err := h.actor(r)
72 if err != nil {
73 http.Error(w, rastrillo.T(r, "docs.error.generic"), http.StatusUnauthorized)
74 return
75 }
76 var documents []*Document
77 if query := strings.TrimSpace(r.URL.Query().Get("q")); query != "" {
78 documents, err = h.store.SearchFor(r.Context(), actor, query)
79 } else {
80 documents, err = h.store.ListFor(r.Context(), actor)
81 }
82 // The Mac and iPhone apps render no partial notice, so under Unknown
83 // this list is unavailable rather than short, as the dashboard feed is
84 // (Fable on oficina/docs #100). Asked after listing, from the same
85 // Access. A "partial" field is the better contract once the clients
86 // render it.
87 if a, ok := r.Context().Value(accessContextKey{}).(*requestAccess); err == nil && ok && a != nil && a.Partial() {
88 err = errTeamUnavailable
89 }
90 if err != nil {
91 http.Error(w, rastrillo.T(r, "docs.error.generic"), h.internalFailureStatus())
92 return
93 }
94 type item struct {
95 Sqid string `json:"sqid"`
96 Title string `json:"title"`
97 UpdatedAt time.Time `json:"updated_at"`
98 Shared bool `json:"shared"`
99 Thumbnail thumbView `json:"thumbnail"`
100 }
101 items := make([]item, 0, len(documents))
102 thumbnail := h.thumbnailer(r.Context())
103 for _, doc := range documents {
104 items = append(items, item{doc.Sqid, doc.Title, doc.UpdatedAt, doc.OwnerID != actor.PersonID, thumbnail(doc)})
105 }
106 nativeJSON(w, r, 200, map[string]any{"documents": items, "can_create": h.member(r)})
107}
108
109// The authentication middleware is rerun against the cookie before every
110// stream write. A context captured when the stream opened is not current proof.
111func (h *handlers) nativeStreamAllowed(r *http.Request, sqid string) bool {
112 if h.requireCurrent == nil {
113 return true
114 } // isolated handler fixtures
115 allowed := false
116 h.requireCurrent(http.HandlerFunc(func(_ http.ResponseWriter, fresh *http.Request) {
117 actor, err := h.actor(fresh)
118 if err != nil {
119 return
120 }
121 _, err = h.store.GetFor(fresh.Context(), actor, sqid)
122 allowed = err == nil
123 })).ServeHTTP(nativeDiscard{}, r)
124 return allowed
125}
126
127type nativeDiscard struct{}
128
129func (nativeDiscard) Header() http.Header { return make(http.Header) }
130func (nativeDiscard) Write(p []byte) (int, error) { return len(p), nil }
131func (nativeDiscard) WriteHeader(int) {}
132