- libs: 新增 hr_sdk / hotel_report / dingtalk,更新 desktopauto - controlplane-next: SDK 管理模块(controller/entity/migrations)与前端视图 - electron-shell: 插件同步、注册表、runner 调整 - plugins: XQ0035/XQ0041/XQ0042/XQ0045_XQ0046/XQ0048/XQ0076/XQ0078 等版本更新 - tests/tools: 新增 SDK 兼容性检查与打包工具(sdk_pack.py、sdk_compat_check.py)
205 lines
8.0 KiB
TypeScript
205 lines
8.0 KiB
TypeScript
import { CoolController, BaseController } from '@cool-midway/core';
|
||
import { Get, Headers, Inject, Param, Provide, Query } from '@midwayjs/core';
|
||
import { InjectEntityModel } from '@midwayjs/typeorm';
|
||
import { Repository } from 'typeorm';
|
||
import * as fs from 'fs';
|
||
import * as path from 'path';
|
||
import { randomBytes } from 'node:crypto';
|
||
import { SdkEntity, SdkVersionEntity } from '../../entity/sdk';
|
||
import { AccountPluginEntity, PluginEntity } from '../../entity/plugin';
|
||
import { DownloadTicketEntity } from '../../entity/account';
|
||
import { CenterAuthService, ApiError } from '../../service/auth';
|
||
import { PKG_DIR, fmtNow } from '../../comm/conf';
|
||
|
||
/**
|
||
* 客户端 SDK 清单与下载票据(对齐 plugins.ts / ticket.ts 的既有口径)。
|
||
*
|
||
* - GET /api/sdks?account= 返回该账号**按插件依赖推导**的可用 SDK 及版本
|
||
* - GET /api/sdks/:id/versions/:v/download-ticket?account= 一次性票据(复用 download_tickets 表)
|
||
*
|
||
* 授权模型:不建 account_sdks 表。SDK 不能独立运行,唯一消费者是插件,因此可用集合
|
||
* = 该账号已授权(can_download=1)且未下架插件的 `plugin.json.requires.sdks` 并集。
|
||
* 插件新增依赖时自动生效,不需要"回填补授"。
|
||
*/
|
||
@Provide()
|
||
@CoolController('/api')
|
||
export class ApiSdksController extends BaseController {
|
||
@Inject()
|
||
centerAuthService: CenterAuthService;
|
||
|
||
@InjectEntityModel(SdkEntity)
|
||
sdkRepo: Repository<SdkEntity>;
|
||
|
||
@InjectEntityModel(SdkVersionEntity)
|
||
sdkVersionRepo: Repository<SdkVersionEntity>;
|
||
|
||
@InjectEntityModel(AccountPluginEntity)
|
||
accountPluginRepo: Repository<AccountPluginEntity>;
|
||
|
||
@InjectEntityModel(DownloadTicketEntity)
|
||
downloadTicketRepo: Repository<DownloadTicketEntity>;
|
||
|
||
private async resolveAcct(
|
||
account: string,
|
||
xApiToken: string,
|
||
authorization: string
|
||
): Promise<string> {
|
||
let acct = await this.centerAuthService.cloudAccount(authorization);
|
||
if (!acct) {
|
||
this.centerAuthService.checkApiToken(xApiToken);
|
||
acct = (account || '').trim();
|
||
}
|
||
if (!acct) throw new ApiError(400, '缺少有效会话或 account');
|
||
return acct;
|
||
}
|
||
|
||
/** 该账号通过已授权插件间接依赖的 SDK id 集合 */
|
||
private async requiredSdkIds(account: string): Promise<Set<string>> {
|
||
const rows = await this.accountPluginRepo
|
||
.createQueryBuilder('ap')
|
||
.innerJoin(PluginEntity, 'p', 'p.id = ap.pluginId')
|
||
.select('p.manifest', 'manifest')
|
||
.where('ap.account = :account', { account })
|
||
.andWhere('ap.canDownload = 1')
|
||
.andWhere("p.status <> 'revoked'")
|
||
.getRawMany();
|
||
const ids = new Set<string>();
|
||
for (const r of rows) {
|
||
try {
|
||
const man = JSON.parse(String(r.manifest || '{}'));
|
||
const sdks = (man.requires || {}).sdks || {};
|
||
for (const id of Object.keys(sdks)) {
|
||
if (id) ids.add(id);
|
||
}
|
||
} catch (e) {
|
||
/* manifest 损坏的插件不贡献依赖 */
|
||
}
|
||
}
|
||
return ids;
|
||
}
|
||
|
||
/**
|
||
* 某 SDK 当前应下发的版本:
|
||
* 管理员且在测 → test_version(前提是该版本没被 yank);否则 latest_version;
|
||
* 两者都不可用(被 yank)→ 取最高非 yanked 版本,等价于"回落上一版"。
|
||
*/
|
||
private async effectiveVersion(sdk: SdkEntity, isAdmin: boolean): Promise<SdkVersionEntity | null> {
|
||
const versions = await this.sdkVersionRepo.find({
|
||
where: { sdkId: sdk.id },
|
||
order: { id: 'DESC' }, // 上传顺序即版本递增(测试版号必须高于正式版,见 admin/sdk.ts)
|
||
});
|
||
const usable = versions.filter(v => String(v.status) !== 'yanked');
|
||
if (!usable.length) return null;
|
||
const testVer = String(sdk.testVersion || '').trim();
|
||
if (isAdmin && String(sdk.status) === 'testing' && testVer) {
|
||
const t = usable.find(v => String(v.version) === testVer);
|
||
if (t) return t;
|
||
}
|
||
const latest = String(sdk.latestVersion || '').trim();
|
||
const pinned = usable.find(v => String(v.version) === latest);
|
||
return pinned || usable[0];
|
||
}
|
||
|
||
/** GET /api/sdks — 按账号返回可用 SDK 清单(版本级 yank 已过滤) */
|
||
@Get('/sdks')
|
||
async sdks(
|
||
@Query('account') account: string = '',
|
||
@Headers('X-API-Token') xApiToken: string = '',
|
||
@Headers('Authorization') authorization: string = ''
|
||
) {
|
||
const acct = await this.resolveAcct(account, xApiToken, authorization);
|
||
if (await this.centerAuthService.accountDisabled(acct)) {
|
||
return { account: acct, sdks: [] };
|
||
}
|
||
const ids = [...(await this.requiredSdkIds(acct))];
|
||
if (!ids.length) return { account: acct, sdks: [] };
|
||
|
||
const isAdmin = await this.centerAuthService.accountIsAdmin(acct);
|
||
const rows = await this.sdkRepo
|
||
.createQueryBuilder('s')
|
||
.where('s.id IN (:...ids)', { ids })
|
||
.andWhere("s.status <> 'revoked'")
|
||
.orderBy('s.id', 'ASC')
|
||
.getMany();
|
||
|
||
const out: any[] = [];
|
||
for (const sdk of rows) {
|
||
// disabled=暂停下发(客户端保留本地版本,不拉新)
|
||
if (String(sdk.status) === 'disabled') {
|
||
out.push({
|
||
id: sdk.id, name: sdk.name, description: sdk.description, status: sdk.status,
|
||
version: '', channel: 'prod', sha256: '', size_bytes: 0,
|
||
});
|
||
continue;
|
||
}
|
||
const ver = await this.effectiveVersion(sdk, isAdmin);
|
||
if (!ver) continue;
|
||
const useTest = isAdmin && String(sdk.status) === 'testing' && ver.version === String(sdk.testVersion || '');
|
||
out.push({
|
||
id: sdk.id,
|
||
name: sdk.name,
|
||
description: sdk.description,
|
||
status: sdk.status,
|
||
version: String(ver.version || ''),
|
||
channel: useTest ? 'test' : 'prod',
|
||
sha256: String(ver.sha256 || ''),
|
||
size_bytes: Number(ver.sizeBytes || 0),
|
||
});
|
||
}
|
||
return { account: acct, sdks: out };
|
||
}
|
||
|
||
/** GET /api/sdks/{sdkId}/versions/{version}/download-ticket */
|
||
@Get('/sdks/:sdkId/versions/:version/download-ticket')
|
||
async downloadTicket(
|
||
@Param('sdkId') sdkId: string,
|
||
@Param('version') version: string,
|
||
@Query('account') account: string = '',
|
||
@Headers('X-API-Token') xApiToken: string = ''
|
||
) {
|
||
this.centerAuthService.checkApiToken(xApiToken);
|
||
const acct = (account || '').trim();
|
||
if (!acct) throw new ApiError(400, 'account 不能为空');
|
||
|
||
const ids = await this.requiredSdkIds(acct);
|
||
if (!ids.has(sdkId)) throw new ApiError(403, `账号未通过任何插件依赖 SDK ${sdkId}`);
|
||
const sdk = await this.sdkRepo.findOneBy({ id: sdkId });
|
||
if (!sdk) throw new ApiError(404, `SDK ${sdkId} 不存在`);
|
||
if (['disabled', 'revoked'].includes(String(sdk.status))) {
|
||
throw new ApiError(403, `SDK ${sdkId} 已停用/下架,禁止下载`);
|
||
}
|
||
|
||
const ver = await this.sdkVersionRepo.findOneBy({ sdkId, version });
|
||
if (!ver) throw new ApiError(404, `未找到 SDK 包 ${sdkId}@${version}`);
|
||
if (String(ver.status) === 'yanked') {
|
||
throw new ApiError(403, `版本 ${version} 已被撤回(yank),禁止下载`);
|
||
}
|
||
// 只允许拉"当前应下发版本":防止客户端自己指定任意历史版本,绕开版本收敛
|
||
const isAdmin = await this.centerAuthService.accountIsAdmin(acct);
|
||
const eff = await this.effectiveVersion(sdk, isAdmin);
|
||
if (!eff || String(eff.version) !== String(version)) {
|
||
throw new ApiError(403, `版本 ${version} 当前不可下载(应下发版本:${eff?.version || '无'})`);
|
||
}
|
||
const pkgPath = path.join(PKG_DIR, ver.filename);
|
||
if (!fs.existsSync(pkgPath)) throw new ApiError(404, `包文件缺失:${ver.filename}`);
|
||
|
||
const nonce = randomBytes(16).toString('hex');
|
||
await this.downloadTicketRepo.manager.query(
|
||
'DELETE FROM download_tickets WHERE created_at < DATE_SUB(NOW(), INTERVAL 3600 SECOND)'
|
||
);
|
||
await this.downloadTicketRepo.insert({
|
||
nonce,
|
||
filename: ver.filename,
|
||
sha256: ver.sha256 || '',
|
||
used: 0,
|
||
});
|
||
return {
|
||
ticket: nonce,
|
||
url: `/api/download/${nonce}`,
|
||
filename: ver.filename,
|
||
sha256: ver.sha256 || '',
|
||
expiresAt: fmtNow(),
|
||
};
|
||
}
|
||
}
|