Documentation
¶
Overview ¶
Package auth provides device tokens, registration invites and the authentication middleware.
Index ¶
- Constants
- Variables
- func AdminMiddleware(db *sql.DB) func(http.Handler) http.Handler
- func ConsumeInvite(ctx context.Context, tx *sql.Tx, code, deviceID string) error
- func CreateDevice(ctx context.Context, tx *sql.Tx, ownerUserID, name, platform string) (deviceID, token string, err error)
- func CreateInvite(ctx context.Context, db *sql.DB, ownerUserID string, ttl time.Duration) (string, error)
- func CreateInviteWithNote(ctx context.Context, db *sql.DB, ownerUserID string, ttl time.Duration, ...) (string, error)
- func CreateLoginCode(ctx context.Context, db *sql.DB, ownerUserID, deviceID, role string) (string, error)
- func DeviceIDFromContext(ctx context.Context) (string, bool)
- func EnsureOwner(ctx context.Context, execer interface{ ... }, ownerUserID string) error
- func GenerateToken() (plaintext, hash string, err error)
- func HashToken(plaintext string) string
- func Middleware(db *sql.DB) func(http.Handler) http.Handler
- func NormalizeUserCode(code string) string
- func ReadMiddleware(db *sql.DB) func(http.Handler) http.Handler
- func ReadOrUIMiddleware(db *sql.DB) func(http.Handler) http.Handler
- func RedeemLoginCode(ctx context.Context, db *sql.DB, code, userAgent string) (string, error)
- func RevokeDevice(ctx context.Context, db *sql.DB, deviceID string) error
- func RevokeUISession(ctx context.Context, db *sql.DB, secret string) error
- func RotateMCPToken(ctx context.Context, db *sql.DB, deviceID string) (string, error)
- func SetUICookie(w http.ResponseWriter, r *http.Request, secret string)
- func UISecret(r *http.Request) string
- func VerifyReadToken(ctx context.Context, db *sql.DB, token string) (deviceID string, err error)
- func VerifyToken(ctx context.Context, db *sql.DB, token string) (deviceID string, err error)
- type ClaimResult
- type DeviceRequest
- type UISession
Constants ¶
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_" )
const ( RequestPending = "pending" RequestApproved = "approved" RequestDenied = "denied" RequestClaimed = "claimed" RequestExpired = "expired" // derived: pending or approved past expires_at )
Request statuses.
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" )
const InvitePrefix = "msi_"
InvitePrefix marks invite codes so they are recognizable in config/logs.
Variables ¶
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") )
var ErrInvalidInvite = errors.New("auth: invalid, expired or already used invite")
ErrInvalidInvite means the invite is unknown, expired or already used.
var ErrInvalidLogin = errors.New("auth: invalid, expired or already used login link")
ErrInvalidLogin means the login code is unknown, expired or used.
var ErrInvalidToken = errors.New("auth: invalid or revoked token")
ErrInvalidToken means the token is unknown or its device was revoked.
var ErrUnknownClaim = errors.New("auth: unknown device request")
ErrUnknownClaim means the claim secret matches no request.
var ErrUnknownDevice = errors.New("auth: unknown device")
ErrUnknownDevice means no device has the given ID.
Functions ¶
func AdminMiddleware ¶
AdminMiddleware admits only admin browser sessions.
func ConsumeInvite ¶
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 ¶
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 ¶
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 ¶
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 ¶
Middleware checks Authorization: Bearer <device token> and attaches the device_id to the request context, or aborts with 401.
func NormalizeUserCode ¶
NormalizeUserCode accepts codes typed with lower case, spaces or no dash.
func ReadMiddleware ¶
ReadMiddleware is Middleware for read-only endpoints: it also accepts the device's MCP token.
func ReadOrUIMiddleware ¶
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 ¶
RedeemLoginCode consumes a login code and opens a UI session, returning the session secret for the cookie.
func RevokeDevice ¶
RevokeDevice permanently invalidates a device's token. Its events stay.
func RevokeUISession ¶
RevokeUISession logs a session out.
func RotateMCPToken ¶
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 VerifyReadToken ¶
VerifyReadToken accepts either the device token or the device's read-only MCP token, for read-only endpoints such as MCP.
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 ¶
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 ¶
UISessionFromContext returns the browser session of a cookie-authenticated request (nil for device tokens).