Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
384f611a26 | ||
|
|
f465979ec3 | ||
|
|
6fef188f2f | ||
|
|
417be3ef54 | ||
|
|
46fa2597d0 | ||
|
|
957cb04324 |
No files matched your search
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "hose-use",
|
||||
"version": "0.9.1",
|
||||
"version": "0.9.2",
|
||||
"description": "合思/易快报 (ekuaibao) 企业级 SaaS CLI 与底层 SDK:多账号登录、企业租户切换、单据明细检索、工作流管理、内置 HTTP 服务与常驻守护进程。",
|
||||
"author": {
|
||||
"name": "yingqing"
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
# hose-use (v0.9.1)
|
||||
# hose-use (v0.9.2)
|
||||
|
||||
合思/易快报(ekuaibao)企业级 CLI 命令行工具与底层 SDK。
|
||||
|
||||
@@ -32,6 +32,17 @@ hose-use version
|
||||
|
||||
> 开发版安装会覆盖当前 PATH 中的 `hose-use`,适合本机测试;发布环境请使用正式 Release 安装脚本。不要用 `npm install -g .` 代替,它会留下不会随源码更新的旧副本。
|
||||
|
||||
### AI PRO 激活(默认关闭)
|
||||
|
||||
`hose-aipro` 与 `hose-use` 是同一个二进制的两个入口,安装脚本会自动软链出 `hose-aipro`。AI PRO 默认**不激活**:
|
||||
|
||||
1. 跑 `hose-aipro version --json` 记下当前版本;
|
||||
2. 把**版本号 + 期望到期日 + 客户名**通过微信 / 邮件 / 工单等离线渠道发给服务方申请凭证;
|
||||
3. 拿到凭证后执行 `hose-aipro login '<凭证>'`(纯本地验签,不联网);
|
||||
4. `hose-aipro scopes --json` 能返回场景数据即激活成功。
|
||||
|
||||
凭证有两条约束:当前二进制版本不得高于其 `maxVersion`,当前时间不得晚于其 `exp`。完整流程与失败处理见 [hose-aipro Skill](./skills/hose-aipro/SKILL.md) 的「首次安装与激活」章节——Agent 自行安装时以该文档为准。
|
||||
|
||||
---
|
||||
|
||||
### CLI 常用命令速查 (`hose-use`)
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "hose-use",
|
||||
"version": "0.9.1",
|
||||
"version": "0.9.2",
|
||||
"module": "src/server.ts",
|
||||
"type": "module",
|
||||
"exports": {
|
||||
|
||||
+3
-1
@@ -263,5 +263,7 @@ echo " 2. List corps: hose-use corps list"
|
||||
echo " 3. List workflows: hose-use workflow list"
|
||||
echo " 4. Switch mode: hose-use config mode stateless"
|
||||
echo " 5. Self-update: hose-use update"
|
||||
echo " AI PRO alias: hose-aipro"
|
||||
echo " AI PRO alias: hose-aipro (默认未激活)"
|
||||
echo " AI PRO 申请凭证: 先跑 hose-aipro version --json,把版本号与期望到期日发给服务方"
|
||||
echo " AI PRO 激活: hose-aipro login '<凭证>'"
|
||||
echo ""
|
||||
@@ -0,0 +1,84 @@
|
||||
#!/usr/bin/env bun
|
||||
/**
|
||||
* AI PRO 离线凭证签发工具(仅签发方本地使用,不参与二进制构建)。
|
||||
*
|
||||
* 用法:
|
||||
* bun run scripts/license/issue.ts --sub "客户名称" --exp 2027-12-31 --max-version 0.9.99
|
||||
*
|
||||
* 私钥来源(优先级):
|
||||
* 1. HOSE_AIPRO_LICENSE_PRIVATE_KEY 环境变量(PEM 文本)
|
||||
* 2. HOSE_AIPRO_LICENSE_PRIVATE_FILE 环境变量(PEM 文件路径)
|
||||
* 3. ~/.config/hose-use/license/private.pem
|
||||
*
|
||||
* 私钥绝不进入仓库。exp 是绝对到期时间,脚本不施加任何时长上限。
|
||||
*/
|
||||
import { existsSync, readFileSync } from "node:fs";
|
||||
import { homedir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { randomBytes, sign } from "node:crypto";
|
||||
|
||||
const DEFAULT_PRIVATE_FILE = join(homedir(), ".config", "hose-use", "license", "private.pem");
|
||||
|
||||
function option(name: string): string | undefined {
|
||||
const prefix = `--${name}=`;
|
||||
const inline = process.argv.slice(2).find((arg) => arg.startsWith(prefix));
|
||||
if (inline) return inline.slice(prefix.length).trim();
|
||||
const index = process.argv.indexOf(`--${name}`);
|
||||
return index >= 0 ? process.argv[index + 1]?.trim() : undefined;
|
||||
}
|
||||
|
||||
function loadPrivateKeyPem(): string {
|
||||
const inline = process.env.HOSE_AIPRO_LICENSE_PRIVATE_KEY?.trim();
|
||||
if (inline) return inline.replace(/\\n/g, "\n");
|
||||
const configured = process.env.HOSE_AIPRO_LICENSE_PRIVATE_FILE?.trim();
|
||||
const file = configured || DEFAULT_PRIVATE_FILE;
|
||||
if (!existsSync(file)) {
|
||||
throw new Error(`找不到签发私钥: ${file}\n请设置 HOSE_AIPRO_LICENSE_PRIVATE_KEY 或 HOSE_AIPRO_LICENSE_PRIVATE_FILE`);
|
||||
}
|
||||
return readFileSync(file, "utf-8");
|
||||
}
|
||||
|
||||
function parseExpiry(raw: string | undefined): number {
|
||||
if (!raw) throw new Error("缺少 --exp(绝对到期时间,如 2027-12-31 或 Unix 秒)");
|
||||
if (/^\d+$/.test(raw)) return Number(raw);
|
||||
const parsed = Date.parse(raw);
|
||||
if (Number.isNaN(parsed)) throw new Error(`无法解析到期时间: ${raw}`);
|
||||
return Math.floor(parsed / 1000);
|
||||
}
|
||||
|
||||
function main(): void {
|
||||
const sub = option("sub");
|
||||
const maxVersion = option("max-version");
|
||||
if (!sub) throw new Error("缺少 --sub(授权对象标识)");
|
||||
if (!maxVersion || !/^\d+\.\d+\.\d+$/.test(maxVersion)) {
|
||||
throw new Error("缺少或非法的 --max-version(应为 x.y.z)");
|
||||
}
|
||||
|
||||
const exp = parseExpiry(option("exp"));
|
||||
const payload = {
|
||||
v: 1 as const,
|
||||
sub,
|
||||
exp,
|
||||
maxVersion,
|
||||
features: ["aipro"],
|
||||
nonce: randomBytes(12).toString("base64url"),
|
||||
};
|
||||
|
||||
const payloadBytes = Buffer.from(JSON.stringify(payload), "utf-8");
|
||||
const signature = sign(null, payloadBytes, loadPrivateKeyPem());
|
||||
const token = `${payloadBytes.toString("base64url")}.${Buffer.from(signature).toString("base64url")}`;
|
||||
|
||||
console.log(`授权对象 : ${sub}`);
|
||||
console.log(`到期时间 : ${new Date(exp * 1000).toISOString().slice(0, 10)}`);
|
||||
console.log(`版本上限 : v${maxVersion}`);
|
||||
console.log(`凭证编号 : ${payload.nonce}`);
|
||||
console.log("");
|
||||
console.log(token);
|
||||
}
|
||||
|
||||
try {
|
||||
main();
|
||||
} catch (error) {
|
||||
console.error(`[签发失败] ${error instanceof Error ? error.message : String(error)}`);
|
||||
process.exit(1);
|
||||
}
|
||||
@@ -2,11 +2,11 @@
|
||||
name: hose-aipro
|
||||
description: "合思 AI PRO(EASO AI PRO)确定性审批仲裁网关 CLI 与技能套件:单据挂载绑定、事实证据核验与打标 (PASS/FAIL/SKIP)、审核要点/规则场景库检索、确定性审批仲裁(同意/驳回/转人工硬阻断)、审计轨迹日志查询与常驻服务管理。用于一切合思 AI PRO 确定性审批仲裁与要点核验请求。"
|
||||
metadata:
|
||||
version: 0.9.1
|
||||
version: 0.9.2
|
||||
short-description: 合思 AI PRO 确定性审批仲裁网关与审核要点核验 skill
|
||||
---
|
||||
|
||||
# hose-aipro (v0.9.1)
|
||||
# hose-aipro (v0.9.2)
|
||||
|
||||
合思 AI PRO 确定性审批仲裁网关是专门面向企业财务核算、单据审核与自动化合规风控的确定性仲裁命令行与 SDK。
|
||||
|
||||
@@ -32,6 +32,89 @@ metadata:
|
||||
|
||||
---
|
||||
|
||||
## 首次安装与激活(Agent 操作序列)
|
||||
|
||||
> [!IMPORTANT]
|
||||
> AI PRO **默认不激活**。装完二进制后,业务命令一律返回 `AIPRO_NOT_ACTIVATED`。
|
||||
> 凭证**不能由 Agent 自行生成**——客户端只内嵌验签公钥,私钥在服务方手里。
|
||||
> 遇到未激活时,Agent 必须停下来向人类用户索取凭证;不要尝试绕过门禁、不要改系统时间、不要伪造或拼接凭证。
|
||||
|
||||
### 步骤 0 · 安装二进制(若尚未安装)
|
||||
|
||||
```bash
|
||||
curl -fsSL https://raw.githubusercontent.com/yunyingk/hose-use/main/scripts/install.sh | bash
|
||||
```
|
||||
|
||||
脚本下载 Release 二进制并校验 SHA-256 清单,安装同一个 `hose-use` 后软链出 `hose-aipro`,同时把两份 Skill 装到 `~/.agents/skills/`。升级用 `hose-use update`。
|
||||
|
||||
### 步骤 1 · 确认版本(申请凭证的必要信息)
|
||||
|
||||
```bash
|
||||
hose-aipro version --json
|
||||
```
|
||||
|
||||
记下 `version` 字段。申请凭证时必须把它交给服务方,服务方据此设定凭证的 `maxVersion`。
|
||||
|
||||
### 步骤 2 · 判断是否已激活
|
||||
|
||||
```bash
|
||||
hose-aipro scopes --json
|
||||
```
|
||||
|
||||
- 返回场景数组 → 已激活,直接跳到步骤 5。
|
||||
- 返回 `{"code":"AIPRO_NOT_ACTIVATED","reason":"missing"}` → 未激活,继续步骤 3。
|
||||
|
||||
`status` / `help` / `version` 属自省命令,未激活也能运行;`scopes` 等业务命令一律受统一门禁管辖。
|
||||
|
||||
### 步骤 3 · 向服务方申请凭证(Agent 在此停下)
|
||||
|
||||
把下表交给人类用户,由用户通过微信 / 邮件 / 工单等**离线渠道**向服务方申请:
|
||||
|
||||
| 需要提供的信息 | 来源 |
|
||||
|---|---|
|
||||
| 当前二进制版本 | 步骤 1 的 `version` |
|
||||
| 期望到期日 | 用户决定;凭证里是绝对到期时间 `exp` |
|
||||
| 客户名 / 用途标识 | 用户决定;会写进凭证的 `sub` |
|
||||
|
||||
服务方返回一串凭证文本。**Agent 不要自己生成、不要拼接、不要修改、不要截断这串文本**;含点号与特殊字符时务必用单引号包裹。
|
||||
|
||||
### 步骤 4 · 本地激活
|
||||
|
||||
```bash
|
||||
hose-aipro login '<凭证>'
|
||||
# 等价写法
|
||||
hose-aipro login --token='<凭证>'
|
||||
```
|
||||
|
||||
纯本地验签并落盘,**不联网**。凭证写到 `~/.config/hose-use/aipro-license.token`(0600);可用 `HOSE_AIPRO_LICENSE_FILE` 环境变量指向别的位置。
|
||||
|
||||
### 步骤 5 · 验证
|
||||
|
||||
```bash
|
||||
hose-aipro scopes --json
|
||||
```
|
||||
|
||||
返回真实场景数据即激活成功。`hose-aipro login --json` 会输出授权对象、到期时间与版本上限。
|
||||
|
||||
### 失败原因与处理
|
||||
|
||||
| `reason` | 含义 | 处理 |
|
||||
|---|---|---|
|
||||
| `missing` | 未激活 | 走步骤 3 申请凭证 |
|
||||
| `expired` | 已超过 `exp` 绝对到期时间 | 重新申请凭证 |
|
||||
| `version_exceeded` | 当前版本高于 `maxVersion` | **不要降级二进制**,重新申请更高 `maxVersion` 的凭证 |
|
||||
| `bad_signature` | 凭证被篡改或复制不完整 | 重新复制完整凭证,检查引号与换行 |
|
||||
| `no_feature` / `malformed` | 凭证不含 AI PRO 授权或格式错误 | 重新申请凭证 |
|
||||
|
||||
### 两条约束
|
||||
|
||||
- 当前二进制版本不得高于凭证的 `maxVersion`(三段数字比较,忽略 `-dev` 后缀)。**升级二进制超过上限会立刻失效**,需重新申请。
|
||||
- 当前时间不得晚于凭证的 `exp`(绝对到期时间)。客户端不做设备绑定、不做时钟防篡改。
|
||||
|
||||
凭证是 Ed25519 签名数据,不是二进制变体:所有客户下载的是**同一个二进制**,区别只在本地有没有凭证文件。新增任意 AI PRO 命令自动受统一门禁管辖。
|
||||
|
||||
---
|
||||
|
||||
## 快速自省与运行上下文 (Zero-Source-Reading)
|
||||
|
||||
在开始执行任何审批仲裁任务前,优先执行自省命令建立当前上下文:
|
||||
|
||||
@@ -2,11 +2,11 @@
|
||||
name: hose-use
|
||||
description: "合思/易快报(Ekuaibao)企业级 SaaS 一站式能力:hose-use CLI/SDK 多账号登录、租户切换、单据检索与审批动作、自建应用与工作流扫描、密钥与应用中心、常驻守护进程与 HTTP 文档/OpenAPI,以及工作流 MVEL 代码节点脚本生成调试、节点批量开通。用于一切合思/易快报相关请求。"
|
||||
metadata:
|
||||
version: 0.9.1
|
||||
version: 0.9.2
|
||||
short-description: 合思/易快报 企业级 CLI 与工作流 skill 套件(含 MVEL 代码节点)
|
||||
---
|
||||
|
||||
# hose-use (v0.9.1)
|
||||
# hose-use (v0.9.2)
|
||||
|
||||
在具备 MCP 的 AI 智能体环境中,**优先使用 `hose_cli` 单工具网关**,传入 `command: string` 执行;在终端或自动化脚本中,直接调用全局 `hose` 或 `hose-use` 命令行。
|
||||
本 Skill 是智能体的路由分发层:保持主文档简明,遇到复杂业务时深入查阅对应的专属参考文档(`references/*.md`)。
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
openapi: 3.1.0
|
||||
info:
|
||||
title: hose-use API & MCP Tools Specification
|
||||
version: 0.9.1
|
||||
version: 0.9.2
|
||||
description: >-
|
||||
Unified Enterprise SaaS API, CLI, and MCP Specification for Ekuaibao (合思/易快报), EASO, and Piper Workflows.
|
||||
servers:
|
||||
|
||||
+1
-1
@@ -2,7 +2,7 @@
|
||||
"openapi": "3.1.0",
|
||||
"info": {
|
||||
"title": "hose-use API & MCP Tools Specification",
|
||||
"version": "0.9.1",
|
||||
"version": "0.9.2",
|
||||
"description": "Unified Enterprise SaaS API, CLI, and MCP Specification for Ekuaibao (合思/易快报), EASO, and Piper Workflows."
|
||||
},
|
||||
"servers": [
|
||||
|
||||
@@ -1,9 +1,14 @@
|
||||
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
|
||||
import { generateKeyPairSync, sign } from "node:crypto";
|
||||
import { mkdtempSync, rmSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { runAiProCli } from "./aipro-cli.js";
|
||||
import { closeDatabase, getDatabase } from "./core/db/index.js";
|
||||
import { ApprovalRepository } from "./domains/approval/repository.js";
|
||||
import { getVersionInfo } from "./version.js";
|
||||
import { COMMAND_METADATA } from "./cli/command-metadata.js";
|
||||
import { setAiProLicenseDeps, resetAiProLicenseDeps, saveAiProLicenseToken } from "./cli/aipro-license.js";
|
||||
import {
|
||||
AIPRO_COMMAND_REGISTRY,
|
||||
findAiProCommand,
|
||||
@@ -12,7 +17,28 @@ import {
|
||||
} from "./cli/aipro-registry.js";
|
||||
|
||||
describe("CLI - hose-aipro 审批流与网关阻拦全链路测试", () => {
|
||||
let licenseDir = "";
|
||||
|
||||
beforeEach(() => {
|
||||
// 门禁默认关闭:注入临时密钥对与有效凭证,让原有全链路用例无需改动
|
||||
licenseDir = mkdtempSync(join(tmpdir(), "hose-aipro-cli-license-"));
|
||||
process.env.HOSE_AIPRO_LICENSE_FILE = join(licenseDir, "license.token");
|
||||
const pair = generateKeyPairSync("ed25519");
|
||||
const publicKeyPem = pair.publicKey.export({ type: "spki", format: "pem" }) as string;
|
||||
const privateKeyPem = pair.privateKey.export({ type: "pkcs8", format: "pem" }) as string;
|
||||
const licensePayload = {
|
||||
v: 1,
|
||||
sub: "集成测试",
|
||||
exp: Math.floor(Date.now() / 1000) + 86_400,
|
||||
maxVersion: "99.99.99",
|
||||
features: ["aipro"],
|
||||
nonce: "integration",
|
||||
};
|
||||
const payloadBytes = Buffer.from(JSON.stringify(licensePayload), "utf-8");
|
||||
const signature = sign(null, payloadBytes, privateKeyPem);
|
||||
saveAiProLicenseToken(`${payloadBytes.toString("base64url")}.${Buffer.from(signature).toString("base64url")}`);
|
||||
setAiProLicenseDeps({ publicKeyPem, version: "0.9.1" });
|
||||
|
||||
process.env.HOSE_APPROVAL_DB = ":memory:";
|
||||
const db = getDatabase(":memory:");
|
||||
const repo = new ApprovalRepository(db);
|
||||
@@ -31,6 +57,9 @@ describe("CLI - hose-aipro 审批流与网关阻拦全链路测试", () => {
|
||||
afterEach(() => {
|
||||
closeDatabase();
|
||||
delete process.env.HOSE_APPROVAL_DB;
|
||||
delete process.env.HOSE_AIPRO_LICENSE_FILE;
|
||||
resetAiProLicenseDeps();
|
||||
rmSync(licenseDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
test("version/help --json only emit machine-readable stdout", async () => {
|
||||
|
||||
@@ -15,6 +15,7 @@ import {
|
||||
handleSaasPlatformRedirect,
|
||||
} from "./cli/aipro-registry.js";
|
||||
import { handleAiProHelp } from "./cli/commands/aipro/status.js";
|
||||
import { assertAiProEnabled, handleAiProLogin } from "./cli/aipro-license.js";
|
||||
import type { AiProExecutionContext } from "./cli/commands/aipro/types.js";
|
||||
|
||||
export async function runAiProCli(
|
||||
@@ -97,11 +98,22 @@ async function runAiProCliOnce(rawArgs: string[]): Promise<{ stdout: string; std
|
||||
};
|
||||
|
||||
try {
|
||||
if (command === "login" || command === "activate") {
|
||||
return handleAiProLogin(rawArgs, jsonMode);
|
||||
}
|
||||
if (booleanOption(parsed.options, ["version", "v"])) {
|
||||
const versionDef = findAiProCommand("version");
|
||||
if (versionDef) return await versionDef.handler(ctx);
|
||||
}
|
||||
|
||||
// 统一门禁:除只读自省命令外,其余 AI PRO 命令一律要求有效凭证。
|
||||
// 以后新增命令只需照常注册,自动被此处拦截,无需改动授权代码。
|
||||
const readOnly = new Set(["status", "whoami", "context", "info", "help", "version", "v"]);
|
||||
if (!readOnly.has(command)) {
|
||||
const licenseGate = assertAiProEnabled(jsonMode);
|
||||
if (licenseGate) return licenseGate;
|
||||
}
|
||||
|
||||
const commandDef = findAiProCommand(command);
|
||||
if (commandDef) {
|
||||
return await commandDef.handler(ctx);
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
|
||||
import { generateKeyPairSync, sign } from "node:crypto";
|
||||
import { mkdtempSync, rmSync, statSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import {
|
||||
assertAiProEnabled,
|
||||
checkAiProLicense,
|
||||
compareBaseVersion,
|
||||
handleAiProLogin,
|
||||
resetAiProLicenseDeps,
|
||||
saveAiProLicenseToken,
|
||||
setAiProLicenseDeps,
|
||||
verifyAiProLicenseToken,
|
||||
} from "./aipro-license.js";
|
||||
|
||||
let tempDir = "";
|
||||
let privateKeyPem = "";
|
||||
|
||||
function issue(overrides: Record<string, unknown> = {}): string {
|
||||
const payload = {
|
||||
v: 1,
|
||||
sub: "测试客户",
|
||||
exp: 4_102_444_800,
|
||||
maxVersion: "0.9.99",
|
||||
features: ["aipro"],
|
||||
nonce: "test-nonce",
|
||||
...overrides,
|
||||
};
|
||||
const bytes = Buffer.from(JSON.stringify(payload), "utf-8");
|
||||
const signature = sign(null, bytes, privateKeyPem);
|
||||
return `${bytes.toString("base64url")}.${Buffer.from(signature).toString("base64url")}`;
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
tempDir = mkdtempSync(join(tmpdir(), "hose-aipro-license-"));
|
||||
process.env.HOSE_AIPRO_LICENSE_FILE = join(tempDir, "license.token");
|
||||
const pair = generateKeyPairSync("ed25519");
|
||||
const publicKeyPem = pair.publicKey.export({ type: "spki", format: "pem" }) as string;
|
||||
privateKeyPem = pair.privateKey.export({ type: "pkcs8", format: "pem" }) as string;
|
||||
setAiProLicenseDeps({ publicKeyPem, version: "0.9.1", nowSeconds: 1_700_000_000 });
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
resetAiProLicenseDeps();
|
||||
delete process.env.HOSE_AIPRO_LICENSE_FILE;
|
||||
rmSync(tempDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
describe("版本上限", () => {
|
||||
test("三段数字比较,dev 后缀被忽略", () => {
|
||||
expect(compareBaseVersion("0.9.1-dev.2+gabc", "0.9.99")).toBe(-1);
|
||||
expect(compareBaseVersion("0.10.0", "0.9.99")).toBe(1);
|
||||
expect(compareBaseVersion("0.9.99-dev.3+gXXX", "0.9.99")).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("双约束校验", () => {
|
||||
test("有效凭证放行", () => {
|
||||
expect(verifyAiProLicenseToken(issue()).ok).toBe(true);
|
||||
});
|
||||
|
||||
test("签名被篡改拒绝", () => {
|
||||
const [payload] = issue().split(".");
|
||||
const forged = `${payload}.${Buffer.from("bad").toString("base64url")}`;
|
||||
expect(verifyAiProLicenseToken(forged)).toMatchObject({ ok: false, reason: "bad_signature" });
|
||||
});
|
||||
|
||||
test("payload 改动后签名失配", () => {
|
||||
const [payload, signature] = issue().split(".");
|
||||
const decoded = JSON.parse(Buffer.from(payload, "base64url").toString("utf-8"));
|
||||
decoded.exp = 9_999_999_999;
|
||||
const forged = `${Buffer.from(JSON.stringify(decoded)).toString("base64url")}.${signature}`;
|
||||
expect(verifyAiProLicenseToken(forged)).toMatchObject({ ok: false, reason: "bad_signature" });
|
||||
});
|
||||
|
||||
test("超过绝对到期时间拒绝", () => {
|
||||
setAiProLicenseDeps({ nowSeconds: 4_102_444_801 });
|
||||
expect(verifyAiProLicenseToken(issue())).toMatchObject({ ok: false, reason: "expired" });
|
||||
});
|
||||
|
||||
test("当前版本超过上限拒绝,等于上限放行", () => {
|
||||
setAiProLicenseDeps({ version: "0.10.0" });
|
||||
expect(verifyAiProLicenseToken(issue())).toMatchObject({ ok: false, reason: "version_exceeded" });
|
||||
setAiProLicenseDeps({ version: "0.9.99" });
|
||||
expect(verifyAiProLicenseToken(issue()).ok).toBe(true);
|
||||
});
|
||||
|
||||
test("缺少 aipro feature 拒绝", () => {
|
||||
expect(verifyAiProLicenseToken(issue({ features: ["other"] }))).toMatchObject({ ok: false, reason: "no_feature" });
|
||||
});
|
||||
|
||||
test("格式错误与非法版本上限拒绝", () => {
|
||||
expect(verifyAiProLicenseToken("not-a-token")).toMatchObject({ ok: false, reason: "malformed" });
|
||||
expect(verifyAiProLicenseToken(issue({ maxVersion: "latest" }))).toMatchObject({ ok: false, reason: "malformed" });
|
||||
});
|
||||
});
|
||||
|
||||
describe("统一门禁与激活", () => {
|
||||
test("默认无凭证即未激活,门禁拦截", () => {
|
||||
expect(checkAiProLicense()).toMatchObject({ ok: false, reason: "missing" });
|
||||
const blocked = assertAiProEnabled(false);
|
||||
expect(blocked?.exitCode).toBe(1);
|
||||
expect(blocked?.stderr).toContain("尚未激活");
|
||||
});
|
||||
|
||||
test("login 激活后门禁放行", () => {
|
||||
const result = handleAiProLogin(["login", issue()], false);
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain("已激活");
|
||||
expect(assertAiProEnabled(false)).toBeNull();
|
||||
});
|
||||
|
||||
test("无效凭证激活失败且不落盘", () => {
|
||||
const result = handleAiProLogin(["login", "forged.token"], false);
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(checkAiProLicense()).toMatchObject({ ok: false, reason: "missing" });
|
||||
});
|
||||
|
||||
test("缺少凭证返回用法提示", () => {
|
||||
expect(handleAiProLogin(["login"], false).exitCode).toBe(2);
|
||||
});
|
||||
|
||||
test("json 模式拦截返回结构化错误", () => {
|
||||
const blocked = assertAiProEnabled(true);
|
||||
expect(blocked?.stderr).toBe("");
|
||||
expect(JSON.parse(blocked?.stdout ?? "{}")).toMatchObject({ code: "AIPRO_NOT_ACTIVATED", reason: "missing" });
|
||||
});
|
||||
|
||||
test("凭证文件权限为 0600", () => {
|
||||
saveAiProLicenseToken(issue());
|
||||
expect(statSync(join(tempDir, "license.token")).mode & 0o777).toBe(0o600);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,234 @@
|
||||
/**
|
||||
* AI PRO 离线授权:单文件,唯一门禁入口由 aipro-cli.ts 调用。
|
||||
*
|
||||
* 新增任意 AI PRO 命令都不需要改动本文件——门禁在分发层统一拦截。
|
||||
* 唯一例外是 login / activate,在门禁之前分流。
|
||||
*
|
||||
* 凭证:base64url(payload).base64url(Ed25519 签名)
|
||||
* payload:{ v, sub, exp, maxVersion, features, nonce }
|
||||
* 两条约束:当前版本 <= maxVersion;当前时间 <= exp(绝对到期,Unix 秒)。
|
||||
* 刻意不做:设备绑定、时钟防篡改、激活时间锚点、相对时长上限。
|
||||
*/
|
||||
import { createPublicKey, verify } from "node:crypto";
|
||||
import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
||||
import { homedir } from "node:os";
|
||||
import { dirname, join } from "node:path";
|
||||
import { VERSION } from "../version.js";
|
||||
import { parseArgs, stringOption } from "./parser.js";
|
||||
import { printJson } from "./printer.js";
|
||||
import type { CliResult } from "./types.js";
|
||||
|
||||
/** 验签公钥(随源码编译进二进制)。私钥由签发方离线保管,绝不进仓库。
|
||||
* SHA-256(SPKI DER): f5ead0d75667c259afae00474040177012fa2de4509e6dfa9c2eb7c25f1ad403
|
||||
* 更换此公钥会使所有已签发凭证失效,发版后不得随意变更。
|
||||
*/
|
||||
const PUBLIC_KEY = `-----BEGIN PUBLIC KEY-----
|
||||
MCowBQYDK2VwAyEA0e0mcz9TnKnVJAEmr96mOc+9OineoekA3tY/UhGE7mo=
|
||||
-----END PUBLIC KEY-----`;
|
||||
|
||||
export const AIPRO_LICENSE_FILE_ENV = "HOSE_AIPRO_LICENSE_FILE";
|
||||
|
||||
interface LicensePayload {
|
||||
v: 1;
|
||||
sub: string;
|
||||
exp: number;
|
||||
maxVersion: string;
|
||||
features: string[];
|
||||
nonce: string;
|
||||
}
|
||||
|
||||
export type LicenseCheck =
|
||||
| { ok: true; payload: LicensePayload }
|
||||
| { ok: false; reason: "missing" | "malformed" | "bad_signature" | "no_feature" | "expired" | "version_exceeded"; message: string };
|
||||
|
||||
interface LicenseDeps {
|
||||
publicKeyPem: string;
|
||||
version: string;
|
||||
nowSeconds?: number;
|
||||
}
|
||||
|
||||
const defaults: LicenseDeps = { publicKeyPem: PUBLIC_KEY.trim(), version: VERSION };
|
||||
let deps: LicenseDeps = { ...defaults };
|
||||
|
||||
/** 进程内依赖注入,仅供单元测试使用;CLI 运行时不暴露。 */
|
||||
export function setAiProLicenseDeps(partial: Partial<LicenseDeps>): void {
|
||||
deps = { ...deps, ...partial };
|
||||
}
|
||||
|
||||
export function resetAiProLicenseDeps(): void {
|
||||
deps = { ...defaults };
|
||||
}
|
||||
|
||||
export function resolveAiProLicenseFile(): string {
|
||||
const explicit = process.env[AIPRO_LICENSE_FILE_ENV]?.trim();
|
||||
if (explicit) return explicit;
|
||||
const stateDir = process.env.HOSE_STATE_DIR?.trim();
|
||||
if (stateDir) return join(stateDir, "aipro-license.token");
|
||||
return join(homedir(), ".config", "hose-use", "aipro-license.token");
|
||||
}
|
||||
|
||||
export function saveAiProLicenseToken(token: string): string {
|
||||
const file = resolveAiProLicenseFile();
|
||||
mkdirSync(dirname(file), { recursive: true, mode: 0o700 });
|
||||
writeFileSync(file, token.trim(), { encoding: "utf-8", mode: 0o600 });
|
||||
try {
|
||||
chmodSync(file, 0o600);
|
||||
} catch {
|
||||
// 写入时的 mode 已生效
|
||||
}
|
||||
return file;
|
||||
}
|
||||
|
||||
function loadToken(): string | null {
|
||||
try {
|
||||
const file = resolveAiProLicenseFile();
|
||||
return existsSync(file) ? readFileSync(file, "utf-8").trim() || null : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** 只取 x.y.z 三段数字,忽略 -dev.N+gXXX 等后缀。 */
|
||||
export function compareBaseVersion(a: string, b: string): number {
|
||||
const parse = (v: string): [number, number, number] | null => {
|
||||
const m = v.match(/^(\d+)\.(\d+)\.(\d+)/);
|
||||
return m ? [Number(m[1]), Number(m[2]), Number(m[3])] : null;
|
||||
};
|
||||
const left = parse(a);
|
||||
const right = parse(b);
|
||||
if (!left || !right) throw new Error(`非法版本号: ${a} 或 ${b}`);
|
||||
for (let i = 0; i < 3; i += 1) {
|
||||
if (left[i] !== right[i]) return left[i] > right[i] ? 1 : -1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
function parsePayload(text: string): LicensePayload | null {
|
||||
try {
|
||||
const p = JSON.parse(text);
|
||||
if (p.v !== 1 || typeof p.sub !== "string" || !p.sub) return null;
|
||||
if (!Number.isInteger(p.exp) || p.exp <= 0) return null;
|
||||
if (typeof p.maxVersion !== "string" || !/^\d+\.\d+\.\d+$/.test(p.maxVersion)) return null;
|
||||
if (!Array.isArray(p.features) || !p.features.every((f: unknown) => typeof f === "string")) return null;
|
||||
if (typeof p.nonce !== "string" || !p.nonce) return null;
|
||||
return p as LicensePayload;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function verifyAiProLicenseToken(token: string): LicenseCheck {
|
||||
const parts = token.trim().split(".");
|
||||
if (parts.length !== 2 || !parts[0] || !parts[1]) {
|
||||
return { ok: false, reason: "malformed", message: "凭证格式错误:应为 <payload>.<signature> 两段" };
|
||||
}
|
||||
|
||||
let payloadBytes: Buffer;
|
||||
let signature: Buffer;
|
||||
try {
|
||||
payloadBytes = Buffer.from(parts[0], "base64url");
|
||||
signature = Buffer.from(parts[1], "base64url");
|
||||
} catch {
|
||||
return { ok: false, reason: "malformed", message: "凭证编码错误:无法按 base64url 解码" };
|
||||
}
|
||||
|
||||
let valid = false;
|
||||
try {
|
||||
valid = verify(null, payloadBytes, createPublicKey(deps.publicKeyPem), signature);
|
||||
} catch {
|
||||
valid = false;
|
||||
}
|
||||
if (!valid) return { ok: false, reason: "bad_signature", message: "凭证签名无效,可能被篡改或并非本工具签发" };
|
||||
|
||||
const payload = parsePayload(payloadBytes.toString("utf-8"));
|
||||
if (!payload) return { ok: false, reason: "malformed", message: "凭证内容无效:字段缺失或格式不符" };
|
||||
if (!payload.features.includes("aipro")) {
|
||||
return { ok: false, reason: "no_feature", message: "该凭证未包含 AI PRO 授权" };
|
||||
}
|
||||
|
||||
const now = deps.nowSeconds ?? Math.floor(Date.now() / 1000);
|
||||
if (now > payload.exp) {
|
||||
const date = new Date(payload.exp * 1000).toISOString().slice(0, 10);
|
||||
return { ok: false, reason: "expired", message: `授权凭证已于 ${date} 到期,请重新申请凭证` };
|
||||
}
|
||||
|
||||
try {
|
||||
if (compareBaseVersion(deps.version, payload.maxVersion) > 0) {
|
||||
return {
|
||||
ok: false,
|
||||
reason: "version_exceeded",
|
||||
message: `当前版本 v${deps.version} 超出授权上限 v${payload.maxVersion},请重新申请凭证`,
|
||||
};
|
||||
}
|
||||
} catch {
|
||||
return { ok: false, reason: "malformed", message: `凭证版本上限非法: ${payload.maxVersion}` };
|
||||
}
|
||||
|
||||
return { ok: true, payload };
|
||||
}
|
||||
|
||||
export function checkAiProLicense(): LicenseCheck {
|
||||
const token = loadToken();
|
||||
if (!token) {
|
||||
return { ok: false, reason: "missing", message: "AI PRO 尚未激活。凭证需向服务方离线申请,拿到后运行 hose-aipro login <凭证>" };
|
||||
}
|
||||
return verifyAiProLicenseToken(token);
|
||||
}
|
||||
|
||||
/** 统一门禁:返回拦截结果,null 表示放行。 */
|
||||
export function assertAiProEnabled(jsonMode: boolean): CliResult | null {
|
||||
const status = checkAiProLicense();
|
||||
if (status.ok) return null;
|
||||
const hint = status.reason === "missing"
|
||||
? "\n下一步: 向服务方申请凭证(提供 hose-aipro version 的版本号与期望到期日),再运行 hose-aipro login <凭证>"
|
||||
: "\n下一步: 联系服务方重新申请凭证";
|
||||
return {
|
||||
stdout: jsonMode
|
||||
? printJson({ error: true, code: "AIPRO_NOT_ACTIVATED", reason: status.reason, message: status.message }) + "\n"
|
||||
: "",
|
||||
stderr: jsonMode ? "" : `[AI PRO 未激活] ${status.message}${hint}\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
/** login 不进注册表,由分发层在门禁之前直接分流,避免任何注册表/元数据同步。 */
|
||||
export function handleAiProLogin(rawArgs: string[], jsonMode: boolean): CliResult {
|
||||
const parsed = parseArgs(rawArgs, "aipro");
|
||||
const token =
|
||||
stringOption(parsed.options, ["token", "license", "credential", "code"]) ||
|
||||
parsed.positional?.slice(1).find((part) => part && !part.startsWith("-")) ||
|
||||
"";
|
||||
|
||||
if (!token.trim()) {
|
||||
return {
|
||||
stdout: jsonMode ? printJson({ error: true, message: "缺少凭证" }) + "\n" : "",
|
||||
stderr: jsonMode
|
||||
? ""
|
||||
: "[AI PRO 激活] 缺少凭证。\n用法: hose-aipro login <凭证>\n 或: hose-aipro login --token=<凭证>\n",
|
||||
exitCode: 2,
|
||||
};
|
||||
}
|
||||
|
||||
const result = verifyAiProLicenseToken(token.trim());
|
||||
if (!result.ok) {
|
||||
return {
|
||||
stdout: jsonMode
|
||||
? printJson({ error: true, activated: false, reason: result.reason, message: result.message }) + "\n"
|
||||
: "",
|
||||
stderr: jsonMode ? "" : `[AI PRO 激活失败] ${result.message}\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const file = saveAiProLicenseToken(token.trim());
|
||||
const { sub, exp, maxVersion } = result.payload;
|
||||
const expiresAt = new Date(exp * 1000).toISOString().slice(0, 10);
|
||||
|
||||
return {
|
||||
stdout: jsonMode
|
||||
? printJson({ activated: true, subject: sub, expiresAt, maxVersion, licenseFile: file }) + "\n"
|
||||
: `AI PRO 已激活。\n 授权对象: ${sub}\n 到期时间: ${expiresAt}\n 版本上限: v${maxVersion}\n 凭证文件: ${file} (0600)\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
Reference in new issue
Block a user