chore: lint fix

This commit is contained in:
xiaojunnuo
2026-08-02 21:06:33 +08:00
parent 27008cb44a
commit 4091abdfd7
38 changed files with 308 additions and 305 deletions
+1 -1
View File
@@ -19,7 +19,7 @@
"pub": "npm publish",
"compile": "tsc --skipLibCheck --watch",
"format": "prettier --write src",
"lint": "eslint --fix"
"lint": "eslint --fix --ext .ts src"
},
"keywords": [],
"author": "greper",
+35 -35
View File
@@ -1,21 +1,21 @@
export const Constants = {
dataDir: './data',
dataDir: "./data",
role: {
defaultUser: 3,
},
per: {
//无需登录
guest: '_guest_',
guest: "_guest_",
//无需登录
anonymous: '_guest_',
anonymous: "_guest_",
//无需登录,有 token 时解析当前用户
guestOptionalAuth: '_guestOptionalAuth_',
guestOptionalAuth: "_guestOptionalAuth_",
//仅需要登录
authOnly: '_authOnly_',
authOnly: "_authOnly_",
//仅需要登录
loginOnly: '_authOnly_',
loginOnly: "_authOnly_",
open: '_open_',
open: "_open_",
},
res: {
serverError(message: string) {
@@ -26,102 +26,102 @@ export const Constants = {
},
error: {
code: 1,
message: 'Internal server error',
message: "Internal server error",
},
success: {
code: 0,
message: 'success',
message: "success",
},
validation: {
code: 10,
message: '参数错误',
message: "参数错误",
},
needvip: {
code: 88,
message: '需要VIP',
message: "需要VIP",
},
needsuite: {
code: 89,
message: '需要购买或升级套餐',
message: "需要购买或升级套餐",
},
loginError: {
code: 2,
message: '登录失败',
message: "登录失败",
},
codeError: {
code: 3,
message: '验证码错误',
message: "验证码错误",
},
auth: {
code: 401,
message: '您还未登录或token已过期',
message: "您还未登录或token已过期",
},
permission: {
code: 402,
message: '您没有权限',
message: "您没有权限",
},
param: {
code: 400,
message: '参数错误',
message: "参数错误",
},
notFound: {
code: 404,
message: '页面/文件/资源不存在',
message: "页面/文件/资源不存在",
},
preview: {
code: 10001,
message: '对不起,预览环境不允许修改此数据',
message: "对不起,预览环境不允许修改此数据",
},
siteOff:{
siteOff: {
code: 10010,
message: '站点已关闭',
message: "站点已关闭",
},
need2fa:{
need2fa: {
code: 10020,
message: '需要2FA认证',
message: "需要2FA认证",
},
openKeyError: {
code: 20000,
message: 'ApiToken错误',
message: "ApiToken错误",
},
openKeySignError: {
code: 20001,
message: 'ApiToken签名错误',
message: "ApiToken签名错误",
},
openKeyExpiresError: {
code: 20002,
message: 'ApiToken时间戳错误',
message: "ApiToken时间戳错误",
},
openKeySignTypeError: {
code: 20003,
message: 'ApiToken签名类型不支持',
message: "ApiToken签名类型不支持",
},
openParamError: {
code: 20010,
message: '请求参数错误',
message: "请求参数错误",
},
openCertNotFound: {
code: 20011,
message: '证书不存在',
message: "证书不存在",
},
openCertNotReady: {
code: 20012,
message: '证书还未生成',
message: "证书还未生成",
},
openCertApplying: {
code: 20013,
message: '证书正在申请中,请稍后重新获取',
message: "证书正在申请中,请稍后重新获取",
},
openDomainNoVerifier:{
openDomainNoVerifier: {
code: 20014,
message: '域名校验方式未配置',
message: "域名校验方式未配置",
},
openEmailNotFound: {
code: 20021,
message: '用户邮箱还未配置',
message: "用户邮箱还未配置",
},
},
systemUserId: 0, // 系统级别userid固定为0
enterpriseUserId: -1 // 企业模式用户id固定为-1
enterpriseUserId: -1, // 企业模式用户id固定为-1
};
@@ -1,11 +1,11 @@
import { ALL, Body, Post, Query } from '@midwayjs/core';
import { BaseController } from './base-controller.js';
import { ALL, Body, Post, Query } from "@midwayjs/core";
import { BaseController } from "./base-controller.js";
export abstract class CrudController<T> extends BaseController {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
abstract getService<T>();
@Post('/page')
@Post("/page")
async page(@Body(ALL) body: any) {
const pageRet = await this.getService().page({
query: body.query ?? {},
@@ -16,7 +16,7 @@ export abstract class CrudController<T> extends BaseController {
return this.ok(pageRet);
}
@Post('/list')
@Post("/list")
async list(@Body(ALL) body: any) {
const listRet = await this.getService().list({
query: body.query ?? {},
@@ -25,33 +25,33 @@ export abstract class CrudController<T> extends BaseController {
return this.ok(listRet);
}
@Post('/add')
@Post("/add")
async add(@Body(ALL) bean: any) {
delete bean.id;
const id = await this.getService().add(bean);
return this.ok(id);
}
@Post('/info')
async info(@Query('id') id: number) {
@Post("/info")
async info(@Query("id") id: number) {
const bean = await this.getService().info(id);
return this.ok(bean);
}
@Post('/update')
@Post("/update")
async update(@Body(ALL) bean: any) {
await this.getService().update(bean);
return this.ok(null);
}
@Post('/delete')
async delete(@Query('id') id: number) {
@Post("/delete")
async delete(@Query("id") id: number) {
await this.getService().delete([id]);
return this.ok(null);
}
@Post('/deleteByIds')
async deleteByIds(@Body('ids') ids: number[]) {
@Post("/deleteByIds")
async deleteByIds(@Body("ids") ids: number[]) {
await this.getService().delete(ids);
return this.ok(null);
}
@@ -1,19 +1,17 @@
import { Constants } from '../constants.js';
import { BaseException } from './base-exception.js';
import { Constants } from "../constants.js";
import { BaseException } from "./base-exception.js";
import { TextException } from "./common-exception.js";
/**
* 授权异常
*/
export class AuthException extends BaseException {
constructor(message?:string) {
super('AuthException', Constants.res.auth.code, message ? message : Constants.res.auth.message);
constructor(message?: string) {
super("AuthException", Constants.res.auth.code, message ? message : Constants.res.auth.message);
}
}
export class Need2FAException extends TextException {
constructor(message:string,data:any) {
super('Need2FAException', Constants.res.need2fa.code, message ? message : Constants.res.need2fa.message,data);
constructor(message: string, data: any) {
super("Need2FAException", Constants.res.need2fa.code, message ? message : Constants.res.need2fa.message, data);
}
}
@@ -3,8 +3,8 @@
*/
export class BaseException extends Error {
code: number;
data?:any
constructor(name: string, code: number, message: string ,data?:any) {
data?: any;
constructor(name: string, code: number, message: string, data?: any) {
super(message);
this.name = name;
this.code = code;
@@ -1,10 +1,10 @@
import { Constants } from '../constants.js';
import { BaseException } from './base-exception.js';
import { Constants } from "../constants.js";
import { BaseException } from "./base-exception.js";
/**
* 验证码异常
*/
export class CodeErrorException extends BaseException {
constructor(message) {
super('CodeErrorException', Constants.res.codeError.code, message ? message : Constants.res.codeError.message);
super("CodeErrorException", Constants.res.codeError.code, message ? message : Constants.res.codeError.message);
}
}
@@ -1,12 +1,13 @@
export * from './auth-exception.js';
export * from './base-exception.js';
export * from './permission-exception.js';
export * from './preview-exception.js';
export * from './validation-exception.js';
export * from './vip-exception.js';
export * from './common-exception.js';
export * from './not-found-exception.js';
export * from './param-exception.js';
export * from './site-off-exception.js';
export * from './login-error-exception.js'
export * from './code-error-exception.js'
export * from "./auth-exception.js";
export * from "./base-exception.js";
export * from "./permission-exception.js";
export * from "./preview-exception.js";
export * from "./validation-exception.js";
export * from "./vip-exception.js";
export * from "./common-exception.js";
export * from "./not-found-exception.js";
export * from "./param-exception.js";
export * from "./site-off-exception.js";
export * from "./login-error-exception.js";
export * from "./code-error-exception.js";
export * from "./non-retryable-exception.js";
@@ -1,12 +1,12 @@
import { Constants } from '../constants.js';
import { BaseException } from './base-exception.js';
import { Constants } from "../constants.js";
import { BaseException } from "./base-exception.js";
/**
* 通用异常
*/
export class LoginErrorException extends BaseException {
leftCount: number;
constructor(message, leftCount: number) {
super('LoginErrorException', Constants.res.loginError.code, message ? message : Constants.res.loginError.message);
super("LoginErrorException", Constants.res.loginError.code, message ? message : Constants.res.loginError.message);
this.leftCount = leftCount;
}
}
@@ -0,0 +1,12 @@
import assert from "assert";
import { NonRetryableException } from "./non-retryable-exception.js";
describe("NonRetryableException", () => {
it("sets the standard error name and message", () => {
const error = new NonRetryableException("cannot retry");
assert.equal(error.name, "NonRetryableException");
assert.equal(error.message, "cannot retry");
assert.equal(error instanceof Error, true);
});
});
@@ -0,0 +1,6 @@
export class NonRetryableException extends Error {
constructor(message: string) {
super(message);
this.name = "NonRetryableException";
}
}
@@ -1,10 +1,10 @@
import { Constants } from '../constants.js';
import { BaseException } from './base-exception.js';
import { Constants } from "../constants.js";
import { BaseException } from "./base-exception.js";
/**
* 资源不存在
*/
export class NotFoundException extends BaseException {
constructor(message) {
super('NotFoundException', Constants.res.notFound.code, message ? message : Constants.res.notFound.message);
super("NotFoundException", Constants.res.notFound.code, message ? message : Constants.res.notFound.message);
}
}
@@ -1,10 +1,10 @@
import { Constants } from '../constants.js';
import { BaseException } from './base-exception.js';
import { Constants } from "../constants.js";
import { BaseException } from "./base-exception.js";
/**
* 参数异常
*/
export class ParamException extends BaseException {
constructor(message) {
super('ParamException', Constants.res.param.code, message ? message : Constants.res.param.message);
super("ParamException", Constants.res.param.code, message ? message : Constants.res.param.message);
}
}
@@ -1,10 +1,10 @@
import { Constants } from '../constants.js';
import { BaseException } from './base-exception.js';
import { Constants } from "../constants.js";
import { BaseException } from "./base-exception.js";
/**
* 授权异常
*/
export class PermissionException extends BaseException {
constructor(message?: string) {
super('PermissionException', Constants.res.permission.code, message ? message : Constants.res.permission.message);
super("PermissionException", Constants.res.permission.code, message ? message : Constants.res.permission.message);
}
}
@@ -1,14 +1,10 @@
import { Constants } from '../constants.js';
import { BaseException } from './base-exception.js';
import { Constants } from "../constants.js";
import { BaseException } from "./base-exception.js";
/**
* 预览模式
*/
export class PreviewException extends BaseException {
constructor(message) {
super(
'PreviewException',
Constants.res.preview.code,
message ? message : Constants.res.preview.message
);
super("PreviewException", Constants.res.preview.code, message ? message : Constants.res.preview.message);
}
}
@@ -1,9 +1,9 @@
import { Constants } from '../constants.js';
import { BaseException } from './base-exception.js';
import { Constants } from "../constants.js";
import { BaseException } from "./base-exception.js";
/**
*/
export class SiteOffException extends BaseException {
constructor(message) {
super('SiteOffException', Constants.res.siteOff.code, message ? message : Constants.res.siteOff.message);
super("SiteOffException", Constants.res.siteOff.code, message ? message : Constants.res.siteOff.message);
}
}
@@ -1,10 +1,10 @@
import { Constants } from '../constants.js';
import { BaseException } from './base-exception.js';
import { Constants } from "../constants.js";
import { BaseException } from "./base-exception.js";
/**
* 校验异常
*/
export class ValidateException extends BaseException {
constructor(message) {
super('ValidateException', Constants.res.validation.code, message ? message : Constants.res.validation.message);
super("ValidateException", Constants.res.validation.code, message ? message : Constants.res.validation.message);
}
}
@@ -1,16 +1,16 @@
import { Constants } from '../constants.js';
import { BaseException } from './base-exception.js';
import { Constants } from "../constants.js";
import { BaseException } from "./base-exception.js";
/**
* 需要vip异常
*/
export class NeedVIPException extends BaseException {
constructor(message) {
super('NeedVIPException', Constants.res.needvip.code, message ? message : Constants.res.needvip.message);
super("NeedVIPException", Constants.res.needvip.code, message ? message : Constants.res.needvip.message);
}
}
export class NeedSuiteException extends BaseException {
constructor(message) {
super('NeedSuiteException', Constants.res.needsuite.code, message ? message : Constants.res.needsuite.message);
super("NeedSuiteException", Constants.res.needsuite.code, message ? message : Constants.res.needsuite.message);
}
}
+8 -8
View File
@@ -1,8 +1,8 @@
export * from './base-controller.js';
export * from './constants.js';
export * from './crud-controller.js';
export * from './enum-item.js';
export * from './exception/index.js';
export * from './result.js';
export * from './base-service.js';
export * from "./mode.js"
export * from "./base-controller.js";
export * from "./constants.js";
export * from "./crud-controller.js";
export * from "./enum-item.js";
export * from "./exception/index.js";
export * from "./result.js";
export * from "./base-service.js";
export * from "./mode.js";
+8 -8
View File
@@ -1,12 +1,12 @@
let adminMode = "saas"
let adminMode = "saas";
export function setAdminMode(mode:string = "saas"){
adminMode = mode
export function setAdminMode(mode: string = "saas") {
adminMode = mode;
}
export function getAdminMode(){
return adminMode
export function getAdminMode() {
return adminMode;
}
export function isEnterprise(){
return adminMode === "enterprise"
}
export function isEnterprise() {
return adminMode === "enterprise";
}
@@ -1,11 +1,11 @@
import type { IMidwayContainer } from '@midwayjs/core';
import { Configuration } from '@midwayjs/core';
import { logger } from '@certd/basic';
import type { IMidwayContainer } from "@midwayjs/core";
import { Configuration } from "@midwayjs/core";
import { logger } from "@certd/basic";
@Configuration({
namespace: 'lib-server',
namespace: "lib-server",
})
export class LibServerConfiguration {
async onReady(container: IMidwayContainer) {
logger.info('lib start...');
logger.info("lib start...");
}
}
+7 -7
View File
@@ -1,9 +1,9 @@
import { SysSettingsEntity } from './system/index.js';
import { AccessEntity } from './user/access/entity/access.js';
import { SysSettingsEntity } from "./system/index.js";
import { AccessEntity } from "./user/access/entity/access.js";
import { AddonEntity } from "./user/index.js";
export * from './basic/index.js';
export * from './system/index.js';
export * from './user/index.js';
export { LibServerConfiguration as Configuration } from './configuration.js';
export * from "./basic/index.js";
export * from "./system/index.js";
export * from "./user/index.js";
export { LibServerConfiguration as Configuration } from "./configuration.js";
export const libServerEntities = [SysSettingsEntity, AccessEntity,AddonEntity];
export const libServerEntities = [SysSettingsEntity, AccessEntity, AddonEntity];
@@ -1,5 +1,5 @@
export * from './service/plus-service.js';
export * from './service/file-service.js';
export * from './service/encryptor.js';
export * from './service/ocr-service.js';
export * from './service/executor-queue.js';
export * from "./service/plus-service.js";
export * from "./service/file-service.js";
export * from "./service/encryptor.js";
export * from "./service/ocr-service.js";
export * from "./service/executor-queue.js";
@@ -1,8 +1,8 @@
import crypto from 'crypto';
import crypto from "crypto";
export class Encryptor {
secretKey: Buffer;
constructor(encryptSecret: string, encoding: BufferEncoding = 'base64') {
constructor(encryptSecret: string, encoding: BufferEncoding = "base64") {
this.secretKey = Buffer.from(encryptSecret, encoding);
}
// 加密函数
@@ -10,18 +10,18 @@ export class Encryptor {
const iv = crypto.randomBytes(16); // 初始化向量
// const secretKey = crypto.randomBytes(32);
// const key = Buffer.from(secretKey);
const cipher = crypto.createCipheriv('aes-256-cbc', this.secretKey, iv);
const cipher = crypto.createCipheriv("aes-256-cbc", this.secretKey, iv);
let encrypted = cipher.update(text);
encrypted = Buffer.concat([encrypted, cipher.final()]);
return iv.toString('hex') + ':' + encrypted.toString('hex');
return iv.toString("hex") + ":" + encrypted.toString("hex");
}
// 解密函数
decrypt(encryptedText: string) {
const textParts = encryptedText.split(':');
const iv = Buffer.from(textParts.shift(), 'hex');
const encrypted = Buffer.from(textParts.join(':'), 'hex');
const decipher = crypto.createDecipheriv('aes-256-cbc', Buffer.from(this.secretKey), iv);
const textParts = encryptedText.split(":");
const iv = Buffer.from(textParts.shift(), "hex");
const encrypted = Buffer.from(textParts.join(":"), "hex");
const decipher = crypto.createDecipheriv("aes-256-cbc", Buffer.from(this.secretKey), iv);
let decrypted = decipher.update(encrypted);
decrypted = Buffer.concat([decrypted, decipher.final()]);
return decrypted.toString();
@@ -1,18 +1,18 @@
import { logger } from "@certd/basic";
export type TaskItem = {
task: ()=>Promise<void>;
}
task: () => Promise<void>;
};
export class UserTaskQueue{
export class UserTaskQueue {
userId: number;
pendingQueue: TaskItem[] = [];
runningQueue: TaskItem[] = [];
getMaxRunningCount: ()=>number ;
getMaxRunningCount: () => number;
constructor(req: { userId: number ,getMaxRunningCount: ()=>number }) {
constructor(req: { userId: number; getMaxRunningCount: () => number }) {
this.userId = req.userId;
this.getMaxRunningCount = req.getMaxRunningCount ;
this.getMaxRunningCount = req.getMaxRunningCount;
}
addTask(task: TaskItem) {
@@ -34,10 +34,10 @@ export class UserTaskQueue{
}
// 执行任务
this.runningQueue.push(task);
const call = async ()=>{
try{
const call = async () => {
try {
await task.task();
}finally{
} finally {
// 任务执行完成,从运行队列中移除
const index = this.runningQueue.indexOf(task);
if (index > -1) {
@@ -46,17 +46,16 @@ export class UserTaskQueue{
// 继续执行下一个任务
this.runTask();
}
}
};
logger.info(`[user_${this.userId}]执行任务,当前运行队列:${this.runningQueue.length}, 等待队列:${this.pendingQueue.length}`);
call()
call();
}
}
export class ExecutorQueue{
export class ExecutorQueue {
queues: Record<number, UserTaskQueue> = {};
maxRunningCount: number = 10;
setMaxRunningCount(count: number) {
this.maxRunningCount = count;
}
@@ -64,7 +63,7 @@ export class ExecutorQueue{
getUserQueue(userId: number) {
const userQueue = this.queues[userId];
if (!userQueue) {
this.queues[userId] = new UserTaskQueue({ userId, getMaxRunningCount: ()=>this.maxRunningCount });
this.queues[userId] = new UserTaskQueue({ userId, getMaxRunningCount: () => this.maxRunningCount });
}
return this.queues[userId];
}
@@ -73,7 +72,6 @@ export class ExecutorQueue{
const userQueue = this.getUserQueue(userId);
userQueue.addTask(task);
}
}
export const executorQueue = new ExecutorQueue();
export const executorQueue = new ExecutorQueue();
@@ -1,42 +1,42 @@
import { Provide, Scope, ScopeEnum } from '@midwayjs/core';
import dayjs from 'dayjs';
import path from 'path';
import fs from 'fs';
import { cache, logger, utils } from '@certd/basic';
import { NotFoundException, ParamException, PermissionException } from '../../../basic/index.js';
import { Provide, Scope, ScopeEnum } from "@midwayjs/core";
import dayjs from "dayjs";
import path from "path";
import fs from "fs";
import { cache, logger, utils } from "@certd/basic";
import { NotFoundException, ParamException, PermissionException } from "../../../basic/index.js";
export type UploadFileItem = {
filename: string;
tmpFilePath: string;
};
const uploadRootDir = './data/upload';
export const uploadTmpFileCacheKey = 'tmpfile_key_';
const uploadRootDir = "./data/upload";
export const uploadTmpFileCacheKey = "tmpfile_key_";
/**
*/
@Provide()
@Scope(ScopeEnum.Request, { allowDowngrade: true })
export class FileService {
async saveFile(userId: number, tmpCacheKey: any, permission: 'public' | 'private') {
async saveFile(userId: number, tmpCacheKey: any, permission: "public" | "private") {
if (tmpCacheKey.startsWith(`/${permission}`)) {
//已经保存过,不需要再次保存
return tmpCacheKey;
}
let fileName = '';
let fileName = "";
let tmpFilePath = tmpCacheKey;
if (uploadTmpFileCacheKey && tmpCacheKey.startsWith(uploadTmpFileCacheKey)) {
const tmpFile: UploadFileItem = cache.get(tmpCacheKey);
if (!tmpFile) {
throw new ParamException('文件已过期,请重新上传');
throw new ParamException("文件已过期,请重新上传");
}
tmpFilePath = tmpFile.tmpFilePath;
fileName = tmpFile.filename || path.basename(tmpFilePath);
}
if (!tmpFilePath || !fs.existsSync(tmpFilePath)) {
throw new Error('文件不存在,请重新上传');
throw new Error("文件不存在,请重新上传");
}
const date = dayjs().format('YYYY_MM_DD');
const date = dayjs().format("YYYY_MM_DD");
const random = Math.random().toString(36).substring(7);
const userIdMd5 = Buffer.from(Buffer.from(userId + '').toString('base64')).toString('hex');
const userIdMd5 = Buffer.from(Buffer.from(userId + "").toString("base64")).toString("hex");
const key = `/${permission}/${userIdMd5}/${date}/${random}_${fileName}`;
let savePath = path.join(uploadRootDir, key);
savePath = path.resolve(savePath);
@@ -44,7 +44,6 @@ export class FileService {
if (!fs.existsSync(parentDir)) {
fs.mkdirSync(parentDir, { recursive: true });
}
// eslint-disable-next-line node/no-unsupported-features/node-builtins
const copyFile = utils.promises.promisify(fs.copyFile);
await copyFile(tmpFilePath, savePath);
try {
@@ -58,29 +57,29 @@ export class FileService {
getFile(key: string, userId?: number, allowAnyPrivateUser = false) {
if (!key) {
throw new ParamException('参数错误');
throw new ParamException("参数错误");
}
if (key.indexOf('..') >= 0) {
if (key.indexOf("..") >= 0) {
//安全性判断
throw new ParamException('参数错误');
throw new ParamException("参数错误");
}
if (!key.startsWith('/')) {
throw new ParamException('参数错误');
if (!key.startsWith("/")) {
throw new ParamException("参数错误");
}
const keyArr = key.split('/');
const keyArr = key.split("/");
const permission = keyArr[1];
const userIdMd5 = keyArr[2];
if (permission !== 'public' && !allowAnyPrivateUser) {
if (permission !== "public" && !allowAnyPrivateUser) {
//非公开文件需要验证用户
const userIdStr = Buffer.from(Buffer.from(userIdMd5, 'hex').toString('base64')).toString();
const userIdStr = Buffer.from(Buffer.from(userIdMd5, "hex").toString("base64")).toString();
const userIdInt: number = parseInt(userIdStr, 10);
if (userId == null || userIdInt !== userId) {
throw new PermissionException('无访问权限');
throw new PermissionException("无访问权限");
}
}
const filePath = path.join(uploadRootDir, key);
if (!fs.existsSync(filePath)) {
throw new NotFoundException('文件不存在');
throw new NotFoundException("文件不存在");
}
return filePath;
}
@@ -15,10 +15,9 @@ export class OcrService implements IOcrService {
url: "/activation/certd/ocr",
method: "post",
data: {
image: opts.image
}
image: opts.image,
},
});
return res;
}
}
+2 -2
View File
@@ -1,2 +1,2 @@
export * from './settings/index.js';
export * from './basic/index.js';
export * from "./settings/index.js";
export * from "./basic/index.js";
@@ -1,3 +1,3 @@
export * from './service/sys-settings-service.js';
export * from './service/models.js';
export * from './entity/sys-settings.js';
export * from "./service/sys-settings-service.js";
export * from "./service/models.js";
export * from "./entity/sys-settings.js";
@@ -1,15 +1,15 @@
import { Provide, Scope, ScopeEnum } from '@midwayjs/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
import { SysSettingsEntity } from '../entity/sys-settings.js';
import { BaseSettings, SysInstallInfo, SysPrivateSettings, SysPublicSettings, SysSecret, SysSecretBackup } from './models.js';
import { Provide, Scope, ScopeEnum } from "@midwayjs/core";
import { InjectEntityModel } from "@midwayjs/typeorm";
import { Repository } from "typeorm";
import { SysSettingsEntity } from "../entity/sys-settings.js";
import { BaseSettings, SysInstallInfo, SysPrivateSettings, SysPublicSettings, SysSecret, SysSecretBackup } from "./models.js";
import { getAllSslProviderDomains, setSslProviderReverseProxies, setWalkFromAuthoritative } from '@certd/acme-client';
import { cache, logger, mergeUtils, setGlobalHeaders, setGlobalProxy } from '@certd/basic';
import { isPlus } from '@certd/plus-core';
import * as dns from 'node:dns';
import { BaseService, setAdminMode } from '../../../basic/index.js';
import { executorQueue } from '../../basic/service/executor-queue.js';
import { getAllSslProviderDomains, setSslProviderReverseProxies, setWalkFromAuthoritative } from "@certd/acme-client";
import { cache, logger, mergeUtils, setGlobalHeaders, setGlobalProxy } from "@certd/basic";
import { isPlus } from "@certd/plus-core";
import * as dns from "node:dns";
import { BaseService, setAdminMode } from "../../../basic/index.js";
import { executorQueue } from "../../basic/service/executor-queue.js";
const { merge } = mergeUtils;
let lastSaveEnvVars = {};
@@ -138,7 +138,7 @@ export class SysSettingsService extends BaseService<SysSettingsEntity> {
res.reverseProxies[domain] = "";
}
}
return res
return res;
}
async savePrivateSettings(bean: SysPrivateSettings) {
@@ -149,14 +149,14 @@ export class SysSettingsService extends BaseService<SysSettingsEntity> {
}
async reloadSettings() {
await this.reloadPrivateSettings()
await this.reloadPublicSettings()
await this.reloadPrivateSettings();
await this.reloadPublicSettings();
}
async reloadPublicSettings() {
const publicSetting = await this.getPublicSettings()
if (isPlus()){
setAdminMode(publicSetting.adminMode )
const publicSetting = await this.getPublicSettings();
if (isPlus()) {
setAdminMode(publicSetting.adminMode);
}
}
@@ -169,7 +169,7 @@ export class SysSettingsService extends BaseService<SysSettingsEntity> {
};
setGlobalProxy(opts);
setGlobalHeaders(this.parseKeyValueText(privateSetting.commonHeaders));
if (privateSetting.dnsResultOrder) {
dns.setDefaultResultOrder(privateSetting.dnsResultOrder as any);
}
@@ -183,29 +183,28 @@ export class SysSettingsService extends BaseService<SysSettingsEntity> {
this.setEnvironmentVars(privateSetting.environmentVars);
setWalkFromAuthoritative(privateSetting.acmeWalkFromAuthoritative);
}
parseKeyValueText(text: string) {
const values = {};
if (typeof text !== 'string') {
if (typeof text !== "string") {
text = "";
}
text.split('\n').forEach(line => {
text.split("\n").forEach(line => {
line = line.trim();
if (!line || line.startsWith('#')) {
return
if (!line || line.startsWith("#")) {
return;
}
const arr = line.split("#")
const arr = line.split("#");
if (arr.length > 0) {
line = arr[0].trim();
}
if (!line.includes("=")) {
return
return;
}
const eqIndex = line.indexOf('=');
const eqIndex = line.indexOf("=");
const key = line.substring(0, eqIndex).trim();
const value = line.substring(eqIndex + 1).trim();
if (key && value) {
@@ -220,7 +219,7 @@ export class SysSettingsService extends BaseService<SysSettingsEntity> {
//先删除旧环境变量
if (lastSaveEnvVars) {
for (const key in lastSaveEnvVars) {
delete process.env[key];
delete process.env[key];
}
}
@@ -234,7 +233,7 @@ export class SysSettingsService extends BaseService<SysSettingsEntity> {
entity.setting = JSON.stringify(setting);
await this.repository.save(entity);
} else {
throw new Error('该设置不存在');
throw new Error("该设置不存在");
}
cache.delete(`settings.${key}`);
}
@@ -246,20 +245,20 @@ export class SysSettingsService extends BaseService<SysSettingsEntity> {
if (settings == null) {
const backup = new SysSecretBackup();
if (installInfo.siteId == null || privateSettings.encryptSecret == null) {
logger.error('备份密钥失败,siteId或encryptSecret为空');
logger.error("备份密钥失败,siteId或encryptSecret为空");
return;
}
backup.siteId = installInfo.siteId;
backup.encryptSecret = privateSettings.encryptSecret;
await this.saveSetting(backup);
logger.info('备份密钥成功');
logger.info("备份密钥成功");
} else {
//校验是否有变化
if (settings.siteId !== installInfo.siteId) {
throw new Error(`siteId与备份不一致,可能是数据异常,请检查:backup=${settings.siteId}, current=${installInfo.siteId}`);
}
if (settings.encryptSecret !== privateSettings.encryptSecret) {
throw new Error('encryptSecret与备份不一致,可能是数据异常,请检查');
throw new Error("encryptSecret与备份不一致,可能是数据异常,请检查");
}
}
}
@@ -271,12 +270,12 @@ export class SysSettingsService extends BaseService<SysSettingsEntity> {
//从备份中读取
const settings = await this.getSettingByKey(SysSecretBackup.__key__);
if (settings == null || !settings.encryptSecret) {
throw new Error('密钥备份不存在');
throw new Error("密钥备份不存在");
}
sysSecret.siteId = settings.siteId;
sysSecret.encryptSecret = settings.encryptSecret;
await this.saveSetting(sysSecret);
logger.info('密钥恢复成功');
logger.info("密钥恢复成功");
return sysSecret;
}
}
@@ -1,46 +1,46 @@
import { Column, Entity, PrimaryGeneratedColumn } from 'typeorm';
import { Column, Entity, PrimaryGeneratedColumn } from "typeorm";
/**
* 授权配置
*/
@Entity('cd_access')
@Entity("cd_access")
export class AccessEntity {
@PrimaryGeneratedColumn()
id: number;
@Column({ name: 'key_id', comment: 'key_id', length: 100 })
@Column({ name: "key_id", comment: "key_id", length: 100 })
keyId: string;
@Column({ name: 'user_id', comment: '用户id' })
@Column({ name: "user_id", comment: "用户id" })
userId: number; // 0为系统级别, -1为企业,大于1为用户
@Column({ comment: '名称', length: 100 })
@Column({ comment: "名称", length: 100 })
name: string;
@Column({ comment: '类型', length: 100 })
@Column({ comment: "类型", length: 100 })
type: string;
@Column({ name: 'subtype', comment: '子类型', length: 100, nullable: true })
@Column({ name: "subtype", comment: "子类型", length: 100, nullable: true })
subtype: string;
@Column({ name: 'setting', comment: '设置', length: 10240, nullable: true })
@Column({ name: "setting", comment: "设置", length: 10240, nullable: true })
setting: string;
@Column({ name: 'encrypt_setting', comment: '已加密设置', length: 10240, nullable: true })
@Column({ name: "encrypt_setting", comment: "已加密设置", length: 10240, nullable: true })
encryptSetting: string;
@Column({ name: 'project_id', comment: '项目id' })
@Column({ name: "project_id", comment: "项目id" })
projectId: number;
@Column({
name: 'create_time',
comment: '创建时间',
default: () => 'CURRENT_TIMESTAMP',
name: "create_time",
comment: "创建时间",
default: () => "CURRENT_TIMESTAMP",
})
createTime: Date;
@Column({
name: 'update_time',
comment: '修改时间',
default: () => 'CURRENT_TIMESTAMP',
name: "update_time",
comment: "修改时间",
default: () => "CURRENT_TIMESTAMP",
})
updateTime: Date;
}
@@ -1,5 +1,5 @@
export * from './entity/access.js';
export * from './service/access-service.js';
export * from './service/access-sys-getter.js';
export * from './service/access-getter.js';
export * from './service/encrypt-service.js';
export * from "./entity/access.js";
export * from "./service/access-service.js";
export * from "./service/access-sys-getter.js";
export * from "./service/access-getter.js";
export * from "./service/encrypt-service.js";
@@ -1,5 +1,5 @@
import { IAccessService } from '@certd/pipeline';
import { AccessService } from './access-service.js';
import { IAccessService } from "@certd/pipeline";
import { AccessService } from "./access-service.js";
export class AccessSysGetter implements IAccessService {
accessService: AccessService;
@@ -1,5 +1,5 @@
import { Inject, Provide, Scope, ScopeEnum } from '@midwayjs/core';
import { Encryptor, SysSecret, SysSettingsService } from '../../../system/index.js';
import { Inject, Provide, Scope, ScopeEnum } from "@midwayjs/core";
import { Encryptor, SysSecret, SysSettingsService } from "../../../system/index.js";
/**
* 授权
@@ -48,8 +48,8 @@ export function AddonInput(input?: AddonInputDefine): PropertyDecorator {
};
}
export async function newAddon(addonType:string,type: string, input: any, ctx: AddonContext) {
const key = `${addonType}:${type}`
export async function newAddon(addonType: string, type: string, input: any, ctx: AddonContext) {
const key = `${addonType}:${type}`;
const register = addonRegistry.get(key);
if (register == null) {
throw new Error(`${addonType} ${type} not found`);
@@ -1,49 +1,46 @@
import { Column, Entity, PrimaryGeneratedColumn } from 'typeorm';
import { Column, Entity, PrimaryGeneratedColumn } from "typeorm";
/**
*/
@Entity('cd_addon')
@Entity("cd_addon")
export class AddonEntity {
@PrimaryGeneratedColumn()
id: number;
@Column({ name: 'key_id', comment: 'key_id', length: 100 })
@Column({ name: "key_id", comment: "key_id", length: 100 })
keyId: string;
@Column({ name: 'user_id', comment: '用户id' })
@Column({ name: "user_id", comment: "用户id" })
userId: number;
@Column({ comment: '名称', length: 100 })
@Column({ comment: "名称", length: 100 })
name: string;
@Column({ name: 'addon_type', comment: 'addon类型', length: 100 })
@Column({ name: "addon_type", comment: "addon类型", length: 100 })
addonType: string;
@Column({ comment: '类型', length: 100 })
@Column({ comment: "类型", length: 100 })
type: string;
@Column({ name: 'setting', comment: '设置', length: 10240, nullable: true })
@Column({ name: "setting", comment: "设置", length: 10240, nullable: true })
setting: string;
@Column({ name: 'is_system', comment: '是否系统级别', nullable: false, default: false })
@Column({ name: "is_system", comment: "是否系统级别", nullable: false, default: false })
isSystem: boolean;
@Column({ name: 'is_default', comment: '是否默认', nullable: false, default: false })
@Column({ name: "is_default", comment: "是否默认", nullable: false, default: false })
isDefault: boolean;
@Column({ name: 'project_id', comment: '项目id' })
@Column({ name: "project_id", comment: "项目id" })
projectId: number;
@Column({
name: 'create_time',
comment: '创建时间',
default: () => 'CURRENT_TIMESTAMP',
name: "create_time",
comment: "创建时间",
default: () => "CURRENT_TIMESTAMP",
})
createTime: Date;
@Column({
name: 'update_time',
comment: '修改时间',
default: () => 'CURRENT_TIMESTAMP',
name: "update_time",
comment: "修改时间",
default: () => "CURRENT_TIMESTAMP",
})
updateTime: Date;
}
@@ -1,3 +1,3 @@
export * from './api/index.js'
export * from './entity/addon.js'
export * from './service/addon-service.js'
export * from "./api/index.js";
export * from "./entity/addon.js";
export * from "./service/addon-service.js";
@@ -49,7 +49,6 @@ export class AddonService extends BaseService<AddonEntity> {
return await super.add(param);
}
/**
* 修改
* @param param 数据
@@ -59,7 +58,7 @@ export class AddonService extends BaseService<AddonEntity> {
if (oldEntity == null) {
throw new ValidateException("该Addon配置不存在,请确认是否已被删除");
}
delete param.keyId
delete param.keyId;
return await super.update(param);
}
@@ -75,11 +74,10 @@ export class AddonService extends BaseService<AddonEntity> {
userId: entity.userId,
addonType: entity.addonType,
type: entity.type,
projectId: entity.projectId
projectId: entity.projectId,
};
}
getDefineList(addonType: string) {
return addonRegistry.getDefineList(addonType);
}
@@ -88,12 +86,11 @@ export class AddonService extends BaseService<AddonEntity> {
return addonRegistry.getDefine(type, prefix) as AddonDefine;
}
async getSimpleByIds(ids: number[], userId: any,projectId?:number) {
async getSimpleByIds(ids: number[], userId: any, projectId?: number) {
if (ids.length === 0) {
return [];
}
if (userId==null) {
if (userId == null) {
return [];
}
const userProjectQuery = this.buildUserProjectQuery(userId, projectId);
@@ -109,14 +106,12 @@ export class AddonService extends BaseService<AddonEntity> {
addonType: true,
type: true,
userId: true,
isSystem: true
}
isSystem: true,
},
});
}
async getDefault(userId: number, addonType: string,projectId?:number): Promise<any> {
async getDefault(userId: number, addonType: string, projectId?: number): Promise<any> {
const userProjectQuery = this.buildUserProjectQuery(userId, projectId);
const res = await this.repository.findOne({
where: {
@@ -124,8 +119,8 @@ export class AddonService extends BaseService<AddonEntity> {
...userProjectQuery,
},
order: {
isDefault: "DESC"
}
isDefault: "DESC",
},
});
if (!res) {
return null;
@@ -143,15 +138,15 @@ export class AddonService extends BaseService<AddonEntity> {
name: res.name,
userId: res.userId,
setting,
projectId: res.projectId
projectId: res.projectId,
};
}
async setDefault(id: number, userId: number, addonType: string,projectId?:number) {
async setDefault(id: number, userId: number, addonType: string, projectId?: number) {
if (!id) {
throw new ValidateException("id不能为空");
}
if (userId==null) {
if (userId == null) {
throw new ValidateException("userId不能为空");
}
const userProjectQuery = this.buildUserProjectQuery(userId, projectId);
@@ -160,24 +155,27 @@ export class AddonService extends BaseService<AddonEntity> {
...userProjectQuery,
};
await this.repository.update(query, {
isDefault: false
});
await this.repository.update({ ...query, id }, {
isDefault: true
isDefault: false,
});
await this.repository.update(
{ ...query, id },
{
isDefault: true,
}
);
}
async getOrCreateDefault(opts: { addonType: string, type: string, inputs: any, userId: any,projectId?:number }) {
const { addonType, type, inputs, userId,projectId } = opts;
async getOrCreateDefault(opts: { addonType: string; type: string; inputs: any; userId: any; projectId?: number }) {
const { addonType, type, inputs, userId, projectId } = opts;
const addonDefine = this.getDefineByType(type, addonType);
const defaultConfig = await this.getDefault(userId, addonType,projectId);
const defaultConfig = await this.getDefault(userId, addonType, projectId);
if (defaultConfig) {
return defaultConfig;
}
const setting = {
...inputs
...inputs,
};
const res = await this.repository.save({
userId,
@@ -186,19 +184,19 @@ export class AddonService extends BaseService<AddonEntity> {
name: addonDefine.title,
setting: JSON.stringify(setting),
isDefault: true,
projectId
projectId,
});
return this.buildAddonInstanceConfig(res);
}
async getOneByType(req:{addonType:string,type:string,userId:number,projectId?:number}) {
async getOneByType(req: { addonType: string; type: string; userId: number; projectId?: number }) {
const userProjectQuery = this.buildUserProjectQuery(req.userId, req.projectId);
return await this.repository.findOne({
where: {
addonType: req.addonType,
type: req.type,
...userProjectQuery,
}
},
});
}
}
+2 -2
View File
@@ -1,2 +1,2 @@
export * from './access/index.js';
export * from './addon/index.js';
export * from "./access/index.js";
export * from "./addon/index.js";