Mobile app (Android):
- Sign-in to any server, with authenticator codes. The server address and
token are kept in secure storage; a dropped connection never signs out.
- Workspaces, recent pages, spaces and a foldable page tree; search; the
inbox with mark-read.
- Pages open read-only in the shared editor from their saved content and
join the live document to edit (with the native toolbar). Page links in
the text open in the app (new "navigate" bridge message).
- Comments: threads, replies, resolve.
- "Save to Docwell" in the Android share sheet makes a page from shared
text, with web addresses as links.
- Offline reading: every answer the app reads is kept on the phone, and
used when the server can't be reached.
- Push through UnifiedPush (ntfy, NextPush, ...). The app uses the Android
connector directly; the umbrella package pulls in a native crypto build
for Linux that breaks `dart run` and tests.
Server:
- /me/devices registers a phone's UnifiedPush endpoint and Web Push keys
(new push_devices collection). Each notification is also pushed,
encrypted with RFC 8291 aes128gcm so the distributor can't read it; the
app drops messages that don't decrypt. Endpoints answering 404/410 are
forgotten. Endpoints follow the webhook address rules.
- /collab accepts the apps' own origins ("null" for the mobile editor page,
wails:// for the desktop app). Sign-in is a token in the first message,
not a cookie, so this opens no cross-site hijacking.
Tried on an Android 15 emulator: sign-in, browsing, reading, live editing,
sharing and offline reading. Not covered: push end to end (no distributor
on the emulator), iOS, and YouTube embeds, which refuse to play from the
app's local editor page (error 153).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
197 lines
5.4 KiB
Go
197 lines
5.4 KiB
Go
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||
|
||
package httpapi
|
||
|
||
import (
|
||
"context"
|
||
"errors"
|
||
"net/http"
|
||
"net/url"
|
||
"time"
|
||
|
||
"github.com/coder/websocket"
|
||
|
||
"docwell/server/internal/access"
|
||
"docwell/server/internal/collab"
|
||
)
|
||
|
||
// recheckEvery is how often an open connection's access is checked again, so
|
||
// role changes reach editors that stay connected.
|
||
var recheckEvery = 30 * time.Second
|
||
|
||
// CollabHub is the part of collab.Hub the WebSocket endpoint uses.
|
||
type CollabHub interface {
|
||
Join(ctx context.Context, page, user string, canWrite bool, p collab.Peer) (*collab.Session, error)
|
||
}
|
||
|
||
// Close codes the editor reacts to (4000–4999 are free for applications).
|
||
const (
|
||
closeUnauthorized = 4401
|
||
closeNotFound = collab.CloseGone
|
||
)
|
||
|
||
// collabRoute serves /collab?page=<id>: the y-websocket protocol for one page.
|
||
// Browsers cannot set headers on a WebSocket, and tokens in URLs end up in
|
||
// logs, so the first message must be a text frame holding the session token.
|
||
func (a *api) collabRoute(mux *routeMux, origins []string) {
|
||
patterns := make([]string, 0, len(origins))
|
||
for _, o := range origins {
|
||
if u, err := url.Parse(o); err == nil && u.Host != "" {
|
||
patterns = append(patterns, u.Host)
|
||
}
|
||
}
|
||
mux.HandleFunc("GET /collab", func(w http.ResponseWriter, r *http.Request) {
|
||
if a.collab == nil {
|
||
writeJSON(w, http.StatusNotFound, map[string]string{"error": "not_found"})
|
||
return
|
||
}
|
||
opts := &websocket.AcceptOptions{OriginPatterns: patterns}
|
||
// The apps' editors have origins no server can list: the mobile
|
||
// WebView's bundled page sends "null", the desktop app wails://.
|
||
// Signing in takes the token as the first message (no cookies), so
|
||
// another site's page can't ride on someone's session either way.
|
||
if appOrigin(r.Header.Get("Origin")) {
|
||
opts.InsecureSkipVerify = true
|
||
}
|
||
conn, err := websocket.Accept(w, r, opts)
|
||
if err != nil {
|
||
return
|
||
}
|
||
defer conn.CloseNow()
|
||
conn.SetReadLimit(16 << 20)
|
||
a.serveCollab(r.Context(), conn, r.URL.Query().Get("page"))
|
||
})
|
||
}
|
||
|
||
func (a *api) serveCollab(ctx context.Context, conn *websocket.Conn, page string) {
|
||
authCtx, cancel := context.WithTimeout(ctx, 10*time.Second)
|
||
typ, token, err := conn.Read(authCtx)
|
||
cancel()
|
||
if err != nil || typ != websocket.MessageText {
|
||
conn.Close(closeUnauthorized, "send the session token first")
|
||
return
|
||
}
|
||
user, err := a.auth.Verify(ctx, string(token))
|
||
if err != nil {
|
||
conn.Close(closeUnauthorized, "unauthorized")
|
||
return
|
||
}
|
||
canWrite, err := a.dir.CollabAccess(ctx, user.Caller(), page)
|
||
if err != nil {
|
||
conn.Close(closeNotFound, "page not found")
|
||
return
|
||
}
|
||
|
||
ctx, cancel = context.WithCancel(ctx)
|
||
defer cancel()
|
||
p := &wsPeer{out: make(chan []byte, 1024), cancel: cancel, conn: conn}
|
||
go p.write(ctx, conn)
|
||
session, err := a.collab.Join(ctx, page, user.ID, canWrite, p)
|
||
if err != nil {
|
||
a.log.Error("collab: join", "page", page, "err", err)
|
||
conn.Close(websocket.StatusInternalError, "could not open the page")
|
||
return
|
||
}
|
||
defer session.Leave()
|
||
go a.recheckCollab(ctx, p, user.Caller(), page, canWrite)
|
||
for {
|
||
typ, msg, err := conn.Read(ctx)
|
||
if err != nil {
|
||
return
|
||
}
|
||
if typ != websocket.MessageBinary {
|
||
continue
|
||
}
|
||
if err := session.Receive(ctx, msg); err != nil {
|
||
conn.Close(websocket.StatusUnsupportedData, "malformed message")
|
||
return
|
||
}
|
||
}
|
||
}
|
||
|
||
// recheckCollab disconnects the peer once its access to the page changes:
|
||
// gone (no longer allowed, or page deleted) or a different write right. The
|
||
// editor then reloads the page and reconnects with its new rights.
|
||
func (a *api) recheckCollab(ctx context.Context, p *wsPeer, c access.Caller, page string, canWrite bool) {
|
||
t := time.NewTicker(recheckEvery)
|
||
defer t.Stop()
|
||
for {
|
||
select {
|
||
case <-ctx.Done():
|
||
return
|
||
case <-t.C:
|
||
}
|
||
now, err := a.dir.CollabAccess(ctx, c, page)
|
||
switch {
|
||
case ctx.Err() != nil:
|
||
return
|
||
case err != nil:
|
||
p.Close(collab.CloseGone, "page not found")
|
||
return
|
||
case now != canWrite:
|
||
p.Close(collab.CloseAccessChanged, "access changed")
|
||
return
|
||
}
|
||
}
|
||
}
|
||
|
||
// wsPeer queues outgoing messages; a peer that falls 1024 messages behind is
|
||
// disconnected and catches up through a fresh sync when it reconnects.
|
||
type wsPeer struct {
|
||
out chan []byte
|
||
cancel context.CancelFunc
|
||
conn *websocket.Conn
|
||
}
|
||
|
||
// Close sends a close frame; the read loop then ends and the session leaves.
|
||
func (p *wsPeer) Close(code int, reason string) {
|
||
go p.conn.Close(websocket.StatusCode(code), reason)
|
||
}
|
||
|
||
func (p *wsPeer) Send(msg []byte) bool {
|
||
select {
|
||
case p.out <- msg:
|
||
return true
|
||
default:
|
||
p.cancel()
|
||
return false
|
||
}
|
||
}
|
||
|
||
func (p *wsPeer) write(ctx context.Context, conn *websocket.Conn) {
|
||
ping := time.NewTicker(30 * time.Second)
|
||
defer ping.Stop()
|
||
for {
|
||
select {
|
||
case msg := <-p.out:
|
||
wctx, cancel := context.WithTimeout(ctx, 10*time.Second)
|
||
err := conn.Write(wctx, websocket.MessageBinary, msg)
|
||
cancel()
|
||
if err != nil {
|
||
p.cancel()
|
||
return
|
||
}
|
||
case <-ping.C:
|
||
pctx, cancel := context.WithTimeout(ctx, 10*time.Second)
|
||
err := conn.Ping(pctx)
|
||
cancel()
|
||
if err != nil && !errors.Is(err, context.Canceled) {
|
||
p.cancel()
|
||
return
|
||
}
|
||
case <-ctx.Done():
|
||
return
|
||
}
|
||
}
|
||
}
|
||
|
||
// appOrigin reports whether origin is one of Docwell's own apps: the mobile
|
||
// editor page (a local file, "null") or the desktop app (Wails).
|
||
func appOrigin(origin string) bool {
|
||
if origin == "null" {
|
||
return true
|
||
}
|
||
u, err := url.Parse(origin)
|
||
return err == nil && (u.Scheme == "wails" || u.Hostname() == "wails.localhost")
|
||
}
|