Documentation
¶
Index ¶
- Constants
- Variables
- func EncodeCursor(data CursorData) string
- func NewID() string
- func NormalizeLimit(limit int) int
- type APIKey
- type AdminProject
- type AdminProjectMember
- type AdminUser
- type AdminUserDetail
- type AuthEvent
- type AuthRequest
- type ChallengeOptions
- type CursorData
- type EmailChallenge
- type Invitation
- type Membership
- type Migration
- type PaginatedResult
- type Project
- type RateLimitEvent
- type ServerDB
- func (db *ServerDB) AcceptInvitation(invitationID, userID, email string) (*Membership, error)
- func (db *ServerDB) AddMember(projectID, userID, role, invitedByUserID string) (*Membership, error)
- func (db *ServerDB) AdminGetProject(id string) (*AdminProject, error)
- func (db *ServerDB) AdminGetUser(id string) (*AdminUserDetail, error)
- func (db *ServerDB) AdminListProjectMembers(projectID string) ([]AdminProjectMember, error)
- func (db *ServerDB) AdminListProjects(query string, includeDeleted bool, limit int, cursor string) (*PaginatedResult[AdminProject], error)
- func (db *ServerDB) AdminListUsers(query string, limit int, cursor string) (*PaginatedResult[AdminUser], error)
- func (db *ServerDB) AdminRevokeAPIKey(keyID string) error
- func (db *ServerDB) ApproveDeviceChallengeAsOperator(userID, selector string) (*EmailChallenge, error)
- func (db *ServerDB) Authorize(projectID, userID, requiredRole string) error
- func (db *ServerDB) BackfillProjectSlugs() error
- func (db *ServerDB) CanDeleteProject(projectID, userID string) error
- func (db *ServerDB) CanManageMembers(projectID, userID string) error
- func (db *ServerDB) CanPullEvents(projectID, userID string) error
- func (db *ServerDB) CanPushEvents(projectID, userID string) error
- func (db *ServerDB) CanViewProject(projectID, userID string) error
- func (db *ServerDB) CleanupAuthEvents(olderThan time.Duration) (int64, error)
- func (db *ServerDB) CleanupExpiredAuthRequests() (int64, error)
- func (db *ServerDB) CleanupExpiredChallenges() (int64, error)
- func (db *ServerDB) CleanupRateLimitEvents(olderThan time.Duration) (int64, error)
- func (db *ServerDB) Close() error
- func (db *ServerDB) CompleteAuthRequest(deviceCode string) (*AuthRequest, error)
- func (db *ServerDB) ConsumeChallenge(selector, plaintextSecret string) (*EmailChallenge, error)
- func (db *ServerDB) CountAdmins() (int, error)
- func (db *ServerDB) CountMembers() (int, error)
- func (db *ServerDB) CountProjects() (int, error)
- func (db *ServerDB) CountUsers() (int, error)
- func (db *ServerDB) CreateAuthRequest(email string) (*AuthRequest, error)
- func (db *ServerDB) CreateEmailChallenge(email, purpose, userID string, opts ChallengeOptions) (selector, plaintextSecret string, err error)
- func (db *ServerDB) CreateInvitation(projectID, email, role, invitedBy, tokenHash string, expiresAt time.Time) (*Invitation, error)
- func (db *ServerDB) CreateProject(name, description, ownerUserID string) (*Project, error)
- func (db *ServerDB) CreateProjectWithID(id, name, description, ownerUserID string) (*Project, error)
- func (db *ServerDB) CreateUser(email string) (*User, error)
- func (db *ServerDB) DeclineInvitation(invitationID, email string) error
- func (db *ServerDB) DeleteInvitation(projectID, invitationID string) error
- func (db *ServerDB) DeleteSyncCursor(projectID, clientID string) error
- func (db *ServerDB) ExtendImpersonationKey(keyID string, renewTTL, maxTTL time.Duration)
- func (db *ServerDB) ForceExpireAuthRequestForTest(id string, expiresAt time.Time)
- func (db *ServerDB) ForceExpireChallengeForTest(selector string, expiresAt time.Time)
- func (db *ServerDB) ForceExpireInvitationForTest(id string, expiresAt time.Time)
- func (db *ServerDB) GenerateAPIKey(userID, name, scopes string, expiresAt *time.Time) (string, *APIKey, error)
- func (db *ServerDB) GenerateImpersonationKey(targetUserID string, ttl time.Duration) (string, *APIKey, error)
- func (db *ServerDB) GetAuthRequestByDeviceCode(deviceCode string) (*AuthRequest, error)
- func (db *ServerDB) GetAuthRequestByUserCode(userCode string) (*AuthRequest, error)
- func (db *ServerDB) GetInvitation(id string) (*Invitation, error)
- func (db *ServerDB) GetMembership(projectID, userID string) (*Membership, error)
- func (db *ServerDB) GetPendingExpiredAuthRequests() ([]AuthRequest, error)
- func (db *ServerDB) GetProject(id string, includeSoftDeleted bool) (*Project, error)
- func (db *ServerDB) GetProjectEventCount(projectID string) (int, *time.Time, error)
- func (db *ServerDB) GetSyncCursor(projectID, clientID string) (*SyncCursor, error)
- func (db *ServerDB) GetUserByEmail(email string) (*User, error)
- func (db *ServerDB) GetUserByID(id string) (*User, error)
- func (db *ServerDB) HasPendingInvitationForEmail(email string) (bool, error)
- func (db *ServerDB) InsertAuthEvent(authRequestID, email, eventType, metadata string) error
- func (db *ServerDB) InsertRateLimitEvent(keyID, ip, endpointClass string) error
- func (db *ServerDB) IsUserAdmin(userID string) (bool, error)
- func (db *ServerDB) ListAPIKeys(userID string) ([]*APIKey, error)
- func (db *ServerDB) ListAPIKeysForUser(userID string) ([]*APIKey, error)
- func (db *ServerDB) ListMembers(projectID string) ([]*Membership, error)
- func (db *ServerDB) ListPendingInvitationsForEmail(email string) ([]*Invitation, error)
- func (db *ServerDB) ListProjectInvitations(projectID string) ([]*Invitation, error)
- func (db *ServerDB) ListProjectsForUser(userID string) ([]*Project, error)
- func (db *ServerDB) ListSyncCursorsForProject(projectID string) ([]SyncCursor, error)
- func (db *ServerDB) ListUsers() ([]*User, error)
- func (db *ServerDB) LookupChallenge(selector string) (*EmailChallenge, error)
- func (db *ServerDB) LookupChallengeByDeviceCodeHash(deviceCodeHash string) (*EmailChallenge, error)
- func (db *ServerDB) LookupDeviceChallenge(deviceCodeHash string) (*EmailChallenge, error)
- func (db *ServerDB) MarkDeviceChallengeConsumed(selector string) (bool, error)
- func (db *ServerDB) PendingDeviceChallenges(userID string) ([]*EmailChallenge, error)
- func (db *ServerDB) Ping() error
- func (db *ServerDB) QueryAuthEvents(eventType, email, from, to string, limit int, cursor string) (*PaginatedResult[AuthEvent], error)
- func (db *ServerDB) QueryRateLimitEvents(keyID, ip, from, to string, limit int, cursor string) (*PaginatedResult[RateLimitEvent], error)
- func (db *ServerDB) RemoveMember(projectID, userID string) error
- func (db *ServerDB) RevokeAPIKey(keyID, userID string) error
- func (db *ServerDB) RunMigrations() (int, error)
- func (db *ServerDB) SetAuthRequestAPIKey(id, apiKeyID string) error
- func (db *ServerDB) SetEmailVerified(userID string) error
- func (db *ServerDB) SetUserAdmin(email string, isAdmin bool) error
- func (db *ServerDB) SoftDeleteProject(id string) error
- func (db *ServerDB) UpdateMemberRole(projectID, userID, newRole string) error
- func (db *ServerDB) UpdateProject(id, name, description string) (*Project, error)
- func (db *ServerDB) UpdateProjectEventCount(projectID string, newEvents int, lastEventAt time.Time) error
- func (db *ServerDB) UpsertSyncCursor(projectID, clientID string, lastEventID int64) error
- func (db *ServerDB) VerifyAPIKey(plaintextKey string) (*APIKey, *User, error)
- func (db *ServerDB) VerifyAndMarkDeviceChallengeVerified(selector, plaintextSecret string) (*EmailChallenge, error)
- func (db *ServerDB) VerifyAuthRequest(userCode, userID string) error
- type SyncCursor
- type User
- type UserProject
Constants ¶
const ( RoleOwner = "owner" RoleWriter = "writer" RoleReader = "reader" )
Role constants
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 or operator approved via CLI, device request marked verified AuthEventLoginFailed = "login_failed" // any terminal failure: wrong token, wrong state, wrong verifier, expired )
Auth event type constants.
const ( AuthStatusPending = "pending" AuthStatusVerified = "verified" AuthStatusExpired = "expired" AuthStatusUsed = "used" AuthRequestTTL = 15 * time.Minute PollInterval = 5 )
const ( ChallengeTTL = 15 * time.Minute ChallengeStatusPending = "pending" ChallengeStatusConsumed = "consumed" ChallengeStatusExpired = "expired" ChallengeStatusVerified = "verified" ChallengeStatusFailed = "failed" ChallengeStatusSuppressed = "suppressed" )
Challenge TTL and status constants.
const ( InvitationStatusPending = "pending" InvitationStatusAccepted = "accepted" InvitationStatusDeclined = "declined" InvitationStatusExpired = "expired" )
const ( DefaultPageLimit = 50 MaxPageLimit = 200 )
const OperatorApprovalMetadata = `{"approved_by":"operator_cli"}`
OperatorApprovalMetadata is the metadata recorded on the device_verified auth event when an operator approves a login with `td-sync admin approve-login`.
const ServerSchemaVersion = 6
ServerSchemaVersion is the current server database schema version
Variables ¶
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.
var ( ErrInvitationNotFound = errors.New("invitation not found") ErrInvitationNotPending = errors.New("invitation not pending") ErrInvitationExpired = errors.New("invitation expired") ErrInvitationEmailMismatch = errors.New("invitation email mismatch") )
var ErrNotFound = errors.New("not found")
ErrNotFound is returned by serverdb methods when a requested record does not exist.
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
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 Membership ¶
type Membership struct {
ProjectID string
UserID string
Email string
Role string
InvitedBy string
CreatedAt time.Time
}
Membership represents a user's role in a project.
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 ¶
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
AdminRevokeAPIKey deletes any API key by ID regardless of owner. Returns ErrNotFound if no row was deleted.
func (*ServerDB) ApproveDeviceChallengeAsOperator ¶ added in v0.67.0
func (db *ServerDB) ApproveDeviceChallengeAsOperator(userID, selector string) (*EmailChallenge, error)
ApproveDeviceChallengeAsOperator marks the device login with the given selector as verified without the emailed token. It lets the operator of a self-hosted server that sends no email approve a waiting `td auth login` after choosing it from PendingDeviceChallenges. Running it requires write access to server.db, which already allows minting API keys, so it grants nothing new. The CLI that started the login must still present its PKCE verifier to /v1/auth/device/poll to receive a key.
The selector is required. Inside the transaction the challenge must still be a pending, unexpired device_login belonging to userID; otherwise it returns ErrChallengeNotFound and changes nothing. web_login and other purposes are never touched.
Unlike the emailed link, this does not set users.email_verified_at, because the operator did not prove ownership of the address. The device_verified auth event is written in the same transaction with OperatorApprovalMetadata.
The transaction starts with BEGIN IMMEDIATE so the write lock is taken up front under the busy timeout. That keeps the re-check and the update atomic, and makes it safe to run while a td-sync server holds the same file.
func (*ServerDB) Authorize ¶
Authorize checks that the user has at least the required role in the project.
func (*ServerDB) BackfillProjectSlugs ¶ added in v0.50.0
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 ¶
CanDeleteProject checks if the user can delete the project (requires owner role).
func (*ServerDB) CanManageMembers ¶
CanManageMembers checks if the user can manage members (requires owner role).
func (*ServerDB) CanPullEvents ¶
CanPullEvents checks if the user can pull events (requires reader role).
func (*ServerDB) CanPushEvents ¶
CanPushEvents checks if the user can push events (requires writer role).
func (*ServerDB) CanViewProject ¶
CanViewProject checks if the user can view the project (requires reader role).
func (*ServerDB) CleanupAuthEvents ¶ added in v0.32.0
CleanupAuthEvents deletes auth events older than the given duration. Returns the number of rows deleted.
func (*ServerDB) CleanupExpiredAuthRequests ¶
CleanupExpiredAuthRequests marks pending auth requests past their expiry as expired.
func (*ServerDB) CleanupExpiredChallenges ¶ added in v0.49.0
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
CleanupRateLimitEvents deletes events older than the given duration. Returns the number of rows deleted.
func (*ServerDB) Close ¶
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
CountAdmins returns the number of users with admin privileges.
func (*ServerDB) CountMembers ¶ added in v0.32.0
CountMembers returns the total number of memberships.
func (*ServerDB) CountProjects ¶ added in v0.32.0
CountProjects returns the total number of non-deleted projects.
func (*ServerDB) CountUsers ¶ added in v0.32.0
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 (*ServerDB) CreateProject ¶
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 ¶
CreateUser inserts a new user with the given email (lowercased). The first user created is automatically made an admin.
The count and the insert share one transaction so two concurrent creations cannot both become admin. It starts with BEGIN IMMEDIATE so the write lock is taken up front under the busy timeout, which makes `td-sync admin create-user` safe to run while a td-sync server holds the same file. A deferred transaction that reads first gets SQLITE_BUSY at once, without waiting, if another connection writes in between.
func (*ServerDB) DeclineInvitation ¶ added in v0.50.0
func (*ServerDB) DeleteInvitation ¶ added in v0.50.0
func (*ServerDB) DeleteSyncCursor ¶ added in v0.45.0
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
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 ¶
ForceExpireAuthRequestForTest forces an auth request's expiry time (test-only helper).
func (*ServerDB) ForceExpireChallengeForTest ¶ added in v0.49.0
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
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 ¶
GetProject returns a project by ID. If includeSoftDeleted is false, soft-deleted projects are excluded.
func (*ServerDB) GetProjectEventCount ¶ added in v0.32.0
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 ¶
GetUserByEmail returns the user with the given email (case-insensitive), or nil if not found.
func (*ServerDB) GetUserByID ¶
GetUserByID returns the user with the given ID, or nil if not found.
func (*ServerDB) HasPendingInvitationForEmail ¶ added in v0.50.0
func (*ServerDB) InsertAuthEvent ¶ added in v0.32.0
InsertAuthEvent inserts an auth event row.
func (*ServerDB) InsertRateLimitEvent ¶ added in v0.32.0
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
IsUserAdmin returns whether the user with the given ID is an admin.
func (*ServerDB) ListAPIKeys ¶
ListAPIKeys returns all API keys for a user (without secrets).
func (*ServerDB) ListAPIKeysForUser ¶ added in v0.32.0
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 ¶
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) 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
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) PendingDeviceChallenges ¶ added in v0.67.0
func (db *ServerDB) PendingDeviceChallenges(userID string) ([]*EmailChallenge, error)
PendingDeviceChallenges returns the device logins for userID that an operator may approve with ApproveDeviceChallengeAsOperator: pending, unexpired device_login challenges, newest first. It changes nothing, so the operator can review them before choosing one.
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 ¶
RemoveMember removes a user from a project. Fails if removing the user would leave the project with no owners.
func (*ServerDB) RevokeAPIKey ¶
RevokeAPIKey deletes an API key, only if owned by the given user.
func (*ServerDB) RunMigrations ¶
RunMigrations runs any pending database migrations.
func (*ServerDB) SetAuthRequestAPIKey ¶
SetAuthRequestAPIKey sets the API key ID on an auth request.
func (*ServerDB) SetEmailVerified ¶
SetEmailVerified marks the user's email as verified.
func (*ServerDB) SetUserAdmin ¶ added in v0.32.0
SetUserAdmin sets or clears the admin flag for a user identified by email.
func (*ServerDB) SoftDeleteProject ¶
SoftDeleteProject marks a project as deleted.
func (*ServerDB) UpdateMemberRole ¶
UpdateMemberRole changes a member's role. Fails if demoting the member would leave the project with no owners.
func (*ServerDB) UpdateProject ¶
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 ¶
UpsertSyncCursor creates or updates a sync cursor for a project/client pair.
func (*ServerDB) VerifyAPIKey ¶
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 ¶
VerifyAuthRequest marks a pending auth request as verified with the given user ID.
type SyncCursor ¶
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.