session

package
v0.9.3 Latest Latest
Warning

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

Go to latest
Published: Nov 9, 2026 License: MIT Imports: 14 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 session implements dashboard sessions, minted by the email and password login flow. The credential is the operator's password, verified with bcrypt. The browser holds an httpOnly cookie tied to the user. See ADR-011 for the full reasoning.

The package exposes, on purpose, only what the dashboard auth flow needs: Issue (mint a session for an authenticated user), Get (resolve a cookie value to its session row) and Revoke (logout). Everything is keyed by sha256(raw_id), and the raw id lives only in the cookie.

Index

Constants

View Source
const CookieName = "hardcount_session"

CookieName is the HTTP cookie that carries the raw session id. Kept constant so middleware, login, and logout all reference the same name without risk of drift.

View Source
const DefaultTTL = 7 * 24 * time.Hour

DefaultTTL is the default session lifetime. 7 days matches GitHub's auth cookie default and ADR-008's value. It is long enough that operators do not see a daily login prompt. It is short enough that a stolen cookie has a bounded lifetime, even if the operator never notices and the cookie is not revoked on the server.

Variables

View Source
var ErrNotFound = errors.New("session: not found")

ErrNotFound signals that a session id resolves to no row, or to a row that has been revoked or expired. Callers funnel all three into 401 to deny enumeration of session ids.

Functions

func HashID

func HashID(raw string) string

HashID returns the storage form of a raw session id. Exported so the logout handler can hash the cookie value before calling Revoke.

func MiddlewareOrAPIKey

func MiddlewareOrAPIKey(sessSvc *Service, keySvc *auth.Service) func(http.Handler) http.Handler

MiddlewareOrAPIKey accepts either a session cookie or an `Authorization: Bearer <api_key>` header. The dashboard uses the cookie, and SDKs and curl callers use the API key. The cookie takes precedence when both are present, so a browser tab with a stale Authorization header cannot bypass session revocation by accident.

Types

type CookieConfig

type CookieConfig struct {
	Domain   string
	Secure   bool
	SameSite http.SameSite
	Path     string
}

CookieConfig centralises cookie attributes. SameSite=Lax keeps the cookie attached across top-level navigation (correct for a first-party dashboard) while blocking most cross-site CSRF.

func DefaultCookieConfig

func DefaultCookieConfig(appEnv string) CookieConfig

DefaultCookieConfig returns the cookie attributes for appEnv, which is config.Config.Env. Tests override fields directly.

Secure is on in staging and production, for every request, so a browser sends the session cookie only over HTTPS, or to localhost (ADR-095 Phase 0(b)). Chrome and Firefox keep a Secure cookie at http://localhost, but Safari does not. Plain HTTP is for local, where Secure is off: make dev, and the Compose quickstart, which sets APP_ENV=local so Safari can sign in at http://localhost.

func (CookieConfig) ClearCookie

func (c CookieConfig) ClearCookie(w http.ResponseWriter)

ClearCookie writes a cleared (Max-Age=-1) cookie on the response. Used by the logout handler.

func (CookieConfig) SetCookie

func (c CookieConfig) SetCookie(w http.ResponseWriter, raw string, expires time.Time)

SetCookie writes the session cookie on the response. Sign-in (internal/user) and invite accept (internal/dashmembers) call it after Issue.

type IssueInput

type IssueInput struct {
	UserID    string
	TenantID  string
	Livemode  bool
	UserAgent string
	IP        string
}

IssueInput is the contract for Issue. Callers (the login handler) pass everything needed to mint a session row. The user has already been authenticated by user.Service.Authenticate.

type Service

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

Service is the auth-flow facade over Store. Issue mints a session for an authenticated user (the caller has already verified the password). Resolve looks up a raw cookie value and returns the Session if it is still active. Revoke handles logout.

func NewService

func NewService(store Store) *Service

NewService returns a Service backed by store. Sessions last DefaultTTL.

func (*Service) Issue

func (s *Service) Issue(ctx context.Context, in IssueInput) (rawID string, sess Session, err error)

Issue creates a session row and returns the raw cookie value the caller should set on the response. The raw value is shown to the caller exactly once. The database stores sha256(raw), so a snapshot cannot be replayed.

func (*Service) Resolve

func (s *Service) Resolve(ctx context.Context, rawID string) (Session, error)

Resolve looks up a raw cookie value and returns the Session if it is active. Revoked or expired rows return ErrNotFound. The middleware turns both into a 401, so session ids cannot be enumerated.

func (*Service) Revoke

func (s *Service) Revoke(ctx context.Context, rawID string) error

Revoke marks the session row as revoked. It is idempotent: revoking an already-revoked or missing row does nothing.

func (*Service) RevokeAllForUser

func (s *Service) RevokeAllForUser(ctx context.Context, userID string) error

RevokeAllForUser revokes every active session of a user. The password-reset flow calls it after the new password is set, so a session minted from a stolen cookie cannot outlive the credential change. It is idempotent: with no active sessions it does nothing.

func (*Service) SetLivemode

func (s *Service) SetLivemode(ctx context.Context, rawID string, livemode bool) error

SetLivemode switches the active mode (test or live) on the cookie session. The same operator switches modes without signing in again, and every later request gets the new mode through session.Resolve.

type Session

type Session struct {
	IDHash     string
	UserID     string
	TenantID   string
	Livemode   bool
	CreatedAt  time.Time
	LastSeenAt time.Time
	ExpiresAt  time.Time
	RevokedAt  *time.Time
	UserAgent  string
	IP         string
}

Session is the domain row. id_hash is sha256(raw), and the raw id never leaves the cookie. UserID identifies the operator the session was minted for: sessions are bound to a user (ADR-011), not to a key. Livemode is set when the session is issued and stays fixed. Sessions do not switch modes, and a mode switch would mint a new session.

func (Session) IsActive

func (s Session) IsActive(now time.Time) bool

IsActive reports whether the session can authenticate a request: it is not revoked and not yet expired. The database query already filters out revoked rows on the active path. This check catches expiry without an index lookup keyed on the clock for every request.

type Store

type Store interface {
	Insert(ctx context.Context, s Session) error
	GetByIDHash(ctx context.Context, idHash string) (Session, error)
	Revoke(ctx context.Context, idHash string) error
	RevokeAllForUser(ctx context.Context, userID string) error
	UpdateLivemode(ctx context.Context, idHash string, livemode bool) error
}

Store is the persistence interface for dashboard_sessions rows. It is narrow on purpose: the dashboard auth flow needs only Insert, GetByIDHash and Revoke. Any further surface (pruning expired rows, listing for an ops UI) belongs on a sibling type when it ships, not here. Sessions are bound to a user and are independent of the API key lifecycle (ADR-011), so the Store has no method that revokes sessions by key.

func NewPostgresStore

func NewPostgresStore(db *postgres.DB) Store

NewPostgresStore returns the Postgres-backed Store. Sessions are queried by id_hash (the primary key), so RLS is not strictly needed: the id space has no overlap across tenants. Inserts and tenant-scoped reads run inside TxBypass, because the session id is itself the auth boundary.

Jump to

Keyboard shortcuts

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