# @harperfast/oauth 中文文档

规范地址：https://npmcn.com/package/%40harperfast/oauth/

版本：2\.12\.0
npm 元数据更新时间：2026-11-13T20:45:12.843Z
中文译文更新时间：2026-11-17T10:26:40.905Z
软件包许可：Apache-2\.0

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40harperfast/oauth
原文对照：https://npmcn.com/package/%40harperfast/oauth/?lang=original
项目主页：https://harper.fast/
源码仓库：https://github.com/HarperFast/oauth

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：1.4 MB，166 个文件
- 模块格式：ES Module
- TypeScript 类型：包内自带
- Node.js 要求：\>=22
- 运行依赖：2 个
- peer 依赖：harper \>=5\.0\.0
- 首次发布：2026-02-10T23:52:40.731Z
- 最新版本发布：2026-11-13T20:45:12.466Z
- 近 30 天下载量：17652（2026-10-18 至 2026-11-16，npm 官方下载统计）
- 已发布版本数：27（近 12 个月 27 个）

## 中文简介

Harper 的 OAuth 2.0 认证插件

## 安装

```sh
npm install @harperfast/oauth
```

也可以使用：`pnpm add @harperfast/oauth`、`yarn add @harperfast/oauth`、`bun add @harperfast/oauth`

## README

# 哈珀 OAuth 插件

OAuth 2.0和哈珀应用程序的OpenID Connect认证. 支持GitHub,Google,Azure AD,Auth0,以及自定义的OIDC供应商,并配有自动令牌刷新和生命周期钩,用于用户提供.

## 特征

-   **多供应商支助** - GitHub、Google、Azure AD、Auth0和自定义的OIDC供应商
-   **自动刷新令牌** - 每一次申请都要主动更新
-   **生命周期钩** - 用户提供和自定义逻辑的可扩展钩
-   **CSRF 保护** - 为集群支持分发的令牌存储
-   **标识符验证** - OIDC全面支持签名验证
-   **0 配置** - 自动使用哈珀的会话系统

## 安装

**需要 Harper v5 数据** (单位:千美元)`harper >=5.0.0`) (中文(简体) ). Harper v4(遗产) `harperdb` 软件包),使用 [`1.x`](https://github.com/HarperFast/oauth/tree/v1.x) 线条.

```bash
npm install @harperfast/oauth
```

## 快速启动

### 1\. 配置 OAuth 插件

添加到您的 `config.yaml`数字 :

```yaml
'@harperfast/oauth':
  package: '@harperfast/oauth'
  redirectUri: ${OAUTH_REDIRECT_URI} # your app's public origin — required for any deployed app
  providers:
    github:
      clientId: ${OAUTH_GITHUB_CLIENT_ID}
      clientSecret: ${OAUTH_GITHUB_CLIENT_SECRET}
```

### 2\. 设置环境变量

```bash
export OAUTH_GITHUB_CLIENT_ID="your-client-id"
export OAUTH_GITHUB_CLIENT_SECRET="your-client-secret"
export OAUTH_REDIRECT_URI="http://localhost:9926/oauth/callback" # local dev value — must become your public origin when you deploy (step 3)
```

> **说明:** 这个 `export` 以上命令只用于本地开发和快速测试。 您也可以使用一个 `.env` 文件为 `dotenv-cli` {\\fn黑体\\fs22\\bord1\\shad0\\3aHBE\\4aH00\\fscx67\\fscy66\\2cHFFFFFF\\3cH808080}为当地的 dev——不要承诺 对于 **哈珀·法布里克** 部署,见 [哈珀文件](https://docs.harperdb.io/docs/fabric/managing-applications) 用于管理运行时环境变量.

### 3\. 配置 OAuth 回调

这已经 **双方** 两者都需要:

1.  **在您的应用程序配置中** 设置 `redirectUri` 您的应用程序的公开来源+ `/oauth/callback` (以上步骤一)。 插件附加了您的提供者名称, 所以每个提供者都有一个设置 .
2.  **在您的提供者设置中** ——注册插件会发送的供应商专用 URL :

```
https://your-domain/oauth/github/callback
```

> **说明:** `redirectUri` 需要——没有 `localhost` 默认。 如果您跳过一面, 应用程序无法从配置错误开始命名提供者和设置以修正, 而不是默默发送您的用户到 `localhost`。见 [理解方向](https://npmcn.com/package/%40harperfast/oauth/docs/configuration.md#understanding-redirects)。 。 。 .

### 4\. (可选)登记生命周期钩

用户登录时创建或更新 :

```typescript
// resources.ts
import { registerHooks } from '@harperfast/oauth';

registerHooks({
    onLogin: async (oauthUser, tokenResponse, session, request, provider) => {
        const { User } = tables;

        // Find or create user
        let user;
        for await (const existing of User.search({ email: oauthUser.email })) {
            user = existing;
            break;
        }

        if (!user) {
            user = await User.create({
                email: oauthUser.email,
                name: oauthUser.name,
                provider: provider,
            });
        }

        return { user: String(user.id) };
    },
});

// Export your resources...
```

钩子也可以打开登录:返回 `{ status: 'denied' }` 或者说 `{ status: 'needs_confirmation', redirect }` 并且没有创建会话 [生命周期钩](https://npmcn.com/package/%40harperfast/oauth/docs/lifecycle-hooks.md#onlogin)。 。 。 .

> **警卫:** 返回时 `{ user }` 具有权威性 **绕过账户选择门**上面的例子可以说明问题——在确认身份之前,不要仅仅通过电子邮件解决现有的账户,因为 `oauthUser.emailVerified` 无法证明电子邮件来自经认证的来源( 见 [登录](https://npmcn.com/package/%40harperfast/oauth/docs/lifecycle-hooks.md#onlogin)) (中文(简体) ). 采用现有账户时,须符合稳定的提供者身份(例如:. `oauthUser.providerUserId`)或使用确认流.

### 5\. 测试认证

导航到 :

```
http://localhost:9926/oauth/github/login
```

## 使用量

访问资源中的认证用户 :

```typescript
export class MyResource extends tables.Resource {
    async get(target, request) {
        if (!request.session?.user) {
            throw new ClientError('Not authenticated', 401);
        }

        return {
            userId: request.session.user,
            email: request.session.oauthUser.email,
        };
    }
}
```

## 支持供应商

内建的提供者模板( 在配置前不活动) :

-   **GitHub 图像** - 奥奥特2.0
-   **谷歌** - OpenID 连接
-   **阿苏雷AD** - OpenID 连接
-   **自动 0** - OpenID 连接
-   **奥克塔** - OpenID 连接(多租户支持)
-   **自定义 OIDC** - 任何符合要求的提供者

> **说明:** 内建供应商是需要配置的模板. 在您提供 OAuth 证书前, 无活动 `clientId`, (中文(简体) ), `clientSecret`(见A/C.5/49/70,附件)。 在插件中拥有提供者代码并不能实现认证或创建安全曝光.

## 如何运作

插件自动处理 :

1.  **OAuth 流量** - 向提供者、处理回调、交换代号
2.  **托肯管理** - 在每个 HTTP 请求上验证并刷新令牌
3.  **会话整合** - 在哈珀会议上存储 OAuth 数据
4.  **CSRF 保护** - 使用分布式符号存储验证状态参数
5.  **自动登录** - 当符号过期而无法刷新时清除会话

## 文档

完整的文件可在 [文档](https://npmcn.com/package/%40harperfast/oauth/docs) 目录 :

-   **[开始](https://npmcn.com/package/%40harperfast/oauth/docs/getting-started.md)** - 安装和快速启动指南
-   **[配置](https://npmcn.com/package/%40harperfast/oauth/docs/configuration.md)** - 完整的配置参考
-   **[OAuth 供应商](https://npmcn.com/package/%40harperfast/oauth/docs/providers.md)** - 供应商设置指南
-   **[生命周期钩](https://npmcn.com/package/%40harperfast/oauth/docs/lifecycle-hooks.md)** - 用户提供和自定义逻辑
-   **[多用途SSO](https://npmcn.com/package/%40harperfast/oauth/docs/multi-tenant-sso.md)** - B2B SaaS的每个组织的OAuth供应商
-   **[托肯刷新和会话](https://npmcn.com/package/%40harperfast/oauth/docs/token-refresh-and-sessions.md)** - OAuth 令牌和哈珀会话如何互动
-   **[MCP OAuth (多功能软件)](https://npmcn.com/package/%40harperfast/oauth/docs/mcp-oauth.md)** - 模式背景协议客户端的授权服务器(实验性)
-   **[API 参考](https://npmcn.com/package/%40harperfast/oauth/docs/api-reference.md)** - 终点和方案性API
-   **[更改日志](https://npmcn.com/package/%40harperfast/oauth/CHANGELOG.md)** - 释放历史
-   **[维持](https://npmcn.com/package/%40harperfast/oauth/docs/maintaining.md)** - 发布程序、CI自动化和设计决定所在(维护者)

## 发展

### 构建

```bash
npm install
npm run build
```

### 测试

```bash
npm test
npm run test:coverage
```

### 林特格式( F)

```bash
npm run lint
npm run format:check
npm run format:write
```

## 数据库Schema

插件管理它自己的表格 `oauth` 数据库——见 [`schema/oauth.graphql`](https://npmcn.com/package/%40harperfast/oauth/schema/oauth.graphql) 定义:

-   `csrf_tokens` ——CSRF对人类OAuth流的保护(10分钟到期)
-   `harper_oauth_mcp_clients` - RFC 7591 动态客户注册;无过期,所以 `client_id`s被 MCP 客户端缓存( Claude Desktop, Cursor, ), `mcp-remote`幸存哈珀重启
-   `harper_oauth_mcp_keys` —— MCP JWT 签名密钥, 存储在数据库中, 因此复制的节点共享一个自转意识密钥集
-   `mcp_auth_codes` 单用途PKCE授权代码(5分钟到期)
-   `mcp_refresh_families` - OAuth 2.1 单用刷新键旋转状态
-   `mcp_assertion_jtis` ——RFC 7523客户端-接力回放后卫(120秒到期)
-   `login_handoffs` 一次性代码,将完成的签名交给 `postLoginRedirectOrigins` 来源( 60- 秒过期; 由代码的散列键键)

## MCP OAuth(实验性)

插件还可以作为 OAuth 2.1 的授权服务器 **示范背景协议** 客户端( Claude 桌面、 光标, `mcp-remote`让他们对同样的上游供应商进行认证。 何时 `mcp.enabled: true` 哈珀号上 `server.registerBearerValidator`,当地 `/mcp` 认证是自动注册的;对于自定义的应用程序拥有的 MCP 路由,请用 `withMCPAuth`。 。 。 .

```yaml
# config.yaml
'@harperfast/oauth':
  package: '@harperfast/oauth'
  providers:
    github:
      clientId: ${OAUTH_GITHUB_CLIENT_ID}
      clientSecret: ${OAUTH_GITHUB_CLIENT_SECRET}
  mcp:
    enabled: true
    issuer: https://my-app.example.com # required; pin to your public origin
```

```typescript
// Optional custom MCP route (in config.yaml, also set mcp.resource: https://my-app.example.com/custom-mcp)
import { server } from 'harper';
import { withMCPAuth } from '@harperfast/oauth';

// request.mcp (verified { sub, client_id, aud, scope }) is guaranteed present inside the guarded handler.
server.http(
    withMCPAuth((request) => ({ status: 200, body: JSON.stringify({ user: request.mcp.sub }) })),
    {
        urlPath: '/custom-mcp',
    }
);
```

该插件为发现服务( E)`/.well-known/*`),动态客户注册,授权/切入端点和JWKS; `withMCPAuth` 在每通电话中都核实听众所持的JWT,失败被关闭. 有一个 [`onMCPTokenIssued`](https://npmcn.com/package/%40harperfast/oauth/docs/lifecycle-hooks.md#onmcptokenissued) 当客户获取访问(客户 用户映射,监测,限速)和内置审计日志时,勾通可以作出反应.

**无头特务 (机相).** 没有浏览器和人类认证的代理商: `grant_type=client_credentials` 使用RFC 7523 `private_key_jwt` 客户端断言(EdDSA),每个经核实的客户端的费率限制. 客户身份解决 CIMD- first — a URL- 形状 `client_id` 以 [客户端ID 元数据文档](https://npmcn.com/package/%40harperfast/oauth/docs/mcp-oauth.md#client-id-metadata-documents-cimd) 通过一个SSRF 守护, 限速获取。 见 [无头特工](https://npmcn.com/package/%40harperfast/oauth/docs/mcp-oauth.md#headless-agents-client_credentials)。 。 。 .

**状态:实验,选入.** 见 **[MCP OAuth (多功能软件)](https://npmcn.com/package/%40harperfast/oauth/docs/mcp-oauth.md)** 为全流量 `withMCPAuth` 登记模式和选项、钩子、配置、生产清单和排除故障——以及 [还没有支持的](https://npmcn.com/package/%40harperfast/oauth/docs/mcp-oauth.md#not-yet-supported-v11) (单位:千美元)[156号](https://github.com/HarperFast/oauth/issues/156)用于v1.1前期工作.

## 安全考虑

-   **所需HTTPS** - OAuth在生产中需要HTTPS
-   **CSRF 保护** - 通过状态参数验证自动
-   **后日志重定向会停留在这个来源上** - 那个 `redirect` 参数减少为路径,除非 `postLoginRedirectOrigins` 列出它的出处;然后将签入的代码交给该出处和启动浏览器。 见 [在另一个来源签名](https://npmcn.com/package/%40harperfast/oauth/docs/configuration.md#signing-in-on-another-origin-postloginredirectorigins)。 。 。 .
-   **标识符验证** - OIDC提供商核实签名
-   **安全会话** - 使用哈珀的安全会话配置
-   **托肯存储** - 存储在会话中的托肯斯(配置安全饼干)
-   **采用账户需要核实索赔(2.6.0+)** - OAuth 登录采用现有的 Harper `hdb_user` 只有在索赔是经核实的、来自经认证来源的电子邮件(经认证的OIDC id sident with a 经认证的发行人,或GitHub的经认证的电子邮件)时,才可提出。 典型的Google/GitHub 验证电子邮件设置(和任何 `onLogin`\-hook登录)不受影响;从未经核实或非电子邮件申请中领养,现在被拒绝,或者在没有账户匹配时,给予无角色,不可解决的身份. 见 [账户选择门](https://npmcn.com/package/%40harperfast/oauth/docs/configuration.md#account-adoption-gate)。 。 。 .
-   **MCP客户注册(何时) `mcp.enabled` 事实)** - 那个 `/oauth/mcp/register` 结束点默认为 **开放式登记** (一) RFC 7591。 设定 `mcp.dynamicClientRegistration.initialAccessToken` 要求在登记时出示无记名证,或 `mcp.dynamicClientRegistration.allowedRedirectUriHosts` 限制哪些主机可以注册 `redirect_uri`s. 见 [`docs/configuration.md`](https://npmcn.com/package/%40harperfast/oauth/docs/configuration.md)。 。 。 .
-   **CIMD 分辨率( 当 `mcp.enabled` 事实)** - URL形状 `client_id`s 以客户身份元数据文档解决 **默认**启用 `mcp.clientIdMetadataDocuments.enabled: false`,或限制所获取的主机 `mcp.clientIdMetadataDocuments.allowedHosts`。 。 。 .

## 调试模式

启用测试的调试端点 :

```yaml
'@harperfast/oauth':
  debug: true
  providers:
    github:
      clientId: ${OAUTH_GITHUB_CLIENT_ID}
      clientSecret: ${OAUTH_GITHUB_CLIENT_SECRET}
```

调试端点 :

-   `GET /oauth/` - 列出已配置的提供者
-   `GET /oauth/test` - 交互式测试页面
-   `GET /oauth/{provider}/user` - 查看当前会话
-   `GET /oauth/{provider}/refresh` - 触发信号刷新

**警告:** 在生产中绝不启用调试模式 .

## 许可证

这个项目根据Apache许可证2.0获得许可——见 [自由主义](https://npmcn.com/package/%40harperfast/oauth/LICENSE) 详细文件.

版权2025 HarperDB, Inc.

## 常见问题

### @harperfast/oauth 是什么？

Harper 的 OAuth 2\.0 认证插件

### 如何安装 @harperfast/oauth？

在项目目录运行 npm install @harperfast/oauth，或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖：harper（\>=5\.0\.0）。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖，Yarn 需要手动安装。

### @harperfast/oauth 支持 TypeScript 吗？

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

### @harperfast/oauth 支持 ESM 还是 CommonJS？

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

### @harperfast/oauth 需要什么版本的 Node\.js？

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

### @harperfast/oauth 可以商用吗？

@harperfast/oauth 使用 Apache-2\.0 许可。宽松许可：允许商业使用、修改和再分发，并附带明确的专利授权；分发时需保留许可与 NOTICE 文件，修改过的文件要注明改动。以上为概括，不构成法律意见，请以许可原文为准。

### @harperfast/oauth 的下载量有多少？

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

### @harperfast/oauth 还在维护吗？

最新版本 2\.12\.0 发布于 2026/11/14（3 天前）；至今共发布 27 个版本，其中过去 12 个月发布了 27 个；首次发布于 2026/02/11。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

