serverdb

package
v0.30.0 Latest Latest
Warning

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

Go to latest
Published: Feb 6, 2026 License: MIT Imports: 12 Imported by: 0

Documentation

Index

Constants

View Source
const (
	RoleOwner  = "owner"
	RoleWriter = "writer"
	RoleReader = "reader"
)

Role constants

View Source
const (
	AuthStatusPending  = "pending"
	AuthStatusVerified = "verified"
	AuthStatusExpired  = "expired"
	AuthStatusUsed     = "used"
	AuthRequestTTL     = 15 * time.Minute
	PollInterval       = 5
)
View Source
const ServerSchemaVersion = 2

ServerSchemaVersion is the current server database schema version

Variables

View Source
var Migrations = []Migration{

	{
		Version:     2,
		Description: "Add auth_requests table for device auth flow",
		SQL: `CREATE TABLE IF NOT EXISTS auth_requests (
			id TEXT PRIMARY KEY,
			email TEXT NOT NULL,
			device_code TEXT UNIQUE NOT NULL,
			user_code TEXT UNIQUE NOT NULL,
			status TEXT NOT NULL DEFAULT 'pending',
			user_id TEXT,
			api_key_id TEXT,
			expires_at DATETIME NOT NULL,
			verified_at DATETIME,
			created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
		);
		CREATE INDEX IF NOT EXISTS idx_auth_requests_device_code ON auth_requests(device_code);
		CREATE INDEX IF NOT EXISTS idx_auth_requests_user_code ON auth_requests(user_code);
		CREATE INDEX IF NOT EXISTS idx_auth_requests_status ON auth_requests(status);
		CREATE INDEX IF NOT EXISTS idx_auth_requests_cleanup ON auth_requests(status, expires_at);`,
	},
}

Migrations is the list of all server database migrations in order

Functions

func NewID

func NewID() string

NewID generates a project ID (exported for callers that need to pre-generate IDs).

Types

type APIKey

type APIKey struct {
	ID         string
	UserID     string
	KeyPrefix  string
	Name       string
	Scopes     string
	ExpiresAt  *time.Time
	LastUsedAt *time.Time
	CreatedAt  time.Time
}

APIKey represents a stored API key (without the plaintext secret).

type AuthRequest

type AuthRequest struct {
	ID         string
	Email      string
	DeviceCode string
	UserCode   string
	Status     string
	UserID     *string
	APIKeyID   *string
	ExpiresAt  time.Time
	VerifiedAt *time.Time
	CreatedAt  time.Time
}

AuthRequest represents a device authorization request.

type Membership

type Membership struct {
	ProjectID string
	UserID    string
	Role      string
	InvitedBy string
	CreatedAt time.Time
}

Membership represents a user's role in a project.

type Migration

type Migration struct {
	Version     int
	Description string
	SQL         string
}

Migration defines a server database migration

type Project

type Project struct {
	ID          string
	Name        string
	Description string
	CreatedAt   time.Time
	UpdatedAt   time.Time
	DeletedAt   *time.Time
}

Project represents a sync project.

type ServerDB

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

ServerDB wraps the server database connection

func Open

func Open(dbPath string) (*ServerDB, error)

Open opens the server database and runs any pending migrations. If the database file does not exist, it is created and initialized.

func (*ServerDB) AddMember

func (db *ServerDB) AddMember(projectID, userID, role, invitedByUserID string) (*Membership, error)

AddMember adds a user to a project with the given role.

func (*ServerDB) Authorize

func (db *ServerDB) Authorize(projectID, userID, requiredRole string) error

Authorize checks that the user has at least the required role in the project.

func (*ServerDB) CanDeleteProject

func (db *ServerDB) CanDeleteProject(projectID, userID string) error

CanDeleteProject checks if the user can delete the project (requires owner role).

func (*ServerDB) CanManageMembers

func (db *ServerDB) CanManageMembers(projectID, userID string) error

CanManageMembers checks if the user can manage members (requires owner role).

func (*ServerDB) CanPullEvents

func (db *ServerDB) CanPullEvents(projectID, userID string) error

CanPullEvents checks if the user can pull events (requires reader role).

func (*ServerDB) CanPushEvents

func (db *ServerDB) CanPushEvents(projectID, userID string) error

CanPushEvents checks if the user can push events (requires writer role).

func (*ServerDB) CanViewProject

func (db *ServerDB) CanViewProject(projectID, userID string) error

CanViewProject checks if the user can view the project (requires reader role).

func (*ServerDB) CleanupExpiredAuthRequests

func (db *ServerDB) CleanupExpiredAuthRequests() (int64, error)

CleanupExpiredAuthRequests marks pending auth requests past their expiry as expired.

func (*ServerDB) Close

func (db *ServerDB) Close() error

Close checkpoints the WAL and closes the database connection.

func (*ServerDB) CompleteAuthRequest

func (db *ServerDB) CompleteAuthRequest(deviceCode string) (*AuthRequest, error)

CompleteAuthRequest transitions a verified auth request to used and returns it. Returns nil if the request is not in verified status.

func (*ServerDB) CreateAuthRequest

func (db *ServerDB) CreateAuthRequest(email string) (*AuthRequest, error)

CreateAuthRequest creates a new device auth request for the given email.

func (*ServerDB) CreateProject

func (db *ServerDB) CreateProject(name, description, ownerUserID string) (*Project, error)

CreateProject creates a new project and adds the owner as a member in a single transaction.

func (*ServerDB) CreateProjectWithID

func (db *ServerDB) CreateProjectWithID(id, name, description, ownerUserID string) (*Project, error)

CreateProjectWithID creates a new project using a pre-generated ID and adds the owner as a member.

func (*ServerDB) CreateUser

func (db *ServerDB) CreateUser(email string) (*User, error)

CreateUser inserts a new user with the given email (lowercased).

func (*ServerDB) ForceExpireAuthRequestForTest

func (db *ServerDB) ForceExpireAuthRequestForTest(id string, expiresAt time.Time)

ForceExpireAuthRequestForTest forces an auth request's expiry time (test-only helper).

func (*ServerDB) GenerateAPIKey

func (db *ServerDB) GenerateAPIKey(userID, name, scopes string, expiresAt *time.Time) (string, *APIKey, error)

GenerateAPIKey creates a new API key for the given user. Returns the plaintext key (shown once) and the stored APIKey record.

func (*ServerDB) GetAuthRequestByDeviceCode

func (db *ServerDB) GetAuthRequestByDeviceCode(deviceCode string) (*AuthRequest, error)

GetAuthRequestByDeviceCode returns the auth request with the given device code, or nil.

func (*ServerDB) GetAuthRequestByUserCode

func (db *ServerDB) GetAuthRequestByUserCode(userCode string) (*AuthRequest, error)

GetAuthRequestByUserCode returns the pending, non-expired auth request with the given user code, or nil.

func (*ServerDB) GetMembership

func (db *ServerDB) GetMembership(projectID, userID string) (*Membership, error)

GetMembership returns a user's membership in a project, or nil if not found.

func (*ServerDB) GetProject

func (db *ServerDB) GetProject(id string, includeSoftDeleted bool) (*Project, error)

GetProject returns a project by ID. If includeSoftDeleted is false, soft-deleted projects are excluded.

func (*ServerDB) GetSyncCursor

func (db *ServerDB) GetSyncCursor(projectID, clientID string) (*SyncCursor, error)

GetSyncCursor returns the sync cursor for a project/client pair, or nil if not found.

func (*ServerDB) GetUserByEmail

func (db *ServerDB) GetUserByEmail(email string) (*User, error)

GetUserByEmail returns the user with the given email (case-insensitive), or nil if not found.

func (*ServerDB) GetUserByID

func (db *ServerDB) GetUserByID(id string) (*User, error)

GetUserByID returns the user with the given ID, or nil if not found.

func (*ServerDB) ListAPIKeys

func (db *ServerDB) ListAPIKeys(userID string) ([]*APIKey, error)

ListAPIKeys returns all API keys for a user (without secrets).

func (*ServerDB) ListMembers

func (db *ServerDB) ListMembers(projectID string) ([]*Membership, error)

ListMembers returns all members of a project.

func (*ServerDB) ListProjectsForUser

func (db *ServerDB) ListProjectsForUser(userID string) ([]*Project, error)

ListProjectsForUser returns all non-deleted projects the user is a member of.

func (*ServerDB) ListUsers

func (db *ServerDB) ListUsers() ([]*User, error)

ListUsers returns all users.

func (*ServerDB) Ping

func (db *ServerDB) Ping() error

Ping checks the database connection is alive.

func (*ServerDB) RemoveMember

func (db *ServerDB) RemoveMember(projectID, userID string) error

RemoveMember removes a user from a project. Fails if removing the user would leave the project with no owners.

func (*ServerDB) RevokeAPIKey

func (db *ServerDB) RevokeAPIKey(keyID, userID string) error

RevokeAPIKey deletes an API key, only if owned by the given user.

func (*ServerDB) RunMigrations

func (db *ServerDB) RunMigrations() (int, error)

RunMigrations runs any pending database migrations.

func (*ServerDB) SetAuthRequestAPIKey

func (db *ServerDB) SetAuthRequestAPIKey(id, apiKeyID string) error

SetAuthRequestAPIKey sets the API key ID on an auth request.

func (*ServerDB) SetEmailVerified

func (db *ServerDB) SetEmailVerified(userID string) error

SetEmailVerified marks the user's email as verified.

func (*ServerDB) SoftDeleteProject

func (db *ServerDB) SoftDeleteProject(id string) error

SoftDeleteProject marks a project as deleted.

func (*ServerDB) UpdateMemberRole

func (db *ServerDB) UpdateMemberRole(projectID, userID, newRole string) error

UpdateMemberRole changes a member's role.

func (*ServerDB) UpdateProject

func (db *ServerDB) UpdateProject(id, name, description string) (*Project, error)

UpdateProject updates a project's name and description.

func (*ServerDB) UpsertSyncCursor

func (db *ServerDB) UpsertSyncCursor(projectID, clientID string, lastEventID int64) error

UpsertSyncCursor creates or updates a sync cursor for a project/client pair.

func (*ServerDB) VerifyAPIKey

func (db *ServerDB) VerifyAPIKey(plaintextKey string) (*APIKey, *User, error)

VerifyAPIKey checks a plaintext key against stored hashes. Returns the matching APIKey and associated User, or an error.

func (*ServerDB) VerifyAuthRequest

func (db *ServerDB) VerifyAuthRequest(userCode, userID string) error

VerifyAuthRequest marks a pending auth request as verified with the given user ID.

type SyncCursor

type SyncCursor struct {
	ProjectID   string
	ClientID    string
	LastEventID int64
	LastSyncAt  *time.Time
}

SyncCursor tracks a client's sync position in a project.

type User

type User struct {
	ID              string
	Email           string
	EmailVerifiedAt *time.Time
	CreatedAt       time.Time
	UpdatedAt       time.Time
}

User represents a registered user.

Jump to

Keyboard shortcuts

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