handlers

package
v0.0.0-...-8f4f983 Latest Latest
Warning

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

Go to latest
Published: May 8, 2026 License: AGPL-3.0 Imports: 38 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var Echo *echo.Echo

Echo is the global echo instance used for routing

Functions

func AdminAlertsSummary

func AdminAlertsSummary(c echo.Context) error

AdminAlertsSummary handles GET /api/admin/alerts/summary Returns storage health warnings for the admin CLI login alert display.

func AdminBillingGift

func AdminBillingGift(c echo.Context) error

AdminBillingGift adds positive microcent credit to a user's balance and writes a typed 'gift' transaction. Replaces the old POST /api/admin/credits endpoint (deleted in Section B+C); this is the only path for any admin- initiated positive balance adjustment.

POST /api/admin/billing/gift Body: { "target_username": "...", "amount_usd": "5.00", "reason": "..." }

func AdminBillingTickNow

func AdminBillingTickNow(c echo.Context) error

AdminBillingTickNow forces an immediate tick (and optional sweep) of every active billable user. Intended for the e2e billing test in scripts/testing/e2e-test.sh; gated to ADMIN_DEV_TEST_API_ENABLED so it is physically not registered as a route in production-flavored deployments (see route_config.go for the gating).

POST /api/admin/billing/tick-now Body: { "sweep": false }

func AdminCancelTask

func AdminCancelTask(c echo.Context) error

AdminCancelTask handles POST /api/admin/storage/cancel-task/:taskId

func AdminCleanupTestUser

func AdminCleanupTestUser(c echo.Context) error

AdminCleanupTestUser performs comprehensive cleanup of test user data

func AdminContactsHandler

func AdminContactsHandler(c echo.Context) error

AdminContactsHandler returns admin contact information for user support

func AdminCopyAll

func AdminCopyAll(c echo.Context) error

AdminCopyAll handles POST /api/admin/storage/copy-all

func AdminCopyFile

func AdminCopyFile(c echo.Context) error

AdminCopyFile handles POST /api/admin/storage/copy-file

func AdminCopyUserFiles

func AdminCopyUserFiles(c echo.Context) error

AdminCopyUserFiles handles POST /api/admin/storage/copy-user-files

func AdminDeleteFile

func AdminDeleteFile(c echo.Context) error

AdminDeleteFile deletes a specific file by file_id (from storage + DB)

func AdminExportFile

func AdminExportFile(c echo.Context) error

AdminExportFile handles GET /api/admin/files/:fileId/export Streams a .arkbackup bundle for any user's file (admin only). Authentication: JWT + Admin middleware

func AdminForceLogout

func AdminForceLogout(c echo.Context) error

AdminForceLogout allows admin to force-logout a specific user (admin-only endpoint)

func AdminGetAllCredits

func AdminGetAllCredits(c echo.Context) error

AdminGetAllCredits returns the credit balances for every user, plus a per-user current_usage block and aggregate totals. Requires admin privileges. Negative balances are rendered with a leading "-".

func AdminGetBillingOverdrawn

func AdminGetBillingOverdrawn(c echo.Context) error

AdminGetBillingOverdrawn lists every user with a negative balance.

GET /api/admin/billing/overdrawn

func AdminGetBillingPrice

func AdminGetBillingPrice(c echo.Context) error

AdminGetBillingPrice returns the current customer price and the derived internal rate. Read-only; safe for any admin to call.

GET /api/admin/billing/price

func AdminGetBillingSweepSummary

func AdminGetBillingSweepSummary(c echo.Context) error

AdminGetBillingSweepSummary returns per-day aggregates of recent 'usage' transactions plus a point-in-time count of users currently in the negative. Used by the operator UI to spot trends.

GET /api/admin/billing/sweep-summary?days=7

func AdminGetContactInfo

func AdminGetContactInfo(c echo.Context) error

AdminGetContactInfo handles GET /api/admin/users/:username/contact-info Returns contact information for any user (admin only).

func AdminGetUserCredits

func AdminGetUserCredits(c echo.Context) error

AdminGetUserCredits returns the credit information for a specific user. Requires admin privileges. Includes the current_usage and credits_runway blocks.

func AdminGetUserStatus

func AdminGetUserStatus(c echo.Context) error

AdminGetUserStatus returns comprehensive user status information

func AdminListUserFiles

func AdminListUserFiles(c echo.Context) error

AdminListUserFiles lists all files owned by a specific user

func AdminListUserShares

func AdminListUserShares(c echo.Context) error

AdminListUserShares lists all shares owned by a specific user

func AdminMiddleware

func AdminMiddleware(next echo.HandlerFunc) echo.HandlerFunc

AdminMiddleware enforces multi-layer security for admin endpoints

func AdminOpaqueAuthFinalize

func AdminOpaqueAuthFinalize(c echo.Context) error

AdminOpaqueAuthFinalize completes admin authentication

func AdminOpaqueAuthResponse

func AdminOpaqueAuthResponse(c echo.Context) error

AdminOpaqueAuthResponse handles server-side credential response creation for admin login

func AdminRevokeShare

func AdminRevokeShare(c echo.Context) error

AdminRevokeShare revokes a specific share by share_id

func AdminRevokeUser

func AdminRevokeUser(c echo.Context) error

AdminRevokeUser revokes a user's access by setting is_approved to false

func AdminSecurityEvents

func AdminSecurityEvents(c echo.Context) error

AdminSecurityEvents exposes existing security event logs via admin API. Supports query parameters for filtering:

  • type: filter by event type (e.g. "share_not_found", "opaque_login_failure")
  • severity: filter by severity ("INFO", "WARNING", "CRITICAL")
  • entity_id: filter by entity ID (HMAC-based, 16-char hex)
  • limit: max events to return (default 100, max 500)

func AdminSetBillingPrice

func AdminSetBillingPrice(c echo.Context) error

AdminSetBillingPrice updates the customer price and atomically swaps the cached billing rate. The next tick observes the new rate.

POST /api/admin/billing/set-price Body: { "customer_price_usd_per_tb_per_month": "19.99" }

func AdminSetCost

func AdminSetCost(c echo.Context) error

AdminSetCost handles POST /api/admin/storage/set-cost

func AdminSetPrimary

func AdminSetPrimary(c echo.Context) error

AdminSetPrimary handles POST /api/admin/storage/set-primary

func AdminSetSecondary

func AdminSetSecondary(c echo.Context) error

AdminSetSecondary handles POST /api/admin/storage/set-secondary

func AdminSetTertiary

func AdminSetTertiary(c echo.Context) error

AdminSetTertiary handles POST /api/admin/storage/set-tertiary

func AdminStorageStatus

func AdminStorageStatus(c echo.Context) error

AdminStorageStatus handles GET /api/admin/storage/status Returns configured providers, file counts, sync status, and cost info.

func AdminSwapProviders

func AdminSwapProviders(c echo.Context) error

AdminSwapProviders handles POST /api/admin/storage/swap-providers

func AdminSyncStatus

func AdminSyncStatus(c echo.Context) error

AdminSyncStatus handles GET /api/admin/storage/sync-status Returns detailed breakdown of file locations and replication gaps.

func AdminSystemHealth

func AdminSystemHealth(c echo.Context) error

AdminSystemHealth bridges existing monitoring infrastructure to admin API endpoints

func AdminSystemStatus

func AdminSystemStatus(c echo.Context) error

AdminSystemStatus returns system status overview including uptime, version, storage and user statistics

func AdminTOTPDecryptCheck

func AdminTOTPDecryptCheck(c echo.Context) error

AdminTOTPDecryptCheck provides TOTP diagnostic information for development

func AdminTaskStatus

func AdminTaskStatus(c echo.Context) error

AdminTaskStatus handles GET /api/admin/storage/task/:taskId

func AdminVerifyAll

func AdminVerifyAll(c echo.Context) error

AdminVerifyAll handles POST /api/admin/storage/verify-all Initiates a background task that performs HEAD requests against all active file_storage_locations to confirm S3 objects exist and sizes match.

func AdminVerifyStorage

func AdminVerifyStorage(c echo.Context) error

AdminVerifyStorage handles POST /api/admin/storage/verify-storage Runs a full S3 round-trip test (upload, download, hash verify, delete). If provider_id is specified in the JSON body, verifies that provider; otherwise defaults to the primary provider.

func ApproveUser

func ApproveUser(c echo.Context) error

ApproveUser approves a user and optionally updates their storage limit

func BootstrapRegisterFinalize

func BootstrapRegisterFinalize(c echo.Context) error

BootstrapRegisterFinalize completes the OPAQUE registration for the bootstrap admin.

func BootstrapRegisterResponse

func BootstrapRegisterResponse(c echo.Context) error

BootstrapRegisterResponse handles the first step of OPAQUE registration for the bootstrap admin.

func CSPMiddleware

func CSPMiddleware(next echo.HandlerFunc) echo.HandlerFunc

CSPMiddleware adds Content Security Policy headers with strict security

func CancelUpload

func CancelUpload(c echo.Context) error

CancelUpload aborts an in-progress upload session

func CompleteUpload

func CompleteUpload(c echo.Context) error

CompleteUpload finalizes a chunked upload

func CreateExportToken

func CreateExportToken(c echo.Context) error

CreateExportToken handles POST /api/files/:fileId/export-token Returns a short-lived JWT scoped to a single file export. Used by the browser frontend to trigger native downloads without memory buffering.

func CreateFileShare

func CreateFileShare(c echo.Context) error

CreateFileShare creates a new Argon2id-based anonymous file share

func CreateUploadSession

func CreateUploadSession(c echo.Context) error

CreateUploadSession initializes a new chunked upload

func DeleteContactInfo

func DeleteContactInfo(c echo.Context) error

DeleteContactInfo handles DELETE /api/user/contact-info Deletes the authenticated user's contact information.

func DeleteFile

func DeleteFile(c echo.Context) error

DeleteFile handles file deletion across all storage providers

func DeleteUser

func DeleteUser(c echo.Context) error

DeleteUser deletes a user and all associated data

func DownloadFileChunk

func DownloadFileChunk(c echo.Context) error

DownloadFileChunk streams a specific chunk of a file to the client GET /api/files/:fileId/chunks/:chunkIndex Returns the specified chunk (0-indexed) of the file

func DownloadShareChunk

func DownloadShareChunk(c echo.Context) error

DownloadShareChunk handles downloading a specific chunk of a shared file GET /api/shares/:id/chunks/:chunkIndex

func ExportFile

func ExportFile(c echo.Context) error

ExportFile handles GET /api/files/:fileId/export Streams a .arkbackup bundle for the authenticated user's own file. Authentication: JWT + TOTP (via totpProtectedGroup middleware) Also accepts ?token= query param for browser downloads (short-lived export token).

func FloodGuardMiddleware

func FloodGuardMiddleware(next echo.HandlerFunc) echo.HandlerFunc

FloodGuardMiddleware detects and rate-limits entities that generate excessive 401/404 responses (vulnerability scanners, path probers). It wraps the request handler: checking for active blocks before processing, and recording bad responses after processing.

func ForceRevokeAllTokens

func ForceRevokeAllTokens(c echo.Context) error

ForceRevokeAllTokens implements security-critical revocation for edge cases This function revokes BOTH refresh tokens AND active JWT tokens immediately Used for: OPAQUE credential re-registration, admin force-logout, security breaches

func GetArgon2Config

func GetArgon2Config(c echo.Context) error

GetArgon2Config returns the Argon2id parameters configuration from embedded data This ensures TypeScript and Go use the same parameters

func GetChunkingConfig

func GetChunkingConfig(c echo.Context) error

GetChunkingConfig returns the chunking parameters configuration from embedded data This ensures TypeScript and Go use the same chunk sizes, envelope format, and AES-GCM parameters

func GetContactInfo

func GetContactInfo(c echo.Context) error

GetContactInfo handles GET /api/user/contact-info Returns the authenticated user's own contact information.

func GetFileEnvelope

func GetFileEnvelope(c echo.Context) error

GetFileEnvelope returns the encrypted FEK and metadata for a file (for share creation)

func GetFileMeta

func GetFileMeta(c echo.Context) error

GetFileMeta returns encrypted file metadata needed for download initialization

func GetFileMetadataBatch

func GetFileMetadataBatch(c echo.Context) error

GetFileMetadataBatch returns lightweight encrypted metadata for an explicit batch of owner-owned file IDs.

func GetPasswordRequirements

func GetPasswordRequirements(c echo.Context) error

GetPasswordRequirements returns the password validation requirements from embedded data This ensures TypeScript and Go use the same validation rules

func GetPendingUsers

func GetPendingUsers(c echo.Context) error

GetPendingUsers returns a list of users pending approval

func GetShareDownloadMetadata

func GetShareDownloadMetadata(c echo.Context) error

GetShareDownloadMetadata returns metadata about a shared file's chunks for resumable downloads GET /api/shares/:id/metadata

func GetShareEnvelope

func GetShareEnvelope(c echo.Context) error

GetShareEnvelope returns the encrypted envelope and salt for a share. The server does NOT receive or process share passwords. Share key derivation (Argon2id) and envelope decryption happen entirely client-side.

func GetSharedFile

func GetSharedFile(c echo.Context) error

GetSharedFile renders the share access page

func GetUploadStatus

func GetUploadStatus(c echo.Context) error

GetUploadStatus returns the status of an upload session including which chunks have been uploaded

func GetUserCredits

func GetUserCredits(c echo.Context) error

GetUserCredits returns the current user's signed microcent balance, the transaction history, and -- once the billing meter is wired in (Section D) -- the current_usage and credits_runway blocks.

func GetVersion

func GetVersion(c echo.Context) error

GetVersion returns the current Arkfile application version

func InitTaskRunner

func InitTaskRunner(maxWorkers int)

InitTaskRunner creates the global task runner. Called from main.go on startup.

func InitializeRateLimitManager

func InitializeRateLimitManager(rateLimitConfig config.RateLimitConfig) error

InitializeRateLimitManager initializes the global rate limit manager

func JSONError

func JSONError(c echo.Context, status int, message string) error

JSONError sends a standard JSON error response

func JSONResponse

func JSONResponse(c echo.Context, status int, message string, data interface{}) error

JSONResponse sends a standard JSON response

func ListFiles

func ListFiles(c echo.Context) error

ListFiles returns a list of files owned by the user with encrypted metadata

func ListRecentFileMetadata

func ListRecentFileMetadata(c echo.Context) error

ListRecentFileMetadata returns a paginated recent metadata listing for the authenticated owner. This endpoint is intended for owner-side local metadata decryption workflows and does not expose FEKs or chunk/download details.

func ListShares

func ListShares(c echo.Context) error

ListShares returns all shares created by a user

func ListUsers

func ListUsers(c echo.Context) error

ListUsers returns a list of all users

func LogAdminAction

func LogAdminAction(db interface {
	Exec(string, ...interface{}) (sql.Result, error)
}, adminUsername, action, targetUsername, details string) error

LogAdminAction logs an admin action to the admin_logs table

func LoginRateLimitMiddleware

func LoginRateLimitMiddleware(next echo.HandlerFunc) echo.HandlerFunc

LoginRateLimitMiddleware provides rate limiting for login endpoints

func Logout

func Logout(c echo.Context) error

Logout handles user logout

func NotifyShareNotFound

func NotifyShareNotFound(entityID, shareIDPrefix string)

NotifyShareNotFound should be called by share handlers when a share ID returns 404. It records the hit in the enumeration guard and applies progressive penalties. The share handler should call this AFTER logging the EventShareNotFound security event.

func OpaqueAuthFinalize

func OpaqueAuthFinalize(c echo.Context) error

OpaqueAuthFinalize completes user authentication

func OpaqueAuthResponse

func OpaqueAuthResponse(c echo.Context) error

OpaqueAuthResponse handles server-side credential response creation

func OpaqueHealthCheck

func OpaqueHealthCheck(c echo.Context) error

OpaqueHealthCheck verifies that the OPAQUE system is functioning properly

func OpaqueRegisterFinalize

func OpaqueRegisterFinalize(c echo.Context) error

OpaqueRegisterFinalize completes user registration

func OpaqueRegisterResponse

func OpaqueRegisterResponse(c echo.Context) error

OpaqueRegisterResponse handles server-side registration response creation

func PrivacyRequestLogger

func PrivacyRequestLogger(next echo.HandlerFunc) echo.HandlerFunc

PrivacyRequestLogger is an Echo middleware that logs HTTP requests without exposing raw IP addresses. It uses the entity ID system to replace the client IP with a privacy-preserving HMAC-based identifier.

func PutContactInfo

func PutContactInfo(c echo.Context) error

PutContactInfo handles PUT /api/user/contact-info Creates or updates the authenticated user's contact information.

func RateLimitMiddleware

func RateLimitMiddleware(endpointConfig config.EndpointConfig) echo.MiddlewareFunc

RateLimitMiddleware creates rate limiting middleware for specific endpoints

func RateLimitShareAccess

func RateLimitShareAccess(shareID string, c echo.Context, accessFunc func() error) error

RateLimitShareAccess wraps share access functions with rate limiting logic

func RefreshToken

func RefreshToken(c echo.Context) error

RefreshToken handles refresh token requests

func RegisterRateLimitMiddleware

func RegisterRateLimitMiddleware(next echo.HandlerFunc) echo.HandlerFunc

RegisterRateLimitMiddleware provides rate limiting for registration endpoints

func RegisterRoutes

func RegisterRoutes()

RegisterRoutes initializes all routes for the application

func RequireAdmin

func RequireAdmin(next echo.HandlerFunc) echo.HandlerFunc

RequireAdmin ensures the user has admin privileges before allowing access

func RequireApproved

func RequireApproved(next echo.HandlerFunc) echo.HandlerFunc

RequireApproved ensures the user is approved before allowing access. Applied to auth.Echo so all routes in that group inherit it. Contact-info endpoints are intentionally placed in a separate group (pendingAllowedGroup in route_config.go) that omits this middleware, allowing pending users to manage their contact information.

func RequireTOTP

func RequireTOTP(next echo.HandlerFunc) echo.HandlerFunc

RequireTOTP ensures the user has TOTP enabled before allowing access to protected resources. Note: /api/totp/setup and /api/totp/verify are on a separate route group using TOTPJWTMiddleware and never reach this middleware, so no path-based bypass is needed here.

func RevokeAllRefreshTokens

func RevokeAllRefreshTokens(c echo.Context) error

RevokeAllRefreshTokens revokes all refresh tokens for the current user Note: This does NOT revoke active JWT tokens - they will expire automatically within 30 minutes

func RevokeShare

func RevokeShare(c echo.Context) error

RevokeShare revokes a share

func RevokeToken

func RevokeToken(c echo.Context) error

RevokeToken revokes a specific JWT token

func ServeRateLimitPage

func ServeRateLimitPage(c echo.Context, retryAfter int, message string) error

ServeRateLimitPage returns the 429 error page with appropriate format (HTML for browsers, JSON for API clients)

func SetBillingGiftFunc

func SetBillingGiftFunc(fn func(db *sql.DB, username string, amountUSDMicrocents int64, reason, adminUsername string) (*models.CreditTransaction, error))

SetBillingGiftFunc wires the billing.GiftCredits call.

func SetBillingProjectionSeams

func SetBillingProjectionSeams(
	freeBaseline func() int64,
	resolveRate func(db *sql.DB) (int64, string, bool),
)

SetBillingProjectionSeams wires the projection helpers to the live billing package. Called once from main.go during startup.

func SetBillingSetPriceFunc

func SetBillingSetPriceFunc(fn func(db *sql.DB, priceStr, updatedBy string) (int64, string, error))

SetBillingSetPriceFunc wires the billing.SetCustomerPrice call.

func SetBillingSweepNowFunc

func SetBillingSweepNowFunc(fn func(db *sql.DB) error)

SetBillingSweepNowFunc wires the dev/test "sweep now" call.

func SetBillingTickNowFunc

func SetBillingTickNowFunc(fn func(db *sql.DB) error)

SetBillingTickNowFunc wires the dev/test "tick now" call.

func ShareEnumerationMiddleware

func ShareEnumerationMiddleware(next echo.HandlerFunc) echo.HandlerFunc

ShareEnumerationMiddleware protects share endpoints against entity-global enumeration attacks (probing many different share IDs). This runs BEFORE the per-share-ID rate limiter and the handler itself.

It applies to both /shared/:id (HTML page) and /api/public/shares/:id/* endpoints.

func ShareRateLimitMiddleware

func ShareRateLimitMiddleware(next echo.HandlerFunc) echo.HandlerFunc

ShareRateLimitMiddleware provides rate limiting for share access attempts This middleware is designed to work WITH TimingProtectionMiddleware by not short-circuiting timing

func TLSVersionCheck

func TLSVersionCheck(next echo.HandlerFunc) echo.HandlerFunc

TLSVersionCheck middleware adds TLS version information to response headers and logs TLS version usage for analytics

func TOTPAuth

func TOTPAuth(c echo.Context) error

TOTPAuth validates a TOTP code and completes authentication

func TOTPRateLimitMiddleware

func TOTPRateLimitMiddleware(endpointType string) echo.MiddlewareFunc

TOTPRateLimitMiddleware provides rate limiting for TOTP endpoints

func TOTPReset

func TOTPReset(c echo.Context) error

TOTPReset resets TOTP for a user (requires valid backup code)

func TOTPSetup

func TOTPSetup(c echo.Context) error

TOTPSetup initializes TOTP setup for a user

func TOTPStatus

func TOTPStatus(c echo.Context) error

TOTPStatus returns the TOTP status for a user

func TOTPVerify

func TOTPVerify(c echo.Context) error

TOTPVerify completes TOTP setup by verifying a test code

func TimingProtectionMiddleware

func TimingProtectionMiddleware(next echo.HandlerFunc) echo.HandlerFunc

TimingProtectionMiddleware enforces 1-second minimum response time for anonymous endpoints

func UpdateUser

func UpdateUser(c echo.Context) error

UpdateUser updates user properties

func UpdateUserStorageLimit

func UpdateUserStorageLimit(c echo.Context) error

UpdateUserStorageLimit updates a user's storage limit

func UploadChunk

func UploadChunk(c echo.Context) error

UploadChunk handles individual chunk uploads

Types

type APIResponse

type APIResponse struct {
	Success bool        `json:"success"`
	Message string      `json:"message,omitempty"`
	Data    interface{} `json:"data,omitempty"`
}

APIResponse represents the standard API response structure

type AdminApproveRequest

type AdminApproveRequest struct {
	ApprovedBy        string `json:"approved_by" validate:"required"`
	StorageLimitBytes *int64 `json:"storage_limit_bytes,omitempty"`
}

AdminApproveRequest represents the request payload for user approval

type AdminApproveResponse

type AdminApproveResponse struct {
	Success    bool      `json:"success"`
	Username   string    `json:"username"`
	IsApproved bool      `json:"is_approved"`
	ApprovedBy string    `json:"approved_by"`
	ApprovedAt time.Time `json:"approved_at"`
}

AdminApproveResponse represents the response from user approval

type AdminBillingStatus

type AdminBillingStatus struct {
	BalanceUSDMicrocents         int64      `json:"balance_usd_microcents"`
	FormattedBalance             string     `json:"formatted_balance"`
	BillableBytes                int64      `json:"billable_bytes"`
	CurrentCostPerMonthUSDApprox string     `json:"current_cost_per_month_usd_approx"`
	LastBilledAt                 *time.Time `json:"last_billed_at,omitempty"`
}

AdminBillingStatus is the per-user billing snapshot surfaced in /api/admin/users/:username/status. Balances are signed microcents.

type AdminCleanupRequest

type AdminCleanupRequest struct {
	Username string `json:"username" validate:"required"`
	Confirm  bool   `json:"confirm" validate:"required"`
}

AdminCleanupRequest represents the request payload for test user cleanup

type AdminCleanupResponse

type AdminCleanupResponse struct {
	Success       bool                   `json:"success"`
	TablesCleared map[string]int         `json:"tables_cleaned"`
	TotalRows     int                    `json:"total_rows_affected"`
	Details       map[string]interface{} `json:"details,omitempty"`
}

AdminCleanupResponse represents the response from test user cleanup

type AdminOPAQUEStatus

type AdminOPAQUEStatus struct {
	HasAccount   bool `json:"has_account"`
	RecordsCount int  `json:"records_count"`
}

AdminOPAQUEStatus represents OPAQUE status information

type AdminTOTPStatus

type AdminTOTPStatus struct {
	Present        bool `json:"present"`
	Decryptable    bool `json:"decryptable"`
	Enabled        bool `json:"enabled"`
	SetupCompleted bool `json:"setup_completed"`
}

AdminTOTPStatus represents TOTP status information

type AdminTokenStatus

type AdminTokenStatus struct {
	ActiveRefreshTokens int `json:"active_refresh_tokens"`
	RevokedTokens       int `json:"revoked_tokens"`
}

AdminTokenStatus represents token status information

type AdminUserInfo

type AdminUserInfo struct {
	ID         int64     `json:"id"`
	Username   string    `json:"username"`
	IsApproved bool      `json:"is_approved"`
	IsAdmin    bool      `json:"is_admin"`
	CreatedAt  time.Time `json:"created_at"`
}

AdminUserInfo represents basic user information

type AdminUserStatusResponse

type AdminUserStatusResponse struct {
	Exists   bool                   `json:"exists"`
	Username string                 `json:"username,omitempty"`
	User     *AdminUserInfo         `json:"user,omitempty"`
	TOTP     *AdminTOTPStatus       `json:"totp,omitempty"`
	OPAQUE   *AdminOPAQUEStatus     `json:"opaque,omitempty"`
	Tokens   *AdminTokenStatus      `json:"tokens,omitempty"`
	Billing  *AdminBillingStatus    `json:"billing,omitempty"`
	Details  map[string]interface{} `json:"details,omitempty"`
}

AdminUserStatusResponse represents the comprehensive user status response

type AuthRateLimitEntry

type AuthRateLimitEntry struct {
	EndpointType       string // "login", "register", "totp_verify", "totp_auth"
	EntityID           string
	FailedCount        int
	LastFailedAttempt  *time.Time
	NextAllowedAttempt *time.Time
}

AuthRateLimitEntry represents a rate limiting entry for authentication endpoints

type BootstrapRegisterFinalizeRequest

type BootstrapRegisterFinalizeRequest struct {
	BootstrapToken     string `json:"bootstrap_token"`
	SessionID          string `json:"session_id"`
	Username           string `json:"username"`
	RegistrationRecord string `json:"registration_record"` // base64 encoded
}

BootstrapRegisterFinalizeRequest represents the final bootstrap registration request

type BootstrapRegisterInitRequest

type BootstrapRegisterInitRequest struct {
	BootstrapToken      string `json:"bootstrap_token"`
	Username            string `json:"username"`
	RegistrationRequest string `json:"registration_request"` // base64 encoded
}

BootstrapRegisterInitRequest represents the initial bootstrap registration request

type CopyTaskDetails

type CopyTaskDetails struct {
	SourceProviderID string `json:"source_provider_id"`
	DestProviderID   string `json:"destination_provider_id"`
	Verify           bool   `json:"verify"`
	SkipExisting     bool   `json:"skip_existing"`
	Username         string `json:"username,omitempty"` // set for copy-user-files
	FilesCopied      int    `json:"files_copied"`
	FilesSkipped     int    `json:"files_skipped"`
	FilesFailed      int    `json:"files_failed"`
	BytesCopied      int64  `json:"bytes_copied"`
	CurrentFileBytes int64  `json:"current_file_bytes"` // bytes copied for file in progress
	CurrentFileSize  int64  `json:"current_file_size"`  // total size of file in progress
}

CopyTaskDetails holds the JSON-serializable details stored in admin_tasks.details.

type CopyTaskRequest

type CopyTaskRequest struct {
	TaskType      string // "copy-all", "copy-user-files", "copy-file"
	AdminUsername string
	SourceID      string
	DestID        string
	Verify        bool
	SkipExisting  bool
	Username      string // only for copy-user-files
	FileID        string // only for copy-file
}

CopyTaskRequest describes a copy operation submitted by an admin API handler.

type ExportTokenClaims

type ExportTokenClaims struct {
	Username string `json:"username"`
	FileID   string `json:"file_id"`
	Action   string `json:"action"`
	jwt.RegisteredClaims
}

ExportTokenClaims holds claims for short-lived export download tokens

type FileMetadataBatchRequest

type FileMetadataBatchRequest struct {
	FileIDs []string `json:"file_ids"`
}

type LogoutRequest

type LogoutRequest struct {
	RefreshToken string `json:"refresh_token"`
}

LogoutRequest represents the request structure for logging out

type OpaqueAuthFinalizeRequest

type OpaqueAuthFinalizeRequest struct {
	Username string `json:"username"`
	AuthU    string `json:"auth_u"` // base64 encoded client authentication token
}

OpaqueAuthFinalizeRequest represents the final authentication request

type OpaqueAuthInitRequest

type OpaqueAuthInitRequest struct {
	Username string `json:"username"`
}

OpaqueAuthInitRequest represents the initial authentication request

type OpaqueAuthResponseRequest

type OpaqueAuthResponseRequest struct {
	Username          string `json:"username"`
	CredentialRequest string `json:"credential_request"` // base64 encoded
}

OpaqueAuthResponseRequest represents the credential response request

type OpaqueHealthCheckResponse

type OpaqueHealthCheckResponse struct {
	OpaqueReady       bool   `json:"opaque_ready"`
	ServerKeysLoaded  bool   `json:"server_keys_loaded"`
	DatabaseConnected bool   `json:"database_connected"`
	Status            string `json:"status"`
	Message           string `json:"message"`
}

OpaqueHealthCheckResponse represents the health status of OPAQUE system

type OpaqueRegisterFinalizeRequest

type OpaqueRegisterFinalizeRequest struct {
	Username           string `json:"username"`
	RegistrationRecord string `json:"registration_record"` // base64 encoded
}

OpaqueRegisterFinalizeRequest represents the final registration request

type OpaqueRegisterResponseRequest

type OpaqueRegisterResponseRequest struct {
	RegistrationRequest string `json:"registration_request"` // base64 encoded
}

OpaqueRegisterResponseRequest represents the server response request

type RateLimitManager

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

RateLimitManager manages rate limiting state with privacy-preserving entity IDs

var DefaultRateLimitManager *RateLimitManager

Global rate limit manager instance

func NewRateLimitManager

func NewRateLimitManager(db *sql.DB, rateLimitConfig config.RateLimitConfig) *RateLimitManager

NewRateLimitManager creates a new rate limit manager

func (*RateLimitManager) CheckRateLimit

func (rlm *RateLimitManager) CheckRateLimit(entityID, endpoint string, limit int, windowSize time.Duration) (bool, error)

CheckRateLimit checks if a request should be rate limited

type RateLimitState

type RateLimitState struct {
	EntityID       string     `json:"entity_id"`
	TimeWindow     string     `json:"time_window"`
	Endpoint       string     `json:"endpoint"`
	RequestCount   int        `json:"request_count"`
	LastRequest    time.Time  `json:"last_request"`
	ViolationCount int        `json:"violation_count"`
	PenaltyUntil   *time.Time `json:"penalty_until"`
}

RateLimitState represents the current rate limiting state for an entity

type RefreshTokenRequest

type RefreshTokenRequest struct {
	RefreshToken string `json:"refresh_token"`
}

RefreshTokenRequest represents the request structure for refreshing a token

type ShareRateLimitEntry

type ShareRateLimitEntry struct {
	ShareID            string
	EntityID           string
	FailedCount        int
	LastFailedAttempt  *time.Time
	NextAllowedAttempt *time.Time
}

ShareRateLimitEntry represents a rate limiting entry for share access

type ShareRequest

type ShareRequest struct {
	ShareID             string `json:"share_id"` // Client-generated share ID
	FileID              string `json:"file_id"`
	Salt                string `json:"salt"`                  // Base64-encoded 32-byte salt
	EncryptedEnvelope   string `json:"encrypted_envelope"`    // Base64-encoded Share Envelope (FEK + Download Token) encrypted with AAD
	DownloadTokenHash   string `json:"download_token_hash"`   // SHA-256 hash of the Download Token
	ExpiresAfterMinutes int    `json:"expires_after_minutes"` // Optional expiration in minutes (0 = no expiration)
	MaxAccesses         *int   `json:"max_accesses"`          // Optional download limit (nil = unlimited)
}

ShareRequest represents a file sharing request (Argon2id-based anonymous shares)

type ShareResponse

type ShareResponse struct {
	ShareID   string     `json:"share_id"`
	ShareURL  string     `json:"share_url"`
	CreatedAt time.Time  `json:"created_at"`
	ExpiresAt *time.Time `json:"expires_at,omitempty"`
}

ShareResponse represents a file share creation response

type StreamingHashState

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

StreamingHashState manages the running hash calculation during chunked uploads

func NewStreamingHashState

func NewStreamingHashState(sessionID string) *StreamingHashState

NewStreamingHashState creates a new streaming hash state for an upload session

func (*StreamingHashState) FinalizeHash

func (s *StreamingHashState) FinalizeHash() string

FinalizeHash completes the hash calculation and returns the final SHA256 hex string

func (*StreamingHashState) WriteChunk

func (s *StreamingHashState) WriteChunk(data []byte) ([]byte, error)

WriteChunk adds a chunk to the running hash and returns the data unchanged

type StreamingHashTeeReader

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

StreamingHashTeeReader wraps an io.Reader to calculate hash while reading

func NewStreamingHashTeeReader

func NewStreamingHashTeeReader(reader io.Reader, expectedHash string) *StreamingHashTeeReader

NewStreamingHashTeeReader creates a new tee reader that calculates hash while reading

func (*StreamingHashTeeReader) GetBytesRead

func (r *StreamingHashTeeReader) GetBytesRead() int64

GetBytesRead returns the total number of bytes read

func (*StreamingHashTeeReader) Read

func (r *StreamingHashTeeReader) Read(p []byte) (n int, err error)

Read implements io.Reader interface, calculating hash as data is read

func (*StreamingHashTeeReader) VerifyHash

func (r *StreamingHashTeeReader) VerifyHash() (bool, string)

VerifyHash checks if the calculated hash matches the expected hash

type TOTPAuthRequest

type TOTPAuthRequest struct {
	Code     string `json:"code"`
	IsBackup bool   `json:"is_backup,omitempty"`
}

TOTPAuthRequest represents the request for TOTP authentication

type TOTPResetRequest

type TOTPResetRequest struct {
	BackupCode string `json:"backup_code"`
}

TOTPResetRequest represents the request for TOTP reset

type TOTPResetResponse

type TOTPResetResponse struct {
	Secret      string   `json:"secret"`
	QRCodeURL   string   `json:"qr_code_url"`
	BackupCodes []string `json:"backup_codes"`
	ManualEntry string   `json:"manual_entry"`
	Message     string   `json:"message"`
}

TOTPResetResponse represents the response for TOTP reset

type TOTPSetupRequest

type TOTPSetupRequest struct {
}

TOTPSetupRequest represents the request for TOTP setup

type TOTPSetupResponse

type TOTPSetupResponse struct {
	Secret      string   `json:"secret"`
	QRCodeURL   string   `json:"qr_code_url"`
	QRCodeImage string   `json:"qr_code_image"` // Base64 data URI for QR code PNG
	BackupCodes []string `json:"backup_codes"`
	ManualEntry string   `json:"manual_entry"`
}

TOTPSetupResponse represents the response for TOTP setup

type TOTPStatusResponse

type TOTPStatusResponse struct {
	Enabled       bool       `json:"enabled"`
	SetupRequired bool       `json:"setup_required"`
	LastUsed      *time.Time `json:"last_used,omitempty"`
	CreatedAt     *time.Time `json:"created_at,omitempty"`
}

TOTPStatusResponse represents the TOTP status response

type TOTPVerifyRequest

type TOTPVerifyRequest struct {
	Code     string `json:"code"`
	IsBackup bool   `json:"is_backup,omitempty"`
}

TOTPVerifyRequest represents the request for TOTP verification

type TaskRunner

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

TaskRunner manages background copy tasks with concurrency control and cancellation.

func GetTaskRunner

func GetTaskRunner() *TaskRunner

GetTaskRunner returns the global task runner.

func (*TaskRunner) CancelTask

func (tr *TaskRunner) CancelTask(taskID string) bool

CancelTask requests cancellation of a running task.

func (*TaskRunner) SubmitCopyTask

func (tr *TaskRunner) SubmitCopyTask(req CopyTaskRequest) (string, error)

SubmitCopyTask creates an admin_tasks row, then runs the copy in a background goroutine. Returns the task ID immediately.

func (*TaskRunner) SubmitVerifyTask

func (tr *TaskRunner) SubmitVerifyTask(req VerifyTaskRequest) (string, error)

SubmitVerifyTask creates an admin_tasks row and runs the verification in background.

type VerifyTaskDetails

type VerifyTaskDetails struct {
	ProviderID   string `json:"provider_id,omitempty"` // empty means all providers
	Fix          bool   `json:"fix"`
	Concurrency  int    `json:"concurrency"`
	VerifiedOK   int    `json:"verified_ok"`
	Missing      int    `json:"missing"`
	SizeMismatch int    `json:"size_mismatch"`
	Errors       int    `json:"errors"`
}

VerifyTaskDetails holds the JSON-serializable details stored in admin_tasks.details.

type VerifyTaskRequest

type VerifyTaskRequest struct {
	AdminUsername string
	ProviderID    string // empty means all providers
	Fix           bool   // if true, mark missing files as "missing" in DB
	Concurrency   int    // parallel HEAD requests (default 10)
}

VerifyTaskRequest describes a verify-all operation submitted by an admin API handler.

Jump to

Keyboard shortcuts

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