Drops the Dialect/Queries abstraction in favor of a single PostgreSQL 16+ implementation collapsed into the root authkit package, removes the public store interfaces, and reshapes the authorization model around seeded slugs (roles, permissions, abilities) with optional labels. Schema is now squashed into one migrations/0001_init.sql and applied automatically on authkit.New (opt-out via Config.SkipAutoMigrate). A schema verifier checks tables/columns/types/nullability on startup, tolerates extra columns, and falls back to default table names when a configured override is missing. Auth API: CreateUser + SetPassword replace Register; password is nullable. Email OTP (RequestEmailOTP/ConsumeEmailOTP) joins magic links and password reset, all with anti-enumeration silent-success defaults and a Config.RevealUnknownEmail opt-in. Service tokens drop owner columns and validate ability slugs against authkit_abilities at issue. Direct user permissions live alongside role-derived ones; queries return their UNION. Predicate API: HasRole/HasPermission/HasAbility leaves with AnyLogin/AllLogin/AnyServiceKey/AllServiceKey combinators. Validate runs at middleware construction, panicking on unknown slugs. Middleware collapses to RequireLogin (cookie + JWT), RequireGuest (configurable OnAuthenticated), and RequireServiceKey. UserIDFromCtx / UserFromCtx (lazy) / RefreshUserInCtx provide request-lifetime user caching. Cookie defaults flip to Secure=true and HttpOnly=true via *bool with BoolPtr opt-out. CLIs ship under cmd/perms, cmd/roles, cmd/abilities for seeding the authorization vocabulary; the library never seeds rows itself. Tests cover unit-level (slug validation + fuzz, opaque secrets, email normalization, extractors, predicates, OTP generator) and integration flows gated on AUTHKIT_TEST_DATABASE_URL (every Auth method, schema drift detection, migration idempotency, lazy user cache, all middleware paths). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
70 lines
2.1 KiB
Go
70 lines
2.1 KiB
Go
package authkit
|
|
|
|
import (
|
|
"git.juancwu.dev/juancwu/errx"
|
|
"github.com/golang-jwt/jwt/v5"
|
|
"github.com/google/uuid"
|
|
)
|
|
|
|
// accessClaims is the JWT shape issued by IssueJWT. session_version carries
|
|
// User.SessionVersion at issue time so AuthenticateJWT can detect global
|
|
// revocations (logout-everywhere, password change).
|
|
type accessClaims struct {
|
|
jwt.RegisteredClaims
|
|
SessionVersion int `json:"sv"`
|
|
Method string `json:"m"`
|
|
}
|
|
|
|
func (a *Auth) signAccessToken(userID uuid.UUID, sessionVersion int) (string, error) {
|
|
const op = "authkit.signAccessToken"
|
|
now := a.now()
|
|
claims := accessClaims{
|
|
RegisteredClaims: jwt.RegisteredClaims{
|
|
Subject: userID.String(),
|
|
Issuer: a.cfg.JWTIssuer,
|
|
Audience: jwt.ClaimStrings{a.cfg.JWTAudience},
|
|
IssuedAt: jwt.NewNumericDate(now),
|
|
ExpiresAt: jwt.NewNumericDate(now.Add(a.cfg.AccessTokenTTL)),
|
|
ID: uuid.NewString(),
|
|
},
|
|
SessionVersion: sessionVersion,
|
|
Method: string(AuthMethodJWT),
|
|
}
|
|
tok := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
|
signed, err := tok.SignedString(a.cfg.JWTSecret)
|
|
if err != nil {
|
|
return "", errx.Wrap(op, err)
|
|
}
|
|
return signed, nil
|
|
}
|
|
|
|
// parseAccessToken validates the signature and returns the parsed claims.
|
|
// Strictly enforces HS256 — alg=none and asymmetric algorithms are rejected.
|
|
func (a *Auth) parseAccessToken(token string) (*accessClaims, error) {
|
|
const op = "authkit.parseAccessToken"
|
|
opts := []jwt.ParserOption{
|
|
jwt.WithValidMethods([]string{jwt.SigningMethodHS256.Alg()}),
|
|
jwt.WithExpirationRequired(),
|
|
jwt.WithIssuedAt(),
|
|
jwt.WithTimeFunc(a.cfg.Clock),
|
|
}
|
|
if a.cfg.JWTIssuer != "" {
|
|
opts = append(opts, jwt.WithIssuer(a.cfg.JWTIssuer))
|
|
}
|
|
if a.cfg.JWTAudience != "" {
|
|
opts = append(opts, jwt.WithAudience(a.cfg.JWTAudience))
|
|
}
|
|
parser := jwt.NewParser(opts...)
|
|
|
|
parsed, err := parser.ParseWithClaims(token, &accessClaims{}, func(t *jwt.Token) (any, error) {
|
|
return a.cfg.JWTSecret, nil
|
|
})
|
|
if err != nil {
|
|
return nil, errx.Wrap(op, ErrTokenInvalid)
|
|
}
|
|
claims, ok := parsed.Claims.(*accessClaims)
|
|
if !ok || !parsed.Valid {
|
|
return nil, errx.Wrap(op, ErrTokenInvalid)
|
|
}
|
|
return claims, nil
|
|
}
|