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.
This commit is contained in:
Anya Tokugawa committed 2026-09-27 14:44:43 +09:00
1 parent 288e6e94ac
commit c1175d389f
699 files changed
+110197 -4117

No files matched your search

+477
View File
@@ -0,0 +1,477 @@
package server
import (
"database/sql"
"encoding/json"
"errors"
"fmt"
"mime"
"net/http"
"net/url"
"path/filepath"
"regexp"
"sort"
"strings"
)
const adapterPluginsConfigKey = "projection_adapter_plugins"
type adapterPlugin struct {
ID string `json:"id"`
Name string `json:"name"`
Mode string `json:"mode"` // hosted viewer or hosted editor
URLTemplate string `json:"url_template"`
MediaTypes []string `json:"media_types,omitempty"`
Extensions []string `json:"extensions,omitempty"`
Enabled bool `json:"enabled"`
NewTab bool `json:"new_tab,omitempty"`
HTMLMarkdown bool `json:"html_markdown,omitempty"`
DefaultEditor bool `json:"default_editor,omitempty"`
Unsupported bool `json:"unsupported,omitempty"`
}
type adapterAction struct {
ID string `json:"id"`
Name string `json:"name"`
Mode string `json:"mode"`
Builtin bool `json:"builtin"`
OpenURL string `json:"open_url"`
NewTab bool `json:"new_tab,omitempty"`
Default bool `json:"default,omitempty"`
}
type builtinAdapterInfo struct {
ID string `json:"id"`
Kind string `json:"kind"`
Delivery string `json:"delivery"`
Selectable bool `json:"selectable"`
}
var adapterIDPattern = regexp.MustCompile(`^[a-z][a-z0-9._-]{1,63}$`)
func builtinAdapterManifest() []builtinAdapterInfo {
out := make([]builtinAdapterInfo, 0, len(projectionAdapters))
for _, adapter := range projectionAdapters {
out = append(out, builtinAdapterInfo{
ID: adapter.ID, Kind: adapter.Kind,
Delivery: string(adapter.Delivery), Selectable: true,
})
}
return out
}
func (s *Server) adapterPlugins(domainUUID string) ([]adapterPlugin, error) {
raw, err := s.store.GetConfigInDomain(domainUUID, adapterPluginsConfigKey)
if err != nil || strings.TrimSpace(raw) == "" {
return []adapterPlugin{}, err
}
var plugins []adapterPlugin
if err := json.Unmarshal([]byte(raw), &plugins); err != nil {
return nil, err
}
// Native execution is reserved for a future local-helper protocol. Keep
// legacy records visible, but never advertise or launch them.
for index := range plugins {
validated := plugins[index]
if err := validateAdapterPlugin(&validated); err != nil {
plugins[index].Enabled = false
plugins[index].Unsupported = true
}
}
return plugins, nil
}
func (s *Server) saveAdapterPlugins(domainUUID string, plugins []adapterPlugin) error {
sort.Slice(plugins, func(i, j int) bool { return plugins[i].ID < plugins[j].ID })
data, err := json.Marshal(plugins)
if err != nil {
return err
}
return s.store.SetConfigInDomain(domainUUID, adapterPluginsConfigKey, string(data))
}
func validateAdapterPlugin(plugin *adapterPlugin) error {
plugin.ID = strings.ToLower(strings.TrimSpace(plugin.ID))
plugin.Name = strings.TrimSpace(plugin.Name)
plugin.Mode = strings.ToLower(strings.TrimSpace(plugin.Mode))
plugin.URLTemplate = strings.TrimSpace(plugin.URLTemplate)
if !adapterIDPattern.MatchString(plugin.ID) || plugin.Name == "" {
return errors.New("invalid adapter id or name")
}
switch plugin.Mode {
case "viewer", "editor":
default:
return errors.New("mode must be viewer or editor; native integration is not implemented")
}
if !strings.Contains(plugin.URLTemplate, "{url}") &&
!strings.Contains(plugin.URLTemplate, "{path}") &&
!strings.Contains(plugin.URLTemplate, "{ticket}") {
return errors.New("URL template must contain {url}, {path}, or {ticket}")
}
if plugin.Mode == "editor" && !strings.Contains(plugin.URLTemplate, "{ticket}") {
return errors.New("hosted editor URL template must contain {ticket}")
}
sample := strings.NewReplacer(
"{url}", "https://example.invalid/v/raw/path:/sample.txt",
"{path}", "/sample.txt",
"{filename}", "sample.txt",
"{ticket}", "pwa_t_sample",
"{origin}", "https://pages.example.invalid",
).Replace(plugin.URLTemplate)
parsed, err := url.Parse(sample)
if err != nil || (parsed.Scheme != "http" && parsed.Scheme != "https") {
return errors.New("hosted adapter URL must use http or https")
}
for index, extension := range plugin.Extensions {
extension = strings.ToLower(strings.TrimSpace(extension))
if extension != "" && !strings.HasPrefix(extension, ".") {
extension = "." + extension
}
plugin.Extensions[index] = extension
}
for index, mediaType := range plugin.MediaTypes {
plugin.MediaTypes[index] = strings.ToLower(strings.TrimSpace(mediaType))
}
return nil
}
func pluginMatches(plugin adapterPlugin, mediaType, filename string) bool {
if !plugin.Enabled || plugin.Unsupported || plugin.Mode == "native" {
return false
}
if len(plugin.MediaTypes) == 0 && len(plugin.Extensions) == 0 {
return true
}
for _, candidate := range plugin.MediaTypes {
if candidate == mediaType ||
(strings.HasSuffix(candidate, "/*") &&
strings.HasPrefix(mediaType, strings.TrimSuffix(candidate, "*"))) {
return true
}
}
extension := strings.ToLower(filepath.Ext(filename))
for _, candidate := range plugin.Extensions {
if extension == candidate {
return true
}
}
return false
}
func (s *Server) adapterActionsForPath(r *http.Request, semanticPath string) ([]adapterAction, error) {
domainUUID := s.domainUUIDForRequest(r)
objectUUID, err := s.store.ResolvePathInDomain(domainUUID, semanticPath)
if err != nil {
return nil, err
}
revision, err := s.latestRevisionForRequest(r, objectUUID)
if err != nil {
return nil, err
}
mediaType, _, _ := mime.ParseMediaType(revision.ContentType)
filename := revision.Filename
if filename == "" {
filename = filepath.Base(semanticPath)
}
selected := selectProjectionAdapter(contentDescriptor{
MediaType: strings.ToLower(mediaType), Filename: filename,
SizeBytes: int64(len(revision.Body)),
})
actions := []adapterAction{
{ID: selected.ID, Name: selected.ID, Mode: "viewer", Builtin: true, OpenURL: semanticPath},
{ID: "download", Name: "download", Mode: "viewer", Builtin: true,
OpenURL: rawProjectionURL("rev:" + revision.UUID)},
}
if selected.NeedsText || selected.ID == "html" || selected.ID == "excalidraw" {
actions = append(actions, adapterAction{
ID: "editor", Name: "Pages Wiki Editor", Mode: "editor",
Builtin: true, OpenURL: "/e" + semanticPath,
})
}
plugins, err := s.adapterPlugins(domainUUID)
if err != nil {
return nil, err
}
sort.SliceStable(plugins, func(i, j int) bool {
return plugins[i].DefaultEditor && !plugins[j].DefaultEditor
})
for _, plugin := range plugins {
if pluginMatches(plugin, strings.ToLower(mediaType), filename) {
actions = append(actions, adapterAction{
ID: plugin.ID, Name: plugin.Name, Mode: plugin.Mode,
NewTab: plugin.NewTab,
Default: plugin.DefaultEditor,
OpenURL: "/v/open-with?adapter=" + url.QueryEscape(plugin.ID) +
"&path=" + url.QueryEscape(semanticPath),
})
}
}
return actions, nil
}
func (s *Server) handleAdapterAPI(w http.ResponseWriter, r *http.Request) {
action := strings.Trim(strings.TrimPrefix(r.URL.Path, "/_/api/v1/adapter"), "/")
domainUUID := s.domainUUIDForRequest(r)
switch action {
case "":
if r.Method == http.MethodGet {
plugins, err := s.adapterPlugins(domainUUID)
if err != nil {
writeEventJSON(w, 500, map[string]string{"error": err.Error()})
return
}
response := map[string]any{
"builtin": builtinAdapterManifest(), "plugins": plugins,
}
if path := strings.TrimSpace(r.URL.Query().Get("path")); path != "" {
actions, err := s.adapterActionsForPath(r, path)
if err != nil {
status := 500
if errors.Is(err, sql.ErrNoRows) {
status = 404
}
writeEventJSON(w, status, map[string]string{"error": err.Error()})
return
}
response["actions"] = actions
}
writeEventJSON(w, 200, response)
return
}
if r.Method == http.MethodPost || r.Method == http.MethodPut {
var plugin adapterPlugin
if !decodeEventJSON(w, r, &plugin) {
return
}
if err := validateAdapterPlugin(&plugin); err != nil {
writeEventJSON(w, 400, map[string]string{"error": err.Error()})
return
}
plugins, err := s.adapterPlugins(domainUUID)
if err != nil {
writeEventJSON(w, 500, map[string]string{"error": err.Error()})
return
}
if plugin.DefaultEditor {
if plugin.Mode != "editor" {
writeEventJSON(w, 400, map[string]string{"error": "only an editor can be the default editor"})
return
}
for index := range plugins {
plugins[index].DefaultEditor = false
}
}
replaced := false
for index := range plugins {
if plugins[index].ID == plugin.ID {
plugins[index] = plugin
replaced = true
}
}
if !replaced {
plugins = append(plugins, plugin)
}
if err := s.saveAdapterPlugins(domainUUID, plugins); err != nil {
writeEventJSON(w, 500, map[string]string{"error": err.Error()})
return
}
writeEventJSON(w, 200, plugin)
return
}
case "delete":
if r.Method == http.MethodPost || r.Method == http.MethodDelete {
var input struct {
ID string `json:"id"`
}
if !decodeEventJSON(w, r, &input) {
return
}
plugins, err := s.adapterPlugins(domainUUID)
if err != nil {
writeEventJSON(w, 500, map[string]string{"error": err.Error()})
return
}
filtered := plugins[:0]
for _, plugin := range plugins {
if plugin.ID != input.ID {
filtered = append(filtered, plugin)
}
}
if err := s.saveAdapterPlugins(domainUUID, filtered); err != nil {
writeEventJSON(w, 500, map[string]string{"error": err.Error()})
return
}
writeEventJSON(w, 200, map[string]bool{"deleted": true})
return
}
}
writeEventJSON(w, http.StatusMethodNotAllowed, map[string]string{"error": "unsupported adapter operation"})
}
func (s *Server) handleOpenWith(w http.ResponseWriter, r *http.Request) {
semanticPath := strings.TrimSpace(r.URL.Query().Get("path"))
adapterID := strings.TrimSpace(r.URL.Query().Get("adapter"))
if semanticPath == "" || adapterID == "" {
http.Error(w, "path and adapter are required", http.StatusBadRequest)
return
}
if s.authorizePathRequest(r, "read", semanticPath) != nil {
http.Error(w, "forbidden", http.StatusForbidden)
return
}
plugins, err := s.adapterPlugins(s.domainUUIDForRequest(r))
if err != nil {
http.Error(w, err.Error(), 500)
return
}
var selected *adapterPlugin
for index := range plugins {
if plugins[index].ID == adapterID && plugins[index].Enabled {
selected = &plugins[index]
break
}
}
if selected == nil {
http.NotFound(w, r)
return
}
actions, err := s.adapterActionsForPath(r, semanticPath)
if err != nil {
http.Error(w, err.Error(), 404)
return
}
allowed := false
for _, action := range actions {
if action.ID == selected.ID {
allowed = true
}
}
if !allowed {
http.Error(w, "adapter does not support this document", http.StatusBadRequest)
return
}
objectUUID, err := s.store.ResolvePathInDomain(s.domainUUIDForRequest(r), semanticPath)
if err != nil {
http.NotFound(w, r)
return
}
revision, err := s.latestRevisionForRequest(r, objectUUID)
if err != nil {
http.Error(w, err.Error(), 500)
return
}
scheme := "https"
if r.TLS == nil {
scheme = "http"
}
if forwarded := strings.ToLower(strings.TrimSpace(
strings.Split(r.Header.Get("X-Forwarded-Proto"), ",")[0],
)); forwarded == "http" || forwarded == "https" {
scheme = forwarded
}
rawURL := fmt.Sprintf("%s://%s%s", scheme, r.Host, rawProjectionURL("rev:"+revision.UUID))
filename := revision.Filename
if filename == "" {
filename = filepath.Base(semanticPath)
}
ticket := ""
if selected.Mode == "editor" {
if s.authorizePathRequest(r, "write", semanticPath) != nil {
http.Error(w, "forbidden", http.StatusForbidden)
return
}
principalUUID := ""
if principal, principalErr := s.store.PrincipalForSession(s.domainUUIDForRequest(r), s.authTokenFromRequest(r)); principalErr == nil {
principalUUID = principal.UUID
}
ticket, err = s.store.IssueAdapterTicketForPrincipal(
principalUUID, s.domainUUIDForRequest(r), selected.ID, objectUUID, revision.UUID, semanticPath,
)
if err != nil {
http.Error(w, err.Error(), 500)
return
}
}
origin := fmt.Sprintf("%s://%s", scheme, r.Host)
target := strings.NewReplacer(
"{url}", url.QueryEscape(rawURL),
"{path}", url.QueryEscape(semanticPath),
"{filename}", url.QueryEscape(filename),
"{ticket}", url.QueryEscape(ticket),
"{origin}", url.QueryEscape(origin),
).Replace(selected.URLTemplate)
http.Redirect(w, r, target, http.StatusFound)
}
func (s *Server) handleAdapterPluginConfig(w http.ResponseWriter, r *http.Request) {
domainUUID := s.domainUUIDForRequest(r)
id := strings.TrimSpace(r.URL.Query().Get("id"))
if r.Method == http.MethodPost {
if err := r.ParseForm(); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
id = strings.TrimSpace(r.FormValue("id"))
}
plugins, err := s.adapterPlugins(domainUUID)
if err != nil {
http.Error(w, err.Error(), 500)
return
}
index := -1
for candidate := range plugins {
if plugins[candidate].ID == id {
index = candidate
break
}
}
if index < 0 {
http.NotFound(w, r)
return
}
if r.Method == http.MethodPost {
if r.FormValue("connection_fields") == "1" {
plugins[index].Name = strings.TrimSpace(r.FormValue("name"))
plugins[index].Mode = strings.TrimSpace(r.FormValue("mode"))
plugins[index].URLTemplate = strings.TrimSpace(r.FormValue("url_template"))
plugins[index].Enabled = r.FormValue("enabled") != ""
plugins[index].MediaTypes = splitAdapterList(r.FormValue("media_types"))
plugins[index].Extensions = splitAdapterList(r.FormValue("extensions"))
if err := validateAdapterPlugin(&plugins[index]); err != nil {
http.Error(w, err.Error(), 400)
return
}
}
plugins[index].NewTab = boolFormValue(r.FormValue("new_tab")) == "true"
plugins[index].HTMLMarkdown = boolFormValue(r.FormValue("html_markdown")) == "true"
makeDefault := boolFormValue(r.FormValue("default_editor")) == "true"
if makeDefault && plugins[index].Mode != "editor" {
http.Error(w, "only an editor can be the default editor", http.StatusBadRequest)
return
}
if makeDefault {
for candidate := range plugins {
plugins[candidate].DefaultEditor = candidate == index
}
} else {
plugins[index].DefaultEditor = false
}
if err := s.saveAdapterPlugins(domainUUID, plugins); err != nil {
http.Error(w, err.Error(), 500)
return
}
http.Redirect(w, r, "/-/sys/config?panel="+url.QueryEscape("adapter-"+id)+"&saved=1", http.StatusFound)
return
}
http.Redirect(w, r, "/-/sys/config?panel="+url.QueryEscape("adapter-"+id), http.StatusFound)
}
func splitAdapterList(value string) []string {
var values []string
for _, item := range strings.Split(value, ",") {
if item = strings.TrimSpace(item); item != "" {
values = append(values, item)
}
}
return values
}