feat: Phase 1 - Core API server with authentication

- Added database schema for users, api_keys, sync_state, change_log, and sync_config
- Implemented API key generation and validation with bcrypt hashing
- Created Chi-based REST API server with endpoints for:
  - Task CRUD operations (create, read, update, delete)
  - Task actions (complete, start, stop)
  - Tag management (list, add, remove)
  - Projects listing
  - Health check endpoint
- Added middleware for authentication and CORS
- Implemented change log tracking with triggers (key:value format)
- Added configurable change log retention (default 30 days)
- Created server CLI commands (opal server start, opal server keygen)
- Dependencies added: golang.org/x/crypto/bcrypt, github.com/go-chi/chi/v5
This commit is contained in:
2026-01-05 16:14:49 +01:00
parent 9bde1aefea
commit ba0cfc08e3
16 changed files with 1423 additions and 7 deletions
+41
View File
@@ -0,0 +1,41 @@
package handlers
import (
"net/http"
"strconv"
"git.jnss.me/joakim/opal/internal/engine"
"github.com/go-chi/chi/v5"
)
// ListAPIKeys returns all API keys for the current user
func ListAPIKeys(w http.ResponseWriter, r *http.Request) {
// For now, use default user ID (1 - shared user)
userID := 1
keys, err := engine.ListAPIKeys(userID)
if err != nil {
errorResponse(w, http.StatusInternalServerError, err.Error())
return
}
jsonResponse(w, http.StatusOK, keys)
}
// RevokeAPIKey revokes an API key by ID
func RevokeAPIKey(w http.ResponseWriter, r *http.Request) {
idStr := chi.URLParam(r, "id")
keyID, err := strconv.Atoi(idStr)
if err != nil {
errorResponse(w, http.StatusBadRequest, "invalid key ID")
return
}
if err := engine.RevokeAPIKey(keyID); err != nil {
errorResponse(w, http.StatusInternalServerError, err.Error())
return
}
jsonResponse(w, http.StatusOK, map[string]string{"message": "API key revoked"})
}
@@ -0,0 +1,18 @@
package handlers
import (
"net/http"
"git.jnss.me/joakim/opal/internal/engine"
)
// ListProjects returns all unique projects from all tasks
func ListProjects(w http.ResponseWriter, r *http.Request) {
projects, err := engine.GetAllProjects()
if err != nil {
errorResponse(w, http.StatusInternalServerError, err.Error())
return
}
jsonResponse(w, http.StatusOK, projects)
}
+167
View File
@@ -0,0 +1,167 @@
package handlers
import (
"encoding/json"
"net/http"
"git.jnss.me/joakim/opal/internal/engine"
)
// GetChangesRequest represents the request for getting changes
type GetChangesRequest struct {
Since int64 `json:"since"`
ClientID string `json:"client_id"`
}
// GetChanges returns tasks that have changed since a given timestamp
func GetChanges(w http.ResponseWriter, r *http.Request) {
var req GetChangesRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
errorResponse(w, http.StatusBadRequest, "invalid request body")
return
}
// Query change_log for entries since timestamp
db := engine.GetDB()
if db == nil {
errorResponse(w, http.StatusInternalServerError, "database not initialized")
return
}
rows, err := db.Query(`
SELECT id, task_uuid, change_type, changed_at, data
FROM change_log
WHERE changed_at > ?
ORDER BY id ASC
`, req.Since)
if err != nil {
errorResponse(w, http.StatusInternalServerError, err.Error())
return
}
defer rows.Close()
type Change struct {
ID int64 `json:"id"`
TaskUUID string `json:"task_uuid"`
ChangeType string `json:"change_type"`
ChangedAt int64 `json:"changed_at"`
Data string `json:"data"`
}
var changes []Change
for rows.Next() {
var change Change
if err := rows.Scan(&change.ID, &change.TaskUUID, &change.ChangeType, &change.ChangedAt, &change.Data); err != nil {
errorResponse(w, http.StatusInternalServerError, err.Error())
return
}
changes = append(changes, change)
}
// Update sync_state for client
_, _ = db.Exec(`
INSERT OR REPLACE INTO sync_state (client_id, last_sync, last_change_id)
VALUES (?, ?, ?)
`, req.ClientID, engine.GetCurrentTimestamp(), 0)
jsonResponse(w, http.StatusOK, changes)
}
// PushChangesRequest represents the request for pushing changes
type PushChangesRequest struct {
Tasks []json.RawMessage `json:"tasks"`
ClientID string `json:"client_id"`
}
// PushChanges accepts task changes from clients
func PushChanges(w http.ResponseWriter, r *http.Request) {
var req PushChangesRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
errorResponse(w, http.StatusBadRequest, "invalid request body")
return
}
db := engine.GetDB()
if db == nil {
errorResponse(w, http.StatusInternalServerError, "database not initialized")
return
}
// For each task, parse and apply (last-write-wins for now)
var processed int
var conflicts int
for _, taskData := range req.Tasks {
var task engine.Task
if err := json.Unmarshal(taskData, &task); err != nil {
continue
}
// Check if task exists
existing, err := engine.GetTask(task.UUID)
if err != nil {
// Task doesn't exist - create it
if err := task.Save(); err != nil {
continue
}
// Add tags
for _, tag := range task.Tags {
_ = task.AddTag(tag)
}
processed++
continue
}
// Task exists - check timestamps for conflicts
if existing.Modified.Unix() > task.Modified.Unix() {
// Server version is newer - conflict (but we'll apply last-write-wins)
conflicts++
}
// Apply changes (last-write-wins)
task.ID = existing.ID // Preserve database ID
if err := task.Save(); err != nil {
continue
}
// Sync tags
existingTags := make(map[string]bool)
for _, tag := range existing.Tags {
existingTags[tag] = true
}
// Add new tags
for _, tag := range task.Tags {
if !existingTags[tag] {
_ = task.AddTag(tag)
}
}
// Remove missing tags
for _, tag := range existing.Tags {
found := false
for _, newTag := range task.Tags {
if tag == newTag {
found = true
break
}
}
if !found {
_ = task.RemoveTag(tag)
}
}
processed++
}
// Update sync_state
_, _ = db.Exec(`
INSERT OR REPLACE INTO sync_state (client_id, last_sync, last_change_id)
VALUES (?, ?, ?)
`, req.ClientID, engine.GetCurrentTimestamp(), 0)
jsonResponse(w, http.StatusOK, map[string]interface{}{
"processed": processed,
"conflicts": conflicts,
})
}
+18
View File
@@ -0,0 +1,18 @@
package handlers
import (
"net/http"
"git.jnss.me/joakim/opal/internal/engine"
)
// ListAllTags returns all unique tags from all tasks
func ListAllTags(w http.ResponseWriter, r *http.Request) {
tags, err := engine.GetAllTags()
if err != nil {
errorResponse(w, http.StatusInternalServerError, err.Error())
return
}
jsonResponse(w, http.StatusOK, tags)
}
+435
View File
@@ -0,0 +1,435 @@
package handlers
import (
"encoding/json"
"fmt"
"net/http"
"time"
"git.jnss.me/joakim/opal/internal/engine"
"github.com/go-chi/chi/v5"
"github.com/google/uuid"
)
// Response helpers (avoiding import cycle)
func jsonResponse(w http.ResponseWriter, status int, data interface{}) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
json.NewEncoder(w).Encode(map[string]interface{}{
"success": status >= 200 && status < 300,
"data": data,
})
}
func errorResponse(w http.ResponseWriter, status int, message string) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
json.NewEncoder(w).Encode(map[string]interface{}{
"success": false,
"error": message,
})
}
// ListTasks returns tasks based on filter query parameters
func ListTasks(w http.ResponseWriter, r *http.Request) {
query := r.URL.Query()
// Build filter from query params
filter := engine.NewFilter()
// Status filter
if status := query.Get("status"); status != "" {
filter.Attributes["status"] = status
}
// Project filter
if project := query.Get("project"); project != "" {
filter.Attributes["project"] = project
}
// Priority filter
if priority := query.Get("priority"); priority != "" {
filter.Attributes["priority"] = priority
}
// Tag filters
if tags := query["tag"]; len(tags) > 0 {
filter.IncludeTags = tags
}
// Get tasks
tasks, err := engine.GetTasks(filter)
if err != nil {
errorResponse(w, http.StatusInternalServerError, err.Error())
return
}
jsonResponse(w, http.StatusOK, tasks)
}
// CreateTaskRequest represents the request body for creating a task
type CreateTaskRequest struct {
Description string `json:"description"`
Tags []string `json:"tags,omitempty"`
Project *string `json:"project,omitempty"`
Priority *string `json:"priority,omitempty"`
Due *int64 `json:"due,omitempty"`
Scheduled *int64 `json:"scheduled,omitempty"`
Wait *int64 `json:"wait,omitempty"`
Until *int64 `json:"until,omitempty"`
Recurrence *string `json:"recurrence,omitempty"`
}
// CreateTask creates a new task
func CreateTask(w http.ResponseWriter, r *http.Request) {
var req CreateTaskRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
errorResponse(w, http.StatusBadRequest, "invalid request body")
return
}
if req.Description == "" {
errorResponse(w, http.StatusBadRequest, "description is required")
return
}
// Build modifier from request
mod := engine.NewModifier()
mod.AddTags = req.Tags
if req.Project != nil {
mod.SetAttributes["project"] = req.Project
}
if req.Priority != nil {
mod.SetAttributes["priority"] = req.Priority
}
if req.Due != nil {
dueStr := fmt.Sprintf("%d", *req.Due)
mod.SetAttributes["due"] = &dueStr
}
if req.Scheduled != nil {
scheduledStr := fmt.Sprintf("%d", *req.Scheduled)
mod.SetAttributes["scheduled"] = &scheduledStr
}
if req.Wait != nil {
waitStr := fmt.Sprintf("%d", *req.Wait)
mod.SetAttributes["wait"] = &waitStr
}
if req.Until != nil {
untilStr := fmt.Sprintf("%d", *req.Until)
mod.SetAttributes["until"] = &untilStr
}
if req.Recurrence != nil {
mod.SetAttributes["recurrence"] = req.Recurrence
}
// Create task
task, err := engine.CreateTaskWithModifier(req.Description, mod)
if err != nil {
errorResponse(w, http.StatusInternalServerError, err.Error())
return
}
jsonResponse(w, http.StatusCreated, task)
}
// GetTask returns a single task by UUID
func GetTask(w http.ResponseWriter, r *http.Request) {
uuidStr := chi.URLParam(r, "uuid")
taskUUID, err := uuid.Parse(uuidStr)
if err != nil {
errorResponse(w, http.StatusBadRequest, "invalid UUID")
return
}
task, err := engine.GetTask(taskUUID)
if err != nil {
errorResponse(w, http.StatusNotFound, "task not found")
return
}
jsonResponse(w, http.StatusOK, task)
}
// UpdateTaskRequest represents the request body for updating a task
type UpdateTaskRequest struct {
Description *string `json:"description,omitempty"`
Status *string `json:"status,omitempty"`
Priority *string `json:"priority,omitempty"`
Project *string `json:"project,omitempty"`
Due *int64 `json:"due,omitempty"`
Scheduled *int64 `json:"scheduled,omitempty"`
Wait *int64 `json:"wait,omitempty"`
Until *int64 `json:"until,omitempty"`
Start *int64 `json:"start,omitempty"`
Recurrence *string `json:"recurrence,omitempty"`
}
// UpdateTask updates an existing task
func UpdateTask(w http.ResponseWriter, r *http.Request) {
uuidStr := chi.URLParam(r, "uuid")
taskUUID, err := uuid.Parse(uuidStr)
if err != nil {
errorResponse(w, http.StatusBadRequest, "invalid UUID")
return
}
task, err := engine.GetTask(taskUUID)
if err != nil {
errorResponse(w, http.StatusNotFound, "task not found")
return
}
var req UpdateTaskRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
errorResponse(w, http.StatusBadRequest, "invalid request body")
return
}
// Build modifier
mod := engine.NewModifier()
if req.Description != nil {
mod.SetAttributes["description"] = req.Description
}
if req.Status != nil {
mod.SetAttributes["status"] = req.Status
}
if req.Priority != nil {
mod.SetAttributes["priority"] = req.Priority
}
if req.Project != nil {
mod.SetAttributes["project"] = req.Project
}
if req.Due != nil {
dueStr := fmt.Sprintf("%d", *req.Due)
mod.SetAttributes["due"] = &dueStr
}
if req.Scheduled != nil {
scheduledStr := fmt.Sprintf("%d", *req.Scheduled)
mod.SetAttributes["scheduled"] = &scheduledStr
}
if req.Wait != nil {
waitStr := fmt.Sprintf("%d", *req.Wait)
mod.SetAttributes["wait"] = &waitStr
}
if req.Until != nil {
untilStr := fmt.Sprintf("%d", *req.Until)
mod.SetAttributes["until"] = &untilStr
}
if req.Start != nil {
t := time.Unix(*req.Start, 0)
task.Start = &t
}
if req.Recurrence != nil {
mod.SetAttributes["recurrence"] = req.Recurrence
}
// Apply modifier
if err := mod.Apply(task); err != nil {
errorResponse(w, http.StatusBadRequest, err.Error())
return
}
jsonResponse(w, http.StatusOK, task)
}
// DeleteTask deletes a task
func DeleteTask(w http.ResponseWriter, r *http.Request) {
uuidStr := chi.URLParam(r, "uuid")
taskUUID, err := uuid.Parse(uuidStr)
if err != nil {
errorResponse(w, http.StatusBadRequest, "invalid UUID")
return
}
task, err := engine.GetTask(taskUUID)
if err != nil {
errorResponse(w, http.StatusNotFound, "task not found")
return
}
// Check for permanent delete flag
permanent := r.URL.Query().Get("permanent") == "true"
if err := task.Delete(permanent); err != nil {
errorResponse(w, http.StatusInternalServerError, err.Error())
return
}
jsonResponse(w, http.StatusOK, map[string]string{"message": "task deleted"})
}
// CompleteTask marks a task as completed
func CompleteTask(w http.ResponseWriter, r *http.Request) {
uuidStr := chi.URLParam(r, "uuid")
taskUUID, err := uuid.Parse(uuidStr)
if err != nil {
errorResponse(w, http.StatusBadRequest, "invalid UUID")
return
}
task, err := engine.GetTask(taskUUID)
if err != nil {
errorResponse(w, http.StatusNotFound, "task not found")
return
}
if err := task.Complete(); err != nil {
errorResponse(w, http.StatusInternalServerError, err.Error())
return
}
jsonResponse(w, http.StatusOK, task)
}
// StartTask sets the start time for a task
func StartTask(w http.ResponseWriter, r *http.Request) {
uuidStr := chi.URLParam(r, "uuid")
taskUUID, err := uuid.Parse(uuidStr)
if err != nil {
errorResponse(w, http.StatusBadRequest, "invalid UUID")
return
}
task, err := engine.GetTask(taskUUID)
if err != nil {
errorResponse(w, http.StatusNotFound, "task not found")
return
}
if err := task.StartTask(); err != nil {
errorResponse(w, http.StatusInternalServerError, err.Error())
return
}
jsonResponse(w, http.StatusOK, task)
}
// StopTask clears the start time for a task
func StopTask(w http.ResponseWriter, r *http.Request) {
uuidStr := chi.URLParam(r, "uuid")
taskUUID, err := uuid.Parse(uuidStr)
if err != nil {
errorResponse(w, http.StatusBadRequest, "invalid UUID")
return
}
task, err := engine.GetTask(taskUUID)
if err != nil {
errorResponse(w, http.StatusNotFound, "task not found")
return
}
if err := task.StopTask(); err != nil {
errorResponse(w, http.StatusInternalServerError, err.Error())
return
}
jsonResponse(w, http.StatusOK, task)
}
// GetTaskTags returns all tags for a task
func GetTaskTags(w http.ResponseWriter, r *http.Request) {
uuidStr := chi.URLParam(r, "uuid")
taskUUID, err := uuid.Parse(uuidStr)
if err != nil {
errorResponse(w, http.StatusBadRequest, "invalid UUID")
return
}
task, err := engine.GetTask(taskUUID)
if err != nil {
errorResponse(w, http.StatusNotFound, "task not found")
return
}
jsonResponse(w, http.StatusOK, task.Tags)
}
// AddTaskTagRequest represents the request to add a tag
type AddTaskTagRequest struct {
Tag string `json:"tag"`
}
// AddTaskTag adds a tag to a task
func AddTaskTag(w http.ResponseWriter, r *http.Request) {
uuidStr := chi.URLParam(r, "uuid")
taskUUID, err := uuid.Parse(uuidStr)
if err != nil {
errorResponse(w, http.StatusBadRequest, "invalid UUID")
return
}
task, err := engine.GetTask(taskUUID)
if err != nil {
errorResponse(w, http.StatusNotFound, "task not found")
return
}
var req AddTaskTagRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
errorResponse(w, http.StatusBadRequest, "invalid request body")
return
}
if req.Tag == "" {
errorResponse(w, http.StatusBadRequest, "tag is required")
return
}
if err := task.AddTag(req.Tag); err != nil {
errorResponse(w, http.StatusInternalServerError, err.Error())
return
}
jsonResponse(w, http.StatusOK, task)
}
// RemoveTaskTag removes a tag from a task
func RemoveTaskTag(w http.ResponseWriter, r *http.Request) {
uuidStr := chi.URLParam(r, "uuid")
tag := chi.URLParam(r, "tag")
taskUUID, err := uuid.Parse(uuidStr)
if err != nil {
errorResponse(w, http.StatusBadRequest, "invalid UUID")
return
}
task, err := engine.GetTask(taskUUID)
if err != nil {
errorResponse(w, http.StatusNotFound, "task not found")
return
}
if err := task.RemoveTag(tag); err != nil {
errorResponse(w, http.StatusInternalServerError, err.Error())
return
}
jsonResponse(w, http.StatusOK, task)
}
+79
View File
@@ -0,0 +1,79 @@
package api
import (
"context"
"net/http"
"strings"
"git.jnss.me/joakim/opal/internal/engine"
)
type contextKey string
const userIDKey contextKey = "userID"
// AuthMiddleware validates API keys and adds userID to context
func AuthMiddleware() func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Get Authorization header
authHeader := r.Header.Get("Authorization")
if authHeader == "" {
Error(w, http.StatusUnauthorized, "missing authorization header")
return
}
// Parse "Bearer <token>"
parts := strings.SplitN(authHeader, " ", 2)
if len(parts) != 2 || parts[0] != "Bearer" {
Error(w, http.StatusUnauthorized, "invalid authorization header format")
return
}
apiKey := parts[1]
// Validate API key
valid, userID, err := engine.ValidateAPIKey(apiKey)
if err != nil {
Error(w, http.StatusInternalServerError, "failed to validate API key")
return
}
if !valid {
Error(w, http.StatusUnauthorized, "invalid API key")
return
}
// Add userID to context
ctx := context.WithValue(r.Context(), userIDKey, userID)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
}
// GetUserID extracts userID from request context
func GetUserID(r *http.Request) int {
userID, ok := r.Context().Value(userIDKey).(int)
if !ok {
return 0
}
return userID
}
// CORSMiddleware adds CORS headers for future web frontend
func CORSMiddleware() func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization")
if r.Method == "OPTIONS" {
w.WriteHeader(http.StatusOK)
return
}
next.ServeHTTP(w, r)
})
}
}
+39
View File
@@ -0,0 +1,39 @@
package api
import (
"encoding/json"
"net/http"
)
// Response represents a standard API response
type Response struct {
Success bool `json:"success"`
Data interface{} `json:"data,omitempty"`
Error string `json:"error,omitempty"`
}
// JSON sends a JSON response
func JSON(w http.ResponseWriter, status int, data interface{}) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
response := Response{
Success: status >= 200 && status < 300,
Data: data,
}
json.NewEncoder(w).Encode(response)
}
// Error sends an error response
func Error(w http.ResponseWriter, status int, message string) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
response := Response{
Success: false,
Error: message,
}
json.NewEncoder(w).Encode(response)
}
+81
View File
@@ -0,0 +1,81 @@
package api
import (
"fmt"
"net/http"
"git.jnss.me/joakim/opal/internal/api/handlers"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
)
// Server represents the API server
type Server struct {
router chi.Router
addr string
}
// NewServer creates a new API server
func NewServer(addr string) *Server {
s := &Server{
router: chi.NewRouter(),
addr: addr,
}
s.setupRoutes()
return s
}
// setupRoutes configures all API routes
func (s *Server) setupRoutes() {
r := s.router
// Global middleware
r.Use(middleware.Logger)
r.Use(middleware.Recoverer)
r.Use(CORSMiddleware())
// Health check (no auth required)
r.Get("/health", func(w http.ResponseWriter, r *http.Request) {
JSON(w, http.StatusOK, map[string]string{"status": "ok"})
})
// Protected routes
r.Group(func(r chi.Router) {
r.Use(AuthMiddleware())
// Tasks
r.Route("/tasks", func(r chi.Router) {
r.Get("/", handlers.ListTasks)
r.Post("/", handlers.CreateTask)
r.Get("/{uuid}", handlers.GetTask)
r.Put("/{uuid}", handlers.UpdateTask)
r.Delete("/{uuid}", handlers.DeleteTask)
r.Post("/{uuid}/complete", handlers.CompleteTask)
r.Post("/{uuid}/start", handlers.StartTask)
r.Post("/{uuid}/stop", handlers.StopTask)
// Tags
r.Get("/{uuid}/tags", handlers.GetTaskTags)
r.Post("/{uuid}/tags", handlers.AddTaskTag)
r.Delete("/{uuid}/tags/{tag}", handlers.RemoveTaskTag)
})
// Metadata
r.Get("/tags", handlers.ListAllTags)
r.Get("/projects", handlers.ListProjects)
// Sync endpoints
r.Post("/sync/changes", handlers.GetChanges)
r.Post("/sync/push", handlers.PushChanges)
// Key management
r.Get("/auth/keys", handlers.ListAPIKeys)
r.Delete("/auth/keys/{id}", handlers.RevokeAPIKey)
})
}
// Start starts the HTTP server
func (s *Server) Start() error {
fmt.Printf("Starting opal API server on %s\n", s.addr)
return http.ListenAndServe(s.addr, s.router)
}