客户不会自己敲命令行,只会把凭证粘贴到与 Agent 的对话框里。 修正面向 Agent 的首次安装与激活流程:步骤 3 改为 Agent 在对话框 向用户索取凭证并引导申请;步骤 4 改为 Agent 从对话内容提取凭证 文本、原样传递并自行执行 login;步骤 5 由 Agent 验证后继续任务。 明确不让用户执行命令、不回显凭证、不写入日志或项目文件。 - skills/hose-aipro/SKILL.md:重写步骤 3-5 与 IMPORTANT 块 - scripts/install.sh、README.md:提示改为「粘贴给你的 AI 助手」 - 未激活错误提示改为引导把凭证交给 AI 助手 注意:Skill 内嵌进二进制,本改动需等 0.9.3 发版才对客户生效; 0.9.2 产物内仍是修正前的说明,本次不打 tag、不触发 Release。 校验:bun test 1094 pass / 0 fail,bun run check 通过。
235 lines
8.7 KiB
TypeScript
235 lines
8.7 KiB
TypeScript
/**
|
||
* 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 尚未激活。凭证需向服务方离线申请,拿到后直接粘贴给 AI 助手完成激活" };
|
||
}
|
||
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 的版本号与期望到期日),把凭证粘贴给 AI 助手,或自行运行 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,
|
||
};
|
||
}
|