domain

package
v0.0.0-...-610d9af Latest Latest
Warning

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

Go to latest
Published: Nov 23, 2026 License: GPL-3.0 Imports: 8 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

Overview

Package domain holds the application's core types and rules: entities, input validation and the error vocabulary. It imports nothing from the rest of the project (no HTTP, no SQL), so every other layer can depend on it without creating import cycles.

Index

Constants

View Source
const (
	MaxEmailLength   = 254 // RFC 5321 path limit
	MaxNameLength    = 100
	MaxTitleLength   = 200
	MinPriority      = 1
	MaxPriority      = 5
	DefaultPriority  = 3
	DefaultPageSize  = 20
	MaxPageSize      = 100
	MinPasswordBytes = 8
	// MaxPasswordBytes bounds the CPU a single login or signup can make us spend. Argon2id,
	// unlike bcrypt (72-byte limit), would happily hash megabytes; 128 bytes is far more than
	// any typed password or password-manager output. Mirrors auth.MaxPasswordBytes.
	MaxPasswordBytes = 128
)

Limits shared by validation and documentation (api/openapi.yaml mirrors them).

View Source
const (
	ProviderCredential = "credential" // email + password; the account holds the argon2id hash
	ProviderGitHub     = "github"
)

Account provider ids. In Better Auth's data model a user can have several "accounts", one per way of signing in.

View Source
const (
	PurposeEmailVerification = "email-verification"
	PurposePasswordReset     = "password-reset"
)

Purposes of a verification token. The stored identifier is "<purpose>:<user id>".

Variables

View Source
var (
	// ErrNotFound means the entity does not exist OR the caller may not see it. Returning the
	// same error for both avoids telling an attacker which ids belong to other users.
	ErrNotFound = errors.New("not found")
	// ErrConflict means a uniqueness rule was violated (duplicate email, duplicate project name).
	ErrConflict = errors.New("conflict")
	// ErrUnauthorized means the caller could not be authenticated (bad credentials or token).
	ErrUnauthorized = errors.New("unauthorized")
	// ErrForbidden means the caller is authenticated but not allowed to do this. Resource
	// ownership checks deliberately use ErrNotFound instead; this one is for future role checks
	// (e.g. admin-only endpoints) where revealing existence is not a concern.
	ErrForbidden = errors.New("forbidden")
	// ErrInvalidToken means a single-use emailed token (email verification, password reset) is
	// unknown, already used or expired. One error for all three: telling them apart would help
	// someone guessing tokens.
	ErrInvalidToken = errors.New("invalid or expired token")
)

Sentinel errors. Lower layers wrap them with context (fmt.Errorf("get task: %w", err)); the HTTP layer finds them with errors.Is in ONE place (httpapi.mapError) and picks a status code. Nothing below the HTTP layer knows what a status code is.

Functions

func NewValidationError

func NewValidationError(field, msg string) error

NewValidationError builds a single-field *ValidationError. Other layers (cursor parsing, query parameters) use it so every "bad input" ends up as the same error type.

func NormalizeLimit

func NormalizeLimit(n int) int

NormalizeLimit applies the default and the cap to a client-supplied page size.

func ValidateEmail

func ValidateEmail(s string) error

ValidateEmail checks that s (already normalized) is a bare, plausible email address.

func ValidatePassword

func ValidatePassword(field, password string) error

ValidatePassword applies the password length rules (bytes, so multi-byte characters count fully, matching what the hash function actually receives).

func ValidateProjectName

func ValidateProjectName(name string) error

ValidateProjectName checks a project name.

Types

type Account

type Account struct {
	ID         string
	UserID     string
	ProviderID string // ProviderCredential or ProviderGitHub
	// AccountID identifies the user at the provider: the user's own id for credential accounts,
	// the provider's user id (e.g. GitHub's numeric id) for OAuth accounts.
	AccountID string
	// Password is the argon2id PHC string; set only for credential accounts.
	Password *string

	// OAuth provider credentials; nil for credential accounts.
	AccessToken           *string
	RefreshToken          *string
	IDToken               *string
	AccessTokenExpiresAt  *time.Time
	RefreshTokenExpiresAt *time.Time
	Scope                 *string

	CreatedAt time.Time
	UpdatedAt time.Time
}

Account is one way a user can sign in (Better Auth's "account" table). Never serialized.

type CreateTaskInput

type CreateTaskInput struct {
	Title    string  `json:"title"`
	Priority *int    `json:"priority"`
	DueDate  *string `json:"due_date"`
}

CreateTaskInput is the payload for creating a task. Pointers distinguish "not sent" (use the default) from an explicit zero value.

func (CreateTaskInput) Validate

func (in CreateTaskInput) Validate() error

Validate checks the input.

type Page

type Page[T any] struct {
	Items   []T
	HasMore bool
}

Page is one slice of a keyset-paginated list.

type Project

type Project struct {
	ID        string    `json:"id"`
	OwnerID   string    `json:"owner_id"`
	Name      string    `json:"name"`
	CreatedAt time.Time `json:"created_at"`
	UpdatedAt time.Time `json:"updated_at"`
}

Project groups tasks and belongs to exactly one user.

type Session

type Session struct {
	ID        string    `json:"id"`
	UserID    string    `json:"-"`
	TokenHash string    `json:"-"` // SHA-256 of the cookie value; see auth.NewToken
	ExpiresAt time.Time `json:"expires_at"`
	IPAddress string    `json:"ip_address"`
	UserAgent string    `json:"user_agent"`
	CreatedAt time.Time `json:"created_at"`
	UpdatedAt time.Time `json:"updated_at"`
}

Session is a server-side login session (cookie authentication). The JSON form is what clients may see: no user id, and above all never the token or its hash.

type SignupInput

type SignupInput struct {
	Email    string `json:"email"`
	Name     string `json:"name"`
	Password string `json:"password"`
}

SignupInput is the payload for creating an account.

func (*SignupInput) Normalize

func (in *SignupInput) Normalize()

Normalize trims and lower-cases the email so "Ada@Example.com " and "ada@example.com" are the same account. (Lower-casing the whole address is a practical simplification: the local part is technically case-sensitive, but virtually no provider treats it that way.)

func (SignupInput) Validate

func (in SignupInput) Validate() error

Validate checks the (normalized) input. Error messages never echo the password.

type Task

type Task struct {
	ID        string     `json:"id"`
	ProjectID string     `json:"project_id"`
	Title     string     `json:"title"`
	Status    TaskStatus `json:"status"`
	Priority  int        `json:"priority"`
	// DueDate is a calendar date (YYYY-MM-DD), not an instant: "due on the 5th" has no time zone.
	DueDate   *string   `json:"due_date"`
	CreatedAt time.Time `json:"created_at"`
	UpdatedAt time.Time `json:"updated_at"`
}

Task is a unit of work inside a project. Ownership is derived from the project.

type TaskStatus

type TaskStatus string

TaskStatus is a closed set of values; the database enforces it too with a CHECK constraint.

const (
	StatusTodo  TaskStatus = "todo"
	StatusDoing TaskStatus = "doing"
	StatusDone  TaskStatus = "done"
)

func (TaskStatus) Valid

func (s TaskStatus) Valid() bool

Valid reports whether s is one of the known statuses.

type UpdateTaskInput

type UpdateTaskInput struct {
	Title    *string     `json:"title"`
	Status   *TaskStatus `json:"status"`
	Priority *int        `json:"priority"`
	DueDate  *string     `json:"due_date"`
}

UpdateTaskInput is a PATCH payload: nil fields are left unchanged. To clear the due date send "due_date": "" (JSON null decodes to nil, which is indistinguishable from "not sent" with plain pointers; the empty string is the explicit "clear" signal).

func (UpdateTaskInput) Apply

func (in UpdateTaskInput) Apply(t *Task, now time.Time)

Apply copies the provided fields onto t. Call Validate first.

func (UpdateTaskInput) Validate

func (in UpdateTaskInput) Validate() error

Validate checks the provided fields and rejects an empty patch.

type User

type User struct {
	ID            string    `json:"id"`
	Email         string    `json:"email"`
	Name          string    `json:"name"`
	EmailVerified bool      `json:"email_verified"`
	Image         *string   `json:"image"`
	CreatedAt     time.Time `json:"created_at"`
	UpdatedAt     time.Time `json:"updated_at"`
}

User is a person. WHO they are lives here; HOW they authenticate lives in Account rows, so the password hash is not part of User and no handler can leak it by accident.

type ValidationError

type ValidationError struct {
	Fields map[string]string // field name -> human-readable problem
}

ValidationError reports which input fields were rejected and why. It is a pointer type so callers use errors.As with *ValidationError.

func (*ValidationError) Error

func (e *ValidationError) Error() string

Error lists the fields in sorted order so messages (and tests) are deterministic.

type Verification

type Verification struct {
	ID         string
	Identifier string // "<purpose>:<user id>"
	Value      string
	ExpiresAt  time.Time
	CreatedAt  time.Time
	UpdatedAt  time.Time
}

Verification is a single-use emailed token (verify email, reset password). Value holds the SHA-256 of the token, never the token.

Jump to

Keyboard shortcuts

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