Files
at-container-registry/pkg/appview/handlers/api.go
T

322 lines
10 KiB
Go

package handlers
import (
"bytes"
"database/sql"
"errors"
"fmt"
"html/template"
"log/slog"
"net/http"
"atcr.io/pkg/appview/db"
"atcr.io/pkg/appview/middleware"
"atcr.io/pkg/atproto"
"atcr.io/pkg/auth/oauth"
"github.com/bluesky-social/indigo/atproto/identity"
"github.com/go-chi/chi/v5"
"github.com/go-chi/render"
)
// StarRepositoryHandler handles starring a repository
type StarRepositoryHandler struct {
DB *sql.DB
Directory identity.Directory
Refresher *oauth.Refresher
Templates *template.Template
}
func (h *StarRepositoryHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// Get authenticated user from middleware
user := middleware.GetUser(r)
if user == nil {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
// Extract parameters
handle := chi.URLParam(r, "handle")
repository := chi.URLParam(r, "repository")
// Resolve owner's handle to DID
ownerDID, err := atproto.ResolveHandleToDID(r.Context(), handle)
if err != nil {
slog.Warn("Failed to resolve handle for star", "handle", handle, "error", err)
http.Error(w, fmt.Sprintf("Failed to resolve handle: %v", err), http.StatusBadRequest)
return
}
// Create ATProto client with session provider (uses DoWithSession for DPoP nonce safety)
slog.Debug("Creating PDS client for star", "user_did", user.DID)
pdsClient := atproto.NewClientWithSessionProvider(user.PDSEndpoint, user.DID, h.Refresher)
// Create star record
starRecord := atproto.NewStarRecord(ownerDID, repository)
rkey := atproto.StarRecordKey(ownerDID, repository)
// Write star record to user's PDS
_, err = pdsClient.PutRecord(r.Context(), atproto.StarCollection, rkey, starRecord)
if err != nil {
// Check if OAuth error - if so, invalidate sessions and return 401
if handleOAuthError(r.Context(), h.Refresher, user.DID, err) {
http.Error(w, "Authentication failed, please log in again", http.StatusUnauthorized)
return
}
slog.Error("Failed to create star record", "error", err)
http.Error(w, fmt.Sprintf("Failed to create star: %v", err), http.StatusInternalServerError)
return
}
// Check if HTMX request - return HTML component
if r.Header.Get("HX-Request") == "true" && h.Templates != nil {
// Get current star count and do optimistic increment
stats, _ := db.GetRepositoryStats(h.DB, ownerDID, repository)
starCount := 0
if stats != nil {
starCount = stats.StarCount
}
starCount++ // Optimistic increment
renderStarComponent(w, h.Templates, handle, repository, true, starCount)
return
}
// Return JSON for API clients
w.WriteHeader(http.StatusCreated)
render.JSON(w, r, map[string]bool{"starred": true})
}
// UnstarRepositoryHandler handles unstarring a repository
type UnstarRepositoryHandler struct {
DB *sql.DB
Directory identity.Directory
Refresher *oauth.Refresher
Templates *template.Template
}
func (h *UnstarRepositoryHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// Get authenticated user from middleware
user := middleware.GetUser(r)
if user == nil {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
// Extract parameters
handle := chi.URLParam(r, "handle")
repository := chi.URLParam(r, "repository")
// Resolve owner's handle to DID
ownerDID, err := atproto.ResolveHandleToDID(r.Context(), handle)
if err != nil {
slog.Warn("Failed to resolve handle for unstar", "handle", handle, "error", err)
http.Error(w, fmt.Sprintf("Failed to resolve handle: %v", err), http.StatusBadRequest)
return
}
// Create ATProto client with session provider (uses DoWithSession for DPoP nonce safety)
slog.Debug("Creating PDS client for unstar", "user_did", user.DID)
pdsClient := atproto.NewClientWithSessionProvider(user.PDSEndpoint, user.DID, h.Refresher)
// Delete star record from user's PDS
rkey := atproto.StarRecordKey(ownerDID, repository)
slog.Debug("Deleting star record", "handle", handle, "repository", repository, "rkey", rkey)
err = pdsClient.DeleteRecord(r.Context(), atproto.StarCollection, rkey)
if err != nil {
// If record doesn't exist, still return success (idempotent)
if !errors.Is(err, atproto.ErrRecordNotFound) {
// Check if OAuth error - if so, invalidate sessions and return 401
if handleOAuthError(r.Context(), h.Refresher, user.DID, err) {
http.Error(w, "Authentication failed, please log in again", http.StatusUnauthorized)
return
}
slog.Error("Failed to delete star record", "error", err)
http.Error(w, fmt.Sprintf("Failed to delete star: %v", err), http.StatusInternalServerError)
return
}
slog.Debug("Star record not found, already unstarred")
}
// Check if HTMX request - return HTML component
if r.Header.Get("HX-Request") == "true" && h.Templates != nil {
// Get current star count and do optimistic decrement
stats, _ := db.GetRepositoryStats(h.DB, ownerDID, repository)
starCount := 0
if stats != nil {
starCount = stats.StarCount
}
if starCount > 0 {
starCount-- // Optimistic decrement
}
renderStarComponent(w, h.Templates, handle, repository, false, starCount)
return
}
// Return JSON for API clients
render.JSON(w, r, map[string]bool{"starred": false})
}
// CheckStarHandler checks if current user has starred a repository
type CheckStarHandler struct {
DB *sql.DB
Directory identity.Directory
Refresher *oauth.Refresher
}
func (h *CheckStarHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// Get authenticated user from middleware
user := middleware.GetUser(r)
if user == nil {
// Not authenticated - return not starred
render.JSON(w, r, map[string]bool{"starred": false})
return
}
// Extract parameters
handle := chi.URLParam(r, "handle")
repository := chi.URLParam(r, "repository")
// Resolve owner's handle to DID
ownerDID, err := atproto.ResolveHandleToDID(r.Context(), handle)
if err != nil {
slog.Warn("Failed to resolve handle for check star", "handle", handle, "error", err)
http.Error(w, fmt.Sprintf("Failed to resolve handle: %v", err), http.StatusBadRequest)
return
}
// Create ATProto client with session provider (uses DoWithSession for DPoP nonce safety)
// Note: Error handling moves to the PDS call - if session doesn't exist, GetRecord will fail
pdsClient := atproto.NewClientWithSessionProvider(user.PDSEndpoint, user.DID, h.Refresher)
// Check if star record exists
rkey := atproto.StarRecordKey(ownerDID, repository)
_, err = pdsClient.GetRecord(r.Context(), atproto.StarCollection, rkey)
// Check if OAuth error - if so, invalidate sessions
if err != nil && handleOAuthError(r.Context(), h.Refresher, user.DID, err) {
// For a read operation, just return not starred instead of error
render.JSON(w, r, map[string]bool{"starred": false})
return
}
starred := err == nil
// Return result
render.JSON(w, r, map[string]bool{"starred": starred})
}
// GetStatsHandler returns repository statistics
type GetStatsHandler struct {
DB *sql.DB
Directory identity.Directory
}
func (h *GetStatsHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// Extract parameters
handle := chi.URLParam(r, "handle")
repository := chi.URLParam(r, "repository")
// Resolve owner's handle to DID
ownerDID, err := atproto.ResolveHandleToDID(r.Context(), handle)
if err != nil {
http.Error(w, "Failed to resolve handle", http.StatusBadRequest)
return
}
// Get repository stats from database
stats, err := db.GetRepositoryStats(h.DB, ownerDID, repository)
if err != nil {
http.Error(w, "Failed to fetch stats", http.StatusInternalServerError)
return
}
// Return stats as JSON
render.JSON(w, r, stats)
}
// ManifestDetailHandler returns detailed manifest information including platforms
type ManifestDetailHandler struct {
DB *sql.DB
Directory identity.Directory
}
func (h *ManifestDetailHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// Extract parameters
handle := chi.URLParam(r, "handle")
repository := chi.URLParam(r, "repository")
digest := chi.URLParam(r, "digest")
// Resolve owner's handle to DID
ownerDID, err := atproto.ResolveHandleToDID(r.Context(), handle)
if err != nil {
http.Error(w, "Failed to resolve handle", http.StatusBadRequest)
return
}
// Get manifest detail from database
manifest, err := db.GetManifestDetail(h.DB, ownerDID, repository, digest)
if err != nil {
if err.Error() == "manifest not found" {
http.Error(w, "Manifest not found", http.StatusNotFound)
return
}
slog.Error("Failed to get manifest detail", "error", err)
http.Error(w, "Failed to fetch manifest", http.StatusInternalServerError)
return
}
// Return manifest as JSON
render.JSON(w, r, manifest)
}
// CredentialHelperVersionResponse is the response for the credential helper version API
type CredentialHelperVersionResponse struct {
Latest string `json:"latest"`
DownloadURLs map[string]string `json:"download_urls"`
Checksums map[string]string `json:"checksums"`
ReleaseNotes string `json:"release_notes,omitempty"`
}
// CredentialHelperVersionHandler returns the latest credential helper version info
// Note: Version info is fetched dynamically from TangledRepo's releases
type CredentialHelperVersionHandler struct {
TangledRepo string
}
func (h *CredentialHelperVersionHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// This endpoint directs users to the Tangled repository for downloads
// Version info should be fetched from the repository's releases page
response := CredentialHelperVersionResponse{
Latest: "",
DownloadURLs: map[string]string{"tangled_repo": h.TangledRepo},
Checksums: nil,
ReleaseNotes: "Visit the Tangled repository for the latest releases: " + h.TangledRepo,
}
render.SetContentType(render.ContentTypeJSON)
w.Header().Set("Cache-Control", "public, max-age=300") // Cache for 5 minutes
render.JSON(w, r, response)
}
// renderStarComponent renders the star component HTML for HTMX responses
func renderStarComponent(w http.ResponseWriter, tmpl *template.Template, handle, repository string, isStarred bool, starCount int) {
data := map[string]any{
"Interactive": true,
"Handle": handle,
"Repository": repository,
"IsStarred": isStarred,
"StarCount": starCount,
}
var buf bytes.Buffer
if err := tmpl.ExecuteTemplate(&buf, "star", data); err != nil {
slog.Error("Failed to render star component", "error", err)
http.Error(w, "Failed to render component", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
_, _ = w.Write(buf.Bytes())
}