levix-bot 4.7.0 → 4.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/README.md +21 -7
  2. package/SETUP.md +21 -2
  3. package/app.cjs +69 -23
  4. package/package.json +3 -2
  5. package/public/dashboard/assets/index-B1sOW2VX.js +561 -0
  6. package/public/dashboard/assets/index-CK8osB4o.css +2 -0
  7. package/public/dashboard/index.html +2 -2
  8. package/public/dashboard.css +50 -0
  9. package/public/dashboard.js +25 -2
  10. package/public/gateway-i18n.js +26 -0
  11. package/src/bootstrap/session-startup-policy.js +6 -6
  12. package/src/commands/group/antilink.cjs +82 -59
  13. package/src/commands/group/antispam.cjs +112 -0
  14. package/src/commands/group/clearwarns.cjs +6 -6
  15. package/src/commands/group/demote.cjs +11 -13
  16. package/src/commands/group/flagged.cjs +52 -0
  17. package/src/commands/group/kick.cjs +25 -15
  18. package/src/commands/group/media.cjs +65 -29
  19. package/src/commands/group/policy.cjs +215 -0
  20. package/src/commands/group/promote.cjs +11 -12
  21. package/src/commands/group/rules.cjs +9 -6
  22. package/src/commands/group/setwarn.cjs +17 -27
  23. package/src/commands/group/warn.cjs +13 -63
  24. package/src/commands/group.cjs +5 -2
  25. package/src/commands/md.cjs +44 -0
  26. package/src/commands/mod.cjs +101 -26
  27. package/src/commands/translate.cjs +585 -0
  28. package/src/config/ai-identity.cjs +53 -1
  29. package/src/config/ai-persona.md +32 -73
  30. package/src/config/defaults.cjs +3 -0
  31. package/src/config/secrets.cjs +71 -3
  32. package/src/config/settings.cjs +22 -1
  33. package/src/core/socket.js +27 -5
  34. package/src/db/db.cjs +66 -0
  35. package/src/db/store.cjs +264 -16
  36. package/src/diagnostics/crashReports.cjs +35 -9
  37. package/src/diagnostics/debugLog.cjs +405 -0
  38. package/src/handlers/command.handler.js +3 -1
  39. package/src/handlers/group.handler.js +32 -1
  40. package/src/handlers/message.handler.js +53 -17
  41. package/src/middleware/antispam.middleware.js +95 -48
  42. package/src/panel/feedback.cjs +32 -5
  43. package/src/panel/one-time-code.cjs +156 -0
  44. package/src/panel/password-reset.cjs +187 -91
  45. package/src/panel/recovery-email.cjs +333 -0
  46. package/src/routes/dashboard.api.esm.js +341 -29
  47. package/src/services/aiAgent.cjs +25 -3
  48. package/src/services/moderationPolicy.cjs +895 -0
  49. package/src/services/settingsTransfer.cjs +4 -2
  50. package/src/utils/linkedCreds.cjs +22 -0
  51. package/src/utils/logger.cjs +93 -34
  52. package/src/utils/markdownParser.cjs +208 -136
  53. package/src/utils/moderationAction.cjs +637 -0
  54. package/src/utils/moderationSummary.cjs +225 -0
  55. package/src/utils/permissions.cjs +70 -0
  56. package/src/utils/permissions.esm.js +48 -8
  57. package/src/utils/storage.cjs +8 -0
  58. package/src/utils/storage.esm.js +4 -0
  59. package/views/login.ejs +100 -28
  60. package/public/dashboard/assets/index-RnT7DAde.js +0 -540
  61. package/public/dashboard/assets/index-UcqCdCvG.css +0 -2
  62. package/src/commands/group/antiSpam.cjs +0 -97
@@ -0,0 +1,895 @@
1
+ // Per-group moderation policy.
2
+ //
3
+ // The stored object is sparse: a missing key means the default, and a feature
4
+ // null means "use the default" even when the legacy action key is set. The
5
+ // same save mirrors limit and feature actions back into warn_system /
6
+ // antilink / media_control / forbidden words / antispam so the old commands
7
+ // and the panel keep reading one value. A bad stored field is skipped; the
8
+ // message path keeps running.
9
+
10
+ const logger = require("../utils/logger.cjs");
11
+ const { getGroupSettings, saveGroupSettings } = require("../db/store.cjs");
12
+
13
+ const MODES = ["simple", "severity"];
14
+ const LIMIT_ACTIONS = ["KICK", "FLAG"];
15
+ const FEATURE_ACTIONS = ["DELETE", "WARN", "KICK"];
16
+ const SPAM_ACTIONS = ["WARN", "KICK"];
17
+ const MERGES = ["max", "sum"];
18
+ const DECAY_MODES = ["off", "expire", "step"];
19
+ const MEMBERSHIPS = ["keep", "clear"];
20
+ const NOTIFIES = ["group", "silent"];
21
+ const WHILE_FLAGGED = ["record", "hold", "escalate"];
22
+ const FEATURES = ["antilink", "media", "forbidden", "antispam"];
23
+ const WEIGHTS = ["antilink", "media", "forbidden", "antispam", "manual"];
24
+ const TOP_KEYS = [
25
+ "mode",
26
+ "limit",
27
+ "limitAction",
28
+ "features",
29
+ "hitMerge",
30
+ "weights",
31
+ "flagAt",
32
+ "kickAt",
33
+ "decay",
34
+ "membership",
35
+ "flag",
36
+ ];
37
+ const PRESET_NAMES = ["relaxed", "standard", "strict"];
38
+
39
+ const RELAXED = {
40
+ limit: 5,
41
+ limitAction: "FLAG",
42
+ decay: { mode: "expire", days: 14 },
43
+ flag: {
44
+ notify: "group",
45
+ mentionAdmins: true,
46
+ cooldownMinutes: 60,
47
+ whileFlagged: "hold",
48
+ },
49
+ };
50
+
51
+ const STRICT = {
52
+ limit: 2,
53
+ limitAction: "KICK",
54
+ features: { antilink: "KICK", antispam: "KICK", media: "WARN", forbidden: "WARN" },
55
+ decay: { mode: "off" },
56
+ };
57
+
58
+ class ModerationPolicyError extends Error {
59
+ constructor(errors) {
60
+ super(errors?.[0]?.message || "Invalid moderation policy");
61
+ this.name = "ModerationPolicyError";
62
+ this.errors = errors || [];
63
+ }
64
+ }
65
+
66
+ function isPlainObject(value) {
67
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return false;
68
+ const proto = Object.getPrototypeOf(value);
69
+ return proto === Object.prototype || proto === null;
70
+ }
71
+
72
+ function error(field, code, message) {
73
+ return { field, code, message };
74
+ }
75
+
76
+ function canonEnum(value, allowed) {
77
+ if (typeof value !== "string") return null;
78
+ const text = value.trim();
79
+ const match = allowed.find((item) => item.toLowerCase() === text.toLowerCase());
80
+ return match || null;
81
+ }
82
+
83
+ function isInteger(value) {
84
+ return typeof value === "number" && Number.isInteger(value);
85
+ }
86
+
87
+ function warnSkip(field) {
88
+ logger.warn({ field }, "ignoring invalid moderation policy field");
89
+ }
90
+
91
+ function legacyLimit(settings) {
92
+ const max = settings?.warn_system?.max_warnings;
93
+ // Old installs stored limits above 50. Keep any positive integer already
94
+ // saved. New writes are rejected outside 1–50 by validateModerationPolicy.
95
+ return isInteger(max) && max >= 1 ? max : 3;
96
+ }
97
+
98
+ function legacyLimitAction(settings) {
99
+ const action = String(settings?.warn_system?.action || "").trim().toUpperCase();
100
+ if (!action) return "KICK";
101
+ if (action === "FLAG" || action === "NONE") return "FLAG";
102
+ if (action === "KICK") return "KICK";
103
+ return "KICK";
104
+ }
105
+
106
+ function legacyFeature(settings, feature) {
107
+ let raw = "";
108
+ if (feature === "antilink") raw = settings?.antilink?.action;
109
+ else if (feature === "media") raw = settings?.media_control?.action;
110
+ else if (feature === "forbidden") {
111
+ raw = settings?.moderation?.forbiddenWords?.action ?? settings?.forbidden_words?.action;
112
+ } else if (feature === "antispam") raw = settings?.antispam?.action;
113
+ const allowed = feature === "antispam" ? SPAM_ACTIONS : FEATURE_ACTIONS;
114
+ return canonEnum(raw == null ? "" : String(raw), allowed);
115
+ }
116
+
117
+ function pickEnum(present, value, allowed, fallback, field) {
118
+ if (!present) return fallback;
119
+ if (value === null) return fallback;
120
+ const canon = canonEnum(value, allowed);
121
+ if (!canon) {
122
+ warnSkip(field);
123
+ return fallback;
124
+ }
125
+ return canon;
126
+ }
127
+
128
+ function pickInt(present, value, min, max, fallback, field) {
129
+ if (!present) return fallback;
130
+ if (!isInteger(value) || value < min || value > max) {
131
+ warnSkip(field);
132
+ return fallback;
133
+ }
134
+ return value;
135
+ }
136
+
137
+ function sectionOf(policy, key) {
138
+ const value = policy?.[key];
139
+ if (value == null) return {};
140
+ if (!isPlainObject(value)) {
141
+ warnSkip(key);
142
+ return {};
143
+ }
144
+ return value;
145
+ }
146
+
147
+ function resolveModerationPolicy(settings) {
148
+ const source = isPlainObject(settings) ? settings : {};
149
+ let policy = source.moderationPolicy;
150
+ if (policy == null) policy = {};
151
+ else if (!isPlainObject(policy)) {
152
+ warnSkip("moderationPolicy");
153
+ policy = {};
154
+ }
155
+
156
+ const has = (key) => Object.prototype.hasOwnProperty.call(policy, key);
157
+ const featuresIn = sectionOf(policy, "features");
158
+ const weightsIn = sectionOf(policy, "weights");
159
+ const decayIn = sectionOf(policy, "decay");
160
+ const flagIn = sectionOf(policy, "flag");
161
+ const featureHas = (key) => Object.prototype.hasOwnProperty.call(featuresIn, key);
162
+
163
+ const features = {};
164
+ for (const feature of FEATURES) {
165
+ if (featureHas(feature)) {
166
+ const value = featuresIn[feature];
167
+ if (value === null) features[feature] = null;
168
+ else {
169
+ const allowed = feature === "antispam" ? SPAM_ACTIONS : FEATURE_ACTIONS;
170
+ const canon = typeof value === "string" ? canonEnum(value, allowed) : null;
171
+ if (!canon) {
172
+ warnSkip(`features.${feature}`);
173
+ features[feature] = legacyFeature(source, feature);
174
+ } else features[feature] = canon;
175
+ }
176
+ } else features[feature] = legacyFeature(source, feature);
177
+ }
178
+
179
+ const weights = {};
180
+ for (const feature of WEIGHTS) {
181
+ weights[feature] = pickInt(
182
+ Object.prototype.hasOwnProperty.call(weightsIn, feature),
183
+ weightsIn[feature],
184
+ 1,
185
+ 10,
186
+ 1,
187
+ `weights.${feature}`,
188
+ );
189
+ }
190
+
191
+ const decayMode = pickEnum(
192
+ Object.prototype.hasOwnProperty.call(decayIn, "mode"),
193
+ decayIn.mode,
194
+ DECAY_MODES,
195
+ "off",
196
+ "decay.mode",
197
+ );
198
+
199
+ return {
200
+ mode: pickEnum(has("mode"), policy.mode, MODES, "simple", "mode"),
201
+ limit: pickInt(has("limit"), policy.limit, 1, 50, legacyLimit(source), "limit"),
202
+ limitAction: pickEnum(
203
+ has("limitAction"),
204
+ policy.limitAction,
205
+ LIMIT_ACTIONS,
206
+ legacyLimitAction(source),
207
+ "limitAction",
208
+ ),
209
+ features,
210
+ hitMerge: pickEnum(has("hitMerge"), policy.hitMerge, MERGES, "max", "hitMerge"),
211
+ weights,
212
+ flagAt: pickInt(has("flagAt"), policy.flagAt, 1, 49, 3, "flagAt"),
213
+ kickAt: pickInt(has("kickAt"), policy.kickAt, 2, 50, 5, "kickAt"),
214
+ decay: {
215
+ mode: decayMode,
216
+ days: pickInt(
217
+ Object.prototype.hasOwnProperty.call(decayIn, "days"),
218
+ decayIn.days,
219
+ 1,
220
+ 365,
221
+ 30,
222
+ "decay.days",
223
+ ),
224
+ },
225
+ membership: pickEnum(has("membership"), policy.membership, MEMBERSHIPS, "clear", "membership"),
226
+ flag: {
227
+ notify: pickEnum(
228
+ Object.prototype.hasOwnProperty.call(flagIn, "notify"),
229
+ flagIn.notify,
230
+ NOTIFIES,
231
+ "group",
232
+ "flag.notify",
233
+ ),
234
+ mentionAdmins: Object.prototype.hasOwnProperty.call(flagIn, "mentionAdmins")
235
+ ? flagIn.mentionAdmins === true
236
+ ? true
237
+ : flagIn.mentionAdmins === false
238
+ ? false
239
+ : (warnSkip("flag.mentionAdmins"), true)
240
+ : true,
241
+ cooldownMinutes: pickInt(
242
+ Object.prototype.hasOwnProperty.call(flagIn, "cooldownMinutes"),
243
+ flagIn.cooldownMinutes,
244
+ 0,
245
+ 10080,
246
+ 0,
247
+ "flag.cooldownMinutes",
248
+ ),
249
+ whileFlagged: pickEnum(
250
+ Object.prototype.hasOwnProperty.call(flagIn, "whileFlagged"),
251
+ flagIn.whileFlagged,
252
+ WHILE_FLAGGED,
253
+ "record",
254
+ "flag.whileFlagged",
255
+ ),
256
+ escalateAfter: pickInt(
257
+ Object.prototype.hasOwnProperty.call(flagIn, "escalateAfter"),
258
+ flagIn.escalateAfter,
259
+ 1,
260
+ 50,
261
+ 3,
262
+ "flag.escalateAfter",
263
+ ),
264
+ },
265
+ };
266
+ }
267
+
268
+ function policyFieldVisibility(effective) {
269
+ const policy = effective || resolveModerationPolicy({});
270
+ const simple = policy.mode !== "severity";
271
+ const flagBlock = !(policy.mode === "simple" && policy.limitAction === "KICK");
272
+ const escalate = policy.flag?.whileFlagged === "escalate";
273
+ return {
274
+ mode: true,
275
+ limit: simple,
276
+ limitAction: simple,
277
+ "features.antilink": true,
278
+ "features.media": true,
279
+ "features.forbidden": true,
280
+ "features.antispam": true,
281
+ hitMerge: !simple,
282
+ "weights.antilink": !simple,
283
+ "weights.media": !simple,
284
+ "weights.forbidden": !simple,
285
+ "weights.antispam": !simple,
286
+ "weights.manual": !simple,
287
+ flagAt: !simple,
288
+ kickAt: !simple,
289
+ "decay.mode": true,
290
+ "decay.days": policy.decay?.mode !== "off",
291
+ membership: true,
292
+ "flag.notify": flagBlock,
293
+ "flag.mentionAdmins": flagBlock && policy.flag?.notify !== "silent",
294
+ "flag.cooldownMinutes": flagBlock,
295
+ "flag.whileFlagged": flagBlock,
296
+ "flag.escalateAfter": flagBlock && escalate,
297
+ };
298
+ }
299
+
300
+ function cleanStored(raw) {
301
+ if (raw == null) return {};
302
+ if (!isPlainObject(raw)) return {};
303
+ const stored = {};
304
+ if (canonEnum(raw.mode, MODES)) stored.mode = canonEnum(raw.mode, MODES);
305
+ if (isInteger(raw.limit) && raw.limit >= 1 && raw.limit <= 50) stored.limit = raw.limit;
306
+ if (canonEnum(raw.limitAction, LIMIT_ACTIONS)) stored.limitAction = canonEnum(raw.limitAction, LIMIT_ACTIONS);
307
+ if (isPlainObject(raw.features)) {
308
+ const features = {};
309
+ for (const feature of FEATURES) {
310
+ if (!Object.prototype.hasOwnProperty.call(raw.features, feature)) continue;
311
+ const value = raw.features[feature];
312
+ if (value === null) features[feature] = null;
313
+ else {
314
+ const allowed = feature === "antispam" ? SPAM_ACTIONS : FEATURE_ACTIONS;
315
+ const canon = typeof value === "string" ? canonEnum(value, allowed) : null;
316
+ if (canon) features[feature] = canon;
317
+ }
318
+ }
319
+ if (Object.keys(features).length) stored.features = features;
320
+ }
321
+ if (canonEnum(raw.hitMerge, MERGES)) stored.hitMerge = canonEnum(raw.hitMerge, MERGES);
322
+ if (isPlainObject(raw.weights)) {
323
+ const weights = {};
324
+ for (const feature of WEIGHTS) {
325
+ const value = raw.weights[feature];
326
+ if (isInteger(value) && value >= 1 && value <= 10) weights[feature] = value;
327
+ }
328
+ if (Object.keys(weights).length) stored.weights = weights;
329
+ }
330
+ if (isInteger(raw.flagAt) && raw.flagAt >= 1 && raw.flagAt <= 49) stored.flagAt = raw.flagAt;
331
+ if (isInteger(raw.kickAt) && raw.kickAt >= 2 && raw.kickAt <= 50) stored.kickAt = raw.kickAt;
332
+ if (isPlainObject(raw.decay)) {
333
+ const decay = {};
334
+ if (canonEnum(raw.decay.mode, DECAY_MODES)) decay.mode = canonEnum(raw.decay.mode, DECAY_MODES);
335
+ if (isInteger(raw.decay.days) && raw.decay.days >= 1 && raw.decay.days <= 365) decay.days = raw.decay.days;
336
+ if (Object.keys(decay).length) stored.decay = decay;
337
+ }
338
+ if (canonEnum(raw.membership, MEMBERSHIPS)) stored.membership = canonEnum(raw.membership, MEMBERSHIPS);
339
+ if (isPlainObject(raw.flag)) {
340
+ const flag = {};
341
+ if (canonEnum(raw.flag.notify, NOTIFIES)) flag.notify = canonEnum(raw.flag.notify, NOTIFIES);
342
+ if (raw.flag.mentionAdmins === true || raw.flag.mentionAdmins === false) {
343
+ flag.mentionAdmins = raw.flag.mentionAdmins;
344
+ }
345
+ if (isInteger(raw.flag.cooldownMinutes) && raw.flag.cooldownMinutes >= 0 && raw.flag.cooldownMinutes <= 10080) {
346
+ flag.cooldownMinutes = raw.flag.cooldownMinutes;
347
+ }
348
+ if (canonEnum(raw.flag.whileFlagged, WHILE_FLAGGED)) {
349
+ flag.whileFlagged = canonEnum(raw.flag.whileFlagged, WHILE_FLAGGED);
350
+ }
351
+ if (isInteger(raw.flag.escalateAfter) && raw.flag.escalateAfter >= 1 && raw.flag.escalateAfter <= 50) {
352
+ flag.escalateAfter = raw.flag.escalateAfter;
353
+ }
354
+ if (Object.keys(flag).length) stored.flag = flag;
355
+ }
356
+ return stored;
357
+ }
358
+
359
+ function checkInteger(errors, field, value, min, max) {
360
+ if (!isInteger(value)) {
361
+ errors.push(error(field, "type", `${field} must be an integer`));
362
+ return false;
363
+ }
364
+ if (value < min || value > max) {
365
+ errors.push(error(field, "range", `${field} must be from ${min} to ${max}`));
366
+ return false;
367
+ }
368
+ return true;
369
+ }
370
+
371
+ function checkEnum(errors, field, value, allowed) {
372
+ const canon = typeof value === "string" ? canonEnum(value, allowed) : null;
373
+ if (!canon) {
374
+ errors.push(error(field, "enum", `${field} must be ${allowed.join(", ")}`));
375
+ return null;
376
+ }
377
+ return canon;
378
+ }
379
+
380
+ function mergeSection(errors, field, base, patch, allowed) {
381
+ if (patch === undefined) return base;
382
+ if (!isPlainObject(patch)) {
383
+ errors.push(error(field, "type", `${field} must be an object`));
384
+ return base;
385
+ }
386
+ const next = { ...(base || {}) };
387
+ for (const [key, value] of Object.entries(patch)) {
388
+ if (!allowed.includes(key)) {
389
+ errors.push(error(`${field}.${key}`, "unknown", `Unknown field ${field}.${key}`));
390
+ continue;
391
+ }
392
+ next[key] = value;
393
+ }
394
+ return next;
395
+ }
396
+
397
+ function validateModerationPolicy(patch, currentSettings) {
398
+ const errors = [];
399
+ if (!isPlainObject(patch)) {
400
+ return { ok: false, errors: [error("moderation_policy", "type", "Policy must be an object")] };
401
+ }
402
+ const current = isPlainObject(currentSettings) ? currentSettings : {};
403
+ const base = cleanStored(current.moderationPolicy);
404
+ const merged = { ...base };
405
+ for (const [key, value] of Object.entries(patch)) {
406
+ if (!TOP_KEYS.includes(key)) {
407
+ errors.push(error(key, "unknown", `Unknown field ${key}`));
408
+ continue;
409
+ }
410
+ if (key === "features" || key === "weights" || key === "decay" || key === "flag") continue;
411
+ merged[key] = value;
412
+ }
413
+ merged.features = mergeSection(errors, "features", base.features, patch.features, FEATURES);
414
+ merged.weights = mergeSection(errors, "weights", base.weights, patch.weights, WEIGHTS);
415
+ merged.decay = mergeSection(errors, "decay", base.decay, patch.decay, ["mode", "days"]);
416
+ merged.flag = mergeSection(errors, "flag", base.flag, patch.flag, [
417
+ "notify",
418
+ "mentionAdmins",
419
+ "cooldownMinutes",
420
+ "whileFlagged",
421
+ "escalateAfter",
422
+ ]);
423
+
424
+ const stored = {};
425
+ if (Object.prototype.hasOwnProperty.call(merged, "mode")) {
426
+ const mode = checkEnum(errors, "mode", merged.mode, MODES);
427
+ if (mode) stored.mode = mode;
428
+ }
429
+ if (Object.prototype.hasOwnProperty.call(merged, "limit")) {
430
+ if (checkInteger(errors, "limit", merged.limit, 1, 50)) stored.limit = merged.limit;
431
+ }
432
+ if (Object.prototype.hasOwnProperty.call(merged, "limitAction")) {
433
+ const action = checkEnum(errors, "limitAction", merged.limitAction, LIMIT_ACTIONS);
434
+ if (action) stored.limitAction = action;
435
+ }
436
+ if (merged.features && Object.keys(merged.features).length) {
437
+ const features = {};
438
+ for (const [feature, value] of Object.entries(merged.features)) {
439
+ if (value === null) {
440
+ features[feature] = null;
441
+ continue;
442
+ }
443
+ const allowed = feature === "antispam" ? SPAM_ACTIONS : FEATURE_ACTIONS;
444
+ if (feature === "antispam" && typeof value === "string" && value.trim().toUpperCase() === "DELETE") {
445
+ errors.push(error("features.antispam", "enum", "features.antispam must be WARN, KICK, or null"));
446
+ continue;
447
+ }
448
+ const action = checkEnum(errors, `features.${feature}`, value, feature === "antispam" ? SPAM_ACTIONS : allowed);
449
+ if (action) features[feature] = action;
450
+ }
451
+ if (Object.keys(features).length) stored.features = features;
452
+ }
453
+ if (Object.prototype.hasOwnProperty.call(merged, "hitMerge")) {
454
+ const merge = checkEnum(errors, "hitMerge", merged.hitMerge, MERGES);
455
+ if (merge) stored.hitMerge = merge;
456
+ }
457
+ if (merged.weights && Object.keys(merged.weights).length) {
458
+ const weights = {};
459
+ for (const [feature, value] of Object.entries(merged.weights)) {
460
+ if (checkInteger(errors, `weights.${feature}`, value, 1, 10)) weights[feature] = value;
461
+ }
462
+ if (Object.keys(weights).length) stored.weights = weights;
463
+ }
464
+ if (Object.prototype.hasOwnProperty.call(merged, "flagAt")) {
465
+ if (checkInteger(errors, "flagAt", merged.flagAt, 1, 49)) stored.flagAt = merged.flagAt;
466
+ }
467
+ if (Object.prototype.hasOwnProperty.call(merged, "kickAt")) {
468
+ if (checkInteger(errors, "kickAt", merged.kickAt, 2, 50)) stored.kickAt = merged.kickAt;
469
+ }
470
+ if (merged.decay && Object.keys(merged.decay).length) {
471
+ const decay = {};
472
+ if (Object.prototype.hasOwnProperty.call(merged.decay, "mode")) {
473
+ const mode = checkEnum(errors, "decay.mode", merged.decay.mode, DECAY_MODES);
474
+ if (mode) decay.mode = mode;
475
+ }
476
+ if (Object.prototype.hasOwnProperty.call(merged.decay, "days")) {
477
+ if (checkInteger(errors, "decay.days", merged.decay.days, 1, 365)) decay.days = merged.decay.days;
478
+ }
479
+ if (Object.keys(decay).length) stored.decay = decay;
480
+ }
481
+ if (Object.prototype.hasOwnProperty.call(merged, "membership")) {
482
+ const membership = checkEnum(errors, "membership", merged.membership, MEMBERSHIPS);
483
+ if (membership) stored.membership = membership;
484
+ }
485
+ if (merged.flag && Object.keys(merged.flag).length) {
486
+ const flag = {};
487
+ if (Object.prototype.hasOwnProperty.call(merged.flag, "notify")) {
488
+ const notify = checkEnum(errors, "flag.notify", merged.flag.notify, NOTIFIES);
489
+ if (notify) flag.notify = notify;
490
+ }
491
+ if (Object.prototype.hasOwnProperty.call(merged.flag, "mentionAdmins")) {
492
+ if (merged.flag.mentionAdmins !== true && merged.flag.mentionAdmins !== false) {
493
+ errors.push(error("flag.mentionAdmins", "type", "flag.mentionAdmins must be true or false"));
494
+ } else flag.mentionAdmins = merged.flag.mentionAdmins;
495
+ }
496
+ if (Object.prototype.hasOwnProperty.call(merged.flag, "cooldownMinutes")) {
497
+ if (checkInteger(errors, "flag.cooldownMinutes", merged.flag.cooldownMinutes, 0, 10080)) {
498
+ flag.cooldownMinutes = merged.flag.cooldownMinutes;
499
+ }
500
+ }
501
+ if (Object.prototype.hasOwnProperty.call(merged.flag, "whileFlagged")) {
502
+ const whileFlagged = checkEnum(errors, "flag.whileFlagged", merged.flag.whileFlagged, WHILE_FLAGGED);
503
+ if (whileFlagged) flag.whileFlagged = whileFlagged;
504
+ }
505
+ if (Object.prototype.hasOwnProperty.call(merged.flag, "escalateAfter")) {
506
+ if (checkInteger(errors, "flag.escalateAfter", merged.flag.escalateAfter, 1, 50)) {
507
+ flag.escalateAfter = merged.flag.escalateAfter;
508
+ }
509
+ }
510
+ if (Object.keys(flag).length) stored.flag = flag;
511
+ }
512
+
513
+ if (errors.length) return { ok: false, errors };
514
+
515
+ const effective = resolveModerationPolicy({ ...current, moderationPolicy: stored });
516
+ if (effective.mode === "severity" && effective.kickAt <= effective.flagAt) {
517
+ errors.push(error("kickAt", "conflict", "kickAt must be greater than flagAt"));
518
+ }
519
+ if (effective.mode === "severity" && effective.flag.whileFlagged === "escalate") {
520
+ errors.push(error("flag.whileFlagged", "conflict", "escalate is not available when mode is severity"));
521
+ }
522
+ const setsFlag = isPlainObject(patch.flag) && Object.keys(patch.flag).length > 0;
523
+ if (effective.mode === "simple" && effective.limitAction === "KICK" && setsFlag) {
524
+ errors.push(
525
+ error("flag", "conflict", "flag settings do not apply when the limit removes the member"),
526
+ );
527
+ }
528
+ if (errors.length) return { ok: false, errors };
529
+ return { ok: true, stored, effective, visibility: policyFieldVisibility(effective) };
530
+ }
531
+
532
+ function ensureWarn(settings) {
533
+ if (!isPlainObject(settings.warn_system)) settings.warn_system = {};
534
+ return settings.warn_system;
535
+ }
536
+
537
+ function featureBucket(settings, feature, create) {
538
+ if (feature === "antilink") {
539
+ if (create && !isPlainObject(settings.antilink)) {
540
+ settings.antilink = { enabled: false, mode: "ALL", allowed_domains: [], blocked_domains: [] };
541
+ }
542
+ return settings.antilink;
543
+ }
544
+ if (feature === "media") {
545
+ if (create && !isPlainObject(settings.media_control)) {
546
+ settings.media_control = { enabled: false, blocked_types: [] };
547
+ }
548
+ return settings.media_control;
549
+ }
550
+ if (feature === "antispam") {
551
+ if (create && !isPlainObject(settings.antispam)) {
552
+ settings.antispam = { enabled: false, message_count: 5, time_window: 10 };
553
+ }
554
+ return settings.antispam;
555
+ }
556
+ if (create) {
557
+ settings.moderation ||= {};
558
+ settings.moderation.forbiddenWords ||= { enabled: false, list: [] };
559
+ }
560
+ return settings.moderation?.forbiddenWords;
561
+ }
562
+
563
+ function mirrorStored(settings, stored, patch) {
564
+ const next = settings;
565
+ next.moderationPolicy = stored;
566
+ if (patch && Object.prototype.hasOwnProperty.call(patch, "limit")) {
567
+ ensureWarn(next).max_warnings = stored.limit;
568
+ }
569
+ if (patch && Object.prototype.hasOwnProperty.call(patch, "limitAction")) {
570
+ ensureWarn(next).action = stored.limitAction;
571
+ }
572
+ if (patch?.features) {
573
+ for (const [feature, action] of Object.entries(patch.features)) {
574
+ const bucket = featureBucket(next, feature, action != null);
575
+ if (!bucket) continue;
576
+ if (action == null) delete bucket.action;
577
+ else bucket.action = action;
578
+ }
579
+ }
580
+ return next;
581
+ }
582
+
583
+ function stripEnforcement(settings) {
584
+ delete settings.moderationPolicy;
585
+ if (isPlainObject(settings.warn_system)) {
586
+ delete settings.warn_system.action;
587
+ delete settings.warn_system.max_warnings;
588
+ }
589
+ for (const feature of FEATURES) {
590
+ const bucket = featureBucket(settings, feature, false);
591
+ if (bucket) delete bucket.action;
592
+ }
593
+ return settings;
594
+ }
595
+
596
+ function projectPreset(settings, name) {
597
+ const preset = String(name || "").trim().toLowerCase();
598
+ if (preset === "standard") return stripEnforcement(settings);
599
+ const patch = preset === "relaxed" ? RELAXED : preset === "strict" ? STRICT : null;
600
+ if (!patch) {
601
+ throw new ModerationPolicyError([
602
+ error("moderation_preset", "enum", "moderation_preset must be relaxed, standard, or strict"),
603
+ ]);
604
+ }
605
+ const bare = { ...settings };
606
+ delete bare.moderationPolicy;
607
+ const validated = validateModerationPolicy(patch, bare);
608
+ if (!validated.ok) throw new ModerationPolicyError(validated.errors);
609
+ stripEnforcement(settings);
610
+ return mirrorStored(settings, validated.stored, patch);
611
+ }
612
+
613
+ function applyModerationPolicy(groupId, patch) {
614
+ const current = getGroupSettings(groupId) || {};
615
+ const validated = validateModerationPolicy(patch, current);
616
+ if (!validated.ok) throw new ModerationPolicyError(validated.errors);
617
+ const settings = mirrorStored(current, validated.stored, patch);
618
+ saveGroupSettings(groupId, settings);
619
+ return { effective: validated.effective, settings };
620
+ }
621
+
622
+ function applyModerationPreset(groupId, name) {
623
+ const current = getGroupSettings(groupId) || {};
624
+ const settings = projectPreset(current, name);
625
+ saveGroupSettings(groupId, settings);
626
+ const effective = resolveModerationPolicy(settings);
627
+ return { effective, settings };
628
+ }
629
+
630
+ function readModerationPolicy(groupId) {
631
+ return describeModerationPolicy(getGroupSettings(groupId) || {});
632
+ }
633
+
634
+ function describeModerationPolicy(settings) {
635
+ const source = isPlainObject(settings) ? settings : {};
636
+ const stored = isPlainObject(source.moderationPolicy) ? source.moderationPolicy : {};
637
+ const effective = resolveModerationPolicy(source);
638
+ return { effective, stored, visibility: policyFieldVisibility(effective) };
639
+ }
640
+
641
+ function cloneSettings(settings) {
642
+ try {
643
+ return JSON.parse(JSON.stringify(settings || {}));
644
+ } catch {
645
+ return {};
646
+ }
647
+ }
648
+
649
+ function normalizeLegacyAction(raw, allowDelete) {
650
+ const action = String(raw || "").trim().toUpperCase();
651
+ if (action === "NONE") return "FLAG";
652
+ if (action === "FLAG" || action === "KICK") return action;
653
+ if (action === "WARN") return "WARN";
654
+ if (allowDelete && action === "DELETE") return "DELETE";
655
+ return null;
656
+ }
657
+
658
+ function collectPolicyInputs(body) {
659
+ const errors = [];
660
+ const source = isPlainObject(body) ? body : {};
661
+ const hasPolicy = Object.prototype.hasOwnProperty.call(source, "moderation_policy");
662
+ const hasPreset = Object.prototype.hasOwnProperty.call(source, "moderation_preset");
663
+ if (hasPreset && hasPolicy) {
664
+ errors.push(
665
+ error("moderation_preset", "conflict", "moderation_preset and moderation_policy cannot both be set"),
666
+ );
667
+ }
668
+ let preset = null;
669
+ if (hasPreset && !hasPolicy) {
670
+ preset = String(source.moderation_preset || "").trim().toLowerCase();
671
+ if (!PRESET_NAMES.includes(preset)) {
672
+ errors.push(
673
+ error("moderation_preset", "enum", "moderation_preset must be relaxed, standard, or strict"),
674
+ );
675
+ preset = null;
676
+ }
677
+ }
678
+ let policy = {};
679
+ if (hasPolicy) {
680
+ if (!isPlainObject(source.moderation_policy)) {
681
+ errors.push(error("moderation_policy", "type", "moderation_policy must be an object"));
682
+ } else policy = source.moderation_policy;
683
+ }
684
+
685
+ const legacy = {};
686
+ if (source.warn_system && Object.prototype.hasOwnProperty.call(source.warn_system, "max_warnings")) {
687
+ const max = source.warn_system.max_warnings;
688
+ if (!isInteger(max)) legacy.limitError = error("warn_system.max_warnings", "type", "max_warnings must be an integer from 1 to 50");
689
+ else if (max < 1 || max > 50) {
690
+ legacy.limitError = error("warn_system.max_warnings", "range", "max_warnings must be between 1 and 50");
691
+ } else legacy.limit = max;
692
+ }
693
+ if (source.warn_system && Object.prototype.hasOwnProperty.call(source.warn_system, "action")) {
694
+ const action = normalizeLegacyAction(source.warn_system.action, false);
695
+ if (!action || action === "WARN" || action === "DELETE") {
696
+ legacy.limitActionError = error("warn_system.action", "enum", "Unknown warn action");
697
+ } else legacy.limitAction = action;
698
+ }
699
+ const featureSources = [
700
+ ["antilink", source.antilink?.action, Object.prototype.hasOwnProperty.call(source.antilink || {}, "action"), true],
701
+ ["media", source.media_control?.action, Object.prototype.hasOwnProperty.call(source.media_control || {}, "action"), true],
702
+ ["forbidden", source.forbidden_words?.action, Object.prototype.hasOwnProperty.call(source.forbidden_words || {}, "action"), true],
703
+ ["antispam", source.antispam?.action, Object.prototype.hasOwnProperty.call(source.antispam || {}, "action"), false],
704
+ ];
705
+ for (const [feature, raw, present, allowDelete] of featureSources) {
706
+ if (!present) continue;
707
+ const action = normalizeLegacyAction(raw, allowDelete);
708
+ const allowed = allowDelete ? "DELETE, WARN, KICK" : "WARN, KICK";
709
+ if (!action || (feature !== "antispam" && action === "FLAG") || (feature === "antispam" && action === "DELETE")) {
710
+ legacy[`${feature}Error`] = error(
711
+ feature === "forbidden" ? "forbidden_words.action" : `${feature}.action`,
712
+ "enum",
713
+ `Unknown ${feature} action. Available: ${allowed}`,
714
+ );
715
+ } else {
716
+ legacy.features ||= {};
717
+ legacy.features[feature] = action === "FLAG" ? null : action;
718
+ }
719
+ }
720
+
721
+ if (legacy.limitError) errors.push(legacy.limitError);
722
+ if (legacy.limitActionError) errors.push(legacy.limitActionError);
723
+ for (const feature of FEATURES) {
724
+ if (legacy[`${feature}Error`]) errors.push(legacy[`${feature}Error`]);
725
+ }
726
+
727
+ const patch = hasPolicy ? { ...policy } : {};
728
+ if (isPlainObject(policy.features)) patch.features = { ...policy.features };
729
+ if (isPlainObject(policy.weights)) patch.weights = { ...policy.weights };
730
+ if (isPlainObject(policy.decay)) patch.decay = { ...policy.decay };
731
+ if (isPlainObject(policy.flag)) patch.flag = { ...policy.flag };
732
+
733
+ const disagree = (field, left, right) => {
734
+ errors.push(error(field, "conflict", `${field} is set to two different values`));
735
+ return left !== right;
736
+ };
737
+ if (legacy.limit !== undefined) {
738
+ if (patch.limit !== undefined && patch.limit !== legacy.limit) disagree("limit", patch.limit, legacy.limit);
739
+ else patch.limit = legacy.limit;
740
+ }
741
+ if (legacy.limitAction !== undefined) {
742
+ if (patch.limitAction !== undefined && canonEnum(String(patch.limitAction), LIMIT_ACTIONS) !== legacy.limitAction) {
743
+ disagree("limitAction", patch.limitAction, legacy.limitAction);
744
+ } else patch.limitAction = legacy.limitAction;
745
+ }
746
+ if (legacy.features) {
747
+ patch.features ||= {};
748
+ for (const [feature, action] of Object.entries(legacy.features)) {
749
+ const current = patch.features[feature];
750
+ if (current !== undefined && canonEnum(String(current), FEATURE_ACTIONS.concat(SPAM_ACTIONS)) !== action && current !== action) {
751
+ disagree(`features.${feature}`, current, action);
752
+ } else patch.features[feature] = action;
753
+ }
754
+ }
755
+
756
+ const legacyPresent =
757
+ legacy.limit !== undefined ||
758
+ legacy.limitAction !== undefined ||
759
+ (legacy.features && Object.keys(legacy.features).length > 0);
760
+ if (hasPreset && legacyPresent) {
761
+ errors.push(
762
+ error("moderation_preset", "conflict", "moderation_preset and a legacy action cannot both be set"),
763
+ );
764
+ }
765
+ const present = hasPolicy || hasPreset || legacyPresent;
766
+ return { errors, present, preset, patch, hasPolicy };
767
+ }
768
+
769
+ function prepareGroupModeration(settings, body) {
770
+ const inputs = collectPolicyInputs(body);
771
+ if (inputs.errors.length) return { ok: false, errors: inputs.errors };
772
+ if (!inputs.present) return { ok: true, kind: "none" };
773
+ if (inputs.preset) return { ok: true, kind: "preset", preset: inputs.preset };
774
+ const validated = validateModerationPolicy(inputs.patch, settings || {});
775
+ if (!validated.ok) return { ok: false, errors: validated.errors };
776
+ return {
777
+ ok: true,
778
+ kind: "patch",
779
+ patch: inputs.patch,
780
+ stored: validated.stored,
781
+ effective: validated.effective,
782
+ visibility: validated.visibility,
783
+ };
784
+ }
785
+
786
+ function commitPreparedModeration(settings, prepared) {
787
+ if (!prepared || prepared.kind === "none") return settings;
788
+ if (prepared.kind === "preset") return projectPreset(settings, prepared.preset);
789
+ return mirrorStored(settings, prepared.stored, prepared.patch);
790
+ }
791
+
792
+ function looseStored(base, patch) {
793
+ const stored = cleanStored(base?.moderationPolicy);
794
+ if (!isPlainObject(patch)) return stored;
795
+ const merged = { ...stored };
796
+ for (const [key, value] of Object.entries(patch)) {
797
+ if (!TOP_KEYS.includes(key)) continue;
798
+ if (key === "features" || key === "weights" || key === "decay" || key === "flag") {
799
+ if (!isPlainObject(value)) continue;
800
+ merged[key] = { ...(isPlainObject(stored[key]) ? stored[key] : {}), ...value };
801
+ } else merged[key] = value;
802
+ }
803
+ return cleanStored(merged);
804
+ }
805
+
806
+ function evaluateModerationDraft(body) {
807
+ const base = isPlainObject(body) ? cloneSettings(body) : {};
808
+ delete base.moderation_policy;
809
+ delete base.moderation_preset;
810
+ const inputs = collectPolicyInputs(body);
811
+ if (inputs.preset && !inputs.errors.length) {
812
+ const settings = projectPreset(cloneSettings(base), inputs.preset);
813
+ const described = describeModerationPolicy(settings);
814
+ return { settings, ...described, errors: [] };
815
+ }
816
+ if (!inputs.present || (inputs.errors.length && !inputs.hasPolicy && !inputs.patch)) {
817
+ const described = describeModerationPolicy(base);
818
+ return { settings: base, ...described, errors: inputs.errors };
819
+ }
820
+ const validated = validateModerationPolicy(inputs.patch || {}, base);
821
+ if (!validated.ok) {
822
+ const settings = { ...base, moderationPolicy: looseStored(base, inputs.patch) };
823
+ const effective = resolveModerationPolicy(settings);
824
+ return {
825
+ settings,
826
+ effective,
827
+ stored: settings.moderationPolicy,
828
+ visibility: policyFieldVisibility(effective),
829
+ errors: inputs.errors.length ? inputs.errors : validated.errors,
830
+ };
831
+ }
832
+ const settings = mirrorStored(cloneSettings(base), validated.stored, inputs.patch);
833
+ return {
834
+ settings,
835
+ effective: validated.effective,
836
+ stored: validated.stored,
837
+ visibility: validated.visibility,
838
+ errors: inputs.errors,
839
+ };
840
+ }
841
+
842
+ const MS_DAY = 24 * 60 * 60 * 1000;
843
+
844
+ function eventPoints(event) {
845
+ if (event && typeof event.points === "number" && Number.isInteger(event.points)) return event.points;
846
+ return 1;
847
+ }
848
+
849
+ function ageDays(date, now) {
850
+ const parsed = Date.parse(date);
851
+ if (!Number.isFinite(parsed)) return null;
852
+ return Math.floor((now - parsed) / MS_DAY);
853
+ }
854
+
855
+ function effectivePoints(events, policy, now = Date.now()) {
856
+ const list = Array.isArray(events) ? events : [];
857
+ const resolved = policy?.decay ? policy : resolveModerationPolicy(policy || {});
858
+ const mode = resolved.decay?.mode || "off";
859
+ const days = resolved.decay?.days || 30;
860
+ let total = 0;
861
+ for (const event of list) {
862
+ const points = eventPoints(event);
863
+ if (!event?.date || mode === "off") {
864
+ total += points;
865
+ continue;
866
+ }
867
+ const age = ageDays(event.date, now);
868
+ if (age == null) {
869
+ total += points;
870
+ continue;
871
+ }
872
+ if (mode === "expire") {
873
+ if (age < days) total += points;
874
+ continue;
875
+ }
876
+ if (mode === "step") total += Math.max(0, points - Math.floor(age / days));
877
+ }
878
+ return total;
879
+ }
880
+
881
+ module.exports = {
882
+ ModerationPolicyError,
883
+ resolveModerationPolicy,
884
+ validateModerationPolicy,
885
+ policyFieldVisibility,
886
+ applyModerationPolicy,
887
+ applyModerationPreset,
888
+ readModerationPolicy,
889
+ describeModerationPolicy,
890
+ prepareGroupModeration,
891
+ commitPreparedModeration,
892
+ evaluateModerationDraft,
893
+ effectivePoints,
894
+ PRESET_NAMES,
895
+ };