// backend/internal/fs.go
package internal

import (
	"errors"
	"os"
	"path/filepath"
	"strings"
)

var absPath = filepath.Abs

// SafeJoin resolves rel under root and rejects any path that escapes the root.
func SafeJoin(root, rel string) (string, error) {
	rel = strings.TrimPrefix(rel, "/")
	p := filepath.Join(root, rel)
	ap, err := absPath(p)
	if err != nil {
		return "", err
	}
	ar, err := absPath(root)
	if err != nil {
		return "", err
	}
	if !strings.HasPrefix(ap, ar+string(os.PathSeparator)) && ap != ar {
		return "", errors.New("path escapes root")
	}
	return ap, nil
}
