@activescott/auth

中文文档
5.9.0发布于 2026/10/19MITTypeScriptES Module构建来源已验证近 30 天下载 9347

Framework-agnostic authentication with provider pattern for magic links, OAuth, and more

原始使用文档
文档目录19 节
  1. Why direct, passwordless authentication?
  2. Features
  3. Documentation & example
  4. Install
  5. What's in the box
  6. Data model
  7. Minimal shape
  8. Session cache
  9. ChallengeStore
  10. Abuse protection
  11. A blocked caller sees a success
  12. Tuning
  13. Form token
  14. Hosted bot checks
  15. Initiate gate
  16. Admin subpath
  17. Logging
  18. Waitlist
  19. License

@activescott/auth

npm version License: MIT

Framework-agnostic direct authentication, deliberately small: single-use magic links and one-time codes via email and SMS, and passkeys (WebAuthn). No third-party identity providers. Runs on Node and edge runtimes (e.g. Cloudflare Workers).

This package is the core: the Auth class, JWT-cookie session management, and the provider/store interfaces. It does not handle any specific authentication method by itself — pair it with one or more provider packages and (optionally) a framework adapter:

Used in production by ramblefeed.com and tinkerbellbot.com.

Why direct, passwordless authentication?

Everyone has an email address or a phone number. Nobody wants another password. And many users hesitate at "Sign in with Google/Apple/Microsoft" because it shares their sign-in activity with a third party. This library focuses on the ways a person can authenticate directly with your app:

  • Lowest friction for your users. No password to create, forget, or reset, and no account with a third party required. Modern platforms AutoFill the codes we send, so signing in is: type your email, type the code your OS offers you.
  • Easiest for you. No OAuth app registrations, no identity-provider dashboards, no extra services. An SMTP server and your database are the only dependencies.
  • Private by design. No third-party identity provider in the loop — big tech doesn't learn when (or that) your users sign in to your app.
  • Deliberately small. This is not a works-with-every-OAuth-provider auth library — that niche is well served by projects like BetterAuth. Constraining the scope is what keeps this one easy to drop into a new app.

Passkeys push the same idea further: phishing-resistant, no shared secret, and still no third party.

Features

  • ✅ Email magic links — single-use, server-backed sign-in links with a confirm step that email security scanners can't consume (see the FAQ). In production.
  • ✅ Email one-time codes — every sign-in email also includes a numeric code with iOS/macOS AutoFill support, so users can type the code instead of switching to the inbox tab.
  • ✅ Bring your own database — three small store interfaces (IdentityStore, UserStore, ChallengeStore); implement them with Prisma, Drizzle, raw SQL, Redis, whatever you use.
  • ✅ Edge-ready, WinterTC-compatible core — standard Fetch Request/Response, WebCrypto, and jose for session JWTs; no Node-only APIs, so it runs on Cloudflare Workers, Deno, Bun, and any WinterTC-aligned runtime.
  • ✅ React Router v8 adapter — createAuthHandlers, requireAuth, optionalAuth, getSession, logout.
  • ✅ SMS one-time codes — vendor-neutral provider with a Twilio Messaging transport (RCS-ready) and WebOTP autofill support.
  • ✅ Hosted verification (no US A2P 10DLC) — the same SMS provider accepts a VerificationTransport where the vendor generates, sends, and checks the code. TwilioVerifyTransport ships in the Twilio package: no number to buy, no brand or campaign registration — at the cost of ~4–6x per sign-in.
  • ✅ Abuse protection, on by default — per-IP and per-recipient rate limits, a minimum-form-fill-time check, blocked attempts logged, and a blocked caller gets the same response a successful send would produce. Optional packages add hosted bot checks (Turnstile).
  • ✅ Passkeys (WebAuthn) — add a passkey while signed in, then sign in usernameless with Touch ID, Face ID, Windows Hello, 1Password, iCloud Keychain, or a security key; conditional UI (passkey autofill) supported. Verification via @simplewebauthn/server; zero-dependency browser client included.

The provider interface (AuthProvider) is the extension point. Implementing a new provider does not require changes to this core package.

Documentation & example

Full docs — quick start, architecture diagram, custom-provider guide, e2e-testing pattern, FAQ — and a runnable React Router framework-mode example with Playwright tests live in the monorepo:

→ https://github.com/activescott/auth**

The rest of this README covers what this core package itself exports and expects.

Install

npm install @activescott/auth

What's in the box

ExportPurpose
AuthOrchestrator. Routes auth requests to providers, manages session cookies.
SessionManagerStandalone JWT session signer/verifier (rarely needed directly).
AuthProviderInterface every provider implements (initiate, verify, canHandle, optional handleAction for extra endpoints).
IdentityStore, UserStoreInterfaces you implement to plug in your database.
ChallengeStore, InMemoryChallengeStoreStorage for short-lived, single-use challenges (see below).
AbuseConfig, RateLimitStore, InMemoryRateLimitStoreAbuse protection for the initiate endpoints — on by default (see below).
InitiateGateYour own policy on who may start a sign-in or link (see below).
createWaitlist, waitlistNotificationEmailWaitlist with admin approval, built on the gate's onVerified (see below).
BotCheckProvider, createFormToken, FORM_TOKEN_FIELDBot-check interface and the login form's anti-bot fields.
generateOtpCode, hashOtpCode, verifyOtpCodeOne-time-code utilities used by OTP-capable providers.
AuthUser, Identity, Session, AuthResult, AuthInitResultCore data types.
AuthErrors, getAuthErrorMessage, AUTH_ERROR_CODESStructured error helpers.

Plus the @activescott/auth/admin subpath: admin dashboard data and the admin allowlist check (see Admin subpath).

Data model

You bring three adapters — IdentityStore, UserStore, and ChallengeStore — that read/write your database. The library handles challenges, cookies, provider routing, and session verification.

An Identity is a (provider, identifier) pair (e.g. ("email", "[email protected]")) linked to one of your User records. One user can have multiple identities — email, phone, and passkeys all use the same table.

Identity.metadata is provider-owned state, opaque to your application: persist it unmodified (a JSON/JSONB column) and return it exactly as stored. Providers with per-identity state keep it there — the passkey provider stores each credential's public key and signature counter — and stateless providers store {}. It may contain sensitive material, so protect it like credential data (encryption at rest is a reasonable default). IdentityStore.update(id, {metadata, verifiedAt}) replaces stored metadata wholesale; providers rely on it, so it is a required method.

Minimal shape

import { Auth, InMemoryChallengeStore } from "@activescott/auth"
import { EmailProvider } from "@activescott/auth-provider-email"

const auth = new Auth({
  session: {
    secret: process.env.JWT_SECRET!,
    maxAge: "30d",
    cookieName: "session",
    cookie: { secure: true, sameSite: "lax", path: "/" },
  },
  identityStore, // your impl
  userStore, // your impl
  challengeStore: new InMemoryChallengeStore(), // DB-backed in production
  providers: [new EmailProvider({ ... })],
})

Then call auth.handleRequest(request) from your framework's routing layer (or use a framework adapter), and auth.verifySession(request) to check the session cookie on protected routes.

Session cache

verifySession keeps each verified session in memory for two minutes, so a page whose loaders each ask who is signed in costs one pair of store reads instead of one per loader. What you pay for it is staleness: for up to two minutes after you block or delete someone, their requests still verify.

session.cacheTtlMs is that window in milliseconds, and 0 turns the cache off so every request reads your stores:

session: {
  secret: process.env.JWT_SECRET!,
  maxAge: "30d",
  cookieName: "session",
  cookie: { secure: true, sameSite: "lax", path: "/" },
  cacheTtlMs: 0, // block a user, and their next request is signed out
}

With the cache on, it holds at most 10,000 sessions and evicts the oldest past that, so a burst of sign-ins between sweeps cannot grow it without limit. Nothing is shared between instances: an entry is only ever a repeat of what that process's stores just said.

ChallengeStore

Every sign-in attempt is backed by a server-side challenge: magic links and one-time codes store the hashed secret, an attempt counter, and an expiry; passkey ceremonies record the WebAuthn challenge so it is redeemable exactly once. That state lives in the challengeStore, which is why it is a required part of the Auth config.

InMemoryChallengeStore is right for a single server process (and dev/examples). Challenges are lost on restart and not shared across instances — for multi-instance deployments implement the four-method ChallengeStore interface against shared storage. A SQL implementation is roughly:

CREATE TABLE challenges (
  id TEXT PRIMARY KEY,
  type TEXT NOT NULL,
  identifier TEXT NOT NULL,
  hashed_code TEXT,
  data JSONB,
  attempts INT NOT NULL DEFAULT 0,
  max_attempts INT NOT NULL,
  created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
  expires_at TIMESTAMPTZ NOT NULL
);

with incrementAttempts as UPDATE challenges SET attempts = attempts + 1 WHERE id = $1 RETURNING attempts (the increment must be atomic — it enforces the guess limit), and a periodic DELETE ... WHERE expires_at < now().

Abuse protection

The initiate endpoints send mail and texts to whatever address a caller submits, which makes them an attractive way to mail-bomb a third party or burn your sending reputation on bounces. Protection is on by default — you do not have to configure or implement anything:

LayerDefault
Per client IP3 per minute, then 10 per hour
Per recipient3 per hour, then 10 per day
Minimum form-fill time2 seconds (only enforced if the form posts a token, below)
Counter storageInMemoryRateLimitStore
Blocked responseidentical to a successful send

Blocked attempts are always logged (console.warn) with the reason, provider, IP, requested identifier, and rule, so an abuse burst is visible:

[auth] blocked initiate: reason=identifier_rate_limited provider=email ip=203.0.113.7 [email protected] rule=3/3600s retryAfter=2841s

A blocked caller sees a success

By design a throttled or bot-flagged request gets exactly the response a real send would produce — the same 302 back to ?sent=1, or the same {success: true, message} — minus the challenge cookie. Nothing is sent and nothing is stored. This is what keeps a bot from mapping which addresses or IPs are throttled. If you would rather return 429 RATE_LIMITED (reasonable for an API-only deployment), set abuse.respondWith: "rateLimited".

One block is answered differently in both modes: a bot check reporting incomplete (a hosted widget that had not issued its token yet when the form was submitted) gets BOT_CHECK_INCOMPLETE, as a 302 back with ?error=BOT_CHECK_INCOMPLETE or a 400. That verdict comes from the request alone, never from the identifier, so it tells the caller nothing they did not send, and it lets a real user on a slow connection know to try again. It is still logged and passed to onBlocked as bot_check_failed.

Tuning

const auth = new Auth({
  // ...
  abuse: {
    perIp: [
      { windowSeconds: 60, max: 3 },
      { windowSeconds: 3600, max: 10 },
    ],
    perIdentifier: [{ windowSeconds: 3600, max: 3 }],
    store: myRedisRateLimitStore, // multi-instance: share the counters
    onBlocked: (event) => logger.warn(event, "auth abuse blocked"),
  },
})

abuse: { enabled: false } turns everything off.

InMemoryRateLimitStore counts per process, so a multi-instance deployment effectively multiplies every limit by the instance count. Implement the one-method RateLimitStore interface against Redis (INCR + EXPIRE) or your database to share counters.

Client IPs come from cf-connecting-ip, then x-forwarded-for (rightmost hop; set abuse.clientIp.trustedProxyHops if more than one proxy appends), then x-real-ip. These headers are spoofable unless a proxy in front of your app rewrites them — supply abuse.clientIp.getClientIp when your runtime exposes the peer address. When no IP can be determined, per-IP limits are skipped and per-recipient limits still apply.

Form token

The minimum-form-fill-time check needs one hidden field in your login form:

import { createFormToken, FORM_TOKEN_FIELD } from "@activescott/auth"

// in the route/loader that renders the form:
const formToken = await createFormToken(process.env.JWT_SECRET!)
<input type="hidden" name="authFormToken" value="{formToken}" />

The token is a signed render timestamp; the server rejects submissions that arrive faster than minFormFillSeconds. It must be signed — an unsigned timestamp is just another field to forge. A submission with no token is allowed, so adding the field is optional and can be rolled out later. A token older than a day is also allowed rather than rejected — a login page left open in a tab is a human.

Hosted bot checks

Cloudflare Turnstile, hCaptcha, and friends live in their own packages, so you only install the vendor you use:

import { TurnstileBotCheck } from "@activescott/auth-botcheck-turnstile"

abuse: {
  botChecks: [new TurnstileBotCheck({ secretKey: process.env.TURNSTILE_SECRET_KEY! })],
}

Implement BotCheckProvider ({ id, verify({ request, body, ip, providerId }) }) to add your own.

Initiate gate

An invite-only beta, an allowlist, or a blocked domain is a rule about who may be sent a sign-in message. Put it in gate.onInitiate rather than in a preamble in your auth route:

const auth = new Auth({
  // ...
  gate: {
    async onInitiate({ provider, identifier, mode, request }) {
      if (mode === "link") return "allow" // already signed in
      if (await invites.has(provider, identifier)) return "allow"
      return { redirect: "/waitlist" }
    },
  },
})

The gate runs inside handleRequest, after the provider has parsed, normalized, and validated the identifier ([email protected] arrives as [email protected], a phone number as E.164) and before anything is created or sent. A malformed identifier is rejected by the provider first, so the gate never acts on one. mode is "signin" or "link" (see linking identities); request is a clone of the initiate request, for headers or cookies.

Return one of:

  • "allow" — send as usual.
  • { redirect: "/waitlist" } — send nothing and answer with a 302 to that URL, for every caller.
  • { error: AuthErrors.invalidCredentials({ reason: "Invite only" }) } — send nothing and fail like any other initiate: a browser form post goes back to the submitting page with ?error=<code>, a fetch caller gets the error as JSON.

A gate that throws fails the initiate. Per-IP and per-recipient abuse limits run before the gate, so a throttled request still gets the silent "sent" answer.

Anyone can start a sign-in for an address they do not own, so a rule that writes something or tells someone about the identifier belongs in the optional gate.onVerified instead. It runs after the provider has verified the identifier and before the session is created, with the same provider, identifier, mode, and request (the verify request), plus the user and identity the verify resolved and isNewUser. It returns the same decisions: "allow" creates the session, { redirect } answers with a 302 and no session, { error } fails the verify like a bad code. It sees email and SMS verifies; passkey sign-ins skip it.

The built-in email and SMS providers consult the gate. With gate set, new Auth throws if any provider that serves an initiate route does not declare consultsInitiateGate: true — an older provider package would otherwise skip your policy without a trace. A custom provider opts in by calling context.gate?.check({ provider, identifier, mode }) once its identifier is valid, returning the result when there is one, and setting consultsInitiateGate = true.

Admin subpath

@activescott/auth/admin is what the admin dashboard is built from, with no framework in it:

ExportPurpose
createAdminData(auth){ listUsers, describeConfig } over your stores, as plain serializable rows.
createAdminPredicate(admins)Builds the allowlist check from a delimited string, an array, or your own predicate.
isAdminUser(auth, user)Answers that check for one user against AUTH_ADMIN_IDENTIFIERS.

The allowlist is email addresses and E.164 phone numbers, separated by commas or whitespace, matched against every identity a user owns. An allowlisted address therefore admits its owner even when they signed in by SMS. An empty or missing allowlist admits nobody.

import { isAdminUser } from "@activescott/auth/admin"

const session = await auth.verifySession(request)
if (!session || !(await isAdminUser(auth, session.user))) {
  return new Response("Not Found", { status: 404 })
}

isAdminUser reads the environment allowlist and loads the user's identities on each call. When the list comes from somewhere else, build the check with createAdminPredicate(admins) and hand it the user's identities yourself (identityStore.findByUserId(user.id)). The React Router adapter's dashboard uses these, so a page you gate yourself and the dashboard agree on who is an admin.

Logging

Redirect destinations reach the library from ?redirectTo=, form fields, and the Referer header. One that names another origin or another scheme is declined and a configured path is used instead, which is otherwise invisible to your app: a stale link or a proxy rewriting Referer shows up only as users landing somewhere unexpected. Give the library somewhere to say so:

const auth = new Auth({
  // ...
  logger: console, // or { warn: (message, context) => log.warn(context, message) }
})

Each declined destination logs one WARN naming the parameter it came from and that value's origin. The value itself is never logged, because a magic-link URL carries a single-use key in its query:

[auth] redirect destination declined, using fallback { source: 'redirectTo', fallback: '/', reason: 'other-origin', origin: 'https://other.example' }

logger is optional and nothing is logged through it when it is absent. Providers receive it as AuthContext.logger, and framework adapters read it off the Auth instance (auth.getLogger()), so configuring it here covers the whole flow. Abuse blocks are separate: those always go to console.warn, plus abuse.onBlocked if you set it.

Waitlist

createWaitlist is a gate for apps that approve new users by hand. Everyone gets a code. Once they verify it, a user without an approved account becomes PENDING and lands on your waitlist page with no session; admins hear about it through notify; an admin approves or blocks from the dashboard. Approved users sign in as usual.

The status lives in your database, behind an ApprovalStore. Its values, "PENDING" | "APPROVED" | "BLOCKED", match the enum apps usually already have:

import {
  createWaitlist,
  waitlistApprovalEmail,
  waitlistNotificationEmail,
} from "@activescott/auth"

const emailOptions = {
  appName: "Fernfiles",
  domain: "fernfiles.com",
  from: "[email protected]",
}

export const waitlist = createWaitlist({
  // Only needed so onApproved below can look up an address to email
  identityStore,
  approvalStore: {
    getApprovalStatus: async (userId) =>
      (await db.user.findUnique({ where: { id: userId } }))?.approvalStatus ??
      null,
    setApprovalStatus: async (userId, approvalStatus) => {
      await db.user.update({ where: { id: userId }, data: { approvalStatus } })
    },
  },
  waitlistUrl: "/waitlist",
  blockedUrl: "/login?error=blocked", // defaults to waitlistUrl
  // App rules that skip the waitlist. Never consulted for BLOCKED users.
  autoApprove: ({ identifier }) => autoApproved.has(identifier),
  notify: (notice) =>
    transporter.sendMail({
      ...waitlistNotificationEmail(notice, emailOptions),
      to: adminEmails,
    }),
  // Tell the user when an admin approves them
  onApproved: ({ identities }) => {
    const to = identities.find((i) => i.provider === "email")?.identifier
    if (to) {
      return transporter.sendMail({
        ...waitlistApprovalEmail(emailOptions),
        to,
      })
    }
  },
  logger: console,
})

const auth = new Auth({ /* ... */ gate: waitlist })

The waitlist acts only after verification, so starting a sign-in for someone else's address creates no user and sends admins nothing. The verify step creates the user as it would without a waitlist; the waitlist then records their status. notify fires once when a user joins the waitlist (reason: "waitlisted") and whenever autoApprove lets someone in (reason: "auto-approved"); a throw there is logged and does not fail the sign-in. The email is plain and generic on purpose: app name, domain, sender, and a link to /admin/users (adminPath changes it). Sending it is yours, so the core takes no mail dependency.

onApproved fires when an admin approves a user who was not already approved, through approve or handleAdminAction, with the user's identities so you can pick an address (an SMS-only user has no email identity). It does not fire for autoApprove, whose user is already signing in. waitlistApprovalEmail renders the message, linking to /login (signInPath changes it). A throw is logged and the approval stands.

A user with no recorded status counts as not approved. Mark existing users APPROVED before turning the waitlist on.

The gate only sees email and SMS sign-ins, and only when they verify. Passkey sign-ins and a user you block after they signed in need a per-request check; waitlist.redirectFor(userId) returns null for approved users and the URL to send anyone else to. With the React Router adapter:

createAuthHandlers(auth, {
  // ...
  onSessionVerified: async ({ user }, request) => {
    const to = await waitlist.redirectFor(user.id)
    if (to) return logout(request, to)
  },
})

For the dashboard, render approve and block buttons in AdminUsersPage's rowActions as forms posting userId and intent ("approve" or "block") to your admin route, and in that route's action call waitlist.handleAdminAction(await request.formData()) after checking the caller is an admin. waitlist.approve(userId) and waitlist.block(userId) do the same from your own code. The form has no CSRF token of its own; it relies on the session cookie being SameSite=Lax or stricter, as the example configures. The example app has the whole flow.

License

MIT

版本与发布记录

@activescott/auth 共发布 22 个版本,首次发布于 2026/03/17;过去 12 个月发布了 22 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
5.9.0latest2026/10/1918 天前
5.8.02026/10/1126 天前
5.7.02026/09/301 个月前
5.6.12026/09/291 个月前
5.6.02026/09/201 个月前
5.5.02026/09/201 个月前

关于 @activescott/auth 的常见问题

@activescott/auth 是什么?

Framework-agnostic authentication with provider pattern for magic links, OAuth, and more

如何安装 @activescott/auth?

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

@activescott/auth 支持 TypeScript 吗?

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

@activescott/auth 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@activescott/auth 可以商用吗?

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

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

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

@activescott/auth 还在维护吗?

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