📚 The open-source, offline-first Notion, Obsidian & Confluence alternative. Advanced Markdown, multi-tenant teams, OIDC/SSO, and local S3 backups. Deploy in one command.
Vue dockergolangkanbanknowledge-baseknowledge-managementmarkdownnote-takingnotesnotes-appnotionnuxtnuxtjsoffline-firstoidcpwaselfhostedssovuevuejswiki
Init new backup system
Smaug673955ef197db724
diff --git a/backend/app/minio.go b/backend/app/minio.goindex 7c135799..6d9fd2bd 100644--- a/backend/app/minio.go+++ b/backend/app/minio.go@@ -2,6 +2,7 @@ package appimport ("alexandrie/pkg/logger"+ "alexandrie/utils""context""fmt""log"@@ -9,6 +10,7 @@ import ("github.com/minio/minio-go/v7""github.com/minio/minio-go/v7/pkg/credentials"+ "github.com/minio/minio-go/v7/pkg/lifecycle")func MinioConnection() (*minio.Client, error) {@@ -28,11 +30,21 @@ func MinioConnection() (*minio.Client, error) {log.Fatalln(errInit)}- // Make a new bucket called dev-minio.+ // Setup main public bucket for user files (avatars, uploads, etc.)bucketName := os.Getenv("MINIO_BUCKET")+ setupPublicBucket(ctx, minioClient, bucketName)++ // Setup private bucket for backups (only accessible via presigned URLs)+ backupBucket := utils.GetBackupBucketName()+ setupPrivateBackupBucket(ctx, minioClient, backupBucket)++ return minioClient, errInit+}++// setupPublicBucket creates and configures the main public bucket+func setupPublicBucket(ctx context.Context, minioClient *minio.Client, bucketName string) {err := minioClient.MakeBucket(ctx, bucketName, minio.MakeBucketOptions{})if err != nil {- // Check to see if we already own this bucket (which happens if you run this twice)exists, errBucketExists := minioClient.BucketExists(ctx, bucketName)if errBucketExists == nil && exists {logger.Info(fmt.Sprintf("We already own %s", bucketName))@@ -42,7 +54,8 @@ func MinioConnection() (*minio.Client, error) {} else {logger.Success("Successfully created " + bucketName)}- // Définir la politique de lecture publique++ // Set public read policy for user filespolicy := fmt.Sprintf(`{"Version": "2012-10-17","Statement": [@@ -59,6 +72,42 @@ func MinioConnection() (*minio.Client, error) {if err != nil {log.Fatalf("Failed to set bucket policy: %v", err)}- logger.Success("Successfully set bucket policy")- return minioClient, errInit+ logger.Success("Successfully set public bucket policy for " + bucketName)+}++// setupPrivateBackupBucket creates and configures the private backup bucket+func setupPrivateBackupBucket(ctx context.Context, minioClient *minio.Client, bucketName string) {+ err := minioClient.MakeBucket(ctx, bucketName, minio.MakeBucketOptions{})+ if err != nil {+ exists, errBucketExists := minioClient.BucketExists(ctx, bucketName)+ if errBucketExists == nil && exists {+ logger.Info(fmt.Sprintf("We already own %s", bucketName))+ } else {+ log.Fatalln(err)+ }+ } else {+ logger.Success("Successfully created private backup bucket: " + bucketName)+ }++ // No public policy - bucket remains private+ // Backups are only accessible via presigned URLs++ // Configure lifecycle rule to auto-delete backup files after 1 day+ lifecycleConfig := lifecycle.NewConfiguration()+ lifecycleConfig.Rules = []lifecycle.Rule{+ {+ ID: "auto-delete-backups",+ Status: "Enabled",+ Expiration: lifecycle.Expiration{+ Days: 1,+ },+ },+ }++ err = minioClient.SetBucketLifecycle(ctx, bucketName, lifecycleConfig)+ if err != nil {+ logger.Warn(fmt.Sprintf("Failed to set lifecycle policy for backups: %v", err))+ } else {+ logger.Success("Successfully set lifecycle policy for backups (auto-delete after 24h)")+ }}diff --git a/backend/controllers/backup.controller.go b/backend/controllers/backup.controller.gonew file mode 100644index 00000000..db502610--- /dev/null+++ b/backend/controllers/backup.controller.go@@ -0,0 +1,117 @@+package controllers++import (+ "alexandrie/app"+ "alexandrie/permissions"+ "alexandrie/types"+ "alexandrie/utils"+ "errors"+ "net/http"++ "github.com/gin-gonic/gin"+)++type BackupController interface {+ CreateBackup(c *gin.Context) (int, any)+ GetBackupStatus(c *gin.Context) (int, any)+ CancelBackup(c *gin.Context) (int, any)+}++func NewBackupController(app *app.App) BackupController {+ return &Controller{+ app: app,+ authorizer: permissions.NewAuthorizer(app.Repos.Permission),+ }+}++// CreateBackupRequest represents the request body for creating a backup+type CreateBackupRequest struct {+ IncludeDocuments *bool `json:"include_documents"` // Include documents/notes content+ IncludeFiles *bool `json:"include_files"` // Include uploaded files+ IncludeSettings *bool `json:"include_settings"` // Include user settings+ IncludeMetadata *bool `json:"include_metadata"` // Include node metadata+}++// CreateBackup starts an asynchronous backup job+// @Method POST+// @Description Start a new backup job with specified options. Returns a job ID for tracking progress.+// @Router /backup [post]+func (ctr *Controller) CreateBackup(c *gin.Context) (int, any) {+ userId, err := utils.GetUserIdCtx(c)+ if err != nil {+ return http.StatusBadRequest, err+ }++ // Parse request body for options+ var req CreateBackupRequest+ if err := c.ShouldBindJSON(&req); err != nil {+ // If no body provided, use default options+ req = CreateBackupRequest{}+ }++ // Build options from request (default to true if not specified)+ options := types.BackupOptions{+ IncludeDocuments: req.IncludeDocuments == nil || *req.IncludeDocuments,+ IncludeFiles: req.IncludeFiles == nil || *req.IncludeFiles,+ IncludeSettings: req.IncludeSettings == nil || *req.IncludeSettings,+ IncludeMetadata: req.IncludeMetadata == nil || *req.IncludeMetadata,+ }++ // Start async backup+ jobId, err := ctr.app.Services.Backup.CreateBackupAsync(userId, options, ctr.app.MinioClient)+ if err != nil {+ return http.StatusInternalServerError, err+ }++ return http.StatusAccepted, gin.H{+ "job_id": jobId, // Return the job ID to the client for tracking+ }+}++// GetBackupStatus returns the current status of a backup job+// @Method GET+// @Description Get the status of an ongoing or completed backup job.+// @Router /backup/:jobId [get]+func (ctr *Controller) GetBackupStatus(c *gin.Context) (int, any) {+ userId, err := utils.GetUserIdCtx(c)+ if err != nil {+ return http.StatusBadRequest, err+ }++ jobId := c.Param("jobId")+ if jobId == "" {+ return http.StatusBadRequest, errors.New("job ID is required")+ }++ job, err := ctr.app.Services.Backup.GetBackupStatus(userId, jobId)+ if err != nil {+ return http.StatusNotFound, err+ }++ return http.StatusOK, job+}++// CancelBackup cancels an ongoing backup job+// @Method DELETE+// @Description Cancel an ongoing backup job.+// @Router /backup/:jobId [delete]+func (ctr *Controller) CancelBackup(c *gin.Context) (int, any) {+ userId, err := utils.GetUserIdCtx(c)+ if err != nil {+ return http.StatusBadRequest, err+ }++ jobId := c.Param("jobId")+ if jobId == "" {+ return http.StatusBadRequest, errors.New("job ID is required")+ }++ err = ctr.app.Services.Backup.CancelBackup(userId, jobId)+ if err != nil {+ return http.StatusBadRequest, err+ }++ return http.StatusOK, gin.H{+ "message": "Backup job cancelled successfully",+ }+}diff --git a/backend/controllers/resources.controller.go b/backend/controllers/resources.controller.goindex 83472774..347f3f96 100644--- a/backend/controllers/resources.controller.go+++ b/backend/controllers/resources.controller.go@@ -12,7 +12,6 @@ import ()type ResourceController interface {- GetBackup(c *gin.Context) (int, any)UploadFile(c *gin.Context) (int, any)UploadAvatar(c *gin.Context) (int, any)}@@ -24,23 +23,6 @@ func NewResourceController(app *app.App) ResourceController {}}-// GetBackup generates a backup link for the user's data-// @Method GET-// @Description Generate a backup link for the user's data.-// @Router /resources/backup [get]-func (ctr *Controller) GetBackup(c *gin.Context) (int, any) {- userId, err := utils.GetUserIdCtx(c)- if err != nil {- return http.StatusBadRequest, err- }-- link, err := ctr.app.Services.Resource.CreateBackup(userId, ctr.app.MinioClient)- if err != nil {- return http.StatusInternalServerError, err- }- return http.StatusCreated, gin.H{"link": link}-}-// UploadFile handles file upload and stores it in the CDN// @Method POST// @Description Upload a file to the CDN.diff --git a/backend/router/router.go b/backend/router/router.goindex 3a6a318e..8d3526fe 100644--- a/backend/router/router.go+++ b/backend/router/router.go@@ -68,6 +68,7 @@ func InitRouter(app *app.App) *gin.Engine {routes.Users(app, mainGroup)routes.Auth(app, mainGroup)routes.Uploads(app, mainGroup)+ routes.Backup(app, mainGroup)routes.Nodes(app, mainGroup)return router}diff --git a/backend/router/routes/ressources.go b/backend/router/routes/ressources.goindex a515d794..4261db8f 100644--- a/backend/router/routes/ressources.go+++ b/backend/router/routes/ressources.go@@ -14,7 +14,16 @@ func Uploads(app *app.App, router *gin.RouterGroup) {resourcesCtrl := controllers.NewResourceController(app)resources.Use(middlewares.Auth())- resources.GET(("/backup"), utils.WP(resourcesCtrl.GetBackup))resources.POST("", utils.WP(resourcesCtrl.UploadFile))resources.POST("/avatar", utils.WP(resourcesCtrl.UploadAvatar))}++func Backup(app *app.App, router *gin.RouterGroup) {+ backup := router.Group("/backup")+ backupCtrl := controllers.NewBackupController(app)++ backup.Use(middlewares.Auth())+ backup.POST("", utils.WP(backupCtrl.CreateBackup))+ backup.GET("/:jobId", utils.WP(backupCtrl.GetBackupStatus))+ backup.DELETE("/:jobId", utils.WP(backupCtrl.CancelBackup))+}diff --git a/backend/services/backup.service.go b/backend/services/backup.service.gonew file mode 100644index 00000000..649ed5e4--- /dev/null+++ b/backend/services/backup.service.go@@ -0,0 +1,610 @@+package services++import (+ "alexandrie/models"+ "alexandrie/pkg/logger"+ "alexandrie/repositories"+ "alexandrie/types"+ "alexandrie/utils"+ "archive/zip"+ "bytes"+ "context"+ "encoding/json"+ "errors"+ "fmt"+ "io"+ "os"+ "path/filepath"+ "sync"+ "time"++ "github.com/minio/minio-go/v7"+)++const (+ backupVersion = "1.0.0"+ backupExpiryHours = 24 // Backup files expire after 24 hours+ maxConcurrentFiles = 5 // Max concurrent file downloads for backup+)++// BackupService handles backup creation and management+type BackupService interface {+ // CreateBackupAsync starts an async backup job and returns the job ID+ CreateBackupAsync(userId types.Snowflake, options types.BackupOptions, minioClient *minio.Client) (string, error)+ // GetBackupStatus returns the current status of a backup job+ GetBackupStatus(userId types.Snowflake, jobId string) (*types.BackupJob, error)+ // CancelBackup cancels an ongoing backup job+ CancelBackup(userId types.Snowflake, jobId string) error+ // CleanupExpiredBackups removes expired backup files+ CleanupExpiredBackups(minioClient *minio.Client) error+}++type backupService struct {+ nodeRepo repositories.NodeRepository+ jobs map[string]*types.BackupJob+ userJobs map[types.Snowflake]string // Maps userId to current jobId+ jobMutex sync.RWMutex+ cancel map[string]context.CancelFunc+}++// NewBackupService creates a new backup service instance+func NewBackupService(nodeRepo repositories.NodeRepository) BackupService {+ return &backupService{+ nodeRepo: nodeRepo,+ jobs: make(map[string]*types.BackupJob),+ userJobs: make(map[types.Snowflake]string),+ cancel: make(map[string]context.CancelFunc),+ }+}++// CreateBackupAsync starts an asynchronous backup job+func (s *backupService) CreateBackupAsync(userId types.Snowflake, options types.BackupOptions, minioClient *minio.Client) (string, error) {+ if minioClient == nil {+ return "", errors.New("minio client not initialized")+ }++ // Cancel any existing backup for this user+ s.cancelExistingBackup(userId, minioClient)++ // Use a fixed job ID per user so backups are replaced+ jobId := fmt.Sprintf("user-%d-backup", userId)++ // Create job entry+ job := &types.BackupJob{+ ID: jobId,+ UserID: userId,+ Status: types.BackupStatusPending,+ Options: options,+ Progress: 0,+ Message: "Initializing backup...",+ CreatedAt: time.Now(),+ UpdatedAt: time.Now(),+ }++ // Store job+ s.jobMutex.Lock()+ s.jobs[jobId] = job+ s.userJobs[userId] = jobId+ s.jobMutex.Unlock()++ // Create cancellation context+ ctx, cancel := context.WithCancel(context.Background())+ s.jobMutex.Lock()+ s.cancel[jobId] = cancel+ s.jobMutex.Unlock()++ // Start async processing+ go s.processBackup(ctx, job, minioClient)++ return jobId, nil+}++// cancelExistingBackup cancels any ongoing backup and removes the old backup file+func (s *backupService) cancelExistingBackup(userId types.Snowflake, minioClient *minio.Client) {+ s.jobMutex.Lock()+ defer s.jobMutex.Unlock()++ // Check if user has an existing job+ existingJobId, exists := s.userJobs[userId]+ if !exists {+ return+ }++ existingJob, jobExists := s.jobs[existingJobId]+ if !jobExists {+ delete(s.userJobs, userId)+ return+ }++ // Cancel if still running+ if existingJob.Status == types.BackupStatusPending || existingJob.Status == types.BackupStatusProcessing {+ if cancel, ok := s.cancel[existingJobId]; ok {+ cancel()+ delete(s.cancel, existingJobId)+ }+ }++ // Delete the old backup file from MinIO (private backup bucket)+ if minioClient != nil {+ objectName := fmt.Sprintf("%d/backup.zip", userId)+ backupBucket := utils.GetBackupBucketName()+ _ = minioClient.RemoveObject(context.Background(), backupBucket, objectName, minio.RemoveObjectOptions{})+ }++ // Remove old job+ delete(s.jobs, existingJobId)+}++// GetBackupStatus returns the current status of a backup job+func (s *backupService) GetBackupStatus(userId types.Snowflake, jobId string) (*types.BackupJob, error) {+ s.jobMutex.RLock()+ defer s.jobMutex.RUnlock()++ job, exists := s.jobs[jobId]+ if !exists {+ return nil, errors.New("backup job not found")+ }++ // Verify ownership+ if job.UserID != userId {+ return nil, errors.New("unauthorized access to backup job")+ }++ return job, nil+}++// CancelBackup cancels an ongoing backup job+func (s *backupService) CancelBackup(userId types.Snowflake, jobId string) error {+ s.jobMutex.Lock()+ defer s.jobMutex.Unlock()++ job, exists := s.jobs[jobId]+ if !exists {+ return errors.New("backup job not found")+ }++ if job.UserID != userId {+ return errors.New("unauthorized access to backup job")+ }++ if job.Status == types.BackupStatusCompleted || job.Status == types.BackupStatusFailed {+ return errors.New("backup job already finished")+ }++ // Cancel the context+ if cancel, ok := s.cancel[jobId]; ok {+ cancel()+ delete(s.cancel, jobId)+ }++ job.Status = types.BackupStatusFailed+ job.Error = "Backup cancelled by user"+ job.UpdatedAt = time.Now()++ return nil+}++// CleanupExpiredBackups cleans up expired job entries from memory.+// Note: The actual backup files are automatically deleted by MinIO lifecycle policy after 24h.+// This function only cleans up the in-memory job tracking.+func (s *backupService) CleanupExpiredBackups(minioClient *minio.Client) error {+ s.jobMutex.Lock()+ defer s.jobMutex.Unlock()++ now := time.Now()++ for jobId, job := range s.jobs {+ if job.Status == types.BackupStatusCompleted && !job.ExpiresAt.IsZero() && now.After(job.ExpiresAt) {+ // Clean up in-memory job tracking (files are auto-deleted by MinIO lifecycle)+ delete(s.jobs, jobId)+ delete(s.userJobs, job.UserID)+ }+ }++ return nil+}++// processBackup is the main backup processing goroutine+func (s *backupService) processBackup(ctx context.Context, job *types.BackupJob, minioClient *minio.Client) {+ defer func() {+ if r := recover(); r != nil {+ s.updateJobStatus(job, types.BackupStatusFailed, 0, "", fmt.Sprintf("Backup failed: %v", r))+ }+ }()++ s.updateJobStatus(job, types.BackupStatusProcessing, 5, "Fetching data...", "")++ // Check for cancellation+ select {+ case <-ctx.Done():+ return+ default:+ }++ // Fetch all nodes for backup+ nodes, err := s.nodeRepo.GetAllForBackup(job.UserID)+ if err != nil {+ s.updateJobStatus(job, types.BackupStatusFailed, 0, "", fmt.Sprintf("Failed to fetch nodes: %v", err))+ return+ }++ s.updateJobStatus(job, types.BackupStatusProcessing, 15, "Preparing backup archive...", "")++ // Create ZIP archive in memory+ var buf bytes.Buffer+ zipWriter := zip.NewWriter(&buf)++ // Prepare backup statistics+ stats := types.BackupStats{+ TotalNodes: len(nodes),+ }++ // Filter and categorize nodes+ var documents []*models.Node+ var files []*models.Node++ for _, node := range nodes {+ if node.Role == 4 { // Role 4 is file/resource+ files = append(files, node)+ stats.TotalFiles+++ } else {+ documents = append(documents, node)+ stats.TotalDocuments+++ }+ }++ s.updateJobStatus(job, types.BackupStatusProcessing, 25, "Processing documents...", "")++ // Add documents to backup+ if job.Options.IncludeDocuments {+ documentsData, err := s.prepareDocumentsData(documents, job.Options.IncludeMetadata)+ if err != nil {+ s.updateJobStatus(job, types.BackupStatusFailed, 0, "", fmt.Sprintf("Failed to prepare documents: %v", err))+ return+ }++ if err := s.addJSONToZip(zipWriter, "documents.json", documentsData); err != nil {+ s.updateJobStatus(job, types.BackupStatusFailed, 0, "", fmt.Sprintf("Failed to add documents to archive: %v", err))+ return+ }+ }++ select {+ case <-ctx.Done():+ return+ default:+ }++ s.updateJobStatus(job, types.BackupStatusProcessing, 40, "Processing files...", "")++ // Add files to backup+ if job.Options.IncludeFiles && len(files) > 0 {+ if err := s.addFilesToZip(ctx, zipWriter, files, job, minioClient, &stats); err != nil {+ if ctx.Err() != nil {+ return // Cancelled+ }+ s.updateJobStatus(job, types.BackupStatusFailed, 0, "", fmt.Sprintf("Failed to add files to archive: %v", err))+ return+ }+ }++ select {+ case <-ctx.Done():+ return+ default:+ }++ s.updateJobStatus(job, types.BackupStatusProcessing, 85, "Creating manifest...", "")++ // Create and add manifest+ manifest := types.BackupManifest{+ Version: backupVersion,+ CreatedAt: time.Now(),+ UserID: job.UserID,+ Options: job.Options,+ Statistics: stats,+ }++ if err := s.addJSONToZip(zipWriter, "manifest.json", manifest); err != nil {+ s.updateJobStatus(job, types.BackupStatusFailed, 0, "", fmt.Sprintf("Failed to add manifest: %v", err))+ return+ }++ // Add file index for easier restoration+ if job.Options.IncludeFiles && len(files) > 0 {+ fileIndex := s.createFileIndex(files)+ if err := s.addJSONToZip(zipWriter, "files_index.json", fileIndex); err != nil {+ s.updateJobStatus(job, types.BackupStatusFailed, 0, "", fmt.Sprintf("Failed to add file index: %v", err))+ return+ }+ }++ // Close ZIP writer+ if err := zipWriter.Close(); err != nil {+ s.updateJobStatus(job, types.BackupStatusFailed, 0, "", fmt.Sprintf("Failed to finalize archive: %v", err))+ return+ }++ s.updateJobStatus(job, types.BackupStatusProcessing, 90, "Uploading backup...", "")++ // Upload to private backup bucket (only accessible via presigned URLs)+ objectName := fmt.Sprintf("%d/backup.zip", job.UserID)+ backupBucket := utils.GetBackupBucketName()++ _, err = minioClient.PutObject(+ context.Background(),+ backupBucket,+ objectName,+ bytes.NewReader(buf.Bytes()),+ int64(buf.Len()),+ minio.PutObjectOptions{ContentType: "application/zip"},+ )+ if err != nil {+ s.updateJobStatus(job, types.BackupStatusFailed, 0, "", fmt.Sprintf("Failed to upload backup: %v", err))+ return+ }++ stats.TotalSize = int64(buf.Len())++ // Generate presigned URL for download (valid for 24 hours)+ // This is the ONLY way to access the backup since the bucket is private+ presignedURL, err := minioClient.PresignedGetObject(+ context.Background(),+ backupBucket,+ objectName,+ time.Duration(backupExpiryHours)*time.Hour,+ nil,+ )+ if err != nil {+ s.updateJobStatus(job, types.BackupStatusFailed, 0, "", fmt.Sprintf("Failed to generate download URL: %v", err))+ return+ }++ // Update job with completion status+ s.jobMutex.Lock()+ job.Status = types.BackupStatusCompleted+ job.Progress = 100+ job.Message = "Backup completed successfully"+ job.DownloadURL = presignedURL.String()+ job.ExpiresAt = time.Now().Add(time.Duration(backupExpiryHours) * time.Hour)+ job.UpdatedAt = time.Now()+ s.jobMutex.Unlock()+}++// updateJobStatus safely updates the job status+func (s *backupService) updateJobStatus(job *types.BackupJob, status types.BackupStatus, progress int, message string, errorMsg string) {+ s.jobMutex.Lock()+ defer s.jobMutex.Unlock()++ job.Status = status++ // Handle failed status: update message to reflect failure+ if status == types.BackupStatusFailed {+ job.Message = "Backup failed"+ if errorMsg != "" {+ job.Error = errorMsg+ }+ } else {+ if progress > 0 {+ job.Progress = progress+ }+ if message != "" {+ job.Message = message+ }+ }++ job.UpdatedAt = time.Now()+}++// prepareDocumentsData prepares document nodes for backup+func (s *backupService) prepareDocumentsData(documents []*models.Node, includeMetadata bool) (interface{}, error) {+ if !includeMetadata {+ // Strip metadata from documents+ stripped := make([]map[string]interface{}, len(documents))+ for i, doc := range documents {+ stripped[i] = map[string]interface{}{+ "id": doc.Id,+ "parent_id": doc.ParentId,+ "name": doc.Name,+ "description": doc.Description,+ "tags": doc.Tags,+ "role": doc.Role,+ "color": doc.Color,+ "icon": doc.Icon,+ "theme": doc.Theme,+ "accessibility": doc.Accessibility,+ "access": doc.Access,+ "display": doc.Display,+ "order": doc.Order,+ "content": doc.Content,+ "content_compiled": doc.ContentCompiled,+ "created_timestamp": doc.CreatedTimestamp,+ "updated_timestamp": doc.UpdatedTimestamp,+ }+ }+ return stripped, nil+ }+ return documents, nil+}++// addJSONToZip adds a JSON file to the ZIP archive+func (s *backupService) addJSONToZip(zipWriter *zip.Writer, filename string, data interface{}) error {+ jsonData, err := json.MarshalIndent(data, "", " ")+ if err != nil {+ return err+ }++ writer, err := zipWriter.Create(filename)+ if err != nil {+ return err+ }++ _, err = writer.Write(jsonData)+ return err+}++// addFilesToZip downloads and adds files to the ZIP archive+func (s *backupService) addFilesToZip(ctx context.Context, zipWriter *zip.Writer, files []*models.Node, job *types.BackupJob, minioClient *minio.Client, stats *types.BackupStats) error {+ bucket := os.Getenv("MINIO_BUCKET")++ // Process files with a semaphore for concurrency control+ sem := make(chan struct{}, maxConcurrentFiles)+ var wg sync.WaitGroup+ var mu sync.Mutex++ totalFiles := len(files)+ processedFiles := 0++ for _, file := range files {+ select {+ case <-ctx.Done():+ return ctx.Err()+ default:+ }++ wg.Add(1)+ sem <- struct{}{} // Acquire semaphore++ go func(f *models.Node) {+ defer wg.Done()+ defer func() { <-sem }() // Release semaphore++ // Get file path from metadata+ var objectPath string+ if f.Metadata != nil {+ if transformedPath, ok := (*f.Metadata)["transformed_path"].(string); ok {+ objectPath = fmt.Sprintf("%d/%s", job.UserID, transformedPath)+ }+ }++ if objectPath == "" {+ // Fallback: try to construct path from content_compiled+ if f.ContentCompiled != nil {+ objectPath = fmt.Sprintf("%d/%s", job.UserID, *f.ContentCompiled)+ }+ }++ if objectPath == "" {+ mu.Lock()+ stats.SkippedFiles = append(stats.SkippedFiles, types.SkippedFile{+ ID: f.Id,+ Name: f.Name,+ Reason: "no path found in metadata",+ })+ mu.Unlock()+ return // Skip file because we can't determine its path+ }++ // Download file from MinIO+ obj, err := minioClient.GetObject(ctx, bucket, objectPath, minio.GetObjectOptions{})+ if err != nil {+ mu.Lock()+ stats.SkippedFiles = append(stats.SkippedFiles, types.SkippedFile{+ ID: f.Id,+ Name: f.Name,+ Reason: fmt.Sprintf("failed to get object: %v", err),+ })+ mu.Unlock()+ return // Skip file on error+ }+ defer obj.Close()++ // Check if object exists by reading stat+ _, err = obj.Stat()+ if err != nil {+ mu.Lock()+ stats.SkippedFiles = append(stats.SkippedFiles, types.SkippedFile{+ ID: f.Id,+ Name: f.Name,+ Reason: "file not found in storage",+ })+ mu.Unlock()+ return // Skip file if not found+ }++ // Read file content+ content, err := io.ReadAll(obj)+ if err != nil {+ mu.Lock()+ stats.SkippedFiles = append(stats.SkippedFiles, types.SkippedFile{+ ID: f.Id,+ Name: f.Name,+ Reason: fmt.Sprintf("failed to read content: %v", err),+ })+ mu.Unlock()+ logger.Warn(fmt.Sprintf("Skipping file %d: failed to read %s: %v", f.Id, objectPath, err))+ return+ }++ // Determine filename for archive+ archivePath := fmt.Sprintf("files/%d%s", f.Id, filepath.Ext(f.Name))+ if f.Metadata != nil {+ if originalPath, ok := (*f.Metadata)["original_path"].(string); ok {+ archivePath = fmt.Sprintf("files/%d_%s", f.Id, filepath.Base(originalPath))+ }+ }++ // Add to ZIP (synchronized to avoid concurrent writes)+ mu.Lock()+ writer, err := zipWriter.Create(archivePath)+ if err != nil {+ stats.SkippedFiles = append(stats.SkippedFiles, types.SkippedFile{+ ID: f.Id,+ Name: f.Name,+ Reason: fmt.Sprintf("failed to create zip entry: %v", err),+ })+ mu.Unlock()+ logger.Warn(fmt.Sprintf("Skipping file %d: failed to create zip entry: %v", f.Id, err))+ return+ }++ _, err = writer.Write(content)+ if err != nil {+ stats.SkippedFiles = append(stats.SkippedFiles, types.SkippedFile{+ ID: f.Id,+ Name: f.Name,+ Reason: fmt.Sprintf("failed to write to zip: %v", err),+ })+ mu.Unlock()+ logger.Warn(fmt.Sprintf("Skipping file %d: failed to write to zip: %v", f.Id, err))+ return+ }++ processedFiles+++ stats.TotalSize += int64(len(content))+ mu.Unlock()++ // Update progress+ progress := 40 + int(float64(processedFiles)/float64(totalFiles)*40)+ s.updateJobStatus(job, types.BackupStatusProcessing, progress, fmt.Sprintf("Processing files (%d/%d)...", processedFiles, totalFiles), "")++ }(file)+ }++ wg.Wait()++ return nil+}++// createFileIndex creates an index mapping file IDs to their archive paths+func (s *backupService) createFileIndex(files []*models.Node) []map[string]interface{} {+ index := make([]map[string]interface{}, len(files))+ for i, f := range files {+ archivePath := fmt.Sprintf("files/%d%s", f.Id, filepath.Ext(f.Name))+ if f.Metadata != nil {+ if originalPath, ok := (*f.Metadata)["original_path"].(string); ok {+ archivePath = fmt.Sprintf("files/%d_%s", f.Id, filepath.Base(originalPath))+ }+ }++ entry := map[string]interface{}{+ "id": f.Id,+ "name": f.Name,+ "archive_path": archivePath,+ "size": f.Size,+ "metadata": f.Metadata,+ }+ index[i] = entry+ }+ return index+}diff --git a/backend/services/manager.go b/backend/services/manager.goindex 2e318592..3a2127a7 100644--- a/backend/services/manager.go+++ b/backend/services/manager.go@@ -18,7 +18,8 @@ type ServiceManager struct {Log LogServiceSession SessionServiceMinio MinioService- Resource ResourceService+ Resource ResourceService+ Backup BackupServiceinitialized bool}@@ -61,6 +62,9 @@ func (sm *ServiceManager) initializeServices(repos *repositories.RepositoryManag// Initialize Resource Servicesm.Resource = NewResourceService(repos.Node, snowflake)+ // Initialize Backup Service+ sm.Backup = NewBackupService(repos.Node)+return nil}diff --git a/backend/services/resource.service.go b/backend/services/resource.service.goindex 7ebe4e68..388495dd 100644--- a/backend/services/resource.service.go+++ b/backend/services/resource.service.go@@ -8,7 +8,6 @@ import ("alexandrie/utils""bytes""context"- "encoding/json""errors""fmt""os"@@ -20,7 +19,6 @@ import ()type ResourceService interface {- CreateBackup(userId types.Snowflake, minioClient *minio.Client) (string, error)UploadFile(filename string, fileSize int64, fileContent []byte, mimeType string, userId types.Snowflake, maxUploadsSize float64, supportedTypes []string, minioClient *minio.Client) (*models.Node, error)UploadAvatar(filename string, fileSize int64, fileContent []byte, mimeType string, userId types.Snowflake, supportedTypes []string, minioClient *minio.Client) error}@@ -37,33 +35,6 @@ func NewResourceService(nodeRepo repositories.NodeRepository, snowflake *snowfla}}-func (s *resourceService) CreateBackup(userId types.Snowflake, minioClient *minio.Client) (string, error) {- if minioClient == nil {- return "", errors.New("minio client not initialized")- }-- nodes, err := s.nodeRepo.GetAllForBackup(userId)- if err != nil {- return "", err- }-- backup := map[string]interface{}{- "nodes": nodes,- }- jsonString, err := json.Marshal(backup)- if err != nil {- return "", err- }-- objectName := fmt.Sprintf("%d/backups/backup.json", userId)- _, err = minioClient.PutObject(context.Background(), os.Getenv("MINIO_BUCKET"), objectName, bytes.NewReader(jsonString), int64(len(jsonString)), minio.PutObjectOptions{ContentType: "application/json"})- if err != nil {- return "", err- }-- return objectName, nil-}-func (s *resourceService) UploadFile(filename string, fileSize int64, fileContent []byte, mimeType string, userId types.Snowflake, maxUploadsSize float64, supportedTypes []string, minioClient *minio.Client) (*models.Node, error) {if minioClient == nil {return nil, errors.New("minio client not initialized")diff --git a/backend/types/backup.go b/backend/types/backup.gonew file mode 100644index 00000000..b8ddb453--- /dev/null+++ b/backend/types/backup.go@@ -0,0 +1,80 @@+package types++import (+ "encoding/json"+ "time"+)++// BackupStatus represents the current state of a backup job+type BackupStatus string++const (+ BackupStatusPending BackupStatus = "pending"+ BackupStatusProcessing BackupStatus = "processing"+ BackupStatusCompleted BackupStatus = "completed"+ BackupStatusFailed BackupStatus = "failed"+)++// BackupOptions defines what data to include in the backup+type BackupOptions struct {+ IncludeDocuments bool `json:"include_documents"` // Include documents/notes content+ IncludeFiles bool `json:"include_files"` // Include uploaded files (images, PDFs, etc.)+ IncludeSettings bool `json:"include_settings"` // Include user settings and preferences+ IncludeMetadata bool `json:"include_metadata"` // Include node metadata+}++// DefaultBackupOptions returns the default backup options (everything included)+func DefaultBackupOptions() BackupOptions {+ return BackupOptions{+ IncludeDocuments: true,+ IncludeFiles: true,+ IncludeSettings: true,+ IncludeMetadata: true,+ }+}++// BackupJob represents an ongoing or completed backup job+type BackupJob struct {+ ID string `json:"id"`+ UserID Snowflake `json:"user_id"`+ Status BackupStatus `json:"status"`+ Options BackupOptions `json:"options"`+ Progress int `json:"progress"` // 0-100+ Message string `json:"message"` // Current status message+ DownloadURL string `json:"download_url,omitempty"` // Available when completed+ Error string `json:"error,omitempty"` // Error message if failed+ CreatedAt time.Time `json:"created_at"`+ UpdatedAt time.Time `json:"updated_at"`+ ExpiresAt time.Time `json:"expires_at,omitempty"` // When the backup file will be deleted+}++// BackupManifest contains metadata about the backup contents+type BackupManifest struct {+ Version string `json:"version"`+ CreatedAt time.Time `json:"created_at"`+ UserID Snowflake `json:"user_id"`+ Options BackupOptions `json:"options"`+ Statistics BackupStats `json:"statistics"`+}++// BackupStats contains statistics about the backup contents+type BackupStats struct {+ TotalNodes int `json:"total_nodes"`+ TotalDocuments int `json:"total_documents"`+ TotalFiles int `json:"total_files"`+ TotalSize int64 `json:"total_size_bytes"`+ SkippedFiles []SkippedFile `json:"skipped_files,omitempty"`+}++// SkippedFile represents a file that was skipped during backup+type SkippedFile struct {+ ID Snowflake `json:"id"`+ Name string `json:"name"`+ Reason string `json:"reason"`+}++// MarshalJSON ensures proper JSON encoding+func (bo BackupOptions) MarshalJSON() ([]byte, error) {+ type Alias BackupOptions+ return json.Marshal(&struct{ Alias }{Alias: Alias(bo)})+}diff --git a/backend/utils/utils.go b/backend/utils/utils.goindex 64716ad0..66db1025 100644--- a/backend/utils/utils.go+++ b/backend/utils/utils.go@@ -1,5 +1,7 @@package utils+import "os"+func IfNotNilPointer[T any](newValue, defaultValue *T) *T {if newValue != nil {return newValue@@ -16,3 +18,9 @@ func IfNotNilValue[T any](newValue *T, defaultValue T) T {func IntPtr(i int) *int {return &i}++// GetBackupBucketName returns the name of the private backup bucket+func GetBackupBucketName() string {+ baseBucket := os.Getenv("MINIO_BUCKET")+ return baseBucket + "-backups"+}diff --git a/frontend/app/components/AppButton.vue b/frontend/app/components/AppButton.vueindex 819fda3b..55530c9e 100644--- a/frontend/app/components/AppButton.vue+++ b/frontend/app/components/AppButton.vue@@ -31,6 +31,9 @@ button {&:hover {background: var(--primary-dark);}+ * {+ fill: white !important;+ }}.secondary {diff --git a/frontend/app/components/Icon.vue b/frontend/app/components/Icon.vueindex 752b0b0e..e9df04aa 100644--- a/frontend/app/components/Icon.vue+++ b/frontend/app/components/Icon.vue@@ -8,7 +8,7 @@</template><script setup lang="ts">-const props = withDefaults(defineProps<{ name: string; fill?: string; display?: 'sm' | 'md' | 'lg' | 'xl' | 'xll'; size?: string }>(), {+const props = withDefaults(defineProps<{ name: string; fill?: string; display?: 'sm' | 'md' | 'lg' | 'xl' | 'xll'; size?: number | string }>(), {display: 'md',fill: 'var(--font-color)',size: undefined,diff --git a/frontend/app/composables/useDateFormatters.ts b/frontend/app/composables/useDateFormatters.tsindex eb4545a9..1c8ecb44 100644--- a/frontend/app/composables/useDateFormatters.ts+++ b/frontend/app/composables/useDateFormatters.ts@@ -7,7 +7,7 @@ function shortDate(timestamp: number | undefined): string {}/** Format a timestamp to a numeric date string (e.g., "12/15/2024") */-function numericDate(timestamp: number): string {+function numericDate(timestamp: number | string): string {return new Date(timestamp).toLocaleDateString(locale, {year: 'numeric',month: '2-digit',diff --git a/frontend/app/error.vue b/frontend/app/error.vueindex 219983ff..53f487eb 100644--- a/frontend/app/error.vue+++ b/frontend/app/error.vue@@ -31,7 +31,7 @@ const props = defineProps({});</script>-<style lang="scss">+<style scoped lang="scss">.error-container {display: flex;min-height: 100vh;diff --git a/frontend/app/pages/dashboard/cdn/index.vue b/frontend/app/pages/dashboard/cdn/index.vueindex cdec70b3..1f1362b8 100644--- a/frontend/app/pages/dashboard/cdn/index.vue+++ b/frontend/app/pages/dashboard/cdn/index.vue@@ -159,7 +159,7 @@ const submitFiles = async () => {};const previewURL = (resource: Node) => {- if ((resource.metadata?.filetype as string)?.includes('image/')) return resourceURL(resource);+ if ((resource.metadata?.filetype || '')?.includes('image/')) return resourceURL(resource);return '/file_placeholder.png';};const headers = [@@ -179,7 +179,7 @@ const rows: ComputedRef<Field[]> = computed(() =>return {name: { content: res.name, type: 'text' },size: { content: readableFileSize(res.size ?? 0), type: 'text' },- type: { content: `<tag class="${color(res.metadata?.filetype as string)}">${res.metadata?.filetype as string}</tag>`, type: 'html' },+ type: { content: `<tag class="${color(res.metadata?.filetype || '')}">${res.metadata?.filetype || ''}</tag>`, type: 'html' },parent: { content: category ? `<tag class="${appColors.getAppAccent(category.color)}">${parent?.name}</tag>` : '', type: 'html' },date: { content: numericDate(res.created_timestamp), type: 'text' },action: { type: 'slot', data: res },diff --git a/frontend/app/pages/dashboard/settings/_views/backups.vue b/frontend/app/pages/dashboard/settings/_views/backups.vueindex 7a22f39a..c6dc29ba 100644--- a/frontend/app/pages/dashboard/settings/_views/backups.vue+++ b/frontend/app/pages/dashboard/settings/_views/backups.vue@@ -1,18 +1,91 @@<template><div>- <h2 class="app-title">Backups</h2>+ <h2 class="app-title">Backups <tag yellow>Beta</tag></h2><div class="main">- <p>Click the button below to create a backup of your data.</p>- <AppButton type="primary" @click="submitFile">Create Backup</AppButton>- <LoaderSpinner v-if="isLoading" />- <div v-if="downloadLink" class="link-section">- <p>Your backup is ready. You can copy the link to share it or download it.</p>- <input v-model="downloadLink" type="text" readonly placeholder="Backup Link" />+ <p>Create a backup of your data with customizable options.</p>++ <!-- Backup Options -->+ <div class="options-section">+ <h3>Backup Options</h3>+ <div class="options-grid">+ <AppCheck v-model="options.includeDocuments">+ <span class="option-label">+ <Icon name="folder" display="sm" />+ Documents & Categories+ </span>+ </AppCheck>+ <AppCheck v-model="options.includeFiles">+ <span class="option-label">+ <Icon name="image" display="sm" />+ Uploaded Files (images, PDFs, etc.)+ </span>+ </AppCheck>+ <AppCheck v-model="options.includeSettings">+ <span class="option-label">+ <Icon name="settings" display="sm" />+ Settings & Preferences+ </span>+ </AppCheck>+ <AppCheck v-model="options.includeMetadata">+ <span class="option-label">+ <Icon name="layers" display="sm" />+ Metadata+ </span>+ </AppCheck>+ </div>+ </div>++ <!-- Start Backup Button -->+ <AppButton type="primary" :disabled="isProcessing || !hasAnyOption" @click="startBackup">+ <Icon v-if="!isProcessing" name="backup" display="sm" />+ {{ isProcessing ? 'Creating Backup...' : 'Create Backup' }}+ </AppButton>+ <LoaderSpinner v-if="isProcessing" />+ <!-- Progress Section -->+ <div v-if="currentJob" class="progress-section">+ <div class="progress-header">+ <span class="status-badge" :class="currentJob.status">+ {{ statusLabel }}+ </span>+ <span v-if="currentJob.status === 'processing'" class="progress-percent"> {{ currentJob.progress }}% </span>+ </div>++ <div v-if="currentJob.status === 'processing'" class="progress-bar-container">+ <div class="progress-bar" :style="{ width: currentJob.progress + '%' }"></div>+ </div>++ <p class="progress-message">{{ currentJob.message }}</p>++ <!-- Cancel Button -->+ <AppButton v-if="currentJob.status === 'processing' || currentJob.status === 'pending'" type="secondary" @click="cancelBackup">+ <Icon name="close" display="sm" />+ Cancel+ </AppButton>++ <!-- Error Message -->+ <div v-if="currentJob.status === 'failed' && currentJob.error" class="error-message">+ {{ currentJob.error }}+ </div>+ </div>++ <!-- Download Section -->+ <div v-if="currentJob?.status === 'completed' && currentJob.download_url" class="link-section">+ <p class="expiry-notice">+ <Icon name="clock" :size="14" />+ This link expires on {{ numericDate(currentJob.expires_at || '') }}+ </p>+ <input v-model="currentJob.download_url" type="text" readonly placeholder="Backup Link" /><div class="actions">- <AppButton type="secondary" @click="copyLink">Copy Link</AppButton>- <a :href="downloadLink + '?response-content-disposition=attachment%3B%20filename%3D%22' + fileName()" download- ><AppButton type="primary">Download Backup</AppButton></a- >+ <AppButton type="secondary" @click="copyLink">+ <Icon name="copy" display="sm" />+ Copy Link+ </AppButton>+ <a :href="currentJob.download_url" download>+ <AppButton type="primary">+ <Icon name="download" display="sm" />+ Download Backup+ </AppButton>+ </a></div></div></div>@@ -20,32 +93,317 @@</template><script setup lang="ts">-const { CDN } = useApi();+interface BackupJob {+ id: string;+ user_id: string;+ status: 'pending' | 'processing' | 'completed' | 'failed';+ options: BackupOptions;+ progress: number;+ message: string;+ download_url?: string;+ error?: string;+ created_at: string;+ updated_at: string;+ expires_at?: string;+}++interface BackupOptions {+ include_documents: boolean;+ include_files: boolean;+ include_settings: boolean;+ include_metadata: boolean;+}++const options = reactive({+ includeDocuments: true,+ includeFiles: true,+ includeSettings: true,+ includeMetadata: true,+});++const { numericDate } = useDateFormatters();+const notifications = useNotifications();++const currentJob = ref<BackupJob | null>(null);+const pollingInterval = ref<ReturnType<typeof setInterval> | null>(null);++const isProcessing = computed(() => currentJob.value?.status === 'pending' || currentJob.value?.status === 'processing');++const hasAnyOption = computed(() => options.includeDocuments || options.includeFiles || options.includeSettings || options.includeMetadata);-const downloadLink = ref<string | null>(null);-const isLoading = ref(false);+const statusLabel = computed(() => {+ switch (currentJob.value?.status) {+ case 'pending':+ return 'Pending';+ case 'processing':+ return 'Processing';+ case 'completed':+ return 'Completed';+ case 'failed':+ return 'Failed';+ default:+ return '';+ }+});-const copyLink = () => navigator.clipboard.writeText(downloadLink.value!);-const fileName = () => `backup-${new Date().toISOString().split('T')[0]}.json`;+const copyLink = () => {+ if (currentJob.value?.download_url) {+ navigator.clipboard.writeText(currentJob.value.download_url);+ notifications.add({ type: 'success', title: 'Copied', message: 'Link copied to clipboard' });+ }+};++async function startBackup() {+ // Clear previous job+ stopPolling();+ currentJob.value = null;++ const result = await makeRequest<{ job_id: string; message: string }>('backup', 'POST', {+ include_documents: options.includeDocuments,+ include_files: options.includeFiles,+ include_settings: options.includeSettings,+ include_metadata: options.includeMetadata,+ });++ if (result.status !== 'success' || !result.result?.job_id) {+ error('Failed to start backup');+ return;+ }++ notifications.add({ type: 'success', title: 'Backup Started', message: 'Your backup is being created...' });+ // Start polling for status+ startPolling(result.result.job_id);+}++async function checkStatus(jobId: string) {+ const result = await makeRequest<BackupJob>(`backup/${jobId}`, 'GET', {});++ if (result.status !== 'success' || !result.result) {+ stopPolling();+ error();+ return;+ }+ currentJob.value = result.result;++ // Stop polling if job is finished+ if (result.result.status === 'completed' || result.result.status === 'failed') {+ stopPolling();++ if (result.result.status === 'completed') {+ notifications.add({ type: 'success', title: 'Backup Complete', message: 'Your backup is ready for download!' });+ } else if (result.result.status === 'failed') {+ error(result.result.message, result.result.error);+ }+ }+}++function startPolling(jobId: string) {+ // Initial check+ checkStatus(jobId);++ // Poll every 2 seconds+ pollingInterval.value = setInterval(() => {+ checkStatus(jobId);+ }, 2000);+}++function stopPolling() {+ if (pollingInterval.value) {+ clearInterval(pollingInterval.value);+ pollingInterval.value = null;+ }+}++async function cancelBackup() {+ if (!currentJob.value?.id) return;++ const result = await makeRequest(`backup/${currentJob.value.id}`, 'DELETE', {});++ if (result.status !== 'success') {+ notifications.add({ type: 'error', title: 'Error', message: result.message || 'Failed to cancel backup' });+ return;+ }++ stopPolling();+ notifications.add({ type: 'info', title: 'Cancelled', message: 'Backup has been cancelled' });+ currentJob.value = null;+}-async function submitFile() {- isLoading.value = true;- const result = await makeRequest<{ link: string }>('resources/backup', 'GET', {});- isLoading.value = false;- if (result.status != 'success') return useNotifications().add({ type: 'error', title: 'Error', message: result.message });- downloadLink.value = `${CDN}/${result.result?.link || ''}`;+function error(message?: string, error?: string) {+ notifications.add({ type: 'error', title: 'Error', message: 'An unknown error occurred' });+ currentJob.value = {+ status: 'failed',+ id: '',+ user_id: '',+ options: { include_documents: false, include_files: false, include_settings: false, include_metadata: false },+ progress: 0,+ message: message || 'An error occurred while fetching the backup status. Please try again later.',+ error: error,+ created_at: '',+ updated_at: '',+ };}++// Cleanup on unmount+onUnmounted(() => {+ stopPolling();+});</script><style scoped lang="scss">.main {+ max-width: 600px;margin: auto;text-align: center;}+.options-section {+ margin: 1.5rem 0;+ padding: 1rem;+ background: var(--bg-color-2);+ border-radius: $radius-sm;+ text-align: left;++ h3 {+ margin-bottom: 1rem;+ font-size: 1rem;+ color: var(--font-color);+ }+}++.options-grid {+ display: flex;+ flex-direction: column;+ gap: 0.75rem;+}++.option-label {+ display: inline-flex;+ align-items: center;+ gap: 0.5rem;+}++.progress-section {+ padding: 1rem;+ background: var(--bg-color-2);+ border-radius: $radius-sm;+}++.progress-header {+ display: flex;+ align-items: center;+ justify-content: space-between;+ margin-bottom: 0.75rem;+}++.status-badge {+ padding: 0.25rem 0.75rem;+ border-radius: $radius-sm;+ font-size: 0.875rem;+ font-weight: 500;++ &.pending {+ background: var(--yellow-bg);+ color: var(--yellow);+ }++ &.processing {+ background: var(--primary-bg);+ color: var(--primary);+ }++ &.completed {+ background: var(--green-bg);+ color: var(--green);+ }++ &.failed {+ background: var(--red-bg);+ color: var(--red);+ }+}++.progress-percent {+ font-weight: 600;+ color: var(--primary);+}++.progress-bar-container {+ width: 100%;+ height: 8px;+ background: var(--border-color);+ border-radius: 4px;+ overflow: hidden;+ margin-bottom: 0.75rem;+}++.progress-bar {+ height: 100%;+ background: var(--primary);+ border-radius: 4px;+ transition: width 0.3s ease;+}++.progress-message {+ color: var(--font-color-dark);+ font-size: 1rem;+ font-weight: bold;+ margin-bottom: 0.75rem;+}++.error-message {+ display: flex;+ align-items: center;+ gap: 0.5rem;+ padding: 0.75rem;+ background: var(--error-bg);+ color: var(--error);+ border-radius: $radius-sm;+ margin-top: 0.75rem;+ text-align: left;+}++.link-section {+ margin-top: 1.5rem;+ padding: 1rem;+ background: var(--bg-color-2);+ border-radius: $radius-sm;+}++.expiry-notice {+ display: flex;+ align-items: center;+ justify-content: center;+ gap: 0.25rem;+ font-size: 0.75rem;+ color: var(--font-color-dark);+ margin-bottom: 1rem;+}++input[type='text'] {+ width: 100%;+ padding: 0.75rem;+ border: 1px solid var(--border-color);+ border-radius: $radius-sm;+ background: var(--bg-color);+ color: var(--font-color);+ font-size: 0.875rem;+}+.actions {display: flex;- gap: 4px;- margin-top: 8px;+ gap: 0.5rem;+ margin-top: 0.75rem;+ justify-content: center;++ a {+ text-decoration: none;+ }+}++button {+ display: inline-flex;+ align-items: center;+ gap: 0.5rem;}</style>diff --git a/frontend/nuxt.config.ts b/frontend/nuxt.config.tsindex a7805df1..efc77c5f 100644--- a/frontend/nuxt.config.ts+++ b/frontend/nuxt.config.ts@@ -159,14 +159,12 @@ export default defineNuxtConfig({},{// Api cache: match /api calls- urlPattern: ({ url }) => url.pathname.startsWith('/api/'),+ urlPattern: ({ url }) => {+ return url.pathname.startsWith('/api/') && !url.pathname.startsWith('/api/backup/');+ },handler: 'NetworkFirst',options: {cacheName: 'api-cache',- expiration: {- maxEntries: 50,- maxAgeSeconds: 86400,- },},},],diff --git a/frontend/public/app-icons/clock.svg b/frontend/public/app-icons/clock.svgnew file mode 100644index 00000000..9d81c062--- /dev/null+++ b/frontend/public/app-icons/clock.svg@@ -0,0 +1 @@+<svg xmlns="http://www.w3.org/2000/svg" height="20px" viewBox="0 -960 960 960" width="20px" fill="var(--font-color)"><path d="m612-292 56-56-148-148v-184h-80v216l172 172ZM480-80q-83 0-156-31.5T197-197q-54-54-85.5-127T80-480q0-83 31.5-156T197-763q54-54 127-85.5T480-880q83 0 156 31.5T763-763q54 54 85.5 127T880-480q0 83-31.5 156T763-197q-54 54-127 85.5T480-80Zm0-400Zm0 320q133 0 226.5-93.5T800-480q0-133-93.5-226.5T480-800q-133 0-226.5 93.5T160-480q0 133 93.5 226.5T480-160Z" /></svg>\ No newline at end of filediff --git a/frontend/public/app-icons/download.svg b/frontend/public/app-icons/download.svgnew file mode 100644index 00000000..1a9b045f--- /dev/null+++ b/frontend/public/app-icons/download.svg@@ -0,0 +1 @@+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 -960 960 960"><path d="M480-320 280-520l56-58 104 104v-326h80v326l104-104 56 58-200 200ZM240-160q-33 0-56.5-23.5T160-240v-120h80v120h480v-120h80v120q0 33-23.5 56.5T720-160H240Z"/></svg>\ No newline at end of filediff --git a/frontend/public/app-icons/success.svg b/frontend/public/app-icons/success.svgnew file mode 100644index 00000000..deff8321--- /dev/null+++ b/frontend/public/app-icons/success.svg@@ -0,0 +1 @@+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 -960 960 960"><path d="m424-296 282-282-56-56-226 226-114-114-56 56 170 170Zm56 216q-83 0-156-31.5T197-197q-54-54-85.5-127T80-480q0-83 31.5-156T197-763q54-54 127-85.5T480-880q83 0 156 31.5T763-763q54 54 85.5 127T880-480q0 83-31.5 156T763-197q-54 54-127 85.5T480-80Zm0-80q134 0 227-93t93-227q0-134-93-227t-227-93q-134 0-227 93t-93 227q0 134 93 227t227 93Zm0-320Z"/></svg>\ No newline at end of file