oficina / docs Public

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

Plain git — no account needed to clone.

Download

Download this file

1// Package docs is the CARLOS Docs rastrillo app: its database handle,
2// router and (for now, one) page. Follows rastrillo's SKILL.md app
3// shape (models.go, app.go, handlers.go, render.go, cmd/docs/main.go),
4// adapted into a New(cfg) (*App, error) constructor + App.Handler()
5// rather than SKILL.md's illustrative App(d, origin, logger)
6// (*http.ServeMux, error) function, because the task that specified
7// this app also specified the test harness (docs.NewForTest,
8// app.Handler().ServeHTTP) that every later task's tests depend on —
9// the constructor name and shape follow that harness; everything else
10// below follows SKILL.md.
11package docs
12
13import (
14 "amadan.net/oficina/estilo.git/sky"
15 connectlinks "amadan.net/oficina/home/connect/linkstore"
16 "context"
17 "errors"
18 "fmt"
19 "log/slog"
20 "net/http"
21 "net/url"
22 "strings"
23 "time"
24
25 "amadan.net/oficina/estilo.git/brand"
26 "amadan.net/oficina/estilo.git/chrome"
27 "amadan.net/oficina/estilo.git/theme"
28 "amadan.net/oficina/home/dashboard"
29 "amadan.net/oficina/home/handoff"
30 "amadan.net/oficina/home/teammode"
31 "amadan.net/oficina/suite/server"
32 nativeauth "amadan.net/rastrillo/native/server"
33 "amadan.net/rastrillo/rastrillo"
34 rauth "amadan.net/rastrillo/rastrillo/auth"
35 "amadan.net/rastrillo/rastrillo/db"
36 "amadan.net/rastrillo/rastrillo/mail"
37 "amadan.net/rastrillo/rastrillo/migrate"
38 "amadan.net/rastrillo/rastrillo/sessions"
39 "github.com/carlosframework/docs/internal/docs/linkstore"
40 "github.com/go-chi/chi/v5"
41
42 "github.com/carlosframework/docs/internal/core"
43
44 "amadan.net/oficina/estilo.git/googleimport"
45)
46
47// Config configures New.
48type Config struct {
49 // WarmHandle keeps a replayed document handle between update POSTs
50 // ($DOCS_WARM_HANDLE, warm.go; the live-push spec's §3.5 and §8). Off,
51 // every POST replays the document, as it always has. Off by default
52 // until slice 1a is proven on production, then on.
53 WarmHandle bool
54 // LivePush lets a stream opened with push=1 carry the update bytes
55 // ($DOCS_LIVE_PUSH, push.go; the live-push spec's §3.1-§3.4, §5, §8).
56 // Off, push=1 is ignored and every client is on today's path. Off by
57 // default.
58 LivePush bool
59
60 AgentIssuer string
61 AgentTeam string
62 Home *HomeConfig
63 // Directory is the hub directory origin ($HOME_DIRECTORY_ORIGIN): the
64 // app switcher's "All apps". Empty means no switcher.
65 Directory string
66 Team *TeamConfig
67
68 // GoogleImport is the optional Google Drive chooser on the import
69 // page (estilo's googleimport): a public OAuth client ID, a public
70 // Picker API key and the Cloud project number, all three or none.
71 // None leaves the ordinary file import as it is; a partial or
72 // malformed setting refuses to start. cmd/docs reads
73 // $DOCS_GOOGLE_CLIENT_ID, $DOCS_GOOGLE_API_KEY and $DOCS_GOOGLE_APP_ID.
74 GoogleImport googleimport.Config
75
76 // DBPath is the SQLite file New opens via rastrillo's db package.
77 DBPath string
78 ContentKey string
79
80 // Env is "development" or "production" ("" defaults to
81 // "production"). It gates two fail-closed defaults below — Origin
82 // and (auth.go) InstanceKey/Mailer — and nothing else: the
83 // development-only stand-in identity that used to live in
84 // devauth.go is gone (fix round 1 on Task 1 — real sign-in made
85 // it dead code the moment RequireSession started guarding every
86 // route, and it was deleted rather than left as an unreachable
87 // trap for whoever next read "DevAuth" and assumed it still did
88 // something). cmd/docs/main.go sources this from an explicit
89 // -env flag, deliberately independent of any identity flag — Env
90 // choosing "log mail instead of sending it" is not the same
91 // decision as "who can sign in", and conflating the two is
92 // exactly what fix round 1 un-did. $DOCS_ENV is consulted too,
93 // but — fix round 2, after that round's own $DOCS_ENV fallback
94 // turned out to reopen the same hole — never for "development"
95 // itself: only the literal flag may ever select it
96 // (cmd/docs/main.go's chooseEnv has the full reasoning).
97 Env string
98
99 // Origin is this app's own origin (scheme://host[:port], no path),
100 // what csrf.Protect (rastrillo SKILL.md §5) uses as its fallback
101 // same-origin evidence. Fix round 3 corrected a wrong model of
102 // what that check actually does — see csrf.Protect's own doc
103 // comment (rastrillo v0.21.0's csrf/csrf.go): it checks
104 // Sec-Fetch-Site FIRST when a browser sends it, which every
105 // current browser does on a state-changing request —
106 // "same-origin"/"none" pass immediately, anything else is refused
107 // immediately, and Origin is never consulted in that path at all.
108 // Only when Sec-Fetch-Site is entirely absent (a legacy browser, or
109 // a non-browser client such as curl) does the check fall back to
110 // comparing the request's Origin or Referer header against this
111 // string exactly. So a wrong-but-nonempty Origin does NOT make a
112 // real browser's genuine same-origin POST fail, and it does NOT
113 // open up a genuine cross-site request either — both of those are
114 // decided by Sec-Fetch-Site alone, never by this string. What a
115 // wrong Origin actually breaks is the legacy fallback path, and it
116 // breaks it silently: a real client that happens to omit
117 // Sec-Fetch-Site gets wrongly rejected, or — if that comparison
118 // were ever loosened or removed — stops being checked at all.
119 // Neither shows up in ordinary manual testing with a real browser,
120 // which is exactly why getting this right cannot be verified by
121 // "the page loaded and the form worked."
122 //
123 // Empty is allowed only when Env is "development" (New falls back
124 // to DefaultOrigin there, for tests and local convenience); with
125 // any other Env, empty is a startup refusal — see New.
126 //
127 // cmd/docs/main.go wires this from $DOCS_ORIGIN, the same
128 // "<APP>_ORIGIN" convention rastrillo's own `new` scaffold uses
129 // (cmd/rastrillo/new.go's mainTemplate) — the platform's real
130 // per-instance origin (spec §9.2's <app>.<sqid>.oncarlos.com)
131 // is set there at deploy time. On the unix-socket/LISTEN_FDS
132 // activation path there is no -addr to derive a fallback from, so
133 // leaving $DOCS_ORIGIN unset must fail loudly rather than quietly
134 // configuring the app with a string that has nothing to do with
135 // where it is actually reachable — that is exactly what the
136 // Env-gated default below refuses to do.
137 //
138 // A non-empty value is trimmed and then validated (validateOrigin)
139 // rather than trusted as-is: whitespace-only is not "empty" by a
140 // bare == "" check, and would otherwise sail past the guard above
141 // with nothing catching it until the legacy fallback path above
142 // tried, and failed, to match it against anything real.
143 Origin string
144
145 // InstanceKey seals rastrillo/auth's pending-link blob (an HMAC
146 // key — auth.Config.InstanceKey's own doc comment explains why an
147 // empty one is dangerous, not just inconvenient: it hashes to one
148 // fixed, publicly computable value, identical across every
149 // deployment that made the same mistake). Sourced from
150 // $DOCS_INSTANCE_KEY (cmd/docs/main.go), the same "read in main,
151 // validated in New" split Origin above uses.
152 //
153 // Empty is allowed only when Env is "development" (New falls back
154 // to a fixed, non-secret development value — see devInstanceKey in
155 // auth.go); with any other Env, empty is a startup refusal, the
156 // same fail-closed shape as Origin.
157 InstanceKey string
158
159 // Mailer delivers the magic-link email. Nil is fine only in
160 // development: New wraps rastrillo/mail's logging fallback so the
161 // link lands in the log, clearly marked, and TestSignIn (testing.go)
162 // can read it back — no mail server required for
163 // scripts/run-dev.sh or for tests. Outside development, nil is a
164 // startup refusal: a sign-in that cannot send its link is not
165 // sign-in, and silently falling back to logging a live credential
166 // in a real deployment's log is exactly the mistake that fallback
167 // exists to flag, not absorb. cmd/docs/main.go builds this with
168 // rastrillo/mail.FromCarlos (platformMailer) when CARLOS mail
169 // submission is on ($CARLOS_MAIL=submit) or $DOCS_SMTP_HOST and
170 // $DOCS_SMTP_FROM are both set, and leaves it nil otherwise — New.buildMailer (auth.go) is
171 // what turns "nil outside development" into the refusal, the same
172 // split Origin/InstanceKey use.
173 Mailer mail.Sender
174
175 // AllowedAddresses is the comma-separated allowlist of the only
176 // addresses this instance admits — $DOCS_ALLOWED_ADDRESSES
177 // (cmd/docs/main.go), the same "<APP>_..." env-var convention
178 // Origin and the SMTP vars above use. Compared case-insensitively,
179 // each entry trimmed of surrounding whitespace (auth.go's
180 // normalizeAddress) — a real config file has spaces after its
181 // commas, and people type capitals into an email field.
182 //
183 // The sign-in mail queue restricts email delivery (mailqueue.go,
184 // listAdmits), and rauth.Config.Authorize
185 // checks verified identities before minting a session. Classification
186 // does not depend on admission, so an OAuth start cannot reveal membership.
187 //
188 // Empty is allowed only when Env is "development"
189 // (resolveAllowlist below defaults that to "admit everyone", so
190 // TestSignIn and scripts/run-dev.sh keep working with no setup of
191 // their own) — anywhere else, empty is a startup refusal; see
192 // resolveAllowlist's own doc comment for why that beats the
193 // alternative of silently admitting nobody.
194 AllowedAddresses string
195
196 // SampleDocuments opts this instance into seeding a brand-new
197 // person's very first sign-in with CARLOS Docs' own sample
198 // documents (seed.go's Seed, six of them) — the fix for "Paul
199 // signed in to a live instance and saw an empty list": the sample
200 // documents docs.Seed already wrote were never reachable on a
201 // deployed instance, because -seed is gated to Env ==
202 // "development" (main.go's own doc comment, unchanged by this
203 // field) and a deployed instance never runs with that flag.
204 // Documents are owner-scoped (Document.OwnerID, owned() in
205 // store.go) and a boot-time seed has no person to own anything, so
206 // this switches seeding from a boot-time, instance-wide event to a
207 // per-person one — see Store.EnsurePerson's own doc comment for
208 // exactly where that happens and why there, not "the list is
209 // empty" (a person who deletes every sample document must not get
210 // them back).
211 //
212 // Sourced from $DOCS_SAMPLE_DOCUMENTS (cmd/docs/main.go), the same
213 // "<APP>_..." convention every other setting on this struct uses.
214 // Parsed by parseSampleDocuments below, which accepts a small,
215 // case-insensitive truthy set ("1", "true", "yes") and treats
216 // everything else — unset, empty, or a typo alike — as off.
217 // Default OFF: a real team instance must never get six invented
218 // documents about a reading room and an allotment committee just
219 // because nobody thought to unset something.
220 //
221 // Deliberately NOT fail-closed the way Origin/InstanceKey/
222 // AllowedAddresses above are: those three guard who can sign in
223 // and what seals a session, where a value New cannot make sense of
224 // silently taking the permissive branch would be a real security
225 // regression, so New refuses to start rather than guess. This
226 // setting only decides whether a new person's document list starts
227 // with six sample documents or zero — cosmetic content, not a
228 // security control — so an unparseable value here is read as "off"
229 // and New boots anyway. A platform whose env var block has a typo
230 // in $DOCS_SAMPLE_DOCUMENTS should get an empty list, silently, the
231 // same outcome as never having set it at all, not a refusal to
232 // serve any traffic over a setting that was never load-bearing for
233 // safety in the first place.
234 SampleDocuments string
235
236 // SuiteConsumers is $DOCS_SUITE_CONSUMERS (server.EnvSuffix), the
237 // siblings allowed to call the suite routes (spec §8.2.2; suite §6.5):
238 // strict JSON, [{"consumer_id":"memoria","tokens":[{"epoch":1,
239 // "sha256":"<64 hex>"}]}], each token held only as its SHA-256. Empty
240 // means no consumers and no /suite/ routes at all; anything malformed
241 // is a startup refusal, so a typo never boots an instance that quietly
242 // serves nobody — or, worse, one that looks configured and is not.
243 SuiteConsumers string
244
245 // Logger defaults to slog.Default().
246 Logger *slog.Logger
247}
248
249// parseSampleDocuments interprets raw the way Config.SampleDocuments'
250// own doc comment describes: a small, case-insensitive truthy set
251// means on, and everything else means off. See that doc comment for
252// why this is deliberately not fail-closed like resolveInstanceKey/
253// resolveAllowlist (auth.go) just below use for their own settings.
254func parseSampleDocuments(raw string) bool {
255 switch strings.ToLower(strings.TrimSpace(raw)) {
256 case "1", "true", "yes":
257 return true
258 default:
259 return false
260 }
261}
262
263// DefaultOrigin is Config.Origin's fallback when empty — see its doc
264// comment. Exported so a caller that needs to know what origin this
265// app is protecting itself against (NewForTest's callers, notably)
266// does not have to duplicate the literal.
267const DefaultOrigin = "http://localhost:8080"
268
269// validateOrigin reports whether origin (already trimmed by the
270// caller — New) is something csrf.Protect's legacy Origin/Referer
271// fallback can actually use: an absolute http(s) URL naming a scheme
272// and a host and nothing else. "Nothing else" is checked
273// deliberately, not just "parses as a URL" — url.Parse happily
274// accepts a bare path, a value carrying a query string, or one with
275// embedded userinfo, none of which a same-origin check has any
276// business being handed, and none of which would ever equal a real
277// browser's Origin header. An app that accepted one would boot
278// looking entirely healthy — a modern browser's genuine same-origin
279// traffic passes on Sec-Fetch-Site alone and never reaches this
280// string at all (Config.Origin's own doc comment) — and only fail,
281// silently, on whatever still uses the legacy fallback.
282func validateOrigin(origin string) error {
283 if origin == "" {
284 return errors.New("origin is blank")
285 }
286 u, err := url.Parse(origin)
287 if err != nil {
288 return fmt.Errorf("origin %q does not parse as a URL: %w", origin, err)
289 }
290 if u.Scheme != "http" && u.Scheme != "https" {
291 return fmt.Errorf("origin %q must have an http or https scheme", origin)
292 }
293 // u.Host != "" is not enough: fix round 2's own bug. "http://:8099"
294 // — exactly what -addr :8099 derives (main.go's "http://"+opts.Addr,
295 // the plan's own example invocation) — has a non-empty Host
296 // (":8099") but an empty Hostname(); Host merely means "there was
297 // something between // and the next / (or the end)", not "there is
298 // a host". A reviewer booted a production-Env binary on this exact
299 // origin and watched it serve. Hostname() is what actually strips
300 // the port and answers "is there a host here at all".
301 if u.Hostname() == "" {
302 return fmt.Errorf("origin %q has no host", origin)
303 }
304 if u.Path != "" || u.RawQuery != "" || u.Fragment != "" || u.User != nil {
305 return fmt.Errorf("origin %q must be scheme://host[:port] only, with no path, query, fragment or userinfo", origin)
306 }
307 return nil
308}
309
310// App is the CARLOS Docs rastrillo app.
311type App struct {
312 cfg Config
313 db *db.DB
314 mux *http.ServeMux
315 logger *slog.Logger
316 core *core.Runtime
317 store *Store
318 handlers *handlers
319 mailRecorder *recordingMailer // nil outside development; see auth.go
320 signinMail *mailQueue // sign-in links, sent after the response
321 // suite is the producer New mounted (or would have, with consumers), so
322 // a test drives the one New built rather than assembling its own.
323 suite *suiteProducer
324}
325
326// Drain ends every open live-update stream and refuses new ones. Call it
327// when the process is told to stop, before or as the HTTP server's
328// graceful shutdown begins: that shutdown waits for every request in
329// progress, cancels none, and so otherwise waits out its whole deadline on
330// any editor that has a document open (hub.drain). Safe to call more
331// than once.
332func (a *App) Drain() {
333 a.handlers.hub.drain()
334 // Every warm handle goes, and no new one is kept (warm.go, rule 6).
335 a.handlers.store.warm.close(context.Background())
336}
337
338// BootSchema is everything New applies at boot, in apply order.
339// migrate.Merge's argument order is apply order (rastrillo SKILL.md
340// §2): sessions.Schema before auth.Schema — auth's own backfill
341// migration reads the sessions table — before this app's own Schema
342// (models.go).
343//
344// linkstore.Schema is Docs' retired link table, which every database has
345// applied; connect's link schema follows the handoff's. Docs' rows move
346// into connect's table at boot (home_links_move.go).
347var BootSchema = migrate.Merge(migrate.MustFromFS(dashboard.Migrations, "oficina_dashboard"), sessions.Schema, authSchema, Schema, linkstore.Schema, migrate.MustFromFS(handoff.Migrations, "oficina_handoff"), migrate.MustFromFS(connectlinks.Migrations, connectlinks.SchemaNamespace))
348
349// New opens the database, applies migrations and wires the router. It
350// is rastrillo SKILL.md's app.go shape: db.Open for the SQLite handle,
351// migrate.Apply once at boot, a chi router wrapped as an
352// *http.ServeMux so httptest exercises the real router, csrf.Protect
353// mounted app-wide (SKILL.md §5), rastrillo/auth (auth.go) guarding
354// every document route behind a real, per-person magic-link sign-in.
355func New(cfg Config) (*App, error) {
356 logger := cfg.Logger
357 if logger == nil {
358 logger = slog.Default()
359 }
360 if cfg.Env == "" {
361 cfg.Env = "production"
362 }
363
364 // Fail closed, loudly: an empty Origin defaults to DefaultOrigin
365 // only in development (tests via NewForTest, a person running
366 // scripts/run-dev.sh). Anywhere else — Env left at its "production"
367 // default very much included — an empty Origin is a startup
368 // refusal, not a silent fallback to a placeholder whose only real
369 // effect is on csrf.Protect's legacy Origin/Referer fallback path
370 // (Config.Origin's own doc comment explains why that path, not
371 // "every request", is what a wrong string actually touches). This
372 // is the same fail-closed shape InstanceKey and Mailer use below
373 // (auth.go): exactly one string ("development") is ever treated
374 // as "safe to default", checked before anything else opens.
375 //
376 // cfg.Origin == "" alone is not the right test: a whitespace value
377 // like $DOCS_ORIGIN=" " is non-empty, so it would sail past that
378 // check. Nothing about a modern browser's own traffic would look
379 // wrong — Sec-Fetch-Site: same-origin passes without this string
380 // ever being read — so the only visible symptom would be the
381 // legacy fallback path failing to match literal whitespace against
382 // anything real, for whichever client still exercises it. That
383 // fails safe on that one path, but silently and late (at request
384 // time, for whoever hits it), not at boot where a malformed origin
385 // belongs. validateOrigin below rejects that and any other value
386 // that cannot possibly be what csrf.Protect needs (no scheme, no
387 // host, a stray path/query/fragment/userinfo) before New ever
388 // returns a listening app.
389 trimmedOrigin := strings.TrimSpace(cfg.Origin)
390 switch {
391 case trimmedOrigin == "" && cfg.Env != "development":
392 return nil, fmt.Errorf("docs: Config.Origin is empty and Env is %q, not %q — refusing to start with an unset origin; set $DOCS_ORIGIN to this instance's real origin", cfg.Env, "development")
393 case trimmedOrigin == "":
394 cfg.Origin = DefaultOrigin
395 default:
396 if err := validateOrigin(trimmedOrigin); err != nil {
397 return nil, fmt.Errorf("docs: Config.Origin is invalid: %w", err)
398 }
399 cfg.Origin = trimmedOrigin
400 }
401
402 // Resolved before anything else opens — same fail-closed shape as
403 // Origin above: a deployment that cannot seal a
404 // pending link, or cannot send one, refuses to start rather than
405 // booting into a broken or (worse) silently-logging-credentials
406 // sign-in. See auth.go.
407 homeSettings, err := validatedHomeConfig(cfg.Home, cfg.Origin)
408 if err != nil {
409 return nil, err
410 }
411 teamSettings, err := validatedTeamConfig(cfg.Team, homeSettings, cfg.Origin)
412 if err != nil {
413 return nil, err
414 }
415 agentVerifier, err := validatedAgentConfig(cfg, homeSettings, teamSettings)
416 if err != nil {
417 return nil, err
418 }
419 instanceKey, err := resolveInstanceKey(cfg)
420 if err != nil {
421 return nil, err
422 }
423 mailer, mailRecorder, err := buildMailer(cfg, logger)
424 if err != nil {
425 return nil, err
426 }
427 // Same fail-closed shape again: an instance with nobody configured
428 // to sign in either refuses to start (outside development) or, in
429 // development, admits everyone — never a silent "admits nobody"
430 // that would boot looking healthy. See resolveAllowlist's own doc
431 // comment for the full reasoning.
432 list, err := resolveAllowlist(cfg)
433 if err != nil {
434 return nil, err
435 }
436 // Parsed before anything opens: a malformed consumer list refuses boot.
437 // The error names no token, only that the list is not the agreed shape.
438 consumers, err := server.ParseConsumers(cfg.SuiteConsumers)
439 if err != nil {
440 return nil, fmt.Errorf("docs: $DOCS_SUITE_CONSUMERS: %w", err)
441 }
442
443 cipher, err := newContentCipher(cfg.ContentKey, cfg.Env)
444 if err != nil {
445 return nil, err
446 }
447 if err := cfg.GoogleImport.Validate(); err != nil {
448 return nil, err
449 }
450
451 d, err := db.Open(cfg.DBPath, logger)
452 if err != nil {
453 return nil, fmt.Errorf("docs: open database: %w", err)
454 }
455
456 // The marker is read before any migration: an activated database
457 // refuses to boot without team configuration, or with another binding.
458 var settings *teammode.Settings
459 if teamSettings != nil {
460 settings = teamSettings.Settings
461 }
462 schema, err := teamState.BootSchema(context.Background(), d.Writer(), settings, BootSchema, TeamBootSchema)
463 if err != nil {
464 d.Close()
465 return nil, errTeamConfig
466 }
467 if _, err := migrate.Apply(context.Background(), d, schema); err != nil {
468 d.Close()
469 return nil, fmt.Errorf("docs: apply migrations: %w", err)
470 }
471
472 state, err := readContentSealing(context.Background(), d.G, cipher)
473 if err == nil && state != nil {
474 err = requireSealedContent(context.Background(), d.G)
475 }
476 if err != nil {
477 d.Close()
478 return nil, err
479 }
480 if state == nil {
481 logger.Error("docs: content sealing not activated", "content_encoding", 0, "key_fingerprint", cipher.fingerprint)
482 }
483
484 // One Runtime for the process (core.New compiles the wasm module
485 // once — expensive; instantiating a per-document Handle from it is
486 // not), shared by every document's Store.replay.
487 rt, err := core.New(context.Background())
488 if err != nil {
489 d.Close()
490 return nil, fmt.Errorf("docs: start core runtime: %w", err)
491 }
492 store := NewStore(d.G, rt, parseSampleDocuments(cfg.SampleDocuments), logger)
493 if cfg.WarmHandle {
494 store.warm = newWarmCache()
495 }
496 if store.logEpoch, err = loadLogEpoch(context.Background(), d.G, cfg.DBPath); err != nil {
497 rt.Close(context.Background())
498 d.Close()
499 return nil, err
500 }
501 if state != nil {
502 store.content = cipher
503 }
504
505 // A grant admits its holder. Wired here rather than inside
506 // resolveAllowlist because the allowlist is resolved before the store
507 // exists — deliberately, so a misconfigured allowlist refuses to boot
508 // before anything else is built. See allowlist.granted for why an
509 // unredeemable invitation is the failure worth avoiding.
510 // The sample library is for members. A guest admitted by a grant is
511 // visiting, not moving in.
512 store.seedOnlyMembers = list.configured
513 // The team rung's readers in lone shape: members, never guests.
514 store.members = list.configured
515 // Home: connect's Bridge, then the one-time move of Docs' own links
516 // into connect's table (home_links_move.go). connect.New has swept
517 // already, nothing else is running, and the team census below reads
518 // the moved table.
519 var home *homeRoutes
520 if homeSettings != nil {
521 if home, err = newHome(homeSettings, cfg.Origin, d.Writer(), store, teamSettings != nil); err == nil {
522 err = moveLinksOntoConnect(context.Background(), d.Writer(), home.bridge)
523 }
524 if err != nil {
525 rt.Close(context.Background())
526 d.Close()
527 return nil, err
528 }
529 }
530 if teamSettings != nil {
531 store.team, err = newTeamRuntime(context.Background(), teamSettings, d.Writer(), homeSettings)
532 if err != nil {
533 rt.Close(context.Background())
534 d.Close()
535 return nil, err
536 }
537 }
538
539 list.granted = func(address string) (bool, error) {
540 // A short deadline rather than context.Background(): this runs on
541 // the sign-in path and now on every request (requireAdmission), so
542 // a stalled query must fail rather than hold a request open.
543 //
544 // The error is passed up rather than folded into false. Each
545 // caller wants a different answer to "the check failed": sign-in
546 // refuses, and a live request answers 503 so the editor's save
547 // queue retries instead of dropping the batch.
548 ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
549 defer cancel()
550 return store.HasGrant(ctx, address)
551 }
552
553 render, err := newRenderer()
554 if err != nil {
555 rt.Close(context.Background())
556 d.Close()
557 return nil, fmt.Errorf("docs: build renderer: %w", err)
558 }
559
560 // Sign-in links go out after the response, from a worker that asks
561 // the allowlist first (mailqueue.go). Closed by Close, or below if
562 // New fails after this point.
563 signinMail := newMailQueue(mailer, listAdmits(list), nil, logger)
564 built := false
565 defer func() {
566 if !built {
567 signinMail.close()
568 }
569 }()
570 // h is built below, after the plugin it wraps; the door rastrillo
571 // calls back into is bound to it late.
572 var h *handlers
573 door := signinDoor{
574 refused: func(w http.ResponseWriter, r *http.Request) { h.signinRefused(w, r) },
575 confirm: func(w http.ResponseWriter, r *http.Request, d rauth.ConfirmPageData) { h.confirmSignin(w, r, d) },
576 }
577 authPlugin, err := newAuthPlugin(cfg, d.Writer(), instanceKey, signinMail, list, logger, door)
578 if err != nil {
579 rt.Close(context.Background())
580 d.Close()
581 return nil, fmt.Errorf("docs: build auth: %w", err)
582 }
583
584 directory, err := validatedDirectory(cfg.Directory)
585 if err != nil {
586 rt.Close(context.Background())
587 d.Close()
588 return nil, err
589 }
590 h = &handlers{render: render, logger: logger, store: store, hub: newHub(), previews: newPreviews(), origin: cfg.Origin, isMember: list.configured, oneShots: newOneShots(), directory: directory, google: cfg.GoogleImport, imports: make(chan struct{}, maxImportsAtOnce),
591 livePush: cfg.LivePush, pushFrameCache: true, pushRegistry: newPushRegistry(), late: newLateAnswers(), pushStats: &pushStats{}}
592 if cfg.LivePush {
593 store.recordOrigin = h.pushRegistry.record
594 }
595 render.frame = h.frame
596 // peek: the viewer on routes no session guards (chrome.go). Standalone
597 // reads rastrillo/auth's own cookie; with Home, the Home bridge's.
598 h.peek = func(r *http.Request) (string, bool) {
599 id, ok := authPlugin.SessionFrom(r)
600 return id.Address, ok
601 }
602
603 if home != nil {
604 if err = home.mount(h, authPlugin); err != nil {
605 rt.Close(context.Background())
606 d.Close()
607 return nil, err
608 }
609 h.homeEnabled = true
610 h.homeLinked = home.bridge.Linked
611 h.peek = func(r *http.Request) (string, bool) {
612 s, ok := home.sessions.From(r)
613 if !ok || s.Subject == "" {
614 return "", false
615 }
616 if s.Method == "magiclink" || s.Method == "keymail" {
617 return s.Subject, true
618 }
619 id, err := home.resolver.resolve(sessions.WithSession(r, s))
620 if err != nil {
621 return "", false
622 }
623 return actorAddress(id.Actor), true
624 }
625 if store.team != nil {
626 store.team.home = home
627 home.team = store.team
628 home.resolver.team = store.team
629 store.team.readSession, err = newTeamSessionReader(d.Writer(), cfg.Origin, home.sessionCookie, logger)
630 if err != nil {
631 rt.Close(context.Background())
632 d.Close()
633 return nil, err
634 }
635 }
636
637 }
638 // Approval and long-lived streams reuse the same current admission chain.
639 h.requireCurrent = func(next http.Handler) http.Handler {
640 if store.team != nil {
641 next = store.team.admission(next)
642 } else {
643 next = requireAdmission(list, "/signin")(next)
644 }
645 if home == nil {
646 return authPlugin.RequireSession(next)
647 }
648 current := home.sessions.Require(home.resolver.middleware("/signin/local")(next))
649 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
650 // A live stream retains its opening context. Require trusts that cached
651 // session, so re-read the cookie before admitting each stream write.
652 session, ok := home.sessions.From(r)
653 if !ok {
654 http.Error(w, rastrillo.T(r, "docs.error.generic"), http.StatusUnauthorized)
655 return
656 }
657 current.ServeHTTP(w, sessions.WithSession(r, session))
658 })
659 }
660 nativeSessions, err := newNativeSessions(d.Writer(), cfg.Origin, logger)
661 if err != nil {
662 rt.Close(context.Background())
663 d.Close()
664 return nil, err
665 }
666 native := nativeauth.New(nativeSessions, cfg.Origin, "Docs", nativeApprover(h.requireCurrent))
667 var standalone *returnMemory
668 if home == nil {
669 if standalone, err = standaloneReturn(instanceKey, cfg.Origin); err != nil {
670 rt.Close(context.Background())
671 d.Close()
672 return nil, err
673 }
674 }
675 h.auth = authPlugin
676 if home == nil {
677 h.rememberReturn, h.returnPath = standalone.rememberReturn, standalone.returnPath
678 } else {
679 h.rememberReturn, h.returnPath = home.returns.rememberReturn, home.returns.returnPath
680 h.homeIssuer = home.issuer
681 }
682 r := chi.NewRouter()
683 // Every route that is not a route is the 404 page for a browser, and a
684 // page GET to a POST-only path is too (errors.go).
685 r.NotFound(h.notFound)
686 r.MethodNotAllowed(h.methodNotAllowed(r))
687 r.Use(native.Resume)
688 // Mounted above every route, per rastrillo SKILL.md §5: refuses a
689 // cross-origin POST/PUT/PATCH/DELETE by Sec-Fetch-Site/Origin/
690 // Referer evidence; GET/HEAD/OPTIONS pass untouched, so this does
691 // nothing to "/" or "/d/{sqid}" and everything to "/documents",
692 // "/signin" and "/signout".
693 r.Use(homeCSRF(cfg.Origin, home))
694 r.Post("/native/request", native.ServeHTTP)
695 r.Post("/native/exchange", native.ServeHTTP)
696 r.Get("/native/start", native.ServeHTTP)
697 r.Get("/native/authorize", native.ServeHTTP)
698 r.Post("/native/authorize", native.ServeHTTP)
699 // Unauthenticated: the sign-in page and its four handlers, and the
700 // static assets that page (and the shell around it) needs to
701 // render at all.
702 if home == nil {
703 r.Get("/signin", h.standaloneSignin)
704 r.Get(localLinkCompletePath, standalone.completeStandalone)
705 r.Get("/signed-out", h.signedOut)
706 } else {
707 home.mountPublic(r)
708 }
709 // Appearance (estilo chrome): inside the app-wide CSRF check above and
710 // outside every session guard below, so a session that expired while
711 // the menu was open cannot turn the click into a sign-in loop.
712 r.Post("/appearance", chrome.HandleAppearance)
713 r.Post("/signin", h.beginSignin(authPlugin.Begin))
714 // "Use a different email" on the door and "Forget me on this device"
715 // on the signed-out page: a same-origin POST, inside the app-wide CSRF
716 // check like any form. With Home, the signed-out page's chains on to
717 // Oficina ID's own Forget (auth.go's forget).
718 r.Post(signinForgetPath, h.forget(authPlugin.Forget))
719 // An emailed link opens GET /auth/verify, which only draws the
720 // confirm door (h.confirmSignin); its Sign in button POSTs the token
721 // back, and the POST spends it. Without the POST nobody signs in by
722 // email. Both sit inside the app-wide CSRF check, which the POST must
723 // pass like any other form. A refused address gets the door in a 403
724 // (h.signinRefused), from either route.
725 r.Get("/auth/callback", localAuthGuard(home, authPlugin.Callback))
726 r.Get("/auth/verify", localAuthGuard(home, authPlugin.Verify))
727 r.Post("/auth/verify", localAuthGuard(home, authPlugin.Verify))
728 // The published document, and the only route here no session guards.
729 // It is authorized by the token in its own path (links.go) rather
730 // than by who is asking — which is what a capability is, and why it
731 // sits above the RequireSession group rather than inside it with an
732 // exception carved into the middleware.
733 r.Get("/p/{token}", h.publicShow)
734 // Alta's readiness probe (team_probe.go): unauthenticated, no account
735 // data, and {"team_mode":false} on an instance not in team mode.
736 r.Method(http.MethodGet, teamProbePath, teamProbe(store.team))
737 // Help → Fonts and Help → Colophon (colophon.go): public, like every
738 // Oficina app's open-source page. The door does not link it (Paul,
739 // 2026-11-19).
740 r.Get(fontsPath, h.helpFonts)
741 r.Get(colophonPath, h.colophon)
742 r.Get(colophonPath+"/{id}", h.colophonLicence)
743 if home == nil {
744 r.Post("/signout", signoutToSignedOut(authPlugin.Signout))
745 } else {
746 r.Post("/signout", home.signout)
747 }
748 // staticHandler (assets.go) composes the committed editor bundle
749 // with render.assets.Handler()'s vendored design-system tree —
750 // both live under this one URL prefix, so one composed handler,
751 // not two competing route registrations. Still unauthenticated,
752 // still mounted above the RequireSession group below.
753 if home != nil {
754 provider, e := h.dashboardProvider(home, homeSettings, list, d.Writer())
755 if e != nil {
756 return nil, e
757 }
758 if provider != nil {
759 r.Handle(dashboard.Path, provider)
760 }
761 }
762 r.Handle("/static/*", staticHandler(render.assets.Handler()))
763 // The suite's app icons, served from estilo (the bar's brand, and the
764 // switcher's tiles once they render).
765 r.Handle(brand.Prefix+"*", brand.Handler())
766 // estilo's retired v1 Onest files. The chrome is set in the system UI
767 // face now, so no page links them (estilo AGENTS.md row 9); they stay
768 // answering so a page cached before the change still resolves its
769 // stylesheet. Docs' own document faces are a different thing, under
770 // /static/fonts/ (internal/fonts).
771 r.Handle(theme.FontPrefix+"*", theme.FontHandler())
772 // The sky behind the sign-in door: a closed set of SVGs, public.
773 r.Handle(sky.Prefix+"*", sky.Handler())
774
775 // Everything else needs a real, signed-in person — rastrillo
776 // SKILL.md §5/§1's "signed-in routes... in a Group with
777 // sess.Require", here auth's own RequireSession. A signed-out
778 // GET/HEAD redirects to /signin; anything else 403s.
779
780 if store.team != nil {
781 r.Group(func(r chi.Router) {
782 r.Use(home.sessions.Require)
783 r.Use(home.resolver.middleware("/signin/local"))
784 r.Use(requireTeamAccountAdmission(list))
785 home.mountAccount(r)
786 })
787 }
788 r.Group(func(r chi.Router) {
789 if home == nil {
790 r.Use(requireSessionReturning(authPlugin))
791 } else {
792 r.Use(home.sessions.Require)
793 r.Use(home.resolver.middleware("/signin/local"))
794 }
795 // After the session middleware, so a 500 page shows the viewer's
796 // own chrome (errors.go).
797 r.Use(h.recoverToErrorPage)
798 // Admission is re-asked per request, not only at sign-in, so
799 // revoking a guest's last grant ends their access now rather
800 // than whenever their 30-day session happens to expire.
801 if store.team != nil {
802 r.Use(store.team.admission)
803 } else {
804 r.Use(requireAdmission(list, "/signin"))
805 if home != nil {
806 home.mountAccount(r)
807 }
808 }
809 r.Get("/", h.list)
810 r.Post("/documents", h.create)
811 r.Get("/import", h.importGet)
812 r.Post("/import", h.importPost)
813 r.Get("/d/{sqid}/import-report", h.importReport)
814 // Title search for the jump-to palette (search.go). Inside
815 // this group like every other document route, and reader-scoped
816 // through Store.Search → Store.List rather than through a
817 // check of its own — a person's document titles are theirs.
818 r.Get("/documents/search", h.searchJSON)
819 r.Get("/d/{sqid}", h.show)
820 r.Post("/d/{sqid}/title", h.rename)
821 // Task 5: the update log, what the browser's editor reads to
822 // build its Yjs doc (GET) and posts new edits back through
823 // (POST) — see handlers.go's updatesGet/updatesPost. Neither
824 // is exempted from csrf.Protect above: rastrillo SKILL.md §5's
825 // origin check is what stops a cross-site page from writing
826 // to a document through this route.
827 // Sharing. All three owner-only, and all three answering 404 to
828 // anybody else — including a writer, who may edit the document and
829 // still may not decide who else reaches it.
830 r.Get("/d/{sqid}/share", h.shareGet)
831 r.Post("/d/{sqid}/share", h.sharePost)
832 r.Post("/d/{sqid}/share/revoke", h.shareRevoke)
833 r.Post("/d/{sqid}/share/link", h.shareLink)
834 r.Post("/d/{sqid}/share/team", h.shareTeam)
835 r.Get("/d/{sqid}/delete", h.deleteGet)
836 r.Post("/d/{sqid}/delete", h.deletePost)
837
838 r.Get("/d/{sqid}/updates", h.updatesGet)
839 r.Post("/d/{sqid}/updates", h.updatesPost)
840 // Export (export.go). Inside this group, so a signed-out
841 // request gets the same redirect every other document route
842 // gives it, and reader-scoped through the same Store.GetFor, so a
843 // document someone else owns 404s identically to one that does
844 // not exist. Extensions in the path rather than a ?format=
845 // query: the URL is what a person sees when they save the
846 // file, and one that ends in .pdf is one a browser and an
847 // operating system both already understand.
848 r.Get("/d/{sqid}/export.md", h.exportMarkdown)
849 r.Get("/d/{sqid}/export.pdf", h.exportPDF)
850 // Plan 5: the live-update stream (stream.go). A GET, so
851 // csrf.Protect passes it through untouched, and reader-scoped
852 // through the same getDocumentForUpdates helper as the two
853 // routes above — a stranger gets 404, never 403.
854 r.Get("/d/{sqid}/stream", h.stream)
855 })
856
857 mux := http.NewServeMux()
858 mux.Handle("/", r)
859 if agentVerifier != nil {
860 agentHandler, e := newDocumentAgent(cfg, homeSettings, home, store, list, agentVerifier, h.hub.broadcast)
861 if e != nil {
862 rt.Close(context.Background())
863 d.Close()
864 return nil, e
865 }
866 mux.Handle("/api/v1/operations", agentHandler)
867 mux.Handle("/api/v1/operations/", agentHandler)
868 }
869 // The suite contract's producer half (suite.go), beside the router
870 // rather than in it. A grant admits its holder here exactly as it does
871 // at the front door, so S2 reads the same allowlist the router does.
872 producer := &suiteProducer{store: store, list: list}
873 if store.team != nil {
874 producer.subjects = home.bridge
875 }
876 mountSuite(mux, server.Handler(producer, consumers, logger))
877
878 built = true
879 return &App{cfg: cfg, db: d, mux: mux, logger: logger, core: rt, store: store, handlers: h, mailRecorder: mailRecorder, signinMail: signinMail, suite: producer}, nil
880}
881
882// Store returns the app's document store — models.go's Document,
883// store.go's Store — over the app's migrated database and shared
884// core.Runtime.
885func (a *App) Store() *Store { return a.store }
886
887// Handler is the app's router: rastrillo.Options.Mux for real serving
888// (cmd/docs/main.go), and — per rastrillo's own doc comment on
889// Handler/Serve — exactly what a test harness should exercise directly,
890// so httptest hits the real route table rather than a hand-duplicated
891// one. *http.ServeMux, not http.Handler: it satisfies both callers
892// without forcing an unchecked type assertion on the main.go side,
893// and matches SKILL.md's own App(...) (*http.ServeMux, error) shape.
894func (a *App) Handler() *http.ServeMux { return a.mux }
895
896// Close releases the database handle and the core runtime's compiled
897// module. NewForTest registers this as a t.Cleanup.
898func (a *App) Close() error {
899 var errs []error
900 // First, while the database the allowlist reads is still open.
901 if a.signinMail != nil {
902 a.signinMail.close()
903 }
904 if a.handlers != nil && a.handlers.store != nil {
905 a.handlers.store.warm.close(context.Background())
906 }
907 if a.core != nil {
908 if err := a.core.Close(context.Background()); err != nil {
909 errs = append(errs, err)
910 }
911 }
912 if err := a.db.Close(); err != nil {
913 errs = append(errs, err)
914 }
915 return errors.Join(errs...)
916}
917