Skip to content

armgit / dbx

Public Imported from GitHub
0

25 MB lightweight cross-platform database client for 100+ databases, including MySQL, PostgreSQL, SQLite, Redis, MongoDB, DuckDB, SQL Server, and Dameng. Built-in AI, MCP Server, CLI, desktop and Docker. | 轻量级跨平台数据库管理工具,支持 MySQL、PostgreSQL、SQLite、Redis、MongoDB、达梦等 100+ 数据库,提供桌面端、Docker、CLI、内置 AI 助手和 MCP。

feat(xugu): add visual user and privilege management

Eliasad221eeb8852
diff --git a/apps/desktop/src/components/admin/XuguUserPermissions.vue b/apps/desktop/src/components/admin/XuguUserPermissions.vue
new file mode 100644
index 0000000000..d039b297e2
--- /dev/null
+++ b/apps/desktop/src/components/admin/XuguUserPermissions.vue
@@ -0,0 +1,902 @@
+<script setup lang="ts">
+import { computed, onBeforeUnmount, onMounted, ref, watch } from "vue";
+import { useI18n } from "vue-i18n";
+import { AlertTriangle, KeyRound, Loader2, Plus, RefreshCw, ShieldCheck, Trash2, Unlock, UserRound, UsersRound } from "@lucide/vue";
+import { Badge } from "@/components/ui/badge";
+import { Button } from "@/components/ui/button";
+import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
+import { Input } from "@/components/ui/input";
+import { useToast } from "@/composables/useToast";
+import { useConnectionStore } from "@/stores/connectionStore";
+import type { ConnectionConfig, QueryResult } from "@/types/database";
+import * as api from "@/lib/backend/api";
+import { executeWithProductionSqlGuard } from "@/lib/database/productionExecutionGuard";
+import {
+ xuguAclAuthorityLabels,
+ parseXuguAclRows,
+ parseXuguMemberships,
+ parseXuguPrincipals,
+ xuguAclRowsFallbackSql,
+ xuguAclRowsSql,
+ xuguAclColumnTargetsSql,
+ xuguAlterLockSql,
+ xuguAlterAccountSql,
+ xuguAlterPasswordSql,
+ xuguCreatePrincipalSql,
+ xuguEnrichAclColumnTargets,
+ xuguDatabaseOptions,
+ xuguDropPrincipalSql,
+ xuguFallbackListRolesSql,
+ xuguFallbackListUsersSql,
+ xuguGrantSql,
+ xuguInheritedRoleIds,
+ xuguListRolesSql,
+ xuguListUsersSql,
+ xuguListSchemasSql,
+ xuguListObjectNamesSql,
+ xuguListColumnNamesSql,
+ xuguRevokeSql,
+ xuguRoleMembershipsFallbackSql,
+ xuguRoleMembershipsSql,
+ xuguPrivilegesForScope,
+ xuguPrincipalIsProtected,
+ XUGU_OBJECT_TYPES,
+ type XuguAclRow,
+ type XuguAdminAuthority,
+ type XuguPrincipal,
+ type XuguPrivilegeScope,
+} from "@/lib/database/xuguUserPermissions";
+
+const props = defineProps<{ connection: ConnectionConfig }>();
+const { t } = useI18n();
+const { toast } = useToast();
+const connectionStore = useConnectionStore();
+
+const users = ref<XuguPrincipal[]>([]);
+const roles = ref<XuguPrincipal[]>([]);
+const databaseNames = ref<string[]>([]);
+const selectedDatabase = ref(props.connection.database?.trim() ?? "");
+const databaseListLimited = ref(false);
+const databaseContextUnknown = ref(false);
+const schemas = ref<string[]>([]);
+const objectNames = ref<string[]>([]);
+const columnNames = ref<string[]>([]);
+const targetLookupIncomplete = ref(false);
+const targetLookupFailed = ref(false);
+const memberships = ref<Array<{ userId: string; roleId: string }>>([]);
+const aclRows = ref<XuguAclRow[]>([]);
+const kind = ref<"user" | "role">("user");
+const selectedId = ref("");
+const search = ref("");
+const loading = ref(false);
+const loadingAcl = ref(false);
+const mutating = ref(false);
+const loadError = ref("");
+const aclError = ref("");
+const dbaCatalogAvailable = ref(false);
+const aclCatalogAvailable = ref(false);
+const roleMembershipsAvailable = ref(false);
+const currentDatabaseIsSystem = ref(false);
+const createDialogOpen = ref(false);
+const passwordDialogOpen = ref(false);
+const accountDialogOpen = ref(false);
+
+const principalName = ref("");
+const principalPassword = ref("");
+const defaultRoleNames = ref<string[]>([]);
+const createValidUntil = ref("");
+const createLocked = ref(false);
+const createPasswordExpired = ref(false);
+const passwordToSet = ref("");
+const validUntilToSet = ref("");
+const expirePassword = ref(false);
+const grantScope = ref<XuguPrivilegeScope>("database");
+const objectType = ref("TABLE");
+const schemaName = ref("");
+const objectName = ref("");
+const columnName = ref("");
+const roleName = ref("");
+const adminAuthority = ref<XuguAdminAuthority>("DBA");
+const selectedPrivileges = ref<string[]>([]);
+const grantOption = ref(false);
+const revokeGrantOptionOnly = ref(false);
+const pendingSql = ref("");
+const pendingLabel = ref("");
+const pendingSystemWide = ref(false);
+const sqlDialogOpen = ref(false);
+let targetLookupTimer: ReturnType<typeof setTimeout> | undefined;
+let targetLookupRequestId = 0;
+let permissionsRequestId = 0;
+let principalsRequestId = 0;
+let databaseContextReady = false;
+let pauseDatabaseWatcher = false;
+
+const principals = computed(() => (kind.value === "user" ? users.value : roles.value));
+const selectedPrincipal = computed(() => principals.value.find((principal) => principal.id === selectedId.value));
+const selectedPrincipalProtected = computed(() => (selectedPrincipal.value ? xuguPrincipalIsProtected(selectedPrincipal.value) : true));
+const visiblePrincipals = computed(() => {
+ const query = search.value.trim().toLocaleLowerCase();
+ return query ? principals.value.filter((principal) => principal.name.toLocaleLowerCase().includes(query)) : principals.value;
+});
+const canMutate = computed(() => !props.connection.read_only && !!selectedDatabase.value && dbaCatalogAvailable.value && aclCatalogAvailable.value && roleMembershipsAvailable.value);
+const availablePrivileges = computed(() => xuguPrivilegesForScope(grantScope.value, objectType.value, currentDatabaseIsSystem.value));
+const selectedPrivilegeSet = computed(() => new Set(selectedPrivileges.value));
+const rolePrincipalMap = computed(() => new Map([...users.value, ...roles.value].map((principal) => [principal.id, principal])));
+const inheritedRoleIds = computed(() => (selectedPrincipal.value ? xuguInheritedRoleIds(selectedPrincipal.value.id, memberships.value) : []));
+const effectiveRoleNames = computed(() => inheritedRoleIds.value.map((id) => rolePrincipalMap.value.get(id)?.name ?? `#${id}`));
+const permissionRows = computed(() =>
+ aclRows.value.flatMap((row) => {
+ const names = xuguAclAuthorityLabels(row.authority, row.objectType, row.scope, t("xuguUserPermissions.unmappedAuthority"));
+ return names.map((name) => ({ ...row, name }));
+ }),
+);
+const previewSql = computed(() => pendingSql.value.replace(/(IDENTIFIED BY\s+)('(?:''|[^'])*')/i, "$1'••••••'"));
+const scopeOptions = computed(() => {
+ const options: Array<{ value: XuguPrivilegeScope; label: string }> = [
+ { value: "database", label: "xuguUserPermissions.scopeDatabase" },
+ { value: "schema", label: "xuguUserPermissions.scopeSchema" },
+ { value: "object", label: "xuguUserPermissions.scopeObject" },
+ { value: "column", label: "xuguUserPermissions.scopeColumn" },
+ { value: "role", label: "xuguUserPermissions.scopeRole" },
+ { value: "admin", label: "xuguUserPermissions.scopeAdmin" },
+ ];
+ if (currentDatabaseIsSystem.value) options.unshift({ value: "system", label: "xuguUserPermissions.scopeSystem" });
+ return options;
+});
+
+function resultError(result: QueryResult): Error | undefined {
+ if (!result.execution_error) return undefined;
+ return new Error(String(result.rows[0]?.[0] ?? "Query failed"));
+}
+
+function requireColumns(result: QueryResult, required: string[], catalogName: string) {
+ const columns = new Set(result.columns.map((column) => column.toLowerCase()));
+ const missing = required.filter((column) => !columns.has(column.toLowerCase()));
+ if (missing.length) throw new Error(`${catalogName} returned an unexpected shape (missing ${missing.join(", ")}).`);
+}
+
+async function query(sql: string, maxRows = 5000): Promise<QueryResult> {
+ const result = await api.executeQuery(props.connection.id, selectedDatabase.value, sql, undefined, undefined, { maxRows });
+ const error = resultError(result);
+ if (error) throw error;
+ return result;
+}
+
+async function queryEither(primary: string, fallback: string): Promise<{ result: QueryResult; privileged: boolean }> {
+ try {
+ return { result: await query(primary), privileged: true };
+ } catch (primaryError) {
+ try {
+ return { result: await query(fallback), privileged: false };
+ } catch {
+ throw primaryError;
+ }
+ }
+}
+
+async function ensureConnection() {
+ await connectionStore.ensureConnected(props.connection.id);
+}
+
+async function loadDatabaseContext() {
+ await ensureConnection();
+ let currentDatabase = selectedDatabase.value.trim() || props.connection.database?.trim() || "";
+ let names: string[] = [];
+ databaseListLimited.value = false;
+ try {
+ names = (await api.listDatabases(props.connection.id)).map((database) => database.name);
+ } catch {
+ databaseListLimited.value = true;
+ }
+ if (!currentDatabase) {
+ try {
+ const result = await api.executeQuery(props.connection.id, "", "SELECT DATABASE() AS DATABASE_NAME;");
+ const error = resultError(result);
+ if (error) throw error;
+ const index = result.columns.findIndex((column) => column.toLowerCase() === "database_name");
+ currentDatabase = index < 0 ? "" : String(result.rows[0]?.[index] ?? "").trim();
+ } catch {
+ // Keep the database unknown and disable mutations rather than guess which
+ // database-scoped user catalog an empty connection context will address.
+ }
+ }
+ const options = xuguDatabaseOptions(names, currentDatabase);
+ pauseDatabaseWatcher = true;
+ databaseNames.value = options;
+ selectedDatabase.value = currentDatabase;
+ databaseContextUnknown.value = !currentDatabase;
+ pauseDatabaseWatcher = false;
+ databaseContextReady = true;
+}
+
+async function loadPrincipals() {
+ const requestId = ++principalsRequestId;
+ loading.value = true;
+ loadError.value = "";
+ dbaCatalogAvailable.value = false;
+ aclCatalogAvailable.value = false;
+ roleMembershipsAvailable.value = false;
+ try {
+ await ensureConnection();
+ if (!databaseContextReady) await loadDatabaseContext();
+ if (requestId !== principalsRequestId) return;
+ currentDatabaseIsSystem.value = false;
+ try {
+ const databaseResult = await query("SELECT DATABASE() AS DATABASE_NAME;");
+ const databaseIndex = databaseResult.columns.findIndex((column) => column.toLowerCase() === "database_name");
+ currentDatabaseIsSystem.value =
+ databaseIndex >= 0 &&
+ String(databaseResult.rows[0]?.[databaseIndex] ?? "")
+ .trim()
+ .toUpperCase() === "SYSTEM";
+ } catch {
+ // Fail closed: system-wide database lifecycle grants stay unavailable
+ // when the current database cannot be identified.
+ }
+ if (!currentDatabaseIsSystem.value && grantScope.value === "system") grantScope.value = "database";
+ const [userResult, roleResult] = await Promise.all([queryEither(xuguListUsersSql(), xuguFallbackListUsersSql()), queryEither(xuguListRolesSql(), xuguFallbackListRolesSql())]);
+ if (requestId !== principalsRequestId) return;
+ requireColumns(userResult.result, ["USER_ID", "USER_NAME"], "User catalog");
+ requireColumns(roleResult.result, ["USER_ID", "USER_NAME"], "Role catalog");
+ users.value = parseXuguPrincipals(userResult.result, false);
+ roles.value = parseXuguPrincipals(roleResult.result, true);
+ dbaCatalogAvailable.value = userResult.privileged && roleResult.privileged;
+ try {
+ const schemaResult = await query(xuguListSchemasSql(dbaCatalogAvailable.value));
+ requireColumns(schemaResult, ["SCHEMA_NAME"], "Schema catalog");
+ const schemaIndex = schemaResult.columns.findIndex((column) => column.toLowerCase() === "schema_name");
+ schemas.value = schemaIndex < 0 ? [] : schemaResult.rows.map((row) => String(row[schemaIndex] ?? "")).filter(Boolean);
+ } catch {
+ schemas.value = [];
+ }
+ roleMembershipsAvailable.value = false;
+ try {
+ const result = await query(xuguRoleMembershipsSql());
+ requireColumns(result, ["USER_ID", "ROLE_ID"], "Role membership catalog");
+ memberships.value = parseXuguMemberships(result);
+ roleMembershipsAvailable.value = true;
+ } catch {
+ try {
+ const result = await query(xuguRoleMembershipsFallbackSql());
+ requireColumns(result, ["USER_ID", "ROLE_ID"], "Role membership catalog");
+ memberships.value = parseXuguMemberships(result);
+ roleMembershipsAvailable.value = false;
+ } catch {
+ memberships.value = [];
+ roleMembershipsAvailable.value = false;
+ }
+ }
+ const nextList = kind.value === "user" ? users.value : roles.value;
+ const nextSelectedId = nextList.some((principal) => principal.id === selectedId.value) ? selectedId.value : (nextList[0]?.id ?? "");
+ if (nextSelectedId === selectedId.value) {
+ if (selectedId.value) await loadPermissions();
+ } else {
+ selectedId.value = nextSelectedId;
+ }
+ } catch (error: any) {
+ users.value = [];
+ roles.value = [];
+ memberships.value = [];
+ aclRows.value = [];
+ loadError.value = error?.message || String(error);
+ } finally {
+ if (requestId === principalsRequestId) loading.value = false;
+ }
+}
+
+async function refreshPermissions() {
+ if (loading.value || mutating.value) return;
+ loading.value = true;
+ try {
+ await loadDatabaseContext();
+ await loadPrincipals();
+ } catch (error: any) {
+ loadError.value = error?.message || String(error);
+ } finally {
+ loading.value = false;
+ }
+}
+
+async function loadPermissions() {
+ const requestId = ++permissionsRequestId;
+ const principal = selectedPrincipal.value;
+ if (!principal) {
+ aclRows.value = [];
+ aclCatalogAvailable.value = false;
+ loadingAcl.value = false;
+ aclError.value = "";
+ return;
+ }
+ loadingAcl.value = true;
+ aclCatalogAvailable.value = false;
+ aclError.value = "";
+ try {
+ const ids = [principal.id, ...xuguInheritedRoleIds(principal.id, memberships.value)];
+ let useDbaCatalog = true;
+ try {
+ const result = await query(xuguAclRowsSql(ids));
+ if (requestId !== permissionsRequestId) return;
+ requireColumns(result, ["GRANTOR_ID", "GRANTEE_ID", "OBJECT_ID", "OBJECT_TYPE", "AUTHORITY", "REGRANT", "TARGET_NAME"], "ACL catalog");
+ aclRows.value = parseXuguAclRows(result, [...users.value, ...roles.value], principal.id, currentDatabaseIsSystem.value);
+ aclCatalogAvailable.value = true;
+ } catch (primaryError: any) {
+ try {
+ useDbaCatalog = false;
+ const result = await query(xuguAclRowsFallbackSql(ids));
+ if (requestId !== permissionsRequestId) return;
+ requireColumns(result, ["GRANTOR_ID", "GRANTEE_ID", "OBJECT_ID", "OBJECT_TYPE", "AUTHORITY", "REGRANT", "TARGET_NAME"], "ACL catalog");
+ aclRows.value = parseXuguAclRows(result, [...users.value, ...roles.value], principal.id, currentDatabaseIsSystem.value);
+ aclCatalogAvailable.value = false;
+ } catch {
+ if (requestId !== permissionsRequestId) return;
+ throw primaryError;
+ }
+ }
+ if (aclRows.value.some((row) => row.scope === "column")) {
+ try {
+ const result = await query(xuguAclColumnTargetsSql(ids, useDbaCatalog));
+ if (requestId !== permissionsRequestId) return;
+ requireColumns(result, ["GRANTEE_ID", "OBJECT_ID", "OBJECT_TYPE", "TARGET_NAME"], "Column ACL target catalog");
+ aclRows.value = xuguEnrichAclColumnTargets(aclRows.value, result);
+ } catch {
+ // Keep the base ACL rows visible with their explicit object-ID fallback
+ // when a server version or restricted catalog cannot resolve columns.
+ }
+ }
+ } catch (error: any) {
+ if (requestId !== permissionsRequestId) return;
+ aclRows.value = [];
+ aclError.value = error?.message || String(error);
+ } finally {
+ if (requestId === permissionsRequestId) loadingAcl.value = false;
+ }
+}
+
+async function loadTargetOptions(requestId: number) {
+ objectNames.value = [];
+ columnNames.value = [];
+ targetLookupIncomplete.value = false;
+ targetLookupFailed.value = false;
+ if (!schemaName.value.trim()) return;
+ try {
+ if (grantScope.value === "object") {
+ const result = await query(xuguListObjectNamesSql(schemaName.value, objectType.value, dbaCatalogAvailable.value), 1000);
+ if (requestId !== targetLookupRequestId) return;
+ const nameIndex = result.columns.findIndex((column) => column.toLowerCase() === "obj_name");
+ objectNames.value = nameIndex < 0 ? [] : result.rows.map((row) => String(row[nameIndex] ?? "")).filter(Boolean);
+ targetLookupIncomplete.value = result.truncated === true || result.rows.length >= 1000;
+ } else if (grantScope.value === "column" && objectName.value.trim() && ["TABLE", "VIEW"].includes(objectType.value)) {
+ const result = await query(xuguListColumnNamesSql(schemaName.value, objectName.value, objectType.value, dbaCatalogAvailable.value), 1000);
+ if (requestId !== targetLookupRequestId) return;
+ const nameIndex = result.columns.findIndex((column) => column.toLowerCase() === "col_name");
+ columnNames.value = nameIndex < 0 ? [] : result.rows.map((row) => String(row[nameIndex] ?? "")).filter(Boolean);
+ targetLookupIncomplete.value = result.truncated === true || result.rows.length >= 1000;
+ }
+ } catch {
+ if (requestId === targetLookupRequestId) targetLookupFailed.value = true;
+ }
+}
+
+function scheduleTargetLookup() {
+ const requestId = ++targetLookupRequestId;
+ if (targetLookupTimer) clearTimeout(targetLookupTimer);
+ objectNames.value = [];
+ columnNames.value = [];
+ targetLookupIncomplete.value = false;
+ targetLookupFailed.value = false;
+ targetLookupTimer = setTimeout(() => void loadTargetOptions(requestId), 250);
+}
+
+function selectKind(nextKind: "user" | "role") {
+ const previousId = selectedId.value;
+ kind.value = nextKind;
+ selectedId.value = (nextKind === "user" ? users.value : roles.value)[0]?.id ?? "";
+ if (selectedId.value && selectedId.value === previousId) {
+ aclCatalogAvailable.value = false;
+ void loadPermissions();
+ }
+}
+
+function togglePrivilege(privilege: string) {
+ if (grantScope.value === "column") {
+ selectedPrivileges.value = selectedPrivilegeSet.value.has(privilege) ? [] : [privilege];
+ return;
+ }
+ if (grantScope.value === "object" && privilege === "ALL PRIVILEGES") {
+ selectedPrivileges.value = selectedPrivilegeSet.value.has(privilege) ? [] : [privilege];
+ return;
+ }
+ const next = new Set(selectedPrivileges.value);
+ if (grantScope.value === "object") next.delete("ALL PRIVILEGES");
+ if (next.has(privilege)) next.delete(privilege);
+ else next.add(privilege);
+ selectedPrivileges.value = [...next];
+}
+
+function preview(sql: string, label: string, systemWide = false) {
+ pendingSql.value = sql;
+ pendingLabel.value = label;
+ pendingSystemWide.value = systemWide;
+ sqlDialogOpen.value = true;
+}
+
+function buildPermissionSql(revoke: boolean): string {
+ const principal = selectedPrincipal.value;
+ if (!principal) throw new Error("Select a user or role first.");
+ const input = {
+ principal,
+ scope: grantScope.value,
+ privileges: selectedPrivileges.value,
+ schema: schemaName.value,
+ objectType: objectType.value,
+ object: objectName.value,
+ column: columnName.value,
+ role: roleName.value,
+ adminAuthority: adminAuthority.value,
+ grantOption: grantOption.value,
+ revokeGrantOptionOnly: revokeGrantOptionOnly.value,
+ systemDatabase: currentDatabaseIsSystem.value,
+ };
+ return revoke ? xuguRevokeSql(input) : xuguGrantSql(input);
+}
+
+function previewPermission(revoke: boolean) {
+ if (!canMutate.value || selectedPrincipalProtected.value) return;
+ try {
+ preview(buildPermissionSql(revoke), revoke ? t("xuguUserPermissions.revoke") : t("xuguUserPermissions.grant"), grantScope.value === "system");
+ } catch (error: any) {
+ toast(error?.message || String(error), 5000);
+ }
+}
+
+function createPrincipal(): boolean {
+ try {
+ const isRole = kind.value === "role";
+ const sql = xuguCreatePrincipalSql(principalName.value, isRole, principalPassword.value, {
+ defaultRoles: defaultRoleNames.value,
+ validUntil: createValidUntil.value,
+ locked: createLocked.value,
+ passwordExpired: createPasswordExpired.value,
+ });
+ preview(sql, t(isRole ? "xuguUserPermissions.createRole" : "xuguUserPermissions.createUser"));
+ principalPassword.value = "";
+ return true;
+ } catch (error: any) {
+ toast(error?.message || String(error), 5000);
+ return false;
+ }
+}
+
+function changePassword(): boolean {
+ const principal = selectedPrincipal.value;
+ if (!principal) return false;
+ try {
+ preview(xuguAlterPasswordSql(principal, passwordToSet.value), t("xuguUserPermissions.changePassword"));
+ passwordToSet.value = "";
+ return true;
+ } catch (error: any) {
+ toast(error?.message || String(error), 5000);
+ return false;
+ }
+}
+
+function previewNewPrincipal() {
+ if (createPrincipal()) createDialogOpen.value = false;
+}
+
+function previewPasswordChange() {
+ if (changePassword()) passwordDialogOpen.value = false;
+}
+
+function previewAccountChanges(): boolean {
+ const principal = selectedPrincipal.value;
+ if (!principal) return false;
+ try {
+ preview(xuguAlterAccountSql(principal, { validUntil: validUntilToSet.value, passwordExpired: expirePassword.value }), t("xuguUserPermissions.accountSettings"));
+ accountDialogOpen.value = false;
+ return true;
+ } catch (error: any) {
+ toast(error?.message || String(error), 5000);
+ return false;
+ }
+}
+
+function openAccountSettings() {
+ validUntilToSet.value = "";
+ expirePassword.value = false;
+ accountDialogOpen.value = true;
+}
+
+async function applyPendingSql() {
+ if (!pendingSql.value || !canMutate.value) return;
+ mutating.value = true;
+ try {
+ const result = await executeWithProductionSqlGuard({
+ connection: props.connection,
+ database: selectedDatabase.value,
+ sql: pendingSql.value,
+ source: t("production.sourceAdmin"),
+ execute: async () => {
+ const results = await api.executeMulti(props.connection.id, selectedDatabase.value, pendingSql.value, undefined, undefined, { maxRows: 1000 });
+ const failed = results.find((item) => item.execution_error === true);
+ if (failed) throw new Error(String(failed.rows[0]?.[0] ?? t("xuguUserPermissions.operationFailed")));
+ return true;
+ },
+ });
+ if (!result) return;
+ sqlDialogOpen.value = false;
+ principalName.value = "";
+ principalPassword.value = "";
+ defaultRoleNames.value = [];
+ createValidUntil.value = "";
+ createLocked.value = false;
+ createPasswordExpired.value = false;
+ passwordToSet.value = "";
+ validUntilToSet.value = "";
+ expirePassword.value = false;
+ toast(t("xuguUserPermissions.operationSuccess"), 2500);
+ await loadPrincipals();
+ } catch (error: any) {
+ toast(t("xuguUserPermissions.operationFailedWithMessage", { message: error?.message || String(error) }), 6000);
+ } finally {
+ mutating.value = false;
+ }
+}
+
+function lockPrincipal(locked: boolean) {
+ const principal = selectedPrincipal.value;
+ if (!principal) return;
+ try {
+ preview(xuguAlterLockSql(principal, locked), t(locked ? "xuguUserPermissions.lock" : "xuguUserPermissions.unlock"));
+ } catch (error: any) {
+ toast(error?.message || String(error), 5000);
+ }
+}
+
+function dropPrincipal() {
+ const principal = selectedPrincipal.value;
+ if (!principal) return;
+ try {
+ preview(xuguDropPrincipalSql(principal), t(principal.isRole ? "xuguUserPermissions.dropRole" : "xuguUserPermissions.dropUser"));
+ } catch (error: any) {
+ toast(error?.message || String(error), 5000);
+ }
+}
+
+watch(selectedId, () => {
+ aclCatalogAvailable.value = false;
+ void loadPermissions();
+});
+watch(
+ selectedDatabase,
+ (database, previousDatabase) => {
+ if (!databaseContextReady || pauseDatabaseWatcher || database === previousDatabase) return;
+ databaseContextUnknown.value = !database;
+ users.value = [];
+ roles.value = [];
+ memberships.value = [];
+ aclRows.value = [];
+ selectedId.value = "";
+ currentDatabaseIsSystem.value = false;
+ void loadPrincipals();
+ },
+ { flush: "sync" },
+);
+watch(sqlDialogOpen, (open) => {
+ if (!open) {
+ pendingSql.value = "";
+ pendingLabel.value = "";
+ pendingSystemWide.value = false;
+ principalPassword.value = "";
+ passwordToSet.value = "";
+ }
+});
+watch(grantScope, () => {
+ selectedPrivileges.value = [];
+ grantOption.value = false;
+ revokeGrantOptionOnly.value = false;
+});
+watch(objectType, () => {
+ selectedPrivileges.value = [];
+});
+watch([grantScope, schemaName, objectType, objectName], scheduleTargetLookup);
+onMounted(() => void loadPrincipals());
+onBeforeUnmount(() => {
+ targetLookupRequestId += 1;
+ if (targetLookupTimer) clearTimeout(targetLookupTimer);
+});
+</script>
+
+<template>
+ <div class="flex h-full min-h-0 flex-col gap-3 p-4">
+ <header class="flex flex-wrap items-center justify-between gap-3">
+ <div class="flex items-center gap-2">
+ <ShieldCheck class="size-5 text-primary" />
+ <h1 class="text-lg font-semibold">{{ t("xuguUserPermissions.title") }}</h1>
+ <Badge variant="outline">XuguDB</Badge>
+ </div>
+ <div class="flex items-center gap-2">
+ <Badge v-if="connection.read_only" variant="secondary">{{ t("xuguUserPermissions.readOnly") }}</Badge>
+ <label v-if="databaseNames.length" class="flex items-center gap-2 text-xs text-muted-foreground">
+ {{ t("xuguUserPermissions.databaseContext") }}
+ <select v-model="selectedDatabase" class="h-8 max-w-56 rounded-md border bg-background px-2 text-sm text-foreground" :disabled="loading || mutating || sqlDialogOpen">
+ <option v-if="databaseContextUnknown" value="" disabled>{{ t("xuguUserPermissions.chooseDatabase") }}</option>
+ <option v-for="database in databaseNames" :key="database" :value="database">{{ database }}</option>
+ </select>
+ </label>
+ <Button variant="outline" size="sm" :disabled="loading || mutating" @click="refreshPermissions">
+ <Loader2 v-if="loading" class="mr-2 size-4 animate-spin" />
+ <RefreshCw v-else class="mr-2 size-4" />{{ t("xuguUserPermissions.refresh") }}
+ </Button>
+ <Button
+ size="sm"
+ :disabled="!canMutate"
+ @click="
+ principalName = '';
+ principalPassword = '';
+ defaultRoleNames = [];
+ createValidUntil = '';
+ createLocked = false;
+ createPasswordExpired = false;
+ sqlDialogOpen = false;
+ createDialogOpen = true;
+ "
+ >
+ <Plus class="mr-2 size-4" />{{ t("xuguUserPermissions.newPrincipal") }}
+ </Button>
+ </div>
+ </header>
+
+ <div v-if="loadError" class="rounded-md border border-destructive/40 bg-destructive/5 p-3 text-sm text-destructive">{{ loadError }}</div>
+ <div v-else-if="databaseContextUnknown" class="rounded-md border border-amber-500/40 bg-amber-500/5 p-3 text-sm text-amber-800 dark:text-amber-200">{{ t("xuguUserPermissions.databaseContextUnknown") }}</div>
+ <div v-else-if="databaseListLimited" class="rounded-md border border-amber-500/40 bg-amber-500/5 p-3 text-sm text-amber-800 dark:text-amber-200">{{ t("xuguUserPermissions.databaseListLimited") }}</div>
+ <div v-else-if="!dbaCatalogAvailable" class="flex items-start gap-2 rounded-md border border-amber-500/40 bg-amber-500/5 p-3 text-sm">
+ <AlertTriangle class="mt-0.5 size-4 shrink-0 text-amber-600" />
+ <span>{{ t("xuguUserPermissions.limitedCatalog") }}</span>
+ </div>
+
+ <div class="grid min-h-0 flex-1 grid-cols-[minmax(15rem,22rem)_minmax(0,1fr)] gap-3">
+ <aside class="flex min-h-0 flex-col overflow-hidden rounded-lg border bg-card">
+ <div class="flex gap-1 border-b p-2">
+ <Button class="flex-1" size="sm" :variant="kind === 'user' ? 'secondary' : 'ghost'" @click="selectKind('user')"
+ ><UserRound class="mr-2 size-4" />{{ t("xuguUserPermissions.users") }} <span class="ml-1 text-muted-foreground">{{ users.length }}</span></Button
+ >
+ <Button class="flex-1" size="sm" :variant="kind === 'role' ? 'secondary' : 'ghost'" @click="selectKind('role')"
+ ><UsersRound class="mr-2 size-4" />{{ t("xuguUserPermissions.roles") }} <span class="ml-1 text-muted-foreground">{{ roles.length }}</span></Button
+ >
+ </div>
+ <div class="border-b p-2"><Input v-model="search" :placeholder="t('xuguUserPermissions.search')" /></div>
+ <div class="min-h-0 flex-1 overflow-auto p-1">
+ <button v-for="principal in visiblePrincipals" :key="principal.id" class="flex w-full items-center justify-between rounded-md px-3 py-2 text-left text-sm hover:bg-muted" :class="selectedId === principal.id ? 'bg-muted font-medium' : ''" @click="selectedId = principal.id">
+ <span class="flex min-w-0 items-center gap-2"
+ ><UserRound v-if="!principal.isRole" class="size-4 shrink-0 text-muted-foreground" /><UsersRound v-else class="size-4 shrink-0 text-muted-foreground" /><span class="truncate">{{ principal.name }}</span></span
+ >
+ <span class="flex gap-1"
+ ><Badge v-if="principal.isSystem" variant="outline" class="px-1.5 py-0 text-[10px]">{{ t("xuguUserPermissions.system") }}</Badge
+ ><Badge v-else-if="!principal.isRole && principal.locked" variant="destructive" class="px-1.5 py-0 text-[10px]">{{ t("xuguUserPermissions.locked") }}</Badge></span
+ >
+ </button>
+ <div v-if="!loading && visiblePrincipals.length === 0" class="p-4 text-sm text-muted-foreground">{{ t("xuguUserPermissions.empty") }}</div>
+ </div>
+ </aside>
+
+ <main class="flex min-h-0 flex-col gap-3 overflow-auto">
+ <section v-if="selectedPrincipal" class="rounded-lg border bg-card p-4">
+ <div class="flex flex-wrap items-start justify-between gap-3">
+ <div class="min-w-0">
+ <div class="flex flex-wrap items-center gap-2">
+ <h2 class="text-base font-semibold">{{ selectedPrincipal.name }}</h2>
+ <Badge variant="outline">{{ selectedPrincipal.isRole ? t("xuguUserPermissions.role") : t("xuguUserPermissions.user") }}</Badge
+ ><Badge v-if="selectedPrincipal.isSystem" variant="secondary">{{ t("xuguUserPermissions.systemPrincipal") }}</Badge
+ ><Badge v-else-if="!selectedPrincipal.isRole" :variant="selectedPrincipal.locked ? 'destructive' : 'outline'">{{ selectedPrincipal.locked ? t("xuguUserPermissions.locked") : t("xuguUserPermissions.active") }}</Badge
+ ><Badge v-if="selectedPrincipal.expired" variant="destructive">{{ t("xuguUserPermissions.expired") }}</Badge>
+ </div>
+ <p v-if="selectedPrincipal.validUntil" class="mt-1 text-xs text-muted-foreground">{{ t("xuguUserPermissions.validUntil", { value: selectedPrincipal.validUntil }) }}</p>
+ <p v-if="effectiveRoleNames.length" class="mt-2 text-xs text-muted-foreground">{{ t("xuguUserPermissions.inheritedRoles", { roles: effectiveRoleNames.join(", ") }) }}</p>
+ </div>
+ <div class="flex flex-wrap gap-2">
+ <Button
+ v-if="!selectedPrincipal.isRole"
+ size="sm"
+ variant="outline"
+ :disabled="!canMutate || selectedPrincipalProtected"
+ @click="
+ passwordToSet = '';
+ passwordDialogOpen = true;
+ "
+ ><KeyRound class="mr-1.5 size-4" />{{ t("xuguUserPermissions.changePassword") }}</Button
+ >
+ <Button v-if="!selectedPrincipal.isRole" size="sm" variant="outline" :disabled="!canMutate || selectedPrincipalProtected" @click="openAccountSettings">{{ t("xuguUserPermissions.accountSettings") }}</Button>
+ <Button v-if="!selectedPrincipal.isRole" size="sm" variant="outline" :disabled="!canMutate || selectedPrincipalProtected" @click="lockPrincipal(!selectedPrincipal.locked)"
+ ><Unlock class="mr-1.5 size-4" />{{ selectedPrincipal.locked ? t("xuguUserPermissions.unlock") : t("xuguUserPermissions.lock") }}</Button
+ >
+ <Button size="sm" variant="destructive" :disabled="!canMutate || selectedPrincipalProtected" @click="dropPrincipal"><Trash2 class="mr-1.5 size-4" />{{ t(selectedPrincipal.isRole ? "xuguUserPermissions.dropRole" : "xuguUserPermissions.dropUser") }}</Button>
+ </div>
+ </div>
+ <p v-if="!canMutate" class="mt-3 text-xs text-muted-foreground">{{ connection.read_only ? t("xuguUserPermissions.readOnlyHint") : t("xuguUserPermissions.managementRequiresDba") }}</p>
+ </section>
+
+ <section class="rounded-lg border bg-card">
+ <div class="flex items-center justify-between border-b px-4 py-3">
+ <div>
+ <h2 class="font-medium">{{ t("xuguUserPermissions.grantsTitle") }}</h2>
+ <p class="mt-0.5 text-xs text-muted-foreground">{{ t("xuguUserPermissions.grantsHint") }}</p>
+ </div>
+ <Badge variant="outline">{{ permissionRows.length }}</Badge>
+ </div>
+ <div v-if="aclError" class="p-4 text-sm text-destructive">{{ aclError }}</div>
+ <div v-else-if="loadingAcl" class="flex items-center gap-2 p-4 text-sm text-muted-foreground"><Loader2 class="size-4 animate-spin" />{{ t("xuguUserPermissions.loading") }}</div>
+ <div v-else-if="!aclCatalogAvailable" class="border-b px-4 py-2 text-xs text-amber-700 dark:text-amber-300">{{ t("xuguUserPermissions.limitedAcl") }}</div>
+ <div v-else-if="permissionRows.length === 0" class="p-4 text-sm text-muted-foreground">{{ t("xuguUserPermissions.noGrants") }}</div>
+ <div v-else class="max-h-72 overflow-auto">
+ <table class="w-full text-left text-sm">
+ <thead class="sticky top-0 bg-muted/80 text-xs text-muted-foreground">
+ <tr>
+ <th class="px-4 py-2">{{ t("xuguUserPermissions.privilege") }}</th>
+ <th class="px-4 py-2">{{ t("xuguUserPermissions.scope") }}</th>
+ <th class="px-4 py-2">{{ t("xuguUserPermissions.target") }}</th>
+ <th class="px-4 py-2">{{ t("xuguUserPermissions.source") }}</th>
+ <th class="px-4 py-2">{{ t("xuguUserPermissions.grantable") }}</th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr v-for="(row, index) in permissionRows" :key="`${row.granteeId}:${row.objectId}:${row.objectType}:${row.name}:${index}`" class="border-t">
+ <td class="px-4 py-2 font-medium">{{ row.name }}</td>
+ <td class="px-4 py-2 text-muted-foreground">{{ t(`xuguUserPermissions.scope${row.scope.charAt(0).toUpperCase()}${row.scope.slice(1)}`) }}</td>
+ <td class="px-4 py-2 font-mono text-xs">{{ row.target }}</td>
+ <td class="px-4 py-2">{{ row.inheritedFrom ? t("xuguUserPermissions.viaRole", { role: row.inheritedFrom }) : t("xuguUserPermissions.direct") }}</td>
+ <td class="px-4 py-2">{{ row.regrant ? t("xuguUserPermissions.yes") : t("xuguUserPermissions.no") }}</td>
+ </tr>
+ </tbody>
+ </table>
+ </div>
+ </section>
+
+ <section class="rounded-lg border bg-card p-4">
+ <div class="mb-3">
+ <h2 class="font-medium">{{ t("xuguUserPermissions.editorTitle") }}</h2>
+ <p class="mt-0.5 text-xs text-muted-foreground">{{ t("xuguUserPermissions.editorHint") }}</p>
+ </div>
+ <div class="grid gap-3 sm:grid-cols-2 xl:grid-cols-3">
+ <label class="space-y-1 text-xs text-muted-foreground"
+ >{{ t("xuguUserPermissions.scope")
+ }}<select v-model="grantScope" class="h-9 w-full rounded-md border bg-background px-2 text-sm text-foreground">
+ <option v-for="option in scopeOptions" :key="option.value" :value="option.value">{{ t(option.label) }}</option>
+ </select></label
+ >
+ <label v-if="grantScope === 'schema' || grantScope === 'object' || grantScope === 'column'" class="space-y-1 text-xs text-muted-foreground"
+ >{{ t("xuguUserPermissions.schema") }}<Input v-model="schemaName" list="xugu-permission-schemas" /><datalist id="xugu-permission-schemas"><option v-for="schema in schemas" :key="schema" :value="schema" /></datalist
+ ></label>
+ <label v-if="grantScope === 'object' || grantScope === 'column'" class="space-y-1 text-xs text-muted-foreground"
+ >{{ t("xuguUserPermissions.objectType")
+ }}<select v-model="objectType" class="h-9 w-full rounded-md border bg-background px-2 text-sm text-foreground">
+ <template v-if="grantScope === 'column'"
+ ><option value="TABLE">{{ t("xuguUserPermissions.tableColumn") }}</option>
+ <option value="VIEW">{{ t("xuguUserPermissions.viewColumn") }}</option></template
+ ><template v-else
+ ><option v-for="item in XUGU_OBJECT_TYPES" :key="item.sql" :value="item.sql">{{ item.label }}</option></template
+ >
+ </select></label
+ >
+ <label v-if="grantScope === 'object' || grantScope === 'column'" class="space-y-1 text-xs text-muted-foreground"
+ >{{ t("xuguUserPermissions.object") }}<Input v-model="objectName" list="xugu-permission-objects" /><datalist id="xugu-permission-objects"><option v-for="name in objectNames" :key="name" :value="name" /></datalist
+ ></label>
+ <label v-if="grantScope === 'column'" class="space-y-1 text-xs text-muted-foreground"
+ >{{ t("xuguUserPermissions.column") }}<Input v-model="columnName" list="xugu-permission-columns" /><datalist id="xugu-permission-columns"><option v-for="name in columnNames" :key="name" :value="name" /></datalist
+ ></label>
+ <label v-if="grantScope === 'role'" class="space-y-1 text-xs text-muted-foreground"
+ >{{ t("xuguUserPermissions.roleToGrant") }}<Input v-model="roleName" list="xugu-permission-roles" /><datalist id="xugu-permission-roles"><option v-for="role in roles" :key="role.id" :value="role.name" /></datalist
+ ></label>
+ <label v-if="grantScope === 'admin'" class="space-y-1 text-xs text-muted-foreground"
+ >{{ t("xuguUserPermissions.adminAuthority")
+ }}<select v-model="adminAuthority" class="h-9 w-full rounded-md border bg-background px-2 text-sm text-foreground">
+ <option value="DBA">DBA</option>
+ <option value="AUDITOR">AUDITOR</option>
+ <option value="SSO">SSO</option>
+ </select></label
+ >
+ </div>
+ <p v-if="targetLookupFailed" class="mt-2 text-xs text-muted-foreground">{{ t("xuguUserPermissions.targetLookupFailed") }}</p>
+ <p v-else-if="targetLookupIncomplete" class="mt-2 text-xs text-muted-foreground">{{ t("xuguUserPermissions.targetLookupIncomplete") }}</p>
+ <p v-if="grantScope === 'system'" class="mt-2 text-xs text-muted-foreground">{{ t("xuguUserPermissions.systemScopeHint") }}</p>
+ <div v-if="availablePrivileges.length" class="mt-3 grid gap-2 sm:grid-cols-2 xl:grid-cols-3">
+ <label v-for="privilege in availablePrivileges" :key="privilege.name" class="flex items-center gap-2 rounded-md border px-3 py-2 text-sm"><input type="checkbox" :checked="selectedPrivilegeSet.has(privilege.name)" @change="togglePrivilege(privilege.name)" />{{ privilege.name }}</label>
+ </div>
+ <div class="mt-3 flex flex-wrap items-center justify-between gap-3">
+ <div v-if="grantScope === 'object'" class="flex flex-wrap gap-4">
+ <label class="flex items-center gap-2 text-sm"><input v-model="grantOption" type="checkbox" />{{ t("xuguUserPermissions.grantOption") }}</label>
+ <label class="flex items-center gap-2 text-sm"><input v-model="revokeGrantOptionOnly" type="checkbox" />{{ t("xuguUserPermissions.revokeGrantOptionOnly") }}</label>
+ </div>
+ <div v-else-if="grantScope === 'column'" class="text-xs text-muted-foreground">
+ {{ t("xuguUserPermissions.columnGrantOptionUnsupported") }}
+ </div>
+ <span v-else class="text-xs text-muted-foreground">{{ t("xuguUserPermissions.grantOptionScope") }}</span>
+ <div class="ml-auto flex gap-2">
+ <Button variant="outline" :disabled="!canMutate || !selectedPrincipal || selectedPrincipalProtected" @click="previewPermission(true)">{{ t("xuguUserPermissions.revoke") }}</Button
+ ><Button :disabled="!canMutate || !selectedPrincipal || selectedPrincipalProtected" @click="previewPermission(false)">{{ t("xuguUserPermissions.grant") }}</Button>
+ </div>
+ </div>
+ </section>
+ </main>
+ </div>
+
+ <Dialog v-model:open="createDialogOpen">
+ <DialogContent>
+ <DialogHeader
+ ><DialogTitle>{{ t("xuguUserPermissions.newPrincipal") }}</DialogTitle></DialogHeader
+ >
+ <div class="space-y-3">
+ <div class="flex gap-2">
+ <Button size="sm" :variant="kind === 'user' ? 'secondary' : 'outline'" @click="kind = 'user'">{{ t("xuguUserPermissions.createUser") }}</Button
+ ><Button size="sm" :variant="kind === 'role' ? 'secondary' : 'outline'" @click="kind = 'role'">{{ t("xuguUserPermissions.createRole") }}</Button>
+ </div>
+ <label class="block space-y-1 text-sm">{{ t("xuguUserPermissions.name") }}<Input v-model="principalName" autocomplete="off" /></label>
+ <label v-if="kind === 'user'" class="block space-y-1 text-sm">{{ t("xuguUserPermissions.initialPassword") }}<Input v-model="principalPassword" type="password" autocomplete="new-password" /></label>
+ <template v-if="kind === 'user'">
+ <label class="block space-y-1 text-sm"
+ >{{ t("xuguUserPermissions.defaultRoles") }}
+ <select v-model="defaultRoleNames" multiple size="4" class="w-full rounded-md border bg-background px-2 py-1 text-sm text-foreground">
+ <option v-for="role in roles" :key="role.id" :value="role.name">{{ role.name }}</option>
+ </select>
+ </label>
+ <label class="block space-y-1 text-sm">{{ t("xuguUserPermissions.validUntil") }}<Input v-model="createValidUntil" type="datetime-local" step="1" /></label>
+ <label class="flex items-center gap-2 text-sm"><input v-model="createLocked" type="checkbox" />{{ t("xuguUserPermissions.createLocked") }}</label>
+ <label class="flex items-center gap-2 text-sm"><input v-model="createPasswordExpired" type="checkbox" />{{ t("xuguUserPermissions.createPasswordExpired") }}</label>
+ <p class="text-xs text-muted-foreground">{{ t("xuguUserPermissions.accountCreateHint") }}</p>
+ </template>
+ </div>
+ <DialogFooter
+ ><Button variant="outline" @click="createDialogOpen = false">{{ t("common.cancel") }}</Button
+ ><Button :disabled="!principalName.trim() || (kind === 'user' && !principalPassword)" @click="previewNewPrincipal">{{ t("xuguUserPermissions.preview") }}</Button></DialogFooter
+ >
+ </DialogContent>
+ </Dialog>
+
+ <Dialog v-model:open="accountDialogOpen">
+ <DialogContent>
+ <DialogHeader
+ ><DialogTitle>{{ t("xuguUserPermissions.accountSettings") }}</DialogTitle></DialogHeader
+ >
+ <div class="space-y-3">
+ <label class="block space-y-1 text-sm">{{ t("xuguUserPermissions.setValidUntil") }}<Input v-model="validUntilToSet" type="datetime-local" step="1" /></label>
+ <label v-if="!selectedPrincipal?.expired" class="flex items-center gap-2 text-sm"><input v-model="expirePassword" type="checkbox" />{{ t("xuguUserPermissions.markPasswordExpired") }}</label>
+ <p v-else class="text-xs text-muted-foreground">{{ t("xuguUserPermissions.passwordAlreadyExpiredHint") }}</p>
+ <p class="text-xs text-muted-foreground">{{ t("xuguUserPermissions.accountSettingsHint") }}</p>
+ </div>
+ <DialogFooter>
+ <Button variant="outline" @click="accountDialogOpen = false">{{ t("common.cancel") }}</Button>
+ <Button :disabled="!validUntilToSet && !expirePassword" @click="previewAccountChanges">{{ t("xuguUserPermissions.preview") }}</Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+
+ <Dialog v-model:open="passwordDialogOpen">
+ <DialogContent>
+ <DialogHeader
+ ><DialogTitle>{{ t("xuguUserPermissions.changePassword") }}</DialogTitle></DialogHeader
+ >
+ <Input v-model="passwordToSet" type="password" autocomplete="new-password" :placeholder="t('xuguUserPermissions.newPassword')" />
+ <DialogFooter
+ ><Button variant="outline" @click="passwordDialogOpen = false">{{ t("common.cancel") }}</Button
+ ><Button :disabled="!passwordToSet" @click="previewPasswordChange">{{ t("xuguUserPermissions.preview") }}</Button></DialogFooter
+ >
+ </DialogContent>
+ </Dialog>
+
+ <Dialog v-model:open="sqlDialogOpen">
+ <DialogContent class="sm:max-w-2xl">
+ <DialogHeader
+ ><DialogTitle>{{ t("xuguUserPermissions.review", { action: pendingLabel }) }}</DialogTitle></DialogHeader
+ >
+ <div class="rounded-md border bg-muted/40 p-3">
+ <pre class="max-h-72 overflow-auto whitespace-pre-wrap break-all font-mono text-xs">{{ previewSql }}</pre>
+ </div>
+ <p class="text-xs text-muted-foreground">{{ t(pendingSystemWide ? "xuguUserPermissions.systemWide" : "xuguUserPermissions.currentDatabaseOnly") }}</p>
+ <DialogFooter
+ ><Button variant="outline" :disabled="mutating" @click="sqlDialogOpen = false">{{ t("common.cancel") }}</Button
+ ><Button :disabled="mutating || !canMutate" @click="applyPendingSql"><Loader2 v-if="mutating" class="mr-2 size-4 animate-spin" />{{ t("xuguUserPermissions.execute") }}</Button></DialogFooter
+ >
+ </DialogContent>
+ </Dialog>
+ </div>
+</template>
diff --git a/apps/desktop/src/components/admin/__tests__/XuguUserPermissions.spec.ts b/apps/desktop/src/components/admin/__tests__/XuguUserPermissions.spec.ts
new file mode 100644
index 0000000000..37e72181f5
--- /dev/null
+++ b/apps/desktop/src/components/admin/__tests__/XuguUserPermissions.spec.ts
@@ -0,0 +1,316 @@
+// @vitest-environment happy-dom
+
+import { createApp, nextTick, type App } from "vue";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ ensureConnected: vi.fn(),
+ executeQuery: vi.fn(),
+ executeMulti: vi.fn(),
+ listDatabases: vi.fn(),
+ toast: vi.fn(),
+ guard: vi.fn(async ({ execute }: { execute: () => Promise<unknown> }) => execute()),
+}));
+
+vi.mock("vue-i18n", () => ({ useI18n: () => ({ t: (key: string) => key }) }));
+vi.mock("@lucide/vue", async () => {
+ const { defineComponent, h } = await import("vue");
+ const icon = defineComponent({ setup: () => () => h("i") });
+ return { AlertTriangle: icon, KeyRound: icon, Loader2: icon, Plus: icon, RefreshCw: icon, ShieldCheck: icon, Trash2: icon, Unlock: icon, UserRound: icon, UsersRound: icon };
+});
+vi.mock("@/components/ui/badge", async () => {
+ const { defineComponent, h } = await import("vue");
+ return {
+ Badge: defineComponent({
+ inheritAttrs: false,
+ setup:
+ (_, { attrs, slots }) =>
+ () =>
+ h("span", attrs, slots.default?.()),
+ }),
+ };
+});
+vi.mock("@/components/ui/button", async () => {
+ const { defineComponent, h } = await import("vue");
+ return {
+ Button: defineComponent({
+ inheritAttrs: false,
+ setup:
+ (_, { attrs, slots }) =>
+ () =>
+ h("button", attrs, slots.default?.()),
+ }),
+ };
+});
+vi.mock("@/components/ui/input", async () => {
+ const { defineComponent, h } = await import("vue");
+ return {
+ Input: defineComponent({
+ inheritAttrs: false,
+ props: { modelValue: { type: [String, Number], default: "" } },
+ emits: ["update:modelValue"],
+ setup(props, { attrs, emit }) {
+ return () => h("input", { ...attrs, value: props.modelValue, onInput: (event: Event) => emit("update:modelValue", (event.target as HTMLInputElement).value) });
+ },
+ }),
+ };
+});
+vi.mock("@/components/ui/dialog", async () => {
+ const { defineComponent, h } = await import("vue");
+ const passthrough = (tag: string) =>
+ defineComponent({
+ inheritAttrs: false,
+ setup:
+ (_, { attrs, slots }) =>
+ () =>
+ h(tag, attrs, slots.default?.()),
+ });
+ return {
+ Dialog: defineComponent({
+ props: { open: Boolean },
+ setup:
+ (props, { slots }) =>
+ () =>
+ props.open ? h("div", { "data-dialog": "" }, slots.default?.()) : null,
+ }),
+ DialogContent: passthrough("section"),
+ DialogFooter: passthrough("footer"),
+ DialogHeader: passthrough("header"),
+ DialogTitle: passthrough("h2"),
+ };
+});
+vi.mock("@/composables/useToast", () => ({ useToast: () => ({ toast: mocks.toast }) }));
+vi.mock("@/stores/connectionStore", () => ({ useConnectionStore: () => ({ ensureConnected: mocks.ensureConnected }) }));
+vi.mock("@/lib/backend/api", () => ({ executeQuery: mocks.executeQuery, executeMulti: mocks.executeMulti, listDatabases: mocks.listDatabases }));
+vi.mock("@/lib/database/productionExecutionGuard", () => ({
+ executeWithProductionSqlGuard: mocks.guard,
+}));
+
+import XuguUserPermissions from "@/components/admin/XuguUserPermissions.vue";
+
+let app: App<Element> | undefined;
+let root: HTMLDivElement | undefined;
+
+function queryResult(columns: string[], rows: unknown[][] = []) {
+ return { columns, rows, affected_rows: 0, execution_time_ms: 0 };
+}
+
+function configureCompleteCatalogs() {
+ mocks.executeQuery.mockImplementation(async (_connectionId: string, database: string, sql: string) => {
+ if (database !== "SYSTEM") throw new Error(`Unexpected database context: ${database}`);
+ if (sql.includes("SELECT DATABASE()")) return queryResult(["DATABASE_NAME"], [["SYSTEM"]]);
+ if (sql.includes("FROM DBA_USERS")) return queryResult(["USER_ID", "USER_NAME", "LOCKED", "EXPIRED", "IS_SYS", "UNTIL_TIME", "ALIAS"], [[101, "APP_READER", false, false, false, null, null]]);
+ if (sql.includes("FROM DBA_ROLES")) return queryResult(["USER_ID", "USER_NAME", "IS_SYS"], [[201, "APP_READ_ROLE", false]]);
+ if (sql.includes("FROM DBA_SCHEMAS")) return queryResult(["SCHEMA_ID", "SCHEMA_NAME"], [[1, "APP_SCHEMA"]]);
+ if (sql.includes("FROM DBA_ROLE_MEMBERS")) return queryResult(["USER_ID", "ROLE_ID"], []);
+ if (sql.includes("FROM DBA_ACLS")) return queryResult(["GRANTOR_ID", "GRANTEE_ID", "OBJECT_ID", "OBJECT_TYPE", "AUTHORITY", "REGRANT", "SCOPE", "TARGET_NAME"], []);
+ throw new Error(`Unexpected catalog request: ${sql}`);
+ });
+}
+
+async function mountPage(readOnly = false) {
+ root = document.createElement("div");
+ document.body.append(root);
+ app = createApp(XuguUserPermissions, {
+ connection: { id: "xugu-connection", name: "Xugu test", db_type: "xugu", database: "SYSTEM", read_only: readOnly } as never,
+ });
+ app.mount(root);
+ await vi.waitFor(() => expect(mocks.executeQuery).toHaveBeenCalled());
+ await vi.waitFor(() => expect(root?.textContent).toContain("APP_READER"));
+ await nextTick();
+ return root;
+}
+
+function buttonByText(container: HTMLElement, text: string): HTMLButtonElement {
+ const found = Array.from(container.querySelectorAll("button")).find((candidate) => candidate.textContent?.trim().includes(text));
+ if (!found) throw new Error(`Could not find button: ${text}`);
+ return found as HTMLButtonElement;
+}
+
+beforeEach(() => {
+ mocks.ensureConnected.mockReset().mockResolvedValue(undefined);
+ mocks.executeQuery.mockReset();
+ mocks.executeMulti.mockReset().mockResolvedValue([queryResult([])]);
+ mocks.listDatabases.mockReset().mockResolvedValue([{ name: "SYSTEM" }, { name: "APP_DB" }]);
+ mocks.toast.mockReset();
+ mocks.guard.mockClear();
+ root = undefined;
+ app = undefined;
+});
+
+afterEach(() => {
+ app?.unmount();
+ root?.remove();
+ app = undefined;
+ root = undefined;
+ document.body.innerHTML = "";
+});
+
+describe("XuguUserPermissions", () => {
+ it("keeps catalog reads in the confirmed database and shows SQL for review without executing it", async () => {
+ configureCompleteCatalogs();
+ const container = await mountPage();
+
+ expect(mocks.ensureConnected).toHaveBeenCalledWith("xugu-connection");
+ expect(mocks.executeQuery.mock.calls.every(([, database]) => database === "SYSTEM")).toBe(true);
+ expect(container.textContent).toContain("xuguUserPermissions.scopeSystem");
+
+ const privilegeCheckbox = container.querySelector('input[type="checkbox"]') as HTMLInputElement | null;
+ expect(privilegeCheckbox).not.toBeNull();
+ privilegeCheckbox!.click();
+ await nextTick();
+ buttonByText(container, "xuguUserPermissions.grant").click();
+ await nextTick();
+
+ expect(container.querySelector("[data-dialog]")?.textContent).toContain("GRANT");
+ expect(mocks.executeMulti).not.toHaveBeenCalled();
+
+ buttonByText(container, "xuguUserPermissions.execute").click();
+ await vi.waitFor(() => expect(mocks.executeMulti).toHaveBeenCalledTimes(1));
+ expect(mocks.guard).toHaveBeenCalledWith(expect.objectContaining({ database: "SYSTEM", connection: expect.objectContaining({ db_type: "xugu" }) }));
+ expect(mocks.executeMulti.mock.calls[0]?.[2]).toContain("GRANT");
+ });
+
+ it("does not expose management actions on read-only connections", async () => {
+ configureCompleteCatalogs();
+ const container = await mountPage(true);
+
+ expect(buttonByText(container, "xuguUserPermissions.newPrincipal").disabled).toBe(true);
+ expect(buttonByText(container, "xuguUserPermissions.grant").disabled).toBe(true);
+ expect(buttonByText(container, "xuguUserPermissions.revoke").disabled).toBe(true);
+ expect(mocks.executeMulti).not.toHaveBeenCalled();
+ });
+
+ it("keeps account creation confirmation database-local even after selecting an instance-wide grant scope", async () => {
+ configureCompleteCatalogs();
+ const container = await mountPage();
+ await vi.waitFor(() => expect(buttonByText(container, "xuguUserPermissions.newPrincipal").disabled).toBe(false));
+
+ const systemScope = Array.from(container.querySelectorAll("select")).find((select) => Array.from(select.options).some((option) => option.value === "system"));
+ expect(systemScope).toBeDefined();
+ systemScope!.value = "system";
+ systemScope!.dispatchEvent(new Event("change", { bubbles: true }));
+ await nextTick();
+
+ buttonByText(container, "xuguUserPermissions.newPrincipal").click();
+ await nextTick();
+ buttonByText(container, "xuguUserPermissions.createRole").click();
+ await nextTick();
+ const nameInput = Array.from(container.querySelectorAll("label"))
+ .find((label) => label.textContent?.includes("xuguUserPermissions.name"))
+ ?.querySelector("input");
+ expect(nameInput).toBeDefined();
+ nameInput!.value = "APP_TEST_ROLE";
+ nameInput!.dispatchEvent(new Event("input", { bubbles: true }));
+ await nextTick();
+
+ buttonByText(container, "xuguUserPermissions.preview").click();
+ await nextTick();
+ const dialogText = container.querySelector("[data-dialog]")?.textContent ?? "";
+ expect(dialogText).toContain("xuguUserPermissions.currentDatabaseOnly");
+ expect(dialogText).not.toContain("xuguUserPermissions.systemWide");
+ expect(mocks.executeMulti).not.toHaveBeenCalled();
+ });
+
+ it("previews user creation with default roles and account lifecycle settings before execution", async () => {
+ configureCompleteCatalogs();
+ const container = await mountPage();
+ buttonByText(container, "xuguUserPermissions.newPrincipal").click();
+ await nextTick();
+
+ const inputForLabel = (key: string) => {
+ const label = Array.from(container.querySelectorAll("label")).find((candidate) => candidate.textContent?.includes(key));
+ const input = label?.querySelector("input");
+ if (!input) throw new Error(`Could not find input for ${key}`);
+ return input;
+ };
+ const setInput = (key: string, value: string) => {
+ const input = inputForLabel(key);
+ input.value = value;
+ input.dispatchEvent(new Event("input", { bubbles: true }));
+ };
+ setInput("xuguUserPermissions.name", "APP_NEW_USER");
+ setInput("xuguUserPermissions.initialPassword", "Secret_123!");
+ setInput("xuguUserPermissions.validUntil", "2035-06-07T08:09");
+
+ const rolesLabel = Array.from(container.querySelectorAll("label")).find((candidate) => candidate.textContent?.includes("xuguUserPermissions.defaultRoles"));
+ const roleSelect = rolesLabel?.querySelector("select");
+ expect(roleSelect?.multiple).toBe(true);
+ const roleOption = Array.from(roleSelect?.options ?? []).find((option) => option.value === "APP_READ_ROLE");
+ expect(roleOption).toBeDefined();
+ roleOption!.selected = true;
+ roleSelect!.dispatchEvent(new Event("change", { bubbles: true }));
+
+ for (const key of ["xuguUserPermissions.createLocked", "xuguUserPermissions.createPasswordExpired"]) {
+ const input = inputForLabel(key);
+ input.checked = true;
+ input.dispatchEvent(new Event("change", { bubbles: true }));
+ }
+ await nextTick();
+ buttonByText(container, "xuguUserPermissions.preview").click();
+ await nextTick();
+
+ const preview = container.querySelector("pre")?.textContent ?? "";
+ expect(preview).toContain('DEFAULT ROLE "APP_READ_ROLE"');
+ expect(preview).toContain("VALID UNTIL '2035-06-07 08:09'");
+ expect(preview).toContain("ACCOUNT LOCK");
+ expect(preview).toContain("PASSWORD EXPIRE");
+ expect(preview).not.toContain("Secret_123!");
+ expect(mocks.executeMulti).not.toHaveBeenCalled();
+ });
+
+ it("previews account expiration changes and exposes table-level trigger privileges", async () => {
+ configureCompleteCatalogs();
+ const container = await mountPage();
+ const objectScope = Array.from(container.querySelectorAll("select")).find((select) => Array.from(select.options).some((option) => option.value === "object"));
+ objectScope!.value = "object";
+ objectScope!.dispatchEvent(new Event("change", { bubbles: true }));
+ await nextTick();
+ const objectType = Array.from(container.querySelectorAll("select")).find((select) => Array.from(select.options).some((option) => option.value === "TABLE"));
+ expect(objectType).toBeDefined();
+ expect(Array.from(objectType!.options).some((option) => option.value === "TRIGGER")).toBe(false);
+ expect(Array.from(container.querySelectorAll("label")).some((label) => label.textContent?.trim() === "TRIGGER")).toBe(true);
+
+ buttonByText(container, "xuguUserPermissions.accountSettings").click();
+ await nextTick();
+ const validUntilLabel = Array.from(container.querySelectorAll("label")).find((candidate) => candidate.textContent?.includes("xuguUserPermissions.setValidUntil"));
+ const validUntil = validUntilLabel?.querySelector("input");
+ expect(validUntil).toBeDefined();
+ validUntil!.value = "2035-06-07T08:09";
+ validUntil!.dispatchEvent(new Event("input", { bubbles: true }));
+ const expiredLabel = Array.from(container.querySelectorAll("label")).find((candidate) => candidate.textContent?.includes("xuguUserPermissions.markPasswordExpired"));
+ const expired = expiredLabel?.querySelector("input");
+ expect(expired).toBeDefined();
+ expired!.checked = true;
+ expired!.dispatchEvent(new Event("change", { bubbles: true }));
+ await nextTick();
+ buttonByText(container, "xuguUserPermissions.preview").click();
+ await nextTick();
+
+ const preview = container.querySelector("pre")?.textContent ?? "";
+ expect(preview).toContain("VALID UNTIL '2035-06-07 08:09'");
+ expect(preview).toContain("PASSWORD EXPIRE");
+ expect(mocks.executeMulti).not.toHaveBeenCalled();
+ });
+
+ it("fails closed when only limited visibility catalogs can be read", async () => {
+ mocks.executeQuery.mockImplementation(async (_connectionId: string, database: string, sql: string) => {
+ if (database !== "SYSTEM") throw new Error(`Unexpected database context: ${database}`);
+ if (sql.includes("SELECT DATABASE()")) return queryResult(["DATABASE_NAME"], [["SYSTEM"]]);
+ if (sql.includes("FROM DBA_USERS") || sql.includes("FROM DBA_ROLES") || sql.includes("FROM DBA_ROLE_MEMBERS") || sql.includes("FROM DBA_ACLS")) {
+ return { ...queryResult([], []), execution_error: true, rows: [["insufficient privilege"]] };
+ }
+ if (sql.includes("FROM ALL_USERS")) return queryResult(["USER_ID", "USER_NAME", "LOCKED", "EXPIRED", "IS_SYS", "UNTIL_TIME", "ALIAS"], [[101, "APP_READER", false, false, false, null, null]]);
+ if (sql.includes("FROM ALL_ROLE_MEMBERS")) return queryResult(["USER_ID", "ROLE_ID"], []);
+ if (sql.includes("FROM ALL_SCHEMAS")) return queryResult(["SCHEMA_ID", "SCHEMA_NAME"], []);
+ if (sql.includes("FROM ALL_ACLS")) return queryResult(["GRANTOR_ID", "GRANTEE_ID", "OBJECT_ID", "OBJECT_TYPE", "AUTHORITY", "REGRANT", "SCOPE", "TARGET_NAME"], []);
+ throw new Error(`Unexpected catalog request: ${sql}`);
+ });
+ const container = await mountPage();
+
+ expect(container.textContent).toContain("xuguUserPermissions.limitedCatalog");
+ expect(buttonByText(container, "xuguUserPermissions.newPrincipal").disabled).toBe(true);
+ expect(buttonByText(container, "xuguUserPermissions.grant").disabled).toBe(true);
+ expect(mocks.executeMulti).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/desktop/src/components/layout/ContentArea.vue b/apps/desktop/src/components/layout/ContentArea.vue
index 8ead1395d9..e2f4e5082f 100644
--- a/apps/desktop/src/components/layout/ContentArea.vue
+++ b/apps/desktop/src/components/layout/ContentArea.vue
@@ -123,6 +123,7 @@ const DatabaseBrowser = defineAsyncComponent(() => import("@/components/objects/
const ObjectBrowser = defineAsyncComponent(() => import("@/components/objects/ObjectBrowser.vue"));
const TableStructureEditor = defineAsyncComponent(() => import("@/components/structure/TableStructureEditor.vue"));
const DatabaseUserAdmin = defineAsyncComponent(() => import("@/components/admin/DatabaseUserAdmin.vue"));
+const XuguUserPermissions = defineAsyncComponent(() => import("@/components/admin/XuguUserPermissions.vue"));
const ProcessListPanel = defineAsyncComponent(() => import("@/components/admin/ProcessListPanel.vue"));
const SqlServerActivityTracePanel = defineAsyncComponent(() => import("@/components/admin/SqlServerActivityTracePanel.vue"));
const MySqlDashboard = defineAsyncComponent(() => import("@/components/admin/MySqlDashboard.vue"));
@@ -3084,6 +3085,10 @@ defineExpose({
<DatabaseUserAdmin :key="activeTab.id" :connection="activeConnection" />
</template>
+ <template v-else-if="activeTab.mode === 'xugu-users' && activeConnection">
+ <XuguUserPermissions :key="activeTab.id" :connection="activeConnection" />
+ </template>
+
<template v-else-if="activeTab.mode === 'processlist' && activeConnection">
<ProcessListPanel :key="activeTab.id" :connection="activeConnection" />
</template>
diff --git a/apps/desktop/src/components/sidebar/SidebarTreeRuntimeHost.vue b/apps/desktop/src/components/sidebar/SidebarTreeRuntimeHost.vue
index 0226dc8c7e..6356c51e1c 100644
--- a/apps/desktop/src/components/sidebar/SidebarTreeRuntimeHost.vue
+++ b/apps/desktop/src/components/sidebar/SidebarTreeRuntimeHost.vue
@@ -1036,6 +1036,9 @@ async function toggle(requestId = beginNavigationRequest()) {
} else if (node.type === "user-admin" && node.connectionId) {
await connectionStore.ensureConnected(node.connectionId);
queryStore.openUserAdmin(node.connectionId);
+ } else if (node.type === "xugu-user-admin" && node.connectionId) {
+ await connectionStore.ensureConnected(node.connectionId);
+ queryStore.openXuguUserAdmin(node.connectionId);
} else if (node.type === "dameng-users" && node.connectionId) {
await connectionStore.ensureConnected(node.connectionId);
queryStore.openDamengUsers(node.connectionId);
@@ -1844,6 +1847,18 @@ async function openUserAdmin() {
}
}
+async function openXuguUserPermissions() {
+ const node = activeNode.value;
+ if (!node.connectionId) return;
+ try {
+ await connectionStore.ensureConnected(node.connectionId);
+ connectionStore.activeConnectionId = node.connectionId;
+ queryStore.openXuguUserAdmin(node.connectionId);
+ } catch (e: any) {
+ toast(t("connection.connectFailed", { message: translateBackendError(t, e?.message || String(e)) }), 5000);
+ }
+}
+
async function openProcessList() {
const node = activeNode.value;
if (!node.connectionId) return;
@@ -6060,6 +6075,11 @@ function buildSpecialSidebarMenu(context: SidebarMenuFactoryContext): boolean {
return true;
}
+ if (node.type === "xugu-user-admin") {
+ items.push({ label: t("contextMenu.openXuguUserPermissions"), action: openXuguUserPermissions, icon: ShieldCheck });
+ return true;
+ }
+
if (node.type === "dameng-job-admin") {
items.push({ label: t("contextMenu.openDamengJobAdmin"), action: openDamengJobAdmin, icon: CalendarClock });
return true;
diff --git a/apps/desktop/src/components/sidebar/TreeItem.vue b/apps/desktop/src/components/sidebar/TreeItem.vue
index c70af7029a..99c0c75655 100644
--- a/apps/desktop/src/components/sidebar/TreeItem.vue
+++ b/apps/desktop/src/components/sidebar/TreeItem.vue
@@ -309,6 +309,8 @@ function getIconInfo(node: TreeNode): { icon: any; colorClass: string } | null {
return { icon: TableProperties, colorClass: "text-primary" };
case "user-admin":
return { icon: UsersRound, colorClass: "text-primary" };
+ case "xugu-user-admin":
+ return { icon: ShieldCheck, colorClass: "text-primary" };
case "dameng-users":
return { icon: UsersRound, colorClass: "text-primary" };
case "dameng-roles":
@@ -447,7 +449,7 @@ function displayLabel(node: TreeNode): string {
// Use the canonical key for persisted trees created before this label was
// internationalized; those nodes may still contain the old Chinese text.
if (node.type === "nacos-access-control") return t("nacos.accessControlSidebarLabel");
- if (node.type === "user-admin" || node.type === "dameng-users" || node.type === "dameng-roles" || node.type === "dameng-job-admin" || node.type === "meilisearch-system") return t(node.label);
+ if (node.type === "user-admin" || node.type === "xugu-user-admin" || node.type === "dameng-users" || node.type === "dameng-roles" || node.type === "dameng-job-admin" || node.type === "meilisearch-system") return t(node.label);
if (node.type === "oracle-db-links" || node.type === "linked-server-root") return t(node.label);
if (node.type === "saved-sql-root") return t(node.label);
if (node.type === "mqtt-topic" && node.id.endsWith(":mqtt-topic:__console__")) return t(node.label);
diff --git a/apps/desktop/src/i18n/locales/en.ts b/apps/desktop/src/i18n/locales/en.ts
index c47ac5df27..9d370ea2ce 100644
--- a/apps/desktop/src/i18n/locales/en.ts
+++ b/apps/desktop/src/i18n/locales/en.ts
@@ -3806,6 +3806,8 @@ export default {
configureVisibleObjects: "Visible Object Filter",
userAdmin: "Users & Privileges",
openUserAdmin: "Open Users & Privileges",
+ xuguUserPermissions: "Xugu Users & Privileges",
+ openXuguUserPermissions: "Open Xugu Users & Privileges",
processList: "Process List",
sqlServerTrace: "Activity Trace",
serverDashboard: "Server Dashboard",
@@ -4308,6 +4310,7 @@ export default {
savedSql: "SQL Library",
queries: "Queries",
userAdmin: "Users & Privileges",
+ xuguUserPermissions: "Xugu Users & Privileges",
damengUsers: "Users",
damengRoles: "Roles",
damengJobAdmin: "Agent Jobs",
@@ -4810,6 +4813,101 @@ export default {
scopeFunctions: "functions",
stepSkipped: "Skipped because a required previous step failed.",
},
+ xuguUserPermissions: {
+ title: "Xugu Users & Privileges",
+ refresh: "Refresh",
+ databaseContext: "Manage database",
+ chooseDatabase: "Choose a database",
+ databaseContextUnknown: "The active database could not be identified. Select one from the list above if available; otherwise verify the connection's default database and refresh. Changes remain disabled until the context is explicit.",
+ databaseListLimited: "The database list could not be fully loaded; this page is limited to the confirmed database context.",
+ newPrincipal: "New User / Role",
+ users: "Users",
+ roles: "Roles",
+ search: "Search users or roles",
+ system: "System",
+ locked: "Locked",
+ active: "Active",
+ expired: "Expired",
+ validUntil: "Valid until: {value}",
+ inheritedRoles: "Inherited roles: {roles}",
+ role: "Role",
+ user: "User",
+ systemPrincipal: "System principal",
+ readOnly: "Read-only connection",
+ readOnlyHint: "This connection is read-only; management actions are disabled.",
+ limitedCatalog: "This account cannot read the complete user and role catalogs, so only visible principals are listed. Management actions are disabled to prevent mistakes from incomplete information.",
+ limitedAcl: "Only ACL rows visible to the current account are available; grants for other users or roles may be missing.",
+ managementRequiresDba: "Full management requires access to DBA_USERS, DBA_ROLES, DBA_ROLE_MEMBERS, and DBA_ACLS. Otherwise, only visible information is shown and changes are disabled.",
+ targetLookupFailed: "Could not load object/column names. You may enter an exact name manually; review it carefully before execution.",
+ targetLookupIncomplete: "The candidate list is capped at 1,000 items. Enter the exact name manually if the target is not listed.",
+ columnGrantOptionUnsupported: "Xugu does not support WITH GRANT OPTION for column-level privileges.",
+ empty: "No visible users or roles.",
+ grantsTitle: "Privilege Details",
+ grantsHint: "Direct grants and grants inherited through roles are listed separately. This is not a complete database-computed effective-privilege report.",
+ loading: "Loading...",
+ noGrants: "No visible grant rows were found.",
+ unmappedAuthority: "Unmapped authority",
+ privilege: "Privilege",
+ scope: "Scope",
+ scopeDatabase: "Current database",
+ scopeSystem: "Instance-level",
+ scopeSchema: "Schema",
+ scopeObject: "Object",
+ scopeColumn: "Column",
+ scopeRole: "Role membership",
+ scopeAdmin: "Administrative authority",
+ target: "Target",
+ source: "Source",
+ grantable: "Grantable",
+ viaRole: "Via role {role}",
+ direct: "Direct grant",
+ yes: "Yes",
+ no: "No",
+ editorTitle: "Grant / Revoke",
+ editorHint: "Catalog queries use the database selected above. Grant SQL is shown for review first; instance-level privileges affect the whole instance.",
+ systemScopeHint: "Available only while connected to SYSTEM. Creating, altering, or dropping a database affects the current instance.",
+ systemWide: "This grants or revokes an instance-level privilege and affects the whole instance, not only the current database.",
+ schema: "Schema name",
+ objectType: "Object type",
+ tableColumn: "Table column",
+ viewColumn: "View column",
+ object: "Object name",
+ column: "Column name",
+ roleToGrant: "Role name to grant",
+ adminAuthority: "Administrative authority",
+ grantOption: "Allow further object grants (WITH GRANT OPTION)",
+ revokeGrantOptionOnly: "Revoke grant option only",
+ grantOptionScope: "WITH GRANT OPTION is available only for object-level grants; Xugu does not support column-level grant option.",
+ grant: "Grant",
+ revoke: "Revoke",
+ newUser: "New User",
+ createUser: "User",
+ createRole: "Role",
+ name: "Name",
+ initialPassword: "Initial password",
+ defaultRoles: "Default roles (select multiple)",
+ createLocked: "Lock account after creation",
+ createPasswordExpired: "Require a password reset after creation",
+ accountCreateHint: "New account attributes are shown as SQL for review first; a locked or password-expired account cannot sign in normally.",
+ accountSettings: "Account settings",
+ setValidUntil: "Set account expiration date",
+ markPasswordExpired: "Mark password as expired",
+ passwordAlreadyExpiredHint: "The password is already expired. Use Change Password to clear the expired state.",
+ accountSettingsHint: "Leave the expiration date blank to keep the current value. Clearing an existing expiration is not available here; use the account card to lock or unlock the user.",
+ changePassword: "Change password",
+ newPassword: "Enter new password",
+ lock: "Lock",
+ unlock: "Unlock",
+ dropUser: "Drop user",
+ dropRole: "Drop role",
+ preview: "Preview SQL",
+ review: "Review action: {action}",
+ currentDatabaseOnly: "SQL runs against the database selected above. User drop uses RESTRICT, never CASCADE. Built-in and system principals cannot be dropped here.",
+ execute: "Confirm and execute",
+ operationSuccess: "Operation completed; privilege data refreshed.",
+ operationFailed: "Operation failed",
+ operationFailedWithMessage: "Operation failed: {message}",
+ },
damengJobAdmin: {
title: "Dameng Agent Jobs",
unsupported: "This page only supports Dameng connections.",
diff --git a/apps/desktop/src/i18n/locales/zh-CN.ts b/apps/desktop/src/i18n/locales/zh-CN.ts
index 76798e7796..a94269e579 100644
--- a/apps/desktop/src/i18n/locales/zh-CN.ts
+++ b/apps/desktop/src/i18n/locales/zh-CN.ts
@@ -3720,6 +3720,8 @@ export default withEnglishFallback({
duplicateSelectedConnections: "复制选中的 {count} 个连接",
userAdmin: "用户与权限",
openUserAdmin: "打开用户与权限",
+ xuguUserPermissions: "虚谷用户与权限",
+ openXuguUserPermissions: "打开虚谷用户与权限",
processList: "进程列表",
sqlServerTrace: "活动跟踪",
serverDashboard: "服务器仪表盘",
@@ -4218,6 +4220,7 @@ export default withEnglishFallback({
savedSql: "SQL 库",
queries: "查询",
userAdmin: "用户与权限",
+ xuguUserPermissions: "虚谷用户与权限",
damengUsers: "用户",
damengRoles: "角色",
damengJobAdmin: "代理作业",
@@ -4785,6 +4788,101 @@ export default withEnglishFallback({
scopeFunctions: "函数",
stepSkipped: "因依赖的前置步骤失败而跳过。",
},
+ xuguUserPermissions: {
+ title: "虚谷用户与权限",
+ refresh: "刷新",
+ databaseContext: "管理数据库",
+ chooseDatabase: "选择数据库",
+ databaseContextUnknown: "无法确认当前数据库。若上方有可选数据库,请选择一个;否则请检查连接默认数据库后刷新。上下文明确前,所有授权和账号修改操作都会禁用。",
+ databaseListLimited: "无法完整读取数据库列表;当前页面仅针对已确认的数据库操作。",
+ newPrincipal: "新建用户 / 角色",
+ users: "用户",
+ roles: "角色",
+ search: "搜索用户或角色",
+ system: "系统",
+ locked: "已锁定",
+ active: "正常",
+ expired: "已过期",
+ validUntil: "有效期至:{value}",
+ inheritedRoles: "继承角色:{roles}",
+ role: "角色",
+ user: "用户",
+ systemPrincipal: "系统主体",
+ readOnly: "只读连接",
+ readOnlyHint: "当前连接为只读,管理操作已禁用。",
+ limitedCatalog: "当前账号无法读取完整的用户和角色字典,因此只显示可见范围;为避免不完整信息导致误操作,所有管理操作已禁用。",
+ limitedAcl: "仅能读取当前账号可见的权限记录,未必包含数据库内所有用户/角色的授权。",
+ managementRequiresDba: "完整管理需要有权读取 DBA_USERS、DBA_ROLES、DBA_ROLE_MEMBERS 和 DBA_ACLS;否则仅显示可见信息且不能修改。",
+ targetLookupFailed: "对象/列目录读取失败;可以手动填写准确名称,执行前请仔细核对。",
+ targetLookupIncomplete: "候选列表最多显示 1000 项;若未列出目标,请手动填写准确名称。",
+ columnGrantOptionUnsupported: "虚谷列级权限不支持 WITH GRANT OPTION。",
+ empty: "没有可显示的用户或角色。",
+ grantsTitle: "权限明细",
+ grantsHint: "直接授权与通过角色继承的授权分开展示;这不是数据库计算后的完整有效权限报告。",
+ loading: "正在加载...",
+ noGrants: "当前未发现可见的授权记录。",
+ unmappedAuthority: "未映射权限值",
+ privilege: "权限",
+ scope: "授权范围",
+ scopeDatabase: "当前数据库",
+ scopeSystem: "实例级",
+ scopeSchema: "模式",
+ scopeObject: "对象",
+ scopeColumn: "列",
+ scopeRole: "角色成员",
+ scopeAdmin: "管理权限",
+ target: "目标",
+ source: "来源",
+ grantable: "可继续授权",
+ viaRole: "通过角色 {role}",
+ direct: "直接授权",
+ yes: "是",
+ no: "否",
+ editorTitle: "授权 / 撤权",
+ editorHint: "目录查询针对上方选择的数据库;授权 SQL 会先展示供确认,实例级权限除外,它会作用于整个实例。",
+ systemScopeHint: "仅在 SYSTEM 库连接下可授予;创建、修改或删除数据库会影响当前实例。",
+ systemWide: "此操作授予或回收实例级权限,将影响整个实例,而不只是当前数据库。",
+ schema: "模式名",
+ objectType: "对象类型",
+ tableColumn: "表列",
+ viewColumn: "视图列",
+ object: "对象名",
+ column: "列名",
+ roleToGrant: "授予的角色名",
+ adminAuthority: "管理权限类型",
+ grantOption: "允许继续授予对象权限(WITH GRANT OPTION)",
+ revokeGrantOptionOnly: "只撤销继续授权选项",
+ grantOptionScope: "WITH GRANT OPTION 仅用于对象级授权;虚谷不支持列级转授权。",
+ grant: "授权",
+ revoke: "撤权",
+ newUser: "新建用户",
+ createUser: "用户",
+ createRole: "角色",
+ name: "名称",
+ initialPassword: "初始密码",
+ defaultRoles: "默认角色(可多选)",
+ createLocked: "创建后锁定账号",
+ createPasswordExpired: "创建后要求重置密码",
+ accountCreateHint: "新账号属性会先展示为 SQL 供确认;锁定或密码过期会阻止该用户正常登录。",
+ accountSettings: "账号状态设置",
+ setValidUntil: "设置有效期截止时间",
+ markPasswordExpired: "将密码标记为过期",
+ passwordAlreadyExpiredHint: "密码已过期;如需解除,请使用“修改密码”。",
+ accountSettingsHint: "有效期留空表示不修改现有值;目前不提供清除有效期的操作。锁定状态可通过账号卡片上的锁定/解锁按钮管理。",
+ changePassword: "修改密码",
+ newPassword: "输入新密码",
+ lock: "锁定",
+ unlock: "解锁",
+ dropUser: "删除用户",
+ dropRole: "删除角色",
+ preview: "预览 SQL",
+ review: "确认操作:{action}",
+ currentDatabaseOnly: "SQL 通过上方选择的数据库执行。删除用户使用 RESTRICT,不会级联删除对象;内置/系统主体不可从此界面删除。",
+ execute: "确认执行",
+ operationSuccess: "操作已执行,权限信息已刷新。",
+ operationFailed: "操作执行失败",
+ operationFailedWithMessage: "操作执行失败:{message}",
+ },
damengJobAdmin: {
title: "达梦代理作业",
unsupported: "当前页面仅支持达梦数据库连接。",
diff --git a/apps/desktop/src/lib/database/__tests__/xuguUserPermissions.spec.ts b/apps/desktop/src/lib/database/__tests__/xuguUserPermissions.spec.ts
new file mode 100644
index 0000000000..93069e8586
--- /dev/null
+++ b/apps/desktop/src/lib/database/__tests__/xuguUserPermissions.spec.ts
@@ -0,0 +1,290 @@
+import { describe, expect, it } from "vitest";
+import type { QueryResult } from "@/types/database";
+import {
+ XUGU_OBJECT_TYPES,
+ decodeXuguAuthority,
+ xuguAclAuthorityLabels,
+ parseXuguAclRows,
+ parseXuguMemberships,
+ parseXuguPrincipals,
+ xuguAclRowsFallbackSql,
+ xuguAclRowsSql,
+ xuguAclColumnTargetsSql,
+ xuguAlterLockSql,
+ xuguAlterAccountSql,
+ xuguAlterPasswordSql,
+ xuguCreatePrincipalSql,
+ xuguEnrichAclColumnTargets,
+ xuguDropPrincipalSql,
+ xuguDatabaseOptions,
+ xuguGrantSql,
+ xuguInheritedRoleIds,
+ xuguListRolesSql,
+ xuguListSchemasSql,
+ xuguListUsersSql,
+ xuguListObjectNamesSql,
+ xuguListColumnNamesSql,
+ xuguPrivilegesForScope,
+ xuguQuoteIdentifier,
+ xuguQuoteLiteral,
+ xuguRevokeSql,
+ xuguRoleMembershipsSql,
+ type XuguPrincipal,
+} from "../xuguUserPermissions";
+
+function result(columns: string[], rows: unknown[][]): QueryResult {
+ return { columns, rows } as QueryResult;
+}
+
+const user: XuguPrincipal = {
+ id: "42",
+ name: "APP_USER",
+ isRole: false,
+ locked: false,
+ expired: false,
+ isSystem: false,
+};
+
+describe("Xugu user and privilege helpers", () => {
+ it("quotes identifiers and literals without allowing statement injection", () => {
+ expect(xuguQuoteIdentifier('user"; DROP USER X')).toBe('"user""; DROP USER X"');
+ expect(xuguQuoteLiteral("p'ass;word")).toBe("'p''ass;word'");
+ expect(() => xuguQuoteIdentifier(" ")).toThrow("An identifier is required.");
+ expect(() => xuguQuoteIdentifier("bad\nvalue")).toThrow("An identifier is required.");
+ expect(() => xuguQuoteLiteral("bad\0value")).toThrow("Invalid string value.");
+ });
+
+ it("keeps database selection explicit and includes the confirmed current context", () => {
+ expect(xuguDatabaseOptions([" DB_B ", "DB_A", "DB_A", ""], "DB_C")).toEqual(["DB_A", "DB_B", "DB_C"]);
+ expect(xuguDatabaseOptions([], "DB_CURRENT")).toEqual(["DB_CURRENT"]);
+ expect(xuguDatabaseOptions(["DB_A"], "")).toEqual(["DB_A"]);
+ });
+
+ it("scopes all catalog enumeration to the currently connected Xugu database", () => {
+ expect(xuguListUsersSql()).toContain("DB_ID = CURRENT_DB_ID");
+ expect(xuguListRolesSql()).toContain("DB_ID = CURRENT_DB_ID");
+ expect(xuguRoleMembershipsSql()).toContain("DB_ID = CURRENT_DB_ID");
+ expect(xuguListSchemasSql()).toContain("DB_ID = CURRENT_DB_ID");
+ expect(xuguListObjectNamesSql("APP' SCHEMA", "TABLE")).toContain("S.SCHEMA_NAME = 'APP'' SCHEMA'");
+ expect(xuguListObjectNamesSql("APP", "TABLE")).toContain("FROM DBA_OBJECTS O JOIN DBA_SCHEMAS S");
+ expect(xuguListObjectNamesSql("APP", "TABLE")).toContain("O.OBJ_TYPE = 5");
+ expect(xuguListObjectNamesSql("APP", "TABLE", false)).toContain("FROM ALL_OBJECTS O JOIN ALL_SCHEMAS S");
+ expect(() => xuguListObjectNamesSql("APP", "TRIGGER")).toThrow("Choose a supported object type.");
+ expect(xuguListColumnNamesSql("APP", "ORDERS", "TABLE")).toContain("FROM DBA_COLUMNS C JOIN DBA_TABLES T");
+ expect(xuguListColumnNamesSql("APP", "ORDERS", "TABLE")).toContain("T.TABLE_NAME = 'ORDERS'");
+ expect(xuguListColumnNamesSql("APP", "ORDER_VIEW", "VIEW")).toContain("FROM DBA_VIEW_COLUMNS C JOIN DBA_VIEWS V");
+ expect(xuguListColumnNamesSql("APP", "ORDER_VIEW", "VIEW")).toContain("V.VIEW_NAME = 'ORDER_VIEW'");
+ expect(xuguListColumnNamesSql("APP", "ORDER_VIEW", "VIEW", false)).toContain("FROM ALL_VIEW_COLUMNS C JOIN ALL_VIEWS V");
+ expect(() => xuguListObjectNamesSql("APP", "DATABASE")).toThrow("Choose a supported object type.");
+ expect(() => xuguListColumnNamesSql("APP", "SEQ", "SEQUENCE")).toThrow("Column grants are supported only for tables and views.");
+ });
+
+ it("filters ACL lookup to numeric principal IDs and provides a visibility fallback", () => {
+ const sql = xuguAclRowsSql(["42", "7", "42", "1); DROP USER X"]);
+ expect(sql).toContain("A.DB_ID = CURRENT_DB_ID");
+ expect(sql).toContain("A.GRANTEE_ID IN (42, 7)");
+ expect(sql).not.toContain("DROP USER");
+ expect(xuguAclRowsSql(["42"])).toContain("FROM DBA_ACLS A");
+ expect(xuguAclRowsSql(["42"])).toContain("A.OBJECT_ID = O.OBJ_ID AND A.OBJECT_TYPE = O.OBJ_TYPE AND A.DB_ID = O.DB_ID");
+ expect(xuguAclRowsSql(["42"])).toContain("A.OBJECT_ID < 0 OR A.OBJECT_TYPE = 4");
+ expect(xuguAclRowsSql(["42"])).toContain("S.SCHEMA_ID = CASE WHEN A.OBJECT_ID < 0 THEN -A.OBJECT_ID ELSE A.OBJECT_ID END AND A.DB_ID = S.DB_ID");
+ expect(xuguAclRowsSql(["42"])).toContain("WHEN SO.SCHEMA_NAME IS NOT NULL AND O.OBJ_NAME IS NOT NULL");
+ expect(xuguAclRowsSql(["42"])).not.toMatch(/\b(SHR|BIT_AND)\s*\(/i);
+ expect(xuguAclRowsFallbackSql(["42"])).toContain("FROM ALL_ACLS A");
+ expect(xuguAclRowsFallbackSql(["42"])).toContain("ALL_SCHEMAS");
+ });
+
+ it("resolves table and view column ACL targets in a separate optional catalog query", () => {
+ const sql = xuguAclColumnTargetsSql(["42", "7", "42", "1); DROP USER X"]);
+ expect(sql).toContain("A.GRANTEE_ID IN (42, 7)");
+ expect(sql).toContain("A.OBJECT_TYPE = 6");
+ expect(sql).toContain("T.TABLE_ID = SHR(A.OBJECT_ID, 10)");
+ expect(sql).toContain("C.COL_NO = BIT_AND(A.OBJECT_ID, 1023)");
+ expect(sql).toContain("V.VIEW_ID = SHR(A.OBJECT_ID, 10)");
+ expect(sql).toContain("VC.COL_NO = BIT_AND(A.OBJECT_ID, 1023)");
+ expect(sql).toContain("A.DB_ID = CURRENT_DB_ID");
+ expect(sql).not.toContain("DROP USER");
+ expect(xuguAclColumnTargetsSql(["42"], false)).toContain("FROM ALL_ACLS A");
+ expect(xuguAclColumnTargetsSql([])).toContain("WHERE 1 = 0");
+
+ const aclRows = [
+ { grantorId: "1", granteeId: "42", objectId: "1076", objectType: 6, authority: "1", regrant: false, target: "Column object ID 1076", scope: "column" as const },
+ { grantorId: "1", granteeId: "42", objectId: "2084", objectType: 28, authority: "2", regrant: false, target: "Column object ID 2084", scope: "column" as const },
+ { grantorId: "1", granteeId: "42", objectId: "9999", objectType: 6, authority: "1", regrant: false, target: "Column object ID 9999", scope: "column" as const },
+ ];
+ const targets = result(
+ ["GRANTEE_ID", "OBJECT_ID", "OBJECT_TYPE", "TARGET_NAME"],
+ [
+ [42, 1076, 6, "APP_SCHEMA.ORDERS.ORDER_ID"],
+ [42, 2084, 28, "APP_SCHEMA.ORDER_VIEW.ORDER_ID"],
+ [42, 9999, 6, "Column object ID 9999"],
+ ],
+ );
+ expect(xuguEnrichAclColumnTargets(aclRows, targets).map((row) => row.target)).toEqual(["APP_SCHEMA.ORDERS.ORDER_ID", "APP_SCHEMA.ORDER_VIEW.ORDER_ID", "Column object ID 9999"]);
+ });
+
+ it("parses user status and roles from database catalog result rows", () => {
+ const principals = parseXuguPrincipals(result(["USER_ID", "USER_NAME", "LOCKED", "EXPIRED", "IS_SYS", "UNTIL_TIME", "ALIAS"], [[42, "APP_USER", true, false, false, "2030-01-01", "Application account"]]), false);
+ expect(principals).toEqual([
+ {
+ id: "42",
+ name: "APP_USER",
+ isRole: false,
+ locked: true,
+ expired: false,
+ isSystem: false,
+ validUntil: "2030-01-01",
+ alias: "Application account",
+ },
+ ]);
+ expect(parseXuguPrincipals(result(["USER_ID", "USER_NAME", "IS_SYS"], [[7, "APP_ROLE", false]]), true)[0]?.isRole).toBe(true);
+ expect(parseXuguMemberships(result(["USER_ID", "ROLE_ID"], [[42, 7]]))).toEqual([{ userId: "42", roleId: "7" }]);
+ });
+
+ it("walks nested role membership without looping on corrupt or cyclic catalog rows", () => {
+ expect(
+ xuguInheritedRoleIds("42", [
+ { userId: "42", roleId: "7" },
+ { userId: "7", roleId: "8" },
+ { userId: "8", roleId: "7" },
+ { userId: "8", roleId: "42" },
+ ]),
+ ).toEqual(expect.arrayContaining(["7", "8"]));
+ expect(xuguInheritedRoleIds("42", [{ userId: "42", roleId: "42" }])).toEqual([]);
+ });
+
+ it("decodes database, schema, object, and column authority masks", () => {
+ expect(decodeXuguAuthority(0x7fffff, 0, "database")).toEqual(["DBA"]);
+ expect(decodeXuguAuthority(0x80, 0, "database")).toEqual(["CREATE"]);
+ expect(decodeXuguAuthority(0x80, 1, "database")).toEqual(["CREATE"]);
+ expect(decodeXuguAuthority(0x80, 9, "database")).toEqual(["CREATE VIEW"]);
+ expect(decodeXuguAuthority(0x100, 9, "database")).toEqual(["CREATE ANY VIEW"]);
+ expect(decodeXuguAuthority(1 | 4, 5, "database")).toEqual(["SELECT ANY TABLE", "INSERT ANY TABLE"]);
+ expect(decodeXuguAuthority(1 | 4, 5, "schema")).toEqual(["SELECT ANY TABLE", "INSERT ANY TABLE"]);
+ expect(decodeXuguAuthority(1 | 4, 5, "object")).toEqual(["SELECT", "INSERT"]);
+ expect(decodeXuguAuthority(3, 6, "column")).toEqual(["SELECT", "UPDATE"]);
+ expect(decodeXuguAuthority("not-a-mask", 5, "object")).toEqual([]);
+ expect(xuguAclAuthorityLabels(4096, 5, "object", "Unmapped authority")).toEqual(["Unmapped authority (4096)"]);
+ });
+
+ it("maps ACL rows to targets and labels inherited role grants separately", () => {
+ const role: XuguPrincipal = { id: "7", name: "APP_READ_ROLE", isRole: true, locked: false, expired: false, isSystem: false };
+ const parsed = parseXuguAclRows(result(["GRANTOR_ID", "GRANTEE_ID", "OBJECT_ID", "OBJECT_TYPE", "AUTHORITY", "REGRANT", "TARGET_NAME"], [[1, 7, 0, 5, 1, "F", "Current database"]]), [user, role], user.id);
+ expect(parsed[0]).toMatchObject({ target: "Current database", scope: "database", regrant: false, inheritedFrom: "APP_READ_ROLE" });
+ });
+
+ it("identifies schema grants encoded as negative schema IDs by the live Xugu catalog", () => {
+ const rows = result(["GRANTOR_ID", "GRANTEE_ID", "OBJECT_ID", "OBJECT_TYPE", "AUTHORITY", "REGRANT", "TARGET_NAME"], [[1, 42, -129, 5, 1, "F", "DBX_PERMISSION_SCHEMA_260929"]]);
+ const grant = parseXuguAclRows(rows, [user], user.id)[0];
+ expect(grant).toMatchObject({ scope: "schema", target: "DBX_PERMISSION_SCHEMA_260929", objectId: "-129", objectType: 5 });
+ expect(decodeXuguAuthority(grant!.authority, grant!.objectType, grant!.scope)).toEqual(["SELECT ANY TABLE"]);
+ const missingTarget = result(["GRANTOR_ID", "GRANTEE_ID", "OBJECT_ID", "OBJECT_TYPE", "AUTHORITY", "REGRANT"], [[1, 42, -129, 5, 1, "F"]]);
+ expect(parseXuguAclRows(missingTarget, [user], user.id)[0]).toMatchObject({ scope: "schema", target: "Schema ID 129" });
+ const typeFour = result(["GRANTOR_ID", "GRANTEE_ID", "OBJECT_ID", "OBJECT_TYPE", "AUTHORITY", "REGRANT"], [[1, 42, 12, 4, 1, "F"]]);
+ expect(parseXuguAclRows(typeFour, [user], user.id)[0]).toMatchObject({ scope: "schema", target: "Schema ID 12" });
+ });
+
+ it("identifies instance-wide database lifecycle grants only in the system database", () => {
+ const rows = result(["GRANTOR_ID", "GRANTEE_ID", "OBJECT_ID", "OBJECT_TYPE", "AUTHORITY", "REGRANT", "TARGET_NAME"], [[1, 42, 0, 1, 0x100, "F", "Current database"]]);
+ const systemGrant = parseXuguAclRows(rows, [user], user.id, true)[0];
+ const databaseGrant = parseXuguAclRows(rows, [user], user.id, false)[0];
+ expect(systemGrant).toMatchObject({ scope: "system", target: "All databases" });
+ expect(decodeXuguAuthority(systemGrant!.authority, systemGrant!.objectType, systemGrant!.scope)).toEqual(["CREATE ANY DATABASE"]);
+ expect(databaseGrant).toMatchObject({ scope: "database", target: "Current database" });
+ });
+
+ it("builds scope-correct grant and revoke statements with identifier quoting", () => {
+ expect(xuguGrantSql({ principal: user, scope: "database", privileges: ["CREATE ANY TABLE"] })).toBe('GRANT CREATE ANY TABLE TO "APP_USER";');
+ expect(xuguGrantSql({ principal: user, scope: "schema", privileges: ["SELECT ANY TABLE"], schema: "APP SCHEMA" })).toBe('GRANT SELECT ANY TABLE IN SCHEMA "APP SCHEMA" TO "APP_USER";');
+ expect(xuguGrantSql({ principal: user, scope: "object", privileges: ["SELECT", "UPDATE"], schema: "APP", object: "ORDERS", objectType: "TABLE", grantOption: true })).toBe('GRANT SELECT, UPDATE ON TABLE "APP"."ORDERS" TO "APP_USER" WITH GRANT OPTION;');
+ expect(xuguGrantSql({ principal: user, scope: "object", privileges: ["EXECUTE"], schema: "APP", object: "DBX_PACKAGE", objectType: "PACKAGE" })).toBe('GRANT EXECUTE ON "APP"."DBX_PACKAGE" TO "APP_USER";');
+ expect(xuguGrantSql({ principal: user, scope: "column", privileges: ["SELECT"], schema: "APP", object: "ORDERS", column: "ORDER_ID", objectType: "TABLE" })).toBe('GRANT SELECT ("ORDER_ID") ON "APP"."ORDERS" TO "APP_USER";');
+ expect(xuguRevokeSql({ principal: user, scope: "object", privileges: ["SELECT"], schema: "APP", object: "ORDERS", objectType: "TABLE" })).toBe('REVOKE SELECT ON TABLE "APP"."ORDERS" FROM "APP_USER";');
+ expect(xuguRevokeSql({ principal: user, scope: "column", privileges: ["UPDATE"], schema: "APP", object: "ORDERS", column: "STATUS", objectType: "TABLE" })).toBe('REVOKE UPDATE ("STATUS") ON "APP"."ORDERS" FROM "APP_USER";');
+ expect(xuguGrantSql({ principal: user, scope: "role", role: "APP_READ_ROLE" })).toBe('GRANT ROLE "APP_READ_ROLE" TO "APP_USER";');
+ expect(xuguRevokeSql({ principal: user, scope: "role", role: "APP_READ_ROLE" })).toBe('REVOKE ROLE "APP_READ_ROLE" FROM "APP_USER";');
+ expect(() => xuguGrantSql({ principal: { ...user, isRole: true }, scope: "role", role: "APP_READ_ROLE" })).toThrow(/only be granted to users/);
+ expect(() => xuguRevokeSql({ principal: { ...user, isRole: true }, scope: "role", role: "APP_READ_ROLE" })).toThrow(/only be revoked from users/);
+ expect(xuguGrantSql({ principal: user, scope: "object", privileges: ["ALL PRIVILEGES"], schema: "APP", object: "ORDERS", objectType: "TABLE" })).toBe('GRANT ALL PRIVILEGES ON TABLE "APP"."ORDERS" TO "APP_USER";');
+ expect(xuguRevokeSql({ principal: user, scope: "object", privileges: ["ALL PRIVILEGES"], schema: "APP", object: "ORDERS", objectType: "TABLE" })).toBe('REVOKE ALL PRIVILEGES ON TABLE "APP"."ORDERS" FROM "APP_USER";');
+ });
+
+ it("limits direct-object grant choices to documented target forms", () => {
+ expect(XUGU_OBJECT_TYPES.map((item) => item.sql)).toEqual(["TABLE", "VIEW", "PROCEDURE", "SEQUENCE", "PACKAGE", "OBJECT"]);
+ expect(xuguPrivilegesForScope("object", "TABLE").map((item) => item.name)).toContain("TRIGGER");
+ expect(xuguPrivilegesForScope("database").map((item) => item.name)).toContain("CREATE ANY TRIGGER");
+ expect(xuguPrivilegesForScope("schema").map((item) => item.name)).toContain("CREATE ANY TRIGGER");
+ expect(xuguGrantSql({ principal: user, scope: "object", privileges: ["TRIGGER"], schema: "APP", object: "ORDERS", objectType: "TABLE" })).toBe('GRANT TRIGGER ON TABLE "APP"."ORDERS" TO "APP_USER";');
+ });
+
+ it("keeps generic job creation separate from CREATE ANY JOB", () => {
+ const jobPrivileges = xuguPrivilegesForScope("database").filter((privilege) => privilege.name.endsWith("JOB"));
+ expect(jobPrivileges).toEqual([
+ { name: "CREATE ANY JOB", authorityType: 22, authorityBit: 0x100 },
+ { name: "ALTER ANY JOB", authorityType: 22, authorityBit: 0x200 },
+ { name: "DROP ANY JOB", authorityType: 22, authorityBit: 0x400 },
+ { name: "CREATE JOB", authorityType: 0, authorityBit: 0x40000 },
+ ]);
+ const allPrivileges = xuguPrivilegesForScope("database");
+ expect(new Set(allPrivileges.map((privilege) => privilege.name)).size).toBe(allPrivileges.length);
+ expect(xuguGrantSql({ principal: user, scope: "database", privileges: ["CREATE ANY JOB"] })).toBe('GRANT CREATE ANY JOB TO "APP_USER";');
+ expect(xuguGrantSql({ principal: user, scope: "database", privileges: ["CREATE JOB"] })).toBe('GRANT CREATE JOB TO "APP_USER";');
+ });
+
+ it("rejects unsupported scope/privilege combinations and database grant option", () => {
+ expect(xuguPrivilegesForScope("schema").some((item) => item.name === "CREATE TABLE")).toBe(false);
+ expect(xuguPrivilegesForScope("database").some((item) => item.name === "CREATE ANY DATABASE")).toBe(false);
+ expect(xuguPrivilegesForScope("system")).toEqual([]);
+ expect(xuguPrivilegesForScope("object", "TABLE").find((item) => item.name === "ALL PRIVILEGES")?.authorityBit).toBe(0x7df);
+ expect(xuguPrivilegesForScope("object", "PROCEDURE").find((item) => item.name === "ALL PRIVILEGES")?.authorityBit).toBe(0x1a0);
+ expect(xuguPrivilegesForScope("object", "SEQUENCE").find((item) => item.name === "ALL PRIVILEGES")?.authorityBit).toBe(0x183);
+ expect(xuguPrivilegesForScope("system", undefined, true).map((item) => item.name)).toEqual(["CREATE ANY DATABASE", "ALTER ANY DATABASE", "DROP ANY DATABASE"]);
+ expect(xuguGrantSql({ principal: user, scope: "system", privileges: ["CREATE ANY DATABASE"], systemDatabase: true })).toBe('GRANT CREATE ANY DATABASE TO "APP_USER";');
+ expect(() => xuguGrantSql({ principal: user, scope: "system", privileges: ["CREATE ANY DATABASE"] })).toThrow("System database privileges can only be managed from the SYSTEM database.");
+ expect(xuguRevokeSql({ principal: user, scope: "system", privileges: ["DROP ANY DATABASE"], systemDatabase: true })).toBe('REVOKE DROP ANY DATABASE FROM "APP_USER";');
+ expect(() => xuguRevokeSql({ principal: user, scope: "system", privileges: ["DROP ANY DATABASE"] })).toThrow("System database privileges can only be managed from the SYSTEM database.");
+ expect(() => xuguGrantSql({ principal: user, scope: "database", privileges: ["DROP USER"] })).toThrow("One or more privileges are not valid for this scope.");
+ expect(() => xuguGrantSql({ principal: user, scope: "database", privileges: ["CREATE ANY TABLE"], grantOption: true })).toThrow("WITH GRANT OPTION is supported only for object-level privileges.");
+ expect(() => xuguGrantSql({ principal: user, scope: "schema", privileges: ["SELECT ANY TABLE"], schema: "APP", grantOption: true })).toThrow("WITH GRANT OPTION is supported only for object-level privileges.");
+ expect(() => xuguGrantSql({ principal: user, scope: "column", privileges: ["SELECT"], schema: "APP", object: "ORDERS", column: "ID", objectType: "TABLE", grantOption: true })).toThrow(/object-level/);
+ expect(() => xuguGrantSql({ principal: user, scope: "column", privileges: ["SELECT"], schema: "APP", object: "ORDERS", column: "ID", objectType: "PROCEDURE" })).toThrow(/tables and views/);
+ expect(() => xuguRevokeSql({ principal: user, scope: "column", privileges: ["SELECT"], schema: "APP", object: "ORDERS", column: "ID", objectType: "PROCEDURE" })).toThrow(/tables and views/);
+ expect(() => xuguRevokeSql({ principal: user, scope: "column", privileges: ["SELECT"], schema: "APP", object: "ORDERS", column: "ID", objectType: "TABLE", revokeGrantOptionOnly: true })).toThrow(/object-level/);
+ expect(() => xuguGrantSql({ principal: user, scope: "object", privileges: ["ALL PRIVILEGES", "SELECT"], schema: "APP", object: "ORDERS", objectType: "TABLE" })).toThrow(/cannot be combined/);
+ expect(() => xuguRevokeSql({ principal: user, scope: "object", privileges: ["ALL PRIVILEGES", "SELECT"], schema: "APP", object: "ORDERS", objectType: "TABLE" })).toThrow(/cannot be combined/);
+ });
+
+ it("builds account lifecycle SQL and blocks built-in/system principal mutations", () => {
+ expect(xuguCreatePrincipalSql("APP USER", false, "secret")).toBe("CREATE USER \"APP USER\" IDENTIFIED BY 'secret';");
+ expect(
+ xuguCreatePrincipalSql("APP USER", false, "p'ass", {
+ defaultRoles: ["APP_READ_ROLE", "app_read_role", "APP_WRITE_ROLE; DROP USER X"],
+ validUntil: "2035-06-07T08:09",
+ locked: true,
+ passwordExpired: true,
+ }),
+ ).toBe("CREATE USER \"APP USER\" IDENTIFIED BY 'p''ass'\n DEFAULT ROLE \"APP_READ_ROLE\", \"APP_WRITE_ROLE; DROP USER X\"\n VALID UNTIL '2035-06-07 08:09'\n ACCOUNT LOCK\n PASSWORD EXPIRE;");
+ expect(xuguCreatePrincipalSql("APP ROLE", true)).toBe('CREATE ROLE "APP ROLE";');
+ expect(() => xuguCreatePrincipalSql("APP USER", false, "secret", { validUntil: "2035-02-31" })).toThrow("Enter a valid date or date and time.");
+ expect(xuguAlterAccountSql(user, { validUntil: "2035-06-07T08:09:10", passwordExpired: true })).toBe("ALTER USER \"APP_USER\"\n VALID UNTIL '2035-06-07 08:09:10'\n PASSWORD EXPIRE;");
+ expect(() => xuguAlterAccountSql(user, {})).toThrow("Set a validity date or mark the password as expired.");
+ expect(() => xuguAlterAccountSql({ ...user, isRole: true }, { validUntil: "2035-06-07" })).toThrow("Only non-system users can have account settings changed here.");
+ expect(() => xuguAlterAccountSql({ ...user, isSystem: true }, { validUntil: "2035-06-07" })).toThrow("Only non-system users can have account settings changed here.");
+ expect(xuguAlterPasswordSql(user, "next'password")).toBe("ALTER USER \"APP_USER\" IDENTIFIED BY 'next''password';");
+ expect(xuguAlterLockSql(user, true)).toBe('ALTER USER "APP_USER" ACCOUNT LOCK;');
+ expect(xuguDropPrincipalSql(user)).toBe('DROP USER "APP_USER" RESTRICT;');
+ expect(() => xuguDropPrincipalSql({ ...user, isSystem: true })).toThrow("Built-in or system principals cannot be dropped from this screen.");
+ expect(() => xuguDropPrincipalSql({ ...user, isRole: true, name: "PUBLIC" })).toThrow("Built-in or system principals cannot be dropped from this screen.");
+ expect(() => xuguAlterLockSql({ ...user, name: "SYSDBA" }, false)).toThrow("Only non-system users can be locked or unlocked here.");
+ expect(() => xuguAlterPasswordSql({ ...user, name: "SYSTEM" }, "x")).toThrow("Password changes are only allowed for non-system users.");
+ expect(() => xuguAlterLockSql({ ...user, isSystem: true }, false)).toThrow("Only non-system users can be locked or unlocked here.");
+ expect(() => xuguAlterPasswordSql({ ...user, isRole: true }, "x")).toThrow("Password changes are only allowed for non-system users.");
+ });
+
+ it("blocks direct grant changes to built-in principals while allowing ordinary principals", () => {
+ const systemRole = { ...user, name: "DB_ADMIN", isRole: true, isSystem: true };
+ expect(() => xuguGrantSql({ principal: systemRole, scope: "database", privileges: ["CREATE ANY TABLE"] })).toThrow("Built-in or system principals cannot be modified from this screen.");
+ expect(() => xuguRevokeSql({ principal: systemRole, scope: "database", privileges: ["CREATE ANY TABLE"] })).toThrow("Built-in or system principals cannot be modified from this screen.");
+ expect(xuguGrantSql({ principal: user, scope: "database", privileges: ["CREATE ANY TABLE"] })).toBe('GRANT CREATE ANY TABLE TO "APP_USER";');
+ });
+});
diff --git a/apps/desktop/src/lib/database/xuguUserPermissions.ts b/apps/desktop/src/lib/database/xuguUserPermissions.ts
new file mode 100644
index 0000000000..1a63939b06
--- /dev/null
+++ b/apps/desktop/src/lib/database/xuguUserPermissions.ts
@@ -0,0 +1,684 @@
+import type { QueryResult } from "@/types/database";
+
+export type XuguPrivilegeScope = "system" | "database" | "schema" | "object" | "column" | "role" | "admin";
+export type XuguAdminAuthority = "DBA" | "AUDITOR" | "SSO";
+
+export interface XuguPrincipal {
+ id: string;
+ name: string;
+ isRole: boolean;
+ locked: boolean;
+ expired: boolean;
+ isSystem: boolean;
+ validUntil?: string;
+ alias?: string;
+}
+
+export interface XuguAclRow {
+ grantorId: string;
+ granteeId: string;
+ objectId: string;
+ objectType: number;
+ authority: string;
+ regrant: boolean;
+ target: string;
+ scope: "system" | "database" | "schema" | "object" | "column";
+ inheritedFrom?: string;
+}
+
+export interface XuguPrivilege {
+ name: string;
+ authorityType: number;
+ authorityBit: number;
+}
+
+export interface XuguGrantInput {
+ principal: XuguPrincipal;
+ scope: XuguPrivilegeScope;
+ privileges?: string[];
+ schema?: string;
+ objectType?: string;
+ object?: string;
+ column?: string;
+ role?: string;
+ adminAuthority?: XuguAdminAuthority;
+ grantOption?: boolean;
+ revokeGrantOptionOnly?: boolean;
+ systemDatabase?: boolean;
+}
+
+export interface XuguCreateUserOptions {
+ defaultRoles?: string[];
+ validUntil?: string;
+ locked?: boolean;
+ passwordExpired?: boolean;
+}
+
+export interface XuguAlterAccountOptions {
+ validUntil?: string;
+ passwordExpired?: boolean;
+}
+
+const DB_ACL = {
+ READ_ANY: 0x1,
+ UPDATE_ANY: 0x2,
+ INSERT_ANY: 0x4,
+ DELETE_ANY: 0x8,
+ REF_ANY: 0x10,
+ EXECUTE_ANY: 0x20,
+ INDEX_ANY: 0x40,
+ CREATE: 0x80,
+ CREATE_ANY: 0x100,
+ ALTER_ANY: 0x200,
+ DROP_ANY: 0x400,
+ BACKUP_ANY: 0x800,
+ RESTORE_ANY: 0x1000,
+ VACUUM_ANY: 0x2000,
+ REPLICATION_ANY: 0x4000,
+ REFRESH_ANY: 0x8000,
+ GRANT_ANY: 0x10000,
+ ENCRYPT_ANY: 0x20000,
+ CREATE_JOB: 0x40000,
+ TRACE: 0x80000,
+ DBA: 0x7fffff,
+ DBO: 0xffffff,
+ AUDITOR: 0x10000000,
+ AUDIT_ADMIN: 0x30000000,
+ SSO: 0x40000000,
+ SS_ADMIN: 0xc0000000,
+} as const;
+
+const OBJECT_ACL = {
+ READ: 0x1,
+ UPDATE: 0x2,
+ INSERT: 0x4,
+ DELETE: 0x8,
+ REFERENCES: 0x10,
+ EXECUTE: 0x20,
+ INDEX: 0x40,
+ ALTER: 0x80,
+ DROP: 0x100,
+ TRIGGER: 0x200,
+ VACUUM: 0x400,
+} as const;
+
+export const XUGU_OBJECT_TYPES = [
+ { label: "Table", sql: "TABLE", type: 5 },
+ { label: "View", sql: "VIEW", type: 9 },
+ { label: "Procedure / Function", sql: "PROCEDURE", type: 7 },
+ { label: "Sequence", sql: "SEQUENCE", type: 8 },
+ { label: "Package", sql: "PACKAGE", type: 18 },
+ { label: "User-defined type", sql: "OBJECT", type: 19 },
+] as const;
+
+const DATABASE_PRIVILEGES: XuguPrivilege[] = [
+ { name: "CREATE ANY SCHEMA", authorityType: 4, authorityBit: DB_ACL.CREATE_ANY },
+ { name: "ALTER ANY SCHEMA", authorityType: 4, authorityBit: DB_ACL.ALTER_ANY },
+ { name: "DROP ANY SCHEMA", authorityType: 4, authorityBit: DB_ACL.DROP_ANY },
+ ...(
+ [
+ [
+ "TABLE",
+ 5,
+ ["CREATE", DB_ACL.CREATE],
+ ["CREATE ANY", DB_ACL.CREATE_ANY],
+ ["ALTER ANY", DB_ACL.ALTER_ANY],
+ ["DROP ANY", DB_ACL.DROP_ANY],
+ ["SELECT ANY", DB_ACL.READ_ANY],
+ ["INSERT ANY", DB_ACL.INSERT_ANY],
+ ["UPDATE ANY", DB_ACL.UPDATE_ANY],
+ ["DELETE ANY", DB_ACL.DELETE_ANY],
+ ["REFERENCES ANY", DB_ACL.REF_ANY],
+ ],
+ ["VIEW", 9, ["CREATE", DB_ACL.CREATE], ["CREATE ANY", DB_ACL.CREATE_ANY], ["ALTER ANY", DB_ACL.ALTER_ANY], ["DROP ANY", DB_ACL.DROP_ANY], ["SELECT ANY", DB_ACL.READ_ANY], ["INSERT ANY", DB_ACL.INSERT_ANY], ["UPDATE ANY", DB_ACL.UPDATE_ANY], ["DELETE ANY", DB_ACL.DELETE_ANY]],
+ ["SEQUENCE", 8, ["CREATE", DB_ACL.CREATE], ["CREATE ANY", DB_ACL.CREATE_ANY], ["ALTER ANY", DB_ACL.ALTER_ANY], ["DROP ANY", DB_ACL.DROP_ANY], ["SELECT ANY", DB_ACL.READ_ANY], ["UPDATE ANY", DB_ACL.UPDATE_ANY], ["REFERENCES ANY", DB_ACL.REF_ANY]],
+ ["PACKAGE", 18, ["CREATE", DB_ACL.CREATE], ["CREATE ANY", DB_ACL.CREATE_ANY], ["ALTER ANY", DB_ACL.ALTER_ANY], ["DROP ANY", DB_ACL.DROP_ANY], ["EXECUTE ANY", DB_ACL.EXECUTE_ANY]],
+ ["PROCEDURE", 7, ["CREATE", DB_ACL.CREATE], ["CREATE ANY", DB_ACL.CREATE_ANY], ["ALTER ANY", DB_ACL.ALTER_ANY], ["DROP ANY", DB_ACL.DROP_ANY], ["EXECUTE ANY", DB_ACL.EXECUTE_ANY]],
+ ["TRIGGER", 11, ["CREATE", DB_ACL.CREATE], ["CREATE ANY", DB_ACL.CREATE_ANY], ["ALTER ANY", DB_ACL.ALTER_ANY], ["DROP ANY", DB_ACL.DROP_ANY]],
+ ["INDEX", 10, ["CREATE", DB_ACL.CREATE], ["CREATE ANY", DB_ACL.CREATE_ANY], ["ALTER ANY", DB_ACL.ALTER_ANY], ["DROP ANY", DB_ACL.DROP_ANY]],
+ ["SYNONYM", 15, ["CREATE", DB_ACL.CREATE], ["CREATE ANY", DB_ACL.CREATE_ANY], ["ALTER ANY", DB_ACL.ALTER_ANY], ["DROP ANY", DB_ACL.DROP_ANY]],
+ ["DATABASE LINK", 12, ["CREATE ANY", DB_ACL.CREATE_ANY], ["ALTER ANY", DB_ACL.ALTER_ANY], ["DROP ANY", DB_ACL.DROP_ANY]],
+ ["USER", 16, ["CREATE ANY", DB_ACL.CREATE_ANY], ["ALTER ANY", DB_ACL.ALTER_ANY], ["DROP ANY", DB_ACL.DROP_ANY]],
+ ["ROLE", 17, ["CREATE ANY", DB_ACL.CREATE_ANY], ["ALTER ANY", DB_ACL.ALTER_ANY], ["DROP ANY", DB_ACL.DROP_ANY]],
+ ["JOB", 22, ["CREATE ANY", DB_ACL.CREATE_ANY], ["ALTER ANY", DB_ACL.ALTER_ANY], ["DROP ANY", DB_ACL.DROP_ANY]],
+ ["OBJECT", 19, ["CREATE", DB_ACL.CREATE], ["CREATE ANY", DB_ACL.CREATE_ANY], ["ALTER ANY", DB_ACL.ALTER_ANY], ["DROP ANY", DB_ACL.DROP_ANY]],
+ ] as Array<[string, number, ...Array<[string, number]>]>
+ ).flatMap(([type, objectType, ...items]) => items.map(([verb, authorityBit]) => ({ name: `${verb} ${type}`, authorityType: objectType, authorityBit }))),
+ ...(
+ [
+ ["BACKUP", DB_ACL.BACKUP_ANY],
+ ["RESTORE", DB_ACL.RESTORE_ANY],
+ ["VACUUM ANY", DB_ACL.VACUUM_ANY],
+ ["REPLICATION ANY", DB_ACL.REPLICATION_ANY],
+ ["REFRESH ANY", DB_ACL.REFRESH_ANY],
+ ["GRANT ANY", DB_ACL.GRANT_ANY],
+ ["ENCRYPT ANY", DB_ACL.ENCRYPT_ANY],
+ // CREATE_JOB is the database-wide job creation bit without an object
+ // type. Keep it distinct from CREATE ANY JOB (object type JOB), which
+ // is backed by DB_ACL.CREATE_ANY and authorityType 22 above.
+ ["CREATE JOB", DB_ACL.CREATE_JOB],
+ ["TRACE", DB_ACL.TRACE],
+ ] as Array<[string, number]>
+ ).map(([name, authorityBit]) => ({ name, authorityType: 0, authorityBit })),
+];
+
+// Database lifecycle privileges are instance-wide and are only actionable
+// from the SYSTEM database. Keep them out of the regular database grant set.
+const SYSTEM_DATABASE_PRIVILEGES: XuguPrivilege[] = [
+ { name: "CREATE ANY DATABASE", authorityType: 1, authorityBit: DB_ACL.CREATE_ANY },
+ { name: "ALTER ANY DATABASE", authorityType: 1, authorityBit: DB_ACL.ALTER_ANY },
+ { name: "DROP ANY DATABASE", authorityType: 1, authorityBit: DB_ACL.DROP_ANY },
+];
+
+// A schema ACL targets the objects inside one schema, so only the ANY-level
+// object privileges are valid here (never database-wide or own-schema CREATE).
+const SCHEMA_PRIVILEGE_TYPES = new Set([5, 9, 8, 18, 7, 11, 10, 15, 19]);
+const SCHEMA_PRIVILEGES = DATABASE_PRIVILEGES.filter((privilege) => SCHEMA_PRIVILEGE_TYPES.has(privilege.authorityType) && privilege.name.includes(" ANY "));
+
+const OBJECT_PRIVILEGES: Record<number, Array<[string, number]>> = {
+ 5: [
+ ["SELECT", OBJECT_ACL.READ],
+ ["INSERT", OBJECT_ACL.INSERT],
+ ["UPDATE", OBJECT_ACL.UPDATE],
+ ["DELETE", OBJECT_ACL.DELETE],
+ ["REFERENCES", OBJECT_ACL.REFERENCES],
+ ["ALTER", OBJECT_ACL.ALTER],
+ ["DROP", OBJECT_ACL.DROP],
+ ["INDEX", OBJECT_ACL.INDEX],
+ ["TRIGGER", OBJECT_ACL.TRIGGER],
+ ["VACUUM", OBJECT_ACL.VACUUM],
+ ],
+ 6: [
+ ["SELECT", OBJECT_ACL.READ],
+ ["UPDATE", OBJECT_ACL.UPDATE],
+ ],
+ 7: [
+ ["EXECUTE", OBJECT_ACL.EXECUTE],
+ ["ALTER", OBJECT_ACL.ALTER],
+ ["DROP", OBJECT_ACL.DROP],
+ ],
+ 8: [
+ ["SELECT", OBJECT_ACL.READ],
+ ["UPDATE", OBJECT_ACL.UPDATE],
+ ["ALTER", OBJECT_ACL.ALTER],
+ ["DROP", OBJECT_ACL.DROP],
+ ],
+ 9: [
+ ["SELECT", OBJECT_ACL.READ],
+ ["INSERT", OBJECT_ACL.INSERT],
+ ["UPDATE", OBJECT_ACL.UPDATE],
+ ["DELETE", OBJECT_ACL.DELETE],
+ ["ALTER", OBJECT_ACL.ALTER],
+ ["DROP", OBJECT_ACL.DROP],
+ ],
+ 11: [
+ ["ALTER", OBJECT_ACL.ALTER],
+ ["DROP", OBJECT_ACL.DROP],
+ ],
+ 18: [
+ ["EXECUTE", OBJECT_ACL.EXECUTE],
+ ["ALTER", OBJECT_ACL.ALTER],
+ ["DROP", OBJECT_ACL.DROP],
+ ],
+ 19: [
+ ["EXECUTE", OBJECT_ACL.EXECUTE],
+ ["ALTER", OBJECT_ACL.ALTER],
+ ["DROP", OBJECT_ACL.DROP],
+ ],
+ 28: [
+ ["SELECT", OBJECT_ACL.READ],
+ ["UPDATE", OBJECT_ACL.UPDATE],
+ ],
+};
+
+const OBJECT_TYPE_LABELS = new Map<number, string>([
+ [1, "DATABASE"],
+ [4, "SCHEMA"],
+ [5, "TABLE"],
+ [6, "COLUMN"],
+ [7, "PROCEDURE"],
+ [8, "SEQUENCE"],
+ [9, "VIEW"],
+ [10, "INDEX"],
+ [11, "TRIGGER"],
+ [12, "DATABASE LINK"],
+ [13, "REPLICATION"],
+ [15, "SYNONYM"],
+ [16, "USER"],
+ [17, "ROLE"],
+ [18, "PACKAGE"],
+ [19, "OBJECT"],
+ [22, "JOB"],
+ [28, "VIEW COLUMN"],
+ [29, "DOMAIN"],
+]);
+
+export function xuguQuoteIdentifier(value: string): string {
+ const normalized = value.trim();
+ if (!normalized || [...normalized].some((character) => character.charCodeAt(0) < 32)) throw new Error("An identifier is required.");
+ return `"${normalized.replace(/"/g, '""')}"`;
+}
+
+export function xuguQuoteLiteral(value: string): string {
+ if (value.includes("\0")) throw new Error("Invalid string value.");
+ return `'${value.replace(/'/g, "''")}'`;
+}
+
+export function xuguDatabaseOptions(names: string[], currentDatabase = ""): string[] {
+ const options = [...new Set(names.map((name) => name.trim()).filter(Boolean))];
+ const current = currentDatabase.trim();
+ if (current && !options.includes(current)) options.push(current);
+ return options.sort((left, right) => left.localeCompare(right, undefined, { numeric: true, sensitivity: "base" }));
+}
+
+export function xuguListUsersSql(): string {
+ return "SELECT USER_ID, USER_NAME, LOCKED, EXPIRED, IS_SYS, UNTIL_TIME, ALIAS FROM DBA_USERS WHERE DB_ID = CURRENT_DB_ID AND IS_ROLE = FALSE ORDER BY USER_NAME;";
+}
+
+export function xuguListRolesSql(): string {
+ return "SELECT USER_ID, USER_NAME, IS_SYS FROM DBA_ROLES WHERE DB_ID = CURRENT_DB_ID AND IS_ROLE = TRUE ORDER BY USER_NAME;";
+}
+
+export function xuguFallbackListRolesSql(): string {
+ return "SELECT USER_ID, USER_NAME, IS_SYS FROM ALL_USERS WHERE DB_ID = CURRENT_DB_ID AND IS_ROLE = TRUE ORDER BY USER_NAME;";
+}
+
+export function xuguListSchemasSql(useDbaCatalog = true): string {
+ const catalog = useDbaCatalog ? "DBA_SCHEMAS" : "ALL_SCHEMAS";
+ return `SELECT SCHEMA_ID, SCHEMA_NAME FROM ${catalog} WHERE DB_ID = CURRENT_DB_ID ORDER BY SCHEMA_NAME;`;
+}
+
+export function xuguListObjectNamesSql(schema: string, objectType: string, useDbaCatalog = true): string {
+ const type = XUGU_OBJECT_TYPES.find((item) => item.sql === objectType);
+ if (!type) throw new Error("Choose a supported object type.");
+ const catalog = useDbaCatalog ? "DBA" : "ALL";
+ return `SELECT O.OBJ_NAME FROM ${catalog}_OBJECTS O JOIN ${catalog}_SCHEMAS S ON O.SCHEMA_ID = S.SCHEMA_ID AND O.DB_ID = S.DB_ID WHERE O.DB_ID = CURRENT_DB_ID AND S.DB_ID = CURRENT_DB_ID AND S.SCHEMA_NAME = ${xuguQuoteLiteral(schema)} AND O.OBJ_TYPE = ${type.type} ORDER BY O.OBJ_NAME;`;
+}
+
+export function xuguListColumnNamesSql(schema: string, object: string, objectType: string, useDbaCatalog = true): string {
+ const schemaLiteral = xuguQuoteLiteral(schema);
+ const objectLiteral = xuguQuoteLiteral(object);
+ const catalog = useDbaCatalog ? "DBA" : "ALL";
+ if (objectType === "VIEW") {
+ return `SELECT C.COL_NAME FROM ${catalog}_VIEW_COLUMNS C JOIN ${catalog}_VIEWS V ON C.VIEW_ID = V.VIEW_ID AND C.DB_ID = V.DB_ID JOIN ${catalog}_SCHEMAS S ON V.SCHEMA_ID = S.SCHEMA_ID AND V.DB_ID = S.DB_ID WHERE C.DB_ID = CURRENT_DB_ID AND S.DB_ID = CURRENT_DB_ID AND S.SCHEMA_NAME = ${schemaLiteral} AND V.VIEW_NAME = ${objectLiteral} ORDER BY C.COL_NO;`;
+ }
+ if (objectType !== "TABLE") throw new Error("Column grants are supported only for tables and views.");
+ return `SELECT C.COL_NAME FROM ${catalog}_COLUMNS C JOIN ${catalog}_TABLES T ON C.TABLE_ID = T.TABLE_ID AND C.DB_ID = T.DB_ID JOIN ${catalog}_SCHEMAS S ON T.SCHEMA_ID = S.SCHEMA_ID AND T.DB_ID = S.DB_ID WHERE C.DB_ID = CURRENT_DB_ID AND S.DB_ID = CURRENT_DB_ID AND S.SCHEMA_NAME = ${schemaLiteral} AND T.TABLE_NAME = ${objectLiteral} ORDER BY C.COL_NO;`;
+}
+
+export function xuguFallbackListUsersSql(): string {
+ return "SELECT USER_ID, USER_NAME, LOCKED, EXPIRED, IS_SYS, UNTIL_TIME, ALIAS FROM ALL_USERS WHERE DB_ID = CURRENT_DB_ID AND IS_ROLE = FALSE ORDER BY USER_NAME;";
+}
+
+export function xuguRoleMembershipsSql(): string {
+ return "SELECT USER_ID, ROLE_ID FROM DBA_ROLE_MEMBERS WHERE DB_ID = CURRENT_DB_ID ORDER BY USER_ID, ROLE_ID;";
+}
+
+export function xuguRoleMembershipsFallbackSql(): string {
+ return "SELECT USER_ID, ROLE_ID FROM ALL_ROLE_MEMBERS WHERE DB_ID = CURRENT_DB_ID ORDER BY USER_ID, ROLE_ID;";
+}
+
+export function xuguAclRowsSql(principalIds: string[], useDbaCatalog = true): string {
+ const catalog = useDbaCatalog ? "DBA" : "ALL";
+ const ids = [...new Set(principalIds.map((id) => id.trim()).filter((id) => /^\d+$/.test(id)))];
+ if (ids.length === 0) return `SELECT GRANTOR_ID, GRANTEE_ID, OBJECT_ID, OBJECT_TYPE, AUTHORITY, REGRANT, 'database' AS SCOPE, 'Current database' AS TARGET_NAME FROM ${catalog}_ACLS WHERE 1 = 0;`;
+ return `SELECT A.GRANTOR_ID, A.GRANTEE_ID, A.OBJECT_ID, A.OBJECT_TYPE, A.AUTHORITY, A.REGRANT,
+CASE WHEN A.OBJECT_ID = 0 THEN 'database' WHEN A.OBJECT_ID < 0 OR A.OBJECT_TYPE = 4 THEN 'schema' WHEN A.OBJECT_TYPE IN (6, 28) THEN 'column' ELSE 'object' END AS SCOPE,
+CASE WHEN A.OBJECT_ID = 0 THEN 'Current database'
+ WHEN A.OBJECT_ID < 0 OR A.OBJECT_TYPE = 4 THEN COALESCE(S.SCHEMA_NAME, 'Schema ID ' || CASE WHEN A.OBJECT_ID < 0 THEN -A.OBJECT_ID ELSE A.OBJECT_ID END)
+ WHEN A.OBJECT_TYPE IN (6, 28) THEN 'Column object ID ' || A.OBJECT_ID
+ WHEN SO.SCHEMA_NAME IS NOT NULL AND O.OBJ_NAME IS NOT NULL THEN SO.SCHEMA_NAME || '.' || O.OBJ_NAME
+ ELSE 'Object ID ' || A.OBJECT_ID END AS TARGET_NAME
+FROM ${catalog}_ACLS A
+LEFT JOIN ${catalog}_SCHEMAS S ON (A.OBJECT_ID < 0 OR A.OBJECT_TYPE = 4) AND S.SCHEMA_ID = CASE WHEN A.OBJECT_ID < 0 THEN -A.OBJECT_ID ELSE A.OBJECT_ID END AND A.DB_ID = S.DB_ID
+LEFT JOIN ${catalog}_OBJECTS O ON A.OBJECT_ID > 0 AND A.OBJECT_TYPE NOT IN (4, 6, 28) AND A.OBJECT_ID = O.OBJ_ID AND A.OBJECT_TYPE = O.OBJ_TYPE AND A.DB_ID = O.DB_ID
+LEFT JOIN ${catalog}_SCHEMAS SO ON O.SCHEMA_ID = SO.SCHEMA_ID AND O.DB_ID = SO.DB_ID
+WHERE A.DB_ID = CURRENT_DB_ID AND A.GRANTEE_ID IN (${ids.join(", ")})
+ORDER BY A.GRANTEE_ID, A.OBJECT_ID, A.OBJECT_TYPE;`;
+}
+
+export function xuguAclRowsFallbackSql(principalIds: string[]): string {
+ return xuguAclRowsSql(principalIds, false);
+}
+
+/**
+ * Column ACL object IDs pack the parent object ID and column ordinal. Resolve
+ * them separately from the base ACL query so an unsupported catalog/function
+ * on an older server does not hide otherwise readable grants.
+ */
+export function xuguAclColumnTargetsSql(principalIds: string[], useDbaCatalog = true): string {
+ const catalog = useDbaCatalog ? "DBA" : "ALL";
+ const ids = [...new Set(principalIds.map((id) => id.trim()).filter((id) => /^\d+$/.test(id)))];
+ if (ids.length === 0) {
+ return `SELECT GRANTEE_ID, OBJECT_ID, OBJECT_TYPE, '' AS TARGET_NAME FROM ${catalog}_ACLS WHERE 1 = 0;`;
+ }
+ return `SELECT A.GRANTEE_ID, A.OBJECT_ID, A.OBJECT_TYPE,
+CASE WHEN A.OBJECT_TYPE = 6 THEN COALESCE(TS.SCHEMA_NAME || '.' || T.TABLE_NAME || '.' || C.COL_NAME, 'Column object ID ' || A.OBJECT_ID)
+ WHEN A.OBJECT_TYPE = 28 THEN COALESCE(VS.SCHEMA_NAME || '.' || V.VIEW_NAME || '.' || VC.COL_NAME, 'Column object ID ' || A.OBJECT_ID)
+ ELSE 'Column object ID ' || A.OBJECT_ID END AS TARGET_NAME
+FROM ${catalog}_ACLS A
+LEFT JOIN ${catalog}_TABLES T ON A.OBJECT_TYPE = 6 AND A.OBJECT_ID > 0 AND T.TABLE_ID = SHR(A.OBJECT_ID, 10) AND T.DB_ID = A.DB_ID
+LEFT JOIN ${catalog}_COLUMNS C ON A.OBJECT_TYPE = 6 AND C.TABLE_ID = T.TABLE_ID AND C.DB_ID = T.DB_ID AND C.COL_NO = BIT_AND(A.OBJECT_ID, 1023)
+LEFT JOIN ${catalog}_SCHEMAS TS ON T.SCHEMA_ID = TS.SCHEMA_ID AND T.DB_ID = TS.DB_ID
+LEFT JOIN ${catalog}_VIEWS V ON A.OBJECT_TYPE = 28 AND A.OBJECT_ID > 0 AND V.VIEW_ID = SHR(A.OBJECT_ID, 10) AND V.DB_ID = A.DB_ID
+LEFT JOIN ${catalog}_VIEW_COLUMNS VC ON A.OBJECT_TYPE = 28 AND VC.VIEW_ID = V.VIEW_ID AND VC.DB_ID = V.DB_ID AND VC.COL_NO = BIT_AND(A.OBJECT_ID, 1023)
+LEFT JOIN ${catalog}_SCHEMAS VS ON V.SCHEMA_ID = VS.SCHEMA_ID AND V.DB_ID = VS.DB_ID
+WHERE A.DB_ID = CURRENT_DB_ID AND A.GRANTEE_ID IN (${ids.join(", ")}) AND A.OBJECT_TYPE IN (6, 28) AND A.OBJECT_ID > 0
+ORDER BY A.GRANTEE_ID, A.OBJECT_ID, A.OBJECT_TYPE;`;
+}
+
+export function xuguEnrichAclColumnTargets(aclRows: XuguAclRow[], result: QueryResult): XuguAclRow[] {
+ const index = findColumns(result.columns);
+ const granteeIndex = index("GRANTEE_ID");
+ const objectIndex = index("OBJECT_ID");
+ const typeIndex = index("OBJECT_TYPE");
+ const targetIndex = index("TARGET_NAME");
+ if ([granteeIndex, objectIndex, typeIndex, targetIndex].some((column) => column < 0)) return aclRows;
+ const targets = new Map<string, string>();
+ for (const row of result.rows) {
+ const granteeId = String(row[granteeIndex] ?? "");
+ const objectId = String(row[objectIndex] ?? "");
+ const objectType = String(row[typeIndex] ?? "");
+ const target = String(row[targetIndex] ?? "").trim();
+ if (granteeId && objectId && (objectType === "6" || objectType === "28") && target && !/^Column object ID\s/i.test(target)) {
+ targets.set(`${granteeId}:${objectId}:${objectType}`, target);
+ }
+ }
+ return aclRows.map((row) => ({ ...row, target: targets.get(`${row.granteeId}:${row.objectId}:${row.objectType}`) ?? row.target }));
+}
+
+export function parseXuguPrincipals(result: QueryResult, isRole: boolean): XuguPrincipal[] {
+ const index = findColumns(result.columns);
+ const id = index("USER_ID");
+ const name = index("USER_NAME");
+ if (id < 0 || name < 0) return [];
+ return result.rows.flatMap((row) => {
+ const principalName = String(row[name] ?? "");
+ if (!principalName) return [];
+ const value = (column: string) => (index(column) < 0 ? undefined : row[index(column)]);
+ return [
+ {
+ id: String(row[id] ?? ""),
+ name: principalName,
+ isRole,
+ locked: !isRole && asBoolean(value("LOCKED")),
+ expired: !isRole && asBoolean(value("EXPIRED")),
+ isSystem: asBoolean(value("IS_SYS")),
+ validUntil: optionalString(value("UNTIL_TIME")),
+ alias: optionalString(value("ALIAS")),
+ },
+ ];
+ });
+}
+
+export function parseXuguMemberships(result: QueryResult): Array<{ userId: string; roleId: string }> {
+ const index = findColumns(result.columns);
+ const userId = index("USER_ID");
+ const roleId = index("ROLE_ID");
+ if (userId < 0 || roleId < 0) return [];
+ return result.rows.map((row) => ({ userId: String(row[userId] ?? ""), roleId: String(row[roleId] ?? "") }));
+}
+
+export function parseXuguAclRows(result: QueryResult, principals: XuguPrincipal[], selectedId: string, systemDatabase = false): XuguAclRow[] {
+ const index = findColumns(result.columns);
+ const principalById = new Map(principals.map((principal) => [principal.id, principal]));
+ const field = (row: unknown[], name: string, fallback = "") => (index(name) < 0 ? fallback : String(row[index(name)] ?? fallback));
+ return result.rows.flatMap((row) => {
+ const granteeId = field(row, "GRANTEE_ID");
+ const objectId = field(row, "OBJECT_ID");
+ const objectType = Number(field(row, "OBJECT_TYPE", "0"));
+ const authority = field(row, "AUTHORITY", "0");
+ const regrant = asBoolean(index("REGRANT") < 0 ? "0" : row[index("REGRANT")]);
+ const targetPrincipal = principalById.get(granteeId);
+ const systemWideDatabasePrivilege = systemDatabase && objectId === "0" && objectType === 1;
+ const scope = objectId === "0" ? (systemWideDatabasePrivilege ? "system" : "database") : objectId.startsWith("-") || objectType === 4 ? "schema" : objectType === 6 || objectType === 28 ? "column" : "object";
+ const schemaId = objectId.startsWith("-") ? objectId.slice(1) : objectId;
+ const target =
+ scope === "system"
+ ? "All databases"
+ : field(row, "TARGET_NAME", scope === "database" ? "Current database" : scope === "schema" ? `Schema ID ${schemaId}` : scope === "object" ? `${OBJECT_TYPE_LABELS.get(objectType) ?? `Object type ${objectType}`} ID ${objectId}` : `Column object ID ${objectId}`);
+ return [{ grantorId: field(row, "GRANTOR_ID"), granteeId, objectId, objectType, authority, regrant, target, scope, inheritedFrom: granteeId !== selectedId ? targetPrincipal?.name : undefined }];
+ });
+}
+
+export function xuguInheritedRoleIds(principalId: string, memberships: Array<{ userId: string; roleId: string }>): string[] {
+ const byMember = new Map<string, string[]>();
+ for (const membership of memberships) {
+ const current = byMember.get(membership.userId) ?? [];
+ current.push(membership.roleId);
+ byMember.set(membership.userId, current);
+ }
+ const found = new Set<string>();
+ const pending = [...(byMember.get(principalId) ?? [])];
+ while (pending.length > 0) {
+ const roleId = pending.pop()!;
+ if (found.has(roleId) || roleId === principalId) continue;
+ found.add(roleId);
+ pending.push(...(byMember.get(roleId) ?? []));
+ }
+ return [...found];
+}
+
+export function xuguPrivilegesForScope(scope: XuguPrivilegeScope, objectType?: string, systemDatabase = false): XuguPrivilege[] {
+ if (scope === "system") return systemDatabase ? SYSTEM_DATABASE_PRIVILEGES : [];
+ if (scope === "database") return DATABASE_PRIVILEGES;
+ if (scope === "schema") return SCHEMA_PRIVILEGES;
+ if (scope === "object" || scope === "column") {
+ const type = scope === "column" ? 6 : XUGU_OBJECT_TYPES.find((item) => item.sql === objectType)?.type;
+ const privileges = (type ? OBJECT_PRIVILEGES[type] : undefined)?.map(([name, authorityBit]) => ({ name, authorityType: type!, authorityBit })) ?? [];
+ if (scope !== "object" || privileges.length === 0) return privileges;
+ const allPrivilegesMask = privileges.reduce((mask, privilege) => mask | privilege.authorityBit, 0);
+ return [...privileges, { name: "ALL PRIVILEGES", authorityType: type!, authorityBit: allPrivilegesMask }];
+ }
+ return [];
+}
+
+export function decodeXuguAuthority(authority: string | number, objectType: number, scope: XuguAclRow["scope"]): string[] {
+ let bits: bigint;
+ try {
+ bits = BigInt(authority);
+ } catch {
+ return [];
+ }
+ if (scope === "system" || scope === "database" || scope === "schema") {
+ bits = BigInt.asUintN(32, bits);
+ const labels = new Set<string>();
+ if (objectType === 0) {
+ if ((bits & BigInt(DB_ACL.DBO)) === BigInt(DB_ACL.DBO)) return ["DBO"];
+ if ((bits & BigInt(DB_ACL.DBA)) === BigInt(DB_ACL.DBA)) return ["DBA"];
+ if ((bits & BigInt(DB_ACL.AUDIT_ADMIN)) === BigInt(DB_ACL.AUDIT_ADMIN)) return ["AUDIT_ADMIN"];
+ if ((bits & BigInt(DB_ACL.AUDITOR)) === BigInt(DB_ACL.AUDITOR)) return ["AUDITOR"];
+ if ((bits & BigInt(DB_ACL.SS_ADMIN)) === BigInt(DB_ACL.SS_ADMIN)) return ["SS_ADMIN"];
+ if ((bits & BigInt(DB_ACL.SSO)) === BigInt(DB_ACL.SSO)) return ["SSO"];
+ }
+ // ACL_CREATE (0x80) can be stored against either the generic database
+ // ACL type (0) or the database object type (1). It permits creating
+ // objects in the principal's own schema and is distinct from the
+ // typed CREATE ANY privileges below.
+ if ((objectType === 0 || objectType === 1) && (bits & BigInt(DB_ACL.CREATE)) === BigInt(DB_ACL.CREATE)) labels.add("CREATE");
+ for (const privilege of [...SYSTEM_DATABASE_PRIVILEGES, ...DATABASE_PRIVILEGES]) {
+ if (privilege.authorityType === objectType && (bits & BigInt(privilege.authorityBit)) === BigInt(privilege.authorityBit)) labels.add(privilege.name);
+ }
+ return [...labels];
+ }
+ const privileges = OBJECT_PRIVILEGES[objectType] ?? [];
+ return privileges.filter(([, mask]) => (bits & BigInt(mask)) === BigInt(mask)).map(([name]) => name);
+}
+
+export function xuguAclAuthorityLabels(authority: string | number, objectType: number, scope: XuguAclRow["scope"], unmappedLabel: string): string[] {
+ const labels = decodeXuguAuthority(authority, objectType, scope);
+ return labels.length > 0 ? labels : [`${unmappedLabel} (${String(authority)})`];
+}
+
+function normalizeValidUntil(value: string): string {
+ const normalized = value.trim().replace("T", " ");
+ const match = normalized.match(/^(\d{4})-(\d{2})-(\d{2})(?: (\d{2}):(\d{2})(?::(\d{2}))?)?$/);
+ if (!match) throw new Error("Enter a valid date or date and time.");
+ const [, yearText, monthText, dayText, hourText = "0", minuteText = "0", secondText = "0"] = match;
+ const year = Number(yearText);
+ const month = Number(monthText);
+ const day = Number(dayText);
+ const hour = Number(hourText);
+ const minute = Number(minuteText);
+ const second = Number(secondText);
+ const daysInMonth = month >= 1 && month <= 12 ? new Date(year, month, 0).getDate() : 0;
+ if (day < 1 || day > daysInMonth || hour > 23 || minute > 59 || second > 59) throw new Error("Enter a valid date or date and time.");
+ return normalized;
+}
+
+export function xuguCreatePrincipalSql(name: string, isRole: boolean, password = "", options: XuguCreateUserOptions = {}): string {
+ const principal = xuguQuoteIdentifier(name);
+ if (isRole) return `CREATE ROLE ${principal};`;
+ const clauses = [`CREATE USER ${principal} IDENTIFIED BY ${xuguQuoteLiteral(password)}`];
+ const roleNames = new Map<string, string>();
+ for (const role of options.defaultRoles ?? []) {
+ const normalizedRole = role.trim();
+ if (normalizedRole && !roleNames.has(normalizedRole.toLocaleUpperCase())) roleNames.set(normalizedRole.toLocaleUpperCase(), normalizedRole);
+ }
+ const defaultRoles = [...roleNames.values()];
+ if (defaultRoles.length) clauses.push(`DEFAULT ROLE ${defaultRoles.map(xuguQuoteIdentifier).join(", ")}`);
+ if (options.validUntil?.trim()) clauses.push(`VALID UNTIL ${xuguQuoteLiteral(normalizeValidUntil(options.validUntil))}`);
+ if (options.locked) clauses.push("ACCOUNT LOCK");
+ if (options.passwordExpired) clauses.push("PASSWORD EXPIRE");
+ return `${clauses.join("\n ")};`;
+}
+
+export function xuguAlterAccountSql(principal: XuguPrincipal, options: XuguAlterAccountOptions): string {
+ if (principal.isRole || isProtectedPrincipal(principal)) throw new Error("Only non-system users can have account settings changed here.");
+ const clauses: string[] = [];
+ if (options.validUntil?.trim()) clauses.push(`VALID UNTIL ${xuguQuoteLiteral(normalizeValidUntil(options.validUntil))}`);
+ if (options.passwordExpired) clauses.push("PASSWORD EXPIRE");
+ if (clauses.length === 0) throw new Error("Set a validity date or mark the password as expired.");
+ return `ALTER USER ${xuguQuoteIdentifier(principal.name)}\n ${clauses.join("\n ")};`;
+}
+
+export function xuguAlterPasswordSql(principal: XuguPrincipal, password: string): string {
+ if (principal.isRole || isProtectedPrincipal(principal)) throw new Error("Password changes are only allowed for non-system users.");
+ return `ALTER USER ${xuguQuoteIdentifier(principal.name)} IDENTIFIED BY ${xuguQuoteLiteral(password)};`;
+}
+
+export function xuguAlterLockSql(principal: XuguPrincipal, locked: boolean): string {
+ if (principal.isRole || isProtectedPrincipal(principal)) throw new Error("Only non-system users can be locked or unlocked here.");
+ return `ALTER USER ${xuguQuoteIdentifier(principal.name)} ACCOUNT ${locked ? "LOCK" : "UNLOCK"};`;
+}
+
+export function xuguDropPrincipalSql(principal: XuguPrincipal): string {
+ if (isProtectedPrincipal(principal)) {
+ throw new Error("Built-in or system principals cannot be dropped from this screen.");
+ }
+ return `DROP ${principal.isRole ? "ROLE" : "USER"} ${xuguQuoteIdentifier(principal.name)}${principal.isRole ? "" : " RESTRICT"};`;
+}
+
+function isProtectedPrincipal(principal: XuguPrincipal): boolean {
+ return principal.isSystem || ["SYS", "SYSTEM", "SYSDBA", "SYSAUDITOR", "SYSSSO", "GUEST", "PUBLIC", "DB_ADMIN", "DB_AUDIT_ADMIN", "DB_AUDIT_OPER", "DB_POLICY_ADMIN", "DB_POLICY_OPER"].includes(principal.name.trim().toUpperCase());
+}
+
+export function xuguPrincipalIsProtected(principal: XuguPrincipal): boolean {
+ return isProtectedPrincipal(principal);
+}
+
+export function xuguGrantSql(input: XuguGrantInput): string {
+ if (isProtectedPrincipal(input.principal)) throw new Error("Built-in or system principals cannot be modified from this screen.");
+ const grantee = xuguQuoteIdentifier(input.principal.name);
+ if (input.revokeGrantOptionOnly) throw new Error("Use revoke to remove a grant option.");
+ if (input.scope === "admin") {
+ const authority = input.adminAuthority;
+ if (!authority) throw new Error("Choose an administrative authority.");
+ return `GRANT ${authority} TO ${grantee};`;
+ }
+ if (input.scope === "role") {
+ if (input.principal.isRole) throw new Error("Roles can only be granted to users.");
+ const role = xuguQuoteIdentifier(input.role ?? "");
+ return `GRANT ROLE ${role} TO ${grantee};`;
+ }
+ if (input.scope === "system" && !input.systemDatabase) throw new Error("System database privileges can only be managed from the SYSTEM database.");
+ if (input.scope === "object" && !XUGU_OBJECT_TYPES.some((item) => item.sql === input.objectType)) throw new Error("Choose a supported object type.");
+ if (input.scope === "column" && !["TABLE", "VIEW"].includes(input.objectType ?? "")) throw new Error("Column grants are supported only for tables and views.");
+ const privileges = [...new Set((input.privileges ?? []).map((value) => value.trim().toUpperCase()).filter(Boolean))];
+ if (privileges.length === 0) throw new Error("Choose at least one privilege.");
+ if (input.scope === "object" && privileges.includes("ALL PRIVILEGES") && privileges.length > 1) throw new Error("ALL PRIVILEGES cannot be combined with individual privileges.");
+ const supportedPrivileges = new Set(xuguPrivilegesForScope(input.scope, input.objectType, input.systemDatabase).map((item) => item.name));
+ if (privileges.some((privilege) => !supportedPrivileges.has(privilege))) throw new Error("One or more privileges are not valid for this scope.");
+ if (input.grantOption && input.scope !== "object") {
+ throw new Error("WITH GRANT OPTION is supported only for object-level privileges.");
+ }
+ if (input.scope === "system" || input.scope === "database") {
+ if (input.grantOption) throw new Error("Xugu does not support grant option for database-level privileges.");
+ return `GRANT ${privileges.join(", ")} TO ${grantee};`;
+ }
+ if (input.scope === "schema") {
+ const schema = xuguQuoteIdentifier(input.schema ?? "");
+ return `GRANT ${privileges.join(", ")} IN SCHEMA ${schema} TO ${grantee}${input.grantOption ? " WITH GRANT OPTION" : ""};`;
+ }
+ const schema = xuguQuoteIdentifier(input.schema ?? "");
+ const object = xuguQuoteIdentifier(input.object ?? "");
+ if (input.scope === "column") {
+ const column = xuguQuoteIdentifier(input.column ?? "");
+ const privilege = privileges[0];
+ if (privileges.length !== 1 || !["SELECT", "UPDATE"].includes(privilege)) throw new Error("Column grants support SELECT or UPDATE, one privilege at a time.");
+ return `GRANT ${privilege} (${column}) ON ${schema}.${object} TO ${grantee}${input.grantOption ? " WITH GRANT OPTION" : ""};`;
+ }
+ const objectType = XUGU_OBJECT_TYPES.find((item) => item.sql === input.objectType);
+ if (!objectType) throw new Error("Choose a supported object type.");
+ const objectTypeClause = ["TABLE", "VIEW", "PROCEDURE", "SEQUENCE"].includes(objectType.sql) ? `${objectType.sql} ` : "";
+ return `GRANT ${privileges.join(", ")} ON ${objectTypeClause}${schema}.${object} TO ${grantee}${input.grantOption ? " WITH GRANT OPTION" : ""};`;
+}
+
+export function xuguRevokeSql(input: XuguGrantInput): string {
+ if (isProtectedPrincipal(input.principal)) throw new Error("Built-in or system principals cannot be modified from this screen.");
+ const grantee = xuguQuoteIdentifier(input.principal.name);
+ if (input.scope === "admin") {
+ if (!input.adminAuthority) throw new Error("Choose an administrative authority.");
+ return `REVOKE ${input.adminAuthority} FROM ${grantee};`;
+ }
+ if (input.scope === "role") {
+ if (input.principal.isRole) throw new Error("Roles can only be revoked from users.");
+ return `REVOKE ROLE ${xuguQuoteIdentifier(input.role ?? "")} FROM ${grantee};`;
+ }
+ if (input.scope === "system" && !input.systemDatabase) throw new Error("System database privileges can only be managed from the SYSTEM database.");
+ if (input.scope === "object" && !XUGU_OBJECT_TYPES.some((item) => item.sql === input.objectType)) throw new Error("Choose a supported object type.");
+ if (input.scope === "column" && !["TABLE", "VIEW"].includes(input.objectType ?? "")) throw new Error("Column grants are supported only for tables and views.");
+ const privileges = [...new Set((input.privileges ?? []).map((value) => value.trim().toUpperCase()).filter(Boolean))];
+ if (privileges.length === 0) throw new Error("Choose at least one privilege.");
+ if (input.scope === "object" && privileges.includes("ALL PRIVILEGES") && privileges.length > 1) throw new Error("ALL PRIVILEGES cannot be combined with individual privileges.");
+ const supportedPrivileges = new Set(xuguPrivilegesForScope(input.scope, input.objectType, input.systemDatabase).map((item) => item.name));
+ if (privileges.some((privilege) => !supportedPrivileges.has(privilege))) throw new Error("One or more privileges are not valid for this scope.");
+ const grantOption = input.revokeGrantOptionOnly ? " GRANT OPTION FOR" : "";
+ if (input.revokeGrantOptionOnly && input.scope !== "object") {
+ throw new Error("WITH GRANT OPTION is supported only for object-level privileges.");
+ }
+ const suffix = input.scope === "database" || input.scope === "system" ? "" : input.scope === "schema" ? ` IN SCHEMA ${xuguQuoteIdentifier(input.schema ?? "")}` : ` ${xuguQuoteIdentifier(input.schema ?? "")}.${xuguQuoteIdentifier(input.object ?? "")}`;
+ if (input.scope === "column") {
+ const column = xuguQuoteIdentifier(input.column ?? "");
+ const privilege = privileges[0];
+ if (privileges.length !== 1 || !["SELECT", "UPDATE"].includes(privilege)) throw new Error("Column grants support SELECT or UPDATE, one privilege at a time.");
+ return `REVOKE${grantOption} ${privilege} (${column}) ON ${xuguQuoteIdentifier(input.schema ?? "")}.${xuguQuoteIdentifier(input.object ?? "")} FROM ${grantee};`;
+ }
+ const objectSuffix = input.scope === "object" ? ` ON${suffix}` : suffix;
+ if (input.scope === "object") {
+ const objectType = XUGU_OBJECT_TYPES.find((item) => item.sql === input.objectType);
+ if (!objectType) throw new Error("Choose a supported object type.");
+ const objectTypeClause = ["TABLE", "VIEW", "PROCEDURE", "SEQUENCE"].includes(objectType.sql) ? ` ${objectType.sql}` : "";
+ return `REVOKE${grantOption} ${privileges.join(", ")} ON${objectTypeClause}${suffix} FROM ${grantee};`;
+ }
+ return `REVOKE${grantOption} ${privileges.join(", ")}${objectSuffix} FROM ${grantee};`;
+}
+
+function findColumns(columns: string[]) {
+ const normalized = columns.map((column) => column.toLowerCase());
+ return (name: string) => normalized.indexOf(name.toLowerCase());
+}
+
+function asBoolean(value: unknown): boolean {
+ if (typeof value === "boolean") return value;
+ return ["1", "t", "true", "y", "yes"].includes(
+ String(value ?? "")
+ .trim()
+ .toLowerCase(),
+ );
+}
+
+function optionalString(value: unknown): string | undefined {
+ if (value == null || String(value).trim() === "" || String(value).toUpperCase() === "NULL") return undefined;
+ return String(value);
+}
diff --git a/apps/desktop/src/lib/sidebar/treeNodeIcon.ts b/apps/desktop/src/lib/sidebar/treeNodeIcon.ts
index 8f7dee9d8f..1f16541a89 100644
--- a/apps/desktop/src/lib/sidebar/treeNodeIcon.ts
+++ b/apps/desktop/src/lib/sidebar/treeNodeIcon.ts
@@ -89,6 +89,8 @@ export function getTreeNodeIconInfo(node: TreeNode): TreeNodeIconInfo | null {
return { icon: TableProperties, colorClass: "text-primary" };
case "user-admin":
return { icon: UsersRound, colorClass: "text-primary" };
+ case "xugu-user-admin":
+ return { icon: ShieldCheck, colorClass: "text-primary" };
case "dameng-users":
return { icon: UsersRound, colorClass: "text-primary" };
case "dameng-roles":
diff --git a/apps/desktop/src/stores/__tests__/connectionStore.metadataLoading.spec.ts b/apps/desktop/src/stores/__tests__/connectionStore.metadataLoading.spec.ts
index 43908af7df..ad3e09a871 100644
--- a/apps/desktop/src/stores/__tests__/connectionStore.metadataLoading.spec.ts
+++ b/apps/desktop/src/stores/__tests__/connectionStore.metadataLoading.spec.ts
@@ -2577,6 +2577,45 @@ describe("connectionStore metadata loading", () => {
expect(store.isTreeNodeChildrenLoaded(test1Id)).toBe(true);
});
+ it("adds the Xugu user-permissions utility only to Xugu connection roots", async () => {
+ const listDatabases = vi.fn().mockResolvedValue([{ name: "testdb", comment: null }]);
+
+ vi.doMock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: () => false }));
+ vi.doMock("@/lib/backend/api", () => ({
+ checkConnectionHealth: vi.fn().mockResolvedValue(undefined),
+ deleteSchemaCachePrefix: vi.fn().mockResolvedValue(undefined),
+ listDatabases,
+ loadSchemaCache: vi.fn().mockResolvedValue(null),
+ saveSchemaCache: vi.fn().mockResolvedValue(undefined),
+ saveConnections: vi.fn().mockResolvedValue(undefined),
+ saveSidebarLayout: vi.fn().mockResolvedValue(undefined),
+ }));
+
+ const { useConnectionStore } = await import("@/stores/connectionStore");
+ const store = useConnectionStore();
+ const xugu = xuguConnection();
+ const mysql = mysqlConnection();
+ store.connections = [xugu, mysql];
+ store.connectedIds = new Set([xugu.id, mysql.id]);
+ store.treeNodes = [xugu, mysql].map((connection) => ({
+ id: connection.id,
+ label: connection.name,
+ type: "connection" as const,
+ connectionId: connection.id,
+ isExpanded: false,
+ children: [],
+ }));
+
+ await store.loadDatabases(xugu.id, { connectedOnly: true });
+ await store.loadDatabases(mysql.id, { connectedOnly: true });
+
+ const xuguRoot = store.treeNodes.find((node) => node.connectionId === xugu.id)!;
+ const mysqlRoot = store.treeNodes.find((node) => node.connectionId === mysql.id)!;
+ expect(xuguRoot.children?.filter((node) => node.type === "xugu-user-admin")).toHaveLength(1);
+ expect(mysqlRoot.children?.some((node) => node.type === "xugu-user-admin")).toBe(false);
+ expect(mysqlRoot.children?.some((node) => node.type === "user-admin")).toBe(true);
+ }, 15000);
+
it("clears connection loading after disconnect even when metadata apply is skipped", async () => {
let resolveDatabases!: (value: { name: string; comment: null }[]) => void;
const listDatabases = vi.fn(
diff --git a/apps/desktop/src/stores/connectionStore.ts b/apps/desktop/src/stores/connectionStore.ts
index 08f18ed6a5..41151134ae 100644
--- a/apps/desktop/src/stores/connectionStore.ts
+++ b/apps/desktop/src/stores/connectionStore.ts
@@ -1823,7 +1823,7 @@ export const useConnectionStore = defineStore("connection", () => {
// as metadata children, withConnectionUtilityNodes would keep the old copies
// AND append fresh ones on every useCachedChildren pass, duplicating the
// 用户/角色 menus once per refresh cycle.
- return node.type === "oracle-db-links" || node.type === "user-admin" || node.type === "dameng-users" || node.type === "dameng-roles" || node.type === "dameng-job-admin" || node.type === "group-tablespaces" || node.type === "saved-sql-root";
+ return node.type === "oracle-db-links" || node.type === "user-admin" || node.type === "xugu-user-admin" || node.type === "dameng-users" || node.type === "dameng-roles" || node.type === "dameng-job-admin" || node.type === "group-tablespaces" || node.type === "saved-sql-root";
}
function connectionMetadataChildren(children: TreeNode[] | undefined): TreeNode[] {
@@ -2091,6 +2091,20 @@ export const useConnectionStore = defineStore("connection", () => {
};
}
+ function buildXuguUserAdminNode(connectionId: string, existingConnectionNode?: TreeNode): TreeNode | undefined {
+ const config = getConfig(connectionId);
+ if (effectiveDatabaseTypeForConnection(config) !== "xugu") return undefined;
+ const existing = existingConnectionNode?.children?.find((child) => child.type === "xugu-user-admin");
+ return {
+ id: `${connectionId}:__xugu_user_admin`,
+ label: "tree.xuguUserPermissions",
+ type: "xugu-user-admin",
+ connectionId,
+ database: config?.database || "",
+ isExpanded: existing?.isExpanded ?? false,
+ };
+ }
+
function buildDamengUserNode(connectionId: string, existingConnectionNode?: TreeNode): TreeNode | undefined {
const config = getConfig(connectionId);
if (effectiveDatabaseTypeForConnection(config) !== "dameng") return undefined;
@@ -2199,11 +2213,12 @@ export const useConnectionStore = defineStore("connection", () => {
function withConnectionUtilityNodes(connectionId: string, children: TreeNode[], existingConnectionNode?: TreeNode): TreeNode[] {
const nonUtilityChildren = connectionMetadataChildren(children);
const userAdminNode = buildUserAdminNode(connectionId, existingConnectionNode);
+ const xuguUserAdminNode = buildXuguUserAdminNode(connectionId, existingConnectionNode);
const damengUserNode = buildDamengUserNode(connectionId, existingConnectionNode);
const damengRoleNode = buildDamengRoleNode(connectionId, existingConnectionNode);
const damengJobAdminNode = buildDamengJobAdminNode(connectionId, existingConnectionNode);
const xuguTablespacesNode = buildXuguTablespacesNode(connectionId, existingConnectionNode);
- return [...nonUtilityChildren, buildOracleDatabaseLinksNode(connectionId, existingConnectionNode), userAdminNode, damengUserNode, damengRoleNode, damengJobAdminNode, xuguTablespacesNode].filter(Boolean) as TreeNode[];
+ return [...nonUtilityChildren, buildOracleDatabaseLinksNode(connectionId, existingConnectionNode), userAdminNode, xuguUserAdminNode, damengUserNode, damengRoleNode, damengJobAdminNode, xuguTablespacesNode].filter(Boolean) as TreeNode[];
}
function withSavedSqlRoot(connectionId: string, children: TreeNode[], existingConnectionNode?: TreeNode): TreeNode[] {
diff --git a/apps/desktop/src/stores/queryStore.ts b/apps/desktop/src/stores/queryStore.ts
index 4ef9b16dd4..2694666094 100644
--- a/apps/desktop/src/stores/queryStore.ts
+++ b/apps/desktop/src/stores/queryStore.ts
@@ -3370,6 +3370,29 @@ export const useQueryStore = defineStore("query", () => {
return registerOpenTab(tab);
}
+ function openXuguUserAdmin(connectionId: string) {
+ const existing = tabs.value.find((tab) => tab.mode === "xugu-users" && tab.connectionId === connectionId);
+ if (existing) {
+ switchTab(existing.id);
+ return existing.id;
+ }
+
+ const conn = useConnectionStore().getConfig(connectionId);
+ const id = uuid();
+ const tab: QueryTab = {
+ id,
+ title: t("xuguUserPermissions.title"),
+ connectionId,
+ database: conn?.database || "",
+ sql: "",
+ isExecuting: false,
+ isCancelling: false,
+ isExplaining: false,
+ mode: "xugu-users",
+ };
+ return registerOpenTab(tab);
+ }
+
function openProcessList(connectionId: string) {
const existing = tabs.value.find((tab) => tab.mode === "processlist" && tab.connectionId === connectionId);
if (existing) {
@@ -9435,6 +9458,7 @@ export const useQueryStore = defineStore("query", () => {
openMongoGridFs,
openMongoBucket,
openUserAdmin,
+ openXuguUserAdmin,
openProcessList,
openSqlServerActivityTrace,
openMysqlDashboard,
diff --git a/apps/desktop/src/types/database.ts b/apps/desktop/src/types/database.ts
index 0fa985070e..fd95de578a 100644
--- a/apps/desktop/src/types/database.ts
+++ b/apps/desktop/src/types/database.ts
@@ -1571,6 +1571,7 @@ export type TreeNodeType =
| "event-trigger"
| "object-browser"
| "user-admin"
+ | "xugu-user-admin"
| "dameng-users"
| "dameng-roles"
| "dameng-job-admin"
@@ -2000,6 +2001,7 @@ export interface QueryTab {
| "objects"
| "structure"
| "users"
+ | "xugu-users"
| "dameng-users"
| "dameng-roles"
| "dameng-jobs"