@sidneyroberto9/sentret-fastify
v1.0.0
Published
Cookie-based session authentication for Fastify 5 on PostgreSQL, with an optional inactivity hub. Port of the sentret-session Java library.
Maintainers
Readme
@sidneyroberto9/sentret-fastify
Lightweight cookie-based session authentication for Fastify 5. Sessions live in your application's
own PostgreSQL (through its postgres.js client), the browser
carries an opaque HttpOnly cookie, and an optional hub serves the inactivity endpoints used by
@sidneyroberto9/sentret-react.
Port of the Java library sentret-session: same table, same session id format and same hub contract, so Java and Node apps can share sessions.
Install
npm install @sidneyroberto9/sentret-fastify postgresRequirements: Node 20+, Fastify 5, PostgreSQL. @fastify/cookie is registered for you when the app
has not registered it already.
Quickstart
import Fastify from "fastify";
import postgres from "postgres";
import { sentret } from "@sidneyroberto9/sentret-fastify";
const sql = postgres(process.env.DATABASE_URL!);
const app = Fastify({ logger: true });
await app.register(sentret, { sql, hub: { loginUrl: "https://app.example.com/login" } });
app.post("/auth/login", async (request, reply) => {
const { userId, email } = await credentials.check(request.body); // your own authentication
return app.sentret.login(reply, userId, email);
});
app.post("/auth/logout", async (request, reply) => {
await app.sentret.logout(request, reply);
return reply.code(204).send();
});
app.get("/me", async (request) => request.sentretUser);Every route requires a session (401, empty body) unless it matches publicPaths or opts out:
app.get("/catalog", { config: { sentret: { public: true } } }, handler);On public routes request.sentretUser is still filled when a valid cookie comes along. The user
carries userId, email, expiresAt and lastAccessedAt; sessionId is there too but never
serialized. Roles and permissions stay in your application, looked up by userId.
With Drizzle
Pass the postgres.js client Drizzle runs on:
const client = postgres(process.env.DATABASE_URL!);
export const db = drizzle(client);
await app.register(sentret, { sql: client });Export the table from your schema so drizzle-kit knows it (push would otherwise offer to drop it):
// src/db/schema.ts
export { sentretSessions } from "@sidneyroberto9/sentret-fastify/drizzle";If you would rather have drizzle-kit migrations own the table, also set createTable: false.
Database
Nothing to do: when the app is ready, the plugin creates sentret_sessions if it does not exist and
leaves an existing one alone. A database user without CREATE TABLE only gets an error logged.
CREATE TABLE sentret_sessions (
session_id VARCHAR(20) NOT NULL PRIMARY KEY,
user_id VARCHAR(255) NOT NULL,
email VARCHAR(255),
created_at BIGINT NOT NULL,
expires_at BIGINT NOT NULL,
last_accessed_at BIGINT NOT NULL
);
CREATE INDEX idx_sentret_sessions_user_id ON sentret_sessions (user_id);
CREATE INDEX idx_sentret_sessions_expires_at ON sentret_sessions (expires_at);Options
Only sql is required. Durations are in milliseconds.
| Option | Default | |
|---|---|---|
| sql | — | The app's postgres.js client. |
| createTable | true | Create the table when missing. false only logs an error. |
| ttlMs | 8h | Absolute session lifetime. |
| maxIdleMs | 30min | Inactivity window, reset only by the hub heartbeat. Enforced only with the hub on; 0 disables it. |
| cookieName | SENTRETSID | Use __Host-SID to harden the cookie. |
| cookieSecure | true | false only for local HTTP. |
| cookieSameSite | lax | |
| cookieDomain | — | Share the cookie across subdomains. |
| publicPaths | /login, /auth/*, /public/*, /health/* | /x/* matches /x and below; others are exact. |
| hub | off | true or an object below. |
| hub.basePath | /session | |
| hub.heartbeatIntervalMs | 60s | Echoed to the client. |
| hub.statusPollIntervalMs | 30s | Echoed to the client. |
| hub.warningBeforeMs | 60s | Echoed to the client. |
| hub.loginUrl | — | Echoed to the client. |
| onSessionCreated / onSessionRenewed / onSessionDestroyed | — | Callbacks with userId and sessionId. |
CORS and CSRF stay with the app: @fastify/cors with
credentials: true when the UI runs on another origin, and
@fastify/csrf-protection if you use
cookieSameSite: "none". Preflight (OPTIONS) requests are never rejected by the plugin.
API (app.sentret)
| Method | |
|---|---|
| login(reply, userId, email?) | Creates the session, writes the cookie, returns the user. Purges expired rows first. |
| logout(request, reply) | Destroys the request's session and clears the cookie. |
| logoutSession(sessionId) | Destroys one session. |
| logoutAll(userId) | Destroys every session of the user. |
| renew(sessionId) | Resets both deadlines of a valid session; null if it is gone. |
| validate(sessionId) | The user of a valid session, or null. Not activity. |
Inactivity hub (optional)
| Endpoint | Auth | |
|---|---|---|
| GET {basePath}/status | public | Remaining absolute/idle time + client config. Never counts as activity. |
| POST {basePath}/heartbeat | session | The only activity signal: one UPDATE. |
| POST {basePath}/renew | session | Resets both deadlines and rewrites the cookie. |
How it works
- An
onRequesthook reads the cookie and validates the session with oneSELECT(a malformed cookie is rejected without querying, and the stored id must match exactly). A dead cookie is cleared and the request goes on anonymous, so public routes such as the login still work. - Only the heartbeat (and an explicit renew) writes
last_accessed_at. Polls and your own API calls never extend a session. - Expired rows are purged on login (indexed
DELETE); there is no scheduler.
License
MIT
