# @grantex/sdk 中文文档

规范地址：https://npmcn.com/package/%40grantex/sdk/

版本：0\.8\.2
npm 元数据更新时间：2026-10-04T12:08:52.850Z
中文译文更新时间：2026-11-17T08:53:18.214Z
软件包许可：Apache-2\.0

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

原始 npm 页面：https://www.npmjs.com/package/%40grantex/sdk
原文对照：https://npmcn.com/package/%40grantex/sdk/?lang=original
项目主页：https://grantex.dev/
源码仓库：https://github.com/mishrasanjeev/grantex

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

- 包体积（解压后）：1.2 MB，476 个文件
- 模块格式：ES Module
- TypeScript 类型：包内自带
- Node.js 要求：\>=22\.12\.0
- 运行依赖：1 个
- 首次发布：2026-02-27T08:30:07.150Z
- 最新版本发布：2026-10-04T12:08:52.663Z
- 近 30 天下载量：4945（2026-10-17 至 2026-11-15，npm 官方下载统计）
- 已发布版本数：39（近 12 个月 39 个）

## 中文简介

Grantex 授权协议的脚本 SDK 类型

## 安装

```sh
npm install @grantex/sdk
```

也可以使用：`pnpm add @grantex/sdk`、`yarn add @grantex/sdk`、`bun add @grantex/sdk`

## README

# @ granex/ sdk (英语)

脚本 SDK 类型 [格兰特克斯](https://grantex.dev/) 授权协议——AI代理OAuth 2.0.

[![npm version](https://img.shields.io/npm/v/@grantex/sdk)](https://www.npmjs.com/package/@grantex/sdk) [![License](https://img.shields.io/npm/l/@grantex/sdk)](https://github.com/mishrasanjeev/grantex/blob/main/LICENSE)

> **[主页](https://grantex.dev/)** | **[文档](https://docs.grantex.dev/)** | **[API 参考](https://docs.grantex.dev/api-reference)** | **[免费签名](https://grantex.dev/dashboard/signup)** | **[GitHub 图像](https://github.com/mishrasanjeev/grantex)**

## 安装

0.8.2版本增加了打入的DPDP客户端响应和可选企业 所罗门群岛 `sessionToken` 字段。 检查 [释放状态](https://docs.grantex.dev/release-status) ;源版本不是登记册发布.

**0.8.0版本:** `enforce()` 检查受赠对象, 需要上限范围的数量,并在线检查当前撤销 默认。 按呼撤销设置不能削弱客户端设置. 需要22.12+节点;建议使用24LTS节点. 这些是破碎的 变化: [执行移徙指南](https://docs.grantex.dev/migration-enforcement)。 。 。 . `verifyGrantToken()` 仅是密码验证,不是电流 撤销检查 。 在安装前在发布状态中验证发布 .

**版本0.7.1:** 在已校验时披露已签名的 WebAuthn 证据引用 赠款和赠款 `webauthnVerified` 越共证明答复. 参考文献不是 (b) 核查签发人、RP ID, 来源、证据摘要和当前证书状况。 服务器控制 单独印发 `PORTABLE_WEBAUTHN_EVIDENCE_ENABLED`; 见 [密码指南](https://docs.grantex.dev/features/fido-webauthn)。 。 。 .

**版本0.7.0:** 增加主机密码入学课程 账户级不规则反应政策方法。 服务器必须启用 相应的特性标记; 此 SDK 不注册没有密码的密码 经认证的客户交接。 0.6.0 版本添加了保存钱包客户端 服务器基础 USDC `evmPayment` 有效载荷和曝光 `reconcileReservation()` 页:1 最终结算/期满。 使用 `@grantex/x402@0.4.0` 或以后为 自动402/支付/重试流量。 确认已发布的 SDK 版本 [释放状态](https://docs.grantex.dev/release-status) 在安装前. 见 [基本监管安排](https://docs.grantex.dev/guides/base-usdc-custody)。 。 。 .

```bash
npm install @grantex/sdk
```

## 快速启动

```typescript
import { Grantex, verifyGrantToken } from '@grantex/sdk';

const grantex = new Grantex({ apiKey: 'YOUR_API_KEY', audience: 'https://api.merchant.example' });

// 1. Register an agent
const agent = await grantex.agents.register({
  name: 'Email Assistant',
  description: 'Reads and sends email on behalf of users',
  scopes: ['email:read', 'email:send'],
});

// 2. Request authorization
const { consentUrl } = await grantex.authorize({
  agentId: agent.agentId,
  userId: 'usr_01J...',
  scopes: ['email:read', 'email:send'],
  resourceServers: ['https://api.merchant.example'],
  audience: 'https://api.merchant.example',
});
// Redirect the user to consentUrl — they approve in plain language

// 3. Exchange authorization code for a grant token
// (your redirect callback receives the `code` after user approves)
const token = await grantex.tokens.exchange({ code, agentId: agent.agentId });
// Treat token.grantToken as a bearer credential; do not log it.
console.log(token.scopes);     // ['email:read', 'email:send']
console.log(token.grantId);    // 'grnt_01J...'

// 4. Verify locally using keys retrieved from the issuer's JWKS
const grant = await verifyGrantToken(token.grantToken, {
  jwksUri: 'https://api.grantex.dev/.well-known/jwks.json',
  audience: 'https://api.merchant.example',
});
console.log(grant.principalId);  // 'usr_01J...'

// 5. Revoke when done
await grantex.tokens.revoke(grant.tokenId);
```

## 配置

```typescript
const grantex = new Grantex({
  apiKey: 'gx_....',              // or set GRANTEX_API_KEY env var
  baseUrl: 'https://api.grantex.dev', // default
  issuer: 'https://grantex.dev',  // optional when token issuer differs from API host
  jwksUri: 'https://api.grantex.dev/.well-known/jwks.json', // optional JWKS override
  timeout: 30000,                 // request timeout in ms (default: 30s)
});
```

| 选项 | 类型 | 默认 | 说明 |
| --- | --- | --- | --- |
| `apiKey` | `string` | `process.env.GRANTEX_API_KEY` | 认证的 API 密钥 |
| `baseUrl` | `string` | `https://api.grantex.dev` | Grantex API 的基础 URL |
| `issuer` | `string` | 来源于 `jwksUri` | 当地签字核查的预期JWT签发人 |
| `jwksUri` | `string` | `${baseUrl}/.well-known/jwks.json` | 核查者从中获取签名密钥的 URL |
| `timeout` | `number` | `30000` | 请求超时( 毫秒) |

## OAuth 代理配置客户端

`OAuthAgentClient` 执行客户角色 `draft-mishra-oauth-agent-grants-03` 简介。 它发现和验证 RFC 8414元数据,默认创建了ES256 DPoP密钥,使用PAR和PKCE S256, 验证 `state` 和RFC 9207号协议 `iss` 响应参数,旋转刷新 符号,执行同源 RFC 8693 衰减,并创建 DPop 证明 用于保护资源的请求.

```typescript
import { OAuthAgentClient } from '@grantex/sdk';

const client = await OAuthAgentClient.create({
  issuer: 'https://grantex.dev',
  clientId: 'ag_01J...',
  redirectUri: 'https://agent.example/callback',
  resource: 'https://api.example/resource',
});

const pending = await client.beginAuthorization({
  scopes: ['grantex.resource.read'],
  principalHint: 'principal@example.com',
});

// Redirect the Principal to pending.authorizationUrl. In the callback:
const tokens = await client.completeAuthorization(callbackUrl);

const response = await client.fetch(
  'https://api.example/resource',
  tokens.access_token,
);

const narrower = await client.attenuate(tokens.access_token, [
  'grantex.resource.read',
]);
const refreshAttempt = crypto.randomUUID();
const rotated = await client.refresh(tokens.refresh_token!, {
  idempotencyKey: refreshAttempt,
});
await client.revoke(rotated.refresh_token!, 'refresh_token');
```

丢失响应时用旧的刷新令牌坚持一能键 恢复必须在呼叫者重新启动后幸存。 在300秒内重复两次 新的 DPoP 证明,并用 重新计算、不延长 `expires_in`A级 不同的密钥或 DPOP 身份被视为刷新重用和取消 象征性的家庭。 未提供密钥时, 客户端生成并保留一个 用于当前过程中5分钟的旧刷新令牌.

如果一个实例必须存活下来,则安全地坚持生成的密钥 重启 。 提供匹配 `privateKey` 财务报告和审定财务报表 `publicJwk` 改为 `create`两者都是 需要一起行动. `principalHint` 是可选的账户发现输入,并且是 不证明校长的身份 授权服务器的密码认证. 除非 `allowInsecureLoopback` 用于本地回路测试。 订正 `-02` 家庭草案作为活跃的个人因特网草案发表; 订正 `-03` 这里执行的工作候选人。 也不是一个 IETF认可或独立认证的标准.

## 代理预付钱包( SDK 0. 5+)

`PrepaidWalletAgentClient` 使用一个 `OAuthAgentClient` 和 DPoP 访问令牌 列出指定的钱包、保留付款和请求重新加载阈值. `PrincipalPrepaidWalletClient` 使用寿命短的正会话符号 创建并资助钱包, 指定安全默认策略, 管理分层支出 政策和确切的付款核准、批准重新装载、检查活动,以及 屏蔽一个代理的任务、钱包或所有钱包. `DeveloperPrepaidWalletPolicyClient` 管理租户一级的政策 开发者 API 密钥 .

访问符必须包含 `wallet:spend` 和每个行动范围 支付(例如 `weather:read`) (中文(简体) ). 代理钱包列表故意省略 保管人身份、钱包地址、主要身份和钱包元数据.

```typescript
import {
  PrepaidWalletAgentClient,
  PrincipalPrepaidWalletClient,
} from '@grantex/sdk';

const agentWallets = new PrepaidWalletAgentClient({
  oauthClient,
  accessToken,
});

const principalWallets = new PrincipalPrepaidWalletClient({
  baseUrl: 'https://api.grantex.dev',
  sessionToken,
});

await principalWallets.createSpendPolicy({
  name: 'Shared research budget',
  scopeType: 'group',
  scopeId: 'research-agents',
  effect: 'limit',
  maxAmount: '1000000',
  windowType: 'month',
  onExceed: 'require_approval',
  purposes: ['research'],
});

const authorization = await agentWallets.authorizePayment({
  amount: '1000',
  asset: 'USDC',
  network: 'grantex:prepaid',
  recipient: 'merchant:weather-api',
  resource: 'https://merchant.example/weather',
  scope: 'weather:read',
  merchantId: 'merchant:weather-api',
  purpose: 'research',
  projectId: 'climate-2026',
  costCenter: 'engineering',
  maxTimeoutSeconds: 120,
  idempotencyKey: crypto.randomUUID(),
});
```

`authorizePayment` 返回已签名的保留或 `approval_required` 反应。 在校长批准这个请求后, 重新尝试 `approvalRequestId`,同样的钱包,一能键,以及所有 原始支付字段。 批准是短命和单用.

量是原子单位整数字符串. 分层政策和准确批准 备查 `@grantex/sdk` 0.5.0 后为相.

自备钱包的部署也必须提供正确的公共资源 路线、迁移 `091` 财务报告和审定财务报表 `092`,持久通知交付,商家方面 独断专行,以及任何外部监管/提供者的整合。 见 [预付钱包 生产 准备情况](https://docs.grantex.dev/guides/prepaid-wallet-production)· ; 仅安装SDK并不能提供这些依赖性.

## 商业 V1 / OACP

SDK包括一个 `commerce` grantex Commerce V1 控制资源 飞机和OACP的活飞行员流.

```typescript
import { Grantex } from '@grantex/sdk';

const grantex = new Grantex({ apiKey: process.env.GRANTEX_API_KEY! });

// Public merchant publishing profile
const profile = await grantex.commerce.getProfile({
  merchantId: 'mch_shopify_mgx0n6_22',
});
console.log(profile.merchant?.merchant_id);

// Catalog grounding
const catalog = await grantex.commerce.searchCatalog({
  merchant_id: 'mch_shopify_mgx0n6_22',
  query: 'shirt',
  limit: 5,
});

// Agent cart creation. Commerce write paths require Idempotency-Key.
const cart = await grantex.commerce.createCart({
  idempotencyKey: crypto.randomUUID(),
  merchant_id: 'mch_shopify_mgx0n6_22',
  currency: 'INR',
  line_items: [
    { variant_id: String(catalog.items[0]?.['variant_id']), quantity: 1 },
  ],
});

// Consent request and Commerce Passport exchange
const consent = await grantex.commerce.createConsentRequest({
  merchant_id: 'mch_shopify_mgx0n6_22',
  passport_type: 'checkout',
  max_amount: Number(cart.data['total_amount']),
  currency: 'INR',
});

// Redirect the buyer to consent.data['consent_url'], then exchange after
// the consent request is granted.
const passport = await grantex.commerce.exchangeConsentForPassport({
  consent_request_id: String(consent.data['consent_request_id']),
});

const payment = await grantex.commerce.createPaymentIntent({
  idempotencyKey: crypto.randomUUID(),
  merchant_id: 'mch_shopify_mgx0n6_22',
  cart_id: String(cart.data['cart_id']),
  passport_jwt: String(passport.data['passport_jwt']),
  amount_minor_units: Number(cart.data['total_amount']),
  currency: 'INR',
  provider_key: 'plural',
});

const checkout = await grantex.commerce.createCheckoutLink(
  String(payment.data['payment_intent_id']),
  {
    idempotencyKey: crypto.randomUUID(),
    passport_jwt: String(passport.data['passport_jwt']),
    success_url: 'https://buyer.example/success',
    cancel_url: 'https://buyer.example/cancel',
  },
);
```

多层网钩摄入量在 `https://api.grantex.dev/v1/webhooks/providers/plural`。提供网络用户是 通常由提供者仪表板调用,而不是应用代码调用. SDK这个 还揭露 `grantex.commerce.getOpsHealth()` 财务报告和审定财务报表 `grantex.commerce.listProviderWebhookEvents()` 操作员健康检查.

## PKCE 支持

SDK包括内置的PKCE(代码交换的Proof key)支持,使用S256方法进行安全授权流:

```typescript
import { Grantex, generatePkce } from '@grantex/sdk';

const grantex = new Grantex({ apiKey: 'YOUR_API_KEY' });

// 1. Generate a PKCE challenge
const pkce = generatePkce();
// pkce.codeVerifier       — random 43-char string (keep secret)
// pkce.codeChallenge      — SHA-256 hash of verifier (send to server)
// pkce.codeChallengeMethod — 'S256'

// 2. Pass the challenge when requesting authorization
const { consentUrl } = await grantex.authorize({
  agentId: 'ag_01J...',
  userId: 'usr_01J...',
  scopes: ['files:read'],
  codeChallenge: pkce.codeChallenge,
  codeChallengeMethod: pkce.codeChallengeMethod,
});

// 3. Exchange the code with the verifier
const token = await grantex.tokens.exchange({
  code: 'auth_code_from_redirect',
  agentId: 'ag_01J...',
  codeVerifier: pkce.codeVerifier,
});
```

* * *

## API 参考

### 授权

#### `grantex.authorize(params)`

启动授权流程。 返回一个同意的 URL 以重定向用户 .

```typescript
const request = await grantex.authorize({
  agentId: 'ag_01J...',
  userId: 'usr_01J...',
  scopes: ['files:read', 'email:send'],
  audience: 'https://api.example.com', // optional; becomes the JWT aud claim
  expiresIn: '24h',          // optional
  redirectUri: 'https://...' // optional
});

console.log(request.consentUrl);     // redirect user here
console.log(request.authRequestId);  // track the request
console.log(request.expiresAt);      // ISO 8601 timestamp
```

**回返**数字 : `AuthorizationRequest`

| 外地 | 类型 | 说明 |
| --- | --- | --- |
| `authRequestId` | `string` | 此授权请求的唯一ID |
| `consentUrl` | `string` | URL 将用户重定向至征得同意 |
| `agentId` | `string` | 请求授权的代理人 |
| `principalId` | `string` | 要求用户同意 |
| `scopes` | `string[]` | 请求范围 |
| `expiresAt` | `string` | 请求到期时(ISO 8601) |
| `status` | `string` | `'pending'`, (中文(简体) ), `'approved'`, (中文(简体) ), `'denied'`,或 `'expired'` |

* * *

### 探员

#### `grantex.agents.register(params)`

注册一个新的AI代理.

```typescript
const agent = await grantex.agents.register({
  name: 'Code Review Bot',
  description: 'Reviews pull requests and suggests improvements',
  scopes: ['repo:read', 'pr:comment'],
});
```

#### `grantex.agents.get(agentId)`

```typescript
const agent = await grantex.agents.get('ag_01J...');
```

#### `grantex.agents.list()`

```typescript
const { agents } = await grantex.agents.list();
```

#### `grantex.agents.update(agentId, params)`

```typescript
const agent = await grantex.agents.update('ag_01J...', {
  name: 'Updated Name',
  scopes: ['repo:read', 'pr:comment', 'pr:approve'],
});
```

#### `grantex.agents.delete(agentId)`

```typescript
await grantex.agents.delete('ag_01J...');
```

* * *

### 赠款

#### `grantex.grants.get(grantId)`

```typescript
const grant = await grantex.grants.get('grnt_01J...');
```

#### `grantex.grants.list(params?)`

```typescript
const { grants } = await grantex.grants.list({
  agentId: 'ag_01J...',       // optional filter
  principalId: 'usr_01J...',  // optional filter
  status: 'active',           // 'active' | 'revoked' | 'expired'
  page: 1,
  pageSize: 20,
});
```

#### `grantex.grants.revoke(grantId)`

```typescript
await grantex.grants.revoke('grnt_01J...');
```

#### `grantex.grants.delegate(params)`

创建授权的代理赠款(每 [SPEC 第9节](https://github.com/mishrasanjeev/grantex/blob/main/SPEC.md)) (中文(简体) ).

```typescript
const delegation = await grantex.grants.delegate({
  parentGrantToken: 'eyJhbG...',
  subAgentId: 'ag_02K...',
  scopes: ['files:read'],         // must be subset of parent scopes
  expiresIn: '1h',                // optional, cannot exceed parent
});

// Deliver delegation.grantToken securely to the sub-agent; do not log it.
console.log(delegation.grantId);
```

#### `grantex.grants.verify(token)`

通过 API(通过实时吊销检查进行在线核查) 验证赠与符 .

```typescript
const verified = await grantex.grants.verify('eyJhbG...');
console.log(verified.principalId);
console.log(verified.scopes);
```

掷出 `GrantexTokenError` 当该符号不活动、被撤销、过期或无法使用时.

* * *

### 键

#### `grantex.tokens.exchange(params)`

将授权代码交换给赠品 这是用户批准同意申请后获得赠与令牌的标准方式.

```typescript
const token = await grantex.tokens.exchange({
  code: 'auth_code_from_redirect',  // from your redirect callback
  agentId: 'ag_01J...',
});

// Deliver token.grantToken securely to the agent; do not log it.
console.log(token.grantId);      // grant record ID
console.log(token.scopes);       // granted scopes
console.log(token.expiresAt);    // ISO 8601 expiry
// Store token.refreshToken securely for refresh; do not log it.
```

**回返**数字 : `ExchangeTokenResponse`

| 外地 | 类型 | 说明 |
| --- | --- | --- |
| `grantToken` | `string` | 签署RS256 JWT——代理人的无记名证书 |
| `grantId` | `string` | 格兰特记录 |
| `scopes` | `string[]` | 核准的用户范围 |
| `expiresAt` | `string` | 基本赠款到期(ISO 8601) |
| `refreshToken` | `string` | 在赠款仍在使用期间刷新证书 |

新的通行证核准补助金, `verifyGrantToken()` 并给予API答复 曝光紧凑 `webauthnEvidence` 参考文献。 请求 `credentialFormat: 'vc-jwt'` 获得选择加入的《维也纳公约》,并完全坚持 `vc.evidence`· ; `grantex.credentials.verify(vcJwt)` 返回时 `{ valid, vcId?, payload?, revoked?, expired?, error?, webauthnVerified? }`。 。 。 . 核查发行人和撤销状态,将预期RP ID/原产地加注,以及 将证据摘要与赠款参考书相匹配。 原始证书公开 键可以链接 VC 演示文稿.

刷新符是单用并在每个接受的刷新上旋转. 如果在犯罪后丢失了回复,请重试相同的前一个刷新符和一能键。 在当前进程中,SDK保留了5分钟的省略密钥;坚持明确 `idempotencyKey` 与旧的符号,当恢复必须存活 重新开始或失败。 Grantex 返回已旋转的对而不延伸 `expiresAt`;批准期满后,重新授权.

* * *

#### `grantex.tokens.verify(token)`

有撤销状态的在线令牌验证 .

```typescript
const result = await grantex.tokens.verify('eyJhbG...');
if (result.valid) {
  console.log(result.scopes);     // ['files:read']
  console.log(result.principal);  // 'usr_01J...'
  console.log(result.agent);      // 'ag_01J...'
  console.log(result.grantId);
  console.log(result.expiresAt);
}
```

#### `grantex.tokens.revoke(tokenId)`

藉由JTI撤销一个标志。 在Redis中立即被封禁;所有被下授权的令牌也被作废.

```typescript
await grantex.tokens.revoke('tok_01J...');
```

* * *

### 本地调试验证

#### `verifyGrantToken(token, options)`

用 RS256 签名密钥从已公布的 JWKS URL 中检索到的密钥, 本地校验一个赠信符 。 一个受限的处理级解析器缓存再利用每个正常的JWKS URI的有效密钥;初始取回和密钥旋转刷新可能需要网络访问.

```typescript
import { verifyGrantToken } from '@grantex/sdk';

const grant = await verifyGrantToken('eyJhbG...', {
  jwksUri: 'https://api.grantex.dev/.well-known/jwks.json',
  issuer: 'https://grantex.dev',   // optional when issuer differs from JWKS host
  requiredScopes: ['files:read'],   // optional — rejects if missing
  audience: 'https://myapp.com',    // optional — validates aud claim
});
```

如果您通过原始 Cloud 运行 URL 或另一个内部主机调用部署, 但服务标志为条形的公有领域, 请通过 `issuer` 当然 否则发行者验证会拒绝有效的符号,因为JWT `iss` 索赔将不符合运输主机.

**回返**数字 : `VerifiedGrant`

| 外地 | 类型 | 说明 |
| --- | --- | --- |
| `tokenId` | `string` | 独一无二的代号( JWT) `jti` 索赔) |
| `grantId` | `string` | 格兰特记录 |
| `principalId` | `string` | 授权发放补助金的用户`sub` 索赔) |
| `agentDid` | `string` | 代理已经做了(`agt` 索赔) |
| `developerId` | `string` | 开发者 org ID (`dev` 索赔) |
| `scopes` | `string[]` | 授予的范围(`scp` 索赔) |
| `issuedAt` | `number` | 发布时间戳(自时代起秒) |
| `expiresAt` | `number` | 过期时间戳( 自时代起秒) |
| `parentAgentDid` | `string?` | 做父母代理人(仅授权) |
| `parentGrantId` | `string?` | 父母津贴 身份证(仅代表) |
| `delegationDepth` | `number?` | 代表团深度 (0 = 根) |

* * *

### 审计

#### `grantex.audit.log(params)`

记录代理人采取的可审计行动.

```typescript
const entry = await grantex.audit.log({
  agentId: 'ag_01J...',
  agentDid: 'did:grantex:ag_01J...',
  grantId: 'grnt_01J...',
  principalId: 'usr_01J...',
  action: 'email:send',
  metadata: { to: 'user@example.com', subject: 'Hello' },
  status: 'success',   // 'success' | 'failure' | 'blocked'
});
```

#### `grantex.audit.list(params?)`

```typescript
const { entries } = await grantex.audit.list({
  agentId: 'ag_01J...',
  action: 'email:send',
  since: '2026-01-01T00:00:00Z',
  until: '2026-02-28T23:59:59Z',
  page: 1,
  pageSize: 50,
});
```

#### `grantex.audit.get(entryId)`

```typescript
const entry = await grantex.audit.get('alog_01J...');
console.log(entry.hash);      // SHA-256 hash for tamper evidence
console.log(entry.prevHash);   // previous entry hash (chain integrity)
```

* * *

### 网络呼号

#### `grantex.webhooks.create(params)`

```typescript
const webhook = await grantex.webhooks.create({
  url: 'https://myapp.com/webhooks/grantex',
  events: ['grant.created', 'grant.revoked', 'token.issued'],
});
console.log(webhook.secret); // HMAC secret for signature verification
```

#### `grantex.webhooks.list()`

```typescript
const { webhooks } = await grantex.webhooks.list();
```

#### `grantex.webhooks.delete(webhookId)`

```typescript
await grantex.webhooks.delete('wh_01J...');
```

#### Webhook 签名验证

```typescript
import { verifyWebhookSignature } from '@grantex/sdk';

// In your webhook handler
verifyWebhookSignature(requestBody, signatureHeader, webhookSecret);
```

* * *

### 政策

为特工制定精细的准入控制规则.

#### `grantex.policies.create(params)`

```typescript
const policy = await grantex.policies.create({
  name: 'Block after hours',
  effect: 'deny',
  priority: 10,
  scopes: ['email:send'],
  timeOfDayStart: '18:00',
  timeOfDayEnd: '08:00',
});
```

#### `grantex.policies.list()`

```typescript
const { policies, total } = await grantex.policies.list();
```

#### `grantex.policies.get(policyId)` 编号 : `update(policyId, params)` 编号 : `delete(policyId)`

```typescript
const policy = await grantex.policies.get('pol_01J...');

await grantex.policies.update('pol_01J...', { effect: 'allow' });

await grantex.policies.delete('pol_01J...');
```

* * *

### 遵守情况

#### `grantex.compliance.getSummary(params?)`

```typescript
const summary = await grantex.compliance.getSummary({
  since: '2026-01-01T00:00:00Z',
  until: '2026-02-28T23:59:59Z',
});
console.log(summary.agents);        // { total, active, suspended, revoked }
console.log(summary.grants);        // { total, active, revoked, expired }
console.log(summary.auditEntries);  // { total, success, failure, blocked }
```

#### `grantex.compliance.exportGrants(params?)`

```typescript
const { grants, total } = await grantex.compliance.exportGrants({
  status: 'active',
});
```

#### `grantex.compliance.exportAudit(params?)`

```typescript
const { entries, total } = await grantex.compliance.exportAudit({
  since: '2026-01-01T00:00:00Z',
  agentId: 'ag_01J...',
});
```

#### `grantex.compliance.evidencePack(params?)`

生成完整的 SOC 2 / GDPR 证据包并附有审计链完整性验证.

```typescript
const pack = await grantex.compliance.evidencePack({
  framework: 'soc2',   // 'soc2' | 'gdpr' | 'all'
  since: '2026-01-01T00:00:00Z',
});

console.log(pack.chainIntegrity.valid);          // true
console.log(pack.chainIntegrity.checkedEntries);  // 1042
console.log(pack.summary);
console.log(pack.grants);
console.log(pack.auditEntries);
console.log(pack.policies);
```

* * *

### 异常检测

在0.7.0版本中, `grantex.anomalies.getResponsePolicy()` 财务报告和审定财务报表 `grantex.anomalies.setResponsePolicy('alert_only')` 控制整个账户 服务器操作员启用后遗留的检测器的响应 `IRREGULARITY_RESPONSE_POLICY_ENABLED=true`。默认行为取消活动 给高/关键发现的代理人的补助。 仅保留警报结果 没有自动取消的事件。 此设置不禁用其他 安全控制系统.

版本0.7.0也支持 `grantex.webauthn.createEnrollmentSession({ principalId, authRequestId? })`。 。 。 . 只有验证客户身份后才能在您的服务器上调用 。 交付 返回该客户端的一用主机链接; 永远不要曝光 API 密钥 或登录链接。 主机登录需要服务器默认关闭 `PASSKEY_ENROLLMENT_ENABLED=true` 设置。 现场同意没有密码,或者 沙盒倒转.

#### `grantex.anomalies.detect()`

对所有特工进行异常探测.

```typescript
const { anomalies, total } = await grantex.anomalies.detect();
// anomaly types: 'rate_spike' | 'high_failure_rate' | 'new_principal' | 'off_hours_activity'
```

#### `grantex.anomalies.list(params?)`

```typescript
const { anomalies } = await grantex.anomalies.list({
  unacknowledged: true,  // only open anomalies
});
```

#### `grantex.anomalies.acknowledge(anomalyId)`

```typescript
const anomaly = await grantex.anomalies.acknowledge('anom_01J...');
```

* * *

### 计费

#### `grantex.billing.getSubscription()`

```typescript
const sub = await grantex.billing.getSubscription();
console.log(sub.plan);             // 'free' | 'pro' | 'enterprise'
console.log(sub.status);           // 'active' | 'past_due' | 'canceled'
console.log(sub.currentPeriodEnd); // ISO 8601 or null
```

#### `grantex.billing.createCheckout(params)`

```typescript
const { checkoutUrl } = await grantex.billing.createCheckout({
  plan: 'pro',
  successUrl: 'https://myapp.com/billing/success',
  cancelUrl: 'https://myapp.com/billing/cancel',
});
// Redirect user to checkoutUrl
```

#### `grantex.billing.createPortal(params)`

```typescript
const { portalUrl } = await grantex.billing.createPortal({
  returnUrl: 'https://myapp.com/settings',
});
```

* * *

### SCIM 2.0 供给

从身份提供者同步用户 .

#### 托肯管理

```typescript
// Create a SCIM bearer token
const { token, id, label } = await grantex.scim.createToken({
  label: 'Okta SCIM integration',
});
// token is returned once — store it securely

const { tokens } = await grantex.scim.listTokens();

await grantex.scim.revokeToken('scimtok_01J...');
```

#### 用户操作

```typescript
// List provisioned users
const { Resources, totalResults } = await grantex.scim.listUsers({
  startIndex: 1,
  count: 100,
});

// Create a user
const user = await grantex.scim.createUser({
  userName: 'alice@example.com',
  displayName: 'Alice',
  emails: [{ value: 'alice@example.com', primary: true }],
});

// Get / Replace / Patch / Delete
const user = await grantex.scim.getUser('scimusr_01J...');

await grantex.scim.replaceUser('scimusr_01J...', { userName: 'alice@new.com' });

await grantex.scim.updateUser('scimusr_01J...', [
  { op: 'replace', path: 'active', value: false },
]);

await grantex.scim.deleteUser('scimusr_01J...');
```

* * *

### 证交所(OIDC)

#### `grantex.sso.createConfig(params)`

```typescript
const config = await grantex.sso.createConfig({
  issuerUrl: 'https://accounts.google.com',
  clientId: 'xxx.apps.googleusercontent.com',
  clientSecret: 'GOCSPX-...',
  redirectUri: 'https://myapp.com/auth/callback',
});
```

#### `grantex.sso.getConfig()` 编号 : `deleteConfig()`

```typescript
const config = await grantex.sso.getConfig();
await grantex.sso.deleteConfig();
```

#### `grantex.sso.getLoginUrl(org)`

```typescript
const { authorizeUrl } = await grantex.sso.getLoginUrl('dev_01J...');
// Redirect user to authorizeUrl
```

#### `grantex.sso.handleCallback(code, state)`

```typescript
const { email, name, sub, developerId } = await grantex.sso.handleCallback(code, state);
```

0.8.2版本类型 `sessionToken` 作为可选企业召回字段 当服务器允许人类SSO会话时. 标志是 不透明无记名证书,而不是 `sessionId` 审计标识符; 远离 木头。 主机仪表板当前使用 OIDC 和机器 API 密钥 继续用于自动化。 见 [企业SSO指南](https://docs.grantex.dev/guides/enterprise-sso)。 。 。 .

* * *

## 处理错误

所有错误延伸 `GrantexError`数字 :

```typescript
import {
  GrantexError,          // base class
  GrantexApiError,       // API returned an error (has statusCode, body, requestId)
  GrantexAuthError,      // 401/403 — invalid or missing API key
  GrantexTokenError,     // token verification failed (invalid signature, expired, etc.)
  GrantexNetworkError,   // network failure (timeout, DNS, connection refused)
} from '@grantex/sdk';

try {
  await grantex.agents.get('ag_invalid');
} catch (err) {
  if (err instanceof GrantexAuthError) {
    console.error('Auth failed:', err.statusCode);     // 401 or 403
    console.error('Request ID:', err.requestId);
  } else if (err instanceof GrantexApiError) {
    console.error('API error:', err.statusCode, err.body);
  } else if (err instanceof GrantexNetworkError) {
    console.error('Network error:', err.message, err.cause);
  }
}
```

* * *

## 所需资源

-   节点.js 18+
-   无害环境管理`"type": "module"` 或使用动态 `import()`(中文(简体) )

## 链接

-   [GitHub 图像](https://github.com/mishrasanjeev/grantex)
-   [协议规格](https://github.com/mishrasanjeev/grantex/blob/main/SPEC.md)
-   [Python SDK 键盘](https://pypi.org/project/grantex/)
-   [API 参考](https://api.grantex.dev/.well-known/jwks.json)

## 执行范围(v0.3.1)

执行工具级别权限 **任何连接器** 确定自己的清单或使用53份预先编制的清单.

```typescript
import { Grantex, ToolManifest, Permission } from '@grantex/sdk';

const grantex = new Grantex({ apiKey: 'gx_...' });

// Define a manifest for any connector — no dependency on Grantex to add support
grantex.loadManifest(new ToolManifest({
  connector: 'my-crm',
  tools: { search: Permission.READ, create_deal: Permission.WRITE, delete_account: Permission.DELETE },
}));

const result = await grantex.enforce({ grantToken: token, connector: 'my-crm', tool: 'delete_account' });
// result.allowed = false — "write scope does not permit delete operations"
```

**特征 :**

-   `enforce()` ——通过表,<1ms验证JWT+检查工具许可
-   `wrapTool()` ——自动增强LangChain工具
-   `enforceMiddleware()` ——快递/快递HTTP中件
-   定义任何连接器的自定义表: 内置, 从 JSON , 或通过 CLI 自动生成
-   53份预先编制的清单(销售部队、枢纽站、Jira、Frede、SAP、S3和另外47份)
-   权限等级 : `admin > delete > write > read`
-   允许移徙的模式(`enforceMode: 'permissive'`(中文(简体) )

[完整指南](https://docs.grantex.dev/guides/scope-enforcement) | [API 参考](https://docs.grantex.dev/sdks/typescript/enforce)

## Grantex 生态系统

| 软件包 | 说明 |
| --- | --- |
| [`grantex`](https://pypi.org/project/grantex/) | Python SDK 键盘 |
| [`@grantex/langchain`](https://www.npmjs.com/package/@grantex/langchain) | 兰彩一体化 |
| [`@grantex/autogen`](https://www.npmjs.com/package/@grantex/autogen) | 自动Gen 集成 |
| [`@grantex/vercel-ai`](https://www.npmjs.com/package/@grantex/vercel-ai) | Vercel AI SDK 集成软件 |
| [`grantex-crewai`](https://pypi.org/project/grantex-crewai/) | CrewAI 整合 |
| [`grantex-openai-agents`](https://pypi.org/project/grantex-openai-agents/) | OpenAI 代理 SDK 集成 |
| [`grantex-adk`](https://pypi.org/project/grantex-adk/) | Google ADK 集成软件 |
| [`@grantex/mcp`](https://www.npmjs.com/package/@grantex/mcp) | Claude 桌面/ cursor / Windsurf 的 MCP 服务器 |
| [`@grantex/cli`](https://www.npmjs.com/package/@grantex/cli) | 命令行工具 |

## 许可证

[Apache 2.0 (英语)](https://github.com/mishrasanjeev/grantex/blob/main/LICENSE)

## 所有权

Grantex由Orchestrum Technologies LLP所拥有. 发明者和所有者:Sanjeev Kumar。 所有权联系人: [sanjeev@orchestrum.in](mailto:sanjeev@orchestrum.in) 或者说 [mithra.sanjeev@gmail.com 互联网档案馆的存檔,存档日期2013-12-02](mailto:mishra.sanjeev@gmail.com)。 。 。 .

## 来源开发

使用节点.js 24 LTS和 `npm ci` 以 Vitest 5 构建或测试此测试. 仓库验证步骤在 [依赖性升级指南](https://docs.grantex.dev/guides/dependency-updates)。 。 。 . 源工具要求与已发布的套件运行时间支持是分开的.

> 权威加固需要类型SDK 0.8.1 (`currentAuthority`, (中文(简体) ), 不只是一个有效的JWT签名。 绑住观众 信任的人/代理人 身份,并在每次处决前检查发行人. 这样不行 创造人类同意或自动消耗行动决定/支出上限. 现有的离线默认仍为离线. 安装前核实登记册的可用性. 见 [SDK 执行权限指南](https://npmcn.com/package/docs/guides/sdk-execution-authority.mdx)。 。 。 .

## 常见问题

### @grantex/sdk 是什么？

Grantex 授权协议的脚本 SDK 类型

### 如何安装 @grantex/sdk？

在项目目录运行 npm install @grantex/sdk，或使用 pnpm add / yarn add / bun add。

### @grantex/sdk 支持 TypeScript 吗？

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

### @grantex/sdk 支持 ESM 还是 CommonJS？

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

### @grantex/sdk 需要什么版本的 Node\.js？

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

### @grantex/sdk 可以商用吗？

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

### @grantex/sdk 的下载量有多少？

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

### @grantex/sdk 还在维护吗？

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

