blossom

package
v0.59.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 13, 2026 License: Unlicense Imports: 28 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// BlossomAuthKind is the Nostr event kind for Blossom authorization events (BUD-01)
	BlossomAuthKind = 24242
	// AuthorizationHeader is the HTTP header name for authorization
	AuthorizationHeader = "Authorization"
	// NostrAuthPrefix is the prefix for Nostr authorization scheme
	NostrAuthPrefix = "Nostr"
)
View Source
const ThumbnailSize = 128

ThumbnailSize defines the maximum dimension for thumbnails (used for list display)

Variables

View Source
var VariantSpecs = map[ImageVariant]VariantSpec{
	VariantThumb:     {Width: 128, Quality: 70},
	VariantMobileSm:  {Width: 512, Quality: 75},
	VariantMobileLg:  {Width: 1024, Quality: 80},
	VariantDesktopSm: {Width: 1536, Quality: 85},
	VariantDesktopMd: {Width: 2048, Quality: 88},
	VariantDesktopLg: {Width: 2560, Quality: 90},
	VariantOriginal:  {Width: 0, Quality: 92},
}

VariantSpecs maps variant types to their specifications

Functions

func BuildBlobURL

func BuildBlobURL(baseURL, sha256Hex, ext string) string

BuildBlobURL builds a blob URL with optional extension

func CalculateSHA256

func CalculateSHA256(data []byte) []byte

CalculateSHA256 calculates the SHA256 hash of data

func CalculateSHA256Hex

func CalculateSHA256Hex(data []byte) string

CalculateSHA256Hex calculates the SHA256 hash and returns it as hex string

func DetectMimeType

func DetectMimeType(contentType string, ext string) string

DetectMimeType detects MIME type from Content-Type header or file extension

func ExtractAuthEvent

func ExtractAuthEvent(r *http.Request) (ev *event.E, err error)

ExtractAuthEvent extracts and parses a kind 24242 authorization event from the Authorization header

func ExtractSHA256FromPath

func ExtractSHA256FromPath(path string) (sha256Hex string, ext string, err error)

ExtractSHA256FromPath extracts SHA256 hash from URL path Supports both /<sha256> and /<sha256>.<ext> formats

func ExtractSHA256FromURL

func ExtractSHA256FromURL(urlStr string) (sha256Hex string, err error)

ExtractSHA256FromURL extracts SHA256 hash from a URL string Uses the last occurrence of a 64 char hex string (as per BUD-03)

func GenerateThumbnail added in v0.58.17

func GenerateThumbnail(data []byte, mimeType string, maxSize int) ([]byte, string, error)

GenerateThumbnail creates a thumbnail from image data using Lanczos resampling. Returns the thumbnail data, MIME type, and any error. Thumbnails are always JPEG for smaller file sizes.

func GetExtensionFromMimeType

func GetExtensionFromMimeType(mimeType string) string

GetExtensionFromMimeType returns file extension based on MIME type

func GetFileExtensionFromPath

func GetFileExtensionFromPath(path string) string

GetFileExtensionFromPath extracts file extension from a path

func GetMimeTypeFromExtension

func GetMimeTypeFromExtension(ext string) string

GetMimeTypeFromExtension returns MIME type based on file extension

func GetPubkeyFromRequest

func GetPubkeyFromRequest(r *http.Request) (pubkey []byte, err error)

GetPubkeyFromRequest extracts pubkey from Authorization header if present

func IsImageMimeType added in v0.58.17

func IsImageMimeType(mimeType string) bool

IsImageMimeType returns true if the MIME type is a supported image format

func OptimizeMedia

func OptimizeMedia(data []byte, mimeType string) (optimizedData []byte, optimizedMimeType string)

OptimizeMedia optimizes media content (BUD-05) This is a placeholder implementation - actual optimization would use libraries like image processing, video encoding, etc.

func ParseRangeHeader

func ParseRangeHeader(rangeHeader string, contentLength int64) (
	start, end int64, valid bool, err error,
)

ParseRangeHeader parses HTTP Range header (RFC 7233) Returns start, end, and total length

func SetPaymentRequired

func SetPaymentRequired(w http.ResponseWriter, paymentHeaders map[string]string)

SetPaymentRequired sets a 402 Payment Required response with payment headers

func ValidateSHA256Hex

func ValidateSHA256Hex(s string) bool

ValidateSHA256Hex validates that a string is a valid SHA256 hex string

func WriteRangeResponse

func WriteRangeResponse(
	w http.ResponseWriter, data []byte, start, end, totalLength int64,
)

WriteRangeResponse writes a partial content response (206)

Types

type AuthEvent

type AuthEvent struct {
	Event   *event.E
	Pubkey  []byte
	Verb    string
	Expires int64
}

AuthEvent represents a validated authorization event

func ValidateAuthEvent

func ValidateAuthEvent(
	r *http.Request, verb string, sha256Hash []byte,
) (authEv *AuthEvent, err error)

ValidateAuthEvent validates a kind 24242 authorization event according to BUD-01

func ValidateAuthEventForDelete added in v0.58.10

func ValidateAuthEventForDelete(
	r *http.Request, serverURL string, sha256Hash []byte, requireServerTag bool,
) (authEv *AuthEvent, err error)

ValidateAuthEventForDelete validates authorization for DELETE requests (BUD-02) If requireServerTag is true, the auth event must include a 'server' tag matching the serverURL This prevents cross-server replay attacks where a malicious server replays delete auth events

func ValidateAuthEventForGet

func ValidateAuthEventForGet(
	r *http.Request, serverURL string, sha256Hash []byte,
) (authEv *AuthEvent, err error)

ValidateAuthEventForGet validates authorization for GET requests (BUD-01) GET requests may have either: - A server tag matching the server URL - At least one x tag matching the blob hash

func ValidateAuthEventOptional

func ValidateAuthEventOptional(
	r *http.Request, verb string, sha256Hash []byte,
) (authEv *AuthEvent, err error)

ValidateAuthEventOptional validates authorization but returns nil if no auth header is present This is used for endpoints where authorization is optional

type BandwidthLimiter added in v0.49.0

type BandwidthLimiter struct {
	// contains filtered or unexported fields
}

BandwidthLimiter implements token bucket rate limiting for uploads. Each identity gets a bucket that replenishes at dailyLimit/day rate. Uploads consume tokens from the bucket.

func NewBandwidthLimiter added in v0.49.0

func NewBandwidthLimiter(dailyLimitMB, burstLimitMB int64) *BandwidthLimiter

NewBandwidthLimiter creates a new bandwidth limiter. dailyLimitMB is the average daily limit in megabytes. burstLimitMB is the maximum burst capacity in megabytes.

func (*BandwidthLimiter) CheckAndConsume added in v0.49.0

func (bl *BandwidthLimiter) CheckAndConsume(identity string, sizeBytes int64) bool

CheckAndConsume checks if an upload of the given size is allowed for the identity, and if so, consumes the tokens. Returns true if allowed, false if rate limited. The identity should be pubkey hex for authenticated users, or IP for anonymous.

func (*BandwidthLimiter) Cleanup added in v0.49.0

func (bl *BandwidthLimiter) Cleanup()

Cleanup removes entries that have fully replenished (at burst limit).

func (*BandwidthLimiter) GetAvailable added in v0.49.0

func (bl *BandwidthLimiter) GetAvailable(identity string) int64

GetAvailable returns the currently available bytes for an identity.

func (*BandwidthLimiter) GetTimeUntilAvailable added in v0.49.0

func (bl *BandwidthLimiter) GetTimeUntilAvailable(identity string, sizeBytes int64) time.Duration

GetTimeUntilAvailable returns how long until the given bytes will be available.

func (*BandwidthLimiter) Stats added in v0.49.0

func (bl *BandwidthLimiter) Stats() int

Stats returns the number of tracked identities.

type BandwidthState added in v0.49.0

type BandwidthState struct {
	BucketBytes int64     // Current token bucket level (bytes available)
	LastUpdate  time.Time // Last time bucket was updated
}

BandwidthState tracks upload bandwidth for an identity

type BaseURLKey added in v0.36.12

type BaseURLKey struct{}

BaseURLKey is the context key for the base URL (exported for use by app handler)

type BlobDescriptor

type BlobDescriptor struct {
	URL      string     `json:"url"`
	SHA256   string     `json:"sha256"`
	Size     int64      `json:"size"`
	Type     string     `json:"type"`
	Uploaded int64      `json:"uploaded"`
	NIP94    [][]string `json:"nip94,omitempty"`
}

BlobDescriptor represents a blob descriptor as defined in BUD-02

func NewBlobDescriptor

func NewBlobDescriptor(
	url, sha256 string, size int64, mimeType string, uploaded int64,
) *BlobDescriptor

NewBlobDescriptor creates a new blob descriptor

type BlobMetadata

type BlobMetadata struct {
	Pubkey    []byte `json:"pubkey"`
	MimeType  string `json:"mime_type"`
	Uploaded  int64  `json:"uploaded"`
	Size      int64  `json:"size"`
	Extension string `json:"extension"` // File extension (e.g., ".png", ".pdf")
}

BlobMetadata stores metadata about a blob in the database

func DeserializeBlobMetadata

func DeserializeBlobMetadata(data []byte) (bm *BlobMetadata, err error)

DeserializeBlobMetadata deserializes blob metadata from JSON

func NewBlobMetadata

func NewBlobMetadata(pubkey []byte, mimeType string, size int64) *BlobMetadata

NewBlobMetadata creates a new blob metadata struct

func (*BlobMetadata) Serialize

func (bm *BlobMetadata) Serialize() (data []byte, err error)

Serialize serializes blob metadata to JSON

type Config

type Config struct {
	BaseURL          string
	MaxBlobSize      int64
	AllowedMimeTypes []string
	RequireAuth      bool

	// Rate limiting (for non-followed users)
	RateLimitEnabled bool
	DailyLimitMB     int64
	BurstLimitMB     int64

	// Delete replay protection (proposed BUD enhancement)
	// When true, DELETE auth events must include a 'server' tag matching this server
	DeleteRequireServerTag bool
}

Config holds configuration for the Blossom server

type ImageVariant added in v0.58.17

type ImageVariant string

ImageVariant represents a responsive image size category per NIP-XX Selection rule: pick smallest variant >= target width (next-larger)

const (
	VariantThumb     ImageVariant = "thumb"      // 128px - list display, previews
	VariantMobileSm  ImageVariant = "mobile-sm"  // 512px - small mobile
	VariantMobileLg  ImageVariant = "mobile-lg"  // 1024px - large mobile, small tablets
	VariantDesktopSm ImageVariant = "desktop-sm" // 1536px - laptops
	VariantDesktopMd ImageVariant = "desktop-md" // 2048px - standard desktops
	VariantDesktopLg ImageVariant = "desktop-lg" // 2560px - large/HiDPI displays
	VariantOriginal  ImageVariant = "original"   // unchanged size, EXIF stripped
)

type PaymentChecker

type PaymentChecker struct {
}

PaymentChecker handles payment requirements (BUD-07)

func NewPaymentChecker

func NewPaymentChecker() *PaymentChecker

NewPaymentChecker creates a new payment checker

func (*PaymentChecker) CheckPaymentRequired

func (pc *PaymentChecker) CheckPaymentRequired(
	endpoint string,
) (required bool, paymentHeaders map[string]string)

CheckPaymentRequired checks if payment is required for an endpoint Returns payment method headers if payment is required

func (*PaymentChecker) ValidatePayment

func (pc *PaymentChecker) ValidatePayment(
	paymentMethod, proof string,
) (valid bool, err error)

ValidatePayment validates a payment proof

type ScaledImage added in v0.58.17

type ScaledImage struct {
	Variant  ImageVariant
	Data     []byte
	Width    int
	Height   int
	MimeType string
}

ScaledImage represents a generated image variant

func GenerateResponsiveVariants added in v0.58.17

func GenerateResponsiveVariants(data []byte, mimeType string) ([]ScaledImage, error)

GenerateResponsiveVariants creates multiple resolution variants of an image. Uses Lanczos resampling for high-quality downscaling. Returns variants from smallest to largest: thumb, mobile, desktop, original. EXIF metadata is automatically stripped from all variants.

type Server

type Server struct {
	// contains filtered or unexported fields
}

Server provides a Blossom server implementation

func NewServer

func NewServer(db database.Database, aclRegistry *acl.S, cfg *Config) *Server

NewServer creates a new Blossom server instance

func (*Server) Handler

func (s *Server) Handler() http.Handler

Handler returns an http.Handler that can be attached to a router

type Storage

type Storage struct {
	// contains filtered or unexported fields
}

Storage provides blob storage operations using the database interface. This is a thin wrapper that delegates to the database's blob methods.

func NewStorage

func NewStorage(db database.Database) *Storage

NewStorage creates a new storage instance using the database interface.

func (*Storage) DeleteBlob

func (s *Storage) DeleteBlob(sha256Hash []byte, pubkey []byte) error

DeleteBlob deletes a blob and its metadata.

func (*Storage) GetBlob

func (s *Storage) GetBlob(sha256Hash []byte) (data []byte, metadata *BlobMetadata, err error)

GetBlob retrieves blob data by SHA256 hash. Returns the data and metadata from the database.

func (*Storage) GetBlobMetadata

func (s *Storage) GetBlobMetadata(sha256Hash []byte) (*BlobMetadata, error)

GetBlobMetadata retrieves only metadata for a blob.

func (*Storage) GetBlobPath added in v0.58.14

func (s *Storage) GetBlobPath(sha256Hex string, extension string) string

GetBlobPath returns the filesystem path for a blob given its hash and extension. This is used by handlers that need to serve files directly via http.ServeFile.

func (*Storage) GetThumbnail added in v0.58.17

func (s *Storage) GetThumbnail(key string) ([]byte, error)

GetThumbnail retrieves a cached thumbnail by key.

func (*Storage) GetTotalStorageUsed

func (s *Storage) GetTotalStorageUsed(pubkey []byte) (totalMB int64, err error)

GetTotalStorageUsed calculates total storage used by a pubkey in MB.

func (*Storage) HasBlob

func (s *Storage) HasBlob(sha256Hash []byte) (exists bool, err error)

HasBlob checks if a blob exists.

func (*Storage) ListAllUserStats added in v0.36.21

func (s *Storage) ListAllUserStats() ([]*UserBlobStats, error)

ListAllUserStats returns storage statistics for all users who have uploaded blobs.

func (*Storage) ListBlobs

func (s *Storage) ListBlobs(pubkey []byte, since, until int64) ([]*BlobDescriptor, error)

ListBlobs lists all blobs for a given pubkey. Returns blob descriptors with time filtering.

func (*Storage) ListImageBlobs added in v0.58.17

func (s *Storage) ListImageBlobs() ([]*BlobDescriptor, error)

ListImageBlobs returns all image blobs that could have thumbnails generated.

func (*Storage) SaveBlob

func (s *Storage) SaveBlob(
	sha256Hash []byte, data []byte, pubkey []byte, mimeType string, extension string,
) error

SaveBlob stores a blob with its metadata. Delegates to the database interface's SaveBlob method.

func (*Storage) SaveReport

func (s *Storage) SaveReport(sha256Hash []byte, reportData []byte) error

SaveReport stores a report for a blob (BUD-09).

func (*Storage) SaveThumbnail added in v0.58.17

func (s *Storage) SaveThumbnail(key string, data []byte) error

SaveThumbnail caches a thumbnail with the given key.

type UserBlobStats added in v0.36.21

type UserBlobStats struct {
	PubkeyHex      string `json:"pubkey"`
	BlobCount      int64  `json:"blob_count"`
	TotalSizeBytes int64  `json:"total_size_bytes"`
}

UserBlobStats represents storage statistics for a single user. This mirrors database.UserBlobStats for API compatibility.

type VariantSpec added in v0.58.17

type VariantSpec struct {
	Width   int
	Quality int
}

VariantSpec defines the target width and JPEG quality for a variant

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL