auth

package
v0.1.3 Latest Latest
Warning

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

Go to latest
Published: Oct 28, 2026 License: Apache-2.0 Imports: 13 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 auth provides device tokens, registration invites and the authentication middleware.

Index

Constants

View Source
const (
	// RequestTTL is how long a request waits for a decision, and how long
	// an approved request waits to be claimed.
	RequestTTL = 10 * time.Minute
	// MaxOpenRequests caps pending requests, since anyone who can reach
	// the server can create one.
	MaxOpenRequests = 20
	// ClaimPrefix marks claim secrets.
	ClaimPrefix = "msr_"
)
View Source
const (
	RequestPending  = "pending"
	RequestApproved = "approved"
	RequestDenied   = "denied"
	RequestClaimed  = "claimed"
	RequestExpired  = "expired" // derived: pending or approved past expires_at
)

Request statuses.

View Source
const (
	// LoginPrefix marks login codes.
	LoginPrefix = "msl_"
	// UICookie is the session cookie name.
	UICookie = "memspace_ui"
	// UIHeader must be present (any value) on cookie-authenticated requests.
	UIHeader = "X-MemSpace-UI"

	LoginLinkTTL = 5 * time.Minute
	UISessionTTL = 14 * 24 * time.Hour

	// RoleAdmin sessions may manage invites, devices and browser sessions;
	// RoleViewer sessions only read.
	RoleAdmin  = "admin"
	RoleViewer = "viewer"
)
View Source
const InvitePrefix = "msi_"

InvitePrefix marks invite codes so they are recognizable in config/logs.

Variables

View Source
var (
	// ErrTooManyRequests means MaxOpenRequests are already pending.
	ErrTooManyRequests = errors.New("auth: too many pending device requests")
	// ErrUnknownRequest means no open request matches.
	ErrUnknownRequest = errors.New("auth: no pending device request with that code")
)
View Source
var ErrInvalidInvite = errors.New("auth: invalid, expired or already used invite")

ErrInvalidInvite means the invite is unknown, expired or already used.

View Source
var ErrInvalidLogin = errors.New("auth: invalid, expired or already used login link")

ErrInvalidLogin means the login code is unknown, expired or used.

View Source
var ErrInvalidToken = errors.New("auth: invalid or revoked token")

ErrInvalidToken means the token is unknown or its device was revoked.

View Source
var ErrUnknownClaim = errors.New("auth: unknown device request")

ErrUnknownClaim means the claim secret matches no request.

View Source
var ErrUnknownDevice = errors.New("auth: unknown device")

ErrUnknownDevice means no device has the given ID.

Functions

func AdminMiddleware

func AdminMiddleware(db *sql.DB) func(http.Handler) http.Handler

AdminMiddleware admits only admin browser sessions.

func ConsumeInvite

func ConsumeInvite(ctx context.Context, tx *sql.Tx, code, deviceID string) error

ConsumeInvite marks an invite as used by deviceID inside tx. It fails with ErrInvalidInvite unless the invite exists, is unexpired and unused.

func CreateDevice

func CreateDevice(ctx context.Context, tx *sql.Tx, ownerUserID, name, platform string) (deviceID, token string, err error)

CreateDevice registers a device inside tx and returns its ID and plaintext token (only the hash is stored).

func CreateInvite

func CreateInvite(ctx context.Context, db *sql.DB, ownerUserID string, ttl time.Duration) (string, error)

CreateInvite stores a new single-use invite valid for ttl and returns its plaintext code (shown once).

func CreateInviteWithNote

func CreateInviteWithNote(ctx context.Context, db *sql.DB, ownerUserID string, ttl time.Duration, note string) (string, error)

CreateInviteWithNote is CreateInvite with a note shown in the admin UI (e.g. the device the invite is meant for).

func CreateLoginCode

func CreateLoginCode(ctx context.Context, db *sql.DB, ownerUserID, deviceID, role string) (string, error)

CreateLoginCode stores a single-use login code. deviceID is the device that asked for it ("" for the server operator or an admin session).

func DeviceIDFromContext

func DeviceIDFromContext(ctx context.Context) (string, bool)

DeviceIDFromContext retrieves the device_id set by the Middleware.

func EnsureOwner

func EnsureOwner(ctx context.Context, execer interface {
	ExecContext(context.Context, string, ...any) (sql.Result, error)
}, ownerUserID string) error

EnsureOwner creates the owner user row if missing.

func GenerateToken

func GenerateToken() (plaintext, hash string, err error)

GenerateToken creates a cryptographically random 32-byte token and returns both the plaintext (to give the client once) and the SHA-256 hash (to store).

func HashToken

func HashToken(plaintext string) string

HashToken returns the SHA-256 hash of a plaintext secret for storage and lookup. Secrets are high-entropy random values, so an unsalted hash is sufficient and allows indexed lookup.

func Middleware

func Middleware(db *sql.DB) func(http.Handler) http.Handler

Middleware checks Authorization: Bearer <device token> and attaches the device_id to the request context, or aborts with 401.

func NormalizeUserCode

func NormalizeUserCode(code string) string

NormalizeUserCode accepts codes typed with lower case, spaces or no dash.

func ReadMiddleware

func ReadMiddleware(db *sql.DB) func(http.Handler) http.Handler

ReadMiddleware is Middleware for read-only endpoints: it also accepts the device's MCP token.

func ReadOrUIMiddleware

func ReadOrUIMiddleware(db *sql.DB) func(http.Handler) http.Handler

ReadOrUIMiddleware authenticates read endpoints shared by agents and the web UI: a device token (Authorization: Bearer), or a UI session cookie together with UIHeader. Cookie requests carry no device id.

func RedeemLoginCode

func RedeemLoginCode(ctx context.Context, db *sql.DB, code, userAgent string) (string, error)

RedeemLoginCode consumes a login code and opens a UI session, returning the session secret for the cookie.

func RevokeDevice

func RevokeDevice(ctx context.Context, db *sql.DB, deviceID string) error

RevokeDevice permanently invalidates a device's token. Its events stay.

func RevokeUISession

func RevokeUISession(ctx context.Context, db *sql.DB, secret string) error

RevokeUISession logs a session out.

func RotateMCPToken

func RotateMCPToken(ctx context.Context, db *sql.DB, deviceID string) (string, error)

RotateMCPToken issues a new read-only MCP token for a device, invalidating the previous one.

func SetUICookie

func SetUICookie(w http.ResponseWriter, r *http.Request, secret string)

SetUICookie sets (secret != "") or clears the session cookie.

func UISecret

func UISecret(r *http.Request) string

UISecret returns the session secret from a request's cookie.

func VerifyReadToken

func VerifyReadToken(ctx context.Context, db *sql.DB, token string) (deviceID string, err error)

VerifyReadToken accepts either the device token or the device's read-only MCP token, for read-only endpoints such as MCP.

func VerifyToken

func VerifyToken(ctx context.Context, db *sql.DB, token string) (deviceID string, err error)

VerifyToken returns the device_id for a valid, unrevoked token.

Types

type ClaimResult

type ClaimResult struct {
	Status    string // pending | approved (token issued) | denied | expired | claimed
	ExpiresAt time.Time
	DeviceID  string
	Token     string // plaintext, only when Status is approved
	Name      string
}

ClaimResult is what a device learns when it polls with its claim secret.

func ClaimDeviceRequest

func ClaimDeviceRequest(ctx context.Context, db *sql.DB, ownerUserID, claim string) (*ClaimResult, error)

ClaimDeviceRequest reports a request's state to the device holding its claim secret and, once approved, registers the device and returns its token, exactly once.

type DeviceRequest

type DeviceRequest struct {
	ID            string     `json:"request_id"`
	UserCode      string     `json:"user_code"`
	Name          string     `json:"name"`
	Platform      string     `json:"platform"`
	RemoteAddr    string     `json:"remote_addr"`
	ClientVersion string     `json:"client_version"`
	Status        string     `json:"status"`
	CreatedAt     time.Time  `json:"created_at"`
	ExpiresAt     time.Time  `json:"expires_at"`
	DecidedAt     *time.Time `json:"decided_at,omitempty"`
}

DeviceRequest is a request as shown to administrators.

func CreateDeviceRequest

func CreateDeviceRequest(ctx context.Context, db *sql.DB, name, platform, remoteAddr, clientVersion string) (*DeviceRequest, string, error)

CreateDeviceRequest stores a pending request and returns it with the plaintext claim secret (given to the requesting device only).

func DecideDeviceRequest

func DecideDeviceRequest(ctx context.Context, db *sql.DB, ref string, approve bool) (*DeviceRequest, error)

DecideDeviceRequest approves or denies the pending request with the given ID or user code. An approved request can be claimed for RequestTTL.

func ListDeviceRequests

func ListDeviceRequests(ctx context.Context, db *sql.DB) ([]DeviceRequest, error)

ListDeviceRequests returns open requests: pending, or approved and not yet claimed, and not expired. Oldest first.

type UISession

type UISession struct {
	ID   string // hash of the secret; safe to show and to revoke by
	Role string
}

UISession is an authenticated browser session.

func UISessionFromContext

func UISessionFromContext(ctx context.Context) *UISession

UISessionFromContext returns the browser session of a cookie-authenticated request (nil for device tokens).

func VerifyUISession

func VerifyUISession(ctx context.Context, db *sql.DB, secret string) (*UISession, error)

VerifyUISession checks a session secret: unexpired, not logged out, and its device (if any) not revoked.

Jump to

Keyboard shortcuts

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