Add Discord timeout actuator for urgent moderation
This commit is contained in:
parent
28e959916d
commit
7a147b655d
7 changed files with 420 additions and 1 deletions
266
scripts/moderate-discord-user.mjs
Normal file
266
scripts/moderate-discord-user.mjs
Normal file
|
|
@ -0,0 +1,266 @@
|
|||
import { readFileSync } from "node:fs";
|
||||
import { dirname, resolve } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { TextDecoder } from "node:util";
|
||||
|
||||
const repoRoot = resolve(dirname(fileURLToPath(import.meta.url)), "..");
|
||||
|
||||
async function main() {
|
||||
const options = parseArgs(process.argv.slice(2));
|
||||
const env = readLocalEnv();
|
||||
const botToken = env.DISCORD_BOT_TOKEN?.trim();
|
||||
const guildId = options.guildId ?? env.DISCORD_GUILD_ID?.trim();
|
||||
|
||||
if (!guildId) {
|
||||
throw new Error("Provide --guild-id or configure DISCORD_GUILD_ID.");
|
||||
}
|
||||
if (!options.userId) {
|
||||
throw new Error("Provide --user-id.");
|
||||
}
|
||||
|
||||
const reason = options.reason ?? "VoidBot moderation action.";
|
||||
if (options.dryRun) {
|
||||
process.stdout.write(`${JSON.stringify({
|
||||
ok: true,
|
||||
dryRun: true,
|
||||
action: options.action,
|
||||
guildId,
|
||||
userId: options.userId,
|
||||
durationMinutes: options.durationMinutes,
|
||||
reason,
|
||||
})}\n`);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!botToken) {
|
||||
throw new Error("DISCORD_BOT_TOKEN is required.");
|
||||
}
|
||||
|
||||
const result = await executeModerationAction({
|
||||
botToken,
|
||||
guildId,
|
||||
userId: options.userId,
|
||||
action: options.action,
|
||||
durationMinutes: options.durationMinutes,
|
||||
reason,
|
||||
});
|
||||
|
||||
process.stdout.write(`${JSON.stringify(result)}\n`);
|
||||
}
|
||||
|
||||
function parseArgs(args) {
|
||||
const options = {
|
||||
action: undefined,
|
||||
guildId: undefined,
|
||||
userId: undefined,
|
||||
durationMinutes: 60,
|
||||
reason: undefined,
|
||||
dryRun: false,
|
||||
};
|
||||
|
||||
for (let index = 0; index < args.length; index += 1) {
|
||||
const argument = args[index];
|
||||
switch (argument) {
|
||||
case "--action":
|
||||
options.action = args[index + 1];
|
||||
index += 1;
|
||||
break;
|
||||
case "--guild-id":
|
||||
options.guildId = args[index + 1];
|
||||
index += 1;
|
||||
break;
|
||||
case "--user-id":
|
||||
options.userId = args[index + 1];
|
||||
index += 1;
|
||||
break;
|
||||
case "--duration-minutes":
|
||||
options.durationMinutes = Number(args[index + 1]);
|
||||
index += 1;
|
||||
break;
|
||||
case "--reason":
|
||||
options.reason = args[index + 1];
|
||||
index += 1;
|
||||
break;
|
||||
case "--dry-run":
|
||||
options.dryRun = true;
|
||||
break;
|
||||
default:
|
||||
throw new Error(`Unknown argument: ${argument}`);
|
||||
}
|
||||
}
|
||||
|
||||
if (!["timeout", "ban", "kick", "remove-timeout"].includes(options.action)) {
|
||||
throw new Error("Provide --action timeout, ban, kick, or remove-timeout.");
|
||||
}
|
||||
if (!Number.isFinite(options.durationMinutes) || options.durationMinutes < 1) {
|
||||
throw new Error("--duration-minutes must be a positive number.");
|
||||
}
|
||||
|
||||
return options;
|
||||
}
|
||||
|
||||
async function executeModerationAction(input) {
|
||||
switch (input.action) {
|
||||
case "timeout":
|
||||
return timeoutMember(input);
|
||||
case "remove-timeout":
|
||||
return removeTimeout(input);
|
||||
case "ban":
|
||||
return banMember(input);
|
||||
case "kick":
|
||||
return kickMember(input);
|
||||
default:
|
||||
throw new Error(`Unsupported moderation action: ${input.action}`);
|
||||
}
|
||||
}
|
||||
|
||||
async function timeoutMember(input) {
|
||||
const until = new Date(Date.now() + input.durationMinutes * 60_000).toISOString();
|
||||
const response = await discordFetch(input.botToken, `/guilds/${input.guildId}/members/${input.userId}`, {
|
||||
method: "PATCH",
|
||||
reason: input.reason,
|
||||
body: {
|
||||
communication_disabled_until: until,
|
||||
},
|
||||
});
|
||||
return {
|
||||
ok: true,
|
||||
action: "timeout",
|
||||
guildId: input.guildId,
|
||||
userId: input.userId,
|
||||
durationMinutes: input.durationMinutes,
|
||||
communicationDisabledUntil: until,
|
||||
status: response.status,
|
||||
};
|
||||
}
|
||||
|
||||
async function removeTimeout(input) {
|
||||
const response = await discordFetch(input.botToken, `/guilds/${input.guildId}/members/${input.userId}`, {
|
||||
method: "PATCH",
|
||||
reason: input.reason,
|
||||
body: {
|
||||
communication_disabled_until: null,
|
||||
},
|
||||
});
|
||||
return {
|
||||
ok: true,
|
||||
action: "remove-timeout",
|
||||
guildId: input.guildId,
|
||||
userId: input.userId,
|
||||
status: response.status,
|
||||
};
|
||||
}
|
||||
|
||||
async function banMember(input) {
|
||||
const response = await discordFetch(input.botToken, `/guilds/${input.guildId}/bans/${input.userId}`, {
|
||||
method: "PUT",
|
||||
reason: input.reason,
|
||||
body: {
|
||||
delete_message_seconds: 0,
|
||||
},
|
||||
});
|
||||
return {
|
||||
ok: true,
|
||||
action: "ban",
|
||||
guildId: input.guildId,
|
||||
userId: input.userId,
|
||||
status: response.status,
|
||||
};
|
||||
}
|
||||
|
||||
async function kickMember(input) {
|
||||
const response = await discordFetch(input.botToken, `/guilds/${input.guildId}/members/${input.userId}`, {
|
||||
method: "DELETE",
|
||||
reason: input.reason,
|
||||
});
|
||||
return {
|
||||
ok: true,
|
||||
action: "kick",
|
||||
guildId: input.guildId,
|
||||
userId: input.userId,
|
||||
status: response.status,
|
||||
};
|
||||
}
|
||||
|
||||
async function discordFetch(botToken, path, options) {
|
||||
const headers = {
|
||||
Authorization: `Bot ${botToken}`,
|
||||
"X-Audit-Log-Reason": encodeURIComponent(options.reason ?? "VoidBot moderation action."),
|
||||
};
|
||||
const request = {
|
||||
method: options.method,
|
||||
headers,
|
||||
};
|
||||
|
||||
if (options.body !== undefined) {
|
||||
headers["Content-Type"] = "application/json";
|
||||
request.body = JSON.stringify(options.body);
|
||||
}
|
||||
|
||||
const response = await fetch(`https://discord.com/api/v10${path}`, request);
|
||||
if (!response.ok) {
|
||||
const text = await response.text();
|
||||
throw new Error(`Discord moderation action failed: ${response.status} ${text}`);
|
||||
}
|
||||
return response;
|
||||
}
|
||||
|
||||
function readLocalEnv() {
|
||||
const envPath = resolve(repoRoot, ".env");
|
||||
const parsed = { ...process.env };
|
||||
|
||||
try {
|
||||
const raw = stripLeadingBom(readTextFileFlexible(envPath));
|
||||
Object.assign(parsed, parseDotEnv(raw));
|
||||
} catch (error) {
|
||||
if (!(error && typeof error === "object" && "code" in error && error.code === "ENOENT")) {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
return parsed;
|
||||
}
|
||||
|
||||
function parseDotEnv(raw) {
|
||||
const result = {};
|
||||
for (const line of raw.split(/\r?\n/)) {
|
||||
const trimmed = line.trim();
|
||||
if (trimmed.length === 0 || trimmed.startsWith("#")) {
|
||||
continue;
|
||||
}
|
||||
const separatorIndex = trimmed.indexOf("=");
|
||||
if (separatorIndex === -1) {
|
||||
continue;
|
||||
}
|
||||
const key = trimmed.slice(0, separatorIndex).trim();
|
||||
let value = trimmed.slice(separatorIndex + 1).trim();
|
||||
if (
|
||||
value.length >= 2 &&
|
||||
((value.startsWith("\"") && value.endsWith("\"")) ||
|
||||
(value.startsWith("'") && value.endsWith("'")))
|
||||
) {
|
||||
value = value.slice(1, -1);
|
||||
}
|
||||
result[key] = value;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
function readTextFileFlexible(path) {
|
||||
const buffer = readFileSync(path);
|
||||
if (buffer.length >= 2) {
|
||||
if (buffer[0] === 0xff && buffer[1] === 0xfe) {
|
||||
return new TextDecoder("utf-16le").decode(buffer);
|
||||
}
|
||||
if (buffer[0] === 0xfe && buffer[1] === 0xff) {
|
||||
return new TextDecoder("utf-16be").decode(buffer);
|
||||
}
|
||||
}
|
||||
return new TextDecoder("utf-8").decode(buffer);
|
||||
}
|
||||
|
||||
function stripLeadingBom(value) {
|
||||
return value.charCodeAt(0) === 0xfeff ? value.slice(1) : value;
|
||||
}
|
||||
|
||||
await main();
|
||||
|
|
@ -43,6 +43,7 @@ $contextProjectionScriptPath = Join-Path $repoRoot "scripts\lib\void-rumination-
|
|||
$recentHistoryScriptPath = Join-Path $repoRoot "scripts\export-recent-discord-history.mjs"
|
||||
$repoActivityScriptPath = Join-Path $repoRoot "scripts\export-recent-repo-activity.mjs"
|
||||
$selfStateScriptPath = Join-Path $repoRoot "scripts\void-self-state.mjs"
|
||||
$moderationActionScriptPath = Join-Path $repoRoot "scripts\moderate-discord-user.mjs"
|
||||
$sendMessageScriptPath = if (-not [string]::IsNullOrWhiteSpace($env:VOID_SEND_DISCORD_SCRIPT)) {
|
||||
$ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($env:VOID_SEND_DISCORD_SCRIPT)
|
||||
} else {
|
||||
|
|
@ -455,6 +456,135 @@ function Assert-UrgentModerationWitnessesHandled {
|
|||
throw "Urgent moderation witness '$((Get-ObjectPropertyString -Value $firstWitness -Name "messageId"))' requires an open case or moderation candidate; silent cursor advancement is forbidden."
|
||||
}
|
||||
|
||||
function Get-PrimaryUrgentModerationWitness {
|
||||
param([object[]] $Witnesses)
|
||||
|
||||
$ownerId = Get-ConfigValue -Name "DISCORD_OWNER_ID" -Values $envValues
|
||||
return @(
|
||||
$Witnesses |
|
||||
Where-Object {
|
||||
$authorId = Get-ObjectPropertyString -Value $_ -Name "authorId"
|
||||
-not [string]::IsNullOrWhiteSpace($authorId) -and $authorId -ne $ownerId
|
||||
}
|
||||
) | Select-Object -First 1
|
||||
}
|
||||
|
||||
function Format-UrgentModerationSummary {
|
||||
param(
|
||||
[Parameter(Mandatory = $true)]
|
||||
$Witness,
|
||||
[string] $Mode
|
||||
)
|
||||
|
||||
$authorName = Get-ObjectPropertyString -Value $Witness -Name "authorName"
|
||||
$authorId = Get-ObjectPropertyString -Value $Witness -Name "authorId"
|
||||
$messageId = Get-ObjectPropertyString -Value $Witness -Name "messageId"
|
||||
$channelId = Get-ObjectPropertyString -Value $Witness -Name "channelId"
|
||||
$content = Get-ObjectPropertyString -Value $Witness -Name "content"
|
||||
$categories = @(Convert-ToValueArray -Value (Get-ObjectPropertyValue -Value $Witness -Name "categories")) -join ", "
|
||||
|
||||
return @(
|
||||
"VoidBot urgent moderation witness"
|
||||
"mode: $Mode"
|
||||
"author: $authorName ($authorId)"
|
||||
"channel: $channelId"
|
||||
"message: $messageId"
|
||||
"categories: $categories"
|
||||
"excerpt: $content"
|
||||
) -join [Environment]::NewLine
|
||||
}
|
||||
|
||||
function Invoke-OwnerModerationNotification {
|
||||
param(
|
||||
[Parameter(Mandatory = $true)]
|
||||
[string] $Content
|
||||
)
|
||||
|
||||
$contentPath = Join-Path $statusDir ("moderation-urgent-notify-{0}.txt" -f ([Guid]::NewGuid().ToString("n")))
|
||||
[System.IO.File]::WriteAllText($contentPath, $Content, [System.Text.UTF8Encoding]::new($false))
|
||||
$output = & node $sendMessageScriptPath --owner-dm --content-file $contentPath 2>&1
|
||||
$exitCode = $LASTEXITCODE
|
||||
Remove-Item -LiteralPath $contentPath -Force -ErrorAction SilentlyContinue
|
||||
if ($exitCode -ne 0) {
|
||||
throw "Owner urgent moderation notification failed: $($output | Out-String)"
|
||||
}
|
||||
return $output | ConvertFrom-Json
|
||||
}
|
||||
|
||||
function Invoke-UrgentModerationEnforcement {
|
||||
param(
|
||||
[object[]] $Witnesses,
|
||||
[string] $Mode,
|
||||
[int] $TimeoutMinutes
|
||||
)
|
||||
|
||||
if ($Witnesses.Count -eq 0) {
|
||||
return $null
|
||||
}
|
||||
|
||||
$normalizedMode = if ([string]::IsNullOrWhiteSpace($Mode)) { "log_only" } else { $Mode.Trim().ToLowerInvariant() }
|
||||
if ($normalizedMode -in @("off", "disabled", "log_only", "log-only", "case_only", "case-only")) {
|
||||
return @{
|
||||
mode = $normalizedMode
|
||||
status = "skipped"
|
||||
reason = "enforcement_mode_non_destructive"
|
||||
witnessCount = [int]$Witnesses.Count
|
||||
}
|
||||
}
|
||||
|
||||
$witness = Get-PrimaryUrgentModerationWitness -Witnesses $Witnesses
|
||||
if ($null -eq $witness) {
|
||||
return @{
|
||||
mode = $normalizedMode
|
||||
status = "skipped"
|
||||
reason = "no_non_owner_witness_author"
|
||||
witnessCount = [int]$Witnesses.Count
|
||||
}
|
||||
}
|
||||
|
||||
$summary = Format-UrgentModerationSummary -Witness $witness -Mode $normalizedMode
|
||||
|
||||
if ($normalizedMode -eq "notify_owner") {
|
||||
$notification = Invoke-OwnerModerationNotification -Content $summary
|
||||
return @{
|
||||
mode = $normalizedMode
|
||||
status = "notified_owner"
|
||||
witnessMessageId = Get-ObjectPropertyString -Value $witness -Name "messageId"
|
||||
authorId = Get-ObjectPropertyString -Value $witness -Name "authorId"
|
||||
notification = $notification
|
||||
}
|
||||
}
|
||||
|
||||
if ($normalizedMode -eq "timeout") {
|
||||
$authorId = Get-ObjectPropertyString -Value $witness -Name "authorId"
|
||||
$messageId = Get-ObjectPropertyString -Value $witness -Name "messageId"
|
||||
$reason = "VoidBot urgent safety witness $messageId"
|
||||
$actionArgs = @(
|
||||
$moderationActionScriptPath,
|
||||
"--action", "timeout",
|
||||
"--user-id", $authorId,
|
||||
"--duration-minutes", ([string]$TimeoutMinutes),
|
||||
"--reason", $reason
|
||||
)
|
||||
$actionOutput = & node @actionArgs 2>&1
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
throw "Discord timeout action failed: $($actionOutput | Out-String)"
|
||||
}
|
||||
$notification = Invoke-OwnerModerationNotification -Content ($summary + [Environment]::NewLine + "action: timeout $TimeoutMinutes minutes")
|
||||
return @{
|
||||
mode = $normalizedMode
|
||||
status = "timed_out"
|
||||
witnessMessageId = $messageId
|
||||
authorId = $authorId
|
||||
timeoutMinutes = [int]$TimeoutMinutes
|
||||
action = $actionOutput | ConvertFrom-Json
|
||||
notification = $notification
|
||||
}
|
||||
}
|
||||
|
||||
throw "Unsupported VOID_MODERATION_ENFORCEMENT_MODE '$Mode'. Use log_only, notify_owner, or timeout."
|
||||
}
|
||||
|
||||
function Get-TypedSelfState {
|
||||
$script = @"
|
||||
const core = require('./packages/core/dist');
|
||||
|
|
@ -1076,7 +1206,7 @@ if (Test-Path $operationOutputPath) {
|
|||
Remove-Item -LiteralPath $operationOutputPath -Force
|
||||
}
|
||||
|
||||
foreach ($requiredPath in @($contextProjectionScriptPath, $recentHistoryScriptPath, $repoActivityScriptPath, $selfStateScriptPath, $sendMessageScriptPath)) {
|
||||
foreach ($requiredPath in @($contextProjectionScriptPath, $recentHistoryScriptPath, $repoActivityScriptPath, $selfStateScriptPath, $moderationActionScriptPath, $sendMessageScriptPath)) {
|
||||
if (-not (Test-Path $requiredPath)) {
|
||||
throw "Missing required helper at $requiredPath"
|
||||
}
|
||||
|
|
@ -1124,6 +1254,14 @@ $codexTimeoutSeconds = if (-not [string]::IsNullOrWhiteSpace($env:VOID_RUMINATIO
|
|||
$publicRoomChannelId = Get-ConfigValue -Name "VOID_PUBLIC_ROOM_CHANNEL_ID" -Values $envValues
|
||||
$publicRoomPersonaName = Get-ConfigValue -Name "VOID_PUBLIC_ROOM_PERSONA_NAME" -Values $envValues
|
||||
$publicRoomPersonaAvatarUrl = Get-ConfigValue -Name "VOID_PUBLIC_ROOM_PERSONA_AVATAR_URL" -Values $envValues
|
||||
$moderationEnforcementMode = Get-ConfigValue -Name "VOID_MODERATION_ENFORCEMENT_MODE" -Values $envValues
|
||||
if ([string]::IsNullOrWhiteSpace($moderationEnforcementMode)) {
|
||||
$moderationEnforcementMode = "log_only"
|
||||
}
|
||||
$moderationTimeoutMinutes = Get-ConfigValue -Name "VOID_MODERATION_TIMEOUT_MINUTES" -Values $envValues
|
||||
if ([string]::IsNullOrWhiteSpace($moderationTimeoutMinutes)) {
|
||||
$moderationTimeoutMinutes = "60"
|
||||
}
|
||||
|
||||
$typedContext = Get-TypedSelfState
|
||||
$typedState = $typedContext.typedState
|
||||
|
|
@ -1305,6 +1443,7 @@ if (-not (Test-Path $operationOutputPath)) {
|
|||
Append-RunLog "reading proposed operation output."
|
||||
$proposedOperations = @(Convert-ToOperationArray -Value (Read-JsonFile -Path $operationOutputPath))
|
||||
$appliedOperations = @()
|
||||
$moderationEnforcementResult = $null
|
||||
|
||||
Assert-UrgentModerationWitnessesHandled -Witnesses $urgentModerationWitnesses -Operations $proposedOperations -TypedState $typedState
|
||||
Assert-SpeechPressureObligationsResolved -Obligations $speechPressureObligations -Operations $proposedOperations
|
||||
|
|
@ -1319,6 +1458,13 @@ foreach ($operation in $proposedOperations) {
|
|||
$appliedOperations += Apply-TypedOperation -Operation $operation
|
||||
}
|
||||
|
||||
if (-not $NoPost) {
|
||||
$moderationEnforcementResult = Invoke-UrgentModerationEnforcement `
|
||||
-Witnesses $urgentModerationWitnesses `
|
||||
-Mode $moderationEnforcementMode `
|
||||
-TimeoutMinutes ([int]$moderationTimeoutMinutes)
|
||||
}
|
||||
|
||||
$observedCursorMessageId = Get-ObjectPropertyString -Value $observedCursor -Name "lastReviewedMessageId"
|
||||
$observedCursorTimestamp = Get-ObjectPropertyString -Value $observedCursor -Name "lastReviewedTimestamp"
|
||||
if (
|
||||
|
|
@ -1405,6 +1551,7 @@ $finalStatus = [ordered]@{
|
|||
proposedOperationCount = [int]@($proposedOperations).Count
|
||||
appliedOperationCount = [int]@($appliedOperations).Count
|
||||
repoCursorOperationCount = [int]@($repoCursorOperations).Count
|
||||
moderationEnforcement = $moderationEnforcementResult
|
||||
deliveredCandidateCount = [int]$deliveredCandidateCount
|
||||
stateUpdated = [bool](@($appliedOperations).Count -gt 0)
|
||||
tracePath = [string]$tracePath
|
||||
|
|
|
|||
Loading…
Reference in a new issue