cookie

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Jan 15, 2026 License: MIT Imports: 10 Imported by: 0

README

A Go package for encrypted HTTP cookie management with automatic expiration handling.

Features

  • AES-256-GCM Encryption: Secure cookie data encryption using industry-standard cryptography
  • Automatic Expiration: Embedded timestamps with configurable max age validation
  • Secure Defaults: Cookies are set with HttpOnly, Secure, and SameSite=Strict flags
  • Simple API: Easy-to-use functions for cookie lifecycle management

Installation

go get github.com/devilcove/cookie

Usage

Before using a cookie, initialize it with a name and max age (in seconds):

import "github.com/devilcove/cookie"

// Create a cookie with 1 hour expiration
err := cookie.New("session", 3600)
if err != nil {
    log.Fatal(err)
}

Encrypt and save data to a cookie:

func handler(w http.ResponseWriter, r *http.Request) {
    data := []byte("user123")
    err := cookie.Save(w, "session", data)
    if err != nil {
        http.Error(w, "Failed to save cookie", http.StatusInternalServerError)
        return
    }
}

Decrypt and retrieve data from a cookie:

func handler(w http.ResponseWriter, r *http.Request) {
    data, err := cookie.Get(r, "session")
    if err == cookie.ErrCookieExpired {
        http.Error(w, "Session expired", http.StatusUnauthorized)
        return
    }
    if err != nil {
        http.Error(w, "Invalid cookie", http.StatusBadRequest)
        return
    }
    
    // Use decrypted data
    userID := string(data)
}

Remove a cookie from the client:

func logoutHandler(w http.ResponseWriter, r *http.Request) {
    // Clear cookie from client, keep configuration in memory
    err := cookie.Clear(w, "session", false)
    
    // Or clear and remove configuration entirely
    err = cookie.Clear(w, "session", true)
    
    if err != nil {
        http.Error(w, "Failed to clear cookie", http.StatusInternalServerError)
        return
    }
}

Complete Example

package main

import (
    "log"
    "net/http"
    
    "github.com/devilcove/cookie"
)

func main() {
    // Initialize cookie with 24 hour expiration
    if err := cookie.New("user_session", 86400); err != nil {
        log.Fatal(err)
    }
    
    http.HandleFunc("/login", loginHandler)
    http.HandleFunc("/dashboard", dashboardHandler)
    http.HandleFunc("/logout", logoutHandler)
    
    log.Fatal(http.ListenAndServe(":8080", nil))
}

func loginHandler(w http.ResponseWriter, r *http.Request) {
    // Authenticate user...
    userID := []byte("user123")
    
    if err := cookie.Save(w, "user_session", userID); err != nil {
        http.Error(w, "Login failed", http.StatusInternalServerError)
        return
    }
    
    w.Write([]byte("Logged in successfully"))
}

func dashboardHandler(w http.ResponseWriter, r *http.Request) {
    data, err := cookie.Get(r, "user_session")
    if err != nil {
        http.Error(w, "Unauthorized", http.StatusUnauthorized)
        return
    }
    
    w.Write([]byte("Welcome, " + string(data)))
}

func logoutHandler(w http.ResponseWriter, r *http.Request) {
    cookie.Clear(w, "user_session", false)
    w.Write([]byte("Logged out successfully"))
}

Error Handling

The package provides specific error types for common scenarios:

  • cookie.ErrNotInitialized: Cookie hasn't been initialized with New()
  • cookie.ErrCookieExpired: Cookie timestamp exceeds its max age
  • cookie.ErrExists: Attempted to create a cookie that already exists

Security Features

  • AES-256-GCM: Authenticated encryption with associated data
  • Random Key Generation: Each cookie gets a unique 256-bit encryption key
  • Random Nonce: Cryptographically secure nonce generation
  • HttpOnly Flag: Prevents JavaScript access to cookies
  • Secure Flag: Ensures cookies are only sent over HTTPS
  • SameSite Strict: Protects against CSRF attacks
  • Timestamp Validation: Automatic expiration checking on retrieval

Limitations

  • Cookie configurations are stored in memory and don't persist across application restarts
  • The same nonce is reused for a given cookie configuration (consider rotating for long-lived applications)
  • Maximum cookie size is limited by browser constraints (typically 4KB)

License

MIT License - see LICENSE file for details

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

Documentation

Overview

Package cookie provides encrypted HTTP cookie management with automatic expiration handling. It uses AES-256-GCM encryption to securely store cookie data with embedded timestamps for expiration validation.

Cookies must be initialized with New before use. Each cookie configuration maintains its own encryption key and is stored in memory for the lifetime of the application.

Example usage:

// Initialize a cookie with 1 hour expiration
err := cookie.New("session", 3600)
if err != nil {
    log.Fatal(err)
}

// Save encrypted data and save cookie in http.Response
data := []byte("user123")
cookie.Save(w, "session", data)

// Retrieve and decrypt data from http.Request
data, err := cookie.Get(r, "session")
if err != nil {
    // Handle expired or invalid cookie
}

Index

Constants

This section is empty.

Variables

View Source
var (

	// ErrNotInitialized is returned when attempting to operate on a cookie
	// that hasn't been initialized with New.returned when attempting to operate on a cookie.
	ErrNotInitialized = errors.New("not initialized")
	// ErrCookieExpired is returned when retrieving a cookie whose timestamp
	// exceeds its MaxAge.
	ErrCookieExpired = errors.New("expired cookie")
	// ErrExists is returned when attempting to create a cookie with a name
	// that already exists.
	ErrExists = errors.New("cookie exists")
)

Functions

func Clear

func Clear(w http.ResponseWriter, name string, remove bool) error

Clear removes the cookie from the client by setting its MaxAge to -1. If remove is true, it also deletes the cookie configuration from memory. Returns ErrNotInitialized if the cookie hasn't been created with New.

func Get

func Get(r *http.Request, name string) ([]byte, error)

Get retrieves and decrypts the cookie data from the request. It verifies the cookie hasn't expired based on its embedded timestamp and MaxAge. Returns ErrNotInitialized if the cookie hasn't been created with New, ErrCookieExpired if the cookie has expired, or other errors for decryption failures.

func New

func New(name string, age int64) error

New initializes a new encrypted cookie configuration with the given name and max age in seconds. It generates a random AES-256 key and nonce for encryption. Returns ErrExists if a cookie with the same name already exists.

func Save

func Save(w http.ResponseWriter, name string, data []byte) error

Save add a timestamp, encrypts the provided data and timestampt, and sets it as an HTTP cookie in the response. The cookie is secured with HttpOnly, Secure, and SameSite flags. Returns ErrNotInitialized if the cookie hasn't been created with New.

Types

type Cookie struct {
	Name   string
	MaxAge int64
	Key    []byte
	Mode   cipher.AEAD
	Nonce  []byte
}

Cookie represents an encrypted cookie configuration with its cryptographic parameters and metadata.

Jump to

Keyboard shortcuts

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