@askrjs/auth

中文文档
0.5.1发布于 2026/11/02Apache-2.0TypeScriptES Module构建来源已验证近 30 天下载 2448

Shared authentication contracts and request auth resolution for Askr

原始使用文档
文档目录8 节
  1. Feature matrix
  2. Request authentication
  3. OIDC
  4. Provider application sessions
  5. MFA
  6. SAML
  7. Install
  8. 0.5.0 preparation

@askrjs/auth

CI npm version

Framework-owned, domain-neutral authentication primitives for Askr. Server sessions require Node.js 24 or newer. The low-level OIDC and passkey client entries retain their explicit Web Crypto/Fetch or Credentials API boundaries.

Feature matrix

EntryOwnsDoes not own
@askrjs/authPrincipal, auth contexts and requirements, bearer/cookie/session request resolutionUsers, organizations, credential storage, password hashing
@askrjs/auth/jwtRS256/ES256 issuance and validation, claims, JWKS rolloverToken persistence or revocation lists
@askrjs/auth/oidcDiscovery, authorization-code PKCE, callback correlation, verified ID-token-to-Principal exchangeProvider UI, account linking, refresh-token storage
@askrjs/auth/serverServer-owned provider transactions, sealed session cookies, refresh families and application hooksApplication users/policy and HTTP adapter ownership
@askrjs/auth/providers/auth0Native Auth0 provider policy and API audiencesBrowser SDKs and application routes
@askrjs/auth/providers/microsoftTenant-bound Microsoft provider and explicit API permissionsMulti-tenant inference and application routes
@askrjs/auth/providers/googleGoogle provider, hosted-domain policy and explicit API permissionsWorkspace administration and application routes
@askrjs/auth/providers/appleApple web sign-in and daily account checksAPI access-token grants and application routes
@askrjs/auth/samlSP metadata and requests, signed/encrypted response validation, request correlationIdP operation, SLO, IdP-initiated SAML, external CA trust policy
@askrjs/auth/mfaTOTP and WebAuthn registration/authentication verificationCredential storage, recovery policy, enrollment UI

Replay prevention stays with the application’s durable storage boundary. SAML requires atomic requestStore.consume(). TOTP returns the accepted counter so it can be atomically marked used. WebAuthn returns the verified new signature counter so it can be atomically persisted.

Request authentication

createAuth() resolves Bearer JWTs, JWT cookies, and opaque session cookies into one auth context. Invalid, expired, or malformed JWTs are treated consistently as unauthenticated and resolution continues to the next configured credential source. Operational failures from tenant, principal, or session stores still reject resolve() so callers can handle unavailable dependencies.

OIDC

exchangeCode() accepts the callback and the stored authorization request separately. It checks state before network access, then validates the required ID token against discovery and JWKS before returning { tokens, principal }. ID-token audiences must identify only this client; any explicit azp must match the configured client ID. Additional-audience trust is not part of this client profile.

The OIDC entrypoint also runs in browsers with Web Crypto, Fetch, and UTF-8 encoding support. JWT decoding uses browser-native bytes and needs no Node Buffer polyfill. Browser clients omit clientSecret; retain the authorization request for callback correlation. This entry is a low-level protocol primitive; it does not replace server-owned application sign-in or retain session tokens in the browser. For application sessions use the server contract and the 0.5 migration.

import { createOidcClient } from "@askrjs/auth/oidc";

const client = createOidcClient({ issuer, clientId, clientSecret, redirectUri });
const request = await client.createAuthorizationRequest();
const result = await client.exchangeCode({ code: callback.code, state: callback.state, request });

Provider application sessions

Configure the shared createProviderSession engine from @askrjs/auth/server with one or more native providers, then bind it to the provider-auth mode in @askrjs/server. The server owns authorization/callback transport, sealed cookies, refresh tokens and per-resource token grants. createSessionAuth from @askrjs/askr/router binds the public session snapshot to an SSR or SPA application; provider tokens and client secrets stay server-side. See the committed ownership/API contract and setup for Auth0, Microsoft, Google or Apple.

@askrjs/auth/browser and the develop-only @askrjs/auth/auth0 SDK adapter are removed in 0.5. There is no replacement browser-held session/SDK path. The published 0.4.2 browser lifecycle requires the explicit server-session migration.

MFA

import { generateTotpSecret, verifyTotpCode } from "@askrjs/auth/mfa";

const secret = generateTotpSecret();
const result = await verifyTotpCode({ secret, code });
if (result.valid) await counters.consume(result.counter); // application-owned atomic replay guard

TOTP defaults to SHA-1, six digits, 30-second periods, and a one-step window. SHA-256, SHA-512, and eight-digit codes are supported. WebAuthn uses exact base64url challenges, exact origin allowlists, one RP ID, and user verification by default. It accepts ES256, RS256 (RSA 2048-bit or larger), and EdDSA/Ed25519 keys. Registration accepts none and cryptographically verified packed self-attestation only; certificate-backed attestation is deliberately rejected. Verification also applies explicit byte limits to client data, credential IDs, challenges, attestation objects, authenticator data, and signatures before parsing or cryptographic work.

SAML

The server-only @askrjs/auth/saml entrypoint provides a narrow SP-initiated SAML 2.0 flow: metadata generation, signed or unsigned HTTP-Redirect AuthnRequests, signed assertion validation, optional signed responses, encrypted assertions, request correlation, and atomic replay protection. It is intentionally separate from createAuth() and the package root.

import { createSamlServiceProvider } from "@askrjs/auth/saml";

const saml = createSamlServiceProvider({
  entityId: "https://app.example.com/saml/metadata",
  acsUrl: "https://app.example.com/saml/acs",
  idp: {
    entityId: "https://idp.example.com",
    ssoUrl: "https://idp.example.com/sso",
    certificates: [idpCertificate],
  },
  requestStore, // save/get plus an atomic consume operation
});

const { url } = await saml.createAuthnRequest({ relayState: "return-to" });
const principal = await saml.validateResponse({ samlResponse, relayState: "return-to" });

The request store is a security boundary: consume(id) must atomically return false for a missing, expired, or previously consumed ID. The validator defaults to a 10-minute request TTL, a five-minute assertion age, and 60 seconds of clock skew. Assertions are always signed; requireSignedResponse additionally requires the outer response signature.

JWT issuance and validation support RS256 with RSA keys and ES256 with EC P-256 keys. A JWK's alg may be omitted and inferred from its key shape; when present, it must match the key.

Install

npm install @askrjs/auth

0.5.0 preparation

See the complete API decisions and migration and hardening evidence. The browser passkey helpers remain at @askrjs/auth/webauthn-client; CBOR/COSE parsing and base64url conversion are private. Application stores retain replay, credential and policy ownership.

版本与发布记录

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

版本发布日期距今
0.5.1latest2026/11/025 天前
0.5.02026/10/1424 天前
0.4.22026/10/0930 天前
0.4.12026/10/011 个月前
0.4.02026/09/291 个月前
0.3.02026/09/121 个月前

关于 @askrjs/auth 的常见问题

@askrjs/auth 是什么?

Shared authentication contracts and request auth resolution for Askr

如何安装 @askrjs/auth?

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

@askrjs/auth 支持 TypeScript 吗?

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

@askrjs/auth 支持 ESM 还是 CommonJS?

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

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

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

@askrjs/auth 可以商用吗?

@askrjs/auth 使用 Apache-2.0 许可。宽松许可:允许商业使用、修改和再分发,并附带明确的专利授权;分发时需保留许可与 NOTICE 文件,修改过的文件要注明改动。以上为概括,不构成法律意见,请以许可原文为准。

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

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

@askrjs/auth 还在维护吗?

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