Skip to main content

@strutvane/auth: Sign-In, Permissions and Multi-Tenancy That Are Safe Before You Configure Anything

Passwords, 2FA, passkeys, API tokens and teams, plus permission rules that compile straight into SQL, for TypeScript business apps.

Updated 7 min readMarkdown

"Managers can approve invoices up to 10,000. Everyone can see their own invoices. Paid invoices can never be deleted. And customer A must never see customer B's data."

Every business app ends up with sentences like these. Writing them down is easy. Enforcing them everywhere, on every list, every export, every search and every edit, is where things quietly go wrong. One forgotten WHERE clause and a list endpoint returns rows nobody should see.

@strutvane/auth is built so that forgetting isn't possible.


What it is

@strutvane/auth is the authentication and authorization package of Strutvane, an open-source (MIT) TypeScript framework for business (B2B) apps.

  • Authentication ("who are you?"): Strutvane's own identity engine, with passwords, email links, two-factor authentication, passkeys, API tokens, teams and impersonation.
  • Authorization ("what may you do?"): typed policies and roles that compile to SQL, so the database itself only returns rows the user may see.
  • Multi-tenancy ("which customer company are you in?"): enforced by PostgreSQL row-level security, plus an audit of the database setup.

It works inside a Strutvane app, or standalone in any Node app through middleware for Hono and plain Node servers.

Why it exists

Two reasons.

First, filtering after the fact is broken. Many apps load 50 rows and then hide the ones the user can't see. Now your page shows 37 rows, your "page 3 of 10" is wrong, and your search results still hint at records that exist. In @strutvane/auth, a permission rule becomes part of the SQL query, so lists, counts and pagination are correct from the start.

Second, the safe choice should be the default one. B2B apps are usually invite-only, so public sign-up is off until you turn it on. A missing rule denies. A switched-off feature doesn't just hide a button; its routes don't exist at all.

What you get

Sign-in features (each one switched on or off in config/auth.ts):

Feature Default
Email + password sign-in, with rate limits and lockout on
Password reset (60-minute, single-use links) follows password
"Confirm your password" before sensitive changes on
Public registration off
Email verification off
Passwordless email links off
Two-factor authentication (TOTP apps) with recovery codes off
Passkeys (WebAuthn) off
Personal API tokens off
Teams (as tenants), with invitations and roles off (on with tenancy)
Impersonation, for platform admins only, audited off

Permissions

  • definePolicy(): allow and deny rules per action, with conditions on the row ("the owner can update their own invoice"). Deny always wins. No matching rule means deny.
  • Typos don't compile. A condition on a field that doesn't exist, or a comparison of the wrong type, is a TypeScript error, and every rule is checked again when the app boots.
  • Field rules: "only managers can read internalNotes." Unreadable fields can't be filtered or sorted on either, so nobody can probe their values one guess at a time.
  • A role map for app-wide grants ("admins may do everything", "members may view and create, and update their own"), so you don't repeat them in every policy. Platform roles and tenant roles are kept separate, so a role inside one customer's team never reaches platform-wide data.

Tenancy and audit

  • A tenant resolver chain (subdomain, path, trusted header or session). A request for a tenant the user doesn't belong to gets a 403.
  • PostgreSQL row-level security set up per transaction, never leaked between pooled connections.
  • tenancyAudit() checks your database for unprotected tables, runtime roles that could bypass the rules, and similar setup mistakes. Run it in CI.
  • Domain events such as auth.login.succeeded, auth.two_factor.enabled or tenant.member.changed, carrying ids only, plus audit records that redact passwords, tokens and secrets.

Storage

  • Identity data in PostgreSQL or SQLite (in-memory stores for tests). Two ordinary migrations create the tables, and your app keeps owning its users table.

How it fits into Strutvane

Auth and the framework never import each other. The framework asks one question through a contract (a "permission provider"): may this user do this, and which rows may they see? Auth answers it.

In an app, the provider loads your policies from app/policies/, combines them with the role map in config/auth.ts, and plugs into the framework's request pipeline through hooks. On PostgreSQL it shares the framework's database connection, so there's one pool, not two. Field rules are enforced on every API record through the framework's serialize and write hooks.

There are CLI commands too, such as node strut auth:migration (copy the migrations into your app) and node strut auth:user:create, which reads the password from an environment variable, never from a command-line flag that would end up in your shell history.

A quick look

npm install @strutvane/auth @strutvane/framework

A policy, and the same rules used for one record in memory and for a whole list in SQL:

import { createPermissionProvider, definePolicy, defineSchema } from '@strutvane/auth'
import { compileToSql } from '@strutvane/auth/sql'

const invoice = defineSchema({
  table: 'invoices',
  columns: {
    ownerId: { column: 'owner_id', type: 'uuid' },
    amount: { column: 'amount', type: 'int4' },
    status: { column: 'status', type: 'text' },
    internalNotes: { column: 'internal_notes', type: 'text' },
  },
})

export const invoicePolicy = definePolicy('invoice', { schema: invoice }, ({ allow, deny, field }) => {
  allow(['viewAny', 'view'], { role: ['accountant', 'manager'] })
  allow(['view', 'update'], { when: ({ actor, row }) => row.ownerId.eq(actor.id) })
  allow('approve', { role: 'manager', when: ({ row }) => row.amount.lte(10_000) })
  deny('delete', { when: ({ row }) => row.status.eq('paid'), name: 'paid-is-final' })
  field('internalNotes').readable({ role: 'manager' })
})

const permissions = createPermissionProvider([invoicePolicy])

// A list, in SQL: pagination counts stay correct, nothing is filtered afterwards
const filter = await permissions.filterFor(actor, 'invoice.view', 'invoice')
const where = compileToSql(filter, invoice, { alias: 'i' })

The in-memory check and the SQL select exactly the same rows. That's not a hope; property-based tests compare the two against a real PostgreSQL.

⚠️ This is a 0.2 preview. The APIs may still change before 1.0, planned for January 2027.

Built to be trusted

Some of the protections the README documents:

  • Passwords are hashed with scrypt, compared in constant time, and every failure returns the same invalid_credentials answer, so attackers can't tell "wrong password" from "no such user".
  • Rate limits per IP address and per account, which can't be dodged with a forged X-Forwarded-For header.
  • Sessions: the cookie holds a random id and the database stores only a keyed digest of it. A new session on every sign-in and every privilege change, idle and absolute timeouts, and a password reset signs you out everywhere.
  • Every secret (session ids, reset links, recovery codes, API tokens, invitations) is stored only as an HMAC (a keyed fingerprint), never in plain text.
  • No value ever reaches SQL text. Values are typed parameters, and untrusted filters are capped in size and depth before any work is done.

And the numbers:

  • 883 automated tests, including attack-style tests (cross-tenant access, role tampering, header spoofing, SQL injection, session fixation, hostile filters) on every CI build.
  • CI on Linux, Windows and macOS, on Node 24 and Node 26.
  • Security-reviewed, secure by default.
  • Every release is staged by CI and approved by a human with two-factor authentication, and published with npm provenance.

What's next

From the README's "not built yet" list:

  • Ready-made screens for login, the 2FA challenge and account settings, and the installer that adds auth to an existing app.
  • A MySQL identity store and an ORM-backed store (today, MySQL and MariaDB apps keep sign-in sessions in memory, with a warning).
  • Single sign-on (OIDC/SAML) and SCIM as separate add-ons. Social sign-in already has its own package, @strutvane/social-login, which gets its own post in this series.

Try it, and tell me what you think

Next in the series: @strutvane/ui, the admin that builds itself. Follow along so you don't miss it. 🔐

— Vishwajit VM


Part of the Strutvane series. Strutvane™ is open source under the MIT licence.

About the author

  • Hi, I'm Vishwajit VM, a backend & AI engineer from New Delhi. For 5+ years I've built the parts of apps you don't see: APIs, databases, queues and AI agents, for teams in hiring, real estate, finance, retail and civic tech. My rule is simple: a system should keep working when something goes wrong. Right now I'm a backend developer at SPNX, building an EU VAT-registration platform that runs in production. After hours I'm building Strutvane, an open-source TypeScript framework for business apps (I'm writing about it as a series on my blog, vishwajitvm.hashnode.dev), plus my own products such as DevFlow-AI (self-hosted AI code review) and Hopline (encrypted peer-to-peer file transfer). Day to day I work with Python, FastAPI, Node.js, TypeScript, NestJS, PostgreSQL, Redis, Docker, LangGraph and RAG, and I've shipped plenty of Laravel/PHP and React along the way. Outside work, I'm a part-time photographer. See my work at https://vishwajit-labs-web.vercel.app/

No comments yet. Be the first to comment.

More from this blog