Merge branch 'refs/heads/v2-dev' into v2-dev-buy

# Conflicts:
#	docs/.vitepress/config.ts
#	packages/ui/certd-client/src/views/certd/pipeline/sub-domain/index.vue
This commit is contained in:
xiaojunnuo
2025-09-22 22:29:59 +08:00
175 changed files with 4551 additions and 684 deletions
+36
View File
@@ -3,6 +3,42 @@
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## [1.36.21](https://github.com/certd/certd/compare/v1.36.20...v1.36.21) (2025-09-15)
### Bug Fixes
* 修复导入插件对话框无法打开的bug,修复插件编辑页面打开多个代码编辑器消失的bug ([e5a080a](https://github.com/certd/certd/commit/e5a080aebe0d2f3e3c0f86bf863f75069c1bf7ab))
## [1.36.20](https://github.com/certd/certd/compare/v1.36.19...v1.36.20) (2025-09-13)
### Bug Fixes
* 修复商业版退出登录后,丢失站点个性化设置的bug ([d75dd05](https://github.com/certd/certd/commit/d75dd058d65c85f80c49e1fa7a910e6c6f08e824))
* 修复授权类型和名称字段排到最后的bug ([43b7977](https://github.com/certd/certd/commit/43b79778ea9034065f6a15af3296274315597c6b))
### Performance Improvements
* 登录支持极验验证码 ([370db62](https://github.com/certd/certd/commit/370db62bf0aece241859244927beabba32d6a257))
* 登录注册、找回密码都支持极验验证码和图片验证码 ([7bdde68](https://github.com/certd/certd/commit/7bdde68ecea29fe2c570fd3cb082139db6c93d93))
* 优化加量包展示效果 ([3c65f37](https://github.com/certd/certd/commit/3c65f37d84177ba107d4a6462648af12d2fc4b7a))
* 证书到期剩余天数进度条根据实际证书有效期计算 ([#528](https://github.com/certd/certd/issues/528)) nicheng-he ([2d4586b](https://github.com/certd/certd/commit/2d4586b1c42c39f97d2a95b9453cca4bc8bfbe61))
## [1.36.19](https://github.com/certd/certd/compare/v1.36.18...v1.36.19) (2025-09-05)
### Bug Fixes
* 修复批量流水线执行时日志显示错乱的问题 ([4372adc](https://github.com/certd/certd/commit/4372adc703b9a4c785664054ab2a533626d815a8))
* 修复远程数据选择无法过滤的bug ([6cbb073](https://github.com/certd/certd/commit/6cbb0739f8428d51b0712f718fe4d236cc087cf9))
* 修复mysql下购买套餐加量包无效的bug ([c26ad4c](https://github.com/certd/certd/commit/c26ad4c8075f0606d45b8da13915737968d6191a))
### Performance Improvements
* 创建证书时支持选择通知时机 ([0e96bfd](https://github.com/certd/certd/commit/0e96bfdfa377824d204e72923d1176408ae6b300))
* 商业版隐藏文档相关链接 ([4443a1c](https://github.com/certd/certd/commit/4443a1c0308fa6b95a05efd73d15d24b65d641c9))
* 商业版隐藏文档相关链接 ([db89561](https://github.com/certd/certd/commit/db8956148083bc4f988226ccf719940d08158a27))
* 支持根据id更新证书(证书Id不变接口),不过该接口为白名单功能,普通腾讯云账户无法使用 ([fe9c4f3](https://github.com/certd/certd/commit/fe9c4f3391ff07c01dd9a252225f69a129c39050))
* 子域名托管说明 ([39a0223](https://github.com/certd/certd/commit/39a02235cf4416bb5bd1acd3831241efeaa2f602))
## [1.36.18](https://github.com/certd/certd/compare/v1.36.17...v1.36.18) (2025-08-28)
### Bug Fixes
+1
View File
@@ -23,5 +23,6 @@
</div>
<script type="module" src="/src/main.ts"></script>
<script src="https://static.geetest.com/v4/gt4.js"></script>
</body>
</html>
+10 -9
View File
@@ -1,6 +1,6 @@
{
"name": "@certd/ui-client",
"version": "1.36.18",
"version": "1.36.21",
"private": true,
"scripts": {
"dev": "vite --open",
@@ -32,10 +32,11 @@
"@aws-sdk/s3-request-presigner": "^3.535.0",
"@certd/vue-js-cron-light": "^4.0.14",
"@ctrl/tinycolor": "^4.1.0",
"@fast-crud/fast-crud": "^1.25.13",
"@fast-crud/fast-extends": "^1.25.13",
"@fast-crud/ui-antdv4": "^1.25.13",
"@fast-crud/ui-interface": "^1.25.13",
"@fast-crud/editor-code": "^1.26.6",
"@fast-crud/fast-crud": "^1.26.6",
"@fast-crud/fast-extends": "^1.26.6",
"@fast-crud/ui-antdv4": "^1.26.6",
"@fast-crud/ui-interface": "^1.26.6",
"@iconify/tailwind": "^1.2.0",
"@iconify/vue": "^4.1.1",
"@manypkg/get-packages": "^2.2.2",
@@ -103,8 +104,8 @@
"zod-defaults": "^0.1.3"
},
"devDependencies": {
"@certd/lib-iframe": "^1.36.18",
"@certd/pipeline": "^1.36.18",
"@certd/lib-iframe": "^1.36.21",
"@certd/pipeline": "^1.36.21",
"@rollup/plugin-commonjs": "^25.0.7",
"@rollup/plugin-node-resolve": "^15.2.3",
"@types/chai": "^4.3.12",
@@ -138,7 +139,7 @@
"prettier": "3.3.3",
"pretty-quick": "^4.0.0",
"rimraf": "^5.0.5",
"rollup": "^4.13.0",
"rollup": "4.50.0",
"rollup-plugin-visualizer": "^5.12.0",
"stylelint": "^15.11.0",
"stylelint-order": "^6.0.4",
@@ -148,7 +149,7 @@
"tslint": "^6.1.3",
"typescript": "^5.4.2",
"unplugin-vue-define-options": "^1.4.2",
"vite": "^5.3.1",
"vite": "5.4.19",
"vite-plugin-compression": "^0.5.1",
"vite-plugin-html": "^3.2.2",
"vite-plugin-theme": "^0.8.6",
@@ -0,0 +1,50 @@
<template>
<component :is="captchaComponent" v-if="settingStore.inited" ref="captchaRef" class="captcha_input" :captcha-get="getCaptcha" @change="onChange" />
</template>
<script setup lang="ts">
import { ref, computed, defineAsyncComponent } from "vue";
import { useSettingStore } from "/@/store/settings";
import { nanoid } from "nanoid";
import { request } from "/@/api/service";
const captchaRef = ref(null);
const settingStore = useSettingStore();
const emits = defineEmits(["update:modelValue", "change"]);
const captchaImpls = import.meta.glob("./captchas/*.vue");
const captchaAddonId = computed(() => {
return settingStore.sysPublic.captchaAddonId ?? 0;
});
const captchaComponent = computed(() => {
let type = "image";
if (settingStore.sysPublic.captchaAddonId && settingStore.sysPublic.captchaType) {
type = settingStore.sysPublic.captchaType;
}
const componentName = `${type}_captcha`;
return defineAsyncComponent(captchaImpls[`./captchas/${componentName}.vue`]);
});
async function getCaptcha(): Promise<any> {
const randomStr = nanoid(10);
return await request({
url: `/basic/code/captcha/get?randomStr=${randomStr}`,
method: "post",
data: {
captchaAddonId: captchaAddonId.value,
},
});
}
function onChange(data) {
emits("update:modelValue", data);
emits("change", data);
}
async function getCaptchaForm() {
return await captchaRef.value.getCaptchaForm();
}
defineExpose({
getCaptchaForm,
});
</script>
@@ -0,0 +1,96 @@
<template>
<div ref="captchaRef" class="geetest_captcha_wrapper"></div>
</template>
<script setup lang="ts">
import { onMounted, defineProps, defineEmits, ref, onUnmounted } from "vue";
import { useSettingStore } from "/@/store/settings";
import { request } from "/src/api/service";
import { notification } from "ant-design-vue";
defineOptions({
name: "GeetestCaptcha",
});
const emit = defineEmits(["update:modelValue", "change"]);
const props = defineProps<{
captchaGet: () => Promise<any>;
}>();
const captchaRef = ref(null);
// const addonApi = createAddonApi();
const settingStore = useSettingStore();
const captchaInstanceRef = ref({});
async function init() {
// if (!initGeetest4) {
// await import("https://static.geetest.com/v4/gt4.js");
// }
const { captchaId } = await props.captchaGet();
// @ts-ignore
initGeetest4(
{
captchaId: captchaId,
},
(captcha: any) => {
// captcha为验证码实例
captcha.appendTo(captchaRef.value); // 调用appendTo将验证码插入到页的某一个元素中,这个元素用户可以自定义
captchaInstanceRef.value.instance = captcha;
captchaInstanceRef.value.captchaId = captchaId;
}
);
}
function getCaptchaForm() {
if (!captchaInstanceRef.value?.instance) {
// notification.error({
// message: "验证码还未初始化",
// });
return false;
}
const result = captchaInstanceRef.value.instance.getValidate();
if (!result) {
// notification.error({
// message: "请先完成验证码验证",
// });
return false;
}
result.captcha_id = captchaInstanceRef.value.captchaId;
return result;
}
const valueRef = ref(null);
const timeoutId = setInterval(() => {
const form = getCaptchaForm();
if (form && valueRef.value != form) {
console.log("form", form);
valueRef.value = form;
emitChange(form);
}
}, 1000);
onUnmounted(() => {
clearTimeout(timeoutId);
});
function emitChange(value: string) {
emit("update:modelValue", value);
emit("change", value);
}
defineExpose({
getCaptchaForm,
});
onMounted(async () => {
await init();
});
</script>
<style lang="less">
.geetest_captcha_wrapper {
.geetest_captcha {
.geetest_holder {
width: 100%;
}
}
}
</style>
@@ -0,0 +1,59 @@
<template>
<div class="flex">
<a-input :value="valueRef" placeholder="请输入图片验证码" autocomplete="off" @update:value="onChange">
<template #prefix>
<fs-icon icon="ion:image-outline"></fs-icon>
</template>
</a-input>
<div class="input-right pointer" title="点击刷新">
<img class="image-code" :src="imageCodeSrc" @click="resetImageCode" />
</div>
</div>
</template>
<script setup lang="ts">
import { defineEmits, defineExpose, defineProps, ref } from "vue";
import { nanoid } from "nanoid";
const props = defineProps<{
captchaGet?: () => Promise<any>;
}>();
defineOptions({
name: "ImageCaptcha",
});
const emit = defineEmits(["update:modelValue", "change"]);
const valueRef = ref("");
const randomStrRef = ref();
const imageCodeSrc = ref();
async function resetImageCode() {
const res = await props.captchaGet();
randomStrRef.value = res.randomStr;
valueRef.value = "";
emitChange(null);
imageCodeSrc.value = "data:image/svg+xml," + encodeURIComponent(res.imageData);
}
function getCaptchaForm() {
return {
imageCode: valueRef.value,
randomStr: randomStrRef.value,
};
}
defineExpose({
resetImageCode,
getCaptchaForm,
});
resetImageCode();
function onChange(value: string) {
valueRef.value = value;
const form = getCaptchaForm();
emitChange(form);
}
function emitChange(value) {
emit("update:modelValue", value);
emit("change", value);
}
</script>
@@ -66,7 +66,7 @@ const getOptions = async () => {
const input = (pluginType === "plugin" ? form?.input : form) || {};
for (let key in define.input) {
const inWatches = props.watches.includes(key);
const inWatches = props.watches?.includes(key);
const inputDefine = define.input[key];
if (inWatches && inputDefine.required) {
const value = input[key];
@@ -105,7 +105,7 @@ const getOptions = async () => {
const input = (pluginType === "plugin" ? form?.input : form) || {};
for (let key in define.input) {
const inWatches = props.watches.includes(key);
const inWatches = props.watches?.includes(key);
const inputDefine = define.input[key];
if (inWatches && inputDefine.required) {
const value = input[key];
@@ -169,7 +169,7 @@ const getOptions = async () => {
};
const filterOption = (input: string, option: any) => {
return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0 || String(option.value).toLowerCase().indexOf(input.toLowerCase());
return option.label.toLowerCase().includes(input.toLowerCase()) || String(option.value).toLowerCase().includes(input.toLowerCase());
};
async function onClick() {
@@ -0,0 +1,191 @@
<template>
<div class="remote-select">
<div class="flex flex-row">
<a-tree-select class="remote-tree-select-input" :tree-data="optionsRef" :value="value" tree-checkable allow-clear v-bind="attrs" @click="onClick" @update:value="emit('update:value', $event)"> </a-tree-select>
<div class="ml-5">
<fs-button :loading="loading" title="刷新选项" icon="ion:refresh-outline" @click="refreshOptions"></fs-button>
</div>
</div>
<div class="helper" :class="{ error: hasError }">
{{ message }}
</div>
</div>
</template>
<script setup lang="ts">
import { ComponentPropsType, doRequest } from "/@/components/plugins/lib";
import { defineComponent, inject, ref, useAttrs, watch, Ref } from "vue";
import { PluginDefine } from "@certd/pipeline";
defineOptions({
name: "RemoteTreeSelect",
});
const props = defineProps<
{
watches: string[];
search?: boolean;
pager?: boolean;
} & ComponentPropsType
>();
const emit = defineEmits<{
"update:value": any;
}>();
const attrs = useAttrs();
const getCurrentPluginDefine: any = inject("getCurrentPluginDefine", () => {
return {};
});
const getScope: any = inject("get:scope", () => {
return {};
});
const getPluginType: any = inject("get:plugin:type", () => {
return "plugin";
});
const searchKeyRef = ref("");
const optionsRef = ref([]);
const message = ref("");
const hasError = ref(false);
const loading = ref(false);
const pagerRef: Ref = ref({
current: 1,
});
const getOptions = async () => {
if (loading.value) {
return;
}
if (!getCurrentPluginDefine) {
return;
}
const define: PluginDefine = getCurrentPluginDefine()?.value;
if (!define) {
return;
}
const pluginType = getPluginType();
const { form } = getScope();
const input = (pluginType === "plugin" ? form?.input : form) || {};
for (let key in define.input) {
const inWatches = props.watches?.includes(key);
const inputDefine = define.input[key];
if (inWatches && inputDefine.required) {
const value = input[key];
if (value == null || value === "") {
console.log("remote-select required", key);
return;
}
}
}
message.value = "";
hasError.value = false;
loading.value = true;
const pageNo = pagerRef.value.pageNo;
const pageSize = pagerRef.value.pageSize;
try {
const res = await doRequest(
{
type: pluginType,
typeName: form.type,
action: props.action,
input,
data: {
searchKey: props.search ? searchKeyRef.value : "",
pageNo,
pageSize,
},
},
{
onError(err: any) {
hasError.value = true;
message.value = `获取选项出错:${err.message}`;
},
showErrorNotify: false,
}
);
const list = res?.list || res || [];
if (list.length > 0) {
message.value = "获取数据成功,请从下拉框中选择";
} else {
message.value = "获取数据成功,没有数据";
}
optionsRef.value = list;
pagerRef.value.total = list.length;
if (props.pager) {
if (res.pageNo != null) {
pagerRef.value.pageNo = res.pageNo ?? 1;
}
if (res.pageSize != null) {
pagerRef.value.pageSize = res.pageSize ?? 100;
}
if (res.total != null) {
pagerRef.value.total = res.total ?? list.length;
}
}
return res;
} finally {
loading.value = false;
}
};
async function onClick() {
if (optionsRef.value?.length === 0) {
await refreshOptions();
}
}
async function refreshOptions() {
await getOptions();
}
async function doSearch() {
pagerRef.value.pageNo = 1;
await refreshOptions();
}
watch(
() => {
const pluginType = getPluginType();
const { form, key } = getScope();
const input = (pluginType === "plugin" ? form?.input : form) || {};
const watches = {};
for (const key of props.watches) {
//@ts-ignore
watches[key] = input[key];
}
return {
form: watches,
key,
};
},
async (value, oldValue) => {
const { form } = value;
const oldForm: any = oldValue?.form;
let changed = oldForm == null || optionsRef.value.length == 0;
for (const key of props.watches) {
//@ts-ignore
if (oldForm && form[key] != oldForm[key]) {
changed = true;
break;
}
}
if (changed) {
await getOptions();
}
},
{
immediate: true,
}
);
async function onPageChange(current: any) {
await refreshOptions();
}
</script>
<style lang="less"></style>
@@ -2,6 +2,7 @@ import SynologyIdDeviceGetter from "./synology/device-id-getter.vue";
import RemoteAutoComplete from "./common/remote-auto-complete.vue";
import RemoteSelect from "./common/remote-select.vue";
import RemoteInput from "./common/remote-input.vue";
import RemoteTreeSelect from "./common/remote-tree-select.vue";
import CertDomainsGetter from "./common/cert-domains-getter.vue";
import OutputSelector from "/@/components/plugins/common/output-selector/index.vue";
import DnsProviderSelector from "/@/components/plugins/cert/dns-provider-selector/index.vue";
@@ -24,6 +25,7 @@ export default {
app.component("SynologyDeviceIdGetter", SynologyIdDeviceGetter);
app.component("RemoteAutoComplete", RemoteAutoComplete);
app.component("RemoteSelect", RemoteSelect);
app.component("RemoteTreeSelect", RemoteTreeSelect);
app.component("RemoteInput", RemoteInput);
app.component("CertDomainsGetter", CertDomainsGetter);
app.component("InputPassword", InputPassword);
@@ -21,6 +21,7 @@ export default {
pipeline: "Pipeline",
domain: "Domain",
deployTimes: "Deployments",
monitorCount: "DomainMonitors",
duration: "Duration",
price: "Price",
paymentMethod: "Payment Method",
@@ -118,6 +119,7 @@ export default {
scheduledTaskCount: "Scheduled Task Count",
deployTaskCount: "Deployment Task Count",
remainingValidity: "Remaining Validity",
effectiveTime: "Effective time",
expiryTime: "Expiry Time",
status: "Status",
lastRun: "Last Run",
@@ -218,6 +220,7 @@ export default {
triggerCronHelper:
"Click the button above to choose a daily execution time.\nIt is recommended to trigger once per day. The task will be skipped if the certificate has not expired and will not be executed repeatedly.",
notificationTitle: "Failure Notification",
notificationWhen: "Notification Timing",
notificationHelper: "Get real-time alerts when the task fails",
groupIdTitle: "Pipeline Group",
},
@@ -248,7 +251,9 @@ export default {
ok: "Valid",
expired: "Expired",
},
certEffectiveTime: "Certificate Effective",
certExpiresTime: "Certificate Expiration",
remainingValidity: "Remaining Validity",
expired: "expired",
days: "days",
lastCheckTime: "Last Check Time",
@@ -463,6 +468,7 @@ export default {
validDays: "Valid Days",
expires: " expires",
days: " days",
effectiveTime: "Effective Time",
expireTime: "Expiration Time",
certIssuer: "Certificate Issuer",
applyTime: "Application Time",
@@ -705,10 +711,23 @@ export default {
pipeline: "Pipeline",
},
addonType: "Type",
addonName: "Name",
addonNameHelper: "Fill freely, helps to distinguish when multiple same type exist",
addonTypeSelect: "Select type",
sys: {
setting: {
showRunStrategy: "Show RunStrategy",
showRunStrategyHelper: "Allow modify the run strategy of the task",
captchaEnabled: "Enable Login Captcha",
captchaHelper: "Whether to enable captcha verification for login",
captchaType: "Captcha Setting",
baseSetting: "Base Settings",
registerSetting: "Register Settings",
safeSetting: "Safe Settings",
paymentSetting: "Payment Settings",
},
},
modal: {
@@ -729,4 +748,8 @@ export default {
challengeSetting: "Challenge Setting",
gotoCnameTip: "Please go to CNAME Record Page",
},
addonSelector: {
select: "Select",
placeholder: "select please",
},
};
@@ -25,6 +25,7 @@ export default {
pipeline: "流水线",
domain: "域名",
deployTimes: "部署次数",
monitorCount: "域名监控数",
duration: "时长",
price: "价格",
paymentMethod: "支付方式",
@@ -124,6 +125,7 @@ export default {
scheduledTaskCount: "定时任务数",
deployTaskCount: "部署任务数",
remainingValidity: "到期剩余",
effectiveTime: "生效时间",
expiryTime: "过期时间",
status: "状态",
lastRun: "最后运行",
@@ -223,6 +225,7 @@ export default {
triggerCronTitle: "定时触发",
triggerCronHelper: "点击上面的按钮,选择每天几点定时执行。\n建议设置为每天触发一次,证书未到期之前任务会跳过,不会重复执行",
notificationTitle: "失败通知",
notificationWhen: "通知时机",
notificationHelper: "任务执行失败实时提醒",
groupIdTitle: "流水线分组",
},
@@ -253,7 +256,9 @@ export default {
ok: "正常",
expired: "过期",
},
certEffectiveTime: "证书生效时间",
certExpiresTime: "证书到期时间",
remainingValidity: "到期剩余",
expired: "过期",
days: "天",
lastCheckTime: "上次检查时间",
@@ -469,6 +474,7 @@ export default {
validDays: "有效天数",
expires: "过期",
days: "天",
effectiveTime: "生效时间",
expireTime: "过期时间",
certIssuer: "证书颁发机构",
applyTime: "申请时间",
@@ -693,7 +699,10 @@ export default {
setAsDefault: "设为默认",
disabledLabel: "禁用",
confirmToggleStatus: "确定要{action}吗?",
addonType: "类型",
addonName: "名称",
addonNameHelper: "随意填写,相同类型助于区分即可",
addonTypeSelect: "请选择",
template: {
title: "流水线模版",
edit: "流水线模版编辑",
@@ -712,6 +721,15 @@ export default {
setting: {
showRunStrategy: "显示运行策略选择",
showRunStrategyHelper: "任务设置中是否允许选择运行策略",
captchaEnabled: "启用登录验证码",
captchaHelper: "登录时是否启用验证码",
captchaType: "验证码配置",
baseSetting: "基本设置",
registerSetting: "注册设置",
safeSetting: "安全设置",
paymentSetting: "支付设置",
},
},
modal: {
@@ -732,4 +750,8 @@ export default {
challengeSetting: "校验配置",
gotoCnameTip: "CNAME域名配置请前往CNAME记录页面添加",
},
addonSelector: {
select: "选择",
placeholder: "请选择",
},
};
@@ -0,0 +1,12 @@
import { useSettingStore } from "/@/store/settings";
export default {
mounted(el: any, binding: any, vnode: any) {
const settingStore = useSettingStore();
const isComm = settingStore.isComm;
const { value } = binding;
if ((value === false && isComm) || (value === true && !isComm)) {
el.parentNode && el.parentNode.removeChild(el);
}
},
};
@@ -0,0 +1,8 @@
import comm from "./comm-show.js";
const install = function (app: any) {
app.directive("comm", comm);
};
export default {
install,
};
@@ -2,7 +2,7 @@ import { request } from "/src/api/service";
// import "/src/mock";
import { ColumnCompositionProps, CrudOptions, FastCrud, PageQuery, PageRes, setLogger, TransformResProps, useColumns, UseCrudProps, UserPageQuery, useTypes, utils } from "@fast-crud/fast-crud";
import "@fast-crud/fast-crud/dist/style.css";
import { FsExtendsCopyable, FsExtendsEditor, FsExtendsJson, FsExtendsTime, FsExtendsUploader, FsExtendsInput, FsUploaderS3SignedUrlType, FsUploaderGetAuthContext, FsUploaderAliossSTS } from "@fast-crud/fast-extends";
import { FsExtendsCopyable, FsExtendsEditor, FsExtendsJson, FsExtendsTime, FsExtendsUploader, FsExtendsInput } from "@fast-crud/fast-extends";
import "@fast-crud/fast-extends/dist/style.css";
import UiAntdv from "@fast-crud/ui-antdv4";
import "@fast-crud/ui-antdv4/dist/style.css";
@@ -13,6 +13,9 @@ import { notification } from "ant-design-vue";
import { usePreferences } from "/@/vben/preferences";
import { LocalStorage } from "/@/utils/util.storage";
import { FsEditorCode } from "@fast-crud/editor-code";
import "@fast-crud/editor-code/dist/style.css"
class ColumnSizeSaver {
save: (key: string, size: number) => void;
constructor() {
@@ -272,6 +275,7 @@ function install(app: App, options: any = {}) {
app.use(FsExtendsTime);
app.use(FsExtendsCopyable);
app.use(FsExtendsInput);
app.use(FsEditorCode);
const { addTypes, getType } = useTypes();
//此处演示修改官方字段类型
@@ -4,9 +4,13 @@ import FastCrud from "./fast-crud";
import permission from "./permission";
import { App } from "vue";
import "./validator/index.js";
import directives from "./directive/index";
import { setupMonaco } from "./monaco";
function install(app: App, options: any = {}) {
app.use(FastCrud, options);
app.use(permission);
app.use(directives);
setupMonaco();
}
export default {
@@ -0,0 +1,15 @@
import editorWorker from "monaco-editor/esm/vs/editor/editor.worker?worker";
import jsonWorker from "monaco-editor/esm/vs/language/json/json.worker?worker";
import cssWorker from "monaco-editor/esm/vs/language/css/css.worker?worker";
import htmlWorker from "monaco-editor/esm/vs/language/html/html.worker?worker";
import yamlWorker from "./yaml.worker?worker";
import tsWorker from "monaco-editor/esm/vs/language/typescript/ts.worker?worker";
import { registerWorker } from "@fast-crud/editor-code";
export function setupMonaco() {
registerWorker("json", jsonWorker);
registerWorker(["css", "less", "scss"], cssWorker);
registerWorker(["html", "handlebars", "razor"], htmlWorker);
registerWorker(["yaml", "yml"], yamlWorker);
registerWorker(["typescript", "javascript"], tsWorker);
registerWorker("*", editorWorker);
}
@@ -0,0 +1 @@
export * from "monaco-yaml/yaml.worker.js";
@@ -167,7 +167,7 @@ export const usePluginStore = defineStore({
},
async clear() {
this.group = null;
this.originGroup = null
this.originGroup = null;
},
async getList(): Promise<PluginDefine[]> {
await this.init();
@@ -46,6 +46,10 @@ export type SysPublicSetting = {
aiChatEnabled?: boolean;
showRunStrategy?: boolean;
captchaEnabled?: boolean;
captchaType?: number;
captchaAddonId?: number;
};
export type SuiteSetting = {
enabled?: boolean;
@@ -12,6 +12,7 @@ import { cloneDeep, merge } from "lodash-es";
import { useI18n } from "/src/locales";
import dayjs from "dayjs";
export interface SettingState {
skipReset?: boolean; // 注销登录时,不清空此store的状态
sysPublic?: SysPublicSetting;
installInfo?: {
siteId: string;
@@ -64,6 +65,7 @@ const defaultSiteInfo: SiteInfo = {
export const useSettingStore = defineStore({
id: "app.setting",
state: (): SettingState => ({
skipReset: true,
plusInfo: {
isPlus: false,
vipType: "free",
@@ -38,6 +38,9 @@ export function resetAllStores() {
}
const allStores = (pinia as any)._s;
for (const [_key, store] of allStores) {
if (store.skipReset) {
continue;
}
store.$reset();
}
}
@@ -105,9 +105,11 @@ export default function ({ crudExpose, context }: CreateCrudOptionsProps): Creat
form: {
rules: [{ required: true, message: t("certd.pleaseEnterName") }],
helper: t("certd.nameHelper"),
order: -2,
},
column: {
width: 200,
order: -2,
},
},
from: {
@@ -87,6 +87,7 @@ export function getCommonColumnDefine(crudExpose: any, typeRef: any, api: any) {
order: -1,
},
form: {
order: -1,
component: {
disabled: false,
showSearch: true,
@@ -79,6 +79,7 @@ export default function ({ crudExpose, context }: CreateCrudOptionsProps): Creat
},
form: {
rules: [{ required: true, message: "必填项" }],
order: -11,
},
column: {
width: 300,
@@ -0,0 +1,178 @@
<template>
<div class="addon-selector">
<div class="flex-o w-100">
<!-- <fs-dict-select class="flex-1" :value="modelValue" :dict="optionsDictRef" :disabled="disabled" :render-label="renderLabel" :slots="selectSlots" :allow-clear="true" v-bind="select" @update:value="onChange" />-->
<span v-if="modelValue" class="mr-5 cd-flex-inline">
<a-tag class="mr-5" color="green">{{ target?.name || modelValue }}</a-tag>
<fs-icon class="cd-icon-button" icon="ion:close-circle-outline" @click="clear"></fs-icon>
</span>
<span v-else class="mlr-5 text-gray">{{ placeholder || t("certd.addonSelector.placeholder") }}</span>
<fs-table-select
ref="tableSelectRef"
class="flex-0"
:model-value="modelValue"
:dict="optionsDictRef"
:create-crud-options="createCrudOptionsWithApi"
:crud-options-override="{
search: { show: false },
table: {
scroll: {
x: 540,
},
},
}"
:show-current="false"
:show-select="false"
:dialog="{ width: 960 }"
:destroy-on-close="false"
height="400px"
v-bind="tableSelect"
@update:model-value="onChange"
@dialog-closed="doRefresh"
>
<template #default="scope">
<fs-button class="ml-5" :disabled="disabled" :size="size" type="primary" :text="t('certd.addonSelector.select')" @click="scope.open" />
</template>
</fs-table-select>
</div>
</div>
</template>
<script lang="tsx" setup>
import { inject, ref, Ref, watch } from "vue";
import { createAddonApi } from "../api";
import { message } from "ant-design-vue";
import { dict } from "@fast-crud/fast-crud";
import createCrudOptions from "../crud";
import { addonProvide } from "../common";
import { useUserStore } from "/@/store/user";
import { useI18n } from "/src/locales";
const { t } = useI18n();
defineOptions({
name: "AddonSelector",
});
const props = defineProps<{
modelValue?: number | string | number[] | string[];
type?: string;
placeholder?: string;
size?: string;
disabled?: boolean;
select?: any;
tableSelect?: any;
addonType: string;
from?: string;
}>();
const onChange = async (value: number) => {
await emitValue(value);
};
const emit = defineEmits(["update:modelValue", "selected-change", "change"]);
const api = createAddonApi({
from: props.from,
addonType: props.addonType,
});
addonProvide(api);
function createCrudOptionsWithApi(opts: any) {
opts.context = {
api,
addonType: props.addonType,
};
return createCrudOptions(opts);
}
const tableSelectRef = ref();
const optionsDictRef = dict({
url: `/addon/options?addonType=${props.addonType}`,
value: "id",
label: "name",
});
const renderLabel = (option: any) => {
return <span>{option.name}</span>;
};
async function openTableSelectDialog() {
selectOpened.value = false;
await tableSelectRef.value.open({});
await tableSelectRef.value.crudExpose.openAdd({});
}
const selectOpened = ref(false);
const selectSlots = ref({
dropdownRender({ menuNode, props }: any) {
const res = [];
res.push(menuNode);
// res.push(<a-divider style="margin: 4px 0" />);
// res.push(<a-space style="padding: 4px 8px" />);
// res.push(<fs-button class="w-100" type="text" icon="plus-outlined" text="新建通知渠道" onClick={openTableSelectDialog}></fs-button>);
return res;
},
});
const target: Ref<any> = ref({});
function clear() {
if (props.disabled) {
return;
}
emitValue(null);
}
const userStore = useUserStore();
async function emitValue(value: any) {
// target.value = optionsDictRef.dataMap[value];
const userId = userStore.userInfo.id;
if (pipeline?.value && pipeline.value.userId !== userId) {
message.error(`对不起,您不能修改他人流水线的${props.addonType}设置`);
return;
}
emit("change", value);
emit("update:modelValue", value);
}
async function refreshTarget(value: any) {
if (value > 0) {
target.value = await api.GetSimpleInfo(value);
} else {
target.value = {
//captchaType会监听此字段,给个默认值
type: "",
};
}
}
watch(
() => {
return props.modelValue;
},
async value => {
// await optionsDictRef.loadDict();
//@ts-ignore
await refreshTarget(value);
// target.value = optionsDictRef.dataMap[value];
emit("selected-change", target.value);
},
{
immediate: true,
}
);
//当不在pipeline中编辑时,可能为空
const pipeline = inject("pipeline", null);
async function doRefresh() {
await optionsDictRef.reloadDict();
}
</script>
<style lang="less">
.addon-selector {
width: 100%;
}
</style>
@@ -0,0 +1,142 @@
import { request } from "/src/api/service";
import { RequestHandleReq } from "/@/components/plugins/lib";
export function createAddonApi(opts: { from: any; addonType: string }) {
let apiPrefix = "/addon";
if (opts.from === "sys") {
apiPrefix = "/sys/addon";
}
return {
async GetList(query: any) {
return await request({
url: apiPrefix + "/page",
method: "post",
data: {
...query,
query: {
addonType: opts.addonType,
...query.query,
},
},
});
},
async AddObj(obj: any) {
return await request({
url: apiPrefix + "/add",
method: "post",
data: {
...obj,
addonType: opts.addonType,
},
});
},
async UpdateObj(obj: any) {
return await request({
url: apiPrefix + "/update",
method: "post",
data: obj,
});
},
async DelObj(id: number) {
return await request({
url: apiPrefix + "/delete",
method: "post",
params: { id },
});
},
async GetObj(id: number) {
return await request({
url: apiPrefix + "/info",
method: "post",
params: { id },
});
},
async GetOptions(id: number) {
return await request({
url: apiPrefix + `/options?addonType=${opts.addonType}`,
method: "post",
});
},
async SetDefault(id: number) {
return await request({
url: apiPrefix + "/setDefault",
method: "post",
params: { id },
});
},
async GetDefaultId() {
return await request({
url: apiPrefix + "/getDefaultId",
method: "post",
});
},
async GetSimpleInfo(id: number) {
return await request({
url: apiPrefix + `/simpleInfo?addonType=${opts.addonType}`,
method: "post",
params: { id },
});
},
async GetDefineTypes() {
return await request({
url: apiPrefix + `/getTypeDict?addonType=${opts.addonType}`,
method: "post",
});
},
async GetProviderDefine(type: string) {
return await request({
url: apiPrefix + `/define?addonType=${opts.addonType}`,
method: "post",
params: { type },
});
},
async GetProviderDefineByType(type: string) {
return await request({
url: apiPrefix + `/defineByType?addonType=${opts.addonType}`,
method: "post",
params: { type },
});
},
async Handle(req: RequestHandleReq, opts: any = {}) {
const url = `/handle/${req.type}?addonType=${opts.addonType}`;
const { typeName, action, data, input } = req;
const res = await request({
url,
method: "post",
data: {
typeName,
action,
data,
input,
},
...opts,
});
return res;
},
};
}
export const AddonTypeDefines = {
captcha: {
name: "captcha",
title: "验证码",
showDefault: false,
showTest: false,
},
};
export function getAddonTypeDefine(addonType: string) {
return AddonTypeDefines[addonType];
}
@@ -0,0 +1,280 @@
import { ColumnCompositionProps, compute, dict } from "@fast-crud/fast-crud";
import { computed, provide, ref, toRef } from "vue";
import { useReference } from "/@/use/use-refrence";
import { forEach, get, merge, set } from "lodash-es";
import { Modal } from "ant-design-vue";
import { mitter } from "/@/utils/util.mitt";
import { useI18n } from "/src/locales";
import * as pipelineApi from "/@/views/certd/pipeline/api";
import { getAddonTypeDefine } from "/@/views/certd/addon/api";
export function addonProvide(api: any) {
provide("addonApi", api);
provide("get:plugin:type", () => {
return "addon";
});
}
export function getCommonColumnDefine(crudExpose: any, typeRef: any, api: any, addonType: string) {
const { t } = useI18n();
// const addonTypeTypeDictRef = dict({
// data: [{ value: "captcha", label: "验证码" }],
// });
const addonTypeDictRef = dict({
url: `/addon/getTypeDict?addonType=${addonType}`,
});
const defaultPluginConfig = {
component: {
name: "a-input",
vModel: "value",
},
};
function buildDefineFields(define: any, form: any, mode: string) {
const formWrapperRef = crudExpose.getFormWrapperRef();
const columnsRef = toRef(formWrapperRef.formOptions, "columns");
for (const key in columnsRef.value) {
if (key.indexOf(".") >= 0) {
delete columnsRef.value[key];
}
}
console.log('crudBinding.value[mode + "Form"].columns', columnsRef.value);
forEach(define.input, (value: any, mapKey: any) => {
const key = "body." + mapKey;
const field = {
...value,
key,
};
const column = merge({ title: key }, defaultPluginConfig, field);
//eval
useReference(column);
if (column.required) {
if (!column.rules) {
column.rules = [];
}
column.rules.push({ required: true, message: t("certd.requiredField") });
}
//设置默认值
if (column.value != null && get(form, key) == null) {
set(form, key, column.value);
}
//字段配置赋值
columnsRef.value[key] = column;
});
}
const currentDefine = ref();
return {
id: {
title: "ID",
key: "id",
type: "number",
column: {
width: 100,
},
form: {
show: false,
},
},
// addonType: {
// title: "Addon类型",
// type: "dict-select",
// dict: addonTypeTypeDictRef,
// search: {
// show: false,
// },
// column: {
// width: 200,
// component: {
// color: "auto",
// },
// },
// form: {
// onChange(ctx: { value: any }) {
// addonTypeDictRef.url = `/addon/getTypeDict?addonType=${ctx.value}`;
// },
// },
// editForm: {
// component: {
// disabled: false,
// },
// },
// },
type: {
title: t("certd.addonType"),
type: "dict-select",
dict: addonTypeDictRef,
search: {
show: false,
},
column: {
width: 200,
component: {
color: "auto",
},
},
editForm: {
component: {
disabled: false,
},
},
form: {
order: -22,
component: {
disabled: false,
showSearch: true,
filterOption: (input: string, option: any) => {
input = input?.toLowerCase();
return option.value.toLowerCase().indexOf(input) >= 0 || option.label.toLowerCase().indexOf(input) >= 0;
},
renderLabel(item: any) {
return (
<span class={"flex-o flex-between"}>
{item.label}
{item.needPlus && <fs-icon icon={"mingcute:vip-1-line"} className={"color-plus"}></fs-icon>}
</span>
);
},
},
rules: [{ required: true, message: t("certd.addonTypeSelect") }],
valueChange: {
immediate: true,
async handle({ value, mode, form, immediate }) {
if (value == null) {
return;
}
const lastTitle = currentDefine.value?.title;
const define = await api.GetProviderDefine(value);
currentDefine.value = define;
console.log("define", define);
if (!immediate) {
form.body = {};
if (define.needPlus) {
mitter.emit("openVipModal");
}
}
if (!form.name || form.name === lastTitle) {
form.name = define.title;
}
buildDefineFields(define, form, mode);
},
},
helper: computed(() => {
const define = currentDefine.value;
if (define == null) {
return "";
}
return define.desc;
}),
},
} as ColumnCompositionProps,
name: {
title: t("certd.addonName"),
search: {
show: true,
},
type: ["text"],
form: {
order: -2,
rules: [{ required: true, message: t("certd.enterName") }],
helper: t("certd.addonNameHelper"),
},
column: {
width: 200,
},
},
isDefault: {
title: t("certd.isDefault"),
type: "dict-switch",
dict: dict({
data: [
{ label: t("certd.yes"), value: true, color: "success" },
{ label: t("certd.no"), value: false, color: "default" },
],
}),
form: {
show: computed(() => {
return getAddonTypeDefine(addonType)?.showDefault ?? false;
}),
value: false,
rules: [{ required: true, message: t("certd.selectIsDefault") }],
order: 999,
},
column: {
align: "center",
width: 100,
show: computed(() => {
return getAddonTypeDefine(addonType)?.showDefault ?? false;
}),
component: {
name: "a-switch",
vModel: "checked",
disabled: compute(({ value }) => {
return value === true;
}),
on: {
// @ts-ignore
change({ row }) {
Modal.confirm({
title: t("certd.prompt"),
content: t("certd.confirmSetDefaultNotification"),
onOk: async () => {
await api.SetDefault(row.id);
await crudExpose.doRefresh();
},
onCancel: async () => {
await crudExpose.doRefresh();
},
});
},
},
},
},
},
test: {
title: t("certd.test"),
form: {
show: compute(({ form }) => {
return !!form.type && currentDefine.value?.showTest === true;
}),
component: {
name: "api-test",
action: "TestRequest",
},
order: 990,
col: {
span: 24,
},
},
column: {
show: false,
},
},
setting: {
column: { show: false },
form: {
show: false,
valueBuilder({ value, form }) {
form.body = {};
if (!value) {
return;
}
const setting = JSON.parse(value);
for (const key in setting) {
form.body[key] = setting[key];
}
},
valueResolve({ form }) {
const setting = form.body;
form.setting = JSON.stringify(setting);
},
},
} as ColumnCompositionProps,
};
}
@@ -0,0 +1,55 @@
import { ref } from "vue";
import { getCommonColumnDefine } from "./common";
import { AddReq, CreateCrudOptionsProps, CreateCrudOptionsRet, DelReq, EditReq, UserPageQuery, UserPageRes } from "@fast-crud/fast-crud";
export default function ({ crudExpose, context }: CreateCrudOptionsProps): CreateCrudOptionsRet {
const api = context.api;
const addonType = context.addonType;
const pageRequest = async (query: UserPageQuery): Promise<UserPageRes> => {
return await api.GetList(query);
};
const editRequest = async (req: EditReq) => {
const { form, row } = req;
form.id = row.id;
const res = await api.UpdateObj(form);
return res;
};
const delRequest = async (req: DelReq) => {
const { row } = req;
return await api.DelObj(row.id);
};
const addRequest = async (req: AddReq) => {
const { form } = req;
const res = await api.AddObj(form);
return res;
};
const typeRef = ref();
const commonColumnsDefine = getCommonColumnDefine(crudExpose, typeRef, api, addonType);
return {
crudOptions: {
request: {
pageRequest,
addRequest,
editRequest,
delRequest,
},
form: {
labelCol: {
//固定label宽度
span: null,
style: {
width: "145px",
},
},
},
rowHandle: {
width: 200,
},
columns: {
...commonColumnsDefine,
},
},
};
}
@@ -0,0 +1,41 @@
<template>
<fs-page>
<template #header>
<div class="title">
通知管理
<span class="sub">管理通知配置</span>
</div>
</template>
<fs-crud ref="crudRef" v-bind="crudBinding"> </fs-crud>
</fs-page>
</template>
<script lang="ts">
import { defineComponent, onActivated, onMounted } from "vue";
import { useFs } from "@fast-crud/fast-crud";
import createCrudOptions from "./crud";
import { createAddonApi } from "./api";
import { addonProvide } from "/@/views/certd/addon/common";
export default defineComponent({
name: "AddonManager",
setup() {
const api = createAddonApi();
addonProvide(api);
const { crudBinding, crudRef, crudExpose } = useFs({ createCrudOptions, context: { api } });
// 页面打开后获取列表数据
onMounted(() => {
crudExpose.doRefresh();
});
onActivated(() => {
crudExpose.doRefresh();
});
return {
crudBinding,
crudRef,
};
},
});
</script>
@@ -4,7 +4,7 @@
<div class="title">
{{ t("certd.cnameRecord") }}
<span class="sub">
<a href="https://certd.docmirror.cn/guide/feature/cname/" target="_blank">
<a v-comm="false" href="https://certd.docmirror.cn/guide/feature/cname/" target="_blank">
{{ t("certd.cname_feature_guide") }}
</a>
</span>
@@ -220,22 +220,47 @@ export default function ({ crudExpose, context }: CreateCrudOptionsProps): Creat
sorter: true,
conditionalRender: false,
cellRender({ row }) {
const value = row.expiresTime;
if (!value) {
const {
applyTime,
effectiveTime,
expiresTime,
} = row || {};
if (!expiresTime) {
return "-";
}
const expireDate = dayjs(value).format("YYYY-MM-DD");
const leftDays = dayjs(value).diff(dayjs(), "day");
// 申请时间 ps:此处为证书在certd创建的时间而非实际证书申请时间
const applyDate = dayjs(effectiveTime ?? applyTime ?? Date.now()).format("YYYY-MM-DD");
// 失效时间
const expireDate = dayjs(expiresTime).format("YYYY-MM-DD");
// 有效天数 ps:此处证书最小设置为90d
const effectiveDays = Math.max(90, dayjs(expiresTime).diff(applyDate, "day"));
// 距离失效时间剩余天数
const leftDays = dayjs(expiresTime).diff(dayjs(), "day");
const color = leftDays < 20 ? "red" : "#389e0d";
const percent = (leftDays / 90) * 100;
const percent = (leftDays / effectiveDays) * 100;
const textColor = leftDays < 20 ? "red" : leftDays > 60 ? "#389e0d" : "";
const format = () => {
return <span style={{ color: textColor }}>{`${leftDays}${t("certd.days")}`}</span>;
};
// console.log('cellRender', 'effectiveDays', effectiveDays, 'expiresTime', expiresTime, 'applyTime', applyTime, 'percent', percent, row)
return <a-progress title={expireDate + t("certd.expires")} percent={percent} strokeColor={color} format={format} />;
},
},
},
effectiveTime: {
title: t("certd.effectiveTime"),
search: {
show: false,
},
type: "datetime",
form: {
show: false,
},
column: {
sorter: true,
show: false,
},
},
expiresTime: {
title: t("certd.expireTime"),
search: {
@@ -345,25 +345,64 @@ export default function ({ crudExpose, context }: CreateCrudOptionsProps): Creat
align: "center",
},
},
certEffectiveTime: {
title: t("certd.monitor.certEffectiveTime"),
search: {
show: false,
},
type: "datetime",
form: {
show: false,
},
column: {
sorter: true,
width: 155,
},
},
certExpiresTime: {
title: t("certd.monitor.certExpiresTime"),
search: {
show: false,
},
type: "datetime",
form: {
show: false,
},
column: {
sorter: true,
width: 155,
},
},
remainingValidity: {
title: t("certd.monitor.remainingValidity"),
search: {
show: false,
},
type: "date",
form: {
show: false,
},
column: {
sorter: true,
cellRender({ value }) {
if (!value) {
conditionalRender: false,
cellRender({ row }) {
const {
certEffectiveTime: effectiveTime,
certExpiresTime: expiresTime,
} = row || {};
if (!expiresTime) {
return "-";
}
const expireDate = dayjs(value).format("YYYY-MM-DD");
const leftDays = dayjs(value).diff(dayjs(), "day");
// 申请时间 ps:此处为证书在certd创建的时间而非实际证书申请时间
const applyDate = dayjs(effectiveTime ?? Date.now()).format("YYYY-MM-DD");
// 失效时间
const expireDate = dayjs(expiresTime).format("YYYY-MM-DD");
// 有效天数 ps:此处证书最小设置为90d
const effectiveDays = Math.max(90, dayjs(expiresTime).diff(applyDate, "day"));
// 距离失效时间剩余天数
const leftDays = dayjs(expiresTime).diff(dayjs(), "day");
const color = leftDays < 20 ? "red" : "#389e0d";
const percent = (leftDays / 90) * 100;
const percent = (leftDays / effectiveDays) * 100;
// console.log('cellRender', 'effectiveDays', effectiveDays, 'expiresTime', expiresTime, 'applyTime', applyTime, 'percent', percent, row)
return <a-progress title={expireDate + t("certd.monitor.expired")} percent={percent} strokeColor={color} format={(percent: number) => `${leftDays}${t("certd.monitor.days")}`} />;
},
},
@@ -96,6 +96,7 @@ export function getCommonColumnDefine(crudExpose: any, typeRef: any, api: any) {
},
},
form: {
order: -3,
component: {
disabled: false,
showSearch: true,
@@ -153,6 +154,7 @@ export function getCommonColumnDefine(crudExpose: any, typeRef: any, api: any) {
},
type: ["text"],
form: {
order: -2,
rules: [{ required: true, message: t("certd.enterName") }],
helper: t("certd.helperNotificationName"),
},
@@ -3,7 +3,7 @@
<template #header>
<div class="title">开放接口密钥管理</div>
<div class="more">
<a :href="OPEN_API_DOC" target="_blank">开放接口文档</a>
<a v-comm="false" :href="OPEN_API_DOC" target="_blank">开放接口文档</a>
</div>
</template>
<fs-crud ref="crudRef" v-bind="crudBinding"> </fs-crud>
@@ -22,7 +22,7 @@ export function fillPipelineByDefaultForm(pipeline: any, form: any) {
if (form.notification != null) {
notifications.push({
type: "custom",
when: ["error", "turnToSuccess", "success"],
when: form.notificationWhen || ["error", "turnToSuccess"],
notificationId: form.notification,
title: form.notificationTarget?.name || "自定义通知",
});
@@ -223,6 +223,25 @@ export function useCertPipelineCreator() {
helper: t("certd.pipelineForm.notificationHelper"),
},
},
notificationWhen: {
title: t("certd.pipelineForm.notificationWhen"),
type: "text",
form: {
value: ["error", "turnToSuccess"],
component: {
name: "a-select",
vModel: "value",
mode: "multiple",
options: [
{ value: "start", label: t("certd.start_time") },
{ value: "success", label: t("certd.success_time") },
{ value: "turnToSuccess", label: t("certd.fail_to_success_time") },
{ value: "error", label: t("certd.fail_time") },
],
},
order: 102,
},
},
groupId: {
title: t("certd.pipelineForm.groupIdTitle"),
type: "dict-select",
@@ -268,7 +287,7 @@ export function useCertPipelineCreator() {
async function doSubmit({ form }: any) {
// const certDetail = readCertDetail(form.cert.crt);
// 添加certd pipeline
const pluginInput = omit(form, ["triggerCron", "notification", "notificationTarget", "certApplyPlugin", "groupId"]);
const pluginInput = omit(form, ["triggerCron", "notification", "notificationTarget", "notificationWhen", "certApplyPlugin", "groupId"]);
let pipeline: any = {
title: form.domains[0] + "证书自动化",
runnableType: "pipeline",
@@ -366,23 +366,49 @@ export default function ({ crudExpose, context: { groupDictRef, selectedRowKeys
},
column: {
cellRender({ row }) {
const value = row.lastVars?.certExpiresTime;
if (!value) {
const {
certEffectiveTime: effectiveTime,
certExpiresTime: expiresTime,
} = row?.lastVars || {};
if (!expiresTime) {
return "-";
}
const expireDate = dayjs(value).format("YYYY-MM-DD");
const leftDays = dayjs(value).diff(dayjs(), "day");
// 申请时间 ps:此处为证书在certd创建的时间而非实际证书申请时间
const applyDate = dayjs(effectiveTime ?? Date.now()).format("YYYY-MM-DD");
// 失效时间
const expireDate = dayjs(expiresTime).format("YYYY-MM-DD");
// 有效天数 ps:此处证书最小设置为90d
const effectiveDays = Math.max(90, dayjs(expiresTime).diff(applyDate, "day"));
// 距离失效时间剩余天数
const leftDays = dayjs(expiresTime).diff(dayjs(), "day");
const color = leftDays < 20 ? "red" : "#389e0d";
const percent = (leftDays / 90) * 100;
const percent = (leftDays / effectiveDays) * 100;
const textColor = leftDays < 20 ? "red" : leftDays > 60 ? "#389e0d" : "";
const format = () => {
return <span style={{ color: textColor }}>{`${leftDays}${t("certd.days")}`}</span>;
};
// console.log('cellRender', 'effectiveDays', effectiveDays, 'expiresTime', expiresTime, 'applyTime', applyTime, 'percent', percent, row)
return <a-progress title={expireDate + t("certd.expires")} percent={percent} strokeColor={color} format={format} />;
},
width: 150,
},
},
"lastVars.certEffectiveTime": {
title: t("certd.fields.effectiveTime"),
search: {
show: false,
},
type: "datetime",
form: {
show: false,
},
column: {
sorter: false,
show: false,
width: 150,
align: "center",
},
},
"lastVars.certExpiresTime": {
title: t("certd.fields.expiryTime"),
search: {
@@ -313,6 +313,8 @@ function useStepForm() {
};
const stepDelete = () => {
//检查输出依赖
Modal.confirm({
title: "确认",
content: `确定要删除此步骤吗?`,
@@ -279,7 +279,7 @@
</fs-page>
</template>
<script lang="ts">
<script lang="tsx">
import { computed, defineComponent, onMounted, onUnmounted, provide, ref, Ref, watch } from "vue";
import { useRouter } from "vue-router";
import PiTaskForm from "./component/task-form/index.vue";
@@ -758,9 +758,12 @@ export default defineComponent({
//stepid
let hasError = false;
let errorMessage = "";
let errorMessages: any = [];
let errorIndex = 1;
eachSteps(pp, (step: any, task: any, stage: any) => {
stepIds.push(step.id);
if (step.disabled !== true) {
stepIds.push(step.id);
}
if (step.input) {
for (const key in step.input) {
const value = step.input[key];
@@ -775,21 +778,36 @@ export default defineComponent({
const paramName = arr[2];
if (!stepIds.includes(stepId)) {
hasError = true;
const message = `任务${step.title}的前置输出步骤${paramName}不存在,请重新修改此任务`;
const message = `${step.title}的前置输出步骤${paramName}不存在或已被禁用`;
errorIndex++;
addValidateError(task.id, {
message,
});
addValidateError(step.id, {
message,
});
errorMessage += message + "";
errorMessages.push(message);
}
}
}
});
if (hasError) {
notification.error({ message: errorMessage });
notification.error({
message: () => {
const nodes = [];
let i = 0;
for (const error of errorMessages) {
i++;
nodes.push(
<div>
{i}.{error}
</div>
);
}
return nodes;
},
});
throw new Error(errorMessage);
}
}
@@ -4,10 +4,14 @@
<div class="title">
{{ t("certd.subdomainHosting") }}
<span class="sub">
{{ t("certd.subdomainHostingHint") }} {{ t("certd.subdomainHelpText") }}
<a href="https://certd.docmirror.cn/guide/use/cert/subdomain.html" target="_blank">
{{ t("certd.subdomainManagement") }}
</a>
{{ t("certd.subdomainHostingHint") }}
<span v-comm="false">
{{ t("certd.subdomainHelpText") }}
<a href="https://certd.docmirror.cn/guide/use/cert/subdomain.html" target="_blank">
{{ t("certd.subdomainManagement") }}
</a>
</span>
</span>
</div>
</template>
@@ -9,6 +9,8 @@ export type SuiteValue = {
export type SuiteDetail = {
enabled?: boolean;
suites?: any[];
suiteList?: any[];
addonList?: any[];
expiresTime?: number;
pipelineCount?: SuiteValue;
domainCount?: SuiteValue;
@@ -1,5 +1,5 @@
<template>
<a-modal v-model:open="openRef" class="order-modal" :title="$t('certd.order.confirmTitle')" @ok="orderCreate">
<a-modal v-model:open="openRef" class="order-modal" :title="$t('certd.order.confirmTitle')" :width="670" @ok="orderCreate">
<div v-if="product" class="order-box">
<div class="flex-o mt-5">
<span class="label">{{ $t("certd.order.package") }}</span>{{ product.title }}
@@ -13,6 +13,7 @@
<span class="flex-o"> {{ $t("certd.order.pipeline") }}<suite-value class="ml-5" :model-value="product.content.maxPipelineCount" :unit="$t('certd.order.unit.pieces')" /> </span>
<span class="flex-o"> {{ $t("certd.order.domain") }}<suite-value class="ml-5" :model-value="product.content.maxDomainCount" :unit="$t('certd.order.unit.count')" /> </span>
<span class="flex-o"> {{ $t("certd.order.deployTimes") }}<suite-value class="ml-5" :model-value="product.content.maxDeployCount" :unit="$t('certd.order.unit.times')" /> </span>
<span class="flex-o"> {{ $t("certd.order.monitorCount") }}<suite-value class="ml-5" :model-value="product.content.maxMonitorCount" :unit="$t('certd.order.unit.times')" /> </span>
</span>
</div>
@@ -11,7 +11,7 @@
@finish="handleFinish"
@finish-failed="handleFinishFailed"
>
<a-tabs v-model:active-key="forgotPasswordType" :destroyInactiveTabPane="true">
<a-tabs v-model:active-key="forgotPasswordType" :destroy-inactive-tab-pane="true">
<a-tab-pane key="email" tab="邮箱找回">
<a-form-item has-feedback name="input" label="邮箱">
<a-input v-model:value="formState.input" placeholder="邮箱" size="large" autocomplete="off">
@@ -20,14 +20,11 @@
</template>
</a-input>
</a-form-item>
<a-form-item has-feedback name="captchaForEmail" label="验证码">
<CaptchaInput v-model:model-value="formState.captchaForEmail"></CaptchaInput>
</a-form-item>
<a-form-item has-feedback name="validateCode" label="邮件验证码">
<email-code
v-model:value="formState.validateCode"
:img-code="formState.imgCode"
:email="formState.input"
:random-str="formState.randomStr"
verification-type="forgotPassword"
/>
<email-code v-model:value="formState.validateCode" :captcha="formState.captchaForEmail" :email="formState.input" :random-str="formState.randomStr" verification-type="forgotPassword" />
</a-form-item>
</a-tab-pane>
<a-tab-pane key="mobile" tab="手机号找回">
@@ -38,23 +35,15 @@
</template>
</a-input>
</a-form-item>
<a-form-item has-feedback name="captchaForSms" label="验证码">
<CaptchaInput v-model:model-value="formState.captchaForSms"></CaptchaInput>
</a-form-item>
<a-form-item name="validateCode" label="手机验证码">
<sms-code
v-model:value="formState.validateCode"
:img-code="formState.imgCode"
:mobile="formState.input"
:phone-code="formState.phoneCode"
:random-str="formState.randomStr"
verification-type="forgotPassword"
/>
<sms-code v-model:value="formState.validateCode" :captcha="formState.captchaForSms" :mobile="formState.input" :phone-code="formState.phoneCode" verification-type="forgotPassword" />
</a-form-item>
</a-tab-pane>
</a-tabs>
<a-form-item has-feedback name="imgCode" label="图片验证码">
<image-code ref="imageCodeRef" v-model:value="formState.imgCode" v-model:random-str="formState.randomStr"></image-code>
</a-form-item>
<a-form-item has-feedback name="password" label="新密码">
<a-input-password v-model:value="formState.password" placeholder="新密码" size="large" autocomplete="off">
<template #prefix>
@@ -72,8 +61,10 @@
<a-form-item>
<a-button type="primary" size="large" html-type="submit" class="submit-button"> 找回密码</a-button>
<div class="mt-2">
<a href="https://certd.docmirror.cn/guide/use/forgotpasswd/" target="_blank"> 管理员无绑定通信方式或MFA丢失找回 </a>
<div class="mt-2 flex-between">
<a v-comm="false" href="https://certd.docmirror.cn/guide/use/forgotpasswd/" target="_blank"> 管理员无绑定通信方式或MFA丢失找回 </a>
<router-link :to="{ name: 'login' }"> 返回登录 </router-link>
</div>
</a-form-item>
</a-form>
@@ -82,12 +73,12 @@
<script setup lang="ts">
import { onMounted, reactive, ref, toRaw, watch } from "vue";
import ImageCode from "/@/views/framework/login/image-code.vue";
import EmailCode from "/@/views/framework/register/email-code.vue";
import SmsCode from "/@/views/framework/login/sms-code.vue";
import { utils } from "@fast-crud/fast-crud";
import { useUserStore } from "/@/store/user";
import { useSettingStore } from "/@/store/settings";
import CaptchaInput from "/@/components/captcha/captcha-input.vue";
defineOptions({
name: "ForgotPasswordPage",
});
@@ -95,7 +86,8 @@ defineOptions({
const rules = {
input: [{ required: true }],
validateCode: [{ required: true }],
imgCode: [{ required: true }, { min: 4, max: 4, message: "请输入4位图片验证码" }],
captchaForEmail: [{ required: true }],
captchaForSms: [{ required: true }],
password: [
{ required: true, trigger: "change", message: "请输入密码" },
{ min: 6, message: "至少输入6位密码" },
@@ -123,16 +115,15 @@ const layout = {
const forgotPasswordType = ref();
const userStore = useUserStore();
const settingStore = useSettingStore();
const formRef = ref();
const imageCodeRef = ref();
const formState: any = reactive({
input: "",
randomStr: "",
imgCode: "",
captchaForSms: null,
captchaForEmail: null,
phoneCode: "86",
validateCode: "",
password: "",
confirmPassword: "",
});
@@ -146,7 +137,6 @@ onMounted(() => {
watch(forgotPasswordType, () => {
formState.input = "";
formState.validateCode = "";
imageCodeRef.value.resetImageCode();
formRef.value.clearValidate(Object.keys(formState).filter(key => !["password", "confirmPassword"].includes(key)));
});
@@ -155,8 +145,6 @@ const handleFinish = async (values: any) => {
toRaw({
type: forgotPasswordType.value,
input: formState.input,
randomStr: formState.randomStr,
imgCode: formState.imgCode,
validateCode: formState.validateCode,
password: formState.password,
confirmPassword: formState.confirmPassword,
@@ -3,7 +3,16 @@
<div class="flex-o flex-wrap">
<a-popover>
<template #content>
<div>
<div style="width: 300px">
<div v-if="detail.addonList.length > 0" class="flex flex-wrap">
<a-tag v-for="(item, index) of detail.addonList" :key="index" color="green" class="pointer flex-o m-1">
<span class="mr-5">
{{ item.title }}
</span>
<span>(<expires-time-text :value="item.expiresTime" />)</span>
</a-tag>
<a-divider class="m-5" />
</div>
<div class="flex-between mt-5">
<div class="flex-o"><fs-icon icon="ant-design:check-outlined" class="color-green mr-5" /> 流水线条数</div>
<suite-value :model-value="detail.pipelineCount.max" :used="detail.pipelineCount.used" unit="条" />
@@ -30,12 +39,13 @@
</template>
<div class="flex-o">
<fs-icon icon="ant-design:gift-outlined" class="color-green mr-5" />
<a-tag v-for="(item, index) of detail.suites" :key="index" color="green" class="pointer flex-o">
<a-tag v-for="(item, index) of detail.suiteList" :key="index" color="green" class="pointer flex-o">
<span class="mr-5">
{{ item.title }}
</span>
<span>(<expires-time-text :value="item.expiresTime" />)</span>
</a-tag>
<a-tag v-if="detail.addonList.length > 0" color="green" class="pointer flex-o">加量包+{{ detail.addonList.length }}</a-tag>
<div v-if="detail.suites?.length === 0" class="flex-o ml-5">暂无套餐 <a-button class="ml-5" type="primary" size="small" @click="goBuy">去购买</a-button></div>
</div>
</a-popover>
@@ -59,6 +69,10 @@ const detail = ref<SuiteDetail>({});
async function loadSuiteDetail() {
detail.value = await mySuiteApi.SuiteDetailGet();
const suites = detail.value.suites.filter(item => item.productType === "suite");
const addons = detail.value.suites.filter(item => item.productType === "addon");
detail.value.suiteList = suites;
detail.value.addonList = addons;
}
loadSuiteDetail();
@@ -1,41 +0,0 @@
<template>
<div class="flex">
<a-input :value="value" placeholder="请输入图片验证码" autocomplete="off" @update:value="onChange">
<template #prefix>
<fs-icon icon="ion:image-outline"></fs-icon>
</template>
</a-input>
<div class="input-right pointer" title="点击刷新">
<img class="image-code" :src="imageCodeUrl" @click="resetImageCode" />
</div>
</div>
</template>
<script setup lang="ts">
import { ref, useAttrs, defineExpose } from "vue";
import { nanoid } from "nanoid";
const props = defineProps<{
randomStr?: string;
value?: string;
}>();
const emit = defineEmits(["update:value", "update:randomStr", "change"]);
function onChange(value: string) {
emit("update:value", value);
emit("change", value);
}
const imageCodeUrl = ref();
function resetImageCode() {
const randomStr = nanoid(10);
let url = "api/basic/code/captcha";
imageCodeUrl.value = url + "?randomStr=" + randomStr;
emit("update:randomStr", randomStr);
}
defineExpose({
resetImageCode,
})
resetImageCode();
</script>
@@ -20,6 +20,10 @@
</template>
</a-input-password>
</a-form-item>
<a-form-item v-if="settingStore.sysPublic.captchaEnabled" has-feedback required name="captcha" :rules="rules.captcha">
<CaptchaInput v-model:model-value="formState.captcha"></CaptchaInput>
</a-form-item>
</template>
</a-tab-pane>
<a-tab-pane v-if="sysPublicSettings.smsLoginEnabled === true" key="sms" :tab="t('authentication.smsTab')">
@@ -32,12 +36,12 @@
</a-input>
</a-form-item>
<a-form-item has-feedback name="imgCode">
<image-code v-model:value="formState.imgCode" v-model:random-str="formState.randomStr"></image-code>
<a-form-item has-feedback name="smsCaptcha">
<CaptchaInput v-model:model-value="formState.smsCaptcha"></CaptchaInput>
</a-form-item>
<a-form-item name="smsCode" :rules="rules.smsCode">
<sms-code v-model:value="formState.smsCode" :img-code="formState.imgCode" :mobile="formState.mobile" :phone-code="formState.phoneCode" :random-str="formState.randomStr" />
<sms-code v-model:value="formState.smsCode" :captcha="formState.smsCaptcha" :mobile="formState.mobile" :phone-code="formState.phoneCode" />
</a-form-item>
</template>
</a-tab-pane>
@@ -87,14 +91,13 @@ import { defineComponent, nextTick, reactive, ref, toRaw } from "vue";
import { useUserStore } from "/src/store/user";
import { useSettingStore } from "/@/store/settings";
import { utils } from "@fast-crud/fast-crud";
import ImageCode from "/@/views/framework/login/image-code.vue";
import SmsCode from "/@/views/framework/login/sms-code.vue";
import { useI18n } from "/@/locales";
import { LanguageToggle } from "/@/vben/layouts";
import CaptchaInput from "/@/components/captcha/captcha-input.vue";
export default defineComponent({
name: "LoginPage",
components: { LanguageToggle, SmsCode, ImageCode },
components: { LanguageToggle, SmsCode, CaptchaInput },
setup() {
const { t } = useI18n();
const verifyCodeInputRef = ref();
@@ -108,9 +111,9 @@ export default defineComponent({
mobile: "",
password: "",
loginType: "password", //password
imgCode: "",
smsCode: "",
randomStr: "",
captcha: null,
smsCaptcha: null,
});
const rules = {
@@ -138,6 +141,12 @@ export default defineComponent({
message: "请输入短信验证码",
},
],
captcha: [
{
required: true,
message: "请进行验证码验证",
},
],
};
const layout = {
labelCol: {
@@ -160,6 +169,10 @@ export default defineComponent({
const handleFinish = async (values: any) => {
loading.value = true;
try {
// formState.captcha = await doCaptchaValidate();
// if (!formState.captcha) {
// return;
// }
const loginType = formState.loginType;
await userStore.login(loginType, toRaw(formState));
} catch (e: any) {
@@ -194,6 +207,21 @@ export default defineComponent({
return sysPublicSettings.registerEnabled && (sysPublicSettings.usernameRegisterEnabled || sysPublicSettings.emailRegisterEnabled);
}
const captchaInputRef = ref();
const captchaInputForSmsCode = ref();
async function doCaptchaValidate() {
if (!sysPublicSettings.captchaEnabled) {
return {};
}
const res = await captchaInputRef.value.getValidatedForm();
if (!res) {
return false;
}
return {
...res,
};
}
return {
t,
loading,
@@ -211,6 +239,8 @@ export default defineComponent({
handleTwoFactorSubmit,
verifyCodeInputRef,
settingStore,
captchaInputRef,
captchaInputForSmsCode,
};
},
});
@@ -5,7 +5,7 @@
<fs-icon icon="ion:mail-outline"></fs-icon>
</template>
</a-input>
<div class="input-right">
<div class="input-right ml-5">
<a-button class="getCaptcha" type="primary" tabindex="-1" :disabled="smsSendBtnDisabled" @click="sendSmsCode">
{{ smsTime <= 0 ? "发送" : smsTime + " s" }}
</a-button>
@@ -21,8 +21,7 @@ const props = defineProps<{
value?: string;
mobile?: string;
phoneCode?: string;
imgCode?: string;
randomStr?: string;
captcha?: any;
verificationType?: string;
}>();
const emit = defineEmits(["update:value", "change"]);
@@ -48,8 +47,8 @@ async function sendSmsCode() {
notification.error({ message: "请输入手机号" });
return;
}
if (!props.imgCode) {
notification.error({ message: "请输入图片验证码" });
if (!props.captcha) {
notification.error({ message: "请输入验证码" });
return;
}
loading.value = true;
@@ -57,8 +56,7 @@ async function sendSmsCode() {
await api.sendSmsCode({
phoneCode: props.phoneCode,
mobile: props.mobile,
imgCode: props.imgCode,
randomStr: props.randomStr,
captcha: props.captcha,
verificationType: props.verificationType,
});
} finally {
@@ -5,7 +5,7 @@
<fs-icon icon="ion:mail-outline"></fs-icon>
</template>
</a-input>
<div class="input-right">
<div class="input-right ml-5">
<a-button class="getCaptcha" type="primary" tabindex="-1" :disabled="smsSendBtnDisabled" @click="sendSmsCode">
{{ smsTime <= 0 ? "发送" : smsTime + " s" }}
</a-button>
@@ -20,8 +20,7 @@ import * as api from "/@/store/settings/api.basic";
const props = defineProps<{
value?: string;
email?: string;
imgCode?: string;
randomStr?: string;
captcha?: any;
verificationType?: string;
}>();
const emit = defineEmits(["update:value", "change"]);
@@ -44,16 +43,15 @@ async function sendSmsCode() {
notification.error({ message: "请输入邮箱" });
return;
}
if (!props.imgCode) {
notification.error({ message: "请输入图片验证码" });
if (!props.captcha) {
notification.error({ message: "请输入验证码" });
return;
}
loading.value = true;
try {
await api.sendEmailCode({
email: props.email,
imgCode: props.imgCode,
randomStr: props.randomStr,
captcha: props.captcha,
verificationType: props.verificationType,
});
} finally {
@@ -25,8 +25,8 @@
</template>
</a-input-password>
</a-form-item>
<a-form-item has-feedback name="imgCode" label="图片验证码" :rules="rules.imgCode">
<image-code v-model:value="formState.imgCode" v-model:random-str="formState.randomStr"></image-code>
<a-form-item has-feedback name="captcha" label="验证码" :rules="rules.captcha">
<CaptchaInput v-model:model-value="formState.captcha"></CaptchaInput>
</a-form-item>
</template>
</a-tab-pane>
@@ -61,12 +61,12 @@
</a-input-password>
</a-form-item>
<a-form-item has-feedback name="imgCode" label="图片验证码" :rules="rules.imgCode">
<image-code v-model:value="formState.imgCode" v-model:random-str="formState.randomStr"></image-code>
<a-form-item has-feedback name="imgCode" label="验证码" :rules="rules.imgCode">
<CaptchaInput v-model:model-value="formState.captchaForEmail"></CaptchaInput>
</a-form-item>
<a-form-item has-feedback name="validateCode" :rules="rules.validateCode" label="邮件验证码">
<email-code v-model:value="formState.validateCode" :img-code="formState.imgCode" :email="formState.email" :random-str="formState.randomStr" />
<email-code v-model:value="formState.validateCode" :captcha="formState.captchaForEmail" :email="formState.email" />
</a-form-item>
</template>
</a-tab-pane>
@@ -86,13 +86,13 @@
import { defineComponent, reactive, ref, toRaw } from "vue";
import { useUserStore } from "/src/store/user";
import { utils } from "@fast-crud/fast-crud";
import ImageCode from "/@/views/framework/login/image-code.vue";
import EmailCode from "./email-code.vue";
import { useSettingStore } from "/@/store/settings";
import { notification } from "ant-design-vue";
import CaptchaInput from "/@/components/captcha/captcha-input.vue";
export default defineComponent({
name: "RegisterPage",
components: { EmailCode, ImageCode },
components: { CaptchaInput, EmailCode },
setup() {
const settingsStore = useSettingStore();
const registerType = ref("email");
@@ -114,7 +114,7 @@ export default defineComponent({
username: "",
password: "",
confirmPassword: "",
randomStr: "",
captcha: null,
});
const rules = {
@@ -159,17 +159,6 @@ export default defineComponent({
},
],
imgCode: [
{
required: true,
message: "请输入图片验证码",
},
{
min: 4,
max: 4,
message: "请输入4位图片验证码",
},
],
smsCode: [
{
required: true,
@@ -198,9 +187,8 @@ export default defineComponent({
type: registerType.value,
password: formState.password,
username: formState.username,
imgCode: formState.imgCode,
randomStr: formState.randomStr,
email: formState.email,
captcha: formState.captcha,
validateCode: formState.validateCode,
}) as any
);
@@ -214,16 +202,7 @@ export default defineComponent({
formRef.value.resetFields();
};
const imageCodeUrl = ref();
function resetImageCode() {
let url = "/basic/code";
imageCodeUrl.value = url + "?t=" + new Date().getTime();
}
resetImageCode();
return {
resetImageCode,
imageCodeUrl,
formState,
formRef,
rules,
@@ -25,7 +25,7 @@
<a-tab-pane key="editor" tab="元数据"> </a-tab-pane>
</a-tabs>
<div class="metadata-body">
<code-editor id="metadata" v-model:model-value="plugin.metadata" language="yaml" @save="doSave"></code-editor>
<code-editor :id="`metadata_${idRef}`" v-model:model-value="plugin.metadata" language="yaml" @save="doSave"></code-editor>
</div>
</div>
<div class="script">
@@ -33,7 +33,7 @@
<a-tab-pane key="script" tab="脚本"> </a-tab-pane>
</a-tabs>
<div class="script-body">
<code-editor id="content" v-model:model-value="plugin.content" language="javascript" @save="doSave"></code-editor>
<code-editor :id="`content_${idRef}`" v-model:model-value="plugin.content" language="javascript" @save="doSave"></code-editor>
</div>
</div>
</div>
@@ -83,6 +83,7 @@ function initFormOptions() {
}
initFormOptions();
const idRef = ref(route.query.id);
async function getPlugin() {
const id = route.query.id;
const pluginObj = await api.GetObj(id);
@@ -1,12 +1,14 @@
import * as api from "/@/views/sys/plugin/api";
import { useFormWrapper } from "@fast-crud/fast-crud";
import { dict, useFormWrapper } from "@fast-crud/fast-crud";
import { useI18n } from "/@/locales";
import { Modal, notification } from "ant-design-vue";
import { notification } from "ant-design-vue";
export function usePluginImport() {
const { openCrudFormDialog } = useFormWrapper();
const { t } = useI18n();
async function openImportDialog({ crudExpose }) {
async function openImportDialog(opts: any) {
const { crudExpose } = opts;
function createCrudOptions() {
return {
crudOptions: {
@@ -5,17 +5,17 @@
<!-- </template>-->
<div class="sys-settings-body md:p-5">
<a-tabs :active-key="activeKey" type="card" class="sys-settings-tabs" @update:active-key="onChange">
<a-tab-pane key="base" tab="基本设置">
<a-tab-pane key="base" :tab="t('certd.sys.setting.baseSetting')">
<SettingBase v-if="activeKey === 'base'" />
</a-tab-pane>
<a-tab-pane key="register" tab="注册设置">
<a-tab-pane key="register" :tab="t('certd.sys.setting.registerSetting')">
<SettingRegister v-if="activeKey === 'register'" />
</a-tab-pane>
<a-tab-pane v-if="settingsStore.isComm" key="payment" tab="支付设置">
<a-tab-pane v-if="settingsStore.isComm" key="payment" :tab="t('certd.sys.setting.paymentSetting')">
<SettingPayment v-if="activeKey === 'payment'" />
</a-tab-pane>
<a-tab-pane key="save" tab="安全设置">
<SettingSafe v-if="activeKey === 'save'" />
<a-tab-pane key="safe" :tab="t('certd.sys.setting.safeSetting')">
<SettingSafe v-if="activeKey === 'safe'" />
</a-tab-pane>
</a-tabs>
</div>
@@ -30,9 +30,11 @@ import SettingSafe from "/@/views/sys/settings/tabs/safe.vue";
import { useRoute, useRouter } from "vue-router";
import { ref } from "vue";
import { useSettingStore } from "/@/store/settings";
import { useI18n } from "/@/locales";
defineOptions({
name: "SysSettings",
});
const { t } = useI18n();
const settingsStore = useSettingStore();
const activeKey = ref("base");
const route = useRoute();
@@ -47,6 +47,18 @@
<div class="helper" v-html="t('certd.commonCnameHelper')"></div>
</a-form-item>
<a-form-item :label="t('certd.sys.setting.captchaEnabled')" :name="['public', 'captchaEnabled']">
<a-switch v-model:checked="formState.public.captchaEnabled" />
<div class="helper" v-html="t('certd.sys.setting.captchaHelper')"></div>
</a-form-item>
<a-form-item :label="t('certd.sys.setting.captchaType')" :name="['public', 'captchaAddonId']">
<addon-selector v-model:model-value="formState.public.captchaAddonId" addon-type="captcha" from="sys" @selected-change="onAddonChanged" />
</a-form-item>
<a-form-item :name="['public', 'captchaType']" class="hidden">
<a-input v-model:model-value="formState.public.captchaType"></a-input>
</a-form-item>
<a-form-item label=" " :colon="false" :wrapper-col="{ span: 8 }">
<a-button :loading="saveLoading" type="primary" html-type="submit">{{ t("certd.saveButton") }}</a-button>
</a-form-item>
@@ -63,7 +75,7 @@ import { useSettingStore } from "/@/store/settings";
import { notification } from "ant-design-vue";
import { util } from "/@/utils";
import { useI18n } from "/src/locales";
import AddonSelector from "../../../certd/addon/addon-selector/index.vue";
const { t } = useI18n();
defineOptions({
@@ -115,6 +127,10 @@ async function stopOtherUserTimer() {
});
}
function onAddonChanged(target: any) {
formState.public.captchaType = target.type;
}
const testProxyLoading = ref(false);
async function testProxy() {
testProxyLoading.value = true;
+1
View File
@@ -68,6 +68,7 @@ export default ({ command, mode }) => {
rollupOptions: {
plugins: [visualizer()],
},
minify: "esbuild",
},
css: {
preprocessorOptions: {
@@ -0,0 +1,15 @@
flyway:
scriptDir: './db/migration-mysql'
typeorm:
dataSource:
default:
type: mysql # mariadb
host: localhost
port: 3309
logging: true
username: root
password: root
database: certd_comm
+32
View File
@@ -3,6 +3,38 @@
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## [1.36.21](https://github.com/certd/certd/compare/v1.36.20...v1.36.21) (2025-09-15)
**Note:** Version bump only for package @certd/ui-server
## [1.36.20](https://github.com/certd/certd/compare/v1.36.19...v1.36.20) (2025-09-13)
### Bug Fixes
* 修复证书监控某些情况下报 options.lookup不能为null的bug ([d2ecfe5](https://github.com/certd/certd/commit/d2ecfe5491b2639eb30b5cae293af6062d58bb9f))
* 修复证书手动托管时新上传的证书无效的bug ([506385e](https://github.com/certd/certd/commit/506385e5a2600887fe30854e0713583caaa2e689))
### Performance Improvements
* 登录支持极验验证码 ([370db62](https://github.com/certd/certd/commit/370db62bf0aece241859244927beabba32d6a257))
* 登录注册、找回密码都支持极验验证码和图片验证码 ([7bdde68](https://github.com/certd/certd/commit/7bdde68ecea29fe2c570fd3cb082139db6c93d93))
* 证书到期剩余天数进度条根据实际证书有效期计算 ([#528](https://github.com/certd/certd/issues/528)) nicheng-he ([2d4586b](https://github.com/certd/certd/commit/2d4586b1c42c39f97d2a95b9453cca4bc8bfbe61))
* add preferred chain option ([#519](https://github.com/certd/certd/issues/519)) @ZeroClover ([902359f](https://github.com/certd/certd/commit/902359f24ed12eee4f9b65178f1d6a60378351d2))
## [1.36.19](https://github.com/certd/certd/compare/v1.36.18...v1.36.19) (2025-09-05)
### Bug Fixes
* 前置任务输出不存在时输出警告提示 ([b59052c](https://github.com/certd/certd/commit/b59052cc43b7b070fabd8b8e914e4c2a5e0ad61c))
* 修复mysql下购买套餐加量包无效的bug ([c26ad4c](https://github.com/certd/certd/commit/c26ad4c8075f0606d45b8da13915737968d6191a))
### Performance Improvements
* 增加健康检查探针 /health/liveliness 和 /health/readiness ([44019e1](https://github.com/certd/certd/commit/44019e104289fedd32a867db00e9c6cb71b389cc))
* 支持根据id更新证书(证书Id不变接口),不过该接口为白名单功能,普通腾讯云账户无法使用 ([fe9c4f3](https://github.com/certd/certd/commit/fe9c4f3391ff07c01dd9a252225f69a129c39050))
* 支持godaddy ([b7980aa](https://github.com/certd/certd/commit/b7980aad5ab50f58662eaddf5d84aa82876a98eb))
* 支持ssl.com证书颁发机构 ([27b6dfa](https://github.com/certd/certd/commit/27b6dfa4d2ab3bddd284c3a34511a72e1a513a4c))
## [1.36.18](https://github.com/certd/certd/compare/v1.36.17...v1.36.18) (2025-08-28)
### Bug Fixes
@@ -0,0 +1,3 @@
update cd_user_suite set is_empty = false where is_empty is null;
ALTER TABLE cd_user_suite MODIFY COLUMN `is_empty` boolean default false ;
@@ -0,0 +1,2 @@
ALTER TABLE cd_cert_info ADD COLUMN effective_time bigint;
ALTER TABLE cd_site_info ADD COLUMN cert_effective_time bigint;
@@ -0,0 +1,13 @@
CREATE TABLE `cd_addon` (
`id` bigint PRIMARY KEY AUTO_INCREMENT NOT NULL,
`user_id` bigint NOT NULL,
`name` varchar(100) NOT NULL,
`type` varchar(100) NOT NULL,
`addon_type` varchar(100) NOT NULL,
`is_default` boolean NOT NULL DEFAULT false,
`is_system` boolean NOT NULL DEFAULT false,
`setting` longtext,
`create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
);
@@ -0,0 +1,2 @@
update cd_user_suite set is_empty = false where is_empty is null;
ALTER TABLE "cd_user_suite" ALTER COLUMN "is_empty" SET DEFAULT false;
@@ -0,0 +1,2 @@
ALTER TABLE cd_cert_info ADD COLUMN effective_time bigint;
ALTER TABLE cd_site_info ADD COLUMN cert_effective_time bigint;
@@ -0,0 +1,13 @@
CREATE TABLE "cd_addon" (
"id" bigint PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY NOT NULL,
"user_id" bigint NOT NULL,
"name" varchar(100) NOT NULL,
"type" varchar(100) NOT NULL,
"addon_type" varchar(100) NOT NULL,
"is_default" boolean NOT NULL DEFAULT (false),
"is_system" boolean NOT NULL DEFAULT (false),
"setting" text,
"create_time" timestamp NOT NULL DEFAULT (CURRENT_TIMESTAMP),
"update_time" timestamp NOT NULL DEFAULT (CURRENT_TIMESTAMP)
);
@@ -0,0 +1,2 @@
ALTER TABLE cd_cert_info ADD COLUMN effective_time INTEGER;
ALTER TABLE cd_site_info ADD COLUMN cert_effective_time INTEGER;
@@ -0,0 +1,13 @@
CREATE TABLE "cd_addon" (
"id" integer PRIMARY KEY AUTOINCREMENT NOT NULL,
"user_id" integer NOT NULL,
"name" varchar(100) NOT NULL,
"type" varchar(100) NOT NULL,
"addon_type" varchar(100) NOT NULL,
"is_default" boolean NOT NULL DEFAULT (false),
"is_system" boolean NOT NULL DEFAULT (false),
"setting" text,
"create_time" datetime NOT NULL DEFAULT (CURRENT_TIMESTAMP),
"update_time" datetime NOT NULL DEFAULT (CURRENT_TIMESTAMP)
);
+2
View File
@@ -39,6 +39,7 @@ function transformPG() {
pgSql = pgSql.replaceAll(/boolean DEFAULT \(0\)/g, 'boolean DEFAULT (false)');
pgSql = pgSql.replaceAll(/boolean.*NOT NULL DEFAULT \(0\)/g, 'boolean NOT NULL DEFAULT (false)');
pgSql = pgSql.replaceAll(/integer/g, 'bigint');
pgSql = pgSql.replaceAll(/INTEGER/g, 'bigint');
pgSql = pgSql.replaceAll(/last_insert_rowid\(\)/g, 'LASTVAL()');
fs.writeFileSync(`./migration-pg/${notFile}`, pgSql);
}
@@ -66,6 +67,7 @@ function transformMysql() {
//DEFAULT (xxx) 替换成 DEFAULT xxx
pgSql = pgSql.replaceAll(/DEFAULT \(([^)]*)\)/g, 'DEFAULT $1');
pgSql = pgSql.replaceAll(/integer/g, 'bigint');
pgSql = pgSql.replaceAll(/INTEGER/g, 'bigint');
pgSql = pgSql.replaceAll(/last_insert_rowid\(\)/g, 'LAST_INSERT_ID()');
//text 改成longtext
pgSql = pgSql.replaceAll(/text/g, 'longtext');
+16 -15
View File
@@ -1,6 +1,6 @@
{
"name": "@certd/ui-server",
"version": "1.36.18",
"version": "1.36.21",
"description": "fast-server base midway",
"private": true,
"type": "module",
@@ -11,6 +11,7 @@
"dev-commpro": "cross-env NODE_ENV=dev-commpro mwtsc --watch --run @midwayjs/mock/app",
"dev-pg": "cross-env NODE_ENV=dev-pg mwtsc --watch --run @midwayjs/mock/app",
"dev-mysql": "cross-env NODE_ENV=dev-mysql mwtsc --watch --run @midwayjs/mock/app",
"dev-mysql-comm": "cross-env NODE_ENV=dev-mysql-comm mwtsc --watch --run @midwayjs/mock/app",
"dev-localplus": "cross-env NODE_ENV=dev-localplus mwtsc --watch --run @midwayjs/mock/app",
"dev-pgpl": "cross-env NODE_ENV=dev-pgpl mwtsc --watch --run @midwayjs/mock/app",
"dev-new": "cross-env NODE_ENV=dev-new mwtsc --watch --run @midwayjs/mock/app",
@@ -42,20 +43,20 @@
"@aws-sdk/client-cloudfront": "^3.699.0",
"@aws-sdk/client-iam": "^3.699.0",
"@aws-sdk/client-s3": "^3.705.0",
"@certd/acme-client": "^1.36.18",
"@certd/basic": "^1.36.18",
"@certd/commercial-core": "^1.36.18",
"@certd/acme-client": "^1.36.21",
"@certd/basic": "^1.36.21",
"@certd/commercial-core": "^1.36.21",
"@certd/cv4pve-api-javascript": "^8.4.2",
"@certd/jdcloud": "^1.36.18",
"@certd/lib-huawei": "^1.36.18",
"@certd/lib-k8s": "^1.36.18",
"@certd/lib-server": "^1.36.18",
"@certd/midway-flyway-js": "^1.36.18",
"@certd/pipeline": "^1.36.18",
"@certd/plugin-cert": "^1.36.18",
"@certd/plugin-lib": "^1.36.18",
"@certd/plugin-plus": "^1.36.18",
"@certd/plus-core": "^1.36.18",
"@certd/jdcloud": "^1.36.21",
"@certd/lib-huawei": "^1.36.21",
"@certd/lib-k8s": "^1.36.21",
"@certd/lib-server": "^1.36.21",
"@certd/midway-flyway-js": "^1.36.21",
"@certd/pipeline": "^1.36.21",
"@certd/plugin-cert": "^1.36.21",
"@certd/plugin-lib": "^1.36.21",
"@certd/plugin-plus": "^1.36.21",
"@certd/plus-core": "^1.36.21",
"@huaweicloud/huaweicloud-sdk-cdn": "^3.1.120",
"@huaweicloud/huaweicloud-sdk-core": "^3.1.120",
"@koa/cors": "^5.0.0",
@@ -117,7 +118,7 @@
"socks-proxy-agent": "^8.0.4",
"strip-ansi": "^7.1.0",
"svg-captcha": "^1.4.0",
"tencentcloud-sdk-nodejs": "^4.0.983",
"tencentcloud-sdk-nodejs": "^4.1.112",
"typeorm": "^0.3.20",
"uuid": "^10.0.0"
},
@@ -27,6 +27,7 @@ const development = {
},
keys: 'certd',
koa: {
hostname:"::",
port: 7001,
},
https: {
@@ -1,8 +1,9 @@
import { Rule, RuleType } from '@midwayjs/validate';
import { ALL, Body, Controller, Get, Inject, Post, Provide, Query } from '@midwayjs/core';
import { BaseController, Constants } from '@certd/lib-server';
import { CodeService } from '../../modules/basic/service/code-service.js';
import { EmailService } from '../../modules/basic/service/email-service.js';
import { Rule, RuleType } from "@midwayjs/validate";
import { ALL, Body, Controller, Inject, Post, Provide, Query } from "@midwayjs/core";
import { BaseController, Constants, SysSettingsService } from "@certd/lib-server";
import { CodeService } from "../../modules/basic/service/code-service.js";
import { EmailService } from "../../modules/basic/service/email-service.js";
import { CaptchaService } from "../../modules/basic/service/captcha-service.js";
export class SmsCodeReq {
@Rule(RuleType.string().required())
@@ -11,11 +12,8 @@ export class SmsCodeReq {
@Rule(RuleType.string().required())
mobile: string;
@Rule(RuleType.string().required().max(10))
randomStr: string;
@Rule(RuleType.string().required().max(4))
imgCode: string;
@Rule(RuleType.required())
captcha: any;
@Rule(RuleType.string())
verificationType: string;
@@ -25,11 +23,8 @@ export class EmailCodeReq {
@Rule(RuleType.string().required())
email: string;
@Rule(RuleType.string().required().max(10))
randomStr: string;
@Rule(RuleType.string().required().max(4))
imgCode: string;
@Rule(RuleType.required())
captcha: any;
@Rule(RuleType.string())
verificationType: string;
@@ -48,6 +43,17 @@ export class BasicController extends BaseController {
@Inject()
emailService: EmailService;
@Inject()
sysSettingsService: SysSettingsService;
@Inject()
captchaService: CaptchaService;
@Post('/captcha/get', { summary: Constants.per.guest })
async getCaptcha(@Query("captchaAddonId") captchaAddonId:number) {
const form = await this.captchaService.getCaptcha(captchaAddonId)
return this.ok(form);
}
@Post('/sendSmsCode', { summary: Constants.per.guest })
public async sendSmsCode(
@@ -64,8 +70,8 @@ export class BasicController extends BaseController {
// opts.verificationCodeLength = 6; //部分厂商这里会设置参数长度这里就不改了
}
await this.codeService.checkCaptcha(body.randomStr, body.imgCode);
await this.codeService.sendSmsCode(body.phoneCode, body.mobile, body.randomStr, opts);
await this.codeService.checkCaptcha(body.captcha);
await this.codeService.sendSmsCode(body.phoneCode, body.mobile, opts);
return this.ok(null);
}
@@ -88,16 +94,10 @@ export class BasicController extends BaseController {
opts.verificationCodeLength = 6;
}
await this.codeService.checkCaptcha(body.randomStr, body.imgCode);
await this.codeService.sendEmailCode(body.email, body.randomStr, opts);
await this.codeService.checkCaptcha(body.captcha);
await this.codeService.sendEmailCode(body.email, opts);
// 设置缓存内容
return this.ok(null);
}
@Get('/captcha', { summary: Constants.per.guest })
public async getCaptcha(@Query('randomStr') randomStr: any) {
const captcha = await this.codeService.generateCaptcha(randomStr);
this.ctx.res.setHeader('Content-Type', 'image/svg+xml');
return captcha.data;
}
}
@@ -23,7 +23,7 @@ const unhiddenHtml = `
@Provide()
@Controller('/api/unhidden')
export class HnhiddenController {
export class UnhiddenController {
@Inject()
ctx: IMidwayKoaContext;
@Inject()
@@ -0,0 +1,83 @@
import { ALL, Body, Controller, Inject, Post, Provide, Query } from "@midwayjs/core";
import { AddonRequestHandleReq, AddonService, Constants } from "@certd/lib-server";
import { AddonController } from "../../user/addon/addon-controller.js";
@Provide()
@Controller('/api/sys/addon')
export class SysAddonController extends AddonController {
@Inject()
service2: AddonService;
getService(): AddonService {
return this.service2;
}
getUserId() {
// checkComm();
return 0;
}
@Post('/page', { summary: 'sys:settings:view' })
async page(@Body(ALL) body: any) {
return await super.page(body);
}
@Post('/list', { summary: 'sys:settings:view' })
async list(@Body(ALL) body: any) {
return await super.list(body);
}
@Post('/add', { summary: 'sys:settings:edit' })
async add(@Body(ALL) bean: any) {
return await super.add(bean);
}
@Post('/update', { summary: 'sys:settings:edit' })
async update(@Body(ALL) bean: any) {
return await super.update(bean);
}
@Post('/info', { summary: 'sys:settings:view' })
async info(@Query('id') id: number) {
return await super.info(id);
}
@Post('/delete', { summary: 'sys:settings:edit' })
async delete(@Query('id') id: number) {
return await super.delete(id);
}
@Post('/define', { summary: Constants.per.authOnly })
async define(@Query('type') type: string,@Query('addonType') addonType: string) {
return await super.define(type,addonType);
}
@Post('/getTypeDict', { summary: Constants.per.authOnly })
async getTypeDict(@Query('addonType') addonType: string) {
return await super.getTypeDict(addonType);
}
@Post('/simpleInfo', { summary: Constants.per.authOnly })
async simpleInfo(@Query('addonType') addonType: string,@Query('id') id: number) {
return await super.simpleInfo(addonType,id);
}
@Post('/getDefaultId', { summary: Constants.per.authOnly })
async getDefaultId(@Query('addonType') addonType: string) {
return await super.getDefaultId(addonType);
}
@Post('/setDefault', { summary: Constants.per.authOnly })
async setDefault(@Query('addonType') addonType: string,@Query('id') id: number) {
return await super.setDefault(addonType,id);
}
@Post('/options', { summary: Constants.per.authOnly })
async options(@Query('addonType') addonType: string) {
return await super.options(addonType);
}
@Post('/handle', { summary: Constants.per.authOnly })
async handle(@Body(ALL) body: AddonRequestHandleReq) {
return await super.handle(body);
}
}
@@ -1,4 +1,4 @@
import {ALL, Body, Controller, Inject, Post, Provide, Query} from '@midwayjs/core';
import { ALL, Body, Controller, Inject, Post, Provide, Query } from "@midwayjs/core";
import {
CrudController,
SysPrivateSettings,
@@ -6,14 +6,14 @@ import {
SysSafeSetting,
SysSettingsEntity,
SysSettingsService
} from '@certd/lib-server';
import {cloneDeep, merge} from 'lodash-es';
import {PipelineService} from '../../../modules/pipeline/service/pipeline-service.js';
import {UserSettingsService} from '../../../modules/mine/service/user-settings-service.js';
import {getEmailSettings} from '../../../modules/sys/settings/fix.js';
import {http, logger, simpleNanoId, utils} from '@certd/basic';
import {CodeService} from '../../../modules/basic/service/code-service.js';
import {SmsServiceFactory} from '../../../modules/basic/sms/factory.js';
} from "@certd/lib-server";
import { cloneDeep, merge } from "lodash-es";
import { PipelineService } from "../../../modules/pipeline/service/pipeline-service.js";
import { UserSettingsService } from "../../../modules/mine/service/user-settings-service.js";
import { getEmailSettings } from "../../../modules/sys/settings/fix.js";
import { http, logger, utils } from "@certd/basic";
import { CodeService } from "../../../modules/basic/service/code-service.js";
import { SmsServiceFactory } from "../../../modules/basic/sms/factory.js";
/**
@@ -158,7 +158,7 @@ export class SysSettingsController extends CrudController<SysSettingsService> {
@Post('/testSms', { summary: 'sys:settings:edit' })
async testSms(@Body(ALL) body) {
await this.codeService.sendSmsCode(body.phoneCode, body.mobile, simpleNanoId());
await this.codeService.sendSmsCode(body.phoneCode, body.mobile );
return this.ok({});
}
@@ -0,0 +1,199 @@
import { ALL, Body, Controller, Inject, Post, Provide, Query } from "@midwayjs/core";
import {
AddonDefine,
AddonRequestHandleReq,
AddonService,
Constants,
CrudController,
newAddon,
ValidateException
} from "@certd/lib-server";
import { AuthService } from "../../../modules/sys/authority/service/auth-service.js";
import { checkPlus } from "@certd/plus-core";
import { http, logger, utils } from "@certd/basic";
/**
* Addon
*/
@Provide()
@Controller('/api/addon')
export class AddonController extends CrudController<AddonService> {
@Inject()
service: AddonService;
@Inject()
authService: AuthService;
getService(): AddonService {
return this.service;
}
@Post('/page', { summary: Constants.per.authOnly })
async page(@Body(ALL) body) {
body.query = body.query ?? {};
delete body.query.userId;
const buildQuery = qb => {
qb.andWhere('user_id = :userId', { userId: this.getUserId() });
};
const res = await this.service.page({
query: body.query,
page: body.page,
sort: body.sort,
buildQuery,
});
return this.ok(res);
}
@Post('/list', { summary: Constants.per.authOnly })
async list(@Body(ALL) body) {
body.query = body.query ?? {};
body.query.userId = this.getUserId();
return super.list(body);
}
@Post('/add', { summary: Constants.per.authOnly })
async add(@Body(ALL) bean) {
bean.userId = this.getUserId();
const type = bean.type;
const addonType = bean.addonType;
if (! type || !addonType){
throw new ValidateException('请选择Addon类型');
}
const define: AddonDefine = this.service.getDefineByType(type,addonType);
if (!define) {
throw new ValidateException('Addon类型不存在');
}
if (define.needPlus) {
checkPlus();
}
return super.add(bean);
}
@Post('/update', { summary: Constants.per.authOnly })
async update(@Body(ALL) bean) {
await this.service.checkUserId(bean.id, this.getUserId());
const old = await this.service.info(bean.id);
if (!old) {
throw new ValidateException('Addon配置不存在');
}
if (old.type !== bean.type ) {
const addonType = old.type;
const type = bean.type;
const define: AddonDefine = this.service.getDefineByType(type,addonType);
if (!define) {
throw new ValidateException('Addon类型不存在');
}
if (define.needPlus) {
checkPlus();
}
}
delete bean.userId;
return super.update(bean);
}
@Post('/info', { summary: Constants.per.authOnly })
async info(@Query('id') id: number) {
await this.service.checkUserId(id, this.getUserId());
return super.info(id);
}
@Post('/delete', { summary: Constants.per.authOnly })
async delete(@Query('id') id: number) {
await this.service.checkUserId(id, this.getUserId());
return super.delete(id);
}
@Post('/define', { summary: Constants.per.authOnly })
async define(@Query('type') type: string,@Query('addonType') addonType: string) {
const notification = this.service.getDefineByType(type,addonType);
return this.ok(notification);
}
@Post('/getTypeDict', { summary: Constants.per.authOnly })
async getTypeDict(@Query('addonType') addonType: string) {
const list: any = this.service.getDefineList(addonType);
let dict = [];
for (const item of list) {
dict.push({
value: item.name,
label: item.title,
needPlus: item.needPlus ?? false,
icon: item.icon,
});
}
dict = dict.sort(a => {
return a.needPlus ? 0 : -1;
});
return this.ok(dict);
}
@Post('/simpleInfo', { summary: Constants.per.authOnly })
async simpleInfo(@Query('addonType') addonType: string,@Query('id') id: number) {
if (id === 0) {
//获取默认
const res = await this.service.getDefault(this.getUserId(),addonType);
if (!res) {
throw new ValidateException('默认Addon配置不存在');
}
const simple = await this.service.getSimpleInfo(res.id);
return this.ok(simple);
}
await this.authService.checkEntityUserId(this.ctx, this.service, id);
const res = await this.service.getSimpleInfo(id);
return this.ok(res);
}
@Post('/getDefaultId', { summary: Constants.per.authOnly })
async getDefaultId(@Query('addonType') addonType: string) {
const res = await this.service.getDefault(this.getUserId(),addonType);
return this.ok(res?.id);
}
@Post('/setDefault', { summary: Constants.per.authOnly })
async setDefault(@Query('addonType') addonType: string,@Query('id') id: number) {
await this.service.checkUserId(id, this.getUserId());
const res = await this.service.setDefault(id, this.getUserId(),addonType);
return this.ok(res);
}
@Post('/options', { summary: Constants.per.authOnly })
async options(@Query('addonType') addonType: string) {
const res = await this.service.list({
query: {
userId: this.getUserId(),
addonType
},
});
for (const item of res) {
delete item.setting;
}
return this.ok(res);
}
@Post('/handle', { summary: Constants.per.authOnly })
async handle(@Body(ALL) body: AddonRequestHandleReq) {
const userId = this.getUserId();
let inputAddon = body.input.addon;
if (body.input.id > 0) {
const oldEntity = await this.service.info(body.input.id);
if (oldEntity) {
if (oldEntity.userId !== userId) {
throw new Error('addon not found');
}
// const param: any = {
// type: body.typeName,
// setting: JSON.stringify(body.input.access),
// };
inputAddon = JSON.parse( oldEntity.setting)
}
}
const ctx = {
http: http,
logger:logger,
utils:utils,
}
const addon = await newAddon(body.addonType,body.typeName, inputAddon,ctx);
const res = await addon.onRequest(body);
return this.ok(res);
}
}
@@ -29,25 +29,23 @@ export class LoginController extends BaseController {
throw new CommonException('暂未开启自助找回');
}
// 找回密码的验证码允许错误次数
const errorNum = 5;
const maxErrorCount = 5;
if(body.type === 'email') {
this.codeService.checkEmailCode({
verificationType: 'forgotPassword',
email: body.input,
randomStr: body.randomStr,
validateCode: body.validateCode,
errorNum,
maxErrorCount: maxErrorCount,
throwError: true,
});
} else if(body.type === 'mobile') {
await this.codeService.checkSmsCode({
verificationType: 'forgotPassword',
mobile: body.input,
randomStr: body.randomStr,
phoneCode: body.phoneCode,
smsCode: body.validateCode,
errorNum,
maxErrorCount: maxErrorCount,
throwError: true,
});
} else {
@@ -1,8 +1,9 @@
import { ALL, Body, Controller, Inject, Post, Provide } from '@midwayjs/core';
import { LoginService } from '../../../modules/login/service/login-service.js';
import { BaseController, Constants, SysPublicSettings, SysSettingsService } from '@certd/lib-server';
import { CodeService } from '../../../modules/basic/service/code-service.js';
import { checkComm } from '@certd/plus-core';
import { ALL, Body, Controller, Inject, Post, Provide } from "@midwayjs/core";
import { LoginService } from "../../../modules/login/service/login-service.js";
import { AddonService, BaseController, Constants, SysPublicSettings, SysSettingsService } from "@certd/lib-server";
import { CodeService } from "../../../modules/basic/service/code-service.js";
import { checkComm } from "@certd/plus-core";
import { CaptchaService } from "../../../modules/basic/service/captcha-service.js";
/**
*/
@@ -16,13 +17,22 @@ export class LoginController extends BaseController {
@Inject()
sysSettingsService: SysSettingsService;
@Inject()
addonService: AddonService;
@Inject()
captchaService: CaptchaService;
@Post('/login', { summary: Constants.per.guest })
public async login(
@Body(ALL)
user: any
body: any
) {
const token = await this.loginService.loginByPassword(user);
const settings = await this.sysSettingsService.getPublicSettings()
if (settings.captchaEnabled === true) {
await this.captchaService.doValidate({form:body.captcha,must:false,captchaAddonId:settings.captchaAddonId})
}
const token = await this.loginService.loginByPassword(body);
this.writeTokenCookie(token);
return this.ok(token);
}
@@ -13,8 +13,7 @@ export type RegisterReq = {
phoneCode?: string;
validateCode: string;
imgCode: string;
randomStr: string;
captcha:any;
};
/**
@@ -52,7 +51,7 @@ export class RegisterController extends BaseController {
throw new Error('用户名不能为空');
}
await this.codeService.checkCaptcha(body.randomStr, body.imgCode);
await this.codeService.checkCaptcha(body.captcha);
const newUser = await this.userService.register(body.type, {
username: body.username,
password: body.password,
@@ -68,7 +67,6 @@ export class RegisterController extends BaseController {
mobile: body.mobile,
phoneCode: body.phoneCode,
smsCode: body.validateCode,
randomStr: body.randomStr,
throwError: true,
});
const newUser = await this.userService.register(body.type, {
@@ -85,7 +83,6 @@ export class RegisterController extends BaseController {
checkPlus();
this.codeService.checkEmailCode({
email: body.email,
randomStr: body.randomStr,
validateCode: body.validateCode,
throwError: true,
});
@@ -0,0 +1,54 @@
import { Inject, Provide, Scope, ScopeEnum } from "@midwayjs/core";
import { AddonService, SysSettingsService } from "@certd/lib-server";
import { logger } from "@certd/basic";
import { ICaptchaAddon } from "../../../plugins/plugin-captcha/api.js";
@Provide()
@Scope(ScopeEnum.Request, { allowDowngrade: true })
export class CaptchaService {
@Inject()
sysSettingsService: SysSettingsService;
@Inject()
addonService: AddonService;
async getCaptcha(captchaAddonId?:number){
if (!captchaAddonId) {
const settings = await this.sysSettingsService.getPublicSettings()
captchaAddonId = settings.captchaAddonId ?? 0
}
const addon:ICaptchaAddon = await this.addonService.getAddonById(captchaAddonId,true,0)
if (!addon) {
throw new Error('验证码插件还未配置')
}
return await addon.getCaptcha()
}
async doValidate(opts:{form:any,must?:boolean,captchaAddonId?:number}){
if (!opts.captchaAddonId) {
const settings = await this.sysSettingsService.getPublicSettings()
opts.captchaAddonId = settings.captchaAddonId ?? 0
}
const addon = await this.addonService.getById(opts.captchaAddonId,0)
if (!addon) {
if (opts.must) {
throw new Error('请先配置验证码插件');
}
logger.warn('验证码插件还未配置,忽略验证码校验')
return true
}
if (!opts.form) {
throw new Error('请输入验证码');
}
const res = await addon.onValidate(opts.form)
if (!res) {
throw new Error('验证码错误');
}
return true
}
}
@@ -8,6 +8,7 @@ import { EmailService } from './email-service.js';
import { AccessService } from '@certd/lib-server';
import { AccessSysGetter } from '@certd/lib-server';
import { isComm } from '@certd/plus-core';
import { CaptchaService } from "./captcha-service.js";
// {data: '<svg.../svg>', text: 'abcd'}
/**
@@ -23,44 +24,19 @@ export class CodeService {
@Inject()
accessService: AccessService;
/**
*/
async generateCaptcha(randomStr) {
const svgCaptcha = await import('svg-captcha');
const c = svgCaptcha.create();
//{data: '<svg.../svg>', text: 'abcd'}
const imgCode = c.text; // = RandomUtil.randomStr(4, true);
cache.set('imgCode:' + randomStr, imgCode, {
ttl: 2 * 60 * 1000, //过期时间 2分钟
});
return c;
}
@Inject()
captchaService: CaptchaService;
async getCaptchaText(randomStr) {
return cache.get('imgCode:' + randomStr);
}
async removeCaptcha(randomStr) {
cache.delete('imgCode:' + randomStr);
}
async checkCaptcha(randomStr: string, userCaptcha: string) {
const code = await this.getCaptchaText(randomStr);
if (code == null) {
throw new Error('验证码已过期');
}
if (code.toLowerCase() !== userCaptcha.toLowerCase()) {
throw new Error('验证码不正确');
}
await this.removeCaptcha(randomStr);
return true;
async checkCaptcha(body:any) {
return await this.captchaService.doValidate({form:body})
}
/**
*/
async sendSmsCode(
phoneCode = '86',
mobile: string,
randomStr: string,
opts?: {
duration?: number,
verificationType?: string,
@@ -70,9 +46,6 @@ export class CodeService {
if (!mobile) {
throw new Error('手机号不能为空');
}
if (!randomStr) {
throw new Error('randomStr不能为空');
}
const verificationCodeLength = Math.floor(Math.max(Math.min(opts?.verificationCodeLength || 4, 8), 4));
const duration = Math.floor(Math.max(Math.min(opts?.duration || 5, 15), 1));
@@ -96,7 +69,7 @@ export class CodeService {
phoneCode,
});
const key = this.buildSmsCodeKey(phoneCode, mobile, randomStr, opts?.verificationType);
const key = this.buildSmsCodeKey(phoneCode, mobile, opts?.verificationType);
cache.set(key, smsCode, {
ttl: duration * 60 * 1000, //5分钟
});
@@ -106,12 +79,10 @@ export class CodeService {
/**
*
* @param email
* @param randomStr
* @param opts title标题 content内容模版 duration有效时间单位分钟 verificationType验证类型
*/
async sendEmailCode(
email: string,
randomStr: string,
opts?: {
title?: string,
content?: string,
@@ -123,9 +94,7 @@ export class CodeService {
if (!email) {
throw new Error('Email不能为空');
}
if (!randomStr) {
throw new Error('randomStr不能为空');
}
let siteTitle = 'Certd';
if (isComm()) {
@@ -149,7 +118,7 @@ export class CodeService {
receivers: [email],
});
const key = this.buildEmailCodeKey(email, randomStr, opts?.verificationType);
const key = this.buildEmailCodeKey(email,opts?.verificationType);
cache.set(key, code, {
ttl: duration * 60 * 1000, //5分钟
});
@@ -159,31 +128,32 @@ export class CodeService {
/**
* checkSms
*/
async checkSmsCode(opts: { mobile: string; phoneCode: string; smsCode: string; randomStr: string; verificationType?: string; throwError: boolean; errorNum?: number }) {
const key = this.buildSmsCodeKey(opts.phoneCode, opts.mobile, opts.randomStr, opts.verificationType);
if (isDev()) {
async checkSmsCode(opts: { mobile: string; phoneCode: string; smsCode: string; verificationType?: string; throwError: boolean; maxErrorCount?: number }) {
const key = this.buildSmsCodeKey(opts.phoneCode, opts.mobile, opts.verificationType);
return this.checkValidateCode("sms",key, opts.smsCode, opts.throwError, opts.maxErrorCount);
}
buildSmsCodeKey(phoneCode: string, mobile: string, verificationType?: string) {
return ['sms', verificationType, phoneCode, mobile].filter(item => !!item).join(':');
}
buildEmailCodeKey(email: string, verificationType?: string) {
return ['email', verificationType, email].filter(item => !!item).join(':');
}
checkValidateCode(type:string,key: string, userCode: string, throwError = true, maxErrorCount = 3) {
// 记录异常次数key
if (isDev() && userCode==="1234567") {
return true;
}
return this.checkValidateCode(key, opts.smsCode, opts.throwError, opts.errorNum);
}
buildSmsCodeKey(phoneCode: string, mobile: string, randomStr: string, verificationType?: string) {
return ['sms', verificationType, phoneCode, mobile, randomStr].filter(item => !!item).join(':');
}
buildEmailCodeKey(email: string, randomStr: string, verificationType?: string) {
return ['email', verificationType, email, randomStr].filter(item => !!item).join(':');
}
checkValidateCode(key: string, userCode: string, throwError = true, errorNum = 3) {
// 记录异常次数key
const err_num_key = key + ':err_num';
//验证图片验证码
//验证邮件验证码
const code = cache.get(key);
if (code == null || code !== userCode) {
let maxRetryCount = false;
if (!!code && errorNum > 0) {
if (!!code && maxErrorCount > 0) {
const err_num = cache.get(err_num_key) || 0
if(err_num >= errorNum - 1) {
if(err_num >= maxErrorCount - 1) {
maxRetryCount = true;
cache.delete(key);
cache.delete(err_num_key);
@@ -194,7 +164,8 @@ export class CodeService {
}
}
if (throwError) {
throw new CodeErrorException(!maxRetryCount ? '验证码错误': '验证码错误请获取新的验证码');
const label = type ==='sms' ? '手机' : '邮箱';
throw new CodeErrorException(!maxRetryCount ? `${label}验证码错误`: `${label}验证码错误请获取新的验证码`);
}
return false;
}
@@ -203,9 +174,9 @@ export class CodeService {
return true;
}
checkEmailCode(opts: { randomStr: string; validateCode: string; email: string; verificationType?: string; throwError: boolean; errorNum?: number }) {
const key = this.buildEmailCodeKey(opts.email, opts.randomStr, opts.verificationType);
return this.checkValidateCode(key, opts.validateCode, opts.throwError, opts.errorNum);
checkEmailCode(opts: { validateCode: string; email: string; verificationType?: string; throwError: boolean; maxErrorCount?: number }) {
const key = this.buildEmailCodeKey(opts.email, opts.verificationType);
return this.checkValidateCode('email',key, opts.validateCode, opts.throwError, opts.maxErrorCount);
}
compile(templateString: string) {
@@ -1,17 +1,22 @@
import {Config, Inject, Provide, Scope, ScopeEnum} from '@midwayjs/core';
import {UserService} from '../../sys/authority/service/user-service.js';
import jwt from 'jsonwebtoken';
import {AuthException, CommonException, Need2FAException} from "@certd/lib-server";
import {RoleService} from '../../sys/authority/service/role-service.js';
import {UserEntity} from '../../sys/authority/entity/user.js';
import {SysSettingsService} from '@certd/lib-server';
import {SysPrivateSettings} from '@certd/lib-server';
import {cache, utils} from '@certd/basic';
import {LoginErrorException} from '@certd/lib-server/dist/basic/exception/login-error-exception.js';
import {CodeService} from '../../basic/service/code-service.js';
import {TwoFactorService} from "../../mine/service/two-factor-service.js";
import {UserSettingsService} from '../../mine/service/user-settings-service.js';
import {isPlus} from "@certd/plus-core";
import { Config, Inject, Provide, Scope, ScopeEnum } from "@midwayjs/core";
import { UserService } from "../../sys/authority/service/user-service.js";
import jwt from "jsonwebtoken";
import {
AuthException,
CommonException,
Need2FAException,
SysPrivateSettings,
SysSettingsService
} from "@certd/lib-server";
import { RoleService } from "../../sys/authority/service/role-service.js";
import { UserEntity } from "../../sys/authority/entity/user.js";
import { cache, utils } from "@certd/basic";
import { LoginErrorException } from "@certd/lib-server/dist/basic/exception/login-error-exception.js";
import { CodeService } from "../../basic/service/code-service.js";
import { TwoFactorService } from "../../mine/service/two-factor-service.js";
import { UserSettingsService } from "../../mine/service/user-settings-service.js";
import { isPlus } from "@certd/plus-core";
import { AddonService } from "@certd/lib-server/dist/user/addon/service/addon-service.js";
/**
*
@@ -35,6 +40,8 @@ export class LoginService {
userSettingsService: UserSettingsService;
@Inject()
twoFactorService: TwoFactorService;
@Inject()
addonService: AddonService;
checkIsBlocked(username: string) {
const blockDurationKey = `login_block_duration:${username}`;
@@ -106,13 +113,12 @@ export class LoginService {
mobile: req.mobile,
phoneCode: req.phoneCode,
smsCode: req.smsCode,
randomStr: req.randomStr,
throwError: false,
});
const {mobile, phoneCode} = req;
if (!smsChecked) {
this.addErrorTimes(mobile, '验证码错误');
this.addErrorTimes(mobile, '手机验证码错误');
}
let info = await this.userService.findOne({phoneCode, mobile: mobile});
if (info == null) {
@@ -30,6 +30,9 @@ export class CertInfoEntity {
@Column({ name: 'cert_provider', comment: '证书颁发机构' })
certProvider: string;
@Column({ name: 'effective_time', comment: '生效时间' })
effectiveTime: number;
@Column({ name: 'expires_time', comment: '过期时间' })
expiresTime: number;
@@ -26,6 +26,8 @@ export class SiteInfoEntity {
@Column({ name: 'cert_provider', comment: '证书颁发机构', length: 100 })
certProvider: string;
@Column({ name: 'cert_effective_time', comment: '证书生效时间' })
certEffectiveTime: number;
@Column({ name: 'cert_expires_time', comment: '证书到期时间' })
certExpiresTime: number;
@Column({ name: 'last_check_time', comment: '上次检查时间' })
@@ -164,6 +164,7 @@ export class CertInfoService extends BaseService<CertInfoEntity> {
bean.domains = domains.join(',');
bean.domain = domains[0];
bean.domainCount = domains.length;
bean.effectiveTime = certReader.effective;
bean.expiresTime = certReader.expires;
bean.certProvider = certReader.detail.issuer.commonName;
bean.userId = userId
@@ -134,6 +134,7 @@ export class SiteInfoService extends BaseService<SiteInfoEntity> {
if (!certi) {
throw new Error("没有发现证书");
}
const effective = certi.valid_from;
const expires = certi.valid_to;
const allDomains = certi.subjectaltname?.replaceAll("DNS:", "").split(",") || [];
const mainDomain = certi.subject?.CN;
@@ -149,12 +150,13 @@ export class SiteInfoService extends BaseService<SiteInfoEntity> {
certDomains: domains.join(","),
certStatus: status,
certProvider: issuer,
certEffectiveTime: dayjs(effective).valueOf(),
certExpiresTime: dayjs(expires).valueOf(),
lastCheckTime: dayjs().valueOf(),
error: null,
checkStatus: "ok"
};
logger.info(`测试站点成功:id=${updateData.id},site=${site.name},expiresTime=${updateData.certExpiresTime}`)
logger.info(`测试站点成功:id=${updateData.id},site=${site.name},certEffectiveTime=${updateData.certEffectiveTime},expiresTime=${updateData.certExpiresTime}`)
if (site.ipCheck) {
delete updateData.checkStatus
}
@@ -80,7 +80,11 @@ export class SiteTester {
}
}
options.agent = new https.Agent({ keepAlive: false, lookup: customLookup });
const agentOptions:any = { keepAlive: false };
if (customLookup) {
agentOptions.lookup = customLookup
}
options.agent = new https.Agent(agentOptions);
// 创建 HTTPS 请求
const requestPromise = safePromise((resolve, reject) => {
@@ -934,6 +934,7 @@ export class PipelineService extends BaseService<PipelineEntity> {
"sslProvider": "letsencrypt",
"privateKeyType": "rsa_2048",
"certProfile": "classic",
"preferredChain": "ISRG Root X1",
"useProxy": false,
"skipLocalVerify": false,
"maxCheckRetryCount": 20,
@@ -238,9 +238,12 @@ export class UserService extends BaseService<UserEntity> {
async forgotPassword(
data: {
type: ForgotPasswordType; input?: string, phoneCode?: string,
randomStr: string, imgCode:string, validateCode: string,
password: string, confirmPassword: string,
type: ForgotPasswordType;
input?: string,
phoneCode?: string,
validateCode: string,
password: string,
confirmPassword: string,
}
) {
if(!data.type) {
@@ -249,7 +252,13 @@ export class UserService extends BaseService<UserEntity> {
if(data.password !== data.confirmPassword) {
throw new CommonException('两次输入的密码不一致');
}
const user = await this.findOne([{ [data.type]: data.input }]);
const where :any= {
[data.type]: data.input,
};
if (data.type === 'mobile' ) {
where.phoneCode = data.phoneCode ?? '86';
}
const user = await this.findOne({ [data.type]: data.input });
console.log('user', user)
if(!user) {
throw new CommonException('用户不存在');
@@ -34,3 +34,5 @@ export * from './plugin-admin/index.js'
export * from './plugin-ksyun/index.js'
export * from './plugin-apisix/index.js'
export * from './plugin-dokploy/index.js'
export * from './plugin-godaddy/index.js'
export * from './plugin-captcha/index.js'
@@ -116,6 +116,12 @@ export class AliyunDeployCertToFC extends AbstractTaskPlugin {
})
protocol!: string;
@TaskInput({
title: '证书名称',
helper: '上传后将以此名称作为前缀备注',
})
certName!: string;
async onInstance() {}
async exec(cmd: string) {
@@ -179,7 +185,7 @@ export class AliyunDeployCertToFC extends AbstractTaskPlugin {
bodyType: 'json',
});
// body params
const certName = this.buildCertName(CertReader.getMainDomain(this.cert.crt))
const certName = this.buildCertName(CertReader.getMainDomain(this.cert.crt),this.certName??"")
const body: { [key: string]: any } = {
certConfig: {
@@ -0,0 +1,4 @@
export interface ICaptchaAddon{
onValidate(data?:any):Promise<any>;
getCaptcha():Promise<any>;
}
@@ -0,0 +1,122 @@
import { AddonInput, BaseAddon, IsAddon } from "@certd/lib-server";
import crypto from "crypto";
import { ICaptchaAddon } from "../api.js";
@IsAddon({
addonType:"captcha",
name: 'geetest',
title: '极验验证码v4',
desc: '',
showTest:false,
})
export class GeeTestCaptcha extends BaseAddon implements ICaptchaAddon{
@AddonInput({
title: '验证ID',
component: {
placeholder: 'captchaId',
},
helper:"[极验验证码v4](https://console.geetest.com/sensbot/management) -> 创建业务模块 -> 新增业务场景",
required: true,
})
captchaId = '';
@AddonInput({
title: '验证Key',
component: {
placeholder: 'captchaKey',
},
required: true,
})
captchaKey = '';
async onValidate(data?:any) {
if (!data) {
return false
}
// geetest 服务地址
// geetest server url
const API_SERVER = "http://gcaptcha4.geetest.com";
// geetest 验证接口
// geetest server interface
const API_URL = API_SERVER + "/validate" + "?captcha_id=" + this.captchaId;
// 前端参数
// web parameter
var lot_number = data['lot_number'];
var captcha_output = data['captcha_output'];
var pass_token = data['pass_token'];
var gen_time = data['gen_time'];
if (!lot_number || !captcha_output || !pass_token || !gen_time) {
return false;
}
// 生成签名, 使用标准的hmac算法,使用用户当前完成验证的流水号lot_number作为原始消息message,使用客户验证私钥作为key
// 采用sha256散列算法将message和key进行单向散列生成最终的 “sign_token” 签名
// use lot_number + CAPTCHA_KEY, generate the signature
var sign_token = this.hmac_sha256_encode(lot_number, this.captchaKey);
// 向极验转发前端数据 + “sign_token” 签名
// send web parameter and “sign_token” to geetest server
var datas = {
'lot_number': lot_number,
'captcha_output': captcha_output,
'pass_token': pass_token,
'gen_time': gen_time,
'sign_token': sign_token
};
// post request
// 根据极验返回的用户验证状态, 网站主进行自己的业务逻辑
// According to the user authentication status returned by the geetest, the website owner carries out his own business logic
try{
const res = await this.doRequest(datas, API_URL)
if (res.result == "success") {
// 验证成功
// verification successful
return true;
} else {
// 验证失败
// verification failed
this.logger.error("极验验证不通过 ",res.reason)
return false;
}
}catch (e) {
this.ctx.logger.error("极验验证服务异常",e)
return true
}
}
// 生成签名
// Generate signature
hmac_sha256_encode(value, key){
var hash = crypto.createHmac("sha256", key)
.update(value, 'utf8')
.digest('hex');
return hash;
}
// 发送post请求, 响应json数据如:{"result": "success", "reason": "", "captcha_args": {}}
// Send a post request and respond to JSON data, such as: {result ":" success "," reason ":" "," captcha_args ": {}}
async doRequest(datas, url){
var options = {
url: url,
method: "POST",
params: datas,
timeout: 5000
};
const result = await this.ctx.http.request(options);
return result;
}
async getCaptcha(): Promise<any> {
return {
captchaId: this.captchaId,
}
}
}
@@ -0,0 +1,56 @@
import { BaseAddon, IsAddon } from "@certd/lib-server";
import { ICaptchaAddon } from "../api.js";
import { cache } from "@certd/basic";
import { nanoid } from "nanoid";
@IsAddon({
addonType:"captcha",
name: 'image',
title: '图片验证码',
desc: '',
showTest:false,
})
export class ImageCaptcha extends BaseAddon implements ICaptchaAddon{
async onValidate(data?:any) {
if (!data) {
return false;
}
return await this.checkCaptcha(data.randomStr, data.imageCode)
}
async getCaptchaText(randomStr:string) {
return cache.get('imgCode:' + randomStr);
}
async removeCaptcha(randomStr:string) {
cache.delete('imgCode:' + randomStr);
}
async checkCaptcha(randomStr: string, userCaptcha: string) {
const code = await this.getCaptchaText(randomStr);
if (code == null) {
throw new Error('验证码已过期');
}
if (code.toLowerCase() !== userCaptcha?.toLowerCase()) {
throw new Error('验证码不正确');
}
await this.removeCaptcha(randomStr);
return true;
}
async getCaptcha(): Promise<any> {
const svgCaptcha = await import('svg-captcha');
const c = svgCaptcha.create();
//{data: '<svg.../svg>', text: 'abcd'}
const imgCode = c.text; // = RandomUtil.randomStr(4, true);
const randomStr = nanoid(10)
cache.set('imgCode:' + randomStr, imgCode, {
ttl: 2 * 60 * 1000, //过期时间 2分钟
})
return {
randomStr: randomStr,
imageData: c.data,
}
}
}
@@ -0,0 +1,2 @@
export * from './geetest/index.js';
export * from './image/index.js';
@@ -22,6 +22,7 @@ export class GcoreflushPlugin extends AbstractTaskPlugin {
certName!: string;
@TaskInput({
title: '证书ID',
required:true,
})
ssl_id!: string;
@@ -66,6 +67,10 @@ export class GcoreflushPlugin extends AbstractTaskPlugin {
async execute(): Promise<void> {
const { cert, accessId } = this;
if(!this.ssl_id){
throw new Error('请填写要刷新的证书ID');
}
const access = (await this.getAccess(accessId)) as GcoreAccess;
let otp = null;
if (access.otpkey) {
@@ -0,0 +1,96 @@
import {AccessInput, BaseAccess, IsAccess, Pager, PageSearch} from '@certd/pipeline';
import {HttpRequestConfig} from "@certd/basic";
/**
*
* certd的后台管理系统中
*/
@IsAccess({
name: 'godaddy',
title: 'godaddy授权',
icon: 'simple-icons:godaddy',
desc: '',
})
export class GodaddyAccess extends BaseAccess {
/**
*
*/
@AccessInput({
title: 'Key',
component: {
placeholder: '授权key',
},
helper:"[https://developer.godaddy.com/keys](https://developer.godaddy.com/keys),创建key(选择product,不要选择ote",
required: true,
encrypt: false,
})
key = '';
@AccessInput({
title: 'Secret',
component: {
name:"a-input-password",
vModel:"value",
},
required: true,
encrypt: true,
})
secret = '';
@AccessInput({
title: 'HTTP代理',
component: {
placeholder: 'http://xxxxx:xx',
},
helper: '使用https_proxy',
required: false,
})
httpProxy = '';
@AccessInput({
title: "测试",
component: {
name: "api-test",
action: "TestRequest"
},
helper: "点击测试接口是否正常(注意账号中必须要有50个域名才能使用API接口)"
})
testRequest = true;
async onTestRequest() {
const res = await this.getDomainList({pageSize:1});
this.ctx.logger.info(res)
return "ok"
}
async getDomainList(opts?: PageSearch){
const pager = new Pager(opts);
const req = {
url :`/v1/domains?limit=${pager.pageSize}`,
method: "get",
}
return await this.doRequest(req);
}
async doRequest(req: HttpRequestConfig){
const headers = {
"Authorization": `sso-key ${this.key}:${this.secret}`,
...req.headers
};
return await this.ctx.http.request({
headers,
baseURL: "https://api.godaddy.com",
...req,
logRes: true,
httpProxy: this.httpProxy,
});
}
}
new GodaddyAccess();
@@ -0,0 +1,90 @@
import { AbstractDnsProvider, CreateRecordOptions, IsDnsProvider, RemoveRecordOptions } from "@certd/plugin-cert";
import { GodaddyAccess } from "./access.js";
export type GodaddyRecord = {
domain: string,
type: string,
name: string,
data: string,
};
// 这里通过IsDnsProvider注册一个dnsProvider
@IsDnsProvider({
name: 'godaddy',
title: 'godaddy',
desc: 'GoDaddy',
icon: 'simple-icons:godaddy',
// 这里是对应的 cloudflare的access类型名称
accessType: 'godaddy',
order:10,
})
export class GodaddyDnsProvider extends AbstractDnsProvider<GodaddyRecord> {
access!: GodaddyAccess;
async onInstance() {
//一些初始化的操作
// 也可以通过ctx成员变量传递context
this.access = this.ctx.access as GodaddyAccess;
}
/**
* dns解析记录
*/
async createRecord(options: CreateRecordOptions): Promise<GodaddyRecord> {
/**
* fullRecord: '_acme-challenge.test.example.com',
* value: 一串uuid
* type: 'TXT',
* domain: 'example.com'
* hostRecord: _acme-challenge.test
*/
const { fullRecord,hostRecord, value, type, domain } = options;
this.logger.info('添加域名解析:', fullRecord, value, type, domain);
const res = await this.access.doRequest({
method: 'PATCH',
url: '/v1/domains/'+domain+'/records',
data: [
{
type: 'TXT',
name: hostRecord,
data: value,
ttl: 600,
}
]
})
this.logger.info('添加域名解析成功:', res);
return {
domain: domain,
type: 'TXT',
name: hostRecord,
data: value,
};
}
/**
* dns解析记录,
* @param options
*/
async removeRecord(options: RemoveRecordOptions<GodaddyRecord>): Promise<void> {
const { fullRecord, value } = options.recordReq;
const record = options.recordRes;
this.logger.info('删除域名解析:', fullRecord, value);
if (!record) {
this.logger.info('record为空,不执行删除');
return;
}
//这里调用删除txt dns解析记录接口
const {name,type,domain} = record
const res = await this.access.doRequest({
method: 'DELETE',
url: '/v1/domains/'+domain+`/records/${type}/${name}`,
})
this.logger.info(`删除域名解析成功:fullRecord=${fullRecord},id=${res}`);
}
}
//实例化这个provider,将其自动注册到系统中
new GodaddyDnsProvider();
@@ -0,0 +1,2 @@
export * from './dns-provider.js';
export * from './access.js';
@@ -103,6 +103,10 @@ export class DeployCertToTencentEO extends AbstractTaskPlugin {
logger: this.logger,
});
if (this.cert == null){
throw new Error('请选择域名证书');
}
let tencentCertId = this.cert as string;
if (typeof this.cert !== 'string') {
const certReader = new CertReader(this.cert);
@@ -9,3 +9,4 @@ export * from './delete-expiring-cert/index.js';
export * from './deploy-to-tke-ingress/index.js';
export * from './deploy-to-live/index.js';
export * from './start-instances/index.js';
export * from './refresh-cert/index.js';
@@ -0,0 +1,340 @@
import {
AbstractTaskPlugin,
IsTaskPlugin,
Pager,
PageSearch,
pluginGroups,
RunStrategy,
TaskInput
} from "@certd/pipeline";
import { CertApplyPluginNames, CertInfo } from "@certd/plugin-cert";
import { createCertDomainGetterInputDefine, createRemoteSelectInputDefine } from "@certd/plugin-lib";
import { TencentAccess, TencentSslClient } from "@certd/plugin-lib";
import { omit } from "lodash-es";
@IsTaskPlugin({
//命名规范,插件类型+功能(就是目录plugin-demo中的demo),大写字母开头,驼峰命名
name: "TencentRefreshCert",
title: "腾讯云-更新证书(Id不变)",
desc: "根据证书id一键更新腾讯云证书并自动部署(Id不变),注意该接口为腾讯云白名单功能,非白名单用户无法使用该功能",
icon: "svg:icon-tencentcloud",
//插件分组
group: pluginGroups.tencent.key,
needPlus: false,
default: {
//默认值配置照抄即可
strategy: {
runStrategy: RunStrategy.SkipWhenSucceed
}
}
})
//类名规范,跟上面插件名称(name)一致
export class TencentRefreshCert extends AbstractTaskPlugin {
//证书选择,此项必须要有
@TaskInput({
title: "域名证书",
helper: "请选择前置任务输出的域名证书",
component: {
name: "output-selector",
from: [...CertApplyPluginNames]
}
// required: true, // 必填
})
cert!: CertInfo;
@TaskInput(createCertDomainGetterInputDefine({ props: { required: false } }))
certDomains!: string[];
//授权选择框
@TaskInput({
title: "腾讯云授权",
component: {
name: "access-selector",
type: "tencent" //固定授权类型
},
required: true //必填
})
accessId!: string;
//
@TaskInput(
createRemoteSelectInputDefine({
title: "证书Id",
helper: "要更新的证书id,如果这里没有,请先给手动绑定一次证书",
action: TencentRefreshCert.prototype.onGetCertList.name,
pager: false,
search: false
})
)
certList!: string[];
// @TaskInput({
// title: '资源类型',
// component: {
// name: 'a-select',
// vModel: 'value',
// allowClear: true,
// mode: "tags",
// options: [
// { value: 'clb',label: '负载均衡'},
// { value: 'cdn',label: 'CDN'},
// { value: 'ddos',label: 'DDoS'},
// { value: 'live',label: '直播'},
// { value: 'vod',label: '点播'},
// { value: 'waf',label: 'Web应用防火墙'},
// { value: 'apigateway',label: 'API网关'},
// { value: 'teo',label: 'TEO'},
// { value: 'tke',label: '容器服务'},
// { value: 'cos',label: '对象存储'},
// { value: 'lighthouse',label: '轻应用服务器'},
// { value: 'tse',label: '云原生微服务'},
// { value: 'tcb',label: '云开发'},
// ]
// },
// helper: '',
// required: true,
// })
// resourceTypes!: string[];
@TaskInput({
title: '资源区域',
helper:"如果云资源类型区分区域,请选择区域,如果区域在选项中不存在,请手动输入",
component: {
name: 'remote-tree-select',
vModel: 'value',
action: TencentRefreshCert.prototype.onGetRegionsTree.name,
pager: false,
search: false,
watches: ['certList'],
},
required: false,
})
resourceTypesRegions!: string[];
//插件实例化时执行的方法
async onInstance() {
}
//插件执行方法
async execute(): Promise<void> {
const access = await this.getAccess<TencentAccess>(this.accessId);
const sslClient = new TencentSslClient({
access:access,
logger: this.logger,
});
// await access.createCert({cert:this.cert})
let resourceTypes = []
const resourceTypesRegions = []
for (const item of this.resourceTypesRegions) {
const [type,region] = item.split("_")
if (!resourceTypes.includes( type)){
resourceTypes.push(type)
}
if (!region){
continue;
}
const resourceType = resourceTypesRegions.find(item => item.ResourceType == type)
if (!resourceType){
resourceTypesRegions.push({
ResourceType: type,
Regions: [region]
})
}else{
resourceType.Regions.push(region)
}
}
// resourceTypes = ["clb"] //固定clb
const maxRetry = 10
for (const certId of this.certList) {
this.logger.info(`----------- 开始更新证书:${certId}`);
let deployRes = null
let retryCount = 0
while(true){
if (retryCount>maxRetry){
this.logger.error(`任务创建失败`);
break;
}
retryCount++
deployRes = await sslClient.UploadUpdateCertificateInstance({
OldCertificateId: certId,
"ResourceTypes": resourceTypes,
"CertificatePublicKey": this.cert.crt,
"CertificatePrivateKey": this.cert.key,
"ResourceTypesRegions":resourceTypesRegions
});
if (deployRes && deployRes.DeployRecordId>0){
this.logger.info(`任务创建成功,开始检查结果:${JSON.stringify(deployRes)}`);
break;
}else{
this.logger.info(`任务创建中,稍后查询:${JSON.stringify(deployRes)}`);
}
await this.ctx.utils.sleep(3000);
}
this.logger.info(`开始查询部署结果`);
retryCount=0
while(true){
if (retryCount>maxRetry){
this.logger.error(`任务结果检查失败`);
break;
}
retryCount++
//查询部署状态
const deployStatus = await sslClient.DescribeHostUploadUpdateRecordDetail({
"DeployRecordId":deployRes.DeployRecordId
})
const details = deployStatus.DeployRecordDetail
let allSuccess = true
for (const item of details) {
this.logger.info(`查询结果:${JSON.stringify(omit(item,"RecordDetailList"))}`);
if (item.Status === 2) {
throw new Error(`任务失败:${JSON.stringify(item.RecordDetailList)}`)
}else if (item.Status !== 1) {
//如果不是成功状态
allSuccess = false
}
}
if (allSuccess) {
break;
}
await this.ctx.utils.sleep(10000);
}
this.logger.info(`----------- 更新证书${certId}成功`);
}
}
async onGetRegionsTree(data: PageSearch = {}){
const commonRegions = [
/**
* 广 waf.ap-guangzhou.tencentcloudapi.com
* waf.ap-shanghai.tencentcloudapi.com
* waf.ap-nanjing.tencentcloudapi.com
* waf.ap-beijing.tencentcloudapi.com
* 西 waf.ap-chengdu.tencentcloudapi.com
* 西 waf.ap-chongqing.tencentcloudapi.com
* waf.ap-hongkong.tencentcloudapi.com
* waf.ap-singapore.tencentcloudapi.com
* waf.ap-jakarta.tencentcloudapi.com
* waf.ap-bangkok.tencentcloudapi.com
* waf.ap-seoul.tencentcloudapi.com
* waf.ap-tokyo.tencentcloudapi.com
* waf.na-ashburn.tencentcloudapi.com
* 西 waf.na-siliconvalley.tencentcloudapi.com
* waf.sa-saopaulo.tencentcloudapi.com
* waf.eu-frankfurt.tencentcloudapi.com
*/
{value:"ap-guangzhou", label:"广州"},
{value:"ap-shanghai", label:"上海"},
{value:"ap-nanjing", label:"南京"},
{value:"ap-beijing", label:"北京"},
{value:"ap-chengdu", label:"成都"},
{value:"ap-chongqing", label:"重庆"},
{value:"ap-hongkong", label:"香港"},
{value:"ap-singapore", label:"新加坡"},
{value:"ap-jakarta", label:"雅加达"},
{value:"ap-bangkok", label:"曼谷"},
{value:"ap-tokyo", label:"东京"},
{value:"ap-seoul", label:"首尔"},
{value:"na-ashburn", label:"弗吉尼亚"},
{value:"na-siliconvalley", label:"硅谷"},
{value:"sa-saopaulo", label:"圣保罗"},
{value:"eu-frankfurt", label:"法兰克福"},
]
function buildTypeRegions(type: string) {
const options :any[]= []
for (const region of commonRegions) {
options.push({
label: type + "_" + region.label,
value: type + "_" + region.value,
});
}
return options
}
return [
{ value: 'cdn',label: 'CDN'},
{ value: 'ddos',label: 'DDoS'},
{ value: 'live',label: '直播'},
{ value: 'vod',label: '点播'},
{ value: 'teo',label: 'TEO'},
{ value: 'lighthouse',label: '轻应用服务器'},
{
label: "负载均衡(clb)",
value: "clb",
children: buildTypeRegions("clb"),
},
{
label: "Web应用防火墙(waf)",
value: "waf",
children: buildTypeRegions("waf"),
},
{
label: "API网关(apigateway)",
value: "apigateway",
children: buildTypeRegions("apigateway"),
},
{
label: "对象存储(COS)",
value: "cos",
children: buildTypeRegions("cos"),
},
{
label: "容器服务(tke)",
value: "tke",
children: buildTypeRegions("tke"),
},
{
label: "云原生微服务(tse)",
value: "tse",
children: buildTypeRegions("tse"),
},
{
label: "云开发(tcb)",
value: "tcb",
children: buildTypeRegions("tcb"),
},
]
}
async onGetCertList(data: PageSearch = {}) {
const access = await this.getAccess<TencentAccess>(this.accessId)
const sslClient = new TencentSslClient({
access:access,
logger: this.logger,
});
const pager = new Pager(data);
const offset = pager.getOffset();
const limit = pager.pageSize
const res = await sslClient.DescribeCertificates({Limit:limit,Offset:offset,SearchKey:data.searchKey})
const list = res.Certificates
if (!list || list.length === 0) {
throw new Error("没有找到证书,你可以直接手动输入id");
}
/**
* certificate-id
* name
* dns-names
*/
const options = list.map((item: any) => {
return {
label: `${item.Alias}<${item.Domain}_${item.CertificateId}>`,
value: item.CertificateId,
domain: item.SubjectAltName,
};
});
return {
list: this.ctx.utils.options.buildGroupOptions(options, this.certDomains),
};
}
}
//实例化一下,注册插件
new TencentRefreshCert();
@@ -65,7 +65,7 @@ export class UpyunClient {
Cookie: req.cookie
}
});
if (res.msg.errors.length > 0) {
if (res.msg?.errors?.length > 0) {
throw new Error(JSON.stringify(res.msg));
}
if(res.data?.error_code){