Files
Docwell/Server/internal/auth/filetoken.go
T
tajniak81andClaude Opus 5.5 e49b1ab34f Add page attachments with images and file blocks
Editors upload files to a page (attach button, paste or drop); images go
into the document as images and other files as download cards. Files are
stored in a new attachments collection, so PocketBase's local or S3
storage applies, and docwell-server streams them after checking the
reader's page access.

Documents keep the file's API path. Because <img> tags cannot send the
Authorization header, clients load files with a short-lived signed file
token (?token=) instead of the session token. Uploads are limited by
DOCWELL_MAX_UPLOAD_MB (default 50), their type is sniffed from the
content, and only images, PDFs and media are served inline, so an
uploaded HTML or SVG file never runs on the API's origin.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 16:51:56 +01:00

61 lines
1.8 KiB
Go

// SPDX-License-Identifier: AGPL-3.0-or-later
package auth
import (
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"strconv"
"strings"
"time"
)
// FileTokens issues short-lived tokens that let <img> and download links
// load attachments: browsers cannot send the Authorization header there, and
// putting the session token in a URL would leak it into logs and history.
// A file token only identifies the user; every download still checks their
// rights to the page.
type FileTokens struct {
key []byte
ttl time.Duration
now func() time.Time
}
// NewFileTokens signs tokens with a key derived from secret.
func NewFileTokens(secret string, ttl time.Duration) *FileTokens {
sum := sha256.Sum256([]byte("docwell-file-token:" + secret))
return &FileTokens{key: sum[:], ttl: ttl, now: time.Now}
}
func (f *FileTokens) sign(payload string) string {
mac := hmac.New(sha256.New, f.key)
mac.Write([]byte(payload))
return base64.RawURLEncoding.EncodeToString(mac.Sum(nil))
}
// Issue returns a token for userID and when it expires.
func (f *FileTokens) Issue(userID string) (string, time.Time) {
exp := f.now().Add(f.ttl).Truncate(time.Second)
payload := userID + "." + strconv.FormatInt(exp.Unix(), 10)
return payload + "." + f.sign(payload), exp
}
// Parse returns the user a valid, unexpired token was issued to.
func (f *FileTokens) Parse(token string) (string, error) {
i := strings.LastIndexByte(token, '.')
if i < 0 {
return "", ErrUnauthorized
}
payload, sig := token[:i], token[i+1:]
if !hmac.Equal([]byte(sig), []byte(f.sign(payload))) {
return "", ErrUnauthorized
}
userID, expStr, ok := strings.Cut(payload, ".")
exp, err := strconv.ParseInt(expStr, 10, 64)
if !ok || err != nil || userID == "" || f.now().Unix() > exp {
return "", ErrUnauthorized
}
return userID, nil
}