Skip to content
LynsoftPublic

About

Authentication-aware PostgreSQL RLS for any Node.js app — no database platform required.

Resources

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

pg-guard

Add authentication-aware PostgreSQL Row-Level Security to any Node.js application — without adopting a database platform or extra infrastructure.

The problem

PostgreSQL already enforces RLS. Most applications still fail at the glue:

  • Session identity is set with session-level SET and leaks across pooled connections.
  • Queries run as a table owner or superuser and silently bypass RLS.
  • Missing context fails open.
  • Teams stitch together an ORM, an auth library, and ad-hoc SQL to imitate Supabase.

pg-guard is the portable runtime that takes a verified server-side session, binds it to one transaction on a pooled connection, and lets PostgreSQL enforce the rest.

Five-minute conceptual example

import { createPgGuard } from "pg-guard";

const guard = createPgGuard({
  pool,
  runtimeRole: "app_authenticated",
});

const session = await getVerifiedSession(); // your auth library, not pg-guard

const projects = await guard.run(
  {
    userId: session.user.id,
    tenantId: session.activeOrganizationId,
  },
  async (client) => {
    const result = await client.query("select * from projects");
    return result.rows;
  },
);

run() validates context, opens a transaction, switches to a restricted role, sets transaction-local GUCs with parameterized set_config(..., true), runs your callback on that client, then commits or rolls back and releases the connection.

Supported stack

Layer MVP
Runtime Node.js 24+
Driver node-postgres
ORM (optional) Drizzle
Auth (optional) Better Auth, or any verifier
Framework (optional) Next.js App Router
Database Any standard PostgreSQL 16+ (self-hosted VPS, local Docker, managed Postgres)

You do not need Supabase, Neon-specific extensions, PostgREST, or a hosted gateway.

Security model

  • pg-guard does not authenticate users. Verify the session first, then map it.
  • pg-guard is server-side only. Do not import it in Client Components or browsers.
  • PostgreSQL remains the enforcement layer. Policies and GRANTs are the source of truth.
  • The package is independent of the database host.
  • Administrative connections must never reach browser code.
  • RLS does not replace application authorization (quotas, workflows, audit rules).

Identity is transaction-local. A reused pool connection cannot keep the previous user’s role or GUCs. Missing context fails closed. System access is a separate API and a separate pool.

See docs/architecture.md and docs/threat-model.md.

See it

cd examples/next-better-auth-drizzle
cp .env.example .env
pnpm db:up && pnpm db:setup && pnpm db:seed && pnpm dev

Open http://localhost:3456. Enter as Acme, try the steal, run the system job, then switch to Globex.

Installation

pnpm add pg-guard pg
pnpm pg-guard init --yes --database-client drizzle --auth better-auth --framework next
pnpm drizzle-kit migrate

Minimal working code

import { createDrizzleGuard } from "pg-guard/drizzle";
import { createBetterAuthMapper } from "pg-guard/better-auth";

export const toGuardContext = createBetterAuthMapper({
  userId: (session) => session.user.id,
  tenantId: (session) => session.session.activeOrganizationId,
  sessionId: (session) => session.session.id,
  roles: (session) => session.user.roles ?? [],
});

export const guard = createDrizzleGuard({
  pool,
  schema,
  runtimeRole: "app_authenticated",
});

const session = await auth.api.getSession({ headers: request.headers });
if (!session) return new Response("Unauthorized", { status: 401 });

return guard.run(toGuardContext(session), async (db) => db.query.projects.findMany());

Limitations

  • Not an auth provider, ORM, query gateway, or static RLS analyzer.
  • Does not verify cookies or JWTs.
  • Cannot stop application code from capturing an unrestricted db in a closure.
  • Does not cover TRUNCATE / superuser operations.
  • Nested guard.run() is rejected.
  • Advanced policy review belongs in pgrls.

Documentation

License

MIT

About

Authentication-aware PostgreSQL RLS for any Node.js app — no database platform required.

Resources

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages