At a glance
5
Go services in app/
auth, core, learn, media, notification; each has its own go.mod and is listed in go.work.
4
services that introspect
core, learn, media and notification call auth-service GET /internal/session through pkg/auth.
60 s
in-process cache TTL
Set in InitAuth (pkg/auth/auth.go); also the upper bound on how long a revoked token can still be honoured by one process.
1
auth replica
replicas: 1 in puchi-infra/infra/backend/auth/deployment.yaml.
✎ Key Insights in 30 Seconds
Decision record: Puchi's auth service is a thin Limen wrapper over Postgres sessions; other Go services introspect over HTTP with a 60-second in-process cache. What that gives, where it leaks, and what is still open.
Problem Context
A JWT held in the browser cannot be revoked before it expires without a deny-list, and any token script can read is exposed to XSS. Puchi's design doc records the move to opaque Limen sessions as a maintenance decision, not a revocation argument.
Naive approach vs. engineered
✕ Before: custom JWT service
- RS256 access token (15 minutes) verified through JWKS
- Opaque refresh token with 30-day rotation
- A Next route (/api/auth/set-session) to bridge the session
- Login, OAuth and session endpoints maintained in-house
✓ Now: Limen sessions
- Opaque session token as HttpOnly cookie or Bearer header
- Sessions in Postgres (auth.sessions), looked up through /internal/session
- No JWKS, no refresh rotation, no set-session route
- Login, OAuth and email flows come from Limen plugins
Opaque Sessions Instead of JWT in Puchi: What the Code Does and What It Costs
Architecture & Design
The auth service mounts Limen at /auth/ over Postgres and exposes GET /internal/session. core, learn, media and notification take the opaque token from a Bearer header or the limen_session cookie, call that endpoint through pkg/auth, and cache the identity in a per-process map for 60 seconds. NATS carries user-created and email events, not session state.
Key Technical Decisions
- 1Use Limen (a Go library) instead of the custom JWT stack: fewer endpoints to maintain, per the 2026-07-17 design doc.
- 2Accept both Bearer and the limen_session cookie in pkg/auth: browsers send the HttpOnly cookie, but the cookie path needs CSRF care that the Bearer path does not.
- 3Introspect over HTTP with a 5-second client timeout: simple, but an auth outage degrades to 401 or guest mode after the cache expires.
- 4Cache identities for 60 seconds per process: fewer auth calls, but revocation can lag by up to 60 seconds and the map is never swept.
- 5Keep the Bearer token in sessionStorage as well as the cookie: lets fetchWithAuth send Authorization, but a script can read it.
What a browser-held JWT costs this product
Puchi is a Next.js PWA for learners, and the same account is used from a phone, a laptop and sometimes a shared device. Three things about that make a self-contained JWT in the browser awkward:
- Logout and revocation. A signed JWT stays valid until it expires unless every service also consults a deny-list. Then you have a lookup per request anyway, plus a second store.
- Where the token lives. A JWT a script can read is a token a script can steal. Anything JS can see (localStorage, a non-HttpOnly cookie) is exposed to XSS.
- Refresh. Short-lived access tokens need a refresh flow, and a lesson in progress is a bad place to discover a race between two tabs refreshing at once.
I should be careful about what the repo actually says here. The design doc (docs/superpowers/specs/2026-07-17-limen-auth-design.md in puchi-backend) records the move from a custom JWT stack (RS256, JWKS, 15-minute access token, 30-day rotating refresh token) to Limen as a maintenance decision: "Tự build login/OAuth/session/MFA" versus "Plugins chuẩn + thin wrapper", and fewer endpoints to maintain. It does not argue revocation or latency. The revocation argument above is mine, and the rest of this note checks how far the code delivers on it. The same doc lists the earlier path: Clerk, Supertokens, Zitadel, a custom JWT service, then Limen.
How sessions work in the code
Limen is a Go library (github.com/thecodearcher/limen v0.1.4 in app/auth/go.mod), not a hosted product. Puchi's auth service is a plain net/http server, about 310 lines in app/auth/cmd/auth/main.go, that mounts Limen's handler at /auth/ and enables the credential-password plugin plus Google, Facebook and a custom TikTok OAuth provider. Sessions are rows in Postgres (auth.sessions, with a unique token, expires_at, last_access, and an index on user_id; app/auth/migrations/001_limen_schema.up.sql). There is no Valkey in the session path: the Go code has no Redis client, even though Valkey is deployed in the cluster and the service configs mention it.
The browser gets the token two ways. Limen sets an HttpOnly limen_session cookie, and a session transformer also returns the same token in the JSON body so the frontend can send it as a Bearer header:
// app/auth/cmd/auth/main.go
limen.WithHTTPSessionTransformer(func(user map[string]any, sessionResult *limen.SessionResult) (map[string]any, error) {
out := map[string]any{"user": user}
if sessionResult != nil && sessionResult.Token != "" {
out["token"] = sessionResult.Token
}
return out, nil
}),
Other Go services do not parse anything. They accept either form and ask the auth service:
// pkg/auth/token.go
func SessionTokenFromRequest(r *http.Request) string {
authHeader := r.Header.Get("Authorization")
if strings.HasPrefix(strings.ToLower(authHeader), "bearer ") {
if token := strings.TrimSpace(authHeader[len("Bearer "):]); token != "" {
return token
}
}
if c, err := r.Cookie(DefaultLimenSessionCookie); err == nil && c != nil {
// ... same trim, return c.Value
}
return ""
}
// app/auth/cmd/auth/main.go
mux.HandleFunc("GET /internal/session", func(w http.ResponseWriter, r *http.Request) {
session, err := auth.GetSession(r)
if err != nil || session == nil || session.User == nil {
http.Error(w, `{"message":"unauthorized"}`, http.StatusUnauthorized)
return
}
// ... writes {"user_id", "email", "username"} as JSON
})
pkg/auth/jwt.go (the file name is left over from the JWT era; the type is still aliased as JWTValidator) calls that endpoint with a 5-second client timeout and keeps an in-process map keyed by the SHA-256 of the token with a fixed 60-second TTL (InitAuth in pkg/auth/auth.go). Four services wire it up (core, learn, media, notification), each pointed at http://auth-service.puchi-backend:8000 in puchi-infra/infra/backend/*/deployment.yaml. The cookie domain in the deployed auth config is puchi.io.vn, and the API sits at api.puchi.io.vn.
The old copy of this article described gRPC introspection and a Valkey cache. Neither exists: introspection is one HTTP GET, and the cache is a Go map in each service process.
✎ note
The cache is a Go map in each service process, not Valkey, and introspection is HTTP, not gRPC. Both differ from the earlier version of this article.
Failure modes I can see in the code
Auth service down or slow. A cache hit still works for up to 60 seconds. After that, introspect returns an error for any non-200/401 response or a timeout. What the user sees depends on the route: protected routes answer 401 NO_SESSION (ErrSessionExpired is defined but nothing returns it), while learn's optional filter (app/learn/internal/server/learn_auth.go) deliberately falls through, so a logged-in learner is treated as a guest. On the client, tryRefreshToken in puchi-frontend/src/lib/token-manager.ts calls clearToken() when getSession() fails or throws, so an auth outage can also log the browser out locally. The auth deployment runs replicas: 1, so this is not a theoretical path.
Revocation lag. Deleting a session row takes effect at the auth service immediately, but each Go process can keep serving the cached identity for up to 60 seconds. "Instant revocation", as the old copy put it, is not what the code does. Failed lookups are not cached, so a stale token costs one auth-service call per request.
Cache growth. getCached ignores expired entries but never deletes them, and nothing sweeps the map. Entries are only replaced if the same token returns. For a small service that is harmless; it is also a leak I would fix before calling it done.
Cookie theft and XSS. The cookie is HttpOnly, but the frontend defeats part of that. setToken stores the Bearer value in a zustand store persisted to sessionStorage under puchi-auth, and hands it to the limen-auth bearer plugin (authClient.bearer.setTokens). A script that can run on the page can read it. The opaque token is no better than a JWT against XSS in this setup; what it buys is that a stolen token can be killed server-side.
CSRF. Every Go service accepts the cookie as a fallback, so a cookie-authenticated POST is possible. The Bearer path is not CSRF-prone; the cookie path relies on SameSite and origin checks. Limen is configured with trusted_origins, and Envoy's CORS policy allows only https://puchi.io.vn and localhost with credentials. I did not read Limen's source, so I cannot state the exact SameSite/Secure attributes of limen_session or whether Limen checks Origin on mutations. The only option Puchi sets is cross-subdomain cookies for puchi.io.vn, and Secure=false when the base URL is local HTTP.
Guest identity. Anonymous learners get a separate puchi_guest_id cookie, which is HttpOnly, SameSite=Lax, Secure, domain .puchi.io.vn, 30 days (app/learn/internal/service/learn.go). Its value is a bare UUID, not a signed token. It is an identifier for guest progress, not a credential for anything sensitive, and ClaimGuest merges it into the user and clears it at login.
Fixation, concurrent devices, clock skew. Session creation and rotation are inside Limen, and I did not audit them. The schema allows many sessions per user, but Puchi's own code adds no "list my devices" or "sign out everywhere" endpoint. Expiry is decided by expires_at in the auth database, so there is one clock; the 60-second cache uses each service's local time only.
! careful
Revocation takes effect at the auth service at once, but a service may keep honouring a revoked token for up to 60 seconds.
What this costs and what is not done
What opaque sessions cost here, concretely:
| Cost | In this codebase |
|---|---|
| A lookup per uncached request | One HTTP call to auth-service, which reads Postgres via Limen. I did not read Limen's internals, and no benchmark in the repo measures it |
| A store to run | The auth schema in CloudNativePG (pg-puchi-rw), in the same Postgres cluster the other Puchi services use |
| Cross-service propagation | None beyond the HTTP lookup. Each service introspects on its own and the gateway does not authenticate |
| Revocation latency | Up to 60 s per process because of the local cache |
Gaps I noticed and would list as open work:
- No gateway auth. An earlier design used Envoy ext_authz and an
X-User-IDheader (.superpowers/sdd/*.mdreports).puchi-infra/infra/envoy-gateway/api-securitypolicy.yamlnow only sets CORS. The media service still has anextractUserIDthat readsx-user-idfrom gRPC metadata. I could not find anything in the current tree that sets it, so I do not know whether media uploads authenticate correctly end to end. That needs a test. - gRPC is unauthenticated. Each service's gRPC server (port 9000) has only the recovery middleware. The gateway routes only the HTTP port and no service calls another over gRPC, so nothing is exposed today, but a future internal client would have no identity to propagate.
- No roles.
SessionInfo.Rolesis never filled, soHasRoleis always false. RBAC is listed as out of scope in the design doc. - Tests.
pkg/authhas three middleware tests and four token-extraction tests. Nothing covers the cache, the introspection call or the failure paths above. - Events are not session-related. NATS carries
auth.user.createdandemail.send(pkg/nats/nats.go); the publisher is a no-op when the URL is empty and uses fire-and-forget goroutines. There is no "session revoked" event, which is why the cache TTL is the only propagation mechanism. - PWA offline. The PWA has a web manifest (
src/app/manifest.ts) but I found no service worker in puchi-frontend, so there is no offline auth behavior to describe.
When JWT would still fit
The repo records nothing about a case where Puchi wants JWT again, so this is my reading, not a documented decision.
The earlier stack (RS256 with JWKS) existed precisely so that services could verify tokens locally. If the auth service became a bottleneck or a single point of failure, which it currently is with one replica, signed short-lived tokens would remove the hot-path lookup, at the price of the revocation window and a refresh flow. Given the current cache, that window is already up to 60 seconds, so the practical gap between the two designs is smaller than the old article suggested.
What I would change first is smaller: sweep the cache, add tests for the failure paths, stop persisting the token to sessionStorage if the cookie alone is enough, and decide what media should do about identity.
Verified repository evidence
auth · direct
Opaque Limen sessions stored in Postgres; core, learn, media and notification resolve them via an internal HTTP session endpoint with a 60-second in-process cache.
↳ Introspection is an HTTP GET to /internal/session with a 5 s client timeout; revocation is immediate at auth-service but cached up to 60 s elsewhere.
puchidemy/puchi-backend ↗
Key Engineering Takeaways
- The recorded reason for opaque sessions is less custom auth code; revocation and XSS arguments are mine and the code only partly delivers them.
- With a 60-second per-process cache, revocation is not instant and the gap to a short-lived JWT is smaller than it looks.
- Open work: sweep the cache, test the failure paths, stop persisting the token to sessionStorage, and settle how media identifies users.