@harperfast/oauth

中文文档
2.12.0发布于 2026/11/14Apache-2.0TypeScriptES Module构建来源已验证近 30 天下载 1.8万

OAuth 2.0 authentication plugin for Harper

原始使用文档
文档目录21 节
  1. Features
  2. Installation
  3. Quick Start
  4. 1. Configure OAuth Plugin
  5. 2. Set Environment Variables
  6. 3. Configure OAuth Callback
  7. 4. (Optional) Register Lifecycle Hooks
  8. 5. Test Authentication
  9. Usage
  10. Supported Providers
  11. How It Works
  12. Documentation
  13. Development
  14. Build
  15. Test
  16. Lint & Format
  17. Database Schema
  18. MCP OAuth (experimental)
  19. Security Considerations
  20. Debug Mode
  21. License

Harper OAuth Plugin

OAuth 2.0 and OpenID Connect authentication for Harper applications. Supports GitHub, Google, Azure AD, Auth0, and custom OIDC providers with automatic token refresh and lifecycle hooks for user provisioning.

Features

  • Multi-provider support - GitHub, Google, Azure AD, Auth0, and custom OIDC providers
  • Automatic token refresh - Proactive token renewal on every request
  • Lifecycle hooks - Extensible hooks for user provisioning and custom logic
  • CSRF protection - Distributed token storage for cluster support
  • ID token verification - Full OIDC support with signature validation
  • Zero configuration - Works with Harper's session system automatically

Installation

Requires Harper v5 (harper >=5.0.0). For Harper v4 (the legacy harperdb package), use the 1.x line.

npm install @harperfast/oauth

Quick Start

1. Configure OAuth Plugin

Add to your config.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. Set Environment Variables

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)

Note: The export commands above are for local development and quick testing only. You can also use a .env file with dotenv-cli for local dev — just don't commit it. For Harper Fabric deployments, see the Harper Fabric documentation for managing runtime environment variables.

3. Configure OAuth Callback

This has two sides — both are required:

  1. In your app config — set redirectUri to your app's public origin plus /oauth/callback (step 1 above). The plugin appends the provider name for you, so one setting covers every provider.
  2. In your provider settings — register the provider-specific URL the plugin will send:
https://your-domain/oauth/github/callback

Note: redirectUri is required — there is no localhost default. If you skip side 1, the app fails to start with a configuration error naming the provider and the setting to fix, rather than silently sending your users to localhost. See Understanding Redirects.

4. (Optional) Register Lifecycle Hooks

Create or update users when they log in:

// 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...

The hook can also gate the login: return { status: 'denied' } or { status: 'needs_confirmation', redirect } and no session is created — see Lifecycle Hooks.

Security: returning { user } is authoritative and bypasses the account-adoption gate. The example above is illustrative — do not resolve an existing account by email alone before you have confirmed the identity, because oauthUser.emailVerified is not proof the email came from an authenticated source (see onLogin). For adopting an existing account, bind to a stable provider identity (e.g. oauthUser.providerUserId) or use a confirmation flow.

5. Test Authentication

Navigate to:

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

Usage

Access authenticated user in your resources:

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,
        };
    }
}

Supported Providers

Built-in provider templates (not active until configured):

  • GitHub - OAuth 2.0
  • Google - OpenID Connect
  • Azure AD - OpenID Connect
  • Auth0 - OpenID Connect
  • Okta - OpenID Connect (with multi-tenant support)
  • Custom OIDC - Any compliant provider

Note: Built-in providers are templates that require configuration. None are active until you provide OAuth credentials (clientId, clientSecret, etc.). Having provider code in the plugin does not enable authentication or create security exposure.

How It Works

The plugin automatically handles:

  1. OAuth Flow - Redirects to provider, handles callback, exchanges code for tokens
  2. Token Management - Validates and refreshes tokens on every HTTP request
  3. Session Integration - Stores OAuth data in Harper sessions
  4. CSRF Protection - Validates state parameter using distributed token storage
  5. Auto-logout - Clears session when tokens expire and can't be refreshed

Documentation

Complete documentation is available in the docs directory:

Development

Build

npm install
npm run build

Test

npm test
npm run test:coverage

Lint & Format

npm run lint
npm run format:check
npm run format:write

Database Schema

The plugin manages its own tables in the oauth database — see schema/oauth.graphql for the definitions:

  • csrf_tokens — CSRF protection for the human OAuth flow (10-minute expiration)
  • harper_oauth_mcp_clients — RFC 7591 Dynamic Client Registration; no expiration, so client_ids cached by MCP clients (Claude Desktop, Cursor, mcp-remote) survive Harper restarts
  • harper_oauth_mcp_keys — MCP JWT signing keys, stored in the database so replicated nodes share one rotation-aware key set
  • mcp_auth_codes — single-use PKCE authorization codes (5-minute expiration)
  • mcp_refresh_families — OAuth 2.1 single-use refresh-token rotation state
  • mcp_assertion_jtis — RFC 7523 client-assertion replay guard (120-second expiration)
  • login_handoffs — one-time codes that hand a finished sign-in to a postLoginRedirectOrigins origin (60-second expiration; keyed by the code's hash)

MCP OAuth (experimental)

The plugin can also act as an OAuth 2.1 authorization server for Model Context Protocol clients (Claude Desktop, Cursor, mcp-remote), letting them authenticate against the same upstream providers. When mcp.enabled: true on Harper with server.registerBearerValidator, native /mcp authentication is registered automatically; for a custom app-owned MCP route, wrap your listener with withMCPAuth.

# 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
// 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',
    }
);

The plugin serves discovery (/.well-known/*), Dynamic Client Registration, the authorize/token endpoints, and JWKS; withMCPAuth verifies the audience-bound JWT on every call and fails closed. There's an onMCPTokenIssued hook to react when a client gains access (client→user mapping, monitoring, rate-limiting) and a built-in audit log.

Headless agents (machine-to-machine). An agent with no browser and no human authenticates as itself: grant_type=client_credentials with an RFC 7523 private_key_jwt client assertion (EdDSA), rate-limited per verified client. Client identity resolves CIMD-first — a URL-shaped client_id is fetched as a Client ID Metadata Document through an SSRF-guarded, rate-limited fetch. See Headless agents.

Status: experimental, opt-in. See MCP OAuth for the full flow, the withMCPAuth registration models and options, the hook, configuration, the production checklist, and troubleshooting — and what's not yet supported (#156) for v1.1 forward-work.

Security Considerations

  • HTTPS required - OAuth requires HTTPS in production
  • CSRF protection - Automatic via state parameter validation
  • Post-login redirects stay on this origin - The redirect parameter is reduced to its path, unless postLoginRedirectOrigins lists its origin; then the sign-in is handed there with a single-use, 60-second code bound to that origin and to the initiating browser. See Signing in on another origin.
  • ID token verification - OIDC providers verify token signatures
  • Secure sessions - Use Harper's secure session configuration
  • Token storage - Tokens stored in session (configure secure cookies)
  • Account adoption requires a verified claim (2.6.0+) - An OAuth login adopts an existing Harper hdb_user only when the claim is a verified email from an authenticated source (a signature-verified OIDC id token with a validated issuer, or GitHub's authenticated email). Typical Google/GitHub verified-email setups (and any onLogin-hook login) are unaffected; adoption from an unverified or non-email claim is now denied, or, when no account matches, given a roleless, non-resolvable identity. See Account-Adoption Gate.
  • MCP client registration (when mcp.enabled is true) - The /oauth/mcp/register endpoint defaults to open registration per RFC 7591. Set mcp.dynamicClientRegistration.initialAccessToken to require a bearer token on registration, or mcp.dynamicClientRegistration.allowedRedirectUriHosts to restrict which hosts may register redirect_uris. See docs/configuration.md.
  • CIMD resolution (when mcp.enabled is true) - URL-shaped client_ids are resolved as Client ID Metadata Documents by default. Disable with mcp.clientIdMetadataDocuments.enabled: false, or restrict which hosts are fetched with mcp.clientIdMetadataDocuments.allowedHosts.

Debug Mode

Enable debug endpoints for testing:

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

Debug endpoints:

  • GET /oauth/ - List configured providers
  • GET /oauth/test - Interactive test page
  • GET /oauth/{provider}/user - View current session
  • GET /oauth/{provider}/refresh - Trigger token refresh

Warning: Never enable debug mode in production.

License

This project is licensed under the Apache License 2.0 - see the LICENSE file for details.

Copyright 2025 HarperDB, Inc.

版本与发布记录

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

版本发布日期距今
2.12.0latest2026/11/143 天前
2.11.02026/11/107 天前
2.10.02026/10/2523 天前
2.9.02026/10/031 个月前
2.8.12026/10/021 个月前
2.8.02026/10/021 个月前

其他发布通道:alpha → 2.0.0-alpha.2,v1-lts → 1.6.2。

关于 @harperfast/oauth 的常见问题

@harperfast/oauth 是什么?

OAuth 2.0 authentication plugin for Harper

如何安装 @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 和提交记录判断。