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