serverdb

package
v0.51.0 Latest Latest
Warning

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

Go to latest
Published: Jun 21, 2026 License: MIT Imports: 17 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

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

Role constants

View Source
const (
	AuthEventStarted             = "started"
	AuthEventCodeVerified        = "code_verified"
	AuthEventKeyIssued           = "key_issued"
	AuthEventExpired             = "expired"
	AuthEventFailed              = "failed"
	AuthEventImpersonationIssued = "impersonation_issued"
	AuthEventKeyRevoked          = "key_revoked"

	// Email-login lifecycle events (used by D1-D5).
	AuthEventChallengeStarted = "challenge_started" // web/start or device/start called, challenge created
	AuthEventEmailSent        = "email_sent"        // email dispatched to provider without error
	AuthEventEmailSuppressed  = "email_suppressed"  // challenge created for unknown/disabled user, generic response sent
	AuthEventWebExchanged     = "web_exchanged"     // web/exchange succeeded, key issued
	AuthEventDeviceVerified   = "device_verified"   // emailed link consumed, device request marked verified
	AuthEventLoginFailed      = "login_failed"      // any terminal failure: wrong token, wrong state, wrong verifier, expired
)

Auth event type constants.

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

	ChallengeStatusPending    = "pending"
	ChallengeStatusConsumed   = "consumed"
	ChallengeStatusExpired    = "expired"
	ChallengeStatusVerified   = "verified"
	ChallengeStatusFailed     = "failed"
	ChallengeStatusSuppressed = "suppressed"
)

Challenge TTL and status constants.

View Source
const (
	InvitationStatusPending  = "pending"
	InvitationStatusAccepted = "accepted"
	InvitationStatusDeclined = "declined"
	InvitationStatusExpired  = "expired"
)
View Source
const (
	DefaultPageLimit = 50
	MaxPageLimit     = 200
)
View Source
const ServerSchemaVersion = 6

ServerSchemaVersion is the current server database schema version

Variables

View Source
var (
	ErrChallengeNotFound        = errors.New("email challenge not found")
	ErrChallengeAlreadyConsumed = errors.New("email challenge already consumed")
	ErrChallengeExpired         = errors.New("email challenge expired")
	ErrChallengeInvalidToken    = errors.New("email challenge invalid token")
)

Sentinel errors returned by ConsumeChallenge.

View Source
var (
	ErrInvitationNotFound      = errors.New("invitation not found")
	ErrInvitationNotPending    = errors.New("invitation not pending")
	ErrInvitationExpired       = errors.New("invitation expired")
	ErrInvitationEmailMismatch = errors.New("invitation email mismatch")
)
View Source
var ErrNotFound = errors.New("not found")

ErrNotFound is returned by serverdb methods when a requested record does not exist.

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);`,
	},
	{
		Version:     3,
		Description: "Add is_admin, auth_events, rate_limit_events, project event caching",
		SQL: `ALTER TABLE users ADD COLUMN is_admin BOOLEAN NOT NULL DEFAULT 0;

		CREATE TABLE IF NOT EXISTS auth_events (
			id INTEGER PRIMARY KEY AUTOINCREMENT,
			auth_request_id TEXT NOT NULL,
			email TEXT NOT NULL,
			event_type TEXT NOT NULL,
			metadata TEXT DEFAULT '{}',
			created_at DATETIME DEFAULT CURRENT_TIMESTAMP
		);
		CREATE INDEX IF NOT EXISTS idx_auth_events_type ON auth_events(event_type);
		CREATE INDEX IF NOT EXISTS idx_auth_events_email ON auth_events(email);
		CREATE INDEX IF NOT EXISTS idx_auth_events_created ON auth_events(created_at);

		CREATE TABLE IF NOT EXISTS rate_limit_events (
			id INTEGER PRIMARY KEY AUTOINCREMENT,
			key_id TEXT,
			ip TEXT,
			endpoint_class TEXT NOT NULL,
			created_at DATETIME DEFAULT CURRENT_TIMESTAMP
		);
		CREATE INDEX IF NOT EXISTS idx_rle_created ON rate_limit_events(created_at);
		CREATE INDEX IF NOT EXISTS idx_rle_key ON rate_limit_events(key_id);

		ALTER TABLE projects ADD COLUMN event_count INTEGER NOT NULL DEFAULT 0;
		ALTER TABLE projects ADD COLUMN last_event_at DATETIME;`,
	},
	{
		Version:     4,
		Description: "Add auth_email_challenges table for email-verified auth",
		SQL: `CREATE TABLE auth_email_challenges (
			id TEXT PRIMARY KEY,
			purpose TEXT NOT NULL CHECK (purpose IN ('web_login','device_login','email_verify','admin_login')),
			email TEXT NOT NULL,
			user_id TEXT,
			selector TEXT UNIQUE NOT NULL,
			token_hash TEXT NOT NULL,
			otp_hash TEXT,
			device_code_hash TEXT,
			code_challenge TEXT,
			code_challenge_method TEXT,
			redirect_uri TEXT,
			state_hash TEXT,
			status TEXT NOT NULL DEFAULT 'pending'
				CHECK (status IN ('pending','verified','consumed','expired','failed','suppressed')),
			attempts INTEGER NOT NULL DEFAULT 0,
			ip TEXT,
			user_agent TEXT,
			expires_at DATETIME NOT NULL,
			verified_at DATETIME,
			consumed_at DATETIME,
			created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
			FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE SET NULL
		);
		CREATE INDEX idx_auth_email_challenges_email_created ON auth_email_challenges(email, created_at);
		CREATE INDEX idx_auth_email_challenges_device ON auth_email_challenges(device_code_hash);
		CREATE INDEX idx_auth_email_challenges_cleanup ON auth_email_challenges(status, expires_at);`,
	},
	{
		Version:     5,
		Description: "Add project invitations table",
		SQL: `CREATE TABLE IF NOT EXISTS invitations (
			id TEXT PRIMARY KEY,
			project_id TEXT NOT NULL,
			email TEXT NOT NULL,
			role TEXT NOT NULL CHECK(role IN ('owner', 'writer', 'reader')),
			invited_by TEXT NOT NULL,
			token_hash TEXT NOT NULL,
			status TEXT NOT NULL DEFAULT 'pending'
				CHECK(status IN ('pending', 'accepted', 'declined', 'expired')),
			created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
			expires_at DATETIME NOT NULL,
			accepted_at DATETIME,
			FOREIGN KEY (project_id) REFERENCES projects(id) ON DELETE CASCADE,
			FOREIGN KEY (invited_by) REFERENCES users(id) ON DELETE CASCADE
		);
		CREATE INDEX IF NOT EXISTS idx_invitations_project ON invitations(project_id);
		CREATE INDEX IF NOT EXISTS idx_invitations_email_status ON invitations(email, status);
		CREATE INDEX IF NOT EXISTS idx_invitations_cleanup ON invitations(status, expires_at);
		CREATE UNIQUE INDEX IF NOT EXISTS idx_invitations_token_hash ON invitations(token_hash);`,
	},
	{
		Version:     6,
		Description: "Add slug column to projects for stable canonical URL slugs",
		SQL: `ALTER TABLE projects ADD COLUMN slug TEXT;
		CREATE UNIQUE INDEX IF NOT EXISTS idx_projects_slug ON projects(slug);`,
	},
}

Migrations is the list of all server database migrations in order

Functions

func EncodeCursor added in v0.32.0

func EncodeCursor(data CursorData) string

EncodeCursor encodes cursor data to an opaque base64 string.

func NewID

func NewID() string

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

func NormalizeLimit added in v0.32.0

func NormalizeLimit(limit int) int

NormalizeLimit clamps limit to valid range.

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 AdminProject added in v0.32.0

type AdminProject struct {
	ID          string  `json:"id"`
	Name        string  `json:"name"`
	Slug        string  `json:"slug"`
	Description string  `json:"description,omitempty"`
	EventCount  int     `json:"event_count"`
	LastEventAt *string `json:"last_event_at"`
	MemberCount int     `json:"member_count"`
	CreatedAt   string  `json:"created_at"`
	UpdatedAt   string  `json:"updated_at"`
	DeletedAt   *string `json:"deleted_at,omitempty"`
}

AdminProject represents a project with aggregate info for admin API.

type AdminProjectMember added in v0.32.0

type AdminProjectMember struct {
	UserID    string `json:"user_id"`
	Email     string `json:"email"`
	Role      string `json:"role"`
	InvitedBy string `json:"invited_by"`
	CreatedAt string `json:"created_at"`
}

AdminProjectMember represents a project member with user email for admin view.

type AdminUser added in v0.32.0

type AdminUser struct {
	ID           string  `json:"id"`
	Email        string  `json:"email"`
	IsAdmin      bool    `json:"is_admin"`
	CreatedAt    string  `json:"created_at"`
	ProjectCount int     `json:"project_count"`
	LastActivity *string `json:"last_activity"`
}

AdminUser represents a user with aggregate info for the admin API.

type AdminUserDetail added in v0.32.0

type AdminUserDetail struct {
	AdminUser
	Projects []UserProject `json:"projects"`
}

AdminUserDetail extends AdminUser with project membership details.

type AuthEvent added in v0.32.0

type AuthEvent struct {
	ID            int64  `json:"id"`
	AuthRequestID string `json:"auth_request_id"`
	Email         string `json:"email"`
	EventType     string `json:"event_type"`
	Metadata      string `json:"metadata"`
	CreatedAt     string `json:"created_at"`
}

AuthEvent represents a row in the auth_events table.

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 ChallengeOptions added in v0.49.0

type ChallengeOptions struct {
	DeviceCodeHash      *string
	CodeChallenge       *string
	CodeChallengeMethod *string
	RedirectURI         *string
	StateHash           *string
	IP                  *string
	UserAgent           *string
}

ChallengeOptions holds optional fields for CreateEmailChallenge.

type CursorData added in v0.32.0

type CursorData struct {
	ID        string `json:"id,omitempty"`
	CreatedAt string `json:"created_at,omitempty"`
	Value     string `json:"value,omitempty"`
}

CursorData holds the opaque cursor state.

func DecodeCursor added in v0.32.0

func DecodeCursor(cursor string) (CursorData, error)

DecodeCursor decodes an opaque cursor string back to CursorData.

type EmailChallenge added in v0.49.0

type EmailChallenge struct {
	ID                  string
	Purpose             string
	Email               string
	UserID              *string
	Selector            string
	TokenHash           string
	OTPHash             *string
	DeviceCodeHash      *string
	CodeChallenge       *string
	CodeChallengeMethod *string
	RedirectURI         *string
	StateHash           *string
	Status              string
	Attempts            int
	IP                  *string
	UserAgent           *string
	ExpiresAt           time.Time
	VerifiedAt          *time.Time
	ConsumedAt          *time.Time
	CreatedAt           time.Time
}

EmailChallenge mirrors the auth_email_challenges table row. Nullable columns use pointer types.

type Invitation added in v0.50.0

type Invitation struct {
	ID         string
	ProjectID  string
	Email      string
	Role       string
	InvitedBy  string
	TokenHash  string
	Status     string
	CreatedAt  time.Time
	ExpiresAt  time.Time
	AcceptedAt *time.Time
}

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 PaginatedResult added in v0.32.0

type PaginatedResult[T any] struct {
	Data       []T    `json:"data"`
	NextCursor string `json:"next_cursor,omitempty"`
	HasMore    bool   `json:"has_more"`
}

PaginatedResult holds a page of results with cursor information.

func PaginatedQuery added in v0.32.0

func PaginatedQuery[T any](
	db *sql.DB,
	baseQuery string,
	args []any,
	limit int,
	cursor string,
	cursorColumn string,
	scanRow func(*sql.Rows) (T, string, error),
) (*PaginatedResult[T], error)

PaginatedQuery executes a paginated query using cursor-based pagination.

baseQuery is the SELECT query without ORDER BY or LIMIT clauses. args contains any existing WHERE clause parameters. cursor is the opaque cursor string from a previous PaginatedResult.NextCursor. cursorColumn is the column used for ordering and cursor comparison (e.g. "id", "created_at"). scanRow scans a single row and returns (item, cursorValue, error) where cursorValue is the value to encode in the next cursor.

The function fetches limit+1 rows to determine HasMore without a separate COUNT query.

type Project

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

Project represents a sync project.

type RateLimitEvent added in v0.32.0

type RateLimitEvent struct {
	ID            int64
	KeyID         string // empty string if IP-based (nullable in DB)
	IP            string
	EndpointClass string // auth, push, pull, other
	CreatedAt     string
}

RateLimitEvent represents a rate limit violation event.

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) AcceptInvitation added in v0.50.0

func (db *ServerDB) AcceptInvitation(invitationID, userID, email string) (*Membership, error)

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) AdminGetProject added in v0.32.0

func (db *ServerDB) AdminGetProject(id string) (*AdminProject, error)

AdminGetProject returns a single project with aggregate info including description.

func (*ServerDB) AdminGetUser added in v0.32.0

func (db *ServerDB) AdminGetUser(id string) (*AdminUserDetail, error)

AdminGetUser returns a single user with aggregate info and project memberships.

func (*ServerDB) AdminListProjectMembers added in v0.32.0

func (db *ServerDB) AdminListProjectMembers(projectID string) ([]AdminProjectMember, error)

AdminListProjectMembers returns all members of a project with user email.

func (*ServerDB) AdminListProjects added in v0.32.0

func (db *ServerDB) AdminListProjects(query string, includeDeleted bool, limit int, cursor string) (*PaginatedResult[AdminProject], error)

AdminListProjects returns a paginated list of all projects with aggregate counts.

func (*ServerDB) AdminListUsers added in v0.32.0

func (db *ServerDB) AdminListUsers(query string, limit int, cursor string) (*PaginatedResult[AdminUser], error)

AdminListUsers returns a paginated list of users with aggregate counts. The query parameter filters by email (LIKE match).

func (*ServerDB) AdminRevokeAPIKey added in v0.49.0

func (db *ServerDB) AdminRevokeAPIKey(keyID string) error

AdminRevokeAPIKey deletes any API key by ID regardless of owner. Returns ErrNotFound if no row was deleted.

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) BackfillProjectSlugs added in v0.50.0

func (db *ServerDB) BackfillProjectSlugs() error

BackfillProjectSlugs assigns a slug to every project that has a NULL or empty slug. Projects are processed in created_at ASC order so the deterministic ordering means the same project always wins the base slug. This is safe to call on every startup — projects that already have a slug are skipped.

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) CleanupAuthEvents added in v0.32.0

func (db *ServerDB) CleanupAuthEvents(olderThan time.Duration) (int64, error)

CleanupAuthEvents deletes auth events older than the given duration. Returns the number of rows deleted.

func (*ServerDB) CleanupExpiredAuthRequests

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

CleanupExpiredAuthRequests marks pending auth requests past their expiry as expired.

func (*ServerDB) CleanupExpiredChallenges added in v0.49.0

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

CleanupExpiredChallenges marks pending challenges that are past their expiry as expired. Returns the number of rows updated.

func (*ServerDB) CleanupRateLimitEvents added in v0.32.0

func (db *ServerDB) CleanupRateLimitEvents(olderThan time.Duration) (int64, error)

CleanupRateLimitEvents deletes events older than the given duration. Returns the number of rows deleted.

func (*ServerDB) Close

func (db *ServerDB) Close() error

Close checkpoints the WAL and closes the database connection. Uses PASSIVE (not TRUNCATE) to avoid stalling when another process still holds the -shm; SQLite's autocheckpoint handles routine WAL maintenance.

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) ConsumeChallenge added in v0.49.0

func (db *ServerDB) ConsumeChallenge(selector, plaintextSecret string) (*EmailChallenge, error)

ConsumeChallenge atomically verifies and consumes a pending, non-expired challenge. It returns the challenge on success. Sentinel errors:

  • ErrChallengeNotFound — selector not found
  • ErrChallengeAlreadyConsumed — status != pending
  • ErrChallengeExpired — expires_at <= now
  • ErrChallengeInvalidToken — SHA-256(plaintextSecret) != token_hash

If user_id is set on the challenge, users.email_verified_at is also set (only if it was previously NULL) within the same transaction.

func (*ServerDB) CountAdmins added in v0.32.0

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

CountAdmins returns the number of users with admin privileges.

func (*ServerDB) CountMembers added in v0.32.0

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

CountMembers returns the total number of memberships.

func (*ServerDB) CountProjects added in v0.32.0

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

CountProjects returns the total number of non-deleted projects.

func (*ServerDB) CountUsers added in v0.32.0

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

CountUsers returns the total number of users.

func (*ServerDB) CreateAuthRequest

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

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

func (*ServerDB) CreateEmailChallenge added in v0.49.0

func (db *ServerDB) CreateEmailChallenge(email, purpose, userID string, opts ChallengeOptions) (selector, plaintextSecret string, err error)

CreateEmailChallenge inserts a new email challenge row and returns the selector and plaintext secret to the caller. The plaintext secret is NEVER stored — only its SHA-256 hash is persisted.

func (*ServerDB) CreateInvitation added in v0.50.0

func (db *ServerDB) CreateInvitation(projectID, email, role, invitedBy, tokenHash string, expiresAt time.Time) (*Invitation, error)

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). The first user created is automatically made an admin.

func (*ServerDB) DeclineInvitation added in v0.50.0

func (db *ServerDB) DeclineInvitation(invitationID, email string) error

func (*ServerDB) DeleteInvitation added in v0.50.0

func (db *ServerDB) DeleteInvitation(projectID, invitationID string) error

func (*ServerDB) DeleteSyncCursor added in v0.45.0

func (db *ServerDB) DeleteSyncCursor(projectID, clientID string) error

DeleteSyncCursor removes the cursor for a project/client pair. Used by tests and diagnostic tooling. Safe to call when no row exists.

func (*ServerDB) ExtendImpersonationKey added in v0.45.0

func (db *ServerDB) ExtendImpersonationKey(keyID string, renewTTL, maxTTL time.Duration)

ExtendImpersonationKey extends the expires_at of an impersonation key by renewTTL, capped at cap from the key's created_at. Also updates last_used_at to now. Returns the new expires_at. No-ops silently (logs a warning) on failure — callers should not fail the request over a stats update.

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) ForceExpireChallengeForTest added in v0.49.0

func (db *ServerDB) ForceExpireChallengeForTest(selector string, expiresAt time.Time)

ForceExpireChallengeForTest sets the expires_at of a challenge to a past time to simulate expiry in tests. This is a test-only helper.

func (*ServerDB) ForceExpireInvitationForTest added in v0.50.0

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

ForceExpireInvitationForTest sets expires_at to simulate expiry in tests.

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) GenerateImpersonationKey added in v0.45.0

func (db *ServerDB) GenerateImpersonationKey(targetUserID string, ttl time.Duration) (string, *APIKey, error)

GenerateImpersonationKey creates a new short-lived ephemeral "view-as" key for the target user. Uses the td_ipk_ prefix and stores the row with scopes = "impersonation:read". Any existing unexpired td_ipk_ keys for the same target user are revoked first ("last one wins").

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) GetInvitation added in v0.50.0

func (db *ServerDB) GetInvitation(id string) (*Invitation, error)

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) GetPendingExpiredAuthRequests added in v0.32.0

func (db *ServerDB) GetPendingExpiredAuthRequests() ([]AuthRequest, error)

GetPendingExpiredAuthRequests returns pending auth requests that have expired, for use when logging "expired" auth events before cleanup marks them.

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) GetProjectEventCount added in v0.32.0

func (db *ServerDB) GetProjectEventCount(projectID string) (int, *time.Time, error)

GetProjectEventCount returns the cached event count and last event timestamp for a project.

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) HasPendingInvitationForEmail added in v0.50.0

func (db *ServerDB) HasPendingInvitationForEmail(email string) (bool, error)

func (*ServerDB) InsertAuthEvent added in v0.32.0

func (db *ServerDB) InsertAuthEvent(authRequestID, email, eventType, metadata string) error

InsertAuthEvent inserts an auth event row.

func (*ServerDB) InsertRateLimitEvent added in v0.32.0

func (db *ServerDB) InsertRateLimitEvent(keyID, ip, endpointClass string) error

InsertRateLimitEvent inserts a rate limit violation event. keyID may be empty for IP-based rate limiting (stored as NULL).

func (*ServerDB) IsUserAdmin added in v0.32.0

func (db *ServerDB) IsUserAdmin(userID string) (bool, error)

IsUserAdmin returns whether the user with the given ID is an admin.

func (*ServerDB) ListAPIKeys

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

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

func (*ServerDB) ListAPIKeysForUser added in v0.32.0

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

ListAPIKeysForUser returns all API keys for a user without the key_hash.

func (*ServerDB) ListMembers

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

ListMembers returns all members of a project.

func (*ServerDB) ListPendingInvitationsForEmail added in v0.50.0

func (db *ServerDB) ListPendingInvitationsForEmail(email string) ([]*Invitation, error)

func (*ServerDB) ListProjectInvitations added in v0.50.0

func (db *ServerDB) ListProjectInvitations(projectID string) ([]*Invitation, error)

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) ListSyncCursorsForProject added in v0.32.0

func (db *ServerDB) ListSyncCursorsForProject(projectID string) ([]SyncCursor, error)

ListSyncCursorsForProject returns all sync cursors for a project.

func (*ServerDB) ListUsers

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

ListUsers returns all users.

func (*ServerDB) LookupChallenge added in v0.49.0

func (db *ServerDB) LookupChallenge(selector string) (*EmailChallenge, error)

LookupChallenge returns the challenge with the given selector, or nil if not found.

func (*ServerDB) LookupChallengeByDeviceCodeHash added in v0.49.0

func (db *ServerDB) LookupChallengeByDeviceCodeHash(deviceCodeHash string) (*EmailChallenge, error)

LookupChallengeByDeviceCodeHash returns the pending, non-expired challenge associated with the given device_code_hash, or nil if not found.

func (*ServerDB) LookupDeviceChallenge added in v0.49.0

func (db *ServerDB) LookupDeviceChallenge(deviceCodeHash string) (*EmailChallenge, error)

LookupDeviceChallenge returns the challenge with the given device_code_hash, regardless of status. Returns nil, nil if no row exists. Used by the poll endpoint which inspects status itself.

func (*ServerDB) MarkDeviceChallengeConsumed added in v0.49.0

func (db *ServerDB) MarkDeviceChallengeConsumed(selector string) (bool, error)

MarkDeviceChallengeConsumed atomically transitions a challenge from status='verified' to status='consumed'. Returns (true, nil) if the transition succeeded, (false, nil) if the row was not in 'verified' state (i.e. a concurrent poll already consumed it). This guards against issuing two API keys for the same device login.

func (*ServerDB) Ping

func (db *ServerDB) Ping() error

Ping checks the database connection is alive.

func (*ServerDB) QueryAuthEvents added in v0.32.0

func (db *ServerDB) QueryAuthEvents(eventType, email, from, to string, limit int, cursor string) (*PaginatedResult[AuthEvent], error)

QueryAuthEvents queries auth events with optional filters and cursor-based pagination. Filters: eventType (exact match), email (LIKE), from/to (created_at range).

func (*ServerDB) QueryRateLimitEvents added in v0.32.0

func (db *ServerDB) QueryRateLimitEvents(keyID, ip, from, to string, limit int, cursor string) (*PaginatedResult[RateLimitEvent], error)

QueryRateLimitEvents queries rate limit events with optional filters. Filters: keyID (exact), ip (exact), from/to (created_at range, RFC3339 or datetime). Uses cursor-based pagination via the PaginatedQuery helper.

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) SetUserAdmin added in v0.32.0

func (db *ServerDB) SetUserAdmin(email string, isAdmin bool) error

SetUserAdmin sets or clears the admin flag for a user identified by email.

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. Slug is intentionally NOT updated on rename — stored slugs are stable canonical identifiers; the 308 permanent redirect on the td-watch side depends on this immutability.

func (*ServerDB) UpdateProjectEventCount added in v0.32.0

func (db *ServerDB) UpdateProjectEventCount(projectID string, newEvents int, lastEventAt time.Time) error

UpdateProjectEventCount atomically increments event_count and updates last_event_at.

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) VerifyAndMarkDeviceChallengeVerified added in v0.49.0

func (db *ServerDB) VerifyAndMarkDeviceChallengeVerified(selector, plaintextSecret string) (*EmailChallenge, error)

VerifyAndMarkDeviceChallengeVerified atomically verifies a device_login challenge by selector+secret and transitions it to status='verified'. It mirrors ConsumeChallenge but sets status='verified' instead of 'consumed'.

Sentinel errors:

  • ErrChallengeNotFound — selector not found
  • ErrChallengeAlreadyConsumed — status != 'pending' (already used or verified)
  • ErrChallengeExpired — expires_at <= now
  • ErrChallengeInvalidToken — SHA-256(plaintextSecret) != token_hash

If user_id is set on the challenge, users.email_verified_at is also set (only if previously NULL) within the same transaction.

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
	IsAdmin         bool
	CreatedAt       time.Time
	UpdatedAt       time.Time
}

User represents a registered user.

type UserProject added in v0.32.0

type UserProject struct {
	ProjectID string `json:"project_id"`
	Name      string `json:"name"`
	Role      string `json:"role"`
}

UserProject represents a project membership for a user.

Jump to

Keyboard shortcuts

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