import fs from "node:fs/promises"; import path from "path"; import * as lib from "@clusterio/lib"; import type { Ctl } from "../ctl.js"; import { asTable, print } from "./command_ops.js"; function printProperties(object: object) { print(asTable(Object.entries(object).map(([property, value]) => ({ property, value })))); } export const userCommands = new lib.CommandTree({ name: "user", alias: ["u"], description: "User management" }); userCommands.add(new lib.Command({ definition: ["show ", "Show details for one user", (yargs) => { yargs.positional("name", { decribe: "Name of user to show", type: "string" }); yargs.options({ "instance-stats": { describe: "include per-instance stats", nargs: 0, type: "boolean", default: false }, }); }], handler: async function(args: { name: string, instanceStats: boolean }, ctl: Ctl) { const user = await ctl.send(new lib.UserGetRequest(args.name)); const { playerStats, instanceStats, ...properties } = user; const instances = args.instanceStats && ctl.output.human ? await ctl.send(new lib.InstanceDetailsListRequest()) : []; ctl.output.result(user, () => { printProperties({ ...properties, ...playerStats }); if (!args.instanceStats) { return; } for (let [id, playerInstanceStats] of instanceStats) { const name = instances.find(i => i.id === id)?.name ?? ""; print(); print(`Instance ${name} (${id}):`); printProperties(playerInstanceStats); } }); }, })); userCommands.add(new lib.Command({ definition: [["list", "l"], "List user in the cluster", (yargs) => { yargs.options({ "stats": { describe: "include user stats", nargs: 0, type: "boolean", default: false }, "attributes": { describe: "include admin/whitelisted/banned", nargs: 0, type: "boolean", default: false }, }); }], handler: async function(args: { stats: boolean, attributes: boolean }, ctl: Ctl) { const users = await ctl.send(new lib.UserListRequest()); ctl.output.table(users, user => { const { playerStats, isDeleted, banReason, instanceStats, isAdmin, isWhitelisted, isBanned, ...row } = user; return { ...row, ...args.attributes && { isAdmin, isWhitelisted, isBanned }, ...args.stats && playerStats, }; }); }, })); userCommands.add(new lib.Command({ definition: ["create ", "Create a user", (yargs) => { yargs.positional("name", { describe: "Name of user to create", type: "string" }); }], handler: async function(args: { name: string }, ctl: Ctl) { await ctl.send(new lib.UserCreateRequest(args.name)); }, })); userCommands.add(new lib.Command({ definition: ["revoke-token ", "Revoke token for user", (yargs) => { yargs.positional("name", { describe: "Name of user to revoke token for", type: "string" }); }], handler: async function(args: { name: string }, ctl: Ctl) { await ctl.send(new lib.UserRevokeTokenRequest(args.name)); }, })); userCommands.add(new lib.Command({ definition: ["set-admin ", "Promote or demote a user to admin", (yargs) => { yargs.positional("user", { describe: "Name of user set admin status for", type: "string" }); yargs.options({ "revoke": { describe: "Revoke admin status", nargs: 0, type: "boolean", default: false }, "create": { describe: "Create user if it does not exist", nargs: 0, type: "boolean", default: false }, }); }], handler: async function(args: { user: string, revoke: boolean, create: boolean }, ctl: Ctl) { await ctl.send(new lib.UserSetAdminRequest(args.user, args.create, !args.revoke)); }, })); userCommands.add(new lib.Command({ definition: ["set-whitelisted ", "Add or remove user from the whitelist", (yargs) => { yargs.positional("user", { describe: "Name of user to set whitelist status for", type: "string" }); yargs.options({ "remove": { describe: "Remove from whitelist", nargs: 0, type: "boolean", default: false }, "create": { describe: "Create user if it does not exist", nargs: 0, type: "boolean", default: false }, }); }], handler: async function(args: { user: string, remove: boolean, create: boolean }, ctl: Ctl) { await ctl.send(new lib.UserSetWhitelistedRequest(args.user, args.create, !args.remove)); }, })); userCommands.add(new lib.Command({ definition: ["set-banned ", "Ban or pardon user from banlist", (yargs) => { yargs.positional("user", { describe: "Name of user to set ban status for", type: "string" }); yargs.options({ "pardon": { describe: "Remove from banlist", nargs: 0, type: "boolean", default: false }, "reason": { describe: "Ban reason", nargs: 1, type: "string", default: "" }, "create": { describe: "Create user if it does not exist", nargs: 0, type: "boolean", default: false }, }); }], handler: async function( args: { user: string, pardon: boolean, reason: string, create: boolean }, ctl: Ctl ) { await ctl.send(new lib.UserSetBannedRequest(args.user, args.create, !args.pardon, args.reason)); }, })); userCommands.add(new lib.Command({ definition: ["set-roles [roles...]", "Replace user roles", (yargs) => { yargs.positional("user", { describe: "Name of user to change roles for", type: "string" }); yargs.positional("roles", { describe: "roles to assign", type: "string" }); }], handler: async function(args: { user: string, roles: string[] }, ctl: Ctl) { let roles = await ctl.send(new lib.RoleListRequest()); let resolvedRoles = []; for (let roleName of args.roles) { if (/^-?\d+$/.test(roleName)) { let roleId = parseInt(roleName, 10); resolvedRoles.push(roleId); } else { let found = false; for (let role of roles) { if (role.name === roleName) { resolvedRoles.push(role.id); found = true; break; } } if (!found) { throw new lib.CommandError(`No role named ${roleName}`); } } } await ctl.send(new lib.UserUpdateRolesRequest(args.user, resolvedRoles)); }, })); userCommands.add(new lib.Command({ definition: ["delete ", "Delete user", (yargs) => { yargs.positional("user", { describe: "Name of user to delete", type: "string" }); }], handler: async function(args: { user: string }, ctl: Ctl) { await ctl.send(new lib.UserDeleteRequest(args.user)); }, })); async function handleImportOrRestore(args: { filepath: string, users: boolean, bans: boolean, admins: boolean, whitelist: boolean, noBackup?: boolean, }, ctl: Ctl, restore: boolean) { let importType: ConstructorParameters[0]; const data = JSON.parse((await fs.readFile(args.filepath)).toString()); const optionCount = [args.users, args.bans, args.admins, args.whitelist] .reduce((acc, bool) => (bool ? acc + 1 : acc), 0); if (optionCount > 1) { throw new lib.CommandError("Can not specify multiple options"); } // Assign based on options or attempt to guess based on filename const filename = path.basename(args.filepath); if (args.users || (optionCount === 0 && data.export_version)) { importType = "users"; } else if (args.bans || (optionCount === 0 && filename.includes("ban"))) { importType = "bans"; } else if (args.admins || (optionCount === 0 && filename.includes("admin"))) { importType = "admins"; } else if (args.whitelist || (optionCount === 0 && filename.includes("whitelist"))) { importType = "whitelist"; } else { throw new lib.CommandError("Unknown json file, please specify an option"); } const backup = await ctl.send( new lib.UserBulkImportRequest(importType, importType === "users" ? data.users : data, restore) ); let backupFile: string | undefined; if (restore && backup && !args.noBackup) { backupFile = `${importType}-backup.json`; await fs.writeFile(backupFile, JSON.stringify(backup, undefined, "\t")); } ctl.output.result({ type: importType, backupFile }, () => { print(`${restore ? "Restored" : "Imported"} ${importType} from ${args.filepath}`); if (backupFile) { print(`Wrote backup to ${backupFile}`); } }); } userCommands.add(new lib.Command({ definition: ["import ", "Import user data from a file", (yargs) => { yargs.positional("filepath", { describe: "Path to the file to import", type: "string" }); yargs.options({ "users": { describe: "Import users json", nargs: 0, type: "boolean", default: false }, "bans": { describe: "Import banlist json", nargs: 0, type: "boolean", default: false }, "admins": { describe: "Import adminlist json", nargs: 0, type: "boolean", default: false }, "whitelist": { describe: "Import whitelist json", nargs: 0, type: "boolean", default: false }, }); }], handler: async function(args: any, ctl: any) { await handleImportOrRestore(args, ctl, false); }, })); userCommands.add(new lib.Command({ definition: ["restore ", "Restore user data from a file", (yargs) => { yargs.positional("filepath", { describe: "Path to the file to import", type: "string" }); yargs.options({ "users": { describe: "Restore users json", nargs: 0, type: "boolean", default: false }, "bans": { describe: "Restore banlist json", nargs: 0, type: "boolean", default: false }, "admins": { describe: "Restore adminlist json", nargs: 0, type: "boolean", default: false }, "whitelist": { describe: "Restore whitelist json", nargs: 0, type: "boolean", default: false }, "no-backup": { describe: "Don't save a backup to the cwd", nargs: 0, type: "boolean", default: false }, }); }], handler: async function(args: any, ctl: any) { await handleImportOrRestore(args, ctl, true); }, })); userCommands.add(new lib.Command({ definition: ["export ", "Export user data to a file", (yargs) => { yargs.positional("filepath", { describe: "Path to the file to save to", type: "string" }); yargs.options({ "users": { describe: "Export users json", nargs: 0, type: "boolean", default: false }, "bans": { describe: "Export banlist json", nargs: 0, type: "boolean", default: false }, "admins": { describe: "Export adminlist json", nargs: 0, type: "boolean", default: false }, "whitelist": { describe: "Export whitelist json", nargs: 0, type: "boolean", default: false }, }); }], handler: async function(args: { filepath: string, users: boolean, bans: boolean, admins: boolean, whitelist: boolean, }, ctl: Ctl) { let exportType = "users" as ConstructorParameters[0]; const optionCount = [args.bans, args.admins, args.whitelist] .reduce((acc, bool) => (bool ? acc + 1 : acc), 0); if (optionCount > 1) { throw new lib.CommandError("Can not specify multiple options"); } // Assign based on options or attempt to guess based on filename if (args.users) { exportType = "users"; } else if (args.bans) { exportType = "bans"; } else if (args.admins) { exportType = "admins"; } else if (args.whitelist) { exportType = "whitelist"; } await fs.writeFile(args.filepath, JSON.stringify(await ctl.send( new lib.UserBulkExportRequest(exportType) ), undefined, "\t")); ctl.output.result( { type: exportType, filepath: args.filepath }, () => print(`Exported ${exportType} to ${args.filepath}`), ); }, }));