diff --git a/scripts/license/issue.ts b/scripts/license/issue.ts new file mode 100644 index 0000000..0856c5d --- /dev/null +++ b/scripts/license/issue.ts @@ -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); +} diff --git a/skills/hose-aipro/SKILL.md b/skills/hose-aipro/SKILL.md index fce378c..852486f 100644 --- a/skills/hose-aipro/SKILL.md +++ b/skills/hose-aipro/SKILL.md @@ -32,6 +32,18 @@ metadata: --- +## 激活(默认关闭) + +AI PRO 默认不激活。首次使用需服务方通过离线渠道下发凭证,然后在本地激活: + +```bash +hose-aipro login <凭证> +``` + +凭证为 Ed25519 签名,校验完全在本地完成,不联网。只有两条约束:当前二进制版本不得高于凭证的 `maxVersion`,当前时间不得晚于凭证的 `exp`(绝对到期时间)。未激活时,除 `login` 与 `status` / `help` / `version` 等自省命令外,所有 AI PRO 命令都会被分发层的统一门禁拦截;新增命令自动受门禁管辖,无需改动授权代码。 + +--- + ## 快速自省与运行上下文 (Zero-Source-Reading) 在开始执行任何审批仲裁任务前,优先执行自省命令建立当前上下文: diff --git a/src/aipro-cli.test.ts b/src/aipro-cli.test.ts index a7f0ca2..fd5059c 100644 --- a/src/aipro-cli.test.ts +++ b/src/aipro-cli.test.ts @@ -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 () => { diff --git a/src/aipro-cli.ts b/src/aipro-cli.ts index c693d0c..7b68b06 100644 --- a/src/aipro-cli.ts +++ b/src/aipro-cli.ts @@ -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); diff --git a/src/cli/aipro-license.test.ts b/src/cli/aipro-license.test.ts new file mode 100644 index 0000000..496c75b --- /dev/null +++ b/src/cli/aipro-license.test.ts @@ -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 { + 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); + }); +}); diff --git a/src/cli/aipro-license.ts b/src/cli/aipro-license.ts new file mode 100644 index 0000000..962aa22 --- /dev/null +++ b/src/cli/aipro-license.ts @@ -0,0 +1,231 @@ +/** + * 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"; + +/** 验签公钥(随源码编译进二进制)。私钥由签发方离线保管,绝不进仓库。 */ +const PUBLIC_KEY = `-----BEGIN PUBLIC KEY----- +MCowBQYDK2VwAyEAKJOKyKQ00RdMPMzZlHk6zFItth2WkigFoF6K/3u+SjU= +-----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): 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: "凭证格式错误:应为 . 两段" }; + } + + 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 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, + }; +}