接通 DNS 账户管理页面并补项目权限与敏感输入回归
This commit is contained in:
1 parent
7f7b0849d5
commit
0adb190a80
21 files changed
+866
-31
No files matched your search
@@ -0,0 +1,93 @@
|
||||
.dns-account-dialog {
|
||||
width: min(620px, calc(100vw - 48px));
|
||||
max-height: calc(100dvh - 48px);
|
||||
box-sizing: border-box;
|
||||
overflow-y: auto;
|
||||
padding: 24px;
|
||||
border: 1px solid #d5ddea;
|
||||
border-radius: 16px;
|
||||
color: #20314f;
|
||||
}
|
||||
|
||||
.dns-account-dialog::backdrop {
|
||||
background: rgb(15 23 42 / 42%);
|
||||
}
|
||||
|
||||
header,
|
||||
footer {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
h3 {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
fieldset {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
gap: 16px;
|
||||
padding: 20px 0;
|
||||
margin: 0;
|
||||
border: 0;
|
||||
}
|
||||
|
||||
label {
|
||||
display: grid;
|
||||
gap: 8px;
|
||||
min-width: 0;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
input,
|
||||
select,
|
||||
button {
|
||||
box-sizing: border-box;
|
||||
min-width: 0;
|
||||
padding: 9px 12px;
|
||||
border: 1px solid #d5ddea;
|
||||
border-radius: 8px;
|
||||
background: white;
|
||||
color: inherit;
|
||||
font: inherit;
|
||||
}
|
||||
|
||||
button {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
button[type="submit"] {
|
||||
color: white;
|
||||
background: #315aaa;
|
||||
}
|
||||
|
||||
:disabled {
|
||||
opacity: 0.6;
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
:focus-visible {
|
||||
outline: 2px solid #315aaa;
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
.dns-dialog-confirm {
|
||||
grid-column: 1 / -1;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.dns-dialog-error {
|
||||
color: #a92e2e;
|
||||
}
|
||||
|
||||
footer {
|
||||
justify-content: flex-end;
|
||||
}
|
||||
|
||||
@media (max-width: 540px) {
|
||||
fieldset {
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
<script setup>
|
||||
import { onBeforeUnmount, onMounted, ref } from "vue";
|
||||
|
||||
defineProps({
|
||||
editor: { type: Object, required: true },
|
||||
title: { type: String, required: true },
|
||||
projects: { type: Array, required: true },
|
||||
providers: { type: Array, required: true },
|
||||
provider: { type: Object, default: null },
|
||||
saving: Boolean,
|
||||
error: { type: String, default: "" },
|
||||
});
|
||||
const emit = defineEmits(["close", "save", "provider-change"]);
|
||||
const dialog = ref(null);
|
||||
let previousFocus;
|
||||
onMounted(() => {
|
||||
previousFocus = document.activeElement;
|
||||
dialog.value.showModal();
|
||||
});
|
||||
onBeforeUnmount(() => previousFocus?.focus?.());
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<dialog ref="dialog" class="dns-account-dialog" aria-labelledby="dns-editor-title" @cancel.prevent="emit('close')">
|
||||
<form autocomplete="off" :aria-busy="saving" @submit.prevent="emit('save')">
|
||||
<header>
|
||||
<h3 id="dns-editor-title">{{ title }}</h3>
|
||||
<button type="button" :disabled="saving" aria-label="关闭账户编辑" @click="emit('close')">关闭</button>
|
||||
</header>
|
||||
<fieldset :disabled="saving">
|
||||
<label v-if="['create', 'rename'].includes(editor.action)">
|
||||
账户名称
|
||||
<input v-model="editor.name" autofocus required maxlength="128" aria-label="账户名称" />
|
||||
</label>
|
||||
<template v-if="editor.action === 'create'">
|
||||
<label>
|
||||
归属项目
|
||||
<select v-model="editor.project_id" required aria-label="归属项目">
|
||||
<option v-for="project in projects" :key="project.id" :value="project.id">{{ project.name }}</option>
|
||||
</select>
|
||||
</label>
|
||||
<label>
|
||||
DNS 服务商
|
||||
<select v-model="editor.provider" required aria-label="DNS 服务商" @change="emit('provider-change')">
|
||||
<option v-for="item in providers" :key="item.id" :value="item.id">{{ item.name }}</option>
|
||||
</select>
|
||||
</label>
|
||||
</template>
|
||||
<template v-if="['create', 'rotate'].includes(editor.action)">
|
||||
<label v-for="field in provider?.credential_fields || []" :key="`${editor.provider}-${field.name}`" :title="field.placeholder">
|
||||
{{ field.label }}{{ field.required ? '(必填)' : '(可选)' }}
|
||||
<input
|
||||
v-model="editor.credentials[field.name]"
|
||||
:type="field.secret ? 'password' : 'text'"
|
||||
:required="field.required"
|
||||
:aria-label="field.label"
|
||||
:placeholder="field.placeholder"
|
||||
autocomplete="off"
|
||||
spellcheck="false"
|
||||
/>
|
||||
</label>
|
||||
</template>
|
||||
<label v-if="editor.action === 'verify'" title="仅填写你有权管理的域名。验证会创建、查询并清理临时 DNS 记录。">
|
||||
授权测试域名
|
||||
<input v-model="editor.test_domain" required aria-label="授权测试域名" placeholder="example.com" />
|
||||
</label>
|
||||
<p v-if="editor.action === 'status'" class="dns-dialog-confirm">
|
||||
确认{{ editor.enabled ? '启用' : '停用' }}账户“{{ editor.name }}”?
|
||||
</p>
|
||||
<p v-if="editor.action === 'rotate'" class="dns-dialog-confirm">
|
||||
为“{{ editor.name }}”保存新凭据后,需要重新验证。
|
||||
</p>
|
||||
</fieldset>
|
||||
<p v-if="error" class="dns-dialog-error" role="alert">{{ error }}</p>
|
||||
<footer>
|
||||
<button type="button" :disabled="saving" @click="emit('close')">取消</button>
|
||||
<button type="submit" :disabled="saving">{{ saving ? '处理中…' : editor.action === 'verify' ? '开始在线验证' : '确认保存' }}</button>
|
||||
</footer>
|
||||
</form>
|
||||
</dialog>
|
||||
</template>
|
||||
|
||||
<style scoped src="./DNSAccountDialog.css"></style>
|
||||
@@ -0,0 +1,131 @@
|
||||
import { computed, onBeforeUnmount, ref } from "vue";
|
||||
import { requestDNS } from "./DNSAccountRequest.js";
|
||||
|
||||
const titles = {
|
||||
create: "新增 DNS 账户", rename: "修改账户名称", rotate: "轮换 DNS 凭据",
|
||||
verify: "验证 DNS 权限", status: "变更账户状态",
|
||||
};
|
||||
|
||||
export function useDNSAccountEditor(projects, providers, loading, refresh) {
|
||||
const editor = ref(null);
|
||||
const saving = ref(false);
|
||||
const mutationError = ref("");
|
||||
const notice = ref("");
|
||||
const managedProjects = computed(() => projects.value.filter((item) => item.can_manage_dns === true));
|
||||
const selectedProvider = computed(() => providers.value.find((item) => item.id === editor.value?.provider));
|
||||
const editorTitle = computed(() => titles[editor.value?.action] || "DNS 账户");
|
||||
let mounted = true;
|
||||
let target = null;
|
||||
|
||||
function canManage(account) {
|
||||
return account?.managed === true && Number.isSafeInteger(account.revision) && account.revision > 0
|
||||
&& managedProjects.value.some((item) => item.id === account.project_id);
|
||||
}
|
||||
|
||||
function clearEditor() {
|
||||
if (editor.value) editor.value.credentials = {};
|
||||
editor.value = null;
|
||||
target = null;
|
||||
}
|
||||
|
||||
function closeEditor() {
|
||||
if (!saving.value) clearEditor();
|
||||
}
|
||||
|
||||
function openEditor(action, account = null) {
|
||||
if (loading.value || saving.value || !titles[action]) return;
|
||||
if (action === "create" ? managedProjects.value.length === 0 : !canManage(account)) return;
|
||||
if (action === "verify" && account.status !== "active") return;
|
||||
clearEditor();
|
||||
mutationError.value = "";
|
||||
notice.value = "";
|
||||
target = action === "create" ? null : { ...account };
|
||||
editor.value = {
|
||||
action, name: account?.name || "", project_id: account?.project_id || managedProjects.value[0]?.id || "",
|
||||
provider: account?.provider || providers.value[0]?.id || "", credentials: {}, test_domain: "",
|
||||
enabled: account?.status !== "active",
|
||||
};
|
||||
}
|
||||
|
||||
function changeProvider() {
|
||||
if (!saving.value && editor.value?.action === "create") editor.value.credentials = {};
|
||||
}
|
||||
|
||||
async function saveEditor() {
|
||||
const form = editor.value;
|
||||
if (!mounted || !form || saving.value || loading.value) return;
|
||||
mutationError.value = "";
|
||||
if (form.action === "create" ? !managedProjects.value.some((item) => item.id === form.project_id) : !canManage(target)) {
|
||||
mutationError.value = "当前项目没有 DNS 管理权限,请刷新列表";
|
||||
return;
|
||||
}
|
||||
const body = form.action === "create" ? {} : { revision: target.revision };
|
||||
if (["create", "rename"].includes(form.action)) {
|
||||
const name = form.name.trim();
|
||||
if (!name || [...name].length > 128 || /[\u0000-\u001f\u007f-\u009f]/u.test(name)) {
|
||||
mutationError.value = "账户名称必须为不含控制字符的 1~128 个字符";
|
||||
return;
|
||||
}
|
||||
body.name = name;
|
||||
}
|
||||
if (["create", "rotate"].includes(form.action)) {
|
||||
const provider = providers.value.find((item) => item.id === (target?.provider || form.provider));
|
||||
if (!provider?.available || !Array.isArray(provider.credential_fields)) {
|
||||
mutationError.value = "请选择可用的 DNS 服务商";
|
||||
return;
|
||||
}
|
||||
body.credentials = {};
|
||||
for (const field of provider.credential_fields) {
|
||||
const value = String(form.credentials[field.name] || "").trim();
|
||||
if (field.required && !value) {
|
||||
mutationError.value = `请填写${field.label}`;
|
||||
return;
|
||||
}
|
||||
if (value) body.credentials[field.name] = value;
|
||||
}
|
||||
if (form.action === "create") Object.assign(body, { provider: provider.id, project_id: form.project_id });
|
||||
}
|
||||
if (form.action === "verify") {
|
||||
body.test_domain = form.test_domain.trim().toLowerCase();
|
||||
if (!body.test_domain || /[\s/:*]/u.test(body.test_domain)) {
|
||||
mutationError.value = "请填写不含协议、路径或通配符的测试域名";
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (form.action === "status") body.enabled = target.status !== "active";
|
||||
const suffix = { rename: "", rotate: "/credentials", verify: "/verify", status: "/status" };
|
||||
const path = "/api/v1/dns/accounts" + (form.action === "create" ? "" : `/${encodeURIComponent(target.id)}${suffix[form.action]}`);
|
||||
saving.value = true;
|
||||
notice.value = "";
|
||||
form.credentials = {};
|
||||
try {
|
||||
await requestDNS(path, {
|
||||
method: ["create", "verify"].includes(form.action) ? "POST" : "PUT",
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
if (!mounted) return;
|
||||
notice.value = ["create", "rotate"].includes(form.action)
|
||||
? "账户已保存,请使用有权管理的测试域名执行在线验证" : "账户操作已完成";
|
||||
} catch (reason) {
|
||||
if (!mounted) return;
|
||||
mutationError.value = reason.message;
|
||||
} finally {
|
||||
// 写请求不自动重放;成功或失败均清空输入并重新读取服务器状态。
|
||||
if (body.credentials) body.credentials = {};
|
||||
if (mounted) {
|
||||
clearEditor();
|
||||
await refresh({ internal: true });
|
||||
if (mounted) saving.value = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
mounted = false;
|
||||
clearEditor();
|
||||
});
|
||||
return {
|
||||
editor, saving, mutationError, notice, managedProjects, selectedProvider, editorTitle,
|
||||
canManage, openEditor, closeEditor, changeProvider, saveEditor,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
export async function requestDNS(path, options = {}) {
|
||||
let response;
|
||||
try {
|
||||
response = await fetch(path, {
|
||||
...options,
|
||||
credentials: "include",
|
||||
cache: "no-store",
|
||||
headers: options.body ? { "Content-Type": "application/json" } : {},
|
||||
});
|
||||
} catch (reason) {
|
||||
if (reason.name === "AbortError") throw reason;
|
||||
throw new Error("网络连接失败;操作结果可能尚未确认,请刷新列表后核对,勿重复提交");
|
||||
}
|
||||
if (!response.ok) {
|
||||
// 不展示任意服务端正文,避免代理错误或服务商响应带出敏感内容。
|
||||
const messages = {
|
||||
400: "参数无效,请检查账户名称、凭据和测试域名",
|
||||
401: "登录会话已过期,请重新登录",
|
||||
403: "当前账号没有操作权限,或目标账户已不可用",
|
||||
409: "账户已变更,请刷新后重新选择,不会自动重试此次操作",
|
||||
422: "DNS 在线验证失败,请检查凭据、测试域名和云端权限",
|
||||
429: "操作过于频繁,请稍后重试",
|
||||
};
|
||||
const error = new Error(messages[response.status] || "DNS 账户请求失败,请稍后刷新核对");
|
||||
error.status = response.status;
|
||||
throw error;
|
||||
}
|
||||
try {
|
||||
return await response.json();
|
||||
} catch {
|
||||
throw new Error("服务器响应格式不正确,请刷新核对操作结果");
|
||||
}
|
||||
}
|
||||
|
||||
export async function loadDNSProjects(signal) {
|
||||
const projects = [];
|
||||
const cursors = new Set();
|
||||
let after = "";
|
||||
while (true) {
|
||||
const query = new URLSearchParams({ page_size: "30", after });
|
||||
const result = await requestDNS(`/api/v1/projects?${query}`, { signal });
|
||||
if (!Array.isArray(result.items)) throw new Error("项目列表格式不正确,请刷新重试");
|
||||
projects.push(...result.items);
|
||||
if (!result.has_more) return projects;
|
||||
if (typeof result.next_cursor !== "string" || !result.next_cursor || cursors.has(result.next_cursor)) {
|
||||
throw new Error("项目分页游标无效,请刷新重试");
|
||||
}
|
||||
after = result.next_cursor;
|
||||
cursors.add(after);
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,9 @@
|
||||
.dns-accounts-panel {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
max-height: calc(100dvh - 130px);
|
||||
min-height: 0;
|
||||
box-sizing: border-box;
|
||||
padding: 24px;
|
||||
border: 1px solid #e2e8f0;
|
||||
border-radius: 20px;
|
||||
@@ -60,7 +65,8 @@ select:focus-visible,
|
||||
}
|
||||
|
||||
.dns-table-scroll {
|
||||
overflow-x: auto;
|
||||
overflow: auto;
|
||||
min-height: 0;
|
||||
}
|
||||
|
||||
.dns-accounts-table {
|
||||
@@ -72,12 +78,14 @@ select:focus-visible,
|
||||
|
||||
.dns-accounts-table th,
|
||||
.dns-accounts-table td {
|
||||
padding: 16px 12px;
|
||||
padding: 10px 12px;
|
||||
border-bottom: 1px solid #e8edf4;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.dns-accounts-table th {
|
||||
position: sticky;
|
||||
top: 0;
|
||||
color: #66758d;
|
||||
background: #f7f9fc;
|
||||
font-weight: 600;
|
||||
@@ -126,6 +134,32 @@ select:focus-visible,
|
||||
margin: 0 5px;
|
||||
}
|
||||
|
||||
.dns-row-actions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.dns-row-actions button {
|
||||
padding: 4px 7px;
|
||||
border: 1px solid #d5ddea;
|
||||
border-radius: 6px;
|
||||
color: #315aaa;
|
||||
background: #fff;
|
||||
white-space: nowrap;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.dns-notice {
|
||||
color: #216044;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.dns-pagination,
|
||||
.dns-accounts-heading {
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
@media (max-width: 760px) {
|
||||
.dns-accounts-panel {
|
||||
padding: 16px;
|
||||
|
||||
@@ -1,8 +1,12 @@
|
||||
import { computed, onBeforeUnmount, onMounted, ref } from "vue";
|
||||
import { loadDNSProjects, requestDNS } from "./DNSAccountRequest.js";
|
||||
import { useDNSAccountEditor } from "./DNSAccountEditor.js";
|
||||
|
||||
export function dnsVerificationLabel(item) {
|
||||
if (item.status === "disabled") return "已停用";
|
||||
if (item.credential_state === "unavailable") return "凭据不可读取";
|
||||
if (item.credential_state === "invalid") return "凭据配置不完整";
|
||||
if (item.verification_state === "failed") return "验证失败";
|
||||
return item.verification_state === "verified" ? "已验证" : "待验证";
|
||||
}
|
||||
|
||||
@@ -13,6 +17,8 @@ export function dnsProjectLabel(item) {
|
||||
|
||||
export function useDNSAccounts() {
|
||||
const accounts = ref([]);
|
||||
const projects = ref([]);
|
||||
const providers = ref([]);
|
||||
const loading = ref(false);
|
||||
const error = ref("");
|
||||
const pageSize = ref(10);
|
||||
@@ -21,31 +27,38 @@ export function useDNSAccounts() {
|
||||
const visibleAccounts = computed(() => accounts.value.slice((page.value - 1) * pageSize.value, page.value * pageSize.value));
|
||||
let requestVersion = 0;
|
||||
let controller;
|
||||
const actions = useDNSAccountEditor(projects, providers, loading, loadAccounts);
|
||||
|
||||
async function loadAccounts() {
|
||||
async function loadAccounts(options = {}) {
|
||||
if (actions.saving.value && options?.internal !== true) return;
|
||||
actions.closeEditor();
|
||||
const version = ++requestVersion;
|
||||
controller?.abort();
|
||||
controller = new AbortController();
|
||||
loading.value = true;
|
||||
error.value = "";
|
||||
accounts.value = [];
|
||||
projects.value = [];
|
||||
providers.value = [];
|
||||
page.value = 1;
|
||||
try {
|
||||
const response = await fetch("/api/v1/dns/accounts", {
|
||||
credentials: "include",
|
||||
cache: "no-store",
|
||||
signal: controller.signal,
|
||||
});
|
||||
if (response.status === 401) throw new Error("登录会话已过期,请重新登录");
|
||||
if (response.status === 403) throw new Error("当前账号没有查看 DNS 账户的权限");
|
||||
if (!response.ok) throw new Error("DNS 账户加载失败,请稍后重试");
|
||||
const data = await response.json();
|
||||
const signal = controller.signal;
|
||||
const [data, projectItems, catalog] = await Promise.all([
|
||||
requestDNS("/api/v1/dns/accounts", { signal }),
|
||||
loadDNSProjects(signal),
|
||||
requestDNS("/api/v1/dns/providers", { signal }),
|
||||
]);
|
||||
if (!Array.isArray(data.items) || !data.items.every((item) => item && typeof item.id === "string")) {
|
||||
throw new Error("DNS 账户响应格式不正确,请刷新重试");
|
||||
}
|
||||
if (version === requestVersion) accounts.value = data.items;
|
||||
if (!Array.isArray(catalog.items)) throw new Error("DNS 服务商目录格式不正确,请刷新重试");
|
||||
if (version === requestVersion) {
|
||||
accounts.value = data.items;
|
||||
projects.value = projectItems;
|
||||
providers.value = catalog.items.filter((item) => item.available === true);
|
||||
}
|
||||
} catch (reason) {
|
||||
if (version === requestVersion) error.value = reason.message || "DNS 账户加载失败,请稍后重试";
|
||||
if (version === requestVersion && reason.name !== "AbortError") error.value = reason.message || "DNS 账户加载失败,请稍后重试";
|
||||
} finally {
|
||||
if (version === requestVersion) loading.value = false;
|
||||
}
|
||||
@@ -61,5 +74,9 @@ export function useDNSAccounts() {
|
||||
controller?.abort();
|
||||
});
|
||||
|
||||
return { accounts, loading, error, pageSize, page, pageCount, visibleAccounts, loadAccounts, changePageSize };
|
||||
function projectLabel(item) {
|
||||
return projects.value.find((project) => project.id === item.project_id)?.name || dnsProjectLabel(item);
|
||||
}
|
||||
|
||||
return { ...actions, accounts, providers, loading, error, pageSize, page, pageCount, visibleAccounts, loadAccounts, changePageSize, projectLabel };
|
||||
}
|
||||
@@ -0,0 +1,268 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { deferred, mountComposable } from "../../test-support/mount.js";
|
||||
import { dnsVerificationLabel, useDNSAccounts } from "./DNSAccounts.js";
|
||||
import { loadDNSProjects, requestDNS } from "./DNSAccountRequest.js";
|
||||
|
||||
const account = {
|
||||
id: "account-a", name: "测试账户", project_id: "project-a", managed: true,
|
||||
provider: "cloudflare", status: "active", revision: 7, verification_state: "verified",
|
||||
};
|
||||
const provider = {
|
||||
id: "cloudflare", name: "Cloudflare", available: true,
|
||||
credential_fields: [{ name: "api_token", label: "访问令牌", required: true, secret: true }],
|
||||
};
|
||||
|
||||
async function setup(t, mutate = () => Response.json({}), options = {}) {
|
||||
const calls = [];
|
||||
const { state, unmount } = await mountComposable(t, useDNSAccounts, async (path, init = {}) => {
|
||||
calls.push({ path, ...init });
|
||||
if (init.method) return mutate(path, init);
|
||||
if (path.startsWith("/api/v1/projects?")) {
|
||||
return Response.json({ items: [{ id: "project-a", name: "项目甲", can_manage_dns: options.manage !== false }] });
|
||||
}
|
||||
if (path.endsWith("/providers")) return Response.json({ items: [provider] });
|
||||
return Response.json({ items: options.accounts || [account] });
|
||||
});
|
||||
return { state, calls, unmount };
|
||||
}
|
||||
|
||||
test("DNS 列表显示项目归属、分页及真实账户验证状态", async (t) => {
|
||||
const { state, calls } = await setup(t, undefined, { accounts: Array.from({ length: 31 }, (_, index) => ({ ...account, id: `a-${index}` })) });
|
||||
assert.equal(state.accounts.value.length, 31);
|
||||
assert.equal(state.visibleAccounts.value.length, 10);
|
||||
assert.equal(state.projectLabel(account), "项目甲");
|
||||
for (const size of [5, 10, 15, 30]) {
|
||||
state.page.value = 2;
|
||||
state.pageSize.value = size;
|
||||
state.changePageSize();
|
||||
assert.equal(state.page.value, 1);
|
||||
assert.equal(state.visibleAccounts.value.length, size);
|
||||
}
|
||||
assert.equal(dnsVerificationLabel({ ...account, status: "disabled" }), "已停用");
|
||||
assert.equal(dnsVerificationLabel({ ...account, verification_state: "failed" }), "验证失败");
|
||||
assert.equal(dnsVerificationLabel({ ...account, credential_state: "stored" }), "已验证");
|
||||
assert.ok(calls.every((item) => item.credentials === "include" && item.cache === "no-store"));
|
||||
});
|
||||
|
||||
test("DNS 新建只发送白名单字段并清空凭据", async (t) => {
|
||||
const { state, calls } = await setup(t);
|
||||
state.openEditor("create");
|
||||
Object.assign(state.editor.value, { name: " 新账户 ", owner_user_id: "forged", revision: 900 });
|
||||
state.editor.value.credentials = { api_token: "fixture-token", unknown: "must-not-send" };
|
||||
await state.saveEditor();
|
||||
const write = calls.find((item) => item.method);
|
||||
assert.equal(write.method, "POST");
|
||||
assert.equal(write.path, "/api/v1/dns/accounts");
|
||||
assert.deepEqual(JSON.parse(write.body), {
|
||||
name: "新账户", project_id: "project-a", provider: "cloudflare", credentials: { api_token: "fixture-token" },
|
||||
});
|
||||
assert.equal(state.editor.value, null);
|
||||
assert.match(state.notice.value, /在线验证/);
|
||||
});
|
||||
|
||||
for (const [action, suffix, body, method] of [
|
||||
["rename", "", { revision: 7, name: "新名称" }, "PUT"],
|
||||
["rotate", "/credentials", { revision: 7, credentials: { api_token: "replacement-token" } }, "PUT"],
|
||||
["status", "/status", { revision: 7, enabled: false }, "PUT"],
|
||||
["verify", "/verify", { revision: 7, test_domain: "example.test" }, "POST"],
|
||||
]) {
|
||||
test(`DNS ${action} 使用选中账户的固定身份与版本`, async (t) => {
|
||||
const { state, calls } = await setup(t);
|
||||
state.openEditor(action, account);
|
||||
Object.assign(state.editor.value, {
|
||||
id: "forged", revision: 999, name: "新名称", test_domain: " EXAMPLE.TEST ",
|
||||
credentials: { api_token: "replacement-token" },
|
||||
});
|
||||
await state.saveEditor();
|
||||
const write = calls.find((item) => item.method);
|
||||
assert.equal(write.path, `/api/v1/dns/accounts/account-a${suffix}`);
|
||||
assert.equal(write.method, method);
|
||||
assert.deepEqual(JSON.parse(write.body), body);
|
||||
});
|
||||
}
|
||||
|
||||
test("只读项目和历史配置不能发起账户写操作", async (t) => {
|
||||
const { state, calls } = await setup(t, undefined, { manage: false });
|
||||
for (const action of ["create", "rename", "rotate", "status", "verify"]) {
|
||||
state.openEditor(action, account);
|
||||
assert.equal(state.editor.value, null);
|
||||
}
|
||||
assert.equal(calls.filter((item) => item.method).length, 0);
|
||||
assert.equal(state.canManage({ ...account, managed: false }), false);
|
||||
});
|
||||
|
||||
test("停用账户不能验证,轮换和重新启用仍可用", async (t) => {
|
||||
const { state, calls } = await setup(t);
|
||||
const disabled = { ...account, status: "disabled" };
|
||||
state.openEditor("verify", disabled);
|
||||
assert.equal(state.editor.value, null);
|
||||
state.openEditor("status", disabled);
|
||||
await state.saveEditor();
|
||||
assert.equal(JSON.parse(calls.find((item) => item.method).body).enabled, true);
|
||||
});
|
||||
|
||||
test("切换服务商、取消和刷新清空未提交凭据", async (t) => {
|
||||
const { state } = await setup(t);
|
||||
state.openEditor("create");
|
||||
state.editor.value.credentials = { api_token: "discard-me" };
|
||||
state.changeProvider();
|
||||
assert.deepEqual(state.editor.value.credentials, {});
|
||||
const form = state.editor.value;
|
||||
form.credentials.api_token = "discard-me";
|
||||
state.closeEditor();
|
||||
assert.deepEqual(form.credentials, {});
|
||||
state.openEditor("rotate", account);
|
||||
const nextForm = state.editor.value;
|
||||
nextForm.credentials.api_token = "discard-me";
|
||||
await state.loadAccounts();
|
||||
assert.deepEqual(nextForm.credentials, {});
|
||||
assert.equal(state.editor.value, null);
|
||||
});
|
||||
|
||||
test("无效名称、缺失凭据和无效域名不发出写请求", async (t) => {
|
||||
const { state, calls } = await setup(t);
|
||||
state.openEditor("create");
|
||||
state.editor.value.name = "坏\u0000名称";
|
||||
await state.saveEditor();
|
||||
assert.match(state.mutationError.value, /名称/);
|
||||
state.editor.value.name = "有效名称";
|
||||
await state.saveEditor();
|
||||
assert.match(state.mutationError.value, /访问令牌/);
|
||||
state.openEditor("verify", account);
|
||||
state.editor.value.test_domain = "https://example.test/path";
|
||||
await state.saveEditor();
|
||||
assert.match(state.mutationError.value, /域名/);
|
||||
assert.equal(calls.filter((item) => item.method).length, 0);
|
||||
});
|
||||
|
||||
for (const status of [401, 403, 409, 422, 503]) {
|
||||
test(`DNS 写入 ${status} 清空输入、刷新状态且不自动重试或显示敏感响应`, async (t) => {
|
||||
const { state, calls } = await setup(t, () => Response.json({ error: "secret://sensitive" }, { status }));
|
||||
state.openEditor("rotate", account);
|
||||
state.editor.value.credentials.api_token = "fixture-token";
|
||||
await state.saveEditor();
|
||||
assert.equal(state.editor.value, null);
|
||||
assert.equal(state.saving.value, false);
|
||||
assert.ok(state.mutationError.value);
|
||||
assert.doesNotMatch(state.mutationError.value, /sensitive|fixture-token/);
|
||||
assert.equal(calls.filter((item) => item.method).length, 1);
|
||||
assert.equal(calls.filter((item) => item.path === "/api/v1/dns/accounts" && !item.method).length, 2);
|
||||
});
|
||||
}
|
||||
|
||||
test("DNS 写入中阻止双击、刷新、切换账户和关闭", async (t) => {
|
||||
const pending = deferred();
|
||||
const { state, calls } = await setup(t, () => pending.promise);
|
||||
state.openEditor("rotate", account);
|
||||
state.editor.value.credentials.api_token = "fixture-token";
|
||||
const request = state.saveEditor();
|
||||
assert.deepEqual(state.editor.value.credentials, {});
|
||||
const count = calls.length;
|
||||
await state.saveEditor();
|
||||
await state.loadAccounts();
|
||||
state.openEditor("rename", { ...account, id: "other" });
|
||||
state.closeEditor();
|
||||
assert.equal(calls.length, count);
|
||||
assert.equal(state.editor.value.action, "rotate");
|
||||
pending.resolve(Response.json({}));
|
||||
await request;
|
||||
assert.equal(state.editor.value, null);
|
||||
});
|
||||
|
||||
test("DNS 页面卸载后迟到的写响应不会重新加载或恢复凭据", async (t) => {
|
||||
const pending = deferred();
|
||||
const { state, calls, unmount } = await setup(t, () => pending.promise);
|
||||
state.openEditor("rotate", account);
|
||||
state.editor.value.credentials.api_token = "fixture-token";
|
||||
const request = state.saveEditor();
|
||||
const count = calls.length;
|
||||
unmount();
|
||||
pending.resolve(Response.json({}));
|
||||
await request;
|
||||
assert.equal(calls.length, count);
|
||||
assert.equal(state.editor.value, null);
|
||||
assert.equal(state.notice.value, "");
|
||||
});
|
||||
|
||||
test("DNS 项目选择遍历游标而非只保留第一页", async (t) => {
|
||||
let pages = 0;
|
||||
t.mock.method(globalThis, "fetch", async (path) => {
|
||||
pages += 1;
|
||||
return Response.json(path.includes("after=next")
|
||||
? { items: [{ id: "second" }], has_more: false }
|
||||
: { items: [{ id: "first" }], has_more: true, next_cursor: "next" });
|
||||
});
|
||||
assert.deepEqual((await loadDNSProjects()).map((item) => item.id), ["first", "second"]);
|
||||
assert.equal(pages, 2);
|
||||
});
|
||||
|
||||
test("DNS 项目列表拒绝重复游标避免循环", async (t) => {
|
||||
t.mock.method(globalThis, "fetch", async () => Response.json({ items: [], has_more: true, next_cursor: "repeat" }));
|
||||
await assert.rejects(loadDNSProjects(), /游标/);
|
||||
});
|
||||
|
||||
test("DNS 旧读取不能覆盖刷新后的权限和账户", async (t) => {
|
||||
const { state } = await setup(t);
|
||||
const pending = deferred();
|
||||
let reads = 0;
|
||||
t.mock.method(globalThis, "fetch", async (path) => {
|
||||
if (path === "/api/v1/dns/accounts" && reads++ === 0) return pending.promise;
|
||||
return Response.json({ items: [] });
|
||||
});
|
||||
const old = state.loadAccounts();
|
||||
await state.loadAccounts();
|
||||
pending.resolve(Response.json({ items: [account] }));
|
||||
await old;
|
||||
assert.deepEqual(state.accounts.value, []);
|
||||
assert.equal(state.managedProjects.value.length, 0);
|
||||
});
|
||||
|
||||
test("DNS 网络中断提示结果未确认而不重试写入", async (t) => {
|
||||
const { state, calls } = await setup(t, () => { throw new Error("sensitive-network-detail"); });
|
||||
state.openEditor("rename", account);
|
||||
await state.saveEditor();
|
||||
assert.match(state.mutationError.value, /未确认/);
|
||||
assert.doesNotMatch(state.mutationError.value, /sensitive/);
|
||||
assert.equal(calls.filter((item) => item.method).length, 1);
|
||||
});
|
||||
|
||||
test("DNS 非 JSON 成功响应也不能暴露原始服务端文本", async (t) => {
|
||||
t.mock.method(globalThis, "fetch", async () => new Response("sensitive upstream content"));
|
||||
await assert.rejects(requestDNS("/api/v1/dns/accounts"), (error) => {
|
||||
assert.match(error.message, /响应格式/);
|
||||
assert.doesNotMatch(error.message, /sensitive/);
|
||||
return true;
|
||||
});
|
||||
});
|
||||
|
||||
test("DNS 刷新失败立即移除旧账户和管理能力", async (t) => {
|
||||
const { state } = await setup(t);
|
||||
assert.equal(state.managedProjects.value.length, 1);
|
||||
t.mock.method(globalThis, "fetch", async () => Response.json({ error: "sensitive" }, { status: 403 }));
|
||||
await state.loadAccounts(null);
|
||||
assert.deepEqual(state.accounts.value, []);
|
||||
assert.deepEqual(state.managedProjects.value, []);
|
||||
state.openEditor("rename", account);
|
||||
assert.equal(state.editor.value, null);
|
||||
assert.match(state.error.value, /权限/);
|
||||
});
|
||||
|
||||
test("DNS 页面与原生对话框可编译,字段分栏且提示不占用常驻空间", async () => {
|
||||
const { readFile } = await import("node:fs/promises");
|
||||
const { parse, compileScript, compileTemplate } = await import("@vue/compiler-sfc");
|
||||
for (const file of ["DNSAccounts.vue", "DNSAccountDialog.vue"]) {
|
||||
const source = await readFile(new URL(file, import.meta.url), "utf8");
|
||||
const { descriptor, errors } = parse(source);
|
||||
assert.deepEqual(errors, []);
|
||||
assert.ok(compileScript(descriptor, { id: file }));
|
||||
assert.deepEqual(compileTemplate({ source: descriptor.template.content, filename: file, id: file }).errors, []);
|
||||
assert.doesNotMatch(source, /&#x[0-9a-f]+;/i);
|
||||
}
|
||||
const dialog = await readFile(new URL("DNSAccountDialog.vue", import.meta.url), "utf8");
|
||||
assert.match(dialog, /showModal\(\)/);
|
||||
assert.match(dialog, /aria-labelledby="dns-editor-title"/);
|
||||
assert.match(dialog, /@cancel.prevent/);
|
||||
assert.match(dialog, /field.secret \? 'password'/);
|
||||
assert.match(dialog, /title="仅填写你有权管理的域名/);
|
||||
});
|
||||
@@ -1,11 +1,14 @@
|
||||
<script setup>
|
||||
import { watch } from "vue";
|
||||
import { dnsProjectLabel, dnsVerificationLabel, useDNSAccounts } from "./DNSAccounts.js";
|
||||
import { dnsVerificationLabel, useDNSAccounts } from "./DNSAccounts.js";
|
||||
import DNSAccountDialog from "./DNSAccountDialog.vue";
|
||||
|
||||
const props = defineProps({ refreshKey: { type: Object, default: null } });
|
||||
const {
|
||||
accounts, loading, error, pageSize, page, pageCount,
|
||||
visibleAccounts, loadAccounts, changePageSize,
|
||||
editor, saving, mutationError, notice, managedProjects, selectedProvider, editorTitle,
|
||||
canManage, openEditor, closeEditor, changeProvider, saveEditor, providers, projectLabel,
|
||||
} = useDNSAccounts();
|
||||
|
||||
watch(() => props.refreshKey, loadAccounts);
|
||||
@@ -18,11 +21,16 @@ watch(() => props.refreshKey, loadAccounts);
|
||||
<h2>DNS 账户管理</h2>
|
||||
<span class="dns-accounts-count">{{ loading ? '正在加载' : error ? '加载失败' : `共 ${accounts.length} 个账号` }}</span>
|
||||
</div>
|
||||
<button class="dns-refresh" type="button" :disabled="loading" @click="loadAccounts">
|
||||
{{ loading ? '加载中…' : '刷新列表' }}
|
||||
</button>
|
||||
<div class="dns-page-actions">
|
||||
<button v-if="managedProjects.length" class="dns-refresh" type="button" :disabled="loading || saving" @click="openEditor('create')">新增账户</button>
|
||||
<button class="dns-refresh" type="button" :disabled="loading || saving" @click="loadAccounts">
|
||||
{{ loading ? '加载中…' : '刷新列表' }}
|
||||
</button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<p v-if="notice" class="dns-notice" role="status">{{ notice }}</p>
|
||||
<p v-if="mutationError && !editor" class="dns-error" role="alert">{{ mutationError }}</p>
|
||||
<p v-if="error" class="dns-error" role="alert">{{ error }}</p>
|
||||
<p v-else-if="loading" class="dns-empty" role="status">正在读取已配置的 DNS 账号…</p>
|
||||
<p v-else-if="accounts.length === 0" class="dns-empty">暂无可查看的已配置 DNS 账号</p>
|
||||
@@ -37,21 +45,31 @@ watch(() => props.refreshKey, loadAccounts);
|
||||
<th scope="col" title="仅展示脱敏后的公开账号标识,不展示密钥或令牌">账号标识</th>
|
||||
<th scope="col" title="归属来自已保存的用户记录;历史配置未记录归属时显示未分配">归属用户</th>
|
||||
<th scope="col" title="已验证表示保存配置时通过验证,不代表此刻云端权限仍然有效">验证状态</th>
|
||||
<th scope="col">操作</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr v-for="account in visibleAccounts" :key="account.id">
|
||||
<td>{{ account.name }}</td>
|
||||
<td>{{ account.provider_name }}</td>
|
||||
<td>{{ dnsProjectLabel(account) }}</td>
|
||||
<td :title="account.project_id">{{ projectLabel(account) }}</td>
|
||||
<td class="dns-identifier">{{ account.account_identifier }}</td>
|
||||
<td :class="{ 'dns-muted': account.owner_state !== 'assigned' }">{{ account.owner_username }}</td>
|
||||
<td>
|
||||
<span
|
||||
class="dns-status"
|
||||
:class="{ verified: account.credential_state === 'available' && account.verification_state === 'verified' }"
|
||||
:class="{ verified: account.status !== 'disabled' && ['stored', 'available'].includes(account.credential_state) && account.verification_state === 'verified' }"
|
||||
>{{ dnsVerificationLabel(account) }}</span>
|
||||
</td>
|
||||
<td>
|
||||
<div v-if="canManage(account)" class="dns-row-actions">
|
||||
<button type="button" :disabled="saving" @click="openEditor('rename', account)">改名</button>
|
||||
<button type="button" :disabled="saving || account.status !== 'active'" @click="openEditor('verify', account)">验证</button>
|
||||
<button type="button" :disabled="saving" title="保存新凭据并使旧验证状态失效" @click="openEditor('rotate', account)">轮换</button>
|
||||
<button type="button" :disabled="saving" @click="openEditor('status', account)">{{ account.status === 'active' ? '停用' : '启用' }}</button>
|
||||
</div>
|
||||
<span v-else class="dns-muted" :title="account.managed ? '当前项目只读,操作权限由服务器实时复核' : '历史系统账户尚未迁移,此处仅展示,不支持独立账户操作'">{{ account.managed ? '只读' : '历史配置' }}</span>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
@@ -71,6 +89,19 @@ watch(() => props.refreshKey, loadAccounts);
|
||||
</div>
|
||||
</footer>
|
||||
</template>
|
||||
<DNSAccountDialog
|
||||
v-if="editor"
|
||||
:editor="editor"
|
||||
:title="editorTitle"
|
||||
:projects="managedProjects"
|
||||
:providers="providers"
|
||||
:provider="selectedProvider"
|
||||
:saving="saving"
|
||||
:error="mutationError"
|
||||
@close="closeEditor"
|
||||
@save="saveEditor"
|
||||
@provider-change="changeProvider"
|
||||
/>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
|
||||
@@ -6,6 +6,7 @@ import "./DashboardLogout.test.js";
|
||||
import "./SettingsAccess.test.js";
|
||||
import "./DomainModal.test.js";
|
||||
import "./DomainForm.test.js";
|
||||
import "../DNSAccounts/DNSAccounts.test.js";
|
||||
import test from "node:test";
|
||||
import { nextTick, ref } from "vue";
|
||||
import { useDashboard } from "./Dashboard.js";
|
||||
|
||||
Reference in new issue
Block a user