api

package
v0.0.0-...-ef425cb Latest Latest
Warning

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

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

Documentation

Index

Constants

View Source
const (
	AccessTokenCookieName  = "fluxbase_access_token"
	RefreshTokenCookieName = "fluxbase_refresh_token"
)

Cookie names for authentication tokens

View Source
const (
	OpEqual          = query.OpEqual
	OpNotEqual       = query.OpNotEqual
	OpGreaterThan    = query.OpGreaterThan
	OpGreaterOrEqual = query.OpGreaterOrEqual
	OpLessThan       = query.OpLessThan
	OpLessOrEqual    = query.OpLessOrEqual
	OpLike           = query.OpLike
	OpILike          = query.OpILike
	OpIn             = query.OpIn
	OpNotIn          = query.OpNotIn
	OpIs             = query.OpIs
	OpIsNot          = query.OpIsNot
	OpContains       = query.OpContains
	OpContained      = query.OpContained
	OpContainedBy    = query.OpContainedBy
	OpOverlap        = query.OpOverlap
	OpOverlaps       = query.OpOverlaps
	OpTextSearch     = query.OpTextSearch
	OpPhraseSearch   = query.OpPhraseSearch
	OpWebSearch      = query.OpWebSearch
	OpNot            = query.OpNot
	OpAdjacent       = query.OpAdjacent
	OpStrictlyLeft   = query.OpStrictlyLeft
	OpStrictlyRight  = query.OpStrictlyRight
	OpNotExtendRight = query.OpNotExtendRight
	OpNotExtendLeft  = query.OpNotExtendLeft

	// PostGIS spatial operators
	OpSTIntersects = query.OpSTIntersects
	OpSTContains   = query.OpSTContains
	OpSTWithin     = query.OpSTWithin
	OpSTDWithin    = query.OpSTDWithin
	OpSTDistance   = query.OpSTDistance
	OpSTTouches    = query.OpSTTouches
	OpSTCrosses    = query.OpSTCrosses
	OpSTOverlaps   = query.OpSTOverlaps

	// pgvector similarity operators
	OpVectorL2     = query.OpVectorL2
	OpVectorCosine = query.OpVectorCosine
	OpVectorIP     = query.OpVectorIP
)

Re-export filter operator constants for backward compatibility

View Source
const (
	ErrCodeMissingAuth             = apperrors.ErrCodeMissingAuth
	ErrCodeInvalidToken            = apperrors.ErrCodeInvalidToken
	ErrCodeExpiredToken            = apperrors.ErrCodeExpiredToken
	ErrCodeRevokedToken            = apperrors.ErrCodeRevokedToken
	ErrCodeAuthRequired            = apperrors.ErrCodeAuthRequired
	ErrCodeInvalidUserID           = apperrors.ErrCodeInvalidUserID
	ErrCodeAccountLocked           = apperrors.ErrCodeAccountLocked
	ErrCodeInvalidCredentials      = apperrors.ErrCodeInvalidCredentials
	ErrCodeInsufficientPermissions = apperrors.ErrCodeInsufficientPermissions
	ErrCodeAdminRequired           = apperrors.ErrCodeAdminRequired
	ErrCodeInvalidRole             = apperrors.ErrCodeInvalidRole
	ErrCodeRLSViolation            = apperrors.ErrCodeRLSViolation
	ErrCodeAccessDenied            = apperrors.ErrCodeAccessDenied
	ErrCodeFeatureDisabled         = apperrors.ErrCodeFeatureDisabled
	ErrCodeInvalidBody             = apperrors.ErrCodeInvalidBody
	ErrCodeMissingField            = apperrors.ErrCodeMissingField
	ErrCodeInvalidInput            = apperrors.ErrCodeInvalidInput
	ErrCodeInvalidID               = apperrors.ErrCodeInvalidID
	ErrCodeInvalidFormat           = apperrors.ErrCodeInvalidFormat
	ErrCodeValidationFailed        = apperrors.ErrCodeValidationFailed
	ErrCodeNotFound                = apperrors.ErrCodeNotFound
	ErrCodeAlreadyExists           = apperrors.ErrCodeAlreadyExists
	ErrCodeDuplicateKey            = apperrors.ErrCodeDuplicateKey
	ErrCodeConflict                = apperrors.ErrCodeConflict
	ErrCodeForeignKeyViolation     = apperrors.ErrCodeForeignKeyViolation
	ErrCodeNotNullViolation        = apperrors.ErrCodeNotNullViolation
	ErrCodeCheckViolation          = apperrors.ErrCodeCheckViolation
	ErrCodeInternalError           = apperrors.ErrCodeInternalError
	ErrCodeDatabaseError           = apperrors.ErrCodeDatabaseError
	ErrCodeOperationFailed         = apperrors.ErrCodeOperationFailed
	ErrCodeRateLimited             = apperrors.ErrCodeRateLimited
	ErrCodeTooManyRequests         = apperrors.ErrCodeTooManyRequests
	ErrCodeSetupRequired           = apperrors.ErrCodeSetupRequired
	ErrCodeSetupCompleted          = apperrors.ErrCodeSetupCompleted
	ErrCodeSetupDisabled           = apperrors.ErrCodeSetupDisabled
	ErrCodeInvalidSetupToken       = apperrors.ErrCodeInvalidSetupToken
)
View Source
const (
	// GraphQLRLSContextKey is used to store RLS context in the request context
	GraphQLRLSContextKey graphqlContextKey = "graphql_rls_context"
)

Variables

View Source
var BigIntScalar = graphql.NewScalar(graphql.ScalarConfig{
	Name:        "BigInt",
	Description: "BigInt scalar type represents large integers as strings",
	Serialize: func(value interface{}) interface{} {
		switch v := value.(type) {
		case int64:
			return fmt.Sprintf("%d", v)
		case *int64:
			if v == nil {
				return nil
			}
			return fmt.Sprintf("%d", *v)
		case int:
			return fmt.Sprintf("%d", v)
		case string:
			return v
		default:
			return fmt.Sprintf("%v", v)
		}
	},
	ParseValue: func(value interface{}) interface{} {
		switch v := value.(type) {
		case string:
			var n int64
			if _, err := fmt.Sscanf(v, "%d", &n); err != nil {
				return nil
			}
			return n
		case int:
			return int64(v)
		case float64:
			return int64(v)
		default:
			return nil
		}
	},
	ParseLiteral: func(valueAST ast.Value) interface{} {
		switch v := valueAST.(type) {
		case *ast.StringValue:
			var n int64
			if _, err := fmt.Sscanf(v.Value, "%d", &n); err != nil {
				return nil
			}
			return n
		case *ast.IntValue:
			var n int64
			if _, err := fmt.Sscanf(v.Value, "%d", &n); err != nil {
				return nil
			}
			return n
		default:
			return nil
		}
	},
})

BigInt scalar for bigint columns (represented as string to avoid JS precision issues)

View Source
var DateTimeScalar = graphql.NewScalar(graphql.ScalarConfig{
	Name:        "DateTime",
	Description: "DateTime scalar type represents a date and time in RFC3339 format",
	Serialize: func(value interface{}) interface{} {
		switch v := value.(type) {
		case time.Time:
			return v.Format(time.RFC3339)
		case *time.Time:
			if v == nil {
				return nil
			}
			return v.Format(time.RFC3339)
		case string:
			return v
		default:
			return nil
		}
	},
	ParseValue: func(value interface{}) interface{} {
		switch v := value.(type) {
		case string:
			t, err := time.Parse(time.RFC3339, v)
			if err != nil {
				return nil
			}
			return t
		default:
			return nil
		}
	},
	ParseLiteral: func(valueAST ast.Value) interface{} {
		switch v := valueAST.(type) {
		case *ast.StringValue:
			t, err := time.Parse(time.RFC3339, v.Value)
			if err != nil {
				return nil
			}
			return t
		default:
			return nil
		}
	},
})

DateTime scalar for timestamp/timestamptz columns

View Source
var JSONScalar = graphql.NewScalar(graphql.ScalarConfig{
	Name:        "JSON",
	Description: "JSON scalar type represents arbitrary JSON data",
	Serialize: func(value interface{}) interface{} {
		switch v := value.(type) {
		case map[string]interface{}:
			return v
		case []interface{}:
			return v
		case string:
			var result interface{}
			if err := json.Unmarshal([]byte(v), &result); err != nil {
				return v
			}
			return result
		case []byte:
			var result interface{}
			if err := json.Unmarshal(v, &result); err != nil {
				return string(v)
			}
			return result
		default:
			return v
		}
	},
	ParseValue: func(value interface{}) interface{} {
		return value
	},
	ParseLiteral: func(valueAST ast.Value) interface{} {
		switch v := valueAST.(type) {
		case *ast.StringValue:
			var result interface{}
			if err := json.Unmarshal([]byte(v.Value), &result); err != nil {
				return v.Value
			}
			return result
		case *ast.ObjectValue:
			return parseObjectValue(v)
		case *ast.ListValue:
			return parseListValue(v)
		default:
			return nil
		}
	},
})

JSON scalar for jsonb/json columns

View Source
var UUIDScalar = graphql.NewScalar(graphql.ScalarConfig{
	Name:        "UUID",
	Description: "UUID scalar type represents a universally unique identifier",
	Serialize: func(value interface{}) interface{} {
		switch v := value.(type) {
		case uuid.UUID:
			return v.String()
		case *uuid.UUID:
			if v == nil {
				return nil
			}
			return v.String()
		case string:
			return v
		case []byte:
			if len(v) == 16 {
				u, err := uuid.FromBytes(v)
				if err == nil {
					return u.String()
				}
			}
			return string(v)
		default:
			return fmt.Sprintf("%v", v)
		}
	},
	ParseValue: func(value interface{}) interface{} {
		switch v := value.(type) {
		case string:
			u, err := uuid.Parse(v)
			if err != nil {
				return nil
			}
			return u
		default:
			return nil
		}
	},
	ParseLiteral: func(valueAST ast.Value) interface{} {
		switch v := valueAST.(type) {
		case *ast.StringValue:
			u, err := uuid.Parse(v.Value)
			if err != nil {
				return nil
			}
			return u
		default:
			return nil
		}
	},
})

UUID scalar for uuid columns

Functions

func AuthMiddleware

func AuthMiddleware(authService *auth.Service) fiber.Handler

AuthMiddleware creates a middleware for JWT authentication

func EncodeCursor

func EncodeCursor(column string, value interface{}, desc bool) string

EncodeCursor creates a base64-encoded cursor from the given data

func EnsureDefaultBucketRecords

func EnsureDefaultBucketRecords(ctx context.Context, db *pgxpool.Pool, bucketNames []string) error

EnsureDefaultBucketRecords creates storage.buckets DB records for the configured default buckets. This complements the physical bucket creation done by storage.Service.EnsureDefaultBuckets(), which only creates directories/S3 buckets without inserting DB rows.

The default tenant's UUID is looked up from platform.tenants. If no default tenant exists, rows are inserted with NULL tenant_id (legacy behavior).

func GetAIConfig

func GetAIConfig(c fiber.Ctx, baseConfig *config.Config) *config.AIConfig

GetAIConfig returns the AI config to use for the current request.

func GetAPIConfig

func GetAPIConfig(c fiber.Ctx, baseConfig *config.Config) *config.APIConfig

GetAPIConfig returns the API config to use for the current request.

func GetAuthConfig

func GetAuthConfig(c fiber.Ctx, baseConfig *config.Config) *config.AuthConfig

GetAuthConfig returns the auth config to use for the current request.

func GetEmailConfig

func GetEmailConfig(c fiber.Ctx, baseConfig *config.Config) *config.EmailConfig

GetEmailConfig returns the email config to use for the current request.

func GetFunctionsConfig

func GetFunctionsConfig(c fiber.Ctx, baseConfig *config.Config) *config.FunctionsConfig

GetFunctionsConfig returns the functions config to use for the current request.

func GetGraphQLConfig

func GetGraphQLConfig(c fiber.Ctx, baseConfig *config.Config) *config.GraphQLConfig

GetGraphQLConfig returns the GraphQL config to use for the current request.

func GetJobsConfig

func GetJobsConfig(c fiber.Ctx, baseConfig *config.Config) *config.JobsConfig

GetJobsConfig returns the jobs config to use for the current request.

func GetRPCConfig

func GetRPCConfig(c fiber.Ctx, baseConfig *config.Config) *config.RPCConfig

GetRPCConfig returns the RPC config to use for the current request.

func GetRealtimeConfig

func GetRealtimeConfig(c fiber.Ctx, baseConfig *config.Config) *config.RealtimeConfig

GetRealtimeConfig returns the realtime config to use for the current request.

func GetStorageConfig

func GetStorageConfig(c fiber.Ctx, baseConfig *config.Config) *config.StorageConfig

GetStorageConfig returns the storage config to use for the current request. If a tenant-specific config is available, it returns that; otherwise returns the base config. This is used by the storage manager to get the appropriate service.

func GetTenantConfig

func GetTenantConfig(c fiber.Ctx, baseConfig *config.Config) *config.Config

GetTenantConfig returns the tenant-specific configuration if available, otherwise returns the base configuration. This is the primary function handlers should use to get configuration.

If a TenantConfigResolver is available, this will resolve config from the database with immediate visibility of changes (no caching).

func GetTenantConfigFromLocals

func GetTenantConfigFromLocals(c fiber.Ctx) *config.Config

GetTenantConfigFromLocals returns only the tenant-specific config from context. Returns nil if no tenant config is set. Note: This does NOT use the resolver - it only returns the YAML-based tenant config.

func GetTenantID

func GetTenantID(c fiber.Ctx) string

GetTenantID returns the current tenant ID from context. Returns empty string if no tenant is set.

func GetTenantRole

func GetTenantRole(c fiber.Ctx) string

GetTenantRole returns the user's role in the current tenant. Returns empty string if no tenant role is set.

func GetTenantSlug

func GetTenantSlug(c fiber.Ctx) string

GetTenantSlug returns the current tenant slug from context. Returns empty string if no tenant slug is set.

func GetTenantSource

func GetTenantSource(c fiber.Ctx) string

GetTenantSource returns where the tenant context came from. Returns empty string if no tenant source is set. Possible values: "header", "jwt", "default"

func GetUserEmail

func GetUserEmail(c fiber.Ctx) (string, bool)

GetUserEmail is a helper to extract user email from context

func GetUserRole

func GetUserRole(c fiber.Ctx) (string, bool)

GetUserRole is a helper to extract user role from context

func IsInstanceAdmin

func IsInstanceAdmin(c fiber.Ctx) bool

IsInstanceAdmin returns true if the user is an instance-level admin.

func NormalizePaginationParams

func NormalizePaginationParams(limit, offset, defaultLimit, maxLimit int) (int, int)

NormalizePaginationParams validates and normalizes limit/offset pagination parameters. It enforces the maximum limit and ensures offset is non-negative. Returns the normalized (limit, offset) values.

func OptionalAuthMiddleware

func OptionalAuthMiddleware(authService *auth.Service) fiber.Handler

OptionalAuthMiddleware creates a middleware that validates JWT but doesn't require it Useful for endpoints that work both authenticated and unauthenticated

func ParseBody

func ParseBody(c fiber.Ctx, req any) error

ParseBody binds the request body to req and returns a fiber.Error on failure.

func PostgresTypeToGraphQL

func PostgresTypeToGraphQL(pgType string, isNullable bool) graphql.Output

PostgresTypeToGraphQL maps PostgreSQL data types to GraphQL types

func RequireRole

func RequireRole(allowedRoles ...string) fiber.Handler

RequireRole creates a middleware that requires a specific role Must be used after AuthMiddleware

func SendAdminRequired

func SendAdminRequired(c fiber.Ctx) error

func SendAppError

func SendAppError(c fiber.Ctx, err error) error

func SendBadRequest

func SendBadRequest(c fiber.Ctx, errMsg string, code string) error

func SendConflict

func SendConflict(c fiber.Ctx, errMsg string, code string) error

func SendError

func SendError(c fiber.Ctx, statusCode int, errMsg string) error

func SendErrorWithCode

func SendErrorWithCode(c fiber.Ctx, statusCode int, errMsg string, code string) error

func SendErrorWithDetails

func SendErrorWithDetails(c fiber.Ctx, statusCode int, errMsg string, code string, message string, hint string, details interface{}) error

func SendFeatureDisabled

func SendFeatureDisabled(c fiber.Ctx, feature string) error

func SendForbidden

func SendForbidden(c fiber.Ctx, errMsg string, code string) error

func SendInsufficientPermissions

func SendInsufficientPermissions(c fiber.Ctx) error

func SendInternalError

func SendInternalError(c fiber.Ctx, errMsg string) error

func SendInvalidBody

func SendInvalidBody(c fiber.Ctx) error

func SendInvalidID

func SendInvalidID(c fiber.Ctx, idName string) error

func SendInvalidToken

func SendInvalidToken(c fiber.Ctx) error

func SendMissingAuth

func SendMissingAuth(c fiber.Ctx) error

func SendMissingField

func SendMissingField(c fiber.Ctx, fieldName string) error

func SendNotFound

func SendNotFound(c fiber.Ctx, errMsg string) error

func SendOperationFailed

func SendOperationFailed(c fiber.Ctx, operation string) error

func SendResourceNotFound

func SendResourceNotFound(c fiber.Ctx, resourceType string) error

func SendTokenRevoked

func SendTokenRevoked(c fiber.Ctx) error

func SendUnauthorized

func SendUnauthorized(c fiber.Ctx, errMsg string, code string) error

func SendValidationError

func SendValidationError(c fiber.Ctx, errMsg string, details interface{}) error

func SetGlobalResolver

func SetGlobalResolver(resolver *TenantConfigResolver)

SetGlobalResolver sets the global tenant config resolver. This should be called once during server initialization.

func UnifiedAuthMiddleware

func UnifiedAuthMiddleware(authService *auth.Service, jwtManager *auth.JWTManager, db *database.Connection) fiber.Handler

UnifiedAuthMiddleware creates a middleware that accepts both auth.users and platform.users authentication This allows both application users with admin role AND dashboard admins to access admin endpoints. The db parameter is used to check the actual role from auth.users when JWT role is "authenticated", allowing role changes to take effect immediately without requiring re-login.

Types

type AIHandlers

type AIHandlers struct {
	Handler         *ai.Handler
	Chat            *ai.ChatHandler
	Conversations   *ai.ConversationManager
	Metrics         *observability.Metrics
	KnowledgeBase   *ai.KnowledgeBaseHandler
	KBStorage       *ai.KnowledgeBaseStorage
	DocProcessor    *ai.DocumentProcessor
	TableExportSync *ai.TableExportSyncService
	VectorManager   *VectorManager
	VectorHandler   *VectorHandler
	Internal        *InternalAIHandler
}

AIHandlers groups AI-related handlers and services.

type AcceptInvitationRequest

type AcceptInvitationRequest struct {
	Password string `json:"password"`
	Name     string `json:"name"`
}

type AcceptInvitationResponse

type AcceptInvitationResponse struct {
	User         *auth.DashboardUser `json:"user"`
	AccessToken  string              `json:"access_token"`
	RefreshToken string              `json:"refresh_token"`
	ExpiresIn    int64               `json:"expires_in"`
}

type AddColumnRequest

type AddColumnRequest struct {
	Name         string `json:"name"`
	Type         string `json:"type"`
	Nullable     bool   `json:"nullable"`
	DefaultValue string `json:"defaultValue,omitempty"`
}

AddColumnRequest represents a request to add a column to a table

type AdminAuthHandler

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

AdminAuthHandler handles admin-specific authentication

func NewAdminAuthHandler

func NewAdminAuthHandler(
	authService *auth.Service,
	userRepo *auth.UserRepository,
	dashboardAuth *auth.DashboardAuthService,
	systemSettings *auth.SystemSettingsService,
	cfg *config.Config,
) *AdminAuthHandler

NewAdminAuthHandler creates a new admin auth handler

func (*AdminAuthHandler) AdminLogin

func (h *AdminAuthHandler) AdminLogin(c fiber.Ctx) error

AdminLogin authenticates an admin user POST /api/v1/admin/login

func (*AdminAuthHandler) AdminLogout

func (h *AdminAuthHandler) AdminLogout(c fiber.Ctx) error

AdminLogout logs out an admin user POST /api/v1/admin/logout

func (*AdminAuthHandler) AdminRefreshToken

func (h *AdminAuthHandler) AdminRefreshToken(c fiber.Ctx) error

AdminRefreshToken refreshes an admin's access token POST /api/v1/admin/refresh

func (*AdminAuthHandler) GetCurrentAdmin

func (h *AdminAuthHandler) GetCurrentAdmin(c fiber.Ctx) error

GetCurrentAdmin returns the currently authenticated admin user GET /api/v1/admin/me

func (*AdminAuthHandler) GetSetupStatus

func (h *AdminAuthHandler) GetSetupStatus(c fiber.Ctx) error

GetSetupStatus checks if initial setup is needed GET /api/v1/admin/setup/status

func (*AdminAuthHandler) InitialSetup

func (h *AdminAuthHandler) InitialSetup(c fiber.Ctx) error

InitialSetup creates the first admin user POST /api/v1/admin/setup

type AdminLoginRequest

type AdminLoginRequest struct {
	Email    string `json:"email"`
	Password string `json:"password"`
}

AdminLoginRequest represents an admin login request

type AdminLoginResponse

type AdminLoginResponse struct {
	User         *auth.DashboardUser `json:"user"`
	AccessToken  string              `json:"access_token"`
	RefreshToken string              `json:"refresh_token"`
	ExpiresIn    int64               `json:"expires_in"`
}

AdminLoginResponse represents an admin login response

type AdminSessionHandler

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

AdminSessionHandler handles admin session management

func NewAdminSessionHandler

func NewAdminSessionHandler(sessionRepo *auth.SessionRepository) *AdminSessionHandler

NewAdminSessionHandler creates a new admin session handler

func (*AdminSessionHandler) ListSessions

func (h *AdminSessionHandler) ListSessions(c fiber.Ctx) error

ListSessions lists all active sessions with pagination

func (*AdminSessionHandler) RevokeSession

func (h *AdminSessionHandler) RevokeSession(c fiber.Ctx) error

RevokeSession revokes a specific session

func (*AdminSessionHandler) RevokeUserSessions

func (h *AdminSessionHandler) RevokeUserSessions(c fiber.Ctx) error

RevokeUserSessions revokes all sessions for a specific user

type AggregateFunction

type AggregateFunction string

AggregateFunction represents aggregation functions

const (
	AggCount    AggregateFunction = "count"
	AggSum      AggregateFunction = "sum"
	AggAvg      AggregateFunction = "avg"
	AggMin      AggregateFunction = "min"
	AggMax      AggregateFunction = "max"
	AggCountAll AggregateFunction = "count(*)"
)

type Aggregation

type Aggregation struct {
	Function AggregateFunction
	Column   string
	Alias    string // Optional alias for the result
}

Aggregation represents an aggregation function

func (*Aggregation) ToSQL

func (agg *Aggregation) ToSQL() string

ToSQL converts an Aggregation to SQL

type AppSettings

type AppSettings struct {
	Authentication AuthenticationSettings `json:"authentication"`
	Features       FeatureSettings        `json:"features"`
	Email          EmailSettings          `json:"email"`
	Security       SecuritySettings       `json:"security"`
	Overrides      SettingOverrides       `json:"overrides,omitempty"` // Indicates which settings are overridden by environment variables
}

AppSettings represents the structured application settings

type AppSettingsHandler

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

AppSettingsHandler handles application settings operations

func NewAppSettingsHandler

func NewAppSettingsHandler(settingsService *auth.SystemSettingsService, settingsCache *auth.SettingsCache, cfg *config.Config) *AppSettingsHandler

NewAppSettingsHandler creates a new app settings handler

func (*AppSettingsHandler) GetAppSettings

func (h *AppSettingsHandler) GetAppSettings(c fiber.Ctx) error

GetAppSettings returns all application settings in a structured format GET /api/v1/admin/app/settings

func (*AppSettingsHandler) UpdateAppSettings

func (h *AppSettingsHandler) UpdateAppSettings(c fiber.Ctx) error

UpdateAppSettings updates application settings PUT /api/v1/admin/app/settings

type AssignAdminRequest

type AssignAdminRequest struct {
	UserID string `json:"user_id"`
}

type AuthConfigResponse

type AuthConfigResponse struct {
	SignupEnabled            bool                        `json:"signup_enabled"`
	RequireEmailVerification bool                        `json:"require_email_verification"`
	MagicLinkEnabled         bool                        `json:"magic_link_enabled"`
	PasswordLoginEnabled     bool                        `json:"password_login_enabled"`
	MFAAvailable             bool                        `json:"mfa_available"`
	PasswordMinLength        int                         `json:"password_min_length"`
	PasswordRequireUppercase bool                        `json:"password_require_uppercase"`
	PasswordRequireLowercase bool                        `json:"password_require_lowercase"`
	PasswordRequireNumber    bool                        `json:"password_require_number"`
	PasswordRequireSpecial   bool                        `json:"password_require_special"`
	OAuthProviders           []OAuthProviderPublic       `json:"oauth_providers"`
	SAMLProviders            []SAMLProviderPublic        `json:"saml_providers"`
	Captcha                  *auth.CaptchaConfigResponse `json:"captcha"`
}

AuthConfigResponse represents the public authentication configuration

type AuthHandler

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

AuthHandler handles authentication HTTP requests

func NewAuthHandler

func NewAuthHandler(db *database.Connection, authService *auth.Service, captchaService *auth.CaptchaService, baseURL string) *AuthHandler

NewAuthHandler creates a new authentication handler

func (*AuthHandler) CheckCaptcha

func (h *AuthHandler) CheckCaptcha(c fiber.Ctx) error

CheckCaptcha performs a pre-flight check to determine if CAPTCHA is required POST /auth/captcha/check

This endpoint evaluates trust signals and returns whether CAPTCHA verification is needed for the subsequent auth action. It issues a challenge_id that must be included in the actual auth request.

Request body:

{
  "endpoint": "login",                    // Required: signup, login, password_reset, magic_link
  "email": "user@example.com",            // Optional: for trust lookup
  "device_fingerprint": "abc123",         // Optional: browser fingerprint
  "trust_token": "tt_..."                 // Optional: token from previous CAPTCHA
}

Response:

{
  "captcha_required": true,
  "reason": "new_ip_address",
  "trust_score": 35,
  "provider": "hcaptcha",
  "site_key": "...",
  "challenge_id": "ch_abc123...",
  "expires_at": "2024-01-15T10:05:00Z"
}

func (*AuthHandler) DisableTOTP

func (h *AuthHandler) DisableTOTP(c fiber.Ctx) error

DisableTOTP disables 2FA for a user POST /auth/2fa/disable

func (*AuthHandler) EnableTOTP

func (h *AuthHandler) EnableTOTP(c fiber.Ctx) error

EnableTOTP enables 2FA after verifying the TOTP code POST /auth/2fa/enable

func (*AuthHandler) GetActiveImpersonation

func (h *AuthHandler) GetActiveImpersonation(c fiber.Ctx) error

GetActiveImpersonation gets the active impersonation session

func (*AuthHandler) GetAuthConfig

func (h *AuthHandler) GetAuthConfig(c fiber.Ctx) error

GetAuthConfig returns the public authentication configuration for clients GET /auth/config

func (*AuthHandler) GetCSRFToken

func (h *AuthHandler) GetCSRFToken(c fiber.Ctx) error

GetCSRFToken returns the current CSRF token for the client Clients should call this endpoint first, then include the token in the X-CSRF-Token header GET /auth/csrf

func (*AuthHandler) GetCaptchaConfig

func (h *AuthHandler) GetCaptchaConfig(c fiber.Ctx) error

GetCaptchaConfig returns the public CAPTCHA configuration for clients GET /auth/captcha/config

func (*AuthHandler) GetTOTPStatus

func (h *AuthHandler) GetTOTPStatus(c fiber.Ctx) error

GetTOTPStatus checks if 2FA is enabled for a user GET /auth/2fa/status

func (*AuthHandler) GetUser

func (h *AuthHandler) GetUser(c fiber.Ctx) error

GetUser handles getting current user profile GET /auth/user

func (*AuthHandler) GetUserIdentities

func (h *AuthHandler) GetUserIdentities(c fiber.Ctx) error

GetUserIdentities gets all OAuth identities linked to a user GET /auth/user/identities

func (*AuthHandler) LinkIdentity

func (h *AuthHandler) LinkIdentity(c fiber.Ctx) error

LinkIdentity initiates OAuth flow to link a provider POST /auth/user/identities

func (*AuthHandler) ListImpersonationSessions

func (h *AuthHandler) ListImpersonationSessions(c fiber.Ctx) error

ListImpersonationSessions lists impersonation sessions for audit

func (*AuthHandler) Reauthenticate

func (h *AuthHandler) Reauthenticate(c fiber.Ctx) error

Reauthenticate generates a security nonce POST /auth/reauthenticate

func (*AuthHandler) RefreshToken

func (h *AuthHandler) RefreshToken(c fiber.Ctx) error

RefreshToken handles token refresh POST /auth/refresh

func (*AuthHandler) RequestPasswordReset

func (h *AuthHandler) RequestPasswordReset(c fiber.Ctx) error

RequestPasswordReset handles password reset requests POST /auth/password/reset

func (*AuthHandler) ResendOTP

func (h *AuthHandler) ResendOTP(c fiber.Ctx) error

ResendOTP resends an OTP code POST /auth/otp/resend

func (*AuthHandler) ResendVerificationEmail

func (h *AuthHandler) ResendVerificationEmail(c fiber.Ctx) error

ResendVerificationEmail resends the verification email to a user POST /auth/verify-email/resend

func (*AuthHandler) ResetPassword

func (h *AuthHandler) ResetPassword(c fiber.Ctx) error

ResetPassword handles password reset with token POST /auth/password/reset/confirm

func (h *AuthHandler) SendMagicLink(c fiber.Ctx) error

SendMagicLink handles sending magic link POST /auth/magiclink

func (*AuthHandler) SendOTP

func (h *AuthHandler) SendOTP(c fiber.Ctx) error

SendOTP sends an OTP code via email or SMS POST /auth/otp/signin

func (*AuthHandler) SetCaptchaTrustService

func (h *AuthHandler) SetCaptchaTrustService(trustService *auth.CaptchaTrustService)

SetCaptchaTrustService sets the CAPTCHA trust service for adaptive verification

func (*AuthHandler) SetSAMLService

func (h *AuthHandler) SetSAMLService(samlService *auth.SAMLService)

SetSAMLService sets the SAML service for SLO integration

func (*AuthHandler) SetSecureCookie

func (h *AuthHandler) SetSecureCookie(secure bool)

SetSecureCookie sets whether cookies should have the Secure flag

func (*AuthHandler) SetupTOTP

func (h *AuthHandler) SetupTOTP(c fiber.Ctx) error

SetupTOTP initiates 2FA setup by generating a TOTP secret POST /auth/2fa/setup

func (*AuthHandler) SignIn

func (h *AuthHandler) SignIn(c fiber.Ctx) error

SignIn handles user login POST /auth/signin

func (*AuthHandler) SignInAnonymous

func (h *AuthHandler) SignInAnonymous(c fiber.Ctx) error

SignInAnonymous is deprecated and disabled for security reasons Anonymous sign-in reduces security by allowing anyone to get tokens Use regular signup/signin flow instead

func (*AuthHandler) SignInWithIDToken

func (h *AuthHandler) SignInWithIDToken(c fiber.Ctx) error

SignInWithIDToken handles OAuth ID token authentication (Google, Apple) POST /auth/signin/idtoken

func (*AuthHandler) SignOut

func (h *AuthHandler) SignOut(c fiber.Ctx) error

SignOut handles user logout POST /auth/signout

func (*AuthHandler) SignUp

func (h *AuthHandler) SignUp(c fiber.Ctx) error

SignUp handles user registration POST /auth/signup

func (*AuthHandler) StartAnonImpersonation

func (h *AuthHandler) StartAnonImpersonation(c fiber.Ctx) error

StartAnonImpersonation starts impersonation as anonymous user

func (*AuthHandler) StartImpersonation

func (h *AuthHandler) StartImpersonation(c fiber.Ctx) error

StartImpersonation starts an admin impersonation session

func (*AuthHandler) StartServiceImpersonation

func (h *AuthHandler) StartServiceImpersonation(c fiber.Ctx) error

func (*AuthHandler) StopImpersonation

func (h *AuthHandler) StopImpersonation(c fiber.Ctx) error

StopImpersonation stops the active impersonation session

func (*AuthHandler) UnlinkIdentity

func (h *AuthHandler) UnlinkIdentity(c fiber.Ctx) error

UnlinkIdentity removes an OAuth identity from a user DELETE /auth/user/identities/:id

func (*AuthHandler) UpdateUser

func (h *AuthHandler) UpdateUser(c fiber.Ctx) error

UpdateUser handles updating user profile PATCH /auth/user

func (*AuthHandler) VerifyEmail

func (h *AuthHandler) VerifyEmail(c fiber.Ctx) error

VerifyEmail verifies a user's email address using a verification token POST /auth/verify-email

func (h *AuthHandler) VerifyMagicLink(c fiber.Ctx) error

VerifyMagicLink handles magic link verification POST /auth/magiclink/verify

func (*AuthHandler) VerifyOTP

func (h *AuthHandler) VerifyOTP(c fiber.Ctx) error

VerifyOTP verifies an OTP code and creates a session POST /auth/otp/verify

func (*AuthHandler) VerifyPasswordResetToken

func (h *AuthHandler) VerifyPasswordResetToken(c fiber.Ctx) error

VerifyPasswordResetToken handles password reset token verification POST /auth/password/reset/verify

func (*AuthHandler) VerifyTOTP

func (h *AuthHandler) VerifyTOTP(c fiber.Ctx) error

VerifyTOTP verifies a TOTP code during login and issues JWT tokens POST /auth/2fa/verify

type AuthHandlers

type AuthHandlers struct {
	Handler          *AuthHandler
	AdminHandler     *AdminAuthHandler
	DashboardHandler *DashboardAuthHandler
	ClientKeyHandler *ClientKeyHandler
	ClientKeyService *auth.ClientKeyService
	OAuthProvider    *OAuthProviderHandler
	OAuth            *OAuthHandler
	SAMLProvider     *SAMLProviderHandler
	SAML             *SAMLHandler
	SAMLService      *auth.SAMLService
	AdminSession     *AdminSessionHandler
	UserManagement   *UserManagementHandler
	Invitation       *InvitationHandler
}

AuthHandlers groups authentication-related handlers.

type AuthSettings

type AuthSettings struct {
	SignupEnabled                 bool                       `json:"enable_signup"`
	RequireEmailVerification      bool                       `json:"require_email_verification"`
	MagicLinkEnabled              bool                       `json:"enable_magic_link"`
	PasswordMinLength             int                        `json:"password_min_length"`
	PasswordRequireUppercase      bool                       `json:"password_require_uppercase"`
	PasswordRequireLowercase      bool                       `json:"password_require_lowercase"`
	PasswordRequireNumber         bool                       `json:"password_require_number"`
	PasswordRequireSpecial        bool                       `json:"password_require_special"`
	SessionTimeoutMinutes         int                        `json:"session_timeout_minutes"`
	MaxSessionsPerUser            int                        `json:"max_sessions_per_user"`
	DisableDashboardPasswordLogin bool                       `json:"disable_dashboard_password_login"`
	DisableAppPasswordLogin       bool                       `json:"disable_app_password_login"`
	Overrides                     map[string]SettingOverride `json:"_overrides,omitempty"`
}

Auth settings types

type AuthenticationSettings

type AuthenticationSettings struct {
	SignupEnabled            bool `json:"enable_signup"`
	MagicLinkEnabled         bool `json:"enable_magic_link"`
	PasswordMinLength        int  `json:"password_min_length"`
	RequireEmailVerification bool `json:"require_email_verification"`
	PasswordRequireUppercase bool `json:"password_require_uppercase"`
	PasswordRequireLowercase bool `json:"password_require_lowercase"`
	PasswordRequireNumber    bool `json:"password_require_number"`
	PasswordRequireSpecial   bool `json:"password_require_special"`
	SessionTimeoutMinutes    int  `json:"session_timeout_minutes"`
	MaxSessionsPerUser       int  `json:"max_sessions_per_user"`
}

AuthenticationSettings contains authentication-related settings

type BatchSettingsRequest

type BatchSettingsRequest struct {
	Keys []string `json:"keys"`
}

type BatchSettingsResponse

type BatchSettingsResponse struct {
	Key   string      `json:"key"`
	Value interface{} `json:"value"`
}

type BranchHandler

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

BranchHandler handles branch management API endpoints

func NewBranchHandler

func NewBranchHandler(manager *branching.Manager, router *branching.Router, cfg config.BranchingConfig) *BranchHandler

NewBranchHandler creates a new branch handler

func (*BranchHandler) CreateBranch

func (h *BranchHandler) CreateBranch(c fiber.Ctx) error

CreateBranch handles POST /admin/branches

func (*BranchHandler) DeleteBranch

func (h *BranchHandler) DeleteBranch(c fiber.Ctx) error

DeleteBranch handles DELETE /admin/branches/:id

func (*BranchHandler) DeleteGitHubConfig

func (h *BranchHandler) DeleteGitHubConfig(c fiber.Ctx) error

DeleteGitHubConfig handles DELETE /admin/branches/github/configs/:repository

func (*BranchHandler) GetActiveBranch

func (h *BranchHandler) GetActiveBranch(c fiber.Ctx) error

GetActiveBranch handles GET /admin/branches/active

func (*BranchHandler) GetBranch

func (h *BranchHandler) GetBranch(c fiber.Ctx) error

GetBranch handles GET /admin/branches/:id

func (*BranchHandler) GetBranchActivity

func (h *BranchHandler) GetBranchActivity(c fiber.Ctx) error

GetBranchActivity handles GET /admin/branches/:id/activity

func (*BranchHandler) GetPoolStats

func (h *BranchHandler) GetPoolStats(c fiber.Ctx) error

GetPoolStats handles GET /admin/branches/stats/pools

func (*BranchHandler) GrantBranchAccess

func (h *BranchHandler) GrantBranchAccess(c fiber.Ctx) error

GrantBranchAccess handles POST /admin/branches/:id/access

func (*BranchHandler) ListBranchAccess

func (h *BranchHandler) ListBranchAccess(c fiber.Ctx) error

ListBranchAccess handles GET /admin/branches/:id/access

func (*BranchHandler) ListBranches

func (h *BranchHandler) ListBranches(c fiber.Ctx) error

ListBranches handles GET /admin/branches

func (*BranchHandler) ListGitHubConfigs

func (h *BranchHandler) ListGitHubConfigs(c fiber.Ctx) error

ListGitHubConfigs handles GET /admin/branches/github/configs

func (*BranchHandler) ResetActiveBranch

func (h *BranchHandler) ResetActiveBranch(c fiber.Ctx) error

ResetActiveBranch handles DELETE /admin/branches/active

func (*BranchHandler) ResetBranch

func (h *BranchHandler) ResetBranch(c fiber.Ctx) error

ResetBranch handles POST /admin/branches/:id/reset

func (*BranchHandler) RevokeBranchAccess

func (h *BranchHandler) RevokeBranchAccess(c fiber.Ctx) error

RevokeBranchAccess handles DELETE /admin/branches/:id/access/:user_id

func (*BranchHandler) SetActiveBranch

func (h *BranchHandler) SetActiveBranch(c fiber.Ctx) error

SetActiveBranch handles POST /admin/branches/active

func (*BranchHandler) UpsertGitHubConfig

func (h *BranchHandler) UpsertGitHubConfig(c fiber.Ctx) error

UpsertGitHubConfig handles POST /admin/branches/github/configs

type BranchingHandlers

type BranchingHandlers struct {
	Manager   *branching.Manager
	Router    *branching.Router
	Handler   *BranchHandler
	GitHub    *GitHubWebhookHandler
	Scheduler *branching.CleanupScheduler
}

BranchingHandlers groups database branching handlers.

type BroadcastRequest

type BroadcastRequest struct {
	Channel string      `json:"channel"`
	Message interface{} `json:"message"`
}

BroadcastRequest represents a broadcast request

type BulkActionRequest

type BulkActionRequest struct {
	Action  string   `json:"action"`          // delete, export
	Targets []string `json:"targets"`         // Array of IDs
	Table   string   `json:"table,omitempty"` // Optional table name (derived from context if not provided)
}

BulkActionRequest represents a bulk action request

type BulkOperationsHandler

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

BulkOperationsHandler handles bulk data operations

func NewBulkOperationsHandler

func NewBulkOperationsHandler(db *database.Connection, authService *auth.Service, schemaCache *database.SchemaCache) *BulkOperationsHandler

NewBulkOperationsHandler creates a new bulk operations handler

func (*BulkOperationsHandler) HandleBulkAction

func (h *BulkOperationsHandler) HandleBulkAction(c fiber.Ctx) error

HandleBulkAction processes a bulk action request

type CaptchaHandlers

type CaptchaHandlers struct {
	Settings *CaptchaSettingsHandler
}

CaptchaHandlers groups captcha-related handlers.

type CaptchaSettingsHandler

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

func NewCaptchaSettingsHandler

func NewCaptchaSettingsHandler(
	settingsService *auth.SystemSettingsService,
	settingsCache *auth.SettingsCache,
	secretsService *settings.SecretsService,
	envConfig *config.SecurityConfig,
	captchaService *auth.CaptchaService,
) *CaptchaSettingsHandler

func (*CaptchaSettingsHandler) GetSettings

func (h *CaptchaSettingsHandler) GetSettings(c fiber.Ctx) error

func (*CaptchaSettingsHandler) UpdateSettings

func (h *CaptchaSettingsHandler) UpdateSettings(c fiber.Ctx) error

type CaptchaSettingsResponse

type CaptchaSettingsResponse struct {
	Enabled        bool     `json:"enabled"`
	Provider       string   `json:"provider"`
	SiteKey        string   `json:"site_key"`
	SecretKeySet   bool     `json:"secret_key_set"`
	ScoreThreshold float64  `json:"score_threshold"`
	Endpoints      []string `json:"endpoints"`
	CapServerURL   string   `json:"cap_server_url"`
	CapAPIKeySet   bool     `json:"cap_api_key_set"`

	Overrides map[string]OverrideInfo `json:"_overrides"`
}

type ChunkedUploadSessionResponse

type ChunkedUploadSessionResponse struct {
	SessionID       string    `json:"session_id"`
	Bucket          string    `json:"bucket"`
	Path            string    `json:"path"`
	TotalSize       int64     `json:"total_size"`
	ChunkSize       int64     `json:"chunk_size"`
	TotalChunks     int       `json:"total_chunks"`
	CompletedChunks []int     `json:"completed_chunks"`
	Status          string    `json:"status"`
	ExpiresAt       time.Time `json:"expires_at"`
	CreatedAt       time.Time `json:"created_at"`
}

ChunkedUploadSessionResponse represents the response for a chunked upload session

type ClientKeyHandler

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

func NewClientKeyHandler

func NewClientKeyHandler(clientKeyService *auth.ClientKeyService) *ClientKeyHandler

func (*ClientKeyHandler) CreateClientKey

func (h *ClientKeyHandler) CreateClientKey(c fiber.Ctx) error

func (*ClientKeyHandler) DeleteClientKey

func (h *ClientKeyHandler) DeleteClientKey(c fiber.Ctx) error

func (*ClientKeyHandler) GetClientKey

func (h *ClientKeyHandler) GetClientKey(c fiber.Ctx) error

func (*ClientKeyHandler) ListClientKeys

func (h *ClientKeyHandler) ListClientKeys(c fiber.Ctx) error

func (*ClientKeyHandler) RevokeClientKey

func (h *ClientKeyHandler) RevokeClientKey(c fiber.Ctx) error

func (*ClientKeyHandler) UpdateClientKey

func (h *ClientKeyHandler) UpdateClientKey(c fiber.Ctx) error

type CompleteChunkedUploadResponse

type CompleteChunkedUploadResponse struct {
	ID          string `json:"id"`
	Path        string `json:"path"`
	FullPath    string `json:"full_path"`
	Size        int64  `json:"size"`
	ContentType string `json:"content_type,omitempty"`
}

CompleteChunkedUploadResponse represents the response after completing a chunked upload

type CountType

type CountType string

CountType represents row count preferences

const (
	CountNone      CountType = "none"
	CountExact     CountType = "exact"
	CountPlanned   CountType = "planned"
	CountEstimated CountType = "estimated"
)

type CreateBranchRequest

type CreateBranchRequest struct {
	Name           string                  `json:"name"`
	TenantID       *uuid.UUID              `json:"tenant_id,omitempty"`
	ParentBranchID *uuid.UUID              `json:"parent_branch_id,omitempty"`
	DataCloneMode  branching.DataCloneMode `json:"data_clone_mode,omitempty"`
	Type           branching.BranchType    `json:"type,omitempty"`
	GitHubPRNumber *int                    `json:"github_pr_number,omitempty"`
	GitHubPRURL    *string                 `json:"github_pr_url,omitempty"`
	GitHubRepo     *string                 `json:"github_repo,omitempty"`
	ExpiresIn      *string                 `json:"expires_in,omitempty"` // Duration string like "24h", "7d"
}

CreateBranchRequest represents the request body for creating a branch

type CreateClientKeyRequest

type CreateClientKeyRequest struct {
	Name               string     `json:"name"`
	Description        *string    `json:"description,omitempty"`
	Scopes             []string   `json:"scopes"`
	RateLimitPerMinute int        `json:"rate_limit_per_minute"`
	ExpiresAt          *time.Time `json:"expires_at,omitempty"`
}

type CreateColumnRequest

type CreateColumnRequest struct {
	Name         string `json:"name"`
	Type         string `json:"type"`
	Nullable     bool   `json:"nullable"`
	PrimaryKey   bool   `json:"primaryKey"`
	DefaultValue string `json:"defaultValue"`
}

CreateColumnRequest represents a column definition

type CreateInvitationRequest

type CreateInvitationRequest struct {
	Email          string `json:"email"`
	Role           string `json:"role"`
	ExpiryDuration int64  `json:"expiry_duration,omitempty"`
}

type CreateInvitationResponse

type CreateInvitationResponse struct {
	Invitation  *auth.InvitationToken `json:"invitation"`
	InviteLink  string                `json:"invite_link"`
	EmailSent   bool                  `json:"email_sent"`
	EmailStatus string                `json:"email_status,omitempty"`
}

type CreateOAuthProviderRequest

type CreateOAuthProviderRequest struct {
	ProviderName        string              `json:"provider_name"`
	DisplayName         string              `json:"display_name"`
	Enabled             bool                `json:"enabled"`
	ClientID            string              `json:"client_id"`
	ClientSecret        string              `json:"client_secret"`
	RedirectURL         string              `json:"redirect_url"`
	Scopes              []string            `json:"scopes"`
	IsCustom            bool                `json:"is_custom"`
	AuthorizationURL    *string             `json:"authorization_url,omitempty"`
	TokenURL            *string             `json:"token_url,omitempty"`
	UserInfoURL         *string             `json:"user_info_url,omitempty"`
	RevocationEndpoint  *string             `json:"revocation_endpoint,omitempty"`  // OAuth 2.0 Token Revocation (RFC 7009)
	EndSessionEndpoint  *string             `json:"end_session_endpoint,omitempty"` // OIDC RP-Initiated Logout
	AllowDashboardLogin *bool               `json:"allow_dashboard_login,omitempty"`
	AllowAppLogin       *bool               `json:"allow_app_login,omitempty"`
	RequiredClaims      map[string][]string `json:"required_claims,omitempty"`
	DeniedClaims        map[string][]string `json:"denied_claims,omitempty"`
}

CreateOAuthProviderRequest represents a request to create an OAuth provider

type CreatePolicyRequest

type CreatePolicyRequest struct {
	Schema     string   `json:"schema"`
	Table      string   `json:"table"`
	Name       string   `json:"name"`
	Command    string   `json:"command"`    // ALL, SELECT, INSERT, UPDATE, DELETE
	Permissive bool     `json:"permissive"` // true = PERMISSIVE, false = RESTRICTIVE
	Roles      []string `json:"roles"`
	Using      string   `json:"using"`
	WithCheck  string   `json:"with_check"`
}

CreatePolicyRequest is the request body for creating a policy

type CreateSAMLProviderRequest

type CreateSAMLProviderRequest struct {
	Name                 string            `json:"name"`
	DisplayName          string            `json:"display_name"`
	Enabled              bool              `json:"enabled"`
	IdPMetadataURL       *string           `json:"idp_metadata_url,omitempty"`
	IdPMetadataXML       *string           `json:"idp_metadata_xml,omitempty"`
	AttributeMapping     map[string]string `json:"attribute_mapping,omitempty"`
	AutoCreateUsers      *bool             `json:"auto_create_users,omitempty"`
	DefaultRole          *string           `json:"default_role,omitempty"`
	AllowDashboardLogin  *bool             `json:"allow_dashboard_login,omitempty"`
	AllowAppLogin        *bool             `json:"allow_app_login,omitempty"`
	AllowIDPInitiated    *bool             `json:"allow_idp_initiated,omitempty"`
	AllowedRedirectHosts []string          `json:"allowed_redirect_hosts,omitempty"`
	RequiredGroups       []string          `json:"required_groups,omitempty"`
	RequiredGroupsAll    []string          `json:"required_groups_all,omitempty"`
	DeniedGroups         []string          `json:"denied_groups,omitempty"`
	GroupAttribute       *string           `json:"group_attribute,omitempty"`
}

CreateSAMLProviderRequest represents a request to create a SAML provider

type CreateSAMLUserRequest

type CreateSAMLUserRequest struct {
	Email      string
	Name       string
	Provider   string
	NameID     string
	Attributes map[string][]string
}

CreateSAMLUser method to add to auth.Service

type CreateSchemaRequest

type CreateSchemaRequest struct {
	Name string `json:"name"`
}

CreateSchemaRequest represents a request to create a new schema

type CreateServiceKeyInternalRequest

type CreateServiceKeyInternalRequest struct {
	Name              string
	Description       string
	KeyType           string
	TenantID          *uuid.UUID
	Scopes            []string
	AllowedNamespaces []string
	RateLimitPerMin   *int
	CreatedBy         *uuid.UUID
}

CreateServiceKeyInternalRequest represents an internal request to create a service key

type CreateServiceKeyRequest

type CreateServiceKeyRequest struct {
	Name               string     `json:"name"`
	Description        *string    `json:"description,omitempty"`
	KeyType            string     `json:"key_type"`
	Scopes             []string   `json:"scopes,omitempty"`
	AllowedNamespaces  []string   `json:"allowed_namespaces,omitempty"`
	RateLimitPerMinute *int       `json:"rate_limit_per_minute,omitempty"`
	RateLimitPerHour   *int       `json:"rate_limit_per_hour,omitempty"`
	ExpiresAt          *time.Time `json:"expires_at,omitempty"`
}

CreateServiceKeyRequest represents a request to create a service key

type CreateTableRequest

type CreateTableRequest struct {
	Schema  string                `json:"schema"`
	Name    string                `json:"name"`
	Columns []CreateColumnRequest `json:"columns"`
}

CreateTableRequest represents a request to create a new table

type CreateTenantRequest

type CreateTenantRequest struct {
	// Basic info
	Slug     string                 `json:"slug"`
	Name     string                 `json:"name"`
	Metadata map[string]interface{} `json:"metadata,omitempty"`

	// Database selection
	DBMode string  `json:"db_mode,omitempty"` // "auto" (default) or "existing"
	DBName *string `json:"db_name,omitempty"` // Required when db_mode is "existing"

	// Key generation
	AutoGenerateKeys bool `json:"auto_generate_keys"` // default: true

	// Admin assignment
	AdminEmail  *string `json:"admin_email,omitempty"`
	AdminUserID *string `json:"admin_user_id,omitempty"`

	// Key delivery
	SendKeysToEmail bool `json:"send_keys_to_email"`
}

type CreateTenantResponse

type CreateTenantResponse struct {
	Tenant          TenantResponse `json:"tenant"`
	AnonKey         *string        `json:"anon_key,omitempty"`
	ServiceKey      *string        `json:"service_key,omitempty"`
	InvitationSent  bool           `json:"invitation_sent"`
	InvitationEmail *string        `json:"invitation_email,omitempty"`
}

CreateTenantResponse represents the response for tenant creation

type CursorData

type CursorData struct {
	Column string      `json:"c"` // Column name (short key for smaller cursor)
	Value  interface{} `json:"v"` // Last value
	Desc   bool        `json:"d"` // True if descending order
}

CursorData represents decoded cursor pagination data

func DecodeCursor

func DecodeCursor(cursor string) (*CursorData, error)

DecodeCursor decodes a base64-encoded cursor

type CustomMCPHandler

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

CustomMCPHandler handles custom MCP tool and resource management requests.

func NewCustomMCPHandler

func NewCustomMCPHandler(storage *custom.Storage, manager *custom.Manager, mcpConfig *config.MCPConfig) *CustomMCPHandler

NewCustomMCPHandler creates a new custom MCP handler.

func (*CustomMCPHandler) CreateResource

func (h *CustomMCPHandler) CreateResource(c fiber.Ctx) error

CreateResource creates a new custom MCP resource.

func (*CustomMCPHandler) CreateTool

func (h *CustomMCPHandler) CreateTool(c fiber.Ctx) error

CreateTool creates a new custom MCP tool.

func (*CustomMCPHandler) DeleteResource

func (h *CustomMCPHandler) DeleteResource(c fiber.Ctx) error

DeleteResource deletes a custom MCP resource.

func (*CustomMCPHandler) DeleteTool

func (h *CustomMCPHandler) DeleteTool(c fiber.Ctx) error

DeleteTool deletes a custom MCP tool.

func (*CustomMCPHandler) GetConfig

func (h *CustomMCPHandler) GetConfig(c fiber.Ctx) error

GetConfig returns the current MCP configuration.

func (*CustomMCPHandler) GetResource

func (h *CustomMCPHandler) GetResource(c fiber.Ctx) error

GetResource returns a custom MCP resource by ID.

func (*CustomMCPHandler) GetTool

func (h *CustomMCPHandler) GetTool(c fiber.Ctx) error

GetTool returns a custom MCP tool by ID.

func (*CustomMCPHandler) ListResources

func (h *CustomMCPHandler) ListResources(c fiber.Ctx) error

ListResources returns all custom MCP resources.

func (*CustomMCPHandler) ListTools

func (h *CustomMCPHandler) ListTools(c fiber.Ctx) error

ListTools returns all custom MCP tools.

func (*CustomMCPHandler) SyncResource

func (h *CustomMCPHandler) SyncResource(c fiber.Ctx) error

SyncResource creates or updates a resource by URI (upsert).

func (*CustomMCPHandler) SyncTool

func (h *CustomMCPHandler) SyncTool(c fiber.Ctx) error

SyncTool creates or updates a tool by name (upsert).

func (*CustomMCPHandler) TestResource

func (h *CustomMCPHandler) TestResource(c fiber.Ctx) error

TestResource tests a custom MCP resource read.

func (*CustomMCPHandler) TestTool

func (h *CustomMCPHandler) TestTool(c fiber.Ctx) error

TestTool tests a custom MCP tool execution.

func (*CustomMCPHandler) UpdateResource

func (h *CustomMCPHandler) UpdateResource(c fiber.Ctx) error

UpdateResource updates an existing custom MCP resource.

func (*CustomMCPHandler) UpdateTool

func (h *CustomMCPHandler) UpdateTool(c fiber.Ctx) error

UpdateTool updates an existing custom MCP tool.

type CustomSettingsHandler

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

func NewCustomSettingsHandler

func NewCustomSettingsHandler(settingsService *settings.CustomSettingsService) *CustomSettingsHandler

func (*CustomSettingsHandler) CreateSecretSetting

func (h *CustomSettingsHandler) CreateSecretSetting(c fiber.Ctx) error

func (*CustomSettingsHandler) CreateSetting

func (h *CustomSettingsHandler) CreateSetting(c fiber.Ctx) error

func (*CustomSettingsHandler) DeleteSecretSetting

func (h *CustomSettingsHandler) DeleteSecretSetting(c fiber.Ctx) error

func (*CustomSettingsHandler) DeleteSetting

func (h *CustomSettingsHandler) DeleteSetting(c fiber.Ctx) error

func (*CustomSettingsHandler) GetSecretSetting

func (h *CustomSettingsHandler) GetSecretSetting(c fiber.Ctx) error

func (*CustomSettingsHandler) GetSetting

func (h *CustomSettingsHandler) GetSetting(c fiber.Ctx) error

func (*CustomSettingsHandler) ListSecretSettings

func (h *CustomSettingsHandler) ListSecretSettings(c fiber.Ctx) error

func (*CustomSettingsHandler) ListSettings

func (h *CustomSettingsHandler) ListSettings(c fiber.Ctx) error

func (*CustomSettingsHandler) UpdateSecretSetting

func (h *CustomSettingsHandler) UpdateSecretSetting(c fiber.Ctx) error

func (*CustomSettingsHandler) UpdateSetting

func (h *CustomSettingsHandler) UpdateSetting(c fiber.Ctx) error

type DDLHandler

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

DDLHandler handles Database Definition Language (DDL) operations for schema and table management

func NewDDLHandler

func NewDDLHandler(db *database.Connection, schemaCache *database.SchemaCache) *DDLHandler

NewDDLHandler creates a new DDL handler

func (*DDLHandler) AddColumn

func (h *DDLHandler) AddColumn(c fiber.Ctx) error

AddColumn adds a new column to an existing table

func (*DDLHandler) CreateSchema

func (h *DDLHandler) CreateSchema(c fiber.Ctx) error

CreateSchema creates a new database schema

func (*DDLHandler) CreateTable

func (h *DDLHandler) CreateTable(c fiber.Ctx) error

CreateTable creates a new table with specified columns

func (*DDLHandler) DeleteTable

func (h *DDLHandler) DeleteTable(c fiber.Ctx) error

DeleteTable drops a table from the database

func (*DDLHandler) DropColumn

func (h *DDLHandler) DropColumn(c fiber.Ctx) error

DropColumn removes a column from a table

func (*DDLHandler) ListSchemas

func (h *DDLHandler) ListSchemas(c fiber.Ctx) error

ListSchemas returns all user schemas (excluding system schemas)

func (*DDLHandler) ListTables

func (h *DDLHandler) ListTables(c fiber.Ctx) error

ListTables returns all tables, optionally filtered by schema

func (*DDLHandler) RenameTable

func (h *DDLHandler) RenameTable(c fiber.Ctx) error

RenameTable renames a table

func (*DDLHandler) SetSchemaCache

func (h *DDLHandler) SetSchemaCache(cache *database.SchemaCache)

SetSchemaCache sets the schema cache for invalidation after DDL operations

type DashboardAuthHandler

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

DashboardAuthHandler handles platform authentication endpoints

func NewDashboardAuthHandler

func NewDashboardAuthHandler(authService *auth.DashboardAuthService, jwtManager *auth.JWTManager, db *database.Connection, samlService *auth.SAMLService, emailService email.Service, baseURL, encryptionKey string, oauthHandler *OAuthHandler) *DashboardAuthHandler

NewDashboardAuthHandler creates a new dashboard auth handler

func (*DashboardAuthHandler) ChangePassword

func (h *DashboardAuthHandler) ChangePassword(c fiber.Ctx) error

ChangePassword changes the current user's password

func (*DashboardAuthHandler) ConfirmPasswordReset

func (h *DashboardAuthHandler) ConfirmPasswordReset(c fiber.Ctx) error

ConfirmPasswordReset resets the password using a valid reset token

func (*DashboardAuthHandler) DeleteAccount

func (h *DashboardAuthHandler) DeleteAccount(c fiber.Ctx) error

DeleteAccount deletes the current user's account

func (*DashboardAuthHandler) DisableTOTP

func (h *DashboardAuthHandler) DisableTOTP(c fiber.Ctx) error

DisableTOTP disables 2FA for the current user

func (*DashboardAuthHandler) EnableTOTP

func (h *DashboardAuthHandler) EnableTOTP(c fiber.Ctx) error

EnableTOTP enables 2FA after verifying the TOTP code

func (*DashboardAuthHandler) GetCurrentUser

func (h *DashboardAuthHandler) GetCurrentUser(c fiber.Ctx) error

GetCurrentUser returns the currently authenticated dashboard user

func (*DashboardAuthHandler) GetSSOProviders

func (h *DashboardAuthHandler) GetSSOProviders(c fiber.Ctx) error

GetSSOProviders returns the list of SSO providers available for dashboard login

func (*DashboardAuthHandler) InitiateOAuthLogin

func (h *DashboardAuthHandler) InitiateOAuthLogin(c fiber.Ctx) error

InitiateOAuthLogin initiates an OAuth login flow for dashboard SSO

func (*DashboardAuthHandler) InitiateSAMLLogin

func (h *DashboardAuthHandler) InitiateSAMLLogin(c fiber.Ctx) error

InitiateSAMLLogin initiates a SAML login flow for dashboard SSO

func (*DashboardAuthHandler) Login

func (h *DashboardAuthHandler) Login(c fiber.Ctx) error

Login authenticates a dashboard user

func (*DashboardAuthHandler) OAuthCallback

func (h *DashboardAuthHandler) OAuthCallback(c fiber.Ctx) error

OAuthCallback handles the OAuth callback for dashboard SSO

func (*DashboardAuthHandler) RefreshToken

func (h *DashboardAuthHandler) RefreshToken(c fiber.Ctx) error

RefreshToken handles token refresh for dashboard users

func (*DashboardAuthHandler) RequestPasswordReset

func (h *DashboardAuthHandler) RequestPasswordReset(c fiber.Ctx) error

RequestPasswordReset initiates a password reset for a dashboard user

func (*DashboardAuthHandler) RequireDashboardAuth

func (h *DashboardAuthHandler) RequireDashboardAuth(c fiber.Ctx) error

RequireDashboardAuth is a middleware that requires dashboard authentication

func (*DashboardAuthHandler) SAMLACSCallback

func (h *DashboardAuthHandler) SAMLACSCallback(c fiber.Ctx) error

SAMLACSCallback handles the SAML Assertion Consumer Service callback for dashboard SSO

func (*DashboardAuthHandler) SetupTOTP

func (h *DashboardAuthHandler) SetupTOTP(c fiber.Ctx) error

SetupTOTP generates a new TOTP secret for 2FA

func (*DashboardAuthHandler) Signup

func (h *DashboardAuthHandler) Signup(c fiber.Ctx) error

Signup creates a new dashboard user account Only allowed if no dashboard users exist yet (first user self-registration)

func (*DashboardAuthHandler) UpdateProfile

func (h *DashboardAuthHandler) UpdateProfile(c fiber.Ctx) error

UpdateProfile updates the current user's profile

func (*DashboardAuthHandler) VerifyPasswordResetToken

func (h *DashboardAuthHandler) VerifyPasswordResetToken(c fiber.Ctx) error

VerifyPasswordResetToken verifies a password reset token is valid

func (*DashboardAuthHandler) VerifyTOTP

func (h *DashboardAuthHandler) VerifyTOTP(c fiber.Ctx) error

VerifyTOTP verifies a TOTP code during login

type DataExportHandler

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

DataExportHandler handles data export operations

func NewDataExportHandler

func NewDataExportHandler(db *database.Connection, authService *auth.Service, schemaCache *database.SchemaCache) *DataExportHandler

NewDataExportHandler creates a new data export handler

func (*DataExportHandler) HandleDataExport

func (h *DataExportHandler) HandleDataExport(c fiber.Ctx) error

HandleDataExport processes a data export request

type DatabaseStats

type DatabaseStats struct {
	AcquireCount            int64   `json:"acquire_count"`
	AcquiredConns           int32   `json:"acquired_conns"`
	CanceledAcquireCount    int64   `json:"canceled_acquire_count"`
	ConstructingConns       int32   `json:"constructing_conns"`
	EmptyAcquireCount       int64   `json:"empty_acquire_count"`
	IdleConns               int32   `json:"idle_conns"`
	MaxConns                int32   `json:"max_conns"`
	TotalConns              int32   `json:"total_conns"`
	NewConnsCount           int64   `json:"new_conns_count"`
	MaxLifetimeDestroyCount int64   `json:"max_lifetime_destroy_count"`
	MaxIdleDestroyCount     int64   `json:"max_idle_destroy_count"`
	AcquireDurationMS       float64 `json:"acquire_duration_ms"`
}

DatabaseStats represents database connection pool stats

type DeprecateServiceKeyRequest

type DeprecateServiceKeyRequest struct {
	Reason           string `json:"reason"`
	GracePeriodHours int    `json:"grace_period_hours"`
}

DeprecateServiceKeyRequest represents a request to deprecate a service key

type EmailHandlers

type EmailHandlers struct {
	Template *EmailTemplateHandler
	Settings *EmailSettingsHandler
}

EmailHandlers groups email-related handlers.

type EmailSettings

type EmailSettings struct {
	Enabled        bool              `json:"enabled"`
	Provider       string            `json:"provider"`
	FromAddress    string            `json:"from_address,omitempty"`
	FromName       string            `json:"from_name,omitempty"`
	ReplyToAddress string            `json:"reply_to_address,omitempty"`
	SMTP           *SMTPSettings     `json:"smtp,omitempty"`
	SendGrid       *SendGridSettings `json:"sendgrid,omitempty"`
	Mailgun        *MailgunSettings  `json:"mailgun,omitempty"`
	SES            *SESSettings      `json:"ses,omitempty"`
}

EmailSettings contains email configuration

type EmailSettingsHandler

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

EmailSettingsHandler handles email configuration management

func NewEmailSettingsHandler

func NewEmailSettingsHandler(
	settingsService *auth.SystemSettingsService,
	settingsCache *auth.SettingsCache,
	emailManager *email.Manager,
	secretsService *settings.SecretsService,
	cfg *config.Config,
	unifiedService *settings.UnifiedService,
) *EmailSettingsHandler

NewEmailSettingsHandler creates a new email settings handler

func (*EmailSettingsHandler) DeleteSettingForTenant

func (h *EmailSettingsHandler) DeleteSettingForTenant(c fiber.Ctx) error

DeleteSettingForTenant removes a tenant-level email setting override, reverting to instance default. DELETE /api/v1/admin/email/settings/tenant/:field

func (*EmailSettingsHandler) GetSettings

func (h *EmailSettingsHandler) GetSettings(c fiber.Ctx) error

GetSettings returns the current email settings GET /api/v1/admin/email/settings

func (*EmailSettingsHandler) GetSettingsForTenant

func (h *EmailSettingsHandler) GetSettingsForTenant(c fiber.Ctx) error

GetSettingsForTenant returns email settings resolved through the cascade for a specific tenant. GET /api/v1/admin/email/settings/tenant

func (*EmailSettingsHandler) TestSettings

func (h *EmailSettingsHandler) TestSettings(c fiber.Ctx) error

TestSettings sends a test email with current settings POST /api/v1/admin/email/settings/test

func (*EmailSettingsHandler) TestSettingsForTenant

func (h *EmailSettingsHandler) TestSettingsForTenant(c fiber.Ctx) error

TestSettingsForTenant sends a test email using the tenant-resolved email configuration. POST /api/v1/admin/email/settings/tenant/test

func (*EmailSettingsHandler) UpdateSettings

func (h *EmailSettingsHandler) UpdateSettings(c fiber.Ctx) error

UpdateSettings updates email settings PUT /api/v1/admin/email/settings

func (*EmailSettingsHandler) UpdateSettingsForTenant

func (h *EmailSettingsHandler) UpdateSettingsForTenant(c fiber.Ctx) error

UpdateSettingsForTenant updates email settings for a specific tenant. PUT /api/v1/admin/email/settings/tenant

type EmailSettingsResponse

type EmailSettingsResponse struct {
	Enabled     bool   `json:"enabled"`
	Provider    string `json:"provider"`
	FromAddress string `json:"from_address"`
	FromName    string `json:"from_name"`

	// SMTP
	SMTPHost        string `json:"smtp_host"`
	SMTPPort        int    `json:"smtp_port"`
	SMTPUsername    string `json:"smtp_username"`
	SMTPPasswordSet bool   `json:"smtp_password_set"` // true if password is configured
	SMTPTLS         bool   `json:"smtp_tls"`

	// SendGrid
	SendGridAPIKeySet bool `json:"sendgrid_api_key_set"`

	// Mailgun
	MailgunAPIKeySet bool   `json:"mailgun_api_key_set"`
	MailgunDomain    string `json:"mailgun_domain"`

	// AWS SES
	SESAccessKeySet bool   `json:"ses_access_key_set"`
	SESSecretKeySet bool   `json:"ses_secret_key_set"`
	SESRegion       string `json:"ses_region"`

	// Override information
	Overrides map[string]OverrideInfo `json:"_overrides"`
}

EmailSettingsResponse represents the email settings returned to the UI

type EmailTemplate

type EmailTemplate struct {
	ID           uuid.UUID `json:"id"`
	TemplateType string    `json:"template_type"`
	Subject      string    `json:"subject"`
	HTMLBody     string    `json:"html_body"`
	TextBody     *string   `json:"text_body,omitempty"`
	IsCustom     bool      `json:"is_custom"`
	CreatedAt    time.Time `json:"created_at"`
	UpdatedAt    time.Time `json:"updated_at"`
}

type EmailTemplateHandler

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

func NewEmailTemplateHandler

func NewEmailTemplateHandler(db *database.Connection, emailService email.Service) *EmailTemplateHandler

func (*EmailTemplateHandler) GetTemplate

func (h *EmailTemplateHandler) GetTemplate(c fiber.Ctx) error

func (*EmailTemplateHandler) ListTemplates

func (h *EmailTemplateHandler) ListTemplates(c fiber.Ctx) error

func (*EmailTemplateHandler) ResetTemplate

func (h *EmailTemplateHandler) ResetTemplate(c fiber.Ctx) error

func (*EmailTemplateHandler) TestTemplate

func (h *EmailTemplateHandler) TestTemplate(c fiber.Ctx) error

func (*EmailTemplateHandler) UpdateTemplate

func (h *EmailTemplateHandler) UpdateTemplate(c fiber.Ctx) error

type EmbedRequest

type EmbedRequest struct {
	Text     string   `json:"text,omitempty"`
	Texts    []string `json:"texts,omitempty"`
	Model    string   `json:"model,omitempty"`
	Provider string   `json:"provider,omitempty"`
}

type EmbedResponse

type EmbedResponse struct {
	Embeddings [][]float32 `json:"embeddings"`
	Model      string      `json:"model"`
	Dimensions int         `json:"dimensions"`
	Usage      *EmbedUsage `json:"usage,omitempty"`
}

type EmbedUsage

type EmbedUsage struct {
	PromptTokens int `json:"prompt_tokens"`
	TotalTokens  int `json:"total_tokens"`
}

type EmbeddedRelation

type EmbeddedRelation struct {
	Name    string   // Relation name
	Select  []string // Fields to select from relation
	Filters []Filter // Filters for the relation
}

EmbeddedRelation represents a relation to embed

type EnableRealtimeRequest

type EnableRealtimeRequest struct {
	Schema  string   `json:"schema"`
	Table   string   `json:"table"`
	Events  []string `json:"events,omitempty"`  // INSERT, UPDATE, DELETE (default: all)
	Exclude []string `json:"exclude,omitempty"` // Columns to exclude from notifications
}

EnableRealtimeRequest represents a request to enable realtime on a table

type EnableRealtimeResponse

type EnableRealtimeResponse struct {
	Schema      string   `json:"schema"`
	Table       string   `json:"table"`
	Events      []string `json:"events"`
	TriggerName string   `json:"trigger_name"`
	Exclude     []string `json:"exclude,omitempty"`
}

EnableRealtimeResponse represents the response after enabling realtime

type ErrorResponse

type ErrorResponse = apperrors.ErrorResponse

type ExecuteSQLRequest

type ExecuteSQLRequest struct {
	Query string `json:"query"`
}

type ExecuteSQLResponse

type ExecuteSQLResponse struct {
	Results []SQLResult `json:"results"`
}

type ExecutionLogsResponse

type ExecutionLogsResponse struct {
	Entries []*storage.LogEntry `json:"entries"`
	Count   int                 `json:"count"`
}

ExecutionLogsResponse represents the response from execution logs query

type ExtensionsHandlers

type ExtensionsHandlers struct {
	Handler *extensions.Handler
}

ExtensionsHandlers groups extension handlers.

type FeatureSettings

type FeatureSettings struct {
	EnableRealtime  bool `json:"enable_realtime"`
	EnableStorage   bool `json:"enable_storage"`
	EnableFunctions bool `json:"enable_functions"`
}

FeatureSettings contains feature flag settings

type Filter

type Filter = query.Filter

Filter is an alias for query.Filter for backward compatibility

type FilterOperator

type FilterOperator = query.FilterOperator

FilterOperator is an alias for query.FilterOperator for backward compatibility

type FunctionsHandlers

type FunctionsHandlers struct {
	Handler   *functions.Handler
	Scheduler *functions.Scheduler
}

FunctionsHandlers groups edge functions handlers.

type GitHubInstallation

type GitHubInstallation struct {
	ID int `json:"id"`
}

GitHubInstallation represents a GitHub App installation

type GitHubIssue

type GitHubIssue struct {
	Number    int           `json:"number"`
	State     string        `json:"state"`
	Title     string        `json:"title"`
	Body      string        `json:"body"`
	HTMLURL   string        `json:"html_url"`
	Labels    []GitHubLabel `json:"labels"`
	Assignees []GitHubUser  `json:"assignees"`
	User      *GitHubUser   `json:"user,omitempty"`
	CreatedAt string        `json:"created_at"`
	UpdatedAt string        `json:"updated_at"`
}

GitHubIssue represents a GitHub issue

type GitHubLabel

type GitHubLabel struct {
	ID          int    `json:"id"`
	Name        string `json:"name"`
	Description string `json:"description"`
	Color       string `json:"color"`
}

GitHubLabel represents a GitHub label

type GitHubPullRequest

type GitHubPullRequest struct {
	Number  int        `json:"number"`
	State   string     `json:"state"`
	Title   string     `json:"title"`
	HTMLURL string     `json:"html_url"`
	Merged  bool       `json:"merged"`
	Base    *GitHubRef `json:"base,omitempty"`
	Head    *GitHubRef `json:"head,omitempty"`
}

GitHubPullRequest represents a GitHub pull request

type GitHubRef

type GitHubRef struct {
	Ref  string            `json:"ref"`
	SHA  string            `json:"sha"`
	Repo *GitHubRepository `json:"repo,omitempty"`
}

GitHubRef represents a Git reference (branch)

type GitHubRepository

type GitHubRepository struct {
	ID       int    `json:"id"`
	Name     string `json:"name"`
	FullName string `json:"full_name"`
	Private  bool   `json:"private"`
	HTMLURL  string `json:"html_url"`
}

GitHubRepository represents a GitHub repository

type GitHubUser

type GitHubUser struct {
	ID    int    `json:"id"`
	Login string `json:"login"`
}

GitHubUser represents a GitHub user

type GitHubWebhookHandler

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

GitHubWebhookHandler handles GitHub webhook events for database branching

func NewGitHubWebhookHandler

func NewGitHubWebhookHandler(manager *branching.Manager, router *branching.Router, cfg config.BranchingConfig) *GitHubWebhookHandler

NewGitHubWebhookHandler creates a new GitHub webhook handler

func (*GitHubWebhookHandler) GetWebhookURL

func (h *GitHubWebhookHandler) GetWebhookURL(baseURL string) string

GetWebhookURL returns the webhook URL for configuration

func (*GitHubWebhookHandler) HandleWebhook

func (h *GitHubWebhookHandler) HandleWebhook(c fiber.Ctx) error

HandleWebhook handles incoming GitHub webhook requests

type GitHubWebhookPayload

type GitHubWebhookPayload struct {
	Action       string              `json:"action"`
	PullRequest  *GitHubPullRequest  `json:"pull_request,omitempty"`
	Issue        *GitHubIssue        `json:"issue,omitempty"`
	Label        *GitHubLabel        `json:"label,omitempty"`
	Repository   *GitHubRepository   `json:"repository,omitempty"`
	Sender       *GitHubUser         `json:"sender,omitempty"`
	Installation *GitHubInstallation `json:"installation,omitempty"`
}

GitHubWebhookPayload represents the common fields in GitHub webhook payloads

type GrantBranchAccessRequest

type GrantBranchAccessRequest struct {
	UserID      string `json:"user_id"`
	AccessLevel string `json:"access_level"`
}

GrantBranchAccessRequest represents the request body for granting access

type GraphQLError

type GraphQLError struct {
	Message    string                 `json:"message"`
	Locations  []GraphQLErrorLocation `json:"locations,omitempty"`
	Path       []interface{}          `json:"path,omitempty"`
	Extensions map[string]interface{} `json:"extensions,omitempty"`
}

GraphQLError represents a GraphQL error

type GraphQLErrorLocation

type GraphQLErrorLocation struct {
	Line   int `json:"line"`
	Column int `json:"column"`
}

GraphQLErrorLocation represents the location of a GraphQL error in the query

type GraphQLFilterOperators

type GraphQLFilterOperators struct {
	Eq          bool // equals
	Neq         bool // not equals
	Gt          bool // greater than
	Gte         bool // greater than or equal
	Lt          bool // less than
	Lte         bool // less than or equal
	Like        bool // LIKE pattern match
	ILike       bool // case-insensitive LIKE
	In          bool // in array
	IsNull      bool // is null / is not null
	Contains    bool // JSON contains (@>)
	ContainedBy bool // JSON contained by (<@)
}

GraphQLFilterOperators defines available filter operators for each type

func GetFilterOperatorsForType

func GetFilterOperatorsForType(pgType string) GraphQLFilterOperators

GetFilterOperatorsForType returns the available filter operators for a PostgreSQL type

type GraphQLHandler

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

GraphQLHandler handles GraphQL HTTP requests

func NewGraphQLHandler

func NewGraphQLHandler(db *database.Connection, schemaCache *database.SchemaCache, cfg *config.GraphQLConfig, baseConfig *config.Config) *GraphQLHandler

NewGraphQLHandler creates a new GraphQL handler

func (*GraphQLHandler) HandleGraphQL

func (h *GraphQLHandler) HandleGraphQL(c fiber.Ctx) error

HandleGraphQL handles POST /api/v1/graphql requests

func (*GraphQLHandler) HandleIntrospection

func (h *GraphQLHandler) HandleIntrospection(c fiber.Ctx) error

HandleIntrospection handles GET /api/v1/graphql (returns introspection data)

func (*GraphQLHandler) InvalidateSchema

func (h *GraphQLHandler) InvalidateSchema()

InvalidateSchema invalidates the cached GraphQL schema

type GraphQLHandlers

type GraphQLHandlers struct {
	Handler *GraphQLHandler
}

GraphQLHandlers groups GraphQL handlers.

type GraphQLRequest

type GraphQLRequest struct {
	Query         string                 `json:"query"`
	OperationName string                 `json:"operationName,omitempty"`
	Variables     map[string]interface{} `json:"variables,omitempty"`
}

GraphQLRequest represents a GraphQL HTTP request body

type GraphQLResolverFactory

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

GraphQLResolverFactory creates resolvers for GraphQL queries and mutations

func NewGraphQLResolverFactory

func NewGraphQLResolverFactory(db *database.Connection, schemaCache *database.SchemaCache) *GraphQLResolverFactory

NewGraphQLResolverFactory creates a new resolver factory

type GraphQLResponse

type GraphQLResponse struct {
	Data   interface{}    `json:"data,omitempty"`
	Errors []GraphQLError `json:"errors,omitempty"`
}

GraphQLResponse represents a GraphQL HTTP response body

type GraphQLSchemaGenerator

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

GraphQLSchemaGenerator generates GraphQL schema from database tables

func NewGraphQLSchemaGenerator

func NewGraphQLSchemaGenerator(schemaCache *database.SchemaCache, db *database.Connection, introspectionOn bool) *GraphQLSchemaGenerator

NewGraphQLSchemaGenerator creates a new schema generator

func (*GraphQLSchemaGenerator) GetSchema

func (g *GraphQLSchemaGenerator) GetSchema(ctx context.Context) (*graphql.Schema, error)

GetSchema returns the current GraphQL schema, regenerating if needed

func (*GraphQLSchemaGenerator) InvalidateSchema

func (g *GraphQLSchemaGenerator) InvalidateSchema()

InvalidateSchema forces schema regeneration on next access

func (*GraphQLSchemaGenerator) SetResolverFactory

func (g *GraphQLSchemaGenerator) SetResolverFactory(factory *GraphQLResolverFactory)

SetResolverFactory sets the resolver factory for query execution

type HealthStatus

type HealthStatus struct {
	Status  string `json:"status"` // "healthy", "degraded", "unhealthy"
	Message string `json:"message,omitempty"`
	Latency int64  `json:"latency_ms,omitempty"`
}

HealthStatus represents the health status of a component

type InitChunkedUploadRequest

type InitChunkedUploadRequest struct {
	Path         string            `json:"path"`
	TotalSize    int64             `json:"total_size"`
	ChunkSize    int64             `json:"chunk_size,omitempty"`
	ContentType  string            `json:"content_type,omitempty"`
	Metadata     map[string]string `json:"metadata,omitempty"`
	CacheControl string            `json:"cache_control,omitempty"`
}

InitChunkedUploadRequest represents the request body for initializing a chunked upload

type InitialSetupRequest

type InitialSetupRequest struct {
	Email      string `json:"email"`
	Password   string `json:"password"`
	Name       string `json:"name"`
	SetupToken string `json:"setup_token"`
}

InitialSetupRequest represents the initial setup request

type InitialSetupResponse

type InitialSetupResponse struct {
	User         *auth.DashboardUser `json:"user"`
	AccessToken  string              `json:"access_token"`
	RefreshToken string              `json:"refresh_token"`
	ExpiresIn    int64               `json:"expires_in"`
}

InitialSetupResponse represents the initial setup response

type InstanceSettingsHandler

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

func NewInstanceSettingsHandler

func NewInstanceSettingsHandler(settingsSvc *settings.UnifiedService) *InstanceSettingsHandler

func (*InstanceSettingsHandler) GetInstanceSettings

func (h *InstanceSettingsHandler) GetInstanceSettings(c fiber.Ctx) error

func (*InstanceSettingsHandler) GetOverridableSettings

func (h *InstanceSettingsHandler) GetOverridableSettings(c fiber.Ctx) error

func (*InstanceSettingsHandler) UpdateInstanceSettings

func (h *InstanceSettingsHandler) UpdateInstanceSettings(c fiber.Ctx) error

func (*InstanceSettingsHandler) UpdateOverridableSettings

func (h *InstanceSettingsHandler) UpdateOverridableSettings(c fiber.Ctx) error

type InstanceSettingsResponse

type InstanceSettingsResponse struct {
	Settings            map[string]any `json:"settings"`
	OverridableSettings []string       `json:"overridable_settings,omitempty"`
}

type InternalAIHandler

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

InternalAIHandler handles AI requests from custom MCP tools, edge functions, and jobs.

func NewInternalAIHandler

func NewInternalAIHandler(aiStorage *ai.Storage, embeddingService *ai.EmbeddingService, defaultProvider string) *InternalAIHandler

NewInternalAIHandler creates a new InternalAIHandler.

func (*InternalAIHandler) HandleChat

func (h *InternalAIHandler) HandleChat(c fiber.Ctx) error

HandleChat handles POST /api/v1/internal/ai/chat This endpoint allows custom MCP tools, edge functions, and jobs to make AI completions.

func (*InternalAIHandler) HandleEmbed

func (h *InternalAIHandler) HandleEmbed(c fiber.Ctx) error

HandleEmbed handles POST /api/v1/internal/ai/embed This endpoint allows custom MCP tools, edge functions, and jobs to generate embeddings.

func (*InternalAIHandler) HandleListProviders

func (h *InternalAIHandler) HandleListProviders(c fiber.Ctx) error

HandleListProviders handles GET /api/v1/internal/ai/providers This endpoint lists available AI providers.

type InternalChatMessage

type InternalChatMessage struct {
	Role    string `json:"role"`
	Content string `json:"content"`
}

InternalChatMessage represents a message in the chat.

type InternalChatRequest

type InternalChatRequest struct {
	Messages    []InternalChatMessage `json:"messages"`
	Model       string                `json:"model,omitempty"`
	Provider    string                `json:"provider,omitempty"`
	MaxTokens   int                   `json:"max_tokens,omitempty"`
	Temperature *float64              `json:"temperature,omitempty"`
}

InternalChatRequest represents a chat completion request.

type InternalChatResponse

type InternalChatResponse struct {
	Content      string `json:"content"`
	Model        string `json:"model"`
	FinishReason string `json:"finish_reason,omitempty"`
	Usage        *struct {
		PromptTokens     int `json:"prompt_tokens"`
		CompletionTokens int `json:"completion_tokens"`
		TotalTokens      int `json:"total_tokens"`
	} `json:"usage,omitempty"`
}

InternalChatResponse represents a chat completion response.

type InternalEmbedRequest

type InternalEmbedRequest struct {
	Text     string `json:"text"`
	Provider string `json:"provider,omitempty"`
}

InternalEmbedRequest represents an embedding request.

type InternalEmbedResponse

type InternalEmbedResponse struct {
	Embedding []float32 `json:"embedding"`
	Model     string    `json:"model"`
}

InternalEmbedResponse represents an embedding response.

type InternalSchemaHandler

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

InternalSchemaHandler handles internal schema management endpoints

func NewInternalSchemaHandler

func NewInternalSchemaHandler() *InternalSchemaHandler

NewInternalSchemaHandler creates a new internal schema handler

func (*InternalSchemaHandler) ApplySchema

func (h *InternalSchemaHandler) ApplySchema(c fiber.Ctx) error

ApplySchema handles POST /api/v1/admin/internal-schema/apply

func (*InternalSchemaHandler) DumpSchema

func (h *InternalSchemaHandler) DumpSchema(c fiber.Ctx) error

DumpSchema handles POST /api/v1/admin/internal-schema/dump

func (*InternalSchemaHandler) GetSchemaStatus

func (h *InternalSchemaHandler) GetSchemaStatus(c fiber.Ctx) error

GetSchemaStatus handles GET /api/v1/admin/internal-schema/status

func (*InternalSchemaHandler) Initialize

func (h *InternalSchemaHandler) Initialize(cfg *config.Config, db *database.Connection)

Initialize initializes the handler with dependencies

func (*InternalSchemaHandler) MigrateSchema

func (h *InternalSchemaHandler) MigrateSchema(c fiber.Ctx) error

MigrateSchema handles POST /api/v1/admin/internal-schema/migrate

func (*InternalSchemaHandler) PlanSchema

func (h *InternalSchemaHandler) PlanSchema(c fiber.Ctx) error

PlanSchema handles POST /api/v1/admin/internal-schema/plan

func (*InternalSchemaHandler) String

func (h *InternalSchemaHandler) String() string

func (*InternalSchemaHandler) ValidateSchema

func (h *InternalSchemaHandler) ValidateSchema(c fiber.Ctx) error

ValidateSchema handles GET /api/v1/admin/internal-schema/validate

type InvitationHandler

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

func NewInvitationHandler

func NewInvitationHandler(
	invitationService *auth.InvitationService,
	dashboardAuth *auth.DashboardAuthService,
	emailService email.Service,
	baseURL string,
) *InvitationHandler

func (*InvitationHandler) AcceptInvitation

func (h *InvitationHandler) AcceptInvitation(c fiber.Ctx) error

func (*InvitationHandler) CreateInvitation

func (h *InvitationHandler) CreateInvitation(c fiber.Ctx) error

func (*InvitationHandler) ListInvitations

func (h *InvitationHandler) ListInvitations(c fiber.Ctx) error

func (*InvitationHandler) RevokeInvitation

func (h *InvitationHandler) RevokeInvitation(c fiber.Ctx) error

func (*InvitationHandler) ValidateInvitation

func (h *InvitationHandler) ValidateInvitation(c fiber.Ctx) error

type JobsHandlers

type JobsHandlers struct {
	Handler   *jobs.Handler
	Manager   *jobs.Manager
	Scheduler *jobs.Scheduler
}

JobsHandlers groups background jobs handlers.

type LogEntry

type LogEntry struct {
	Timestamp time.Time              `json:"timestamp"`
	Level     string                 `json:"level"`
	Message   string                 `json:"message"`
	Module    string                 `json:"module,omitempty"`
	Error     string                 `json:"error,omitempty"`
	Fields    map[string]interface{} `json:"fields,omitempty"`
}

LogEntry represents a log entry

type LogQueryResponse

type LogQueryResponse struct {
	Entries    []*storage.LogEntry `json:"entries"`
	TotalCount int64               `json:"total_count"`
	HasMore    bool                `json:"has_more"`
}

LogQueryResponse represents the response from log query

type LogStatsResponse

type LogStatsResponse struct {
	TotalEntries      int64            `json:"total_entries"`
	EntriesByCategory map[string]int64 `json:"entries_by_category"`
	EntriesByLevel    map[string]int64 `json:"entries_by_level"`
	OldestEntry       *time.Time       `json:"oldest_entry,omitempty"`
	NewestEntry       *time.Time       `json:"newest_entry,omitempty"`
}

LogStatsResponse represents the response from log stats

type LoggingHandler

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

LoggingHandler handles logging-related API endpoints

func NewLoggingHandler

func NewLoggingHandler(loggingService *logging.Service) *LoggingHandler

NewLoggingHandler creates a new logging handler

func (*LoggingHandler) FlushLogs

func (h *LoggingHandler) FlushLogs(c fiber.Ctx) error

FlushLogs handles POST /admin/logs/flush @Summary Flush buffered logs @Description Force flush any buffered log entries to storage @Tags Admin/Logging @Accept json @Produce json @Success 200 {object} SuccessResponse @Failure 401 {object} ErrorResponse @Failure 500 {object} ErrorResponse @Router /admin/logs/flush [post]

func (*LoggingHandler) GenerateTestLogs

func (h *LoggingHandler) GenerateTestLogs(c fiber.Ctx) error

GenerateTestLogs handles POST /admin/logs/test @Summary Generate test logs @Description Generates test log entries for diagnostic purposes @Tags Admin/Logging @Accept json @Produce json @Success 200 {object} SuccessResponse @Failure 401 {object} ErrorResponse @Failure 500 {object} ErrorResponse @Router /admin/logs/test [post]

func (*LoggingHandler) GetExecutionLogs

func (h *LoggingHandler) GetExecutionLogs(c fiber.Ctx) error

GetExecutionLogs handles GET /admin/logs/executions/:execution_id @Summary Get execution logs @Description Get logs for a specific execution @Tags Admin/Logging @Accept json @Produce json @Param execution_id path string true "Execution ID" @Param after_line query int false "Return logs after this line number" @Success 200 {object} ExecutionLogsResponse @Failure 400 {object} ErrorResponse @Failure 401 {object} ErrorResponse @Failure 500 {object} ErrorResponse @Router /admin/logs/executions/{execution_id} [get]

func (*LoggingHandler) GetLogStats

func (h *LoggingHandler) GetLogStats(c fiber.Ctx) error

GetLogStats handles GET /admin/logs/stats @Summary Get log statistics @Description Get statistics about stored logs @Tags Admin/Logging @Accept json @Produce json @Success 200 {object} LogStatsResponse @Failure 401 {object} ErrorResponse @Failure 500 {object} ErrorResponse @Router /admin/logs/stats [get]

func (*LoggingHandler) QueryLogs

func (h *LoggingHandler) QueryLogs(c fiber.Ctx) error

QueryLogs handles GET /admin/logs @Summary Query logs @Description Query logs with filters @Tags Admin/Logging @Accept json @Produce json @Param category query string false "Log category (system, http, security, execution, ai, custom)" @Param custom_category query string false "Custom category name (only used when category=custom)" @Param level query string false "Log levels (comma-separated: debug, info, warn, error)" @Param component query string false "Component name" @Param request_id query string false "Request ID" @Param trace_id query string false "Trace ID" @Param user_id query string false "User ID" @Param execution_id query string false "Execution ID" @Param search query string false "Search text in message" @Param start_time query string false "Start time (RFC3339)" @Param end_time query string false "End time (RFC3339)" @Param limit query int false "Max results (default 100)" @Param offset query int false "Offset for pagination" @Param sort_asc query bool false "Sort ascending by timestamp" @Param hide_static_assets query bool false "Hide HTTP logs for static assets (js, css, images, fonts)" @Success 200 {object} LogQueryResponse @Failure 400 {object} ErrorResponse @Failure 401 {object} ErrorResponse @Failure 500 {object} ErrorResponse @Router /admin/logs [get]

type LoggingHandlers

type LoggingHandlers struct {
	Service   *logging.Service
	Handler   *LoggingHandler
	Retention *logging.RetentionService
}

LoggingHandlers groups logging handlers.

type MCPHandlers

type MCPHandlers struct {
	Handler       *mcp.Handler
	OAuth         *MCPOAuthHandler
	CustomManager *custom.Manager
	CustomHandler *CustomMCPHandler
}

MCPHandlers groups Model Context Protocol handlers.

type MCPOAuthHandler

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

func NewMCPOAuthHandler

func NewMCPOAuthHandler(db *database.Connection, cfg *config.MCPConfig, authService *auth.Service, baseURL, publicURL string) *MCPOAuthHandler

func (*MCPOAuthHandler) HandleAuthorizationServerMetadata

func (h *MCPOAuthHandler) HandleAuthorizationServerMetadata(c fiber.Ctx) error

func (*MCPOAuthHandler) HandleAuthorize

func (h *MCPOAuthHandler) HandleAuthorize(c fiber.Ctx) error

func (*MCPOAuthHandler) HandleAuthorizeConsent

func (h *MCPOAuthHandler) HandleAuthorizeConsent(c fiber.Ctx) error

func (*MCPOAuthHandler) HandleClientRegistration

func (h *MCPOAuthHandler) HandleClientRegistration(c fiber.Ctx) error

func (*MCPOAuthHandler) HandleProtectedResourceMetadata

func (h *MCPOAuthHandler) HandleProtectedResourceMetadata(c fiber.Ctx) error

func (*MCPOAuthHandler) HandleRevoke

func (h *MCPOAuthHandler) HandleRevoke(c fiber.Ctx) error

func (*MCPOAuthHandler) HandleToken

func (h *MCPOAuthHandler) HandleToken(c fiber.Ctx) error

func (*MCPOAuthHandler) ValidateAccessToken

func (h *MCPOAuthHandler) ValidateAccessToken(c fiber.Ctx, token string) (clientID string, userID *string, scopes []string, err error)

type MailgunSettings

type MailgunSettings struct {
	APIKey   string `json:"api_key,omitempty"` // Omit in responses for security
	Domain   string `json:"domain"`
	EURegion bool   `json:"eu_region"`
}

MailgunSettings contains Mailgun configuration

type MetricsComponents

type MetricsComponents struct {
	Metrics   *observability.Metrics
	Server    *observability.MetricsServer
	StartTime time.Time
	StopChan  chan struct{}
}

MetricsComponents groups metrics-related components.

type MiddlewareComponents

type MiddlewareComponents struct {
	Tenant      fiber.Handler
	TenantDB    fiber.Handler
	Branch      fiber.Handler
	Idempotency *middleware.IdempotencyMiddleware
}

MiddlewareComponents groups middleware-related components.

type MonitoringHandler

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

MonitoringHandler handles system monitoring and health check endpoints

func NewMonitoringHandler

func NewMonitoringHandler(db *database.Connection, realtimeHandler *realtime.RealtimeHandler, storageProvider storage.Provider) *MonitoringHandler

NewMonitoringHandler creates a new monitoring handler

func (*MonitoringHandler) GetHealth

func (h *MonitoringHandler) GetHealth(c fiber.Ctx) error

GetHealth returns the health status of all system components Admin-only endpoint - non-admin users receive 403 Forbidden

func (*MonitoringHandler) GetLogs

func (h *MonitoringHandler) GetLogs(c fiber.Ctx) error

GetLogs returns recent application logs Admin-only endpoint - non-admin users receive 403 Forbidden

func (*MonitoringHandler) GetMetrics

func (h *MonitoringHandler) GetMetrics(c fiber.Ctx) error

GetMetrics returns system metrics Admin-only endpoint - non-admin users receive 403 Forbidden

func (*MonitoringHandler) SetJobsStorage

func (h *MonitoringHandler) SetJobsStorage(jobsStorage *jobs.Storage)

SetJobsStorage sets the jobs storage for job health monitoring

func (*MonitoringHandler) SetLoggingService

func (h *MonitoringHandler) SetLoggingService(loggingService *logging.Service)

SetLoggingService sets the logging service for log queries

type MonitoringHandlers

type MonitoringHandlers struct {
	Handler *MonitoringHandler
}

MonitoringHandlers groups monitoring handlers.

type OAuthHandler

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

OAuthHandler handles OAuth authentication flow

func NewOAuthHandler

func NewOAuthHandler(db *database.Connection, authSvc *auth.Service, jwtManager *auth.JWTManager, baseURL, encryptionKey string, configProviders []config.OAuthProviderConfig) *OAuthHandler

NewOAuthHandler creates a new OAuth handler

func (*OAuthHandler) Authorize

func (h *OAuthHandler) Authorize(c fiber.Ctx) error

Authorize initiates the OAuth flow GET /api/v1/auth/oauth/:provider/authorize

func (*OAuthHandler) Callback

func (h *OAuthHandler) Callback(c fiber.Ctx) error

Callback handles the OAuth callback GET /api/v1/auth/oauth/:provider/callback

func (*OAuthHandler) GetAndValidateState

func (h *OAuthHandler) GetAndValidateState(state string) (*auth.StateMetadata, bool)

GetAndValidateState validates and consumes a state token, returning its metadata Returns the state metadata and true if valid, nil and false if not found or expired This is used by the dashboard OAuth callback to validate states created by the app OAuth authorize endpoint

func (*OAuthHandler) GetProviderToken

func (h *OAuthHandler) GetProviderToken(c fiber.Ctx) error

GetProviderToken retrieves the OAuth provider tokens for the authenticated user This endpoint allows users to retrieve their stored OAuth tokens to make API calls to the provider (e.g., Google Drive API). GET /api/v1/auth/oauth/:provider/token

func (*OAuthHandler) ListEnabledProviders

func (h *OAuthHandler) ListEnabledProviders(c fiber.Ctx) error

ListEnabledProviders lists all enabled OAuth providers for app login GET /api/v1/auth/oauth/providers

func (*OAuthHandler) Logout

func (h *OAuthHandler) Logout(c fiber.Ctx) error

Logout initiates OAuth Single Logout POST /api/v1/auth/oauth/:provider/logout

func (*OAuthHandler) LogoutCallback

func (h *OAuthHandler) LogoutCallback(c fiber.Ctx) error

LogoutCallback handles the callback after OIDC logout GET /api/v1/auth/oauth/:provider/logout/callback

func (*OAuthHandler) Stop

func (h *OAuthHandler) Stop()

Stop stops the cleanup goroutines

type OAuthProvider

type OAuthProvider struct {
	ID                  uuid.UUID           `json:"id"`
	ProviderName        string              `json:"provider_name"`
	DisplayName         string              `json:"display_name"`
	Enabled             bool                `json:"enabled"`
	ClientID            string              `json:"client_id"`
	ClientSecret        string              `json:"client_secret,omitempty"` // Omitted in GET responses
	HasSecret           bool                `json:"has_secret"`              // Indicates if a client secret is set
	RedirectURL         string              `json:"redirect_url"`
	Scopes              []string            `json:"scopes"`
	IsCustom            bool                `json:"is_custom"`
	AuthorizationURL    *string             `json:"authorization_url,omitempty"`
	TokenURL            *string             `json:"token_url,omitempty"`
	UserInfoURL         *string             `json:"user_info_url,omitempty"`
	RevocationEndpoint  *string             `json:"revocation_endpoint,omitempty"`  // OAuth 2.0 Token Revocation (RFC 7009)
	EndSessionEndpoint  *string             `json:"end_session_endpoint,omitempty"` // OIDC RP-Initiated Logout
	AllowDashboardLogin bool                `json:"allow_dashboard_login"`
	AllowAppLogin       bool                `json:"allow_app_login"`
	RequiredClaims      map[string][]string `json:"required_claims,omitempty"`
	DeniedClaims        map[string][]string `json:"denied_claims,omitempty"`
	Source              string              `json:"source,omitempty"` // "database" or "config"
	TenantID            *string             `json:"tenant_id,omitempty"`
	CreatedAt           time.Time           `json:"created_at"`
	UpdatedAt           time.Time           `json:"updated_at"`
}

OAuthProvider represents an OAuth provider configuration

type OAuthProviderHandler

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

OAuthProviderHandler handles OAuth provider configuration management

func NewOAuthProviderHandler

func NewOAuthProviderHandler(db *database.Connection, settingsCache *auth.SettingsCache, encryptionKey, baseURL string, configProviders []config.OAuthProviderConfig) *OAuthProviderHandler

NewOAuthProviderHandler creates a new OAuth provider handler

func (*OAuthProviderHandler) CreateOAuthProvider

func (h *OAuthProviderHandler) CreateOAuthProvider(c fiber.Ctx) error

CreateOAuthProvider creates a new OAuth provider

func (*OAuthProviderHandler) DeleteOAuthProvider

func (h *OAuthProviderHandler) DeleteOAuthProvider(c fiber.Ctx) error

DeleteOAuthProvider deletes an OAuth provider

func (*OAuthProviderHandler) EncryptExistingSecrets

func (h *OAuthProviderHandler) EncryptExistingSecrets(ctx context.Context) error

EncryptExistingSecrets encrypts any plaintext client secrets in the database. This should be called on startup to migrate existing secrets to encrypted format.

func (*OAuthProviderHandler) GetAuthSettings

func (h *OAuthProviderHandler) GetAuthSettings(c fiber.Ctx) error

GetAuthSettings retrieves authentication settings

func (*OAuthProviderHandler) GetOAuthProvider

func (h *OAuthProviderHandler) GetOAuthProvider(c fiber.Ctx) error

GetOAuthProvider gets a single OAuth provider by ID

func (*OAuthProviderHandler) ListOAuthProviders

func (h *OAuthProviderHandler) ListOAuthProviders(c fiber.Ctx) error

ListOAuthProviders lists all OAuth providers

func (*OAuthProviderHandler) UpdateAuthSettings

func (h *OAuthProviderHandler) UpdateAuthSettings(c fiber.Ctx) error

UpdateAuthSettings updates authentication settings

func (*OAuthProviderHandler) UpdateOAuthProvider

func (h *OAuthProviderHandler) UpdateOAuthProvider(c fiber.Ctx) error

UpdateOAuthProvider updates an existing OAuth provider

type OAuthProviderPublic

type OAuthProviderPublic struct {
	Provider     string `json:"provider"`
	DisplayName  string `json:"display_name"`
	AuthorizeURL string `json:"authorize_url"`
}

OAuthProviderPublic represents public OAuth provider information

type OpenAPIComponents

type OpenAPIComponents struct {
	Schemas         map[string]interface{} `json:"schemas,omitempty"`
	SecuritySchemes map[string]interface{} `json:"securitySchemes,omitempty"`
}

type OpenAPIHandler

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

OpenAPIHandler handles OpenAPI spec generation

func NewOpenAPIHandler

func NewOpenAPIHandler(db *database.Connection) *OpenAPIHandler

NewOpenAPIHandler creates a new OpenAPI handler

func (*OpenAPIHandler) GetOpenAPISpec

func (h *OpenAPIHandler) GetOpenAPISpec(c fiber.Ctx) error

GetOpenAPISpec generates and returns the OpenAPI specification Admin users get full spec with database schema; non-admin users get minimal spec

type OpenAPIInfo

type OpenAPIInfo struct {
	Title       string `json:"title"`
	Description string `json:"description"`
	Version     string `json:"version"`
}

type OpenAPIMedia

type OpenAPIMedia struct {
	Schema interface{} `json:"schema"`
}

type OpenAPIOperation

type OpenAPIOperation struct {
	Summary     string                     `json:"summary,omitempty"`
	Description string                     `json:"description,omitempty"`
	OperationID string                     `json:"operationId,omitempty"`
	Tags        []string                   `json:"tags,omitempty"`
	Parameters  []OpenAPIParameter         `json:"parameters,omitempty"`
	RequestBody *OpenAPIRequestBody        `json:"requestBody,omitempty"`
	Responses   map[string]OpenAPIResponse `json:"responses"`
	Security    []map[string][]string      `json:"security,omitempty"`
}

type OpenAPIParameter

type OpenAPIParameter struct {
	Name        string      `json:"name"`
	In          string      `json:"in"`
	Description string      `json:"description,omitempty"`
	Required    bool        `json:"required,omitempty"`
	Schema      interface{} `json:"schema"`
}

type OpenAPIPath

type OpenAPIPath map[string]OpenAPIOperation

type OpenAPIRequestBody

type OpenAPIRequestBody struct {
	Description string                  `json:"description,omitempty"`
	Required    bool                    `json:"required,omitempty"`
	Content     map[string]OpenAPIMedia `json:"content"`
}

type OpenAPIResponse

type OpenAPIResponse struct {
	Description string                  `json:"description"`
	Content     map[string]OpenAPIMedia `json:"content,omitempty"`
}

type OpenAPIServer

type OpenAPIServer struct {
	URL         string `json:"url"`
	Description string `json:"description"`
}

type OpenAPISpec

type OpenAPISpec struct {
	OpenAPI    string                 `json:"openapi"`
	Info       OpenAPIInfo            `json:"info"`
	Servers    []OpenAPIServer        `json:"servers"`
	Paths      map[string]OpenAPIPath `json:"paths"`
	Components OpenAPIComponents      `json:"components"`
}

OpenAPISpec represents the OpenAPI 3.0 specification

type OrderBy

type OrderBy = query.OrderBy

OrderBy is an alias for query.OrderBy for backward compatibility

type OverrideInfo

type OverrideInfo struct {
	IsOverridden bool   `json:"is_overridden"`
	EnvVar       string `json:"env_var,omitempty"`
}

OverrideInfo indicates if a setting is overridden by environment variable

type ParseOptions

type ParseOptions struct {
	// BypassMaxTotalResults skips the max_total_results enforcement.
	// Use for admin/dashboard requests that should have unlimited access.
	BypassMaxTotalResults bool
}

ParseOptions configures query parsing behavior

type Policy

type Policy struct {
	Schema     string   `json:"schema"`
	Table      string   `json:"table"`
	PolicyName string   `json:"policy_name"`
	Permissive string   `json:"permissive"` // "PERMISSIVE" or "RESTRICTIVE"
	Roles      []string `json:"roles"`
	Command    string   `json:"command"`    // ALL, SELECT, INSERT, UPDATE, DELETE
	Using      *string  `json:"using"`      // USING expression
	WithCheck  *string  `json:"with_check"` // WITH CHECK expression
}

Policy represents a PostgreSQL RLS policy

type PostQueryBetweenFilter

type PostQueryBetweenFilter struct {
	Column  string      `json:"column"`
	Min     interface{} `json:"min"`
	Max     interface{} `json:"max"`
	Negated bool        `json:"negated"`
}

PostQueryBetweenFilter represents a between filter in the POST body

type PostQueryFilter

type PostQueryFilter struct {
	Column   string      `json:"column"`
	Operator string      `json:"operator"`
	Value    interface{} `json:"value"`
}

PostQueryFilter represents a single filter in the POST body

type PostQueryOrderBy

type PostQueryOrderBy struct {
	Column    string `json:"column"`
	Direction string `json:"direction"`
	Nulls     string `json:"nulls,omitempty"`
}

PostQueryOrderBy represents an order clause in the POST body

type PostQueryRequest

type PostQueryRequest struct {
	Select         string                   `json:"select,omitempty"`
	Filters        []PostQueryFilter        `json:"filters,omitempty"`
	OrFilters      []string                 `json:"orFilters,omitempty"`
	AndFilters     []string                 `json:"andFilters,omitempty"`
	BetweenFilters []PostQueryBetweenFilter `json:"betweenFilters,omitempty"`
	Order          []PostQueryOrderBy       `json:"order,omitempty"`
	Limit          *int                     `json:"limit,omitempty"`
	Offset         *int                     `json:"offset,omitempty"`
	Count          string                   `json:"count,omitempty"`
	GroupBy        []string                 `json:"groupBy,omitempty"`
}

PostQueryRequest represents the JSON body for POST-based queries Used when query parameters would exceed URL length limits

type ProviderTokenResponse

type ProviderTokenResponse struct {
	Provider     string   `json:"provider"`
	AccessToken  string   `json:"access_token"`
	RefreshToken string   `json:"refresh_token,omitempty"`
	TokenExpiry  string   `json:"token_expiry"`
	ExpiresIn    int      `json:"expires_in"`
	IDToken      string   `json:"id_token,omitempty"`
	Scopes       []string `json:"scopes,omitempty"`
	TokenType    string   `json:"token_type"`
}

ProviderTokenResponse represents the response for getting provider tokens

type QueryBuilder

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

QueryBuilder provides a fluent interface for building SQL queries. It separates query construction from execution, enabling unit testing of query generation without database access.

func NewQueryBuilder

func NewQueryBuilder(schema, table string) *QueryBuilder

NewQueryBuilder creates a new QueryBuilder for the given schema and table.

func (*QueryBuilder) BuildCount

func (qb *QueryBuilder) BuildCount() (string, []interface{})

BuildCount builds a COUNT query and returns the SQL string and arguments.

func (*QueryBuilder) BuildDelete

func (qb *QueryBuilder) BuildDelete() (string, []interface{})

BuildDelete builds a DELETE query and returns the SQL string and arguments.

func (*QueryBuilder) BuildInsert

func (qb *QueryBuilder) BuildInsert(data map[string]interface{}) (string, []interface{})

BuildInsert builds an INSERT query and returns the SQL string, arguments, and column order (for value mapping).

func (*QueryBuilder) BuildSelect

func (qb *QueryBuilder) BuildSelect() (string, []interface{})

BuildSelect builds a SELECT query and returns the SQL string and arguments.

func (*QueryBuilder) BuildUpdate

func (qb *QueryBuilder) BuildUpdate(data map[string]interface{}) (string, []interface{})

BuildUpdate builds an UPDATE query and returns the SQL string and arguments.

func (*QueryBuilder) WithColumns

func (qb *QueryBuilder) WithColumns(columns []string) *QueryBuilder

WithColumns sets the columns to select.

func (*QueryBuilder) WithCursor

func (qb *QueryBuilder) WithCursor(cursor string, cursorColumn string) error

WithCursor sets cursor pagination parameters. The cursor is a base64-encoded string containing the last row's value. cursorColumn overrides the column in the cursor (optional).

func (*QueryBuilder) WithFilters

func (qb *QueryBuilder) WithFilters(filters []Filter) *QueryBuilder

WithFilters sets the WHERE conditions.

func (*QueryBuilder) WithGroupBy

func (qb *QueryBuilder) WithGroupBy(columns []string) *QueryBuilder

WithGroupBy sets the GROUP BY columns.

func (*QueryBuilder) WithLimit

func (qb *QueryBuilder) WithLimit(limit int) *QueryBuilder

WithLimit sets the LIMIT clause.

func (*QueryBuilder) WithOffset

func (qb *QueryBuilder) WithOffset(offset int) *QueryBuilder

WithOffset sets the OFFSET clause.

func (*QueryBuilder) WithOrder

func (qb *QueryBuilder) WithOrder(order []OrderBy) *QueryBuilder

WithOrder sets the ORDER BY clauses.

func (*QueryBuilder) WithReturning

func (qb *QueryBuilder) WithReturning(columns []string) *QueryBuilder

WithReturning sets the RETURNING clause columns.

type QueryParams

type QueryParams struct {
	Select         []string           // Fields to select
	Filters        []Filter           // WHERE conditions
	Order          []OrderBy          // ORDER BY clauses
	Limit          *int               // LIMIT clause
	Offset         *int               // OFFSET clause
	Cursor         *string            // Base64-encoded cursor for keyset pagination
	CursorColumn   *string            // Column to use for cursor (default: primary key)
	Embedded       []EmbeddedRelation // Relations to embed
	Count          CountType          // Count preference
	Aggregations   []Aggregation      // Aggregation functions
	GroupBy        []string           // GROUP BY columns
	TruncateLength *int               // Truncate text columns to this length (for table browsing)
	// contains filtered or unexported fields
}

QueryParams represents parsed query parameters for REST API

func (*QueryParams) BuildGroupByClause

func (params *QueryParams) BuildGroupByClause() string

BuildGroupByClause builds the GROUP BY clause

func (*QueryParams) BuildSelectClause

func (params *QueryParams) BuildSelectClause(tableName string) string

BuildSelectClause builds the SELECT clause, including aggregations

func (*QueryParams) ToSQL

func (params *QueryParams) ToSQL(tableName string) (string, []interface{})

ToSQL converts QueryParams to SQL WHERE, ORDER BY, LIMIT, OFFSET clauses

type QueryParser

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

QueryParser parses PostgREST-compatible query parameters

func NewQueryParser

func NewQueryParser(cfg *config.Config) *QueryParser

NewQueryParser creates a new query parser

func (*QueryParser) Parse

func (qp *QueryParser) Parse(values url.Values) (*QueryParams, error)

Parse parses URL query parameters into QueryParams with default options

func (*QueryParser) ParseWithOptions

func (qp *QueryParser) ParseWithOptions(values url.Values, opts ParseOptions) (*QueryParams, error)

ParseWithOptions parses URL query parameters into QueryParams with custom options

type QuotaHandler

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

QuotaHandler handles quota-related HTTP requests

func NewQuotaHandler

func NewQuotaHandler(quotaService *ai.QuotaService, userMgmtService *auth.UserManagementService) *QuotaHandler

NewQuotaHandler creates a new quota handler

func (*QuotaHandler) GetUserQuota

func (h *QuotaHandler) GetUserQuota(c fiber.Ctx) error

GetUserQuota returns quota information for a specific user GET /api/v1/admin/users/:id/quota

func (*QuotaHandler) ListUsersWithQuotas

func (h *QuotaHandler) ListUsersWithQuotas(c fiber.Ctx) error

ListUsersWithQuotas returns all users with their quota information GET /api/v1/admin/users

func (*QuotaHandler) SetUserQuota

func (h *QuotaHandler) SetUserQuota(c fiber.Ctx) error

SetUserQuota sets quota limits for a specific user PUT /api/v1/admin/users/:id/quota

type QuotaHandlers

type QuotaHandlers struct {
	Handler *QuotaHandler
}

QuotaHandlers groups quota handlers.

type RESTHandler

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

RESTHandler handles dynamic REST API endpoints

func NewRESTHandler

func NewRESTHandler(db *database.Connection, parser *QueryParser, schemaCache *database.SchemaCache, cfg *config.Config) *RESTHandler

NewRESTHandler creates a new REST handler

func (*RESTHandler) BuildFullTablePath

func (h *RESTHandler) BuildFullTablePath(table database.TableInfo) string

BuildFullTablePath builds the full REST API path for a table (including /api/v1/tables prefix) Used for client consumption in API responses

func (*RESTHandler) BuildTablePath

func (h *RESTHandler) BuildTablePath(table database.TableInfo) string

BuildTablePath builds the REST API path for a table (relative to router group) Used for registering routes on the /api/v1/tables router group

func (*RESTHandler) HandleDynamicQuery

func (h *RESTHandler) HandleDynamicQuery(c fiber.Ctx) error

HandleDynamicQuery handles POST-based query for complex filters

func (*RESTHandler) HandleDynamicTable

func (h *RESTHandler) HandleDynamicTable(c fiber.Ctx) error

HandleDynamicTable handles REST operations for any table via dynamic lookup Supports GET (list), POST (create), PATCH (batch update), DELETE (batch delete)

func (*RESTHandler) HandleDynamicTableById

func (h *RESTHandler) HandleDynamicTableById(c fiber.Ctx) error

HandleDynamicTableById handles REST operations for a specific record Supports GET (fetch), PUT (replace), PATCH (update), DELETE (remove)

func (*RESTHandler) HandleGetTables

func (h *RESTHandler) HandleGetTables(c fiber.Ctx) error

HandleGetTables returns metadata about available tables

func (*RESTHandler) RegisterTableRoutes

func (h *RESTHandler) RegisterTableRoutes(router fiber.Router, table database.TableInfo)

RegisterTableRoutes registers REST routes for a table

func (*RESTHandler) RegisterViewRoutes

func (h *RESTHandler) RegisterViewRoutes(router fiber.Router, view database.TableInfo)

RegisterViewRoutes registers read-only REST routes for a database view

func (*RESTHandler) SchemaCache

func (h *RESTHandler) SchemaCache() *database.SchemaCache

SchemaCache returns the schema cache for external access (e.g., migrations handler)

type RLSContext

type RLSContext struct {
	UserID string
	Role   string
	Claims map[string]interface{}
}

RLSContext contains information needed for Row Level Security

type RPCHandlers

type RPCHandlers struct {
	Handler   *rpc.Handler
	Scheduler *rpc.Scheduler
}

RPCHandlers groups RPC handlers.

type RealtimeAdminHandler

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

RealtimeAdminHandler handles realtime enablement for user tables

func NewRealtimeAdminHandler

func NewRealtimeAdminHandler(db *database.Connection) *RealtimeAdminHandler

NewRealtimeAdminHandler creates a new realtime admin handler

func (*RealtimeAdminHandler) HandleDisableRealtime

func (h *RealtimeAdminHandler) HandleDisableRealtime(c fiber.Ctx) error

HandleDisableRealtime disables realtime on a table

func (*RealtimeAdminHandler) HandleEnableRealtime

func (h *RealtimeAdminHandler) HandleEnableRealtime(c fiber.Ctx) error

HandleEnableRealtime enables realtime on a table

func (*RealtimeAdminHandler) HandleGetRealtimeStatus

func (h *RealtimeAdminHandler) HandleGetRealtimeStatus(c fiber.Ctx) error

HandleGetRealtimeStatus gets the realtime status for a specific table

func (*RealtimeAdminHandler) HandleListRealtimeTables

func (h *RealtimeAdminHandler) HandleListRealtimeTables(c fiber.Ctx) error

HandleListRealtimeTables lists all realtime-enabled tables

func (*RealtimeAdminHandler) HandleUpdateRealtimeConfig

func (h *RealtimeAdminHandler) HandleUpdateRealtimeConfig(c fiber.Ctx) error

HandleUpdateRealtimeConfig updates the realtime configuration for a table

type RealtimeHandlers

type RealtimeHandlers struct {
	Manager  *realtime.Manager
	Handler  *realtime.RealtimeHandler
	Listener realtime.RealtimeListener
	Admin    *RealtimeAdminHandler
}

RealtimeHandlers groups realtime/WebSocket handlers.

type RealtimeStats

type RealtimeStats struct {
	TotalConnections   int `json:"total_connections"`
	ActiveChannels     int `json:"active_channels"`
	TotalSubscriptions int `json:"total_subscriptions"`
}

RealtimeStats represents realtime connection stats

type RealtimeTableStatus

type RealtimeTableStatus struct {
	ID              int      `json:"id"`
	Schema          string   `json:"schema"`
	Table           string   `json:"table"`
	RealtimeEnabled bool     `json:"realtime_enabled"`
	Events          []string `json:"events"`
	ExcludedColumns []string `json:"excluded_columns,omitempty"`
	CreatedAt       string   `json:"created_at"`
	UpdatedAt       string   `json:"updated_at"`
}

RealtimeTableStatus represents the status of a realtime-enabled table

type RenameTableRequest

type RenameTableRequest struct {
	NewName string `json:"newName"`
}

RenameTableRequest represents a request to rename a table

type ResolvedConfig

ResolvedConfig contains fully-resolved per-feature configuration. All configs are copies and can be safely modified.

type RevokeServiceKeyRequest

type RevokeServiceKeyRequest struct {
	Reason string `json:"reason"`
}

RevokeServiceKeyRequest represents a request to revoke a service key

type RotateServiceKeyRequest

type RotateServiceKeyRequest struct {
	NewName          *string  `json:"new_name,omitempty"`
	NewKeyName       *string  `json:"new_key_name,omitempty"`
	NewScopes        []string `json:"new_scopes,omitempty"`
	GracePeriodHours int      `json:"grace_period_hours,omitempty"`
}

RotateServiceKeyRequest represents a request to rotate a service key

type SAMLCallbackResponse

type SAMLCallbackResponse struct {
	AccessToken  string     `json:"access_token"`
	RefreshToken string     `json:"refresh_token"`
	ExpiresIn    int64      `json:"expires_in"`
	TokenType    string     `json:"token_type"`
	User         *auth.User `json:"user"`
}

SAMLCallbackResponse represents the response after successful SAML authentication

type SAMLHandler

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

SAMLHandler handles SAML SSO endpoints

func NewSAMLHandler

func NewSAMLHandler(samlService *auth.SAMLService, authService *auth.Service) *SAMLHandler

NewSAMLHandler creates a new SAML handler

func (*SAMLHandler) GetSPMetadata

func (h *SAMLHandler) GetSPMetadata(c fiber.Ctx) error

GetSPMetadata returns the SP metadata XML for a provider GET /auth/saml/metadata/:provider

func (*SAMLHandler) HandleSAMLAssertion

func (h *SAMLHandler) HandleSAMLAssertion(c fiber.Ctx) error

HandleSAMLAssertion handles the SAML assertion callback from the IdP POST /auth/saml/acs

func (*SAMLHandler) HandleSAMLLogout

func (h *SAMLHandler) HandleSAMLLogout(c fiber.Ctx) error

HandleSAMLLogout handles SAML Single Logout (SLO) This endpoint handles both IdP-initiated logout (SAMLRequest) and SP-initiated logout callback (SAMLResponse) POST /auth/saml/slo GET /auth/saml/slo

func (*SAMLHandler) InitiateSAMLLogin

func (h *SAMLHandler) InitiateSAMLLogin(c fiber.Ctx) error

InitiateSAMLLogin initiates SAML login by redirecting to the IdP GET /auth/saml/login/:provider

func (*SAMLHandler) InitiateSAMLLogout

func (h *SAMLHandler) InitiateSAMLLogout(c fiber.Ctx) error

InitiateSAMLLogout initiates SP-initiated SAML logout GET /auth/saml/logout/:provider

func (*SAMLHandler) ListSAMLProviders

func (h *SAMLHandler) ListSAMLProviders(c fiber.Ctx) error

ListSAMLProviders returns all enabled SAML providers for app login GET /auth/saml/providers

type SAMLLoginResponse

type SAMLLoginResponse struct {
	RedirectURL string `json:"redirect_url"`
}

SAMLLoginResponse represents the response for initiating SAML login

type SAMLProviderConfig

type SAMLProviderConfig struct {
	ID                   uuid.UUID         `json:"id"`
	Name                 string            `json:"name"`
	DisplayName          string            `json:"display_name"`
	Enabled              bool              `json:"enabled"`
	EntityID             string            `json:"entity_id"`
	AcsURL               string            `json:"acs_url"`
	IdPMetadataURL       *string           `json:"idp_metadata_url,omitempty"`
	IdPMetadataXML       *string           `json:"idp_metadata_xml,omitempty"`
	IdPEntityID          *string           `json:"idp_entity_id,omitempty"`
	IdPSsoURL            *string           `json:"idp_sso_url,omitempty"`
	AttributeMapping     map[string]string `json:"attribute_mapping"`
	AutoCreateUsers      bool              `json:"auto_create_users"`
	DefaultRole          string            `json:"default_role"`
	AllowDashboardLogin  bool              `json:"allow_dashboard_login"`
	AllowAppLogin        bool              `json:"allow_app_login"`
	AllowIDPInitiated    bool              `json:"allow_idp_initiated"`
	AllowedRedirectHosts []string          `json:"allowed_redirect_hosts"`
	RequiredGroups       []string          `json:"required_groups,omitempty"`
	RequiredGroupsAll    []string          `json:"required_groups_all,omitempty"`
	DeniedGroups         []string          `json:"denied_groups,omitempty"`
	GroupAttribute       string            `json:"group_attribute,omitempty"`
	Source               string            `json:"source"` // "database" or "config"
	TenantID             *string           `json:"tenant_id,omitempty"`
	CreatedAt            time.Time         `json:"created_at"`
	UpdatedAt            time.Time         `json:"updated_at"`
}

SAMLProviderConfig represents a SAML provider configuration for API responses

type SAMLProviderHandler

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

SAMLProviderHandler handles SAML provider configuration management

func NewSAMLProviderHandler

func NewSAMLProviderHandler(db *database.Connection, samlService *auth.SAMLService) *SAMLProviderHandler

NewSAMLProviderHandler creates a new SAML provider handler

func (*SAMLProviderHandler) CreateSAMLProvider

func (h *SAMLProviderHandler) CreateSAMLProvider(c fiber.Ctx) error

CreateSAMLProvider creates a new SAML provider

func (*SAMLProviderHandler) DeleteSAMLProvider

func (h *SAMLProviderHandler) DeleteSAMLProvider(c fiber.Ctx) error

DeleteSAMLProvider deletes a SAML provider

func (*SAMLProviderHandler) GetSAMLProvider

func (h *SAMLProviderHandler) GetSAMLProvider(c fiber.Ctx) error

GetSAMLProvider gets a single SAML provider by ID

func (*SAMLProviderHandler) GetSPMetadata

func (h *SAMLProviderHandler) GetSPMetadata(c fiber.Ctx) error

GetSPMetadata returns the Service Provider metadata XML for a provider

func (*SAMLProviderHandler) ListSAMLProviders

func (h *SAMLProviderHandler) ListSAMLProviders(c fiber.Ctx) error

ListSAMLProviders lists all SAML providers (database + config)

func (*SAMLProviderHandler) UpdateSAMLProvider

func (h *SAMLProviderHandler) UpdateSAMLProvider(c fiber.Ctx) error

UpdateSAMLProvider updates an existing SAML provider

func (*SAMLProviderHandler) UploadMetadata

func (h *SAMLProviderHandler) UploadMetadata(c fiber.Ctx) error

UploadMetadata handles file upload for IdP metadata XML

func (*SAMLProviderHandler) ValidateMetadata

func (h *SAMLProviderHandler) ValidateMetadata(c fiber.Ctx) error

ValidateMetadata validates SAML IdP metadata from URL or XML

type SAMLProviderPublic

type SAMLProviderPublic struct {
	Provider    string `json:"provider"`
	DisplayName string `json:"display_name"`
}

SAMLProviderPublic represents public SAML provider information

type SAMLProviderResponse

type SAMLProviderResponse struct {
	ID       string `json:"id"`
	Name     string `json:"name"`
	EntityID string `json:"entity_id"`
	SsoURL   string `json:"sso_url"`
	LoginURL string `json:"login_url"`
	Enabled  bool   `json:"enabled"`
}

SAMLProviderResponse represents a SAML provider for API responses

type SESSettings

type SESSettings struct {
	Region          string `json:"region"`
	AccessKeyID     string `json:"access_key_id,omitempty"`     // Omit in responses for security
	SecretAccessKey string `json:"secret_access_key,omitempty"` // Omit in responses for security
}

SESSettings contains AWS SES configuration

type SMTPSettings

type SMTPSettings struct {
	Host     string `json:"host"`
	Port     int    `json:"port"`
	Username string `json:"username"`
	Password string `json:"password,omitempty"` // Omit in responses for security
	TLS      bool   `json:"tls"`
}

SMTPSettings contains SMTP configuration

type SQLHandler

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

func NewSQLHandler

func NewSQLHandler(db *database.Connection, authService *auth.Service) *SQLHandler

func (*SQLHandler) ExecuteSQL

func (h *SQLHandler) ExecuteSQL(c fiber.Ctx) error

type SQLResult

type SQLResult struct {
	Columns         []string         `json:"columns,omitempty"`
	Rows            []map[string]any `json:"rows,omitempty"`
	RowCount        int              `json:"row_count"`
	AffectedRows    int64            `json:"affected_rows,omitempty"`
	ExecutionTimeMS float64          `json:"execution_time_ms"`
	Error           *string          `json:"error,omitempty"`
	Statement       string           `json:"statement"`
}

type SSOProvider

type SSOProvider struct {
	ID       string `json:"id"`
	Name     string `json:"name"`
	Type     string `json:"type"`               // "oauth" or "saml"
	Provider string `json:"provider,omitempty"` // For OAuth: google, github, etc.
}

SSOProvider represents an SSO provider available for dashboard login

type ScalingHandlers

type ScalingHandlers struct {
	JobsLeader      *scaling.LeaderElector
	FunctionsLeader *scaling.LeaderElector
	RPCLeader       *scaling.LeaderElector
}

ScalingHandlers groups scaling/leader election handlers.

type SchemaExportHandler

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

SchemaExportHandler handles schema export operations for type generation

func NewSchemaExportHandler

func NewSchemaExportHandler(schemaCache *database.SchemaCache, inspector *database.SchemaInspector) *SchemaExportHandler

NewSchemaExportHandler creates a new schema export handler

func (*SchemaExportHandler) HandleExportTypeScript

func (h *SchemaExportHandler) HandleExportTypeScript(c fiber.Ctx) error

HandleExportTypeScript generates TypeScript type definitions from the database schema

type SchemaGraphResponse

type SchemaGraphResponse struct {
	Nodes   []SchemaNode         `json:"nodes"`
	Edges   []SchemaRelationship `json:"edges"`
	Schemas []string             `json:"schemas"`
}

SchemaGraphResponse is the response for the schema graph endpoint

type SchemaHandlers

type SchemaHandlers struct {
	DDL            *DDLHandler
	Migrations     *migrations.Handler
	Cache          *database.SchemaCache
	Export         *SchemaExportHandler
	InternalSchema *InternalSchemaHandler
}

SchemaHandlers groups schema/migration handlers.

type SchemaNode

type SchemaNode struct {
	Schema           string             `json:"schema"`
	Name             string             `json:"name"`
	Columns          []SchemaNodeColumn `json:"columns"`
	PrimaryKey       []string           `json:"primary_key"`
	RLSEnabled       bool               `json:"rls_enabled"`
	ForceRLS         bool               `json:"force_rls"`
	RowEstimate      *int64             `json:"row_estimate,omitempty"`
	Comment          *string            `json:"comment,omitempty"`
	IncomingRelCount int                `json:"incoming_rel_count"`
	OutgoingRelCount int                `json:"outgoing_rel_count"`
}

SchemaNode represents a table for ERD visualization

type SchemaNodeColumn

type SchemaNodeColumn struct {
	Name         string  `json:"name"`
	DataType     string  `json:"data_type"`
	Nullable     bool    `json:"nullable"`
	IsPrimaryKey bool    `json:"is_primary_key"`
	IsForeignKey bool    `json:"is_foreign_key"`
	FKTarget     *string `json:"fk_target,omitempty"`
	DefaultValue *string `json:"default_value,omitempty"`
	IsUnique     bool    `json:"is_unique"`
	IsIndexed    bool    `json:"is_indexed"`
	Comment      *string `json:"comment,omitempty"`
}

SchemaNodeColumn represents a column in a schema node

type SchemaRelationship

type SchemaRelationship struct {
	ID             string `json:"id"`
	SourceSchema   string `json:"source_schema"`
	SourceTable    string `json:"source_table"`
	SourceColumn   string `json:"source_column"`
	TargetSchema   string `json:"target_schema"`
	TargetTable    string `json:"target_table"`
	TargetColumn   string `json:"target_column"`
	ConstraintName string `json:"constraint_name"`
	OnDelete       string `json:"on_delete"`
	OnUpdate       string `json:"on_update"`
	Cardinality    string `json:"cardinality"`
}

SchemaRelationship represents a foreign key relationship for ERD visualization

type SecretsHandlers

type SecretsHandlers struct {
	Handler *secrets.Handler
	Storage *secrets.Storage
}

SecretsHandlers groups secret management handlers.

type SecuritySettings

type SecuritySettings struct {
	EnableGlobalRateLimit bool `json:"enable_global_rate_limit"`
}

SecuritySettings contains security-related settings

type SecurityWarning

type SecurityWarning struct {
	ID         string `json:"id"`
	Severity   string `json:"severity"` // critical, high, medium, low
	Category   string `json:"category"`
	Schema     string `json:"schema"`
	Table      string `json:"table"`
	PolicyName string `json:"policy_name,omitempty"`
	Message    string `json:"message"`
	Suggestion string `json:"suggestion"`
	FixSQL     string `json:"fix_sql,omitempty"`
}

SecurityWarning represents a security issue detected

type SendGridSettings

type SendGridSettings struct {
	APIKey string `json:"api_key,omitempty"` // Omit in responses for security
}

SendGridSettings contains SendGrid configuration

type Server

type Server struct {

	// Handler groups (organized by domain)
	Auth       *AuthHandlers
	Storage    *StorageHandlers
	AI         *AIHandlers
	Functions  *FunctionsHandlers
	Jobs       *JobsHandlers
	Realtime   *RealtimeHandlers
	MCP        *MCPHandlers
	Tenancy    *TenancyHandlers
	Branching  *BranchingHandlers
	Settings   *SettingsHandlers
	Webhook    *WebhookHandlers
	Logging    *LoggingHandlers
	Schema     *SchemaHandlers
	RPC        *RPCHandlers
	GraphQL    *GraphQLHandlers
	Extensions *ExtensionsHandlers
	Secrets    *SecretsHandlers
	Scaling    *ScalingHandlers
	Metrics    *MetricsComponents
	Email      *EmailHandlers
	Captcha    *CaptchaHandlers
	Monitoring *MonitoringHandlers
	Quota      *QuotaHandlers
	Middleware *MiddlewareComponents
	// contains filtered or unexported fields
}

Server represents the HTTP server

func NewServer

func NewServer(cfg *config.Config, db *database.Connection, version string) *Server

NewServer creates a new HTTP server

func NewServerWithTx

func NewServerWithTx(cfg *config.Config, db *database.Connection, tx pgx.Tx, version string) *Server

NewServerWithTx creates a test-mode server with transaction isolation. This is specifically for HTTP API tests that need to use a transaction.

Note: This function creates a minimal server with only the essential components for HTTP API testing. It does NOT initialize all services (webhooks, realtime, jobs, etc.).

func (*Server) App

func (s *Server) App() *fiber.App

App returns the underlying Fiber app instance for testing

func (*Server) CreatePolicy

func (s *Server) CreatePolicy(c fiber.Ctx) error

CreatePolicy creates a new RLS policy POST /api/v1/admin/policies

func (*Server) DB

func (s *Server) DB() *pgxpool.Pool

DB returns the database querier to use. In test mode with a transaction, it returns the transaction (note: can't use tx as pool). Otherwise, it returns the normal database connection pool.

func (*Server) DeletePolicy

func (s *Server) DeletePolicy(c fiber.Ctx) error

DeletePolicy drops an RLS policy DELETE /api/v1/admin/policies/:schema/:table/:policy

func (*Server) GetAuthService

func (s *Server) GetAuthService() *auth.Service

GetAuthService returns the auth service from the auth handler

func (*Server) GetLoggingService

func (s *Server) GetLoggingService() *logging.Service

GetLoggingService returns the central logging service

func (*Server) GetPolicyTemplates

func (s *Server) GetPolicyTemplates(c fiber.Ctx) error

GetPolicyTemplates returns pre-built policy templates GET /api/v1/admin/policies/templates

func (*Server) GetSchemaGraph

func (s *Server) GetSchemaGraph(c fiber.Ctx) error

GetSchemaGraph returns all tables and relationships for ERD visualization. Results are cached for 2 minutes per (tenant, schema list) combination. GET /api/v1/admin/schema/graph

func (*Server) GetSecurityWarnings

func (s *Server) GetSecurityWarnings(c fiber.Ctx) error

GetSecurityWarnings scans for security issues GET /api/v1/admin/security/warnings

func (*Server) GetStorageService

func (s *Server) GetStorageService() *storage.Service

GetStorageService returns the base storage service from the storage handler

func (*Server) GetTableRLSStatus

func (s *Server) GetTableRLSStatus(c fiber.Ctx) error

GetTableRLSStatus returns RLS status and policies for a specific table GET /api/v1/admin/tables/:schema/:table/rls

func (*Server) GetTableRelationships

func (s *Server) GetTableRelationships(c fiber.Ctx) error

GetTableRelationships returns relationships for a specific table GET /api/v1/admin/tables/:schema/:table/relationships

func (*Server) GetTablesWithRLS

func (s *Server) GetTablesWithRLS(c fiber.Ctx) error

GetTablesWithRLS returns all tables with their RLS status and policies GET /api/v1/admin/tables/rls

func (*Server) GetTenantConfigLoader

func (s *Server) GetTenantConfigLoader() *config.TenantConfigLoader

GetTenantConfigLoader returns the tenant configuration loader

func (*Server) GetWebhookTriggerService

func (s *Server) GetWebhookTriggerService() *webhook.TriggerService

GetWebhookTriggerService returns the webhook trigger service for testing

func (*Server) InvalidateSchemaCache

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

InvalidateSchemaCache invalidates the REST API schema cache.

func (*Server) ListPolicies

func (s *Server) ListPolicies(c fiber.Ctx) error

ListPolicies returns all RLS policies GET /api/v1/admin/policies

func (*Server) LoadAIChatbotsFromFilesystem

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

LoadAIChatbotsFromFilesystem loads AI chatbots from the filesystem

func (*Server) LoadFunctionsFromFilesystem

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

LoadFunctionsFromFilesystem loads edge functions from the filesystem

func (*Server) LoadJobsFromFilesystem

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

LoadJobsFromFilesystem loads job functions from the filesystem

func (*Server) SchemaCache

func (s *Server) SchemaCache() *database.SchemaCache

SchemaCache returns the REST API schema cache

func (*Server) SetTenantConfigLoader

func (s *Server) SetTenantConfigLoader(loader *config.TenantConfigLoader)

SetTenantConfigLoader sets the tenant configuration loader

func (*Server) Shutdown

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

Shutdown gracefully shuts down the server

func (*Server) Start

func (s *Server) Start() error

Start starts the HTTP server

func (*Server) ToggleTableRLS

func (s *Server) ToggleTableRLS(c fiber.Ctx) error

ToggleTableRLS enables or disables RLS on a table POST /api/v1/admin/tables/:schema/:table/rls/toggle

func (*Server) UpdatePolicy

func (s *Server) UpdatePolicy(c fiber.Ctx) error

UpdatePolicy modifies an existing RLS policy PUT /api/v1/admin/policies/:schema/:table/:policy Note: PostgreSQL's ALTER POLICY can only change roles, USING, and WITH CHECK. It cannot change the policy name, command type, or permissive/restrictive mode.

type ServiceKey

type ServiceKey struct {
	ID                 uuid.UUID  `json:"id"`
	Name               string     `json:"name"`
	Description        *string    `json:"description,omitempty"`
	KeyPrefix          string     `json:"key_prefix"`
	KeyType            string     `json:"key_type"`
	Scopes             []string   `json:"scopes"`
	AllowedNamespaces  []string   `json:"allowed_namespaces,omitempty"`
	Enabled            bool       `json:"enabled"`
	RateLimitPerMinute *int       `json:"rate_limit_per_minute,omitempty"`
	RateLimitPerHour   *int       `json:"rate_limit_per_hour,omitempty"`
	CreatedBy          *uuid.UUID `json:"created_by,omitempty"`
	CreatedAt          time.Time  `json:"created_at"`
	LastUsedAt         *time.Time `json:"last_used_at,omitempty"`
	ExpiresAt          *time.Time `json:"expires_at,omitempty"`
	RevokedAt          *time.Time `json:"revoked_at,omitempty"`
	DeprecatedAt       *time.Time `json:"deprecated_at,omitempty"`
	GracePeriodEndsAt  *time.Time `json:"grace_period_ends_at,omitempty"`
	ReplacedBy         *uuid.UUID `json:"replaced_by,omitempty"`
}

ServiceKey represents a service key in the database

type ServiceKeyHandler

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

ServiceKeyHandler handles service key management requests

func NewServiceKeyHandler

func NewServiceKeyHandler(db *database.Connection) *ServiceKeyHandler

NewServiceKeyHandler creates a new service key handler

func (*ServiceKeyHandler) CreateServiceKey

func (h *ServiceKeyHandler) CreateServiceKey(c fiber.Ctx) error

CreateServiceKey creates a new service key

func (*ServiceKeyHandler) DeleteServiceKey

func (h *ServiceKeyHandler) DeleteServiceKey(c fiber.Ctx) error

DeleteServiceKey deletes a service key

func (*ServiceKeyHandler) DeprecateServiceKey

func (h *ServiceKeyHandler) DeprecateServiceKey(c fiber.Ctx) error

DeprecateServiceKey marks a service key for rotation

func (*ServiceKeyHandler) DisableServiceKey

func (h *ServiceKeyHandler) DisableServiceKey(c fiber.Ctx) error

DisableServiceKey disables a service key

func (*ServiceKeyHandler) EnableServiceKey

func (h *ServiceKeyHandler) EnableServiceKey(c fiber.Ctx) error

EnableServiceKey enables a service key

func (*ServiceKeyHandler) GetRevocationHistory

func (h *ServiceKeyHandler) GetRevocationHistory(c fiber.Ctx) error

GetRevocationHistory returns the revocation history for a service key

func (*ServiceKeyHandler) GetServiceKey

func (h *ServiceKeyHandler) GetServiceKey(c fiber.Ctx) error

GetServiceKey retrieves a single service key

func (*ServiceKeyHandler) ListServiceKeys

func (h *ServiceKeyHandler) ListServiceKeys(c fiber.Ctx) error

ListServiceKeys lists all service keys

func (*ServiceKeyHandler) RevokeServiceKey

func (h *ServiceKeyHandler) RevokeServiceKey(c fiber.Ctx) error

RevokeServiceKey revokes a service key

func (*ServiceKeyHandler) RotateServiceKey

func (h *ServiceKeyHandler) RotateServiceKey(c fiber.Ctx) error

RotateServiceKey rotates a service key, creating a new one and deprecating the old

func (*ServiceKeyHandler) UpdateServiceKey

func (h *ServiceKeyHandler) UpdateServiceKey(c fiber.Ctx) error

UpdateServiceKey updates a service key

type ServiceKeyWithKey

type ServiceKeyWithKey struct {
	ServiceKey
	Key string `json:"key"`
}

ServiceKeyWithKey is returned only on creation, includes the plaintext key

type SetActiveBranchRequest

type SetActiveBranchRequest struct {
	Branch string `json:"branch"`
}

SetActiveBranchRequest represents the request body for setting the active branch

type SettingOverride

type SettingOverride struct {
	IsOverridden bool   `json:"is_overridden"`
	EnvVar       string `json:"env_var"`
}

SettingOverride contains override information for a specific setting

type SettingOverrides

type SettingOverrides struct {
	Authentication map[string]bool `json:"authentication,omitempty"`
	Features       map[string]bool `json:"features,omitempty"`
	Email          map[string]bool `json:"email,omitempty"`
	Security       map[string]bool `json:"security,omitempty"`
}

SettingOverrides indicates which settings are overridden by environment variables

type SettingResponse

type SettingResponse struct {
	Value interface{} `json:"value"`
}

type SettingsHandler

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

func NewSettingsHandler

func NewSettingsHandler(db *database.Connection) *SettingsHandler

func (*SettingsHandler) GetSetting

func (h *SettingsHandler) GetSetting(c fiber.Ctx) error

func (*SettingsHandler) GetSettings

func (h *SettingsHandler) GetSettings(c fiber.Ctx) error

type SettingsHandlers

SettingsHandlers groups settings/configuration handlers.

type SetupStatusResponse

type SetupStatusResponse struct {
	NeedsSetup bool `json:"needs_setup"`
	HasAdmin   bool `json:"has_admin"`
}

SetupStatusResponse represents the setup status

type StorageHandler

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

StorageHandler handles file storage operations Methods are split across multiple files: - storage_files.go: UploadFile, DownloadFile, DeleteFile, GetFileInfo, ListFiles - storage_buckets.go: CreateBucket, UpdateBucketSettings, DeleteBucket, ListBuckets - storage_signed.go: GenerateSignedURL, DownloadSignedObject - storage_multipart.go: MultipartUpload - storage_sharing.go: ShareObject, RevokeShare, ListShares - storage_utils.go: helper functions (detectContentType, parseMetadata, getUserID, setRLSContext)

func NewStorageHandler

func NewStorageHandler(storageMgr *storage.Manager, db *database.Connection, baseConfig *config.Config, transformCfg *config.TransformConfig) *StorageHandler

NewStorageHandler creates a new storage handler with automatic cache initialization

func NewStorageHandlerWithCache

func NewStorageHandlerWithCache(storageMgr *storage.Manager, db *database.Connection, baseConfig *config.Config, transformCfg *config.TransformConfig, cache *storage.TransformCache) *StorageHandler

NewStorageHandlerWithCache creates a new storage handler with optional transform cache

func (*StorageHandler) AbortChunkedUpload

func (h *StorageHandler) AbortChunkedUpload(c fiber.Ctx) error

AbortChunkedUpload aborts a chunked upload and cleans up DELETE /api/v1/storage/:bucket/chunked/:uploadId

func (*StorageHandler) CompleteChunkedUpload

func (h *StorageHandler) CompleteChunkedUpload(c fiber.Ctx) error

CompleteChunkedUpload finalizes a chunked upload POST /api/v1/storage/:bucket/chunked/:uploadId/complete

func (*StorageHandler) CreateBucket

func (h *StorageHandler) CreateBucket(c fiber.Ctx) error

func (*StorageHandler) DeleteBucket

func (h *StorageHandler) DeleteBucket(c fiber.Ctx) error

func (*StorageHandler) DeleteFile

func (h *StorageHandler) DeleteFile(c fiber.Ctx) error

DeleteFile handles file deletion DELETE /api/v1/storage/:bucket/:key

func (*StorageHandler) DownloadFile

func (h *StorageHandler) DownloadFile(c fiber.Ctx) error

DownloadFile handles file download and HEAD requests for file info GET /api/v1/storage/:bucket/:key HEAD /api/v1/storage/:bucket/:key (for downloadResumable to get Content-Length)

func (*StorageHandler) DownloadSignedObject

func (h *StorageHandler) DownloadSignedObject(c fiber.Ctx) error

DownloadSignedObject handles file downloads via signed URL tokens GET /api/v1/storage/object?token=... This is a PUBLIC endpoint - authentication is provided by the signed token

func (*StorageHandler) GenerateSignedURL

func (h *StorageHandler) GenerateSignedURL(c fiber.Ctx) error

GenerateSignedURL generates a presigned URL for temporary access POST /api/v1/storage/:bucket/sign/*

func (*StorageHandler) GetChunkedUploadStatus

func (h *StorageHandler) GetChunkedUploadStatus(c fiber.Ctx) error

GetChunkedUploadStatus retrieves the status of a chunked upload session GET /api/v1/storage/:bucket/chunked/:uploadId/status

func (*StorageHandler) GetFileInfo

func (h *StorageHandler) GetFileInfo(c fiber.Ctx) error

GetFileInfo handles getting file metadata HEAD /api/v1/storage/:bucket/:key

func (*StorageHandler) GetTransformConfig

func (h *StorageHandler) GetTransformConfig(c fiber.Ctx) error

GetTransformConfig returns the image transformation configuration This is a public endpoint that returns configuration info for the admin dashboard

func (*StorageHandler) InitChunkedUpload

func (h *StorageHandler) InitChunkedUpload(c fiber.Ctx) error

InitChunkedUpload initializes a new chunked upload session POST /api/v1/storage/:bucket/chunked/init

func (*StorageHandler) ListBuckets

func (h *StorageHandler) ListBuckets(c fiber.Ctx) error

func (*StorageHandler) ListFiles

func (h *StorageHandler) ListFiles(c fiber.Ctx) error

ListFiles handles listing files in a bucket GET /api/v1/storage/:bucket

func (*StorageHandler) ListShares

func (h *StorageHandler) ListShares(c fiber.Ctx) error

ListShares handles listing users a file is shared with GET /api/v1/storage/:bucket/:path/shares

func (*StorageHandler) MultipartUpload

func (h *StorageHandler) MultipartUpload(c fiber.Ctx) error

MultipartUpload handles multipart upload POST /api/v1/storage/:bucket/multipart

func (*StorageHandler) RevokeShare

func (h *StorageHandler) RevokeShare(c fiber.Ctx) error

RevokeShare handles revoking file access from a user DELETE /api/v1/storage/:bucket/:path/share/:user_id

func (*StorageHandler) ShareObject

func (h *StorageHandler) ShareObject(c fiber.Ctx) error

ShareObject handles sharing a file with another user POST /api/v1/storage/:bucket/:path/share

func (*StorageHandler) StreamUpload

func (h *StorageHandler) StreamUpload(c fiber.Ctx) error

StreamUpload handles streaming file upload with reduced memory usage POST /api/v1/storage/:bucket/stream/:key

This endpoint reads the raw request body as a stream, avoiding the memory overhead of multipart form parsing. Use this for large file uploads.

Headers:

  • Content-Length: Required. The size of the file in bytes.
  • X-Storage-Content-Type: Optional. The MIME type of the file.
  • X-Storage-Cache-Control: Optional. Cache-Control header value.
  • X-Storage-Metadata: Optional. JSON object with custom metadata.
  • X-Storage-Upsert: Optional. "true" to overwrite existing files.

func (*StorageHandler) UpdateBucketSettings

func (h *StorageHandler) UpdateBucketSettings(c fiber.Ctx) error

func (*StorageHandler) UploadChunk

func (h *StorageHandler) UploadChunk(c fiber.Ctx) error

UploadChunk uploads a single chunk of a file PUT /api/v1/storage/:bucket/chunked/:uploadId/:chunkIndex

func (*StorageHandler) UploadFile

func (h *StorageHandler) UploadFile(c fiber.Ctx) error

UploadFile handles file upload POST /api/v1/storage/:bucket/:key

type StorageHandlers

type StorageHandlers struct {
	Handler *StorageHandler
}

StorageHandlers groups storage-related handlers.

type StorageStats

type StorageStats struct {
	TotalBuckets int     `json:"total_buckets"`
	TotalFiles   int     `json:"total_files"`
	TotalSizeGB  float64 `json:"total_size_gb"`
}

StorageStats represents storage usage stats

type SystemHealth

type SystemHealth struct {
	Status   string                  `json:"status"` // "healthy", "degraded", "unhealthy"
	Services map[string]HealthStatus `json:"services"`
}

SystemHealth represents the health of all system components

type SystemMetrics

type SystemMetrics struct {
	// System info
	Uptime       int64  `json:"uptime_seconds"`
	GoVersion    string `json:"go_version"`
	NumGoroutine int    `json:"num_goroutines"`

	// Memory stats
	MemoryAllocMB      uint64  `json:"memory_alloc_mb"`
	MemoryTotalAllocMB uint64  `json:"memory_total_alloc_mb"`
	MemorySysMB        uint64  `json:"memory_sys_mb"`
	NumGC              uint32  `json:"num_gc"`
	GCPauseMS          float64 `json:"gc_pause_ms"`

	// Database stats
	DatabaseStats DatabaseStats `json:"database"`

	// Realtime stats
	RealtimeStats RealtimeStats `json:"realtime"`

	// Storage stats (if available)
	StorageStats *StorageStats `json:"storage,omitempty"`
}

SystemMetrics represents system-wide metrics

type SystemSettingsHandler

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

func NewSystemSettingsHandler

func NewSystemSettingsHandler(settingsService *auth.SystemSettingsService, settingsCache *auth.SettingsCache) *SystemSettingsHandler

func (*SystemSettingsHandler) DeleteSetting

func (h *SystemSettingsHandler) DeleteSetting(c fiber.Ctx) error

func (*SystemSettingsHandler) GetSetting

func (h *SystemSettingsHandler) GetSetting(c fiber.Ctx) error

func (*SystemSettingsHandler) ListSettings

func (h *SystemSettingsHandler) ListSettings(c fiber.Ctx) error

func (*SystemSettingsHandler) UpdateSetting

func (h *SystemSettingsHandler) UpdateSetting(c fiber.Ctx) error

type TableRLSStatus

type TableRLSStatus struct {
	Schema      string   `json:"schema"`
	Table       string   `json:"table"`
	RLSEnabled  bool     `json:"rls_enabled"`
	RLSForced   bool     `json:"rls_forced"`
	PolicyCount int      `json:"policy_count"`
	Policies    []Policy `json:"policies"`
	HasWarnings bool     `json:"has_warnings"`
}

TableRLSStatus represents RLS status for a table

type TenancyHandlers

type TenancyHandlers struct {
	ServiceKey *ServiceKeyHandler
	Tenant     *TenantHandler
	Manager    *tenantdb.Manager
	Storage    *tenantdb.Storage
}

TenancyHandlers groups multi-tenancy handlers.

type TenantAdminAssignment

type TenantAdminAssignment struct {
	ID         string    `json:"id"`
	TenantID   string    `json:"tenant_id"`
	UserID     string    `json:"user_id"`
	AssignedAt time.Time `json:"assigned_at"`
}

type TenantConfigResolver

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

TenantConfigResolver resolves tenant-specific configuration at request time. It merges settings from multiple sources with NO caching to ensure immediate visibility of database changes.

Configuration Cascade (Priority: Low → High):

  1. Hardcoded defaults (code)
  2. Config file (fluxbase.yaml)
  3. Instance settings (database: platform.instance_settings WHERE tenant_id IS NULL)
  4. Tenant settings (database: platform.instance_settings WHERE tenant_id = $1)

func GetGlobalResolver

func GetGlobalResolver() *TenantConfigResolver

GetGlobalResolver returns the global tenant config resolver. Returns nil if not set.

func NewTenantConfigResolver

func NewTenantConfigResolver(
	db *database.Connection,
	baseConfig *config.Config,
	unifiedSettings *settings.UnifiedService,
) *TenantConfigResolver

NewTenantConfigResolver creates a new tenant config resolver.

func (*TenantConfigResolver) GetBaseConfig

func (r *TenantConfigResolver) GetBaseConfig() *config.Config

GetBaseConfig returns the base configuration (for reference only). Use ResolveForRequest() to get tenant-specific config.

func (*TenantConfigResolver) ResolveForRequest

func (r *TenantConfigResolver) ResolveForRequest(ctx context.Context, c fiber.Ctx) *ResolvedConfig

ResolveForRequest merges all configuration layers for the current request. This method does NOT cache results - every call fetches fresh data from the database to ensure immediate visibility of setting changes.

For the default tenant, the cascade is: baseConfig (YAML+env) → instance DB → tenant DB. For non-default tenants, the cascade is: instance DB → tenant DB (no YAML/env layer).

func (*TenantConfigResolver) ResolveForTenant

func (r *TenantConfigResolver) ResolveForTenant(ctx context.Context, tenantID string, isDefaultTenant bool) *ResolvedConfig

ResolveForTenant resolves configuration for a specific tenant ID. This is used by background workers (jobs) that don't have a fiber context.

type TenantEmailSettingsResponse

type TenantEmailSettingsResponse struct {
	EmailSettingsResponse
	Sources map[string]string `json:"_sources"` // field -> "instance" | "tenant" | "config" | "default"
}

TenantEmailSettingsResponse extends EmailSettingsResponse with source information per field.

type TenantHandler

type TenantHandler struct {
	DB                *database.Connection
	Manager           *tenantdb.Manager
	Storage           *tenantdb.Storage
	InvitationService *auth.InvitationService
	EmailService      email.Service
	Config            *config.Config
}

func NewTenantHandler

func NewTenantHandler(db *database.Connection, manager *tenantdb.Manager, storage *tenantdb.Storage, invitationService *auth.InvitationService, emailService email.Service, cfg *config.Config) *TenantHandler

func (*TenantHandler) ApplyTenantSchema

func (h *TenantHandler) ApplyTenantSchema(c fiber.Ctx) error

ApplyTenantSchema applies the declarative schema for a tenant

func (*TenantHandler) ApplyUploadedTenantSchema

func (h *TenantHandler) ApplyUploadedTenantSchema(c fiber.Ctx) error

ApplyUploadedTenantSchema applies the previously uploaded schema for a tenant

func (*TenantHandler) AssignAdmin

func (h *TenantHandler) AssignAdmin(c fiber.Ctx) error

func (*TenantHandler) CreateTenant

func (h *TenantHandler) CreateTenant(c fiber.Ctx) error

func (*TenantHandler) DeleteStoredSchema

func (h *TenantHandler) DeleteStoredSchema(c fiber.Ctx) error

DeleteStoredSchema deletes the stored schema content for a tenant

func (*TenantHandler) DeleteTenant

func (h *TenantHandler) DeleteTenant(c fiber.Ctx) error

func (*TenantHandler) GetStoredSchema

func (h *TenantHandler) GetStoredSchema(c fiber.Ctx) error

GetStoredSchema retrieves the stored schema content for a tenant

func (*TenantHandler) GetTenant

func (h *TenantHandler) GetTenant(c fiber.Ctx) error

func (*TenantHandler) GetTenantSchemaStatus

func (h *TenantHandler) GetTenantSchemaStatus(c fiber.Ctx) error

GetTenantSchemaStatus returns the status of a tenant's declarative schema

func (*TenantHandler) ListAdmins

func (h *TenantHandler) ListAdmins(c fiber.Ctx) error

func (*TenantHandler) ListDeletedTenants

func (h *TenantHandler) ListDeletedTenants(c fiber.Ctx) error

func (*TenantHandler) ListMyTenants

func (h *TenantHandler) ListMyTenants(c fiber.Ctx) error

func (*TenantHandler) ListTenants

func (h *TenantHandler) ListTenants(c fiber.Ctx) error

func (*TenantHandler) MigrateTenant

func (h *TenantHandler) MigrateTenant(c fiber.Ctx) error

func (*TenantHandler) RecoverTenant

func (h *TenantHandler) RecoverTenant(c fiber.Ctx) error

func (*TenantHandler) RemoveAdmin

func (h *TenantHandler) RemoveAdmin(c fiber.Ctx) error

func (*TenantHandler) RepairTenant

func (h *TenantHandler) RepairTenant(c fiber.Ctx) error

RepairTenant re-runs schema application and FDW setup for an existing tenant.

func (*TenantHandler) UpdateTenant

func (h *TenantHandler) UpdateTenant(c fiber.Ctx) error

func (*TenantHandler) UploadTenantSchema

func (h *TenantHandler) UploadTenantSchema(c fiber.Ctx) error

UploadTenantSchema uploads and stores schema content for a tenant

type TenantResponse

type TenantResponse struct {
	ID        string                 `json:"id"`
	Slug      string                 `json:"slug"`
	Name      string                 `json:"name"`
	DbName    *string                `json:"db_name,omitempty"`
	Status    string                 `json:"status"`
	IsDefault bool                   `json:"is_default"`
	Metadata  map[string]interface{} `json:"metadata,omitempty"`
	CreatedAt time.Time              `json:"created_at"`
	UpdatedAt time.Time              `json:"updated_at,omitempty"`
	DeletedAt *time.Time             `json:"deleted_at,omitempty"`
}

type TenantSettingsHandler

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

TenantSettingsHandler handles tenant-level settings API endpoints

func NewTenantSettingsHandler

func NewTenantSettingsHandler(settingsSvc *settings.UnifiedService, tenantDB *tenantdb.Storage) *TenantSettingsHandler

NewTenantSettingsHandler creates a new tenant settings handler

func (*TenantSettingsHandler) DeleteTenantSetting

func (h *TenantSettingsHandler) DeleteTenantSetting(c fiber.Ctx) error

DeleteTenantSetting removes a tenant-specific setting (resets to instance default) DELETE /admin/tenants/:id/settings/*path

func (*TenantSettingsHandler) GetTenantSetting

func (h *TenantSettingsHandler) GetTenantSetting(c fiber.Ctx) error

GetTenantSetting returns a specific tenant setting with resolved value GET /admin/tenants/:id/settings/*path

func (*TenantSettingsHandler) GetTenantSettings

func (h *TenantSettingsHandler) GetTenantSettings(c fiber.Ctx) error

GetTenantSettings returns all tenant-specific settings with resolved values GET /admin/tenants/:id/settings

func (*TenantSettingsHandler) UpdateTenantSettings

func (h *TenantSettingsHandler) UpdateTenantSettings(c fiber.Ctx) error

UpdateTenantSettings updates tenant-specific settings PATCH /admin/tenants/:id/settings

type TenantSettingsResponse

type TenantSettingsResponse struct {
	TenantID  string                              `json:"tenant_id"`
	Settings  map[string]settings.ResolvedSetting `json:"settings"`
	CreatedAt string                              `json:"created_at,omitempty"`
	UpdatedAt string                              `json:"updated_at,omitempty"`
}

TenantSettingsResponse represents the response for tenant settings

type TestEmailRequest

type TestEmailRequest struct {
	RecipientEmail string `json:"recipient_email"`
}

type TestEmailSettingsRequest

type TestEmailSettingsRequest struct {
	RecipientEmail string `json:"recipient_email"`
}

TestEmailSettingsRequest represents a test email request

type TransformConfigResponse

type TransformConfigResponse struct {
	Enabled        bool     `json:"enabled"`
	DefaultQuality int      `json:"default_quality"`
	MaxWidth       int      `json:"max_width"`
	MaxHeight      int      `json:"max_height"`
	AllowedFormats []string `json:"allowed_formats,omitempty"`
}

TransformConfigResponse represents the response for the transform config endpoint

type TypeScriptExportRequest

type TypeScriptExportRequest struct {
	Schemas          []string `json:"schemas"`           // Schemas to include (default: ["public"])
	IncludeFunctions bool     `json:"include_functions"` // Include RPC function types
	IncludeViews     bool     `json:"include_views"`     // Include view types
	Format           string   `json:"format"`            // "types" (interfaces only) or "full" (with helpers)
}

TypeScriptExportRequest represents a request for TypeScript type generation

type UpdateAppSettingsRequest

type UpdateAppSettingsRequest struct {
	Authentication *AuthenticationSettings `json:"authentication,omitempty"`
	Features       *FeatureSettings        `json:"features,omitempty"`
	Email          *EmailSettings          `json:"email,omitempty"`
	Security       *SecuritySettings       `json:"security,omitempty"`
}

UpdateAppSettingsRequest represents the request to update app settings

type UpdateCaptchaSettingsRequest

type UpdateCaptchaSettingsRequest struct {
	Enabled        *bool     `json:"enabled,omitempty"`
	Provider       *string   `json:"provider,omitempty"`
	SiteKey        *string   `json:"site_key,omitempty"`
	SecretKey      *string   `json:"secret_key,omitempty"`
	ScoreThreshold *float64  `json:"score_threshold,omitempty"`
	Endpoints      *[]string `json:"endpoints,omitempty"`
	CapServerURL   *string   `json:"cap_server_url,omitempty"`
	CapAPIKey      *string   `json:"cap_api_key,omitempty"`
}

type UpdateClientKeyRequest

type UpdateClientKeyRequest struct {
	Name               *string  `json:"name,omitempty"`
	Description        *string  `json:"description,omitempty"`
	Scopes             []string `json:"scopes,omitempty"`
	RateLimitPerMinute *int     `json:"rate_limit_per_minute,omitempty"`
}

type UpdateEmailSettingsRequest

type UpdateEmailSettingsRequest struct {
	Enabled     *bool   `json:"enabled,omitempty"`
	Provider    *string `json:"provider,omitempty"`
	FromAddress *string `json:"from_address,omitempty"`
	FromName    *string `json:"from_name,omitempty"`

	// SMTP
	SMTPHost     *string `json:"smtp_host,omitempty"`
	SMTPPort     *int    `json:"smtp_port,omitempty"`
	SMTPUsername *string `json:"smtp_username,omitempty"`
	SMTPPassword *string `json:"smtp_password,omitempty"` // Only set if changing
	SMTPTLS      *bool   `json:"smtp_tls,omitempty"`

	// SendGrid
	SendGridAPIKey *string `json:"sendgrid_api_key,omitempty"`

	// Mailgun
	MailgunAPIKey *string `json:"mailgun_api_key,omitempty"`
	MailgunDomain *string `json:"mailgun_domain,omitempty"`

	// AWS SES
	SESAccessKey *string `json:"ses_access_key,omitempty"`
	SESSecretKey *string `json:"ses_secret_key,omitempty"`
	SESRegion    *string `json:"ses_region,omitempty"`
}

UpdateEmailSettingsRequest represents the request to update email settings

type UpdateInstanceSettingsRequest

type UpdateInstanceSettingsRequest struct {
	Settings map[string]any `json:"settings"`
}

type UpdateOAuthProviderRequest

type UpdateOAuthProviderRequest struct {
	DisplayName         *string             `json:"display_name,omitempty"`
	Enabled             *bool               `json:"enabled,omitempty"`
	ClientID            *string             `json:"client_id,omitempty"`
	ClientSecret        *string             `json:"client_secret,omitempty"`
	RedirectURL         *string             `json:"redirect_url,omitempty"`
	Scopes              []string            `json:"scopes,omitempty"`
	AuthorizationURL    *string             `json:"authorization_url,omitempty"`
	TokenURL            *string             `json:"token_url,omitempty"`
	UserInfoURL         *string             `json:"user_info_url,omitempty"`
	RevocationEndpoint  *string             `json:"revocation_endpoint,omitempty"`  // OAuth 2.0 Token Revocation (RFC 7009)
	EndSessionEndpoint  *string             `json:"end_session_endpoint,omitempty"` // OIDC RP-Initiated Logout
	AllowDashboardLogin *bool               `json:"allow_dashboard_login,omitempty"`
	AllowAppLogin       *bool               `json:"allow_app_login,omitempty"`
	RequiredClaims      map[string][]string `json:"required_claims,omitempty"`
	DeniedClaims        map[string][]string `json:"denied_claims,omitempty"`
}

UpdateOAuthProviderRequest represents a request to update an OAuth provider

type UpdateOverridableSettingsRequest

type UpdateOverridableSettingsRequest struct {
	OverridableSettings []string `json:"overridable_settings"`
}

type UpdatePolicyRequest

type UpdatePolicyRequest struct {
	Roles     []string `json:"roles"`
	Using     *string  `json:"using"`
	WithCheck *string  `json:"with_check"`
}

UpdatePolicyRequest is the request body for updating a policy

type UpdateSAMLProviderRequest

type UpdateSAMLProviderRequest struct {
	DisplayName          *string           `json:"display_name,omitempty"`
	Enabled              *bool             `json:"enabled,omitempty"`
	IdPMetadataURL       *string           `json:"idp_metadata_url,omitempty"`
	IdPMetadataXML       *string           `json:"idp_metadata_xml,omitempty"`
	AttributeMapping     map[string]string `json:"attribute_mapping,omitempty"`
	AutoCreateUsers      *bool             `json:"auto_create_users,omitempty"`
	DefaultRole          *string           `json:"default_role,omitempty"`
	AllowDashboardLogin  *bool             `json:"allow_dashboard_login,omitempty"`
	AllowAppLogin        *bool             `json:"allow_app_login,omitempty"`
	AllowIDPInitiated    *bool             `json:"allow_idp_initiated,omitempty"`
	AllowedRedirectHosts []string          `json:"allowed_redirect_hosts,omitempty"`
	RequiredGroups       []string          `json:"required_groups,omitempty"`
	RequiredGroupsAll    []string          `json:"required_groups_all,omitempty"`
	DeniedGroups         []string          `json:"denied_groups,omitempty"`
	GroupAttribute       *string           `json:"group_attribute,omitempty"`
}

UpdateSAMLProviderRequest represents a request to update a SAML provider

type UpdateServiceKeyRequest

type UpdateServiceKeyRequest struct {
	Name               *string  `json:"name,omitempty"`
	Description        *string  `json:"description,omitempty"`
	Scopes             []string `json:"scopes,omitempty"`
	AllowedNamespaces  []string `json:"allowed_namespaces,omitempty"`
	Enabled            *bool    `json:"enabled,omitempty"`
	RateLimitPerMinute *int     `json:"rate_limit_per_minute,omitempty"`
	RateLimitPerHour   *int     `json:"rate_limit_per_hour,omitempty"`
}

UpdateServiceKeyRequest represents a request to update a service key

type UpdateTemplateRequest

type UpdateTemplateRequest struct {
	Subject  string  `json:"subject"`
	HTMLBody string  `json:"html_body"`
	TextBody *string `json:"text_body,omitempty"`
}

type UpdateTenantRequest

type UpdateTenantRequest struct {
	Name     *string                `json:"name,omitempty"`
	Metadata map[string]interface{} `json:"metadata,omitempty"`
}

type UpdateTenantSettingsRequest

type UpdateTenantSettingsRequest struct {
	Settings map[string]any `json:"settings"`
	Secrets  map[string]any `json:"secrets,omitempty"`
}

UpdateTenantSettingsRequest represents the request to update tenant settings

type UploadChunkResponse

type UploadChunkResponse struct {
	ChunkIndex int                          `json:"chunk_index"`
	ETag       string                       `json:"etag,omitempty"`
	Size       int64                        `json:"size"`
	Session    ChunkedUploadSessionResponse `json:"session"`
}

UploadChunkResponse represents the response after uploading a chunk

type UploadTenantSchemaRequest

type UploadTenantSchemaRequest struct {
	Schema string `json:"schema"`
}

UploadTenantSchemaRequest represents the request body for uploading a tenant schema

type UpsertGitHubConfigRequest

type UpsertGitHubConfigRequest struct {
	Repository           string                  `json:"repository"`
	AutoCreateOnPR       *bool                   `json:"auto_create_on_pr,omitempty"`
	AutoDeleteOnMerge    *bool                   `json:"auto_delete_on_merge,omitempty"`
	DefaultDataCloneMode branching.DataCloneMode `json:"default_data_clone_mode,omitempty"`
	WebhookSecret        *string                 `json:"webhook_secret,omitempty"`
}

UpsertGitHubConfigRequest represents the request for creating/updating GitHub config

type UserManagementHandler

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

func NewUserManagementHandler

func NewUserManagementHandler(userMgmtService *auth.UserManagementService, authService *auth.Service) *UserManagementHandler

func (*UserManagementHandler) DeleteUser

func (h *UserManagementHandler) DeleteUser(c fiber.Ctx) error

func (*UserManagementHandler) GetUserByID

func (h *UserManagementHandler) GetUserByID(c fiber.Ctx) error

func (*UserManagementHandler) InviteUser

func (h *UserManagementHandler) InviteUser(c fiber.Ctx) error

func (*UserManagementHandler) ListUsers

func (h *UserManagementHandler) ListUsers(c fiber.Ctx) error

func (*UserManagementHandler) LockUser

func (h *UserManagementHandler) LockUser(c fiber.Ctx) error

func (*UserManagementHandler) ResetUserPassword

func (h *UserManagementHandler) ResetUserPassword(c fiber.Ctx) error

func (*UserManagementHandler) UnlockUser

func (h *UserManagementHandler) UnlockUser(c fiber.Ctx) error

func (*UserManagementHandler) UpdateUser

func (h *UserManagementHandler) UpdateUser(c fiber.Ctx) error

func (*UserManagementHandler) UpdateUserRole

func (h *UserManagementHandler) UpdateUserRole(c fiber.Ctx) error

type UserSettingsHandler

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

UserSettingsHandler handles user-specific secret settings operations

func NewUserSettingsHandler

func NewUserSettingsHandler(db *database.Connection, settingsService *settings.CustomSettingsService) *UserSettingsHandler

NewUserSettingsHandler creates a new user settings handler

func (*UserSettingsHandler) CreateSecret

func (h *UserSettingsHandler) CreateSecret(c fiber.Ctx) error

CreateSecret creates a new encrypted user-specific secret setting POST /api/v1/settings/secret

func (*UserSettingsHandler) DeleteSecret

func (h *UserSettingsHandler) DeleteSecret(c fiber.Ctx) error

DeleteSecret deletes a user's secret setting DELETE /api/v1/settings/secret/*

func (*UserSettingsHandler) DeleteSetting

func (h *UserSettingsHandler) DeleteSetting(c fiber.Ctx) error

DeleteSetting removes a user's setting DELETE /api/v1/settings/user/:key

func (*UserSettingsHandler) GetSecret

func (h *UserSettingsHandler) GetSecret(c fiber.Ctx) error

GetSecret returns metadata for a user's secret setting (never returns the value) GET /api/v1/settings/secret/*

func (*UserSettingsHandler) GetSetting

func (h *UserSettingsHandler) GetSetting(c fiber.Ctx) error

GetSetting retrieves a setting with user -> system fallback GET /api/v1/settings/user/:key

func (*UserSettingsHandler) GetSystemSettingPublic

func (h *UserSettingsHandler) GetSystemSettingPublic(c fiber.Ctx) error

GetSystemSettingPublic retrieves a system-level setting (user_id IS NULL) GET /api/v1/settings/user/system/:key

func (*UserSettingsHandler) GetUserOwnSetting

func (h *UserSettingsHandler) GetUserOwnSetting(c fiber.Ctx) error

GetUserOwnSetting retrieves only the user's own setting (no fallback) GET /api/v1/settings/user/own/:key

func (*UserSettingsHandler) GetUserSecretValue

func (h *UserSettingsHandler) GetUserSecretValue(c fiber.Ctx) error

GetUserSecretValue retrieves the decrypted value of a specific user's secret This is a privileged operation that requires service_role GET /api/v1/admin/settings/user/:user_id/secret/:key/decrypt

func (*UserSettingsHandler) ListSecrets

func (h *UserSettingsHandler) ListSecrets(c fiber.Ctx) error

ListSecrets returns metadata for all user's secret settings GET /api/v1/settings/secrets

func (*UserSettingsHandler) ListSettings

func (h *UserSettingsHandler) ListSettings(c fiber.Ctx) error

ListSettings returns all user's own settings GET /api/v1/settings/user/list

func (*UserSettingsHandler) SetSecretsService

func (h *UserSettingsHandler) SetSecretsService(secretsService *settings.SecretsService)

SetSecretsService sets the secrets service for decryption operations

func (*UserSettingsHandler) SetSetting

func (h *UserSettingsHandler) SetSetting(c fiber.Ctx) error

SetSetting creates or updates a user setting PUT /api/v1/settings/user/:key

func (*UserSettingsHandler) UpdateSecret

func (h *UserSettingsHandler) UpdateSecret(c fiber.Ctx) error

UpdateSecret updates a user's secret setting PUT /api/v1/settings/secret/*

type ValidateInvitationResponse

type ValidateInvitationResponse struct {
	Valid      bool                  `json:"valid"`
	Invitation *auth.InvitationToken `json:"invitation,omitempty"`
	Error      string                `json:"error,omitempty"`
}

type ValidateMetadataRequest

type ValidateMetadataRequest struct {
	MetadataURL *string `json:"metadata_url,omitempty"`
	MetadataXML *string `json:"metadata_xml,omitempty"`
}

ValidateMetadataRequest represents a request to validate SAML metadata

type ValidateMetadataResponse

type ValidateMetadataResponse struct {
	Valid       bool    `json:"valid"`
	EntityID    string  `json:"entity_id,omitempty"`
	SsoURL      string  `json:"sso_url,omitempty"`
	SloURL      string  `json:"slo_url,omitempty"`
	Certificate string  `json:"certificate,omitempty"`
	Error       *string `json:"error,omitempty"`
}

ValidateMetadataResponse represents the response from metadata validation

type VectorCapabilities

type VectorCapabilities struct {
	Enabled           bool   `json:"enabled"`
	PgVectorInstalled bool   `json:"pgvector_installed"`
	PgVectorVersion   string `json:"pgvector_version,omitempty"`
	EmbeddingEnabled  bool   `json:"embedding_enabled"`
	EmbeddingProvider string `json:"embedding_provider,omitempty"`
	EmbeddingModel    string `json:"embedding_model,omitempty"`
}

type VectorHandler

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

func NewVectorHandler

func NewVectorHandler(vectorManager *VectorManager, schemaInspector *database.SchemaInspector, db *database.Connection, baseConfig *config.Config) (*VectorHandler, error)

func (*VectorHandler) GetEmbeddingService

func (h *VectorHandler) GetEmbeddingService() *ai.EmbeddingService

func (*VectorHandler) HandleEmbed

func (h *VectorHandler) HandleEmbed(c fiber.Ctx) error

func (*VectorHandler) HandleGetCapabilities

func (h *VectorHandler) HandleGetCapabilities(c fiber.Ctx) error

func (*VectorHandler) HandleSearch

func (h *VectorHandler) HandleSearch(c fiber.Ctx) error

func (*VectorHandler) IsEmbeddingConfigured

func (h *VectorHandler) IsEmbeddingConfigured() bool

func (*VectorHandler) IsPgVectorInstalled

func (h *VectorHandler) IsPgVectorInstalled(c fiber.Ctx) bool

type VectorManager

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

VectorManager manages the embedding service with support for dynamic configuration refresh from database-stored AI providers. It follows the pattern established by email.Manager.

func NewVectorManager

func NewVectorManager(envConfig *config.AIConfig, aiStorage *ai.Storage, schemaInspector *database.SchemaInspector, db *database.Connection) *VectorManager

NewVectorManager creates a new vector manager with hot-reload capability

func (*VectorManager) GetEmbeddingService

func (m *VectorManager) GetEmbeddingService() *ai.EmbeddingService

GetEmbeddingService returns the current embedding service (thread-safe)

func (*VectorManager) GetEmbeddingServiceForProvider

func (m *VectorManager) GetEmbeddingServiceForProvider(ctx context.Context, providerID string) (*ai.EmbeddingService, error)

GetEmbeddingServiceForProvider creates an embedding service for a specific provider by ID This is used when admins want to use a different provider than the default

func (*VectorManager) RefreshFromDatabase

func (m *VectorManager) RefreshFromDatabase(ctx context.Context) error

RefreshFromDatabase rebuilds the embedding service from database-stored AI providers

type VectorQueryFilter

type VectorQueryFilter struct {
	Column   string      `json:"column"`
	Operator string      `json:"operator"`
	Value    interface{} `json:"value"`
}

type VectorSearchRequest

type VectorSearchRequest struct {
	Table          string              `json:"table"`
	Column         string              `json:"column"`
	Query          string              `json:"query,omitempty"`
	Vector         []float64           `json:"vector,omitempty"`
	Metric         string              `json:"metric,omitempty"`
	MatchThreshold *float64            `json:"match_threshold,omitempty"`
	MatchCount     *int                `json:"match_count,omitempty"`
	Select         string              `json:"select,omitempty"`
	Filters        []VectorQueryFilter `json:"filters,omitempty"`
}

type VectorSearchResponse

type VectorSearchResponse struct {
	Data      []map[string]interface{} `json:"data"`
	Distances []float64                `json:"distances,omitempty"`
	Model     string                   `json:"model,omitempty"`
}

type WebhookHandler

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

WebhookHandler handles HTTP requests for webhooks

func NewWebhookHandler

func NewWebhookHandler(webhookService *webhook.WebhookService) *WebhookHandler

NewWebhookHandler creates a new webhook handler

func (*WebhookHandler) CreateWebhook

func (h *WebhookHandler) CreateWebhook(c fiber.Ctx) error

CreateWebhook creates a new webhook

func (*WebhookHandler) DeleteWebhook

func (h *WebhookHandler) DeleteWebhook(c fiber.Ctx) error

DeleteWebhook deletes a webhook

func (*WebhookHandler) GetWebhook

func (h *WebhookHandler) GetWebhook(c fiber.Ctx) error

GetWebhook retrieves a webhook by ID

func (*WebhookHandler) ListDeliveries

func (h *WebhookHandler) ListDeliveries(c fiber.Ctx) error

ListDeliveries lists webhook deliveries

func (*WebhookHandler) ListWebhooks

func (h *WebhookHandler) ListWebhooks(c fiber.Ctx) error

ListWebhooks lists all webhooks

func (*WebhookHandler) TestWebhook

func (h *WebhookHandler) TestWebhook(c fiber.Ctx) error

TestWebhook sends a test webhook

func (*WebhookHandler) UpdateWebhook

func (h *WebhookHandler) UpdateWebhook(c fiber.Ctx) error

UpdateWebhook updates a webhook

type WebhookHandlers

type WebhookHandlers struct {
	Handler *WebhookHandler
	Trigger *webhook.TriggerService
}

WebhookHandlers groups webhook handlers.

type WebhookResponse

type WebhookResponse struct {
	ID                  uuid.UUID             `json:"id"`
	Name                string                `json:"name"`
	Description         *string               `json:"description,omitempty"`
	URL                 string                `json:"url"`
	Enabled             bool                  `json:"enabled"`
	Events              []webhook.EventConfig `json:"events"`
	MaxRetries          int                   `json:"max_retries"`
	RetryBackoffSeconds int                   `json:"retry_backoff_seconds"`
	TimeoutSeconds      int                   `json:"timeout_seconds"`
	Headers             map[string]string     `json:"headers"`
	Scope               string                `json:"scope"` // "user" or "global"
	CreatedBy           *uuid.UUID            `json:"created_by,omitempty"`
	CreatedAt           time.Time             `json:"created_at"`
	UpdatedAt           time.Time             `json:"updated_at"`
}

WebhookResponse represents a webhook response without the secret H-21: WebhookResponse DTO excludes secret field for security

Source Files

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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