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(`