Files
Anya Tokugawa c1175d389f Implement Knowledge City platform, organizer and DAV integration
Capture accumulated application, UI, CLI, regression tests and design documentation changes, including task project mapping and default CalDAV list naming.

Keep deployment data, backups, local credentials and build artifacts out of Git. Move the Compose enrollment token to an ignored local environment file.
2026-09-27 14:44:43 +09:00

516 lines
16 KiB
Go

package main
import (
"bytes"
"crypto/rand"
"encoding/base64"
"encoding/hex"
"encoding/json"
"fmt"
"html/template"
"io"
"log"
"net/http"
"net/http/httputil"
"net/url"
"os"
"path/filepath"
"strings"
"sync"
"time"
)
type gatewaySession struct {
VimSettings json.RawMessage
Token string
PluginID string
Filename string
ContentType string
ExpiresAtMS int64
Workspace string
Files map[string]gatewayFile
LastError string
}
type gatewayFile struct {
SemanticPath string
RevisionUUID string
LastContent string
}
type gateway struct {
origin string
client *http.Client
mu sync.Mutex
sessions map[string]gatewaySession
codeProxy *httputil.ReverseProxy
excalidrawProxy *httputil.ReverseProxy
}
func main() {
origin := strings.TrimRight(os.Getenv("PAGESWIKI_ORIGIN"), "/")
if origin == "" {
origin = "http://app:3000"
}
codeOrigin := os.Getenv("CODE_SERVER_ORIGIN")
if codeOrigin == "" {
codeOrigin = "http://code-server:8080"
}
codeURL, err := url.Parse(codeOrigin)
if err != nil {
log.Fatal(err)
}
proxy := httputil.NewSingleHostReverseProxy(codeURL)
originalDirector := proxy.Director
proxy.Director = func(req *http.Request) {
req.URL.Path = strings.TrimPrefix(req.URL.Path, "/code")
if req.URL.Path == "" {
req.URL.Path = "/"
}
originalDirector(req)
}
excalidrawOrigin := os.Getenv("EXCALIDRAW_VIEWER_ORIGIN")
if excalidrawOrigin == "" {
excalidrawOrigin = "http://excalidraw-viewer:8080"
}
excalidrawURL, err := url.Parse(excalidrawOrigin)
if err != nil {
log.Fatal(err)
}
excalidrawProxy := httputil.NewSingleHostReverseProxy(excalidrawURL)
excalidrawDirector := excalidrawProxy.Director
excalidrawProxy.Director = func(req *http.Request) {
req.URL.Path = strings.TrimPrefix(req.URL.Path, "/excalidraw")
if req.URL.Path == "" {
req.URL.Path = "/"
}
excalidrawDirector(req)
}
g := &gateway{origin: origin, client: &http.Client{Timeout: 30 * time.Second}, sessions: map[string]gatewaySession{}, codeProxy: proxy, excalidrawProxy: excalidrawProxy}
mux := http.NewServeMux()
mux.HandleFunc("/health", func(w http.ResponseWriter, _ *http.Request) { w.Write([]byte("ok")) })
mux.HandleFunc("/open", g.open)
mux.HandleFunc("/code/open", g.open)
mux.HandleFunc("/vim/open", g.open)
mux.HandleFunc("/edit", g.edit)
mux.HandleFunc("/save", g.save)
mux.HandleFunc("/code/", g.code)
mux.HandleFunc("/vim/api/session", g.vimSession)
mux.HandleFunc("/vim/api/save", g.vimSave)
vimFiles := http.FileServer(http.Dir("/vimwasm"))
vimHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/vim/" {
data, err := os.ReadFile("/vimwasm/index.html")
if err != nil {
http.Error(w, "vim.wasm frontend is unavailable", http.StatusServiceUnavailable)
return
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
_, _ = w.Write(data)
return
}
http.StripPrefix("/vim/", vimFiles).ServeHTTP(w, r)
})
mux.Handle("/vim/", isolationHeaders(vimHandler))
mux.Handle("/excalidraw/", excalidrawHeaders(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
g.excalidrawProxy.ServeHTTP(w, r)
})))
log.Printf("adapter gateway origin=%s listen=:3000", origin)
log.Fatal(http.ListenAndServe(":3000", mux))
}
func excalidrawHeaders(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Security-Policy", "default-src 'self'; script-src 'self' 'unsafe-eval' 'wasm-unsafe-eval'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; font-src 'self' data:; worker-src 'self' blob:; connect-src 'self'; frame-ancestors 'self'; object-src 'none'; base-uri 'none'")
w.Header().Set("X-Content-Type-Options", "nosniff")
w.Header().Set("Referrer-Policy", "no-referrer")
next.ServeHTTP(w, r)
})
}
func isolationHeaders(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cross-Origin-Opener-Policy", "same-origin")
w.Header().Set("Cross-Origin-Embedder-Policy", "require-corp")
w.Header().Set("Cross-Origin-Resource-Policy", "same-origin")
w.Header().Set("Origin-Agent-Cluster", "?1")
next.ServeHTTP(w, r)
})
}
func randomID() string {
b := make([]byte, 24)
_, _ = rand.Read(b)
return hex.EncodeToString(b)
}
func ensureCoderDirectory(root, directory string) error {
relative, err := filepath.Rel(root, directory)
if err != nil || relative == ".." || strings.HasPrefix(relative, ".."+string(filepath.Separator)) {
return fmt.Errorf("workspace directory escapes root")
}
current := root
for _, component := range strings.Split(relative, string(filepath.Separator)) {
if component == "" || component == "." {
continue
}
current = filepath.Join(current, component)
if err := os.Mkdir(current, 0700); err != nil && !os.IsExist(err) {
return err
}
if err := os.Chown(current, 1000, 1000); err != nil {
return err
}
}
return nil
}
func (g *gateway) request(method, path, bearer string, input any, output any) error {
var body io.Reader
if input != nil {
data, _ := json.Marshal(input)
body = bytes.NewReader(data)
}
req, err := http.NewRequest(method, g.origin+path, body)
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/json")
if bearer != "" {
req.Header.Set("Authorization", "Bearer "+bearer)
}
res, err := g.client.Do(req)
if err != nil {
return err
}
defer res.Body.Close()
if res.StatusCode < 200 || res.StatusCode >= 300 {
message, _ := io.ReadAll(io.LimitReader(res.Body, 4096))
return fmt.Errorf("Pages Wiki HTTP %d: %s", res.StatusCode, strings.TrimSpace(string(message)))
}
return json.NewDecoder(res.Body).Decode(output)
}
func (g *gateway) open(w http.ResponseWriter, r *http.Request) {
publicPrefix := strings.TrimRight(strings.TrimSpace(r.Header.Get("X-Forwarded-Prefix")), "/")
ticket := strings.TrimSpace(r.URL.Query().Get("ticket"))
if ticket == "" {
http.Error(w, "ticket is required", 400)
return
}
var exchanged struct {
SessionToken string `json:"session_token"`
PluginID string `json:"plugin_id"`
Filename string `json:"filename"`
ContentType string `json:"content_type"`
ExpiresAtMS int64 `json:"expires_at_ms"`
}
if err := g.request("POST", "/_/api/v1/adapter/session/exchange", "",
map[string]string{"ticket": ticket}, &exchanged); err != nil {
http.Error(w, err.Error(), http.StatusBadGateway)
return
}
var workspaceData struct {
VimSettings json.RawMessage `json:"vim_settings"`
Files []struct {
Path string `json:"path"`
SemanticPath string `json:"semantic_path"`
RevisionUUID string `json:"revision_uuid"`
ContentBase64 string `json:"content_base64"`
} `json:"files"`
}
if err := g.request("GET", "/_/api/v1/adapter/session/workspace", exchanged.SessionToken, nil, &workspaceData); err != nil {
http.Error(w, err.Error(), http.StatusBadGateway)
return
}
id := randomID()
workspace := filepath.Join("/workspaces", id)
if err := os.MkdirAll(workspace, 0700); err != nil {
http.Error(w, err.Error(), 500)
return
}
_ = os.Chown(workspace, 1000, 1000)
files := make(map[string]gatewayFile, len(workspaceData.Files))
filename := "document.txt"
for index, source := range workspaceData.Files {
clean := filepath.Clean(filepath.FromSlash(source.Path))
if clean == "." || filepath.IsAbs(clean) || strings.HasPrefix(clean, ".."+string(filepath.Separator)) {
continue
}
data, decodeErr := base64.StdEncoding.DecodeString(source.ContentBase64)
if decodeErr != nil {
http.Error(w, "invalid workspace content", http.StatusBadGateway)
return
}
target := filepath.Join(workspace, clean)
if _, duplicate := files[clean]; duplicate {
http.Error(w, "workspace contains duplicate filenames", http.StatusConflict)
return
}
if err := ensureCoderDirectory(workspace, filepath.Dir(target)); err != nil {
http.Error(w, err.Error(), 500)
return
}
if err := os.WriteFile(target, data, 0600); err != nil {
http.Error(w, err.Error(), 500)
return
}
_ = os.Chown(target, 1000, 1000)
files[clean] = gatewayFile{SemanticPath: source.SemanticPath,
RevisionUUID: source.RevisionUUID, LastContent: source.ContentBase64}
if index == 0 {
filename = clean
}
}
if len(files) == 0 {
http.Error(w, "workspace contains no editable files", http.StatusBadGateway)
return
}
g.mu.Lock()
g.sessions[id] = gatewaySession{Token: exchanged.SessionToken, PluginID: exchanged.PluginID, Filename: filename,
ContentType: exchanged.ContentType, ExpiresAtMS: exchanged.ExpiresAtMS,
Workspace: workspace, Files: files, VimSettings: workspaceData.VimSettings}
g.mu.Unlock()
cookiePath := "/"
if publicPrefix != "" {
cookiePath = publicPrefix + "/"
}
http.SetCookie(w, &http.Cookie{Name: "pageswiki_adapter", Value: id, Path: cookiePath, HttpOnly: true, SameSite: http.SameSiteLaxMode, MaxAge: 8 * 3600})
if exchanged.PluginID == "vim.wasm" {
go g.expire(id)
http.Redirect(w, r, publicPrefix+"/vim/", http.StatusFound)
return
}
go g.watch(id)
http.Redirect(w, r, publicPrefix+"/code/?folder="+url.QueryEscape(workspace), http.StatusFound)
}
func (g *gateway) session(r *http.Request) (gatewaySession, bool) {
cookie, err := r.Cookie("pageswiki_adapter")
if err != nil {
return gatewaySession{}, false
}
g.mu.Lock()
defer g.mu.Unlock()
s, ok := g.sessions[cookie.Value]
if !ok || s.ExpiresAtMS < time.Now().UnixMilli() {
delete(g.sessions, cookie.Value)
return gatewaySession{}, false
}
return s, true
}
var editorTemplate = template.Must(template.New("editor").Parse(`<!doctype html>
<html><head><meta charset="utf-8"><title>{{.Filename}}</title>
<style>html,body,form{height:100%;margin:0}form{display:grid;grid-template-rows:auto 1fr}.bar{padding:.5rem;background:#20242b;color:#eee}textarea{resize:none;border:0;padding:1rem;font:14px/1.5 monospace;background:#11151a;color:#e8e8e8;outline:0}</style></head>
<body><form method="post" action="/save"><div class="bar"><strong>{{.Filename}}</strong> <button type="submit">Save as new Revision</button> {{.Status}}</div><textarea name="content" spellcheck="false">{{.Content}}</textarea></form></body></html>`))
func (g *gateway) edit(w http.ResponseWriter, r *http.Request) {
s, ok := g.session(r)
if !ok {
http.Error(w, "session expired", 401)
return
}
var content struct {
ContentBase64 string `json:"content_base64"`
}
if err := g.request("GET", "/_/api/v1/adapter/session/content", s.Token, nil, &content); err != nil {
http.Error(w, err.Error(), 502)
return
}
data, err := base64.StdEncoding.DecodeString(content.ContentBase64)
if err != nil {
http.Error(w, "invalid content", 502)
return
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
_ = editorTemplate.Execute(w, map[string]any{"Filename": s.Filename, "Content": string(data), "Status": r.URL.Query().Get("status")})
}
func (g *gateway) save(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "method not allowed", 405)
return
}
s, ok := g.session(r)
if !ok {
http.Error(w, "session expired", 401)
return
}
r.Body = http.MaxBytesReader(w, r.Body, 65<<20)
if err := r.ParseForm(); err != nil {
http.Error(w, err.Error(), 400)
return
}
var output map[string]any
err := g.request("PUT", "/_/api/v1/adapter/session/content", s.Token, map[string]string{
"content_base64": base64.StdEncoding.EncodeToString([]byte(r.FormValue("content"))),
"message": "hosted editor: " + s.Filename,
}, &output)
if err != nil {
http.Error(w, err.Error(), http.StatusConflict)
return
}
http.Redirect(w, r, "/edit?status=saved", http.StatusFound)
}
func (g *gateway) code(w http.ResponseWriter, r *http.Request) {
if _, ok := g.session(r); !ok {
http.Error(w, "session expired", http.StatusUnauthorized)
return
}
g.codeProxy.ServeHTTP(w, r)
}
func (g *gateway) vimSession(w http.ResponseWriter, r *http.Request) {
session, ok := g.session(r)
if !ok || session.PluginID != "vim.wasm" {
http.Error(w, "session expired", http.StatusUnauthorized)
return
}
type vimFile struct {
Path string `json:"path"`
Content string `json:"content"`
}
files := make([]vimFile, 0, len(session.Files))
for relative, tracked := range session.Files {
data, err := base64.StdEncoding.DecodeString(tracked.LastContent)
if err != nil {
continue
}
files = append(files, vimFile{Path: filepath.ToSlash(relative), Content: string(data)})
}
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Cache-Control", "no-store")
_ = json.NewEncoder(w).Encode(map[string]any{"initial": filepath.ToSlash(session.Filename), "files": files, "vim_settings": session.VimSettings})
}
func (g *gateway) vimSave(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPut {
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
session, ok := g.session(r)
if !ok || session.PluginID != "vim.wasm" {
http.Error(w, "session expired", http.StatusUnauthorized)
return
}
var input struct {
Path string `json:"path"`
ContentBase64 string `json:"content_base64"`
}
r.Body = http.MaxBytesReader(w, r.Body, 65<<20)
if err := json.NewDecoder(r.Body).Decode(&input); err != nil {
http.Error(w, "invalid JSON", http.StatusBadRequest)
return
}
clean := filepath.Clean(filepath.FromSlash(strings.TrimPrefix(input.Path, "/work/")))
tracked, exists := session.Files[clean]
if !exists {
http.Error(w, "file is outside the adapter workspace", http.StatusForbidden)
return
}
var output struct {
RevisionUUID string `json:"revision_uuid"`
}
err := g.request("PUT", "/_/api/v1/adapter/session/content", session.Token,
map[string]string{"content_base64": input.ContentBase64, "path": tracked.SemanticPath,
"revision_uuid": tracked.RevisionUUID, "message": "vim.wasm write: " + clean}, &output)
if err != nil {
http.Error(w, err.Error(), http.StatusConflict)
return
}
cookie, _ := r.Cookie("pageswiki_adapter")
g.mu.Lock()
current, exists := g.sessions[cookie.Value]
if exists {
updated := current.Files[clean]
updated.LastContent = input.ContentBase64
updated.RevisionUUID = output.RevisionUUID
current.Files[clean] = updated
g.sessions[cookie.Value] = current
}
g.mu.Unlock()
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]any{"revision_uuid": output.RevisionUUID})
}
func (g *gateway) expire(id string) {
g.mu.Lock()
session, ok := g.sessions[id]
g.mu.Unlock()
if !ok {
return
}
delay := time.Until(time.UnixMilli(session.ExpiresAtMS))
if delay > 0 {
timer := time.NewTimer(delay)
defer timer.Stop()
<-timer.C
}
g.mu.Lock()
session, ok = g.sessions[id]
delete(g.sessions, id)
g.mu.Unlock()
if ok {
if err := os.RemoveAll(session.Workspace); err != nil {
log.Printf("remove expired workspace %s: %v", session.Workspace, err)
}
}
}
func (g *gateway) watch(id string) {
ticker := time.NewTicker(2 * time.Second)
defer ticker.Stop()
defer func() {
g.mu.Lock()
session, ok := g.sessions[id]
delete(g.sessions, id)
g.mu.Unlock()
if ok {
if err := os.RemoveAll(session.Workspace); err != nil {
log.Printf("remove expired workspace %s: %v", session.Workspace, err)
}
}
}()
for range ticker.C {
g.mu.Lock()
session, ok := g.sessions[id]
g.mu.Unlock()
if !ok || session.ExpiresAtMS < time.Now().UnixMilli() {
return
}
for relative, tracked := range session.Files {
data, err := os.ReadFile(filepath.Join(session.Workspace, relative))
if err != nil {
continue
}
encoded := base64.StdEncoding.EncodeToString(data)
if encoded == tracked.LastContent {
continue
}
var output struct {
RevisionUUID string `json:"revision_uuid"`
}
err = g.request("PUT", "/_/api/v1/adapter/session/content", session.Token,
map[string]string{"content_base64": encoded, "path": tracked.SemanticPath,
"revision_uuid": tracked.RevisionUUID, "message": "code-server autosave: " + relative}, &output)
g.mu.Lock()
current, exists := g.sessions[id]
if exists {
currentFile := current.Files[relative]
if err == nil {
currentFile.LastContent = encoded
currentFile.RevisionUUID = output.RevisionUUID
current.Files[relative] = currentFile
current.LastError = ""
} else {
current.LastError = err.Error()
}
g.sessions[id] = current
}
g.mu.Unlock()
}
}
}