internal

package
v0.0.0-...-56ecfe3 Latest Latest
Warning

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

Go to latest
Published: Dec 24, 2024 License: MIT Imports: 39 Imported by: 0

Documentation

Overview

Package internal contains internal implementation details

Index

Constants

View Source
const (

	// InvalidConfigValue is the constant value for invalid config values
	// which must be changed for production configurations before successful
	// startup
	InvalidConfigValue = "INVALID CONFIG VALUE - PLEASE CHANGE THIS VALUE"

	// DefaultDebug is the default debug mode
	DefaultDebug = false

	// DefaultTLS is the default for whether to enable TLS
	DefaultTLS = false

	// DefaultTLSKey is the default path to a TLS private key (if blank uses Let's Encrypt)
	DefaultTLSKey = ""

	// DefaultTLSCert is the default path to a TLS certificate (if blank uses Let's Encrypt)
	DefaultTLSCert = ""

	// DefaultData is the default data directory for storage
	DefaultData = "./data"

	// DefaultStore is the default data store used for accounts, sessions, etc
	DefaultStore = "bitcask://data/saltyim.db"

	// DefaultBaseURL is the default Base URL for the server
	DefaultBaseURL = "https://salty." + DefaultPrimaryDomain

	// DefaultPrimaryDomain is the default primary domain delegated to this broker
	DefaultPrimaryDomain = "home.arpa"

	// DefaultAdminUser is the default publickye to grant admin privileges to
	DefaultAdminUser = ""

	// DefaultSupportEmail is the default email of the admin user used in support requests
	DefaultSupportEmail = "support@" + DefaultPrimaryDomain
)

Variables

View Source
var (
	// Jobs and StartupJobs are initialized with default jobs.
	Jobs map[string]JobSpec

	// StartupJobs is initialized empty, but may be populated with jobs
	// by other packages in the future.
	StartupJobs map[string]JobSpec
)
View Source
var (
	// ErrInvalidStore is returned if the StoreURI is invalid
	// or if the Store cannot be created
	ErrInvalidStore = errors.New("error: invalid store")

	// ErrPollNotFound is returned if the poll does not exist
	ErrPollNotFound = errors.New("error: poll not found")
)
View Source
var (
	// ErrAddressExists is returned if the address already exists
	ErrAddressExists = errors.New("error: address already exists")

	// ErrBlobNotFound is returned if the blob does not exist
	ErrBlobNotFound = errors.New("error: blob not found")
)

Functions

func CreateConfig

func CreateConfig(conf *Config, hash string, key string) error

CreateConfig creates a new config file for the given user hash and public key. The config file is written to the .well-known/salty directory. The config file is in JSON format and contains the endpoint URL and the public key. If the config file already exists, ErrAddressExists is returned. If there is an error writing the file, an error is returned.

func CreateOrUpdateAvatar

func CreateOrUpdateAvatar(conf *Config, addr saltyim.Addr, contents []byte) error

CreateOrUpdateAvatar writes the given avatar image to a file on disk in the given directory. The Addr.Hash() is used as the filename for the avatar. If the avatar already exists, it is overwritten.

Returns an error if writing the avatar fails.

func CreateOrUpdateBlob

func CreateOrUpdateBlob(conf *Config, key string, data []byte, signer string) error

CreateOrUpdateBlob writes the given data to a blob on disk in the given directory. The key is used as the filename for the blob. If the blob already exists, it is overwritten.

The signer parameter is used to select the directory where the blob is stored. This is used to ensure that a blob is only accessible by the owner of the blob.

Returns an error if writing the blob fails.

func DeleteBlob

func DeleteBlob(conf *Config, key string, signer string) error

DeleteBlob deletes a blob from the data directory based on the given key and the signer public key.

If the blob does not exist, an ErrBlobNotFound error is returned.

func FileExists

func FileExists(name string) bool

FileExists returns true if the given file exists

func GenerateAvatar

func GenerateAvatar(conf *Config, domainNick string) (image.Image, error)

GenerateAvatar generates a unique avatar for a user based on an identicon

func GenerateRandomToken

func GenerateRandomToken() string

GenerateRandomToken generates random tokens used primarily for recovery

func GetBlob

func GetBlob(conf *Config, key string, signer string) (*saltyim.Blob, error)

GetBlob reads a blob from disk and returns a *saltyim.Blob object on success otherwise an error is returned.

If the blob does not exist, an ErrBlobNotFound error is returned.

func InitJobs

func InitJobs(_ *Config)

InitJobs initializes the Jobs and StartupJobs maps with default jobs.

The Jobs map contains jobs that are run on a schedule, and the StartupJobs map contains jobs that are run once during server startup.

The Jobs map is initialized with a single job, "SyncStore", which syncs the data store every 1 minute.

The StartupJobs map is initialized empty, but may be populated with jobs by other packages in the future.

func IsImage

func IsImage(data []byte) bool

IsImage returns true if the bytes are an image

func NewSyncStoreJob

func NewSyncStoreJob(conf *Config, db Store) cron.Job

NewSyncStoreJob returns a new SyncStoreJob, which is a cron.Job that syncs the data store every time it is run.

The returned cron.Job will use the given config and store to sync the data store when it is run.

func NewTestUser

func NewTestUser(addr, _ string, t *testing.T) *saltyim.Client

NewTestUser returns a new Salty IM client for a given address, suitable for use in tests. The second argument is ignored.

func ProcessImage

func ProcessImage(r io.Reader, opts *ImageOptions) (image.Image, error)

ProcessImage processes an image and resizes the image according to the image options provided and returns a new image for storage or to be served

func SaveAvatar

func SaveAvatar(fn string, r io.Reader, size int) error

SaveAvatar saves a processed avatar image to a file at the given path. The image is resized to the given size.

Types

type API

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

API ...

func NewAPI

func NewAPI(router *Router, config *Config, db Store) *API

NewAPI ...

func (*API) AvatarEndpoint

func (a *API) AvatarEndpoint() httprouter.Handle

AvatarEndpoint ...

func (*API) BlobEndpoint

func (a *API) BlobEndpoint() httprouter.Handle

BlobEndpoint ...

func (*API) LookupEndpoint

func (a *API) LookupEndpoint() httprouter.Handle

LookupEndpoint ...

func (*API) PingEndpoint

func (a *API) PingEndpoint() httprouter.Handle

PingEndpoint ...

func (*API) RegisterEndpoint

func (a *API) RegisterEndpoint() httprouter.Handle

RegisterEndpoint ...

func (*API) SendEndpoint

func (a *API) SendEndpoint() httprouter.Handle

SendEndpoint ...

func (*API) WhoamiEndpoint

func (a *API) WhoamiEndpoint() httprouter.Handle

WhoamiEndpoint ...

type Config

type Config struct {
	Debug bool

	TLS     bool   `json:"-"`
	TLSKey  string `json:"-"`
	TLSCert string `json:"-"`

	Data  string `json:"-"`
	Store string `json:"-"`

	BaseURL       string
	BrokerURI     string
	PrimaryDomain string

	AdminUser    string `json:"-"`
	SupportEmail string `json:"-"`
	// contains filtered or unexported fields
}

Config contains the server configuration parameters

func NewConfig

func NewConfig() *Config

NewConfig returns a new Config with all the default values set.

func (*Config) Validate

func (c *Config) Validate() error

Validate validates the configuration is valid which for the most part just ensures that default secrets are actually configured correctly

type ImageOptions

type ImageOptions struct {
	Resize bool
	Width  int
	Height int
}

ImageOptions set options for handling image resizing

type JobFactory

type JobFactory func(conf *Config, store Store) cron.Job

JobFactory is a function that returns a cron.Job.

type JobSpec

type JobSpec struct {
	Schedule string
	Factory  JobFactory
}

JobSpec ...

func NewJobSpec

func NewJobSpec(schedule string, factory JobFactory) JobSpec

NewJobSpec returns a new JobSpec with the given schedule and factory.

The schedule is a cron expression (e.g. "@every 1m", "@hourly", "@daily", etc.), and the factory is a function that returns a cron.Job that will be run on the given schedule.

type Middleware

type Middleware func(httprouter.Handle) httprouter.Handle

Middleware ...

type Option

type Option func(*Config) error

Option is a function that takes a config struct and modifies it

func WithAdminUser

func WithAdminUser(adminUser string) Option

WithAdminUser sets the Admin user used for granting special features to

func WithBaseURL

func WithBaseURL(baseURL string) Option

WithBaseURL sets the Base URL used for constructing feed URLs

func WithData

func WithData(data string) Option

WithData sets the data directory to use for storage

func WithDebug

func WithDebug(debug bool) Option

WithDebug sets the debug mode lfag

func WithPrimaryDomain

func WithPrimaryDomain(primaryDomain string) Option

WithPrimaryDomain sets the Primary Domain this broker is delegated for

func WithStore

func WithStore(store string) Option

WithStore sets the store to use for accounts, sessions, etc.

func WithSupportEmail

func WithSupportEmail(supportEmail string) Option

WithSupportEmail sets the Support email used to contact the operator of this broker

func WithTLS

func WithTLS(tls bool) Option

WithTLS sets the tls flag

func WithTLSCert

func WithTLSCert(tlsCert string) Option

WithTLSCert sets the path to a TLS certificate

func WithTLSKey

func WithTLSKey(tlsKey string) Option

WithTLSKey sets the path to a TLS private key

type Router

type Router struct {
	httprouter.Router
	// contains filtered or unexported fields
}

Router ...

func NewRouter

func NewRouter() *Router

NewRouter ...

func (*Router) DELETE

func (r *Router) DELETE(path string, handle httprouter.Handle)

DELETE is a shortcut for Router.Handle("DELETE", path, handle)

func (*Router) File

func (r *Router) File(path, name string)

File serves the named file.

func (*Router) GET

func (r *Router) GET(path string, handle httprouter.Handle)

GET is a shortcut for Router.Handle("GET", path, handle)

func (*Router) Group

func (r *Router) Group(path string, m ...Middleware) *Router

Group returns new *Router with given path and middlewares. It should be used for handles which have same path prefix or common middlewares.

func (*Router) HEAD

func (r *Router) HEAD(path string, handle httprouter.Handle)

HEAD is a shortcut for Router.Handle("HEAD", path, handle)

func (*Router) Handle

func (r *Router) Handle(method, path string, handle httprouter.Handle)

Handle registers a new request handle combined with middlewares.

func (*Router) Handler

func (r *Router) Handler(method, path string, handler http.Handler)

Handler is an adapter for http.Handler.

func (*Router) HandlerFunc

func (r *Router) HandlerFunc(method, path string, handler http.HandlerFunc)

HandlerFunc is an adapter for http.HandlerFunc.

func (*Router) OPTIONS

func (r *Router) OPTIONS(path string, handle httprouter.Handle)

OPTIONS is a shortcut for Router.Handle("OPTIONS", path, handle)

func (*Router) PATCH

func (r *Router) PATCH(path string, handle httprouter.Handle)

PATCH is a shortcut for Router.Handle("PATCH", path, handle)

func (*Router) POST

func (r *Router) POST(path string, handle httprouter.Handle)

POST is a shortcut for Router.Handle("POST", path, handle)

func (*Router) PUT

func (r *Router) PUT(path string, handle httprouter.Handle)

PUT is a shortcut for Router.Handle("PUT", path, handle)

func (*Router) ServeFilesWithCacheControl

func (r *Router) ServeFilesWithCacheControl(path string, root fs.FS)

ServeFilesWithCacheControl ...

func (*Router) ServeHTTP

func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request)

func (*Router) Static

func (r *Router) Static(path, root string)

Static serves files from given root directory.

func (*Router) Use

func (r *Router) Use(m ...Middleware) *Router

Use appends new middleware to current Router.

type Server

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

Server ...

func NewServer

func NewServer(bind string, options ...Option) (*Server, error)

NewServer ...

func (*Server) AddCronJob

func (s *Server) AddCronJob(spec string, job cron.Job) error

AddCronJob ...

func (*Server) AddRoute

func (s *Server) AddRoute(method, path string, handler http.Handler)

AddRoute ...

func (*Server) AddShutdownHook

func (s *Server) AddShutdownHook(f func())

AddShutdownHook ...

func (*Server) AvatarHandler

func (s *Server) AvatarHandler() httprouter.Handle

AvatarHandler ...

func (*Server) ConfigHandler

func (s *Server) ConfigHandler() httprouter.Handle

ConfigHandler ...

func (*Server) IndexHandler

func (s *Server) IndexHandler() httprouter.Handle

IndexHandler ...

func (*Server) ListenAndServe

func (s *Server) ListenAndServe() error

ListenAndServe ...

func (*Server) NotFoundHandler

func (s *Server) NotFoundHandler(w http.ResponseWriter, r *http.Request)

NotFoundHandler is the default handler for requests that do not match any other registered route. It returns a 404 status code and a JSON or plain text response with the message "Endpoint Not Found".

func (*Server) Run

func (s *Server) Run(ctx context.Context) (err error)

Run ...

func (*Server) Shutdown

func (s *Server) Shutdown(ctx context.Context) error

Shutdown ...

type Store

type Store interface {
	Merge() error
	Close() error
	Sync() error
}

Store is an interface for a persistent storage backend.

func NewStore

func NewStore(store string) (Store, error)

NewStore creates a new Store based on the given URI string.

Currently supported Stores are:

- "bitcask://path/to/file.db" - "memory://"

Returns an error if the URI is invalid or if the Store cannot be created.

type StoreURI

type StoreURI struct {
	Type string
	Path string
}

StoreURI is a URI string in the form of "<type>://<path>".

func ParseStoreURI

func ParseStoreURI(uri string) (*StoreURI, error)

ParseStoreURI takes a URI string in the form of "<type>://<path>" and parses it into a StoreURI.

func (StoreURI) IsZero

func (u StoreURI) IsZero() bool

IsZero returns true if the StoreURI is empty and has no type or path.

func (StoreURI) String

func (u StoreURI) String() string

type SyncStoreJob

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

SyncStoreJob is a cron.Job that syncs the data store every time it is run.

func (*SyncStoreJob) Run

func (job *SyncStoreJob) Run()

Run runs the SyncStoreJob, syncing the data store.

The job logs a warning if there is an error syncing the store, and logs an info message when the store is successfully synced.

Directories

Path Synopsis
Package app implements a terminal user interface (tui)
Package app implements a terminal user interface (tui)
Package authreq signa and verifies HTTP requests using Ed25519 private/public keys
Package authreq signa and verifies HTTP requests using Ed25519 private/public keys

Jump to

Keyboard shortcuts

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