Files
pages/internal/server/anonymous_view.go
T
Anya Tokugawa d5d21b7841
Build and publish container images / images (push) Successful in 9m34s
Release container images / release (push) Successful in 36s
Refactor architecture into eight components and consolidate reliability work
Extract Grammaratur, Dregarnuhr, Geduldh, Mestionora, Ordoschnellic, Schutzaria, Kunstzeal and Seheweit behind compatible application contracts.

Include accumulated editor resilience, navigation and theme UX, remote CLI, storage/schema and DR groundwork, tests and design/operations documentation.

Verified: uncached full Go suite; go vet ./...; race tests for all eight components; 11 targeted Chromium tests; Node suites; 19 Python CLI tests; reproducible editor build. No push, release tag or deployment in this checkpoint.
2026-11-01 15:23:31 +09:00

166 lines
5.4 KiB
Go

package server
import (
"context"
"database/sql"
"errors"
"html/template"
"io"
"mime"
"net/http"
"net/url"
"path"
"strings"
"time"
"pageswiki/internal/store"
)
type anonymousProjectionKey struct{}
func isAnonymousProjection(r *http.Request) bool {
value, _ := r.Context().Value(anonymousProjectionKey{}).(bool)
return value
}
func (s *Server) tryAnonymousProjection(w http.ResponseWriter, r *http.Request) bool {
if r.Method != "GET" && r.Method != "HEAD" {
return false
}
// A bad or expired credential must not fall back to a weaker identity.
if len(r.Header.Values("Authorization")) > 0 {
return false
}
for _, c := range r.Cookies() {
if c.Name == authCookieName {
return false
}
}
if s.servePublicPeriodical(w, r) {
return true
}
if s.servePublicUserSpace(w, r) {
return true
}
if s.servePublicUserNavigation(w, r) {
return true
}
if s.servePublicNavigation(w, r) {
return true
}
semantic := r.URL.Path
raw := strings.HasPrefix(semantic, "/v/raw/path:")
if raw {
semantic = strings.TrimPrefix(semantic, "/v/raw/path:")
}
if !store.PublicSemanticPath(semantic) {
return false
}
v, err := s.store.AnonymousRevision(r.Context(), s.domainUUIDForRequest(r), semantic, s.revisionLanguageCandidates(r))
if errors.Is(err, sql.ErrNoRows) {
// A structural folder discloses only the already-public descendants,
// never an unapproved Page at the same Path. Raw reads stay exact-only.
if !raw {
publicRequest, navigationErr := s.withPublicNavigation(r)
if navigationErr != nil {
http.Error(w, "navigation unavailable", 503)
return true
}
if publicNavigationFor(publicRequest).hasChildren(semantic) {
s.renderPublicDirectory(w, publicRequest, semantic, true)
return true
}
}
return false
}
if err != nil {
http.Error(w, "publication unavailable", 503)
return true
}
r = r.WithContext(context.WithValue(r.Context(), anonymousProjectionKey{}, true))
r, err = s.withPublicNavigation(r)
if err != nil {
http.Error(w, "navigation unavailable", 503)
return true
}
if current, ok := publicNavigationFor(r).pages[semantic]; !ok || current.UUID != v.UUID {
http.Error(w, "publication changed; retry", 503)
return true
}
return s.serveAnonymousRevision(w, r, semantic, raw, v)
}
func (s *Server) serveAnonymousRevision(w http.ResponseWriter, r *http.Request, semantic string, raw bool, v *store.Revision) bool {
reader, err := s.store.OpenDocumentContext(r.Context(), v.DocumentHash)
if err != nil {
http.Error(w, "published document unavailable", 503)
return true
}
defer reader.Close()
w.Header().Set("Cache-Control", "private, no-store")
w.Header().Set("Referrer-Policy", "no-referrer")
w.Header().Set("X-Content-Type-Options", "nosniff")
w.Header().Add("Vary", "Accept-Language")
contentType, _, _ := mime.ParseMediaType(v.ContentType)
filename := path.Base(v.Filename)
if filename == "." || filename == "/" || filename == "" {
filename = path.Base(semantic)
}
if raw {
// Raw authored HTML, SVG and unknown formats are attachments, never
// executable same-origin content. Native passive formats can stream.
inline := contentType == "application/pdf" || contentType == "image/png" || contentType == "image/jpeg" || contentType == "image/gif" || contentType == "image/webp" || strings.HasPrefix(contentType, "audio/") || strings.HasPrefix(contentType, "video/")
disposition := "attachment"
if inline {
disposition = "inline"
}
csp := "default-src 'none'; frame-ancestors 'self'"
if !inline {
csp = "sandbox; " + csp
}
w.Header().Set("Content-Security-Policy", csp)
w.Header().Set("Content-Disposition", mime.FormatMediaType(disposition, map[string]string{"filename": filename}))
if contentType == "" {
contentType = "application/octet-stream"
}
w.Header().Set("Content-Type", contentType)
w.Header().Set("ETag", `"`+v.DocumentHash+`"`)
setDocumentIdentityHeaders(w.Header(), v.ObjectUUID, v.UUID, v.DocumentHash)
http.ServeContent(w, r, filename, time.UnixMilli(v.CreatedAtMS), reader)
return true
}
data := s.publicNavigationData(r, semantic)
data["Title"] = filename
data["RawURL"] = cityPageHref("/v/raw/path:"+semantic) + "?lang=" + url.QueryEscape(v.Language)
switch {
case contentType == "text/html":
body, e := io.ReadAll(io.LimitReader(reader, maxProjectionInput+1))
if e != nil {
http.Error(w, "published document unavailable", 503)
return true
}
data["HTML"] = template.HTML(s.safeHTMLProjection(r, string(body), semantic, true))
data["SocialSource"] = string(body)
case contentType == "image/png" || contentType == "image/jpeg" || contentType == "image/gif" || contentType == "image/webp":
data["Media"] = "image"
case contentType == "application/pdf":
data["Media"] = "pdf"
case strings.HasPrefix(contentType, "audio/"):
data["Media"] = "audio"
case strings.HasPrefix(contentType, "video/"):
data["Media"] = "video"
case strings.HasPrefix(contentType, "text/") || contentType == "application/json":
body, e := io.ReadAll(io.LimitReader(reader, 64<<10))
if e != nil {
http.Error(w, "published document unavailable", 503)
return true
}
data["Text"] = string(body)
data["CodeLanguage"] = codeLanguage(contentType, filename, string(body))
}
data["SocialMetadata"] = s.socialMetadataForRequest(r, "anonymous_view.gohtml", data)
w.Header().Set("Content-Type", "text/html; charset=utf-8")
s.render(w, "anonymous_view.gohtml", data)
return true
}