@gentleduck/auth
Faceted, framework-agnostic, transport-pluggable authentication for TypeScript. Pairs with @gentleduck/iam for authorization.
MIT - Changelog - Security - Docs
Every TypeScript auth library makes you choose framework lock-in (NextAuth, Auth.js), a hosted control plane (Clerk, WorkOS, Stytch), or DIY-on-Lucia + passport + your own glue. @gentleduck/auth is the third option, but unified: framework-agnostic core, batteries-included adapters, no hosted plane. Wire it into Express, Hono, Next.js, Fastify, Koa, NestJS, Elysia, gRPC, or your own router with one adapter import.
Zero hosted dependencies. Tree-shakeable subpath exports. Lazy peer deps for the heavy bits (argon2, simplewebauthn, the AWS KMS client, the database drivers).
Install
npm install @gentleduck/auth
# or
bun add @gentleduck/auth
Install only what you wire:
| Package | When you need it |
|---|---|
@node-rs/argon2 | Argon2id password hashing (FIPS / HIPAA presets) |
@simplewebauthn/server | Passkey / WebAuthn-MFA |
@aws-sdk/client-kms | AWS KMS envelope encryption at rest |
drizzle-orm + pg, mysql2 or better-sqlite3 | Drizzle adapter (pg / mysql / sqlite) |
ioredis or @upstash/redis | Redis-backed session / idempotency / limiter / events / DPoP-nonce stores |
@node-saml/node-saml | SAML 2.0 SP |
@nestjs/common | NestJS adapter |
Quick start
import { createAuth } from '@gentleduck/auth/core'
import { MemoryAdapter } from '@gentleduck/auth/adapters/memory'
import { MemoryLimiter } from '@gentleduck/auth/limiters/memory'
import { Argon2idHasher, passwords } from '@gentleduck/auth/providers/passwords'
const storage = new MemoryAdapter()
export const auth = createAuth({
baseUrl: 'http://localhost:3000',
stores: storage,
limiter: new MemoryLimiter({ max: 5, windowMs: 60_000 }),
providers: [passwords({ hasher: new Argon2idHasher() })],
})
const identity = await auth.identities.create({ profile: { username: 'a', email: '[email protected]' } })
await auth.passwords.set(identity.id, 'correct-horse-battery', auth.cfg.stores.credentials, null)
const result = await auth.flows.signIn({
providerId: 'password',
input: { email: '[email protected]', password: 'correct-horse-battery' },
})
// result.session, result.sid, result.intents[]
createAuth is the factory that wires the facets, picks sane defaults (a CookieTransport named __Host-duck-sid, InMemoryEvents), and registers the providers you pass. passwords() hashes with Argon2idHasher unless you pass hasher, so install @node-rs/argon2 or pass ScryptHasher. For full control, instantiate AuthEngine directly - both APIs accept the same primitives.
Architecture
AuthEngine is the root: every state-changing operation lives behind one named facet so adapters, transports, and providers compose without back-channel coupling.
| Facet | Owns |
|---|---|
identities | profile CRUD, link/unlink, soft-delete + grace-period restore, GDPR export, bulk import |
sessions | rotateOrCreate (single privilege-changing API), getBySid, revoke, revokeAllForIdentity, gc |
credentials | password / api-key / oauth / passkey / recovery / totp / webauthn-mfa rows; CAS rotation |
passwords | strength + cap validation, constant-time verify, needsRehash + auto-rehash, common-list reject |
passkeys | list / revoke / revokeAll, scoped to the identity that holds them |
mfa | TOTP enrollment + verify, backup-code mint/verify, WebAuthn-MFA |
apiKeys | mint / list / rotate / revoke / revokeAll / verify + scope checks, tenant-bound issuance |
flows | signIn / signOut / signUp (multi-stage) / password-reset / email-verification / account-deletion / linkProvider / unlinkProvider / impersonate / step-up / step-down |
csrf | double-submit + origin-only + sec-fetch-site gates, __Host- cookie |
webhooks | HMAC + timestamp + tolerance, retry w/ backoff, dead-letter, SSRF-guarded URLs |
events | typed bus, lockout / signin.success / signin.failed / suspicious / session.revoked / mfa.removed |
hijack | IP / UA drift detection + step-up / rotate / revoke reaction policy |
anomaly | pluggable detectors (impossible-travel, device-fingerprint), composition + decision ladder |
orgs | org + membership CRUD, role sanitisation, multi-tenant guard |
Plus m2m (client_credentials OAuth2 grant), compliance (GDPR / HIPAA / SOC2 / FIPS presets), plugin (named install + facet extension), and audit (admin-mutation hook with redaction).
Providers
| Path | What |
|---|---|
@gentleduck/auth/providers/passwords | Email + password |
@gentleduck/auth/providers/magic-link | Passwordless one-time link |
@gentleduck/auth/providers/passkey | WebAuthn passkey (lazy peerDep on @simplewebauthn/server) |
@gentleduck/auth/providers/api-key | Long-lived bearer keys via ApiKeysFacet |
@gentleduck/auth/providers/oauth/google | Google OAuth (PKCE + nonce) |
@gentleduck/auth/providers/oauth/github | GitHub OAuth (PKCE + state) |
@gentleduck/auth/providers/oauth/microsoft | Microsoft / Entra ID OAuth |
@gentleduck/auth/providers/oauth/discord | Discord OAuth |
@gentleduck/auth/providers/oauth/linkedin | LinkedIn OAuth |
@gentleduck/auth/providers/oauth/apple | Sign in with Apple |
@gentleduck/auth/providers/oauth/core | Any other OAuth 2.0 / OIDC IdP: oProvider over an OAuthClient |
@gentleduck/auth/providers/saml | Wrapper over a @node-saml/node-saml client you build: SP-initiated + IdP-initiated SSO, SP metadata XML generation, Single Logout (SP- and IdP-initiated) |
Transports
import {
CookieTransport, // __Host- prefix + HttpOnly + SameSite=Lax (default)
BearerTransport, // opaque tokens in Authorization header
JwtTransport, // HS256 / RS256 / ES256 / EdDSA + JWKS rotation
CompositeTransport, // chain multiple transports
} from '@gentleduck/auth/core/transport'
import {
DPoPVerifier,
MemoryDPoPNonceStore,
computeJwkThumbprint,
bindPayloadToDPoP,
} from '@gentleduck/auth/core/transport' // RFC 9449
Storage adapters
import { MemoryAdapter } from '@gentleduck/auth/adapters/memory'
import { DrizzlePgAdapter } from '@gentleduck/auth/adapters/drizzle/pg'
import { DrizzleMysqlAdapter } from '@gentleduck/auth/adapters/drizzle/mysql'
import { DrizzleSqliteAdapter } from '@gentleduck/auth/adapters/drizzle/sqlite'
import {
RedisSessionImpl,
RedisEvents,
RedisDPoPNonceStore,
} from '@gentleduck/auth/adapters/redis'
import { RedisLimiter } from '@gentleduck/auth/limiters/redis'
import { FakeRedis } from '@gentleduck/auth/test' // in-tree, for tests
// One class per dialect, implementing the three store contracts. The constructor takes a
// connection string, a driver pool, or a drizzle handle you already have.
const storage = new DrizzlePgAdapter('postgres://localhost/app')
const { identities, credentials, sessions } = storage
What a call costs
p50 at the adapter boundary - drizzle building the SQL, the driver, the round trip and the row mapping - over 50k identities and 100k logins on every backend, on one laptop under everyday load:
| call | Memory | SQLite | Postgres | MySQL |
|---|---|---|---|---|
find({ id }) | 3 µs | 0.089 ms | 0.280 ms | 0.255 ms |
find({ email }) | 7 µs | 0.090 ms | 0.299 ms | 0.259 ms |
find({ providerId, providerSub }) | 8 µs | 0.112 ms | 0.383 ms | 0.282 ms |
create (2 logins) | 2.125 ms | 0.632 ms | 0.650 ms | 1.184 ms |
erase | 3 µs | 0.543 ms | 0.499 ms | 1.348 ms |
link | 0.630 ms | 0.454 ms | 0.549 ms | 1.404 ms |
patchMetadata | 4 µs | 0.282 ms | 0.271 ms | 0.906 ms |
Reads are index-driven on every dialect and the driver round trip costs ~5x the query it carries. Writes
are one statement on Postgres (create and erase are each a single CTE) and a transaction on the
others, which have no RETURNING or no DML inside a WITH. Memory's create and link are the
outliers: both check a login against every row the adapter holds, which is a test double being one, not a
store to run 50k accounts through.
Run it yourself with bun run bench:adapters - it starts and removes its own containers. The plans, the
p95s, the method behind these and what is deliberately left unoptimised are in
src/adapters/README.md.
Transactions
Every SQL-backed write and read can run on a transaction you own. withTransaction(tx)
returns a view of the engine bound to your transaction handle; the handle is opaque to
duck-auth and is handed straight back to your adapter.
const pending = await db.transaction(async (tx) => {
const auth = engine.withTransaction(tx)
await auth.identities.softDelete(identityId)
await auth.sessions.revokeAllForIdentity(identityId)
await tx.delete(users).where(eq(users.id, identityId))
return auth.pending
})
await pending.flush() // publish the events only once the commit landed
Nested calls inherit it: auth.flows.completeAccountDeletion() reaches
identities.softDelete, sessions.revokeAllForIdentity and credentials.delete, and all
three land on your transaction. Reads are bound too, so a read inside the transaction sees
that transaction's own uncommitted writes.
Events do not fire inside a transaction. They buffer in pending and publish when you
call flush(). A rolled-back delete therefore never appears in the audit trail as a
completed one. Call flush() after your commit; call pending.discard() if you rolled
back deliberately and want the buffer dropped. pending.peek() inspects the buffer without
draining it.
What is and isn't transactional
| Surface | In a transaction? | On rollback |
|---|---|---|
identities, sessions, credentials - writes and reads | yes | undone |
flows.*, including nested facet calls | yes | undone |
mfa, apiKeys, passwords credential writes | yes | undone |
orgs | interface ready; no shipped SQL adapter | n/a |
| events | buffered in pending | never published |
deliver calls (verification / reset mail) | no - sent immediately | mail already delivered |
limiter counters | no | token stays consumed |
hijack / anomaly scoring | no | scores stand |
The last two rows are guards: they decide whether to do the work, they write nothing to SQL,
and they are not reachable on the bound view at all - use engine.limiter,
engine.hijack and engine.anomaly outside the transaction. A flow that sends mail should be
called outside a transaction, or split so the send happens after the commit; no rollback
can retract a delivered email.
An engine with no transaction supplied behaves exactly as before: writes go to its own connection and events publish immediately.
Adapter support
withTransaction needs the adapter you passed as stores to implement withClient - one
call rebinds every facet, since they share its connection. The drizzle pg, mysql and sqlite
adapters do. Memory, redis and valkey do not - they cannot join a SQL transaction - and nor
can a bag you assembled facet by facet, so withTransaction throws AUTH_MISCONFIGURED
rather than silently leaving those writes outside your transaction.
Every mutating call answers with what it did
A write that returns void cannot be told apart from one that matched nothing, and forces a
second read for something the statement already had. Every mutating call returns the row,
the rows, or the count it touched. A single-row call that matched nothing rejects, and .orNull()
reads that as null; a bulk one answers [] or 0. Where the
dialect has RETURNING this is the same round trip.
const identity = await auth.identities.softDelete(id)
// `deletedAt` is when the grace window CLOSES, so the deadline you show the user
// comes off the write itself rather than a second reading of the clock.
identity.deletedAt // Date | null
identity.emailVerified // false - the address is free to be claimed meanwhile
const erased = await auth.identities.erase(id, { reason: 'gdpr' })
// The row as it was: after the delete there is nothing left to read.
const ended = await auth.sessions.revokeAllForIdentity(id)
const notice = `Signed out of ${ended.length} devices` // no second query; already read to emit events
| Surface | Calls | Answers with |
|---|---|---|
identities | softDelete, restore, erase, link, unlink | the row |
sessions | revoke, revokeByHash | the session ended |
sessions | revokeAllForIdentity | the sessions ended |
cfg.stores.credentials | revoke / revokeByKind, delete / deleteByKind | the row / the rows |
apiKeys | revoke / revokeAll | the key / the keys revoked |
passkeys | revoke / revokeAll | the passkey / the passkeys revoked, without the secret |
mfa | removeTotp, removeWebauthnMfa, removeBackupCodes | { removed } - the count, not the rows, which carry the secret |
orgs | removeMember, setRoles | the membership, with the sanitized role set actually stored |
flows | completeAccountDeletion, cancelAccountDeletion, completeEmailVerification, linkProvider, unlinkProvider | identity, alongside the fields they already returned |
webhooks | deliverOne | one Delivery per eligible endpoint |
pending | flush, discard | { published } / { discarded } |
anomaly | unregister | whether it removed anything |
Assertions (apiKeys.requireScopes), hijack.applyReaction, registrations (anomaly.register, providers.register) and
plugins.dispose stay void: they throw or they do not, and a return value would be noise.
Batch writes
Batch forms take a list and answer the rows they wrote:
const written = await auth.identities.updateProfileMany([
{ id: a, patch: { displayName: 'A' }, expectedVersion: 3 },
{ id: b, patch: { displayName: 'B' }, expectedVersion: 7 },
])
written.map((row) => row.id) // [a] when b lost its version race
Available on identities (softDeleteMany, restoreMany, eraseMany, updateProfileMany,
linkMany, unlinkMany) and sessions (revokeAllForIdentities, revokeByHashes). Each collapses to one
statement per table where the adapter can express it and loops otherwise, so every adapter
supports every batch form.
A hard failure - a constraint violation - throws and aborts your transaction, so one bad row rolls the whole batch back. A soft failure - a lost optimistic-lock race, a missing row - leaves that row out of the answer and does not throw.
Events
Each handler picks where it runs. An origin handler runs once, on the server that emitted, inside
that request's async context. A fleet handler, the default, runs on every server; on the others it
gets a copy of the payload and no request context.
import { redisEvents } from '@gentleduck/auth/adapters/redis'
const auth = createAuth({ events: redisEvents({ redis }) /* ... */ })
// A write that must happen once: origin.
auth.events.on('session.revoked', (e) => auditLog.write(e), { delivery: 'origin' })
// State every server keeps: fleet.
auth.events.on('authz.revoked', ({ identityId }) => decisionCache.drop(identityId))
fleet handlers need redisEvents once there is more than one server, since the in-process default
runs them on one. In production strict() refuses the in-process bus while it holds a fleet
handler, and passes it when every handler is origin. It sees only the handlers registered before it
runs, so call it after every on() and use(). Webhooks go out as origin, once per emit.
Server adapters
duck-auth ships no routes and no client. Your app writes its own routes over auth.flows.* and calls them
with its own fetch. Each adapter carries only the glue: a CSRF guard, the caller's address and user agent,
an intents writer, the actor context and the error mapping.
import { AuthError } from '@gentleduck/auth/core'
import { applyIntents, expressCaller, expressCsrf, toHeaders } from '@gentleduck/auth/server/express'
import { errorToHttp } from '@gentleduck/auth/server/generic'
app.use('/auth', expressCsrf(auth))
app.post('/auth/signin', async (req, res) => {
const { providerId, input } = req.body ?? {}
if (typeof providerId !== 'string') throw new AuthError('AUTH_INVALID_PARAMETERS')
const headers = toHeaders(req.headers)
const { intents } = await auth.flows.signIn({
input,
providerId,
...expressCaller(req),
previousSid: auth.transport.extract({ headers }) ?? undefined,
})
applyIntents(intents, res)
})
app.post('/auth/signout', async (req, res) => {
const sid = auth.transport.extract({ headers: toHeaders(req.headers) })
applyIntents(sid ? (await auth.flows.signOut(sid)).intents : auth.transport.revoke(), res)
})
// A refusal throws an AuthError; `errorToHttp` maps it to the status and body
app.use((err, _req, res, _next) => {
const { status, body } = errorToHttp(err)
res.status(status).json(body)
})
| Framework | Import | Glue |
|---|---|---|
| Express | @gentleduck/auth/server/express | expressCsrf, expressCaller, applyIntents, expressActorContext |
| Hono | @gentleduck/auth/server/hono | honoCsrf, honoCaller, honoActorContext |
| Fastify | @gentleduck/auth/server/fastify | fastifyCsrf, fastifyCaller, fastifyWithActor |
| Koa | @gentleduck/auth/server/koa | koaCsrf, koaCaller, koaApplyIntents, koaActorContext |
| NestJS | @gentleduck/auth/server/nestjs | makeCsrfGuard, makeGuard, nestCaller, NestExceptionFilter, CurrentSession |
| Elysia | @gentleduck/auth/server/elysia | elysiaCsrf, elysiaCaller, elysiaWithActor |
| Next.js | @gentleduck/auth/server/next | withNextCsrf, nextCaller, nextWithActor |
| gRPC | @gentleduck/auth/server/grpc | withGrpc |
| Web Fetch | @gentleduck/auth/server/generic | executeIntents, jsonResponse, errorResponse, errorToHttp, readBodyJson |
What your routes now own:
- CSRF on sign-in, sign-out, provider begin and every other mutation.
- The OAuth callback stays unguarded. Apple posts it cross-site by design and the signed state is the
proof. Read the query on a GET, the urlencoded body on a POST, and pass
cookieHeaderandpreviousSid. csrfHashout of any session you answer with. It is server-side state; the browser holds the plaintext.- The session passed to every factor change. Adding, removing or replacing a factor, minting backup codes
and remembering a device take the caller's session, and refuse one below AAL 2 once the account holds any
factor beside the password. Rate-limit any TOTP verification of your own on
stepup:${identityId}. - The session's tenant passed to
auth.mfa.*, which without one reaches only the factors with no tenant. - The request's tenant, in a multi-tenant app, named on the actor scope (
tenantId: (req) => ...) and onresolveSession. Without it a session in a tenant resolves as nobody.
examples/duck-auth has the full route set for all eight frameworks.
Delivery
Every outbound token - magic link, email verification, password reset, account deletion and its undo
link - goes to one deliver callback on the engine config. The library signs the URL and hands over the
recipient's identity, the template vars and the tenant; the host picks the transport and writes the
template. Every message's vars has the signed url and its lifetime ttlMin; switching on kind narrows
them further (requiresMfa on a password reset, restorableUntil on the undo link). Throw from it to report a failure: the flow answers the caller the same either way and reports
the refusal as a signin.failed event, never the thrown text.
const auth = createAuth({
baseUrl: 'https://app.example.com',
deliver: async ({ identity, kind, vars }) => {
if (kind === 'magic-link') return mailer.send(identity.profile.email, signInTemplate(vars.url))
await mailer.send(identity.profile.email, genericTemplate(kind, vars))
},
// ...
})
Captcha verifiers
import {
authTurnstileVerifier,
authHCaptchaVerifier,
authRecaptchaV3Verifier,
} from '@gentleduck/auth/core'
Tooling
| Path | What |
|---|---|
@gentleduck/auth/oidc | OIDC discovery-doc + JWKS helper |
@gentleduck/auth/oidc/op | Full OAuth2/OIDC OP: /authorize (code + S256 PKCE), /token (auth_code + refresh, family-rotated), /userinfo, /introspect, /revoke, /register (RFC 7591 Dynamic Client Registration) |
@gentleduck/auth/oidc/op/drizzle/pg | Postgres Drizzle stores for the OIDC OP (5 tables, GC helper) |
@gentleduck/auth/oidc/op/drizzle/sqlite | SQLite Drizzle stores for the OIDC OP |
@gentleduck/auth/oidc/op/drizzle/mysql | MySQL Drizzle stores for the OIDC OP |
Production primitives
AuthEngine.strict()- boot-time validation wheneverNODE_ENVis notdevelopmentortest, unset included: rejectsNoopLimiter, memory stores, missinglockoutlistener, non-HTTPSbaseUrlJwtTransport.rotateSignKey()+retireVerifyKey(kid)- zero-downtime JWKS rotation with overlap windowapplyCompliancePreset(cfg, 'gdpr' | 'hipaa' | 'soc2' | 'fips')- a free function over the config, not an engine method: it ratchets the three session TTLs down to the named floor. The password, MFA and api-key floors are provider-level - pass the same preset topasswords({ compliance })and its siblings - andstrict()enforces the rest, including data-at-restWebhookDeliverer- HMAC body + timestamp + freshness tolerance, exponential backoff, dead-letter sink, SSRF guard on endpoint URLs,redirect: 'error'on dispatchauth.hijack+auth.anomaly- drift detection, decision ladder (allow / step-up / deny), pluggable signalsredisIdempotency/valkeyIdempotency- per-(identity, key) tombstone + poll for the host's replay-safe mutating routes; the host holds it, the engine does not- DPoP (RFC 9449) - proof-of-possession on bearer tokens with
athbinding and server nonce - Tenant boundary: a call naming no tenant reaches only the records with no tenant and
ALL_TENANTSevery tenant's; a session or API key resolves only in its own tenant
Security posture
AuthEngine.strict() runs every production-grade gate before boot.
See SECURITY.md for the STRIDE / OWASP ASVS mapping of every threat the library mitigates and every threat the host app must own.
Module sizes (gzipped)
| Module | Size |
|---|---|
Core AuthEngine (typical import) | ~22 KB |
| Each transport | 2 - 6 KB |
| Each provider | 1.5 - 8 KB |
| Each adapter | 2 - 9 KB |
| Each server middleware | 2 - 4 KB |
Real deployments importing only what they wire end up at 25 - 60 KB total. The "import everything" worst case (import * from '@gentleduck/auth') is not the intended usage.
Docs
- Site: gentleduck.org/duck-auth
- Reference app:
apps/duck-auth-demo- every flow exercised end-to-end - Sibling repos:
@gentleduck/iam,@gentleduck/ui,@gentleduck/upload,@gentleduck/md
Contributing
PR checklist + style notes in the repo's CONTRIBUTING.md.
Security disclosures: SECURITY.md.
License
MIT. See LICENSE.