server

package
v0.0.4-0...-3ddfab5 Latest Latest
Warning

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

Go to latest
Published: Feb 13, 2026 License: MIT Imports: 44 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrNotFound        = errors.New("Not found")
	ErrPathOutsideRoot = errors.New("Path not in space")
	ErrCouldNotWrite   = errors.New("Could not write file")
	ErrCouldNotGetMeta = errors.New("Could not get file metadata")
)

Common errors

View Source
var NotAllowedError = errors.New("Not allowed")

Functions

func DecodeURLParam

func DecodeURLParam(r *http.Request, name string) string

func LookupContentTypeFromPath

func LookupContentTypeFromPath(path string) string

lookupContentTypeFromPath determines MIME type based on file extension

func ParseVersionFromTypeScript

func ParseVersionFromTypeScript(code string) (string, error)

func Router

func Router(config *ServerConfig) chi.Router

func RunServer

func RunServer(config *ServerConfig) error

func ServerSideRender

func ServerSideRender(config *ServerConfig, spaceConfig *SpaceConfig, pageName string, w http.ResponseWriter, r *http.Request)

func TestSpacePrimitives

func TestSpacePrimitives(t *testing.T, spacePrimitives SpacePrimitives)

TestSpacePrimitives runs a comprehensive test suite against any SpacePrimitives implementation

Types

type AuthOptions

type AuthOptions struct {
	AuthToken       string `json:"authToken,omitempty"`
	User            string `json:"user"`
	Pass            string `json:"pass"`
	LockoutTime     int    `json:"lockoutTime"` // in seconds
	LockoutLimit    int    `json:"lockoutLimit"`
	RememberMeHours int    `json:"rememberMeHours"` // duration for "remember me" sessions
}

Auth options for user authentication

type Authenticator

type Authenticator struct {
	SecretKey string `json:"secret_key"`
	AuthHash  string `json:"auth_hash"`
	Salt      string `json:"salt"` // base64 encoded 16 byte randomized salt used for encryption
	// contains filtered or unexported fields
}

Authenticator handles JWT creation and verification

func CreateAuthenticator

func CreateAuthenticator(path string, authOptions *AuthOptions) (*Authenticator, error)

func (*Authenticator) CreateJWT

func (j *Authenticator) CreateJWT(payload map[string]any, expirySeconds ...int) (string, error)

CreateJWT creates a new JWT token with the given payload

func (*Authenticator) VerifyAndDecodeJWT

func (j *Authenticator) VerifyAndDecodeJWT(tokenString string) (map[string]any, error)

VerifyAndDecodeJWT verifies and decodes a JWT token

type BootConfig

type BootConfig struct {
	SpaceFolderPath string `json:"spaceFolderPath"`
	IndexPage       string `json:"indexPage"`
	ReadOnly        bool   `json:"readOnly"`

	// Whether or not the client should push logs to the server
	LogPush bool `json:"logPush"`

	// Encryption
	EnableClientEncryption bool `json:"enableClientEncryption"`
}

BootConfig represents the client configuration

type ConfigResolver

type ConfigResolver func(r *http.Request) (*SpaceConfig, error)

type CookieOptions

type CookieOptions struct {
	Path     string
	Expires  time.Time
	HttpOnly bool
	Secure   bool
	SameSite string
}

CookieOptions represents cookie configuration options

type DiskSpacePrimitives

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

DiskSpacePrimitives implements SpacePrimitives for local disk storage

func NewDiskSpacePrimitives

func NewDiskSpacePrimitives(rootPath string, gitIgnore string) (*DiskSpacePrimitives, error)

NewDiskSpacePrimitives creates a new DiskSpacePrimitives instance

func (*DiskSpacePrimitives) DeleteFile

func (d *DiskSpacePrimitives) DeleteFile(path string) error

DeleteFile implements SpacePrimitives.DeleteFile

func (*DiskSpacePrimitives) FetchFileList

func (d *DiskSpacePrimitives) FetchFileList() ([]FileMeta, error)

FetchFileList implements SpacePrimitives.FetchFileList Returns a list of files in the space, with the following filtering rules: - Hidden files and directories (starting with '.') are excluded at any depth - Files without extensions are excluded - Files matching gitignore patterns are excluded

func (*DiskSpacePrimitives) GetFileMeta

func (d *DiskSpacePrimitives) GetFileMeta(path string) (FileMeta, error)

GetFileMeta implements SpacePrimitives.GetFileMeta

func (*DiskSpacePrimitives) ReadFile

func (d *DiskSpacePrimitives) ReadFile(path string) ([]byte, FileMeta, error)

ReadFile implements SpacePrimitives.ReadFile

func (*DiskSpacePrimitives) WriteFile

func (d *DiskSpacePrimitives) WriteFile(path string, data []byte, meta *FileMeta) (FileMeta, error)

WriteFile implements SpacePrimitives.WriteFile

type FileMeta

type FileMeta struct {
	Name         string `json:"name"`
	Created      int64  `json:"created"`
	LastModified int64  `json:"lastModified"`
	ContentType  string `json:"contentType"`
	Size         int64  `json:"size"`
	Perm         string `json:"perm"` // "ro" or "rw"
}

FileMeta represents metadata for a file in the space

type LocalShell

type LocalShell struct {
	Cwd          string
	CmdWhiteList []string
	AllowAllCmds bool
}

LocalShell implements shell execution on the local system

func NewLocalShell

func NewLocalShell(cwd string, cmdWhiteList string) *LocalShell

NewLocalShell creates a new LocalShell instance

func (*LocalShell) Handle

func (ls *LocalShell) Handle(request ShellRequest) (ShellResponse, error)

Handle executes a shell command and returns the result

type LockoutTimer

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

LockoutTimer implements a simple rate limiter to prevent brute force attacks

func NewLockoutTimer

func NewLockoutTimer(countPeriodMs int, limit int) *LockoutTimer

NewLockoutTimer creates a new lockout timer countPeriodMs: time window in milliseconds limit: maximum attempts allowed in the time window

func (*LockoutTimer) AddCount

func (lt *LockoutTimer) AddCount()

AddCount increments the attempt counter IsLocked() should be called first to keep bucketTime current

func (*LockoutTimer) IsLocked

func (lt *LockoutTimer) IsLocked() bool

IsLocked checks if the timer is currently locked due to too many attempts

type LogEntry

type LogEntry struct {
	Source    string `json:"source"`
	Level     string `json:"level"`
	Message   string `json:"message"`
	Timestamp int64  `json:"timestamp"`
}

type Manifest

type Manifest struct {
	ShortName       string         `json:"short_name"`
	Name            string         `json:"name"`
	Icons           []ManifestIcon `json:"icons"`
	CaptureLinks    string         `json:"capture_links"`
	StartURL        string         `json:"start_url"`
	Display         string         `json:"display"`
	DisplayOverride []string       `json:"display_override"`
	Scope           string         `json:"scope"`
	ThemeColor      string         `json:"theme_color"`
	Description     string         `json:"description"`
}

Manifest represents the structure of a PWA manifest.json file

type ManifestIcon

type ManifestIcon struct {
	Src   string `json:"src"`
	Type  string `json:"type"`
	Sizes string `json:"sizes"`
}

ManifestIcon represents an icon in the PWA manifest

type NotSupportedShell

type NotSupportedShell struct{}

NotSupportedShell implements a shell backend that doesn't support execution

func NewNotSupportedShell

func NewNotSupportedShell() *NotSupportedShell

NewNotSupportedShell creates a new NotSupportedShell instance

func (*NotSupportedShell) Handle

func (nss *NotSupportedShell) Handle(request ShellRequest) (ShellResponse, error)

Handle always returns a "not supported" error

type ReadOnlyFallthroughSpacePrimitives

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

Implements a simple read-only fallthrough implementation of SpacePrimitives, used to serve static files embedde in the Go binary

func NewReadOnlyFallthroughSpacePrimitives

func NewReadOnlyFallthroughSpacePrimitives(fsys fs.FS, rootPath string, timeStamp time.Time, wrapped SpacePrimitives) *ReadOnlyFallthroughSpacePrimitives

func (*ReadOnlyFallthroughSpacePrimitives) DeleteFile

func (e *ReadOnlyFallthroughSpacePrimitives) DeleteFile(path string) error

DeleteFile implements SpacePrimitives.DeleteFile Fails if file exists in filesystem, otherwise delegates to fallback

func (*ReadOnlyFallthroughSpacePrimitives) FetchFileList

func (e *ReadOnlyFallthroughSpacePrimitives) FetchFileList() ([]FileMeta, error)

FetchFileList implements SpacePrimitives.FetchFileList Lists all files from the filesystem first, then combines files from the fallback.

func (*ReadOnlyFallthroughSpacePrimitives) GetFileMeta

func (e *ReadOnlyFallthroughSpacePrimitives) GetFileMeta(path string) (FileMeta, error)

GetFileMeta implements SpacePrimitives.GetFileMeta

func (*ReadOnlyFallthroughSpacePrimitives) ReadFile

ReadFile implements SpacePrimitives.ReadFile

func (*ReadOnlyFallthroughSpacePrimitives) WriteFile

func (e *ReadOnlyFallthroughSpacePrimitives) WriteFile(path string, data []byte, meta *FileMeta) (FileMeta, error)

WriteFile implements SpacePrimitives.WriteFile Fails if file exists in filesystem, otherwise delegates to fallback

type ReadOnlySpacePrimitives

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

func NewReadOnlySpacePrimitives

func NewReadOnlySpacePrimitives(wrapped SpacePrimitives) *ReadOnlySpacePrimitives

func (*ReadOnlySpacePrimitives) DeleteFile

func (ro *ReadOnlySpacePrimitives) DeleteFile(path string) error

DeleteFile returns an error since this is a read-only implementation

func (*ReadOnlySpacePrimitives) FetchFileList

func (ro *ReadOnlySpacePrimitives) FetchFileList() ([]FileMeta, error)

FetchFileList retrieves a list of all files in the space

func (*ReadOnlySpacePrimitives) GetFileMeta

func (ro *ReadOnlySpacePrimitives) GetFileMeta(path string) (FileMeta, error)

GetFileMeta retrieves metadata for a specific file

func (*ReadOnlySpacePrimitives) ReadFile

func (ro *ReadOnlySpacePrimitives) ReadFile(path string) ([]byte, FileMeta, error)

ReadFile reads a file and returns its data and metadata

func (*ReadOnlySpacePrimitives) WriteFile

func (ro *ReadOnlySpacePrimitives) WriteFile(path string, data []byte, meta *FileMeta) (FileMeta, error)

WriteFile returns an error since this is a read-only implementation

type ServerConfig

type ServerConfig struct {
	SpaceConfigResolver ConfigResolver

	BindHost          string
	Port              int
	MetricsPort       int
	EnableHTTPLogging bool
	// TODO: Ideally this is configurable per space, but kinda hard
	HostURLPrefix string

	ClientBundle SpacePrimitives
}

type ShellBackend

type ShellBackend interface {
	Handle(request ShellRequest) (ShellResponse, error)
}

Shell backend interface

type ShellRequest

type ShellRequest struct {
	Cmd   string   `json:"cmd"`
	Args  []string `json:"args"`
	Stdin *string  `json:"stdin,omitempty"`
}

Shell request/response types

type ShellResponse

type ShellResponse struct {
	Stdout string `json:"stdout"`
	Stderr string `json:"stderr"`
	Code   int    `json:"code"`
}

type SpaceConfig

type SpaceConfig struct {
	Hostname string
	Auth     *AuthOptions

	Authorize UserPasswordAuthorizer

	SpacePrimitives SpacePrimitives

	SpaceFolderPath string
	IndexPage       string
	GitIgnore       string
	ReadOnlyMode    bool
	LogPush         bool

	// Used for the PWA manifest and login page
	SpaceName        string
	SpaceDescription string

	// Used to inject additional HTML into the <head> of index.html
	AdditionalHeadHTML template.HTML

	// Shell configuration
	ShellBackend ShellBackend

	// Auth temporary objects
	JwtIssuer    *Authenticator
	LockoutTimer *LockoutTimer
	// contains filtered or unexported fields
}

func (*SpaceConfig) InitAuth

func (spaceConfig *SpaceConfig) InitAuth() error

type SpacePrimitives

type SpacePrimitives interface {
	// FetchFileList retrieves a list of all files in the space
	FetchFileList() ([]FileMeta, error)

	// GetFileMeta retrieves metadata for a specific file
	GetFileMeta(path string) (FileMeta, error)

	// ReadFile reads a file and returns its data and metadata
	ReadFile(path string) ([]byte, FileMeta, error)

	// WriteFile writes data to a file with optional metadata
	// Returns the actual metadata of the written file
	WriteFile(path string, data []byte, meta *FileMeta) (FileMeta, error)

	// DeleteFile removes a file from the space
	DeleteFile(path string) error
}

SpacePrimitives defines the interface for storage backends

type UserPasswordAuthorizer

type UserPasswordAuthorizer func(username, password string) bool

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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