mirror of
https://github.com/J3vb/OwnCord.git
synced 2026-09-03 03:50:00 +03:00
* feat(auth): add revocable API tokens (bot/service auth) Add long-lived, revocable API tokens so headless clients (the introspection MCP tool, bots, CI) can authenticate without a password. Presented as "Authorization: Bearer <token>", a token authenticates as a specific user, inheriting that user's role and permissions. - migration 018 + dedicated api_tokens table (kept separate from sessions so bulk logout and the per-user session cap never touch these); only the SHA-256 hash is stored, raw token shown once at creation - auth.ResolveTokenHash: one shared bearer resolver that both AuthMiddleware and adminAuthMiddleware now call. Sessions are matched first so existing login behavior is unchanged; API tokens are a fallback only on session miss. A DB outage is returned wrapped, never mistaken for a bad token. - `server token create|list|revoke` CLI: mints directly against the DB with no HTTP and no login — the password-free bootstrap path - tests: resolver (8 cases incl. outage-not-fallthrough), db queries (6), api middleware integration (valid + revoked token) Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * feat(tools): add owncord-introspect MCP server A local MCP dev tool that lets Claude Code introspect a running OwnCord instance: read its logs, query any REST endpoint, and tail the desktop client's log file. It is a thin wrapper over the existing API plus the client log — no new product surface. - tools/mcp-introspect/index.mjs (Node/ESM, one dep: @modelcontextprotocol/sdk) exposes api_request (full read-write passthrough), server_logs (admin SSE ring-buffer stream), client_logs (reads the desktop log file) - authenticates with an API token (OWNCORD_API_TOKEN); pins the self-signed cert and skips hostname checks (the cert has no SAN) - registered in .mcp.json (secret-free ${OWNCORD_API_TOKEN}) - un-ignore tools/mcp-introspect/ so this shared dev tool is committed, while tools/livekit-server.exe and node_modules stay ignored - docs/mcp-introspect.md: how it works, tool reference, setup, troubleshooting Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * feat(dependencies): update and add various crate versions in Cargo.lock * feat(admin): manage API tokens from the admin panel Add Owner-gated HTTP endpoints and a UI card to create, list, and revoke API tokens from the web admin panel. Previously only the `server token` CLI could manage them, which requires shell access to the host. - POST|GET|DELETE /admin/api/tokens in admin/handlers_tokens.go, wired in admin/api.go. All three are Owner-only (ownerOnlyMiddleware, like backups/updates): an HTTP token-mint endpoint is a network-reachable credential-minting surface, and API tokens deliberately survive password change + bulk logout, so a hijacked admin session must not mint one. - Reuses the same db.*APIToken calls as the CLI; create sources the actor from request context (audits who clicked, not the bound user); the raw token is returned once in the 201 body, never stored. - Add json tags to db.APITokenListItem for snake_case wire consistency. - Admin panel: "API Tokens" nav item + create modal, show-once reveal, revoke confirm in admin/static/index.html. - Tests: 7 in admin/api_test.go (+api_tokens table in the in-memory schema). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * refactor: modernize to Go 1.26 idioms + enable modernize linter Apply `golangci-lint modernize` autofixes across the server and enable the linter in .golangci.yml so these stop re-accumulating (they built up only because modernize was never in the config). Production code: slices.Contains for hand-rolled membership loops (api router, ws origin, db/account, plugin manifest); strings.SplitSeq for allocation-free line/segment iteration (db/migrate, updater, livekit_proxy); strings.Cut (config); fmt.Appendf (dm_handler); min() (event_pruner); any (ws client). Tests: range-over-int, t.Context(), WaitGroup.Go, slices.Sort, maps.Copy, new(expr), interface{}->any. - plugin/manifest.go parent-traversal check applied by hand: modernize skipped it (two conflicting rewrites); used the slices.Contains form. - Removed the now-dead ptr() test helper after newexpr inlined its callers. - Dropped dangling sort imports left by the sort.Slice->slices.Sort rewrite. No behavior change. All four tag variants build, full test suite is green, and golangci-lint (with modernize enabled) reports 0 issues. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
219 lines
6.2 KiB
Go
219 lines
6.2 KiB
Go
package api
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"log/slog"
|
|
"net/http"
|
|
|
|
"github.com/go-chi/chi/v5"
|
|
"github.com/owncord/server/db"
|
|
"github.com/owncord/server/service"
|
|
)
|
|
|
|
// DMBroadcaster is the interface needed to send WebSocket events from REST
|
|
// handlers. Satisfied by *ws.Hub.
|
|
type DMBroadcaster interface {
|
|
SendToUser(userID int64, msg []byte) bool
|
|
}
|
|
|
|
// MountDMRoutes registers DM-related routes onto r.
|
|
// All routes require authentication.
|
|
// hub is used to send real-time WebSocket events on DM close.
|
|
func MountDMRoutes(r chi.Router, database *db.DB, svc *service.Services, broadcaster DMBroadcaster) {
|
|
r.Route("/api/v1/dms", func(r chi.Router) {
|
|
r.Use(AuthMiddleware(database))
|
|
r.Post("/", handleCreateDM(svc))
|
|
r.Get("/", handleListDMs(svc))
|
|
r.Delete("/{channelId}", handleCloseDM(svc, broadcaster))
|
|
})
|
|
|
|
// User blocking routes — prevent DM creation and messaging.
|
|
r.Route("/api/v1/blocks", func(r chi.Router) {
|
|
r.Use(AuthMiddleware(database))
|
|
r.Get("/", handleListBlocks(svc))
|
|
r.Put("/{userId}", handleBlockUser(svc))
|
|
r.Delete("/{userId}", handleUnblockUser(svc))
|
|
})
|
|
}
|
|
|
|
// createDMRequest is the JSON body for POST /api/v1/dms.
|
|
type createDMRequest struct {
|
|
RecipientID int64 `json:"recipient_id"`
|
|
}
|
|
|
|
// createDMResponse is the JSON response for POST /api/v1/dms.
|
|
type createDMResponse struct {
|
|
ChannelID int64 `json:"channel_id"`
|
|
Recipient db.DMUser `json:"recipient"`
|
|
Created bool `json:"created"`
|
|
}
|
|
|
|
// listDMsResponse is the JSON response for GET /api/v1/dms.
|
|
type listDMsResponse struct {
|
|
DMChannels []db.DMChannelInfo `json:"dm_channels"`
|
|
}
|
|
|
|
// handleCreateDM creates or retrieves a DM channel with a recipient.
|
|
func handleCreateDM(svc *service.Services) http.HandlerFunc {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
user, ok := r.Context().Value(UserKey).(*db.User)
|
|
if !ok || user == nil {
|
|
writeJSON(w, http.StatusUnauthorized, errorResponse{
|
|
Error: "UNAUTHORIZED", Message: "authentication required",
|
|
})
|
|
return
|
|
}
|
|
|
|
var req createDMRequest
|
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
|
writeJSON(w, http.StatusBadRequest, errorResponse{
|
|
Error: "BAD_REQUEST", Message: "invalid request body",
|
|
})
|
|
return
|
|
}
|
|
|
|
result, err := svc.DMs.CreateDM(r.Context(), user.ID, req.RecipientID)
|
|
if err != nil {
|
|
writeServiceError(r.Context(), w, err)
|
|
return
|
|
}
|
|
|
|
avatarStr := ""
|
|
if result.Recipient.Avatar != nil {
|
|
avatarStr = *result.Recipient.Avatar
|
|
}
|
|
dmUser := db.DMUser{
|
|
ID: result.Recipient.ID,
|
|
Username: result.Recipient.Username,
|
|
Avatar: avatarStr,
|
|
Status: result.Recipient.Status,
|
|
}
|
|
|
|
status := http.StatusOK
|
|
if result.Created {
|
|
status = http.StatusCreated
|
|
}
|
|
writeJSON(w, status, createDMResponse{
|
|
ChannelID: result.Channel.ID,
|
|
Recipient: dmUser,
|
|
Created: result.Created,
|
|
})
|
|
}
|
|
}
|
|
|
|
// handleListDMs returns all open DM channels for the authenticated user.
|
|
func handleListDMs(svc *service.Services) http.HandlerFunc {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
user, ok := r.Context().Value(UserKey).(*db.User)
|
|
if !ok || user == nil {
|
|
writeJSON(w, http.StatusUnauthorized, errorResponse{
|
|
Error: "UNAUTHORIZED", Message: "authentication required",
|
|
})
|
|
return
|
|
}
|
|
|
|
channels, err := svc.DMs.ListDMs(r.Context(), user.ID)
|
|
if err != nil {
|
|
writeServiceError(r.Context(), w, err)
|
|
return
|
|
}
|
|
writeJSON(w, http.StatusOK, listDMsResponse{DMChannels: channels})
|
|
}
|
|
}
|
|
|
|
// handleCloseDM removes a DM channel from the authenticated user's open list.
|
|
func handleCloseDM(svc *service.Services, broadcaster DMBroadcaster) http.HandlerFunc {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
user, ok := r.Context().Value(UserKey).(*db.User)
|
|
if !ok || user == nil {
|
|
writeJSON(w, http.StatusUnauthorized, errorResponse{
|
|
Error: "UNAUTHORIZED", Message: "authentication required",
|
|
})
|
|
return
|
|
}
|
|
|
|
channelID, ok := parseIDParam(w, r, "channelId")
|
|
if !ok {
|
|
return
|
|
}
|
|
|
|
if err := svc.DMs.CloseDM(r.Context(), user.ID, channelID); err != nil {
|
|
writeServiceError(r.Context(), w, err)
|
|
return
|
|
}
|
|
|
|
// Notify via WebSocket so sidebar updates immediately.
|
|
if broadcaster != nil {
|
|
closeMsg := fmt.Appendf(nil, `{"type":"dm_channel_close","payload":{"channel_id":%d}}`, channelID)
|
|
if ok := broadcaster.SendToUser(user.ID, closeMsg); !ok {
|
|
slog.Debug("handleCloseDM: user not connected", "user_id", user.ID, "channel_id", channelID)
|
|
}
|
|
}
|
|
|
|
w.WriteHeader(http.StatusNoContent)
|
|
}
|
|
}
|
|
|
|
// handleBlockUser blocks a user.
|
|
func handleBlockUser(svc *service.Services) http.HandlerFunc {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
user, _ := r.Context().Value(UserKey).(*db.User)
|
|
if user == nil {
|
|
writeJSON(w, http.StatusUnauthorized, errorResponse{Error: "UNAUTHORIZED", Message: "authentication required"})
|
|
return
|
|
}
|
|
|
|
targetID, ok := parseIDParam(w, r, "userId")
|
|
if !ok {
|
|
return
|
|
}
|
|
|
|
if err := svc.Blocks.BlockUser(r.Context(), user.ID, targetID); err != nil {
|
|
writeServiceError(r.Context(), w, err)
|
|
return
|
|
}
|
|
writeJSON(w, http.StatusOK, map[string]string{"message": "user blocked"})
|
|
}
|
|
}
|
|
|
|
// handleUnblockUser unblocks a user.
|
|
func handleUnblockUser(svc *service.Services) http.HandlerFunc {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
user, _ := r.Context().Value(UserKey).(*db.User)
|
|
if user == nil {
|
|
writeJSON(w, http.StatusUnauthorized, errorResponse{Error: "UNAUTHORIZED", Message: "authentication required"})
|
|
return
|
|
}
|
|
|
|
targetID, ok := parseIDParam(w, r, "userId")
|
|
if !ok {
|
|
return
|
|
}
|
|
|
|
if err := svc.Blocks.UnblockUser(r.Context(), user.ID, targetID); err != nil {
|
|
writeServiceError(r.Context(), w, err)
|
|
return
|
|
}
|
|
writeJSON(w, http.StatusOK, map[string]string{"message": "user unblocked"})
|
|
}
|
|
}
|
|
|
|
// handleListBlocks returns all blocked user IDs.
|
|
func handleListBlocks(svc *service.Services) http.HandlerFunc {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
user, _ := r.Context().Value(UserKey).(*db.User)
|
|
if user == nil {
|
|
writeJSON(w, http.StatusUnauthorized, errorResponse{Error: "UNAUTHORIZED", Message: "authentication required"})
|
|
return
|
|
}
|
|
|
|
ids, err := svc.Blocks.ListBlocked(r.Context(), user.ID)
|
|
if err != nil {
|
|
writeServiceError(r.Context(), w, err)
|
|
return
|
|
}
|
|
writeJSON(w, http.StatusOK, map[string]any{"blocked_user_ids": ids})
|
|
}
|
|
}
|