npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@vafast/auth-middleware

v0.4.1

Published

Authentication middleware for Vafast - Generic JWT/API Key verification with dependency injection

Readme

@vafast/auth-middleware

对接 auth-server 的 JWT / API Key 硬认证app-id 校验、守卫与带类型的路由定义器。

硬认证:挂了就必须成功;失败直接 401/400。需要认证就挂,不需要就不挂。

完整文档:Auth Middleware

先搞清几个概念

Bearer JWT vs API Key

都使用 Authorization: Bearer <凭证>,用凭证是否含 : 区分:

| 方式 | 凭证 | 行为 | |------|------|------| | JWT | 不含 : | /verifyJwt;可附带请求头 app-id | | API Key | id:secret | /verifyApiKey;注入 userInfo + apiKey |

服务间调用 auth-server 用的 AUTH_SERVICE_API_KEY_* 与用户侧 Bearer API Key 是两套凭证。

失败码:401 vs 400

| 场景 | 状态码 | |------|--------| | 缺少/非法 Authorization、JWT/API Key 失败、账号禁用/删除 | 401 | | 缺少/无效 app-id | 400 | | 守卫无 userInfo / apiKey | 401 | | 守卫无 app | 400 | | auth-server 超时 / 不可用 | 504 / 503 风格 |

app-id 多租户

appValidator / authWithApp 要求 app-id 请求头并校验后注入 app

安装

npm install @vafast/auth-middleware

快速开始

AUTH_API_BASE_URL=http://localhost:9003
AUTH_SERVICE_API_KEY_ID=ak_xxx
AUTH_SERVICE_API_KEY_SECRET=sk_xxx
# 可选:AUTH_API_TIMEOUT=5000
import { authWithApp, requireUser, defineAuthRouteWithApp } from '@vafast/auth-middleware'
import { defineRoute, defineRoutes } from 'vafast'

export const routes = defineRoutes([
  defineRoute({
    path: '/api',
    middleware: [authWithApp],
    children: [
      defineAuthRouteWithApp({
        method: 'GET',
        path: '/profile',
        middleware: [requireUser],
        handler: ({ userInfo, app }) => ({
          id: userInfo.id,
          appId: app.id,
        }),
      }),
    ],
  }),
])

用法

环境变量

| 变量 | 必需 | 说明 | |------|------|------| | AUTH_API_BASE_URL | 是* | auth-server 地址 | | AUTH_SERVICE_API_KEY_ID | 否 | 服务间 API Key ID | | AUTH_SERVICE_API_KEY_SECRET | 否 | 服务间 API Key Secret | | AUTH_API_TIMEOUT | 否 | 超时毫秒,默认 5000 |

* 缺少 baseUrl(参数与环境变量都没有)时 createAuthClient 会抛错。

请求头

| Header | 说明 | |--------|------| | Authorization: Bearer <jwt> | JWT | | Authorization: Bearer <apiKeyId>:<secret> | API Key | | app-id: <appId> | 多租户 / appValidator / authWithApp |

预配置中间件(懒加载)

| 导出 | 说明 | 注入 | |------|------|------| | auth | JWT + API Key | userInfo(+ apiKey) | | jwtAuth | 仅 JWT(含 : 非法) | userInfo | | apiKeyAuth | 仅 API Key | userInfo + apiKey | | appValidator | 必需 app-id | app | | authWithApp | 用户 + app | userInfo + app(+ apiKey) |

工厂

| 函数 | 别名 | |------|------| | authenticate | authJwtAndApiKey | | authenticateJwt | authJwt | | authenticateApiKey | authApiKey | | validateApp | validateAppId | | authenticateWithApp | authApp |

可传 AuthClientConfig、已有 AuthClient,或不传(读环境变量)。

validateApp(config?, { required?, verify? })required / verify 默认均为 trueverify: false 只检查 header,注入最小化 app。

守卫(不发网络请求)

| 守卫 | 条件 | 失败 | |------|------|------| | requireUser | 有 userInfo | 401 | | requireApp | 有 app | 400 | | requireApiKey | 有 apiKey | 401 | | requireUserAndApp | 两者都有 | 401 / 400 |

路由定义器

defineAuthRoutedefineOptionalAuthRoutedefineApiKeyRoutedefineAuthRouteWithAppdefineRouteWithAppdefineOptionalAuthRouteWithAppdefineFullAuthRoute

内置 webhook?: boolean | { eventKey?, include?, exclude? }(精简类型;完整能力见 @vafast/webhook)。

API

createAuthClient(config?)

| 字段 | 默认 | 说明 | |------|------|------| | baseUrl | AUTH_API_BASE_URL | 缺则抛错 | | apiKeyId | AUTH_SERVICE_API_KEY_ID | 服务间 Bearer | | apiKeySecret | AUTH_SERVICE_API_KEY_SECRET | 与 ID 组成 id:secret | | timeout | AUTH_API_TIMEOUT5000 | 毫秒 |

客户端方法:verifyJwtverifyApiKeyverifyAppgetUsersBatchsearchUsersgetUsersStats

UserInfo 组织相关字段(源码注释)

| 字段 | 含义 | |------|------| | organizationId | 组织成员所属组织;组织成员身份直接归属 organization | | accountType | organization_member = 组织成员;customer_user = 客户应用终端用户 | | isOrgMemberAccess | 组织成员跨 app 访问时为 true | | targetAppId | 本次请求 app-id 指向的目标 app;跨 app 时与原始 appId 不同 | | accessMode | directorg_member_delegate |

另有基础字段:idappIdemailphoneavatarstatusroleIdnicknameverified
VerifiedUserInfo 可带 app?: AppInfoAppInfo.extensions 为 auth-server 维护的结构化扩展(如 organizationId)。

最佳实践

  • 路由组挂 authWithApp,叶子挂 requireUser 等守卫。
  • 公开接口不挂认证中间件。
  • 多中间件共享同一 createAuthClient() 实例。
  • 跨 app / 组织代理访问时读取 accessMode / isOrgMemberAccess / targetAppId

注意事项

  • 硬认证:没有「软登录失败继续」的预配置中间件。
  • 预配置依赖环境变量;测试请用工厂 + 显式 client。
  • jwtAuth 拒带 : 的 token;apiKeyAuth 要求 id:secret
  • 用户凭证失败多为 401app-id 问题多为 400
  • 包内 webhook 类型只便于声明;实际分发需 server.use(webhook(...))

相关链接

License

MIT