@gentleduck/auth

中文文档
5.18.0发布于 2026/10/27MITTypeScriptESM + CJS近 30 天下载 3782

Authentication for modern TypeScript apps. Faceted, framework-agnostic, transport-pluggable. Pairs with @gentleduck/iam.

原始使用文档
文档目录23 节
  1. Install
  2. Quick start
  3. Architecture
  4. Providers
  5. Transports
  6. Storage adapters
  7. What a call costs
  8. Transactions
  9. What is and isn't transactional
  10. Adapter support
  11. Every mutating call answers with what it did
  12. Batch writes
  13. Events
  14. Server adapters
  15. Delivery
  16. Captcha verifiers
  17. Tooling
  18. Production primitives
  19. Security posture
  20. Module sizes (gzipped)
  21. Docs
  22. Contributing
  23. License

@gentleduck/auth

@gentleduck/auth

Faceted, framework-agnostic, transport-pluggable authentication for TypeScript. Pairs with @gentleduck/iam for authorization.

MIT - Changelog - Security - Docs

npm downloads MIT


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:

PackageWhen you need it
@node-rs/argon2Argon2id password hashing (FIPS / HIPAA presets)
@simplewebauthn/serverPasskey / WebAuthn-MFA
@aws-sdk/client-kmsAWS KMS envelope encryption at rest
drizzle-orm + pg, mysql2 or better-sqlite3Drizzle adapter (pg / mysql / sqlite)
ioredis or @upstash/redisRedis-backed session / idempotency / limiter / events / DPoP-nonce stores
@node-saml/node-samlSAML 2.0 SP
@nestjs/commonNestJS 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.

FacetOwns
identitiesprofile CRUD, link/unlink, soft-delete + grace-period restore, GDPR export, bulk import
sessionsrotateOrCreate (single privilege-changing API), getBySid, revoke, revokeAllForIdentity, gc
credentialspassword / api-key / oauth / passkey / recovery / totp / webauthn-mfa rows; CAS rotation
passwordsstrength + cap validation, constant-time verify, needsRehash + auto-rehash, common-list reject
passkeyslist / revoke / revokeAll, scoped to the identity that holds them
mfaTOTP enrollment + verify, backup-code mint/verify, WebAuthn-MFA
apiKeysmint / list / rotate / revoke / revokeAll / verify + scope checks, tenant-bound issuance
flowssignIn / signOut / signUp (multi-stage) / password-reset / email-verification / account-deletion / linkProvider / unlinkProvider / impersonate / step-up / step-down
csrfdouble-submit + origin-only + sec-fetch-site gates, __Host- cookie
webhooksHMAC + timestamp + tolerance, retry w/ backoff, dead-letter, SSRF-guarded URLs
eventstyped bus, lockout / signin.success / signin.failed / suspicious / session.revoked / mfa.removed
hijackIP / UA drift detection + step-up / rotate / revoke reaction policy
anomalypluggable detectors (impossible-travel, device-fingerprint), composition + decision ladder
orgsorg + 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

PathWhat
@gentleduck/auth/providers/passwordsEmail + password
@gentleduck/auth/providers/magic-linkPasswordless one-time link
@gentleduck/auth/providers/passkeyWebAuthn passkey (lazy peerDep on @simplewebauthn/server)
@gentleduck/auth/providers/api-keyLong-lived bearer keys via ApiKeysFacet
@gentleduck/auth/providers/oauth/googleGoogle OAuth (PKCE + nonce)
@gentleduck/auth/providers/oauth/githubGitHub OAuth (PKCE + state)
@gentleduck/auth/providers/oauth/microsoftMicrosoft / Entra ID OAuth
@gentleduck/auth/providers/oauth/discordDiscord OAuth
@gentleduck/auth/providers/oauth/linkedinLinkedIn OAuth
@gentleduck/auth/providers/oauth/appleSign in with Apple
@gentleduck/auth/providers/oauth/coreAny other OAuth 2.0 / OIDC IdP: oProvider over an OAuthClient
@gentleduck/auth/providers/samlWrapper 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:

callMemorySQLitePostgresMySQL
find({ id })3 µs0.089 ms0.280 ms0.255 ms
find({ email })7 µs0.090 ms0.299 ms0.259 ms
find({ providerId, providerSub })8 µs0.112 ms0.383 ms0.282 ms
create (2 logins)2.125 ms0.632 ms0.650 ms1.184 ms
erase3 µs0.543 ms0.499 ms1.348 ms
link0.630 ms0.454 ms0.549 ms1.404 ms
patchMetadata4 µs0.282 ms0.271 ms0.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

SurfaceIn a transaction?On rollback
identities, sessions, credentials - writes and readsyesundone
flows.*, including nested facet callsyesundone
mfa, apiKeys, passwords credential writesyesundone
orgsinterface ready; no shipped SQL adaptern/a
eventsbuffered in pendingnever published
deliver calls (verification / reset mail)no - sent immediatelymail already delivered
limiter countersnotoken stays consumed
hijack / anomaly scoringnoscores 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
SurfaceCallsAnswers with
identitiessoftDelete, restore, erase, link, unlinkthe row
sessionsrevoke, revokeByHashthe session ended
sessionsrevokeAllForIdentitythe sessions ended
cfg.stores.credentialsrevoke / revokeByKind, delete / deleteByKindthe row / the rows
apiKeysrevoke / revokeAllthe key / the keys revoked
passkeysrevoke / revokeAllthe passkey / the passkeys revoked, without the secret
mfaremoveTotp, removeWebauthnMfa, removeBackupCodes{ removed } - the count, not the rows, which carry the secret
orgsremoveMember, setRolesthe membership, with the sanitized role set actually stored
flowscompleteAccountDeletion, cancelAccountDeletion, completeEmailVerification, linkProvider, unlinkProvideridentity, alongside the fields they already returned
webhooksdeliverOneone Delivery per eligible endpoint
pendingflush, discard{ published } / { discarded }
anomalyunregisterwhether 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)
})
FrameworkImportGlue
Express@gentleduck/auth/server/expressexpressCsrf, expressCaller, applyIntents, expressActorContext
Hono@gentleduck/auth/server/honohonoCsrf, honoCaller, honoActorContext
Fastify@gentleduck/auth/server/fastifyfastifyCsrf, fastifyCaller, fastifyWithActor
Koa@gentleduck/auth/server/koakoaCsrf, koaCaller, koaApplyIntents, koaActorContext
NestJS@gentleduck/auth/server/nestjsmakeCsrfGuard, makeGuard, nestCaller, NestExceptionFilter, CurrentSession
Elysia@gentleduck/auth/server/elysiaelysiaCsrf, elysiaCaller, elysiaWithActor
Next.js@gentleduck/auth/server/nextwithNextCsrf, nextCaller, nextWithActor
gRPC@gentleduck/auth/server/grpcwithGrpc
Web Fetch@gentleduck/auth/server/genericexecuteIntents, 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 cookieHeader and previousSid.
  • csrfHash out 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 on resolveSession. 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

PathWhat
@gentleduck/auth/oidcOIDC discovery-doc + JWKS helper
@gentleduck/auth/oidc/opFull 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/pgPostgres Drizzle stores for the OIDC OP (5 tables, GC helper)
@gentleduck/auth/oidc/op/drizzle/sqliteSQLite Drizzle stores for the OIDC OP
@gentleduck/auth/oidc/op/drizzle/mysqlMySQL Drizzle stores for the OIDC OP

Production primitives

  • AuthEngine.strict() - boot-time validation whenever NODE_ENV is not development or test, unset included: rejects NoopLimiter, memory stores, missing lockout listener, non-HTTPS baseUrl
  • JwtTransport.rotateSignKey() + retireVerifyKey(kid) - zero-downtime JWKS rotation with overlap window
  • applyCompliancePreset(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 to passwords({ compliance }) and its siblings - and strict() enforces the rest, including data-at-rest
  • WebhookDeliverer - HMAC body + timestamp + freshness tolerance, exponential backoff, dead-letter sink, SSRF guard on endpoint URLs, redirect: 'error' on dispatch
  • auth.hijack + auth.anomaly - drift detection, decision ladder (allow / step-up / deny), pluggable signals
  • redisIdempotency / 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 ath binding and server nonce
  • Tenant boundary: a call naming no tenant reaches only the records with no tenant and ALL_TENANTS every 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)

ModuleSize
Core AuthEngine (typical import)~22 KB
Each transport2 - 6 KB
Each provider1.5 - 8 KB
Each adapter2 - 9 KB
Each server middleware2 - 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

Contributing

PR checklist + style notes in the repo's CONTRIBUTING.md. Security disclosures: SECURITY.md.

License

MIT. See LICENSE.

版本与发布记录

@gentleduck/auth 共发布 31 个版本,首次发布于 2026/05/29;过去 12 个月发布了 31 个版本。

版本发布日期距今
5.18.0latest2026/10/2719 天前
5.17.02026/10/2323 天前
5.16.02026/09/301 个月前
5.14.02026/09/291 个月前
5.13.02026/09/201 个月前
5.12.02026/09/191 个月前

关于 @gentleduck/auth 的常见问题

@gentleduck/auth 是什么?

Authentication for modern TypeScript apps. Faceted, framework-agnostic, transport-pluggable. Pairs with @gentleduck/iam.

如何安装 @gentleduck/auth?

在项目目录运行 npm install @gentleduck/auth,或使用 pnpm add / yarn add / bun add。

@gentleduck/auth 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@gentleduck/auth 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@gentleduck/auth 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=22.0.0。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@gentleduck/auth 可以商用吗?

@gentleduck/auth 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@gentleduck/auth 的下载量有多少?

根据 npm 官方下载统计,@gentleduck/auth 在 2026/10/16 – 2026/11/14 这 30 天内被下载 3,782 次,日均约 126 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@gentleduck/auth 还在维护吗?

最新版本 5.18.0 发布于 2026/10/27(19 天前);至今共发布 31 个版本,其中过去 12 个月发布了 31 个;首次发布于 2026/05/29。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。