@chatwarden/core 0.1.8 → 0.1.9

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 (115) hide show
  1. package/README.md +184 -5
  2. package/dist/src/ai/case.d.ts +2 -1
  3. package/dist/src/ai/case.d.ts.map +1 -1
  4. package/dist/src/ai/case.js +1 -1
  5. package/dist/src/ai/case.js.map +1 -1
  6. package/dist/src/ai/hash.d.ts +1 -1
  7. package/dist/src/ai/hash.js +3 -3
  8. package/dist/src/ai/hash.js.map +1 -1
  9. package/dist/src/ai/prompt.d.ts +8 -1
  10. package/dist/src/ai/prompt.d.ts.map +1 -1
  11. package/dist/src/ai/prompt.js +20 -1
  12. package/dist/src/ai/prompt.js.map +1 -1
  13. package/dist/src/ai/service.d.ts +16 -5
  14. package/dist/src/ai/service.d.ts.map +1 -1
  15. package/dist/src/ai/service.js +12 -7
  16. package/dist/src/ai/service.js.map +1 -1
  17. package/dist/src/ai/types.d.ts +17 -2
  18. package/dist/src/ai/types.d.ts.map +1 -1
  19. package/dist/src/ai/types.js +3 -2
  20. package/dist/src/ai/types.js.map +1 -1
  21. package/dist/src/ai/worker.d.ts +5 -0
  22. package/dist/src/ai/worker.d.ts.map +1 -1
  23. package/dist/src/ai/worker.js +9 -2
  24. package/dist/src/ai/worker.js.map +1 -1
  25. package/dist/src/appealService.d.ts +105 -0
  26. package/dist/src/appealService.d.ts.map +1 -0
  27. package/dist/src/appealService.js +548 -0
  28. package/dist/src/appealService.js.map +1 -0
  29. package/dist/src/appeals.d.ts +194 -0
  30. package/dist/src/appeals.d.ts.map +1 -0
  31. package/dist/src/appeals.js +107 -0
  32. package/dist/src/appeals.js.map +1 -0
  33. package/dist/src/audit.d.ts +7 -3
  34. package/dist/src/audit.d.ts.map +1 -1
  35. package/dist/src/audit.js +18 -3
  36. package/dist/src/audit.js.map +1 -1
  37. package/dist/src/chatwarden.d.ts +129 -9
  38. package/dist/src/chatwarden.d.ts.map +1 -1
  39. package/dist/src/chatwarden.js +94 -19
  40. package/dist/src/chatwarden.js.map +1 -1
  41. package/dist/src/decide.d.ts +2 -0
  42. package/dist/src/decide.d.ts.map +1 -1
  43. package/dist/src/decide.js +12 -7
  44. package/dist/src/decide.js.map +1 -1
  45. package/dist/src/documents.d.ts +1 -1
  46. package/dist/src/documents.d.ts.map +1 -1
  47. package/dist/src/documents.js +3 -1
  48. package/dist/src/documents.js.map +1 -1
  49. package/dist/src/events.d.ts +38 -0
  50. package/dist/src/events.d.ts.map +1 -1
  51. package/dist/src/events.js +3 -0
  52. package/dist/src/events.js.map +1 -1
  53. package/dist/src/index.d.ts +9 -5
  54. package/dist/src/index.d.ts.map +1 -1
  55. package/dist/src/index.js +5 -2
  56. package/dist/src/index.js.map +1 -1
  57. package/dist/src/nameService.d.ts +90 -0
  58. package/dist/src/nameService.d.ts.map +1 -0
  59. package/dist/src/nameService.js +224 -0
  60. package/dist/src/nameService.js.map +1 -0
  61. package/dist/src/names.d.ts +68 -0
  62. package/dist/src/names.d.ts.map +1 -0
  63. package/dist/src/names.js +87 -0
  64. package/dist/src/names.js.map +1 -0
  65. package/dist/src/notices.d.ts +53 -5
  66. package/dist/src/notices.d.ts.map +1 -1
  67. package/dist/src/notices.js +93 -8
  68. package/dist/src/notices.js.map +1 -1
  69. package/dist/src/policy.d.ts +9 -0
  70. package/dist/src/policy.d.ts.map +1 -1
  71. package/dist/src/policy.js +20 -2
  72. package/dist/src/policy.js.map +1 -1
  73. package/dist/src/profile.d.ts +23 -1
  74. package/dist/src/profile.d.ts.map +1 -1
  75. package/dist/src/profile.js +14 -2
  76. package/dist/src/profile.js.map +1 -1
  77. package/dist/src/retention.d.ts +31 -1
  78. package/dist/src/retention.d.ts.map +1 -1
  79. package/dist/src/retention.js +41 -3
  80. package/dist/src/retention.js.map +1 -1
  81. package/dist/src/sanctions.d.ts +29 -1
  82. package/dist/src/sanctions.d.ts.map +1 -1
  83. package/dist/src/sanctions.js +52 -9
  84. package/dist/src/sanctions.js.map +1 -1
  85. package/dist/src/staffViews.d.ts +18 -0
  86. package/dist/src/staffViews.d.ts.map +1 -1
  87. package/dist/src/staffViews.js +14 -0
  88. package/dist/src/staffViews.js.map +1 -1
  89. package/dist/src/types.d.ts +198 -6
  90. package/dist/src/types.d.ts.map +1 -1
  91. package/dist/src/types.js.map +1 -1
  92. package/package.json +2 -2
  93. package/src/ai/case.ts +4 -2
  94. package/src/ai/hash.ts +3 -3
  95. package/src/ai/prompt.ts +23 -1
  96. package/src/ai/service.ts +21 -12
  97. package/src/ai/types.ts +14 -2
  98. package/src/ai/worker.ts +10 -2
  99. package/src/appealService.ts +584 -0
  100. package/src/appeals.ts +256 -0
  101. package/src/audit.ts +18 -3
  102. package/src/chatwarden.ts +199 -21
  103. package/src/decide.ts +13 -7
  104. package/src/documents.ts +6 -3
  105. package/src/events.ts +23 -1
  106. package/src/index.ts +12 -1
  107. package/src/nameService.ts +255 -0
  108. package/src/names.ts +121 -0
  109. package/src/notices.ts +112 -14
  110. package/src/policy.ts +20 -3
  111. package/src/profile.ts +34 -2
  112. package/src/retention.ts +63 -3
  113. package/src/sanctions.ts +72 -9
  114. package/src/staffViews.ts +30 -0
  115. package/src/types.ts +210 -7
package/src/decide.ts CHANGED
@@ -6,7 +6,7 @@ import { safeWarn } from './log.js';
6
6
  import { ownLines } from './notices.js';
7
7
  import type { NoticeService } from './notices.js';
8
8
  import type { CommunityRules, RuleRef } from './rules.js';
9
- import { SANCTION_KINDS, SANCTION_SOURCES, validateSanctionInput, writeSanction } from './sanctions.js';
9
+ import { APPEALS_START_TOKEN, SANCTION_KINDS, SANCTION_SOURCES, validateSanctionInput, writeSanction } from './sanctions.js';
10
10
  import type { SanctionIndex } from './sanctions.js';
11
11
  import type { SubjectIndex } from './subjects.js';
12
12
  import { CONDUCT_LEVELS } from './types.js';
@@ -480,7 +480,7 @@ export class DecisionService {
480
480
  });
481
481
  }
482
482
 
483
- private sanctionInput(norm: Normal, a: NormalAction, roomId: string) {
483
+ private sanctionInput(norm: Normal, a: NormalAction, roomId: string, reportId?: string) {
484
484
  return {
485
485
  kind: a.kind,
486
486
  subject: a.subject,
@@ -493,6 +493,8 @@ export class DecisionService {
493
493
  rule: a.rule,
494
494
  roomId: roomId === '' ? null : roomId,
495
495
  ...(a.gapNote === undefined ? {} : { gapNote: a.gapNote }),
496
+ // The report this decision closes: a granted appeal against the sanction marks that decision reversed.
497
+ ...(reportId === undefined ? {} : { reportId, startsAtToken: APPEALS_START_TOKEN }),
496
498
  };
497
499
  }
498
500
 
@@ -513,7 +515,7 @@ export class DecisionService {
513
515
  const told = new Set<SubjectId>();
514
516
  for (const { action: a, lines } of plan) {
515
517
  // No index here: the rows reach it only after the transaction has committed.
516
- const written = writeSanction(this.store, this.subjects, this.sanctionInput(norm, a, report.roomId), now, pending);
518
+ const written = writeSanction(this.store, this.subjects, this.sanctionInput(norm, a, report.roomId, report.id), now, pending);
517
519
  // A note is on the record and tells the player nothing: no notice, so nobody to announce to either.
518
520
  const noticeId =
519
521
  a.kind === 'note'
@@ -629,6 +631,8 @@ export interface RevokeDeps {
629
631
  clock: Clock;
630
632
  /** Dropped from once the revoke has committed. */
631
633
  index?: SanctionIndex;
634
+ /** True when `retention.appealStatementsMs` is 0: the statement of an appeal this revoke makes moot is cleared with it. */
635
+ clearAppealStatements?: () => boolean;
632
636
  }
633
637
 
634
638
  /**
@@ -646,10 +650,12 @@ export function revokeAndWithdraw(
646
650
  ): Promise<{ revoked: boolean; withdrawn: number }> {
647
651
  try {
648
652
  const now = deps.clock.now();
649
- const out = store.transaction(() => ({
650
- revoked: store.revokeSanctionGroup(groupId, actor, now, reason) > 0,
651
- withdrawn: deps.notices.withdrawGroup(groupId),
652
- }));
653
+ const out = store.transaction(() => {
654
+ const revoked = store.revokeSanctionGroup(groupId, actor, now, reason) > 0;
655
+ // An appeal still open against this group is moot now (same transaction: both land or neither).
656
+ if (revoked) store.closeAppealsForGroup?.(groupId, actor, now, deps.clearAppealStatements?.() === true);
657
+ return { revoked, withdrawn: deps.notices.withdrawGroup(groupId) };
658
+ });
653
659
  deps.index?.remove(groupId);
654
660
  return Promise.resolve(out);
655
661
  } catch (err) {
package/src/documents.ts CHANGED
@@ -53,7 +53,7 @@ export interface ModeratorGuideOptions {
53
53
  export interface PolicyJson {
54
54
  version: 1;
55
55
  /** With `durations` and `customDuration` filled in, so a profile written for 0.1.1 reads back with the two new keys. */
56
- profile: Omit<ResolvedProfile, 'ai' | 'pace' | 'signals'>;
56
+ profile: Omit<ResolvedProfile, 'ai' | 'pace' | 'signals' | 'appeals' | 'names'>;
57
57
  /** Every rule, retired ones included, in number order. */
58
58
  rules: CommunityRule[];
59
59
  }
@@ -705,11 +705,14 @@ export function agentBrief(policy: DocumentPolicy): string {
705
705
  */
706
706
  export function policyJson(policy: DocumentPolicy): PolicyJson {
707
707
  const snapshot = checkPolicy(policy);
708
- // The AI settings, the pace settings and the signal settings are runtime switches, not policy text: the document tools never carry them.
709
- const profile: Omit<ResolvedProfile, 'ai' | 'pace' | 'signals'> & { ai?: unknown; pace?: unknown; signals?: unknown } = structuredClone(snapshot.profile);
708
+ // The AI, pace, signal, appeal and name settings are runtime switches, not policy text: the document tools never carry them.
709
+ const profile: Omit<ResolvedProfile, 'ai' | 'pace' | 'signals' | 'appeals' | 'names'> & { ai?: unknown; pace?: unknown; signals?: unknown; appeals?: unknown; names?: unknown } =
710
+ structuredClone(snapshot.profile);
710
711
  delete profile.ai;
711
712
  delete profile.pace;
712
713
  delete profile.signals;
714
+ delete profile.appeals;
715
+ delete profile.names;
713
716
  return { version: 1, profile, rules: snapshot.rules.all() };
714
717
  }
715
718
 
package/src/events.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { safeWarn } from './log.js';
2
+ import type { AppealOutcome } from './appeals.js';
2
3
  import type { RuleRef } from './rules.js';
3
4
  import type { Logger, ReportCategory, SanctionKind, Source, SubjectId } from './types.js';
4
5
 
@@ -67,7 +68,25 @@ export type KitEvent =
67
68
  * person who was timed out (canonical at emit time).
68
69
  * Carries subject ids: staff channels only, never send to a player.
69
70
  */
70
- | { type: 'auto.restricted'; groupId: string; refCode: string; second: boolean; subject: StaffRef };
71
+ | { type: 'auto.restricted'; groupId: string; refCode: string; second: boolean; subject: StaffRef }
72
+ /**
73
+ * A player filed an appeal against a sanction. `target` is the person (canonical at emit time), `kind` the sanction's kind and `rule`
74
+ * the Community Rule it cited. Like `report.created` it carries ids, codes and times, never the statement or the player's handle.
75
+ * Carries subject ids: staff channels only, never send to a player. @experimental
76
+ */
77
+ | { type: 'appeal.created'; appealId: string; createdAt: number; target: StaffRef; kind: SanctionKind; rule: RuleRef | null }
78
+ /**
79
+ * A moderator decided an appeal: `outcome` is uphold, reduce or revoke. Never the reason, the statement or a handle; an appeal made
80
+ * moot by someone else's revoke announces nothing.
81
+ * Carries subject ids: staff channels only, never send to a player. @experimental
82
+ */
83
+ | { type: 'appeal.decided'; appealId: string; at: number; target: StaffRef; outcome: AppealOutcome; rule: RuleRef | null }
84
+ /**
85
+ * A moderator required a rename. It names no name and no reason: the game learns who to rename through `cw.people.accountIds(target)`
86
+ * or a webhook that opted in to accounts.
87
+ * Carries subject ids: staff channels only, never send to a player. @experimental
88
+ */
89
+ | { type: 'rename.required'; at: number; target: StaffRef; rule: RuleRef | null };
71
90
 
72
91
  /** Every event type, for checking a subscription. */
73
92
  export const KIT_EVENT_TYPES: readonly KitEvent['type'][] = [
@@ -77,6 +96,9 @@ export const KIT_EVENT_TYPES: readonly KitEvent['type'][] = [
77
96
  'sanction.revoked',
78
97
  'gap.created',
79
98
  'auto.restricted',
99
+ 'appeal.created',
100
+ 'appeal.decided',
101
+ 'rename.required',
80
102
  ];
81
103
 
82
104
  /** The event of a type. */
package/src/index.ts CHANGED
@@ -1,4 +1,4 @@
1
- export const VERSION = '0.1.8';
1
+ export const VERSION = '0.1.9';
2
2
 
3
3
  export type {
4
4
  Clock,
@@ -47,6 +47,8 @@ export type {
47
47
  ReasonRow,
48
48
  SignalRow,
49
49
  SignalSourceRow,
50
+ AppealRow,
51
+ BlockedNameRow,
50
52
  ConductLevel,
51
53
  Source,
52
54
  Store,
@@ -192,6 +194,7 @@ export type { ReporterAccuracy } from './reporterAccuracy.js';
192
194
  export type {
193
195
  BlockedDays,
194
196
  BlockedItem,
197
+ BlockedNameItem,
195
198
  PersonSanctionView,
196
199
  ReporterRecord,
197
200
  SanctionGroupView,
@@ -228,6 +231,7 @@ export { WEBHOOK_KEY_TTL_MS } from './types.js';
228
231
  export type { PurgeResult, RetentionPolicy } from './retention.js';
229
232
  export {
230
233
  ExcerptError,
234
+ MESSAGE_NOTICE_KINDS,
231
235
  NOTICE_EXCERPT_MAX,
232
236
  NOTICE_RECORD_WINDOW_MS,
233
237
  NoticeService,
@@ -236,6 +240,8 @@ export {
236
240
  } from './notices.js';
237
241
  export type {
238
242
  ExcerptErrorCode,
243
+ MessageNoticeKind,
244
+ MessageNoticeOptions,
239
245
  NoticeCreateOptions,
240
246
  NoticeServiceDeps,
241
247
  PlayerNotice,
@@ -321,6 +327,11 @@ export {
321
327
  // Pace settings (@experimental): slow mode, burst limit and repeat refusal, all off until set.
322
328
  export { DUPLICATE_MIN_CHARS, DUPLICATE_RECENT, mergePace, PACE_KEYS_MAX, PACE_REASONS, PACE_SUGGESTIONS, resolvePace } from './pace.js';
323
329
  export type { PaceReason, PaceSettings, ResolvedPace } from './pace.js';
330
+ // Appeals and names settings (@experimental): off until set (names masking in the hub is the one default-on setting).
331
+ export { APPEAL_OUTCOMES, APPEAL_RATE_ELEVATED, APPEAL_RATE_HIGH, APPEAL_STATEMENT_MAX, APPEAL_STATS_MIN_SANCTIONS, normalizeStatement, resolveAppeals, SANCTION_KIND_ORDER, statementLength } from './appeals.js';
332
+ export type { AppealDecideResult, AppealDecision, AppealDetail, AppealFileResult, AppealOutcome, AppealPage, AppealRuleStats, AppealStats, AppealSummary, AppealRefusal, AppealSettings, AppealStatus, PlayerAppeal, ResolvedAppeals } from './appeals.js';
333
+ export { resolveNames } from './names.js';
334
+ export type { NameCheckResult, NameReason, NameSettings, ResolvedNames } from './names.js';
324
335
  // Signals (@experimental): kinds a game declares, the guards, and the feeds that say where counts may be read.
325
336
  export {
326
337
  BUILTIN_SIGNAL_KINDS,
@@ -0,0 +1,255 @@
1
+ import { isValidAuditActor } from './audit.js';
2
+ import { randomId } from './crypto.js';
3
+ import type { KitEvent } from './events.js';
4
+ import { hashWho } from './hasher.js';
5
+ import { safeWarn, ThrottledWarn } from './log.js';
6
+ import { DECISION_REASON_MAX } from './decide.js';
7
+ import { evidenceName, NameEvidenceLimiter, profanityView } from './names.js';
8
+ import type { NameCheckResult, NameReason, ResolvedNames } from './names.js';
9
+ import type { NoticeService } from './notices.js';
10
+ import type { CommunityRules } from './rules.js';
11
+ import type { SubjectIndex } from './subjects.js';
12
+ import type { Clock, Hasher, Logger, Matcher, ProfanityFilter, RawWho, Store, SubjectId } from './types.js';
13
+
14
+ // The name check behind `cw.names`: the matcher, an optional profanity pass, optional kept evidence (capped), and the evidence-free
15
+ // `flagged` read for staff paths. A name is never logged and never echoed; the answer carries a reason id and a rule number.
16
+
17
+ export interface NameServiceDeps {
18
+ store: Store;
19
+ clock: Clock;
20
+ logger: Logger | undefined;
21
+ hasher: Hasher;
22
+ /** The slur filter's rule (`autoRestrictRule`): what a refusal cites. */
23
+ rule: number;
24
+ matcher: Matcher | undefined;
25
+ /** The settings in force now (read on every call: a policy change takes effect at once). */
26
+ settings: () => ResolvedNames;
27
+ /** The profanity filter for names, or undefined when there is none. May throw (a package that cannot build one). */
28
+ filter: () => ProfanityFilter | undefined;
29
+ /** The person behind a caller, FOUND and never created. */
30
+ personOf: (who: RawWho) => SubjectId | null;
31
+ /** Required renames are notices of kind `rename_required`. */
32
+ notices: NoticeService;
33
+ /** Who is who: a person the kit holds, and the surviving id of an alias. */
34
+ subjects: SubjectIndex;
35
+ /** The rule a rename may cite must be active here. */
36
+ rules: CommunityRules;
37
+ /** Raise an event after the write has committed. */
38
+ emit: (event: KitEvent) => void;
39
+ }
40
+
41
+ /** What `requireRename` answers. */
42
+ export type RenameResult = { ok: true; noticeId: string } | { ok: false; error: 'off' | 'not_found' | 'pending' | 'invalid' };
43
+
44
+ /** The shape of a rename request, once checked. */
45
+ interface CheckedRename {
46
+ subject: SubjectId;
47
+ rule: number;
48
+ }
49
+
50
+ /**
51
+ * The longest private reason a required rename takes, in characters: the decision's limit, one constant for every private reason. (Defined here,
52
+ * not in `names.ts`: the profile imports that file and the decision module imports the profile, so the other way round is a cycle.)
53
+ */
54
+ export const RENAME_REASON_MAX = DECISION_REASON_MAX;
55
+
56
+ /** The most rename requests `renamesOf` lists. */
57
+ const RENAMES_OF_MAX = 20;
58
+
59
+ const errName = (err: unknown): string => (err instanceof Error ? err.name : typeof err);
60
+
61
+ /** Why a name is refused, and the matcher's term id for a `name_not_allowed`. */
62
+ interface Verdict {
63
+ reason: NameReason;
64
+ termId: string | null;
65
+ }
66
+
67
+ export class NameService {
68
+ private readonly d: NameServiceDeps;
69
+ private readonly limiter = new NameEvidenceLimiter();
70
+ private readonly flaggedWarn: ThrottledWarn;
71
+ private readonly evidenceWarn: ThrottledWarn;
72
+
73
+ constructor(deps: NameServiceDeps) {
74
+ this.d = deps;
75
+ this.flaggedWarn = new ThrottledWarn(deps.logger, deps.clock);
76
+ this.evidenceWarn = new ThrottledWarn(deps.logger, deps.clock);
77
+ }
78
+
79
+ check(text: string, opts?: { who?: RawWho }): NameCheckResult {
80
+ if (typeof text !== 'string') throw new TypeError('names.check: the name must be a string');
81
+ const verdict = this.verdict(text);
82
+ if (verdict === null) return { ok: true };
83
+ this.keep(text, verdict, opts);
84
+ return { ok: false, reason: verdict.reason, rule: this.d.rule };
85
+ }
86
+
87
+ /** The matcher's reading alone: no profanity, no store, no person. False for anything it cannot read. Never throws. */
88
+ flagged(text: string): boolean {
89
+ if (typeof text !== 'string') return false;
90
+ try {
91
+ return this.matched(text) !== null;
92
+ } catch (err) {
93
+ this.flaggedWarn.warn('chatwarden.names_matcher_failed', { error: errName(err) });
94
+ return false;
95
+ }
96
+ }
97
+
98
+ /** The matcher's term id for a name it refuses, or null. Throws what the matcher throws. */
99
+ private matched(text: string): { termId: string | null } | null {
100
+ const m = this.d.matcher;
101
+ if (m === undefined) return null;
102
+ const hit = typeof m.matchName === 'function' ? m.matchName(text) : m.match(text);
103
+ if (hit === null || hit === undefined) return null;
104
+ return { termId: typeof hit.termId === 'string' ? hit.termId : null };
105
+ }
106
+
107
+ private verdict(text: string): Verdict | null {
108
+ try {
109
+ const hit = this.matched(text);
110
+ if (hit !== null) return { reason: 'name_not_allowed', termId: hit.termId };
111
+ } catch (err) {
112
+ safeWarn(this.d.logger, 'chatwarden.names_matcher_failed', { error: errName(err) });
113
+ }
114
+ if (!this.d.settings().profanity) return null;
115
+ try {
116
+ const filter = this.d.filter();
117
+ if (filter === undefined) return null;
118
+ if (filter.apply(text).hit) return { reason: 'name_profane', termId: null };
119
+ const spaced = profanityView(text);
120
+ if (spaced !== text && filter.apply(spaced).hit) return { reason: 'name_profane', termId: null };
121
+ } catch (err) {
122
+ safeWarn(this.d.logger, 'chatwarden.names_filter_failed', { error: errName(err) });
123
+ }
124
+ return null;
125
+ }
126
+
127
+ /** Keep a blocked name as evidence, when the adopter opted in and the hourly caps allow. Fenced: nothing in here reaches the caller. */
128
+ private keep(text: string, verdict: Verdict, opts: { who?: RawWho } | undefined): void {
129
+ try {
130
+ if (!this.d.settings().keepBlocked) return;
131
+ const store = this.d.store;
132
+ if (typeof store.insertBlockedName !== 'function') {
133
+ this.evidenceWarn.warn('chatwarden.names_evidence_unavailable', {});
134
+ return;
135
+ }
136
+ const now = this.d.clock.now();
137
+ const name = evidenceName(text);
138
+ const who = this.whoOf(opts);
139
+ const subject = who === undefined ? null : this.d.personOf(who);
140
+ const key = this.keyOf(subject, who, name);
141
+ if (!this.limiter.allow(key, now)) return;
142
+ store.transaction(() => store.insertBlockedName?.({ id: randomId(), subject, name, termId: verdict.termId, reason: verdict.reason, at: now }));
143
+ this.limiter.record(key, now);
144
+ } catch (err) {
145
+ safeWarn(this.d.logger, 'chatwarden.names_evidence_failed', { error: errName(err) });
146
+ }
147
+ }
148
+
149
+ /** The caller, as far as it is usable: an object. A getter that throws is the caller's fault and is absorbed by `keep`'s fence. */
150
+ private whoOf(opts: { who?: RawWho } | undefined): RawWho | undefined {
151
+ if (typeof opts !== 'object' || opts === null) return undefined;
152
+ const who: unknown = opts.who;
153
+ return typeof who === 'object' && who !== null ? (who as RawWho) : undefined;
154
+ }
155
+
156
+ /** What the hourly cap counts a person by: the person found, else the caller's own identifiers, else the name. Never the raw values. */
157
+ private keyOf(subject: SubjectId | null, who: RawWho | undefined, name: string): string {
158
+ if (subject !== null) return `s:${subject}`;
159
+ if (who !== undefined) {
160
+ const ids = hashWho(this.d.hasher, who);
161
+ if (ids.clientKey !== null || ids.accountId !== null || ids.ipHash !== null) {
162
+ return `w:${ids.clientKey ?? ''}|${typeof ids.accountId === 'string' ? this.d.hasher.clientKey(`account:${ids.accountId}`) : ''}|${ids.ipHash ?? ''}`;
163
+ }
164
+ }
165
+ return `n:${this.d.hasher.clientKey(`name:${name.toLowerCase()}`)}`;
166
+ }
167
+
168
+ /**
169
+ * Ask a player to choose a new name: one `rename_required` notice (no name, no excerpt, no reason) and, after the write, the player's
170
+ * client is told and `rename.required` goes out. Answers, in this order: `off` (`names.renames` is false, or the store cannot release a
171
+ * rename), `invalid` (a malformed input, a reason that is not 1 to 500 characters once trimmed, a rule that is not an active integer rule),
172
+ * `not_found` (a person the kit does not hold), `pending` (an unreleased request exists, seen or not). A store failure is logged by class
173
+ * and thrown, with nothing written. The reason and the actor are validated here and kept by the staff layer's audit row, not by the notice.
174
+ */
175
+ requireRename(input: { subject: SubjectId; actor: string; reason: string; rule?: number }): RenameResult {
176
+ const d = this.d;
177
+ if (!this.renamesEnabled()) return { ok: false, error: 'off' };
178
+ const checked = this.checkRename(input);
179
+ if (checked === null) return { ok: false, error: 'invalid' };
180
+ let noticeId: string;
181
+ let person: SubjectId;
182
+ let at: number;
183
+ try {
184
+ person = d.subjects.canonical(checked.subject);
185
+ if (!d.subjects.knows(person)) return { ok: false, error: 'not_found' };
186
+ if (d.notices.renamePending(person)) return { ok: false, error: 'pending' };
187
+ at = d.clock.now();
188
+ noticeId = d.notices.createMessage(person, 'rename_required', { rule: checked.rule, notify: false });
189
+ } catch (err) {
190
+ safeWarn(d.logger, 'chatwarden.rename_failed', { error: errName(err) });
191
+ throw err;
192
+ }
193
+ // After the write: the client is told (fenced inside `announce`), then the event (a listener that throws is not the caller's problem).
194
+ d.notices.announce(person);
195
+ try {
196
+ d.emit({ type: 'rename.required', at, target: person, rule: checked.rule });
197
+ } catch (err) {
198
+ safeWarn(d.logger, 'chatwarden.event_failed', { error: errName(err) });
199
+ }
200
+ return { ok: true, noticeId };
201
+ }
202
+
203
+ /** Can a moderator ask for a rename now: the setting is on and the store can release one (the test `requireRename` applies first). */
204
+ renamesEnabled(): boolean {
205
+ return this.d.settings().renames && this.d.notices.canWithdrawOne();
206
+ }
207
+
208
+ /** A person's rename requests, newest first (at most {@link RENAMES_OF_MAX}): when, and whether one still waits. No reason, actor or rule. Staff only. */
209
+ renamesOf(subject: SubjectId): Array<{ at: number; pending: boolean }> {
210
+ if (typeof subject !== 'string' || subject === '') return [];
211
+ try {
212
+ return this.d.notices
213
+ .renameRows(subject)
214
+ .slice(0, RENAMES_OF_MAX)
215
+ .map((r) => ({ at: r.createdAt, pending: r.withdrawnAt === null }));
216
+ } catch (err) {
217
+ safeWarn(this.d.logger, 'chatwarden.rename_failed', { error: errName(err) });
218
+ return [];
219
+ }
220
+ }
221
+
222
+ /** True while the person has a required rename they have not been released from. False for anyone the kit cannot find (never creates one). */
223
+ pendingRename(who: RawWho): boolean {
224
+ return this.releaseOrRead(who, (subject) => this.d.notices.renamePending(subject));
225
+ }
226
+
227
+ /** The game says the player has a new name: withdraws their pending rename notices. True when it withdrew one. */
228
+ renamed(who: RawWho): boolean {
229
+ return this.releaseOrRead(who, (subject) => this.d.notices.withdrawRenames(subject) > 0);
230
+ }
231
+
232
+ private releaseOrRead(who: RawWho, read: (subject: SubjectId) => boolean): boolean {
233
+ if (typeof who !== 'object' || who === null) return false;
234
+ try {
235
+ const subject = this.d.personOf(who);
236
+ return subject === null ? false : read(subject);
237
+ } catch (err) {
238
+ safeWarn(this.d.logger, 'chatwarden.rename_failed', { error: errName(err) });
239
+ return false;
240
+ }
241
+ }
242
+
243
+ private checkRename(input: unknown): CheckedRename | null {
244
+ if (typeof input !== 'object' || input === null) return null;
245
+ const { subject, actor, reason, rule } = input as Record<string, unknown>;
246
+ if (typeof subject !== 'string' || subject === '') return null;
247
+ if (!isValidAuditActor(actor)) return null;
248
+ if (typeof reason !== 'string') return null;
249
+ const why = reason.trim();
250
+ if (why === '' || why.length > RENAME_REASON_MAX) return null;
251
+ if (rule === undefined) return { subject, rule: this.d.rule };
252
+ if (typeof rule !== 'number' || !Number.isSafeInteger(rule) || !this.d.rules.isCitable(rule)) return null;
253
+ return { subject, rule };
254
+ }
255
+ }
package/src/names.ts ADDED
@@ -0,0 +1,121 @@
1
+ import { ProfileError } from './profileError.js';
2
+
3
+ // The name settings: a second check (profanity), optional kept evidence, a way to require a rename, and whether the hub masks a name
4
+ // the matcher flags. Pure data and validation. Off until set, except `maskInHub`, which is on: it changes only what the hub shows.
5
+
6
+ /** Why a name was refused. `name_profane` needs `names.profanity`. @experimental */
7
+ export type NameReason = 'name_not_allowed' | 'name_profane';
8
+
9
+ /** The answer of `cw.names.check`: allowed, or a reason id and the Community Rule it cites; never the text. @experimental */
10
+ export type NameCheckResult = { ok: true } | { ok: false; reason: NameReason; rule: number };
11
+
12
+ const KEYS = ['profanity', 'keepBlocked', 'renames', 'maskInHub'] as const;
13
+
14
+ /**
15
+ * How names are checked and shown. Every field is optional.
16
+ * @experimental
17
+ */
18
+ export interface NameSettings {
19
+ /** Also refuse a name the profanity filter flags. Default false (a swear word is not a slur; this is for a family game). */
20
+ profanity?: boolean;
21
+ /** Keep a blocked name, with the term it hit, as evidence. Default false: a name check stores nothing. */
22
+ keepBlocked?: boolean;
23
+ /** May a moderator require a rename from the Person page? Default false. */
24
+ renames?: boolean;
25
+ /** Mask a name the matcher flags in the hub until a moderator shows it. Default true. */
26
+ maskInHub?: boolean;
27
+ }
28
+
29
+ /**
30
+ * What the kit reads: every field filled in.
31
+ * @experimental
32
+ */
33
+ export interface ResolvedNames {
34
+ profanity: boolean;
35
+ keepBlocked: boolean;
36
+ renames: boolean;
37
+ maskInHub: boolean;
38
+ }
39
+
40
+ function isPlain(v: unknown): v is Record<string, unknown> {
41
+ if (typeof v !== 'object' || v === null || Array.isArray(v)) return false;
42
+ const proto: unknown = Object.getPrototypeOf(v);
43
+ return proto === Object.prototype || proto === null;
44
+ }
45
+
46
+ /**
47
+ * Validate and fill. Throws ProfileError naming the field (`names.keepBlocked`), never echoing the value. `path` names the settings in
48
+ * the error (default `names`). The result is a new object that shares nothing with the input; each value is read from `input` once.
49
+ * @experimental
50
+ */
51
+ export function resolveNames(input: NameSettings | undefined, path = 'names'): ResolvedNames {
52
+ const out: ResolvedNames = { profanity: false, keepBlocked: false, renames: false, maskInHub: true };
53
+ if (input === undefined) return out;
54
+ if (!isPlain(input)) throw new ProfileError(path, 'must be an object');
55
+ for (const k of Object.keys(input)) if (!(KEYS as readonly string[]).includes(k)) throw new ProfileError(`${path}.${k}`, 'is not a known setting');
56
+ for (const k of KEYS) {
57
+ const v = Object.hasOwn(input, k) ? input[k] : undefined;
58
+ if (v === undefined) continue;
59
+ if (typeof v !== 'boolean') throw new ProfileError(`${path}.${k}`, 'must be true or false');
60
+ out[k] = v;
61
+ }
62
+ return out;
63
+ }
64
+
65
+ /** Most kept blocked names per person in an hour. */
66
+ export const NAME_EVIDENCE_PER_PERSON_HOUR = 5;
67
+ /** Most kept blocked names an hour, over everyone, in this process. */
68
+ export const NAME_EVIDENCE_PER_HOUR = 200;
69
+ /** The window both caps count over: a row leaves it exactly an hour after it was kept. */
70
+ export const NAME_EVIDENCE_WINDOW_MS = 3_600_000;
71
+ /** Most characters of a blocked name that are kept (a name is short; this bounds what a hostile caller can make the table hold). */
72
+ export const NAME_EVIDENCE_MAX_LENGTH = 200;
73
+
74
+ /** The name with underscores and digits turned into spaces: the second view the profanity filter reads (`big_snerp_99` is `big snerp `). */
75
+ export function profanityView(name: string): string {
76
+ return name.replace(/[_\p{Nd}]/gu, ' ');
77
+ }
78
+
79
+ const LONE_SURROGATE = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g;
80
+
81
+ /**
82
+ * The copy of a blocked name that is kept: NUL removed, a lone surrogate (which a database would not round-trip) replaced by U+FFFD, cut to
83
+ * {@link NAME_EVIDENCE_MAX_LENGTH} characters without leaving half an emoji. Only the first `2 * MAX` characters are even looked at.
84
+ */
85
+ export function evidenceName(name: string): string {
86
+ const head = name.slice(0, NAME_EVIDENCE_MAX_LENGTH * 2).replaceAll('\u0000', '').replace(LONE_SURROGATE, '\uFFFD');
87
+ if (head.length <= NAME_EVIDENCE_MAX_LENGTH) return head;
88
+ const cut = head.slice(0, NAME_EVIDENCE_MAX_LENGTH);
89
+ const last = cut.charCodeAt(cut.length - 1);
90
+ return last >= 0xd800 && last <= 0xdbff ? cut.slice(0, -1) : cut;
91
+ }
92
+
93
+ /**
94
+ * The hourly caps on kept blocked names: {@link NAME_EVIDENCE_PER_PERSON_HOUR} per key and {@link NAME_EVIDENCE_PER_HOUR} overall, in memory,
95
+ * over a sliding window. A key is whatever the caller counts a person by. `allow` only asks; `record` counts a row that really was kept, so a
96
+ * failed write never uses the cap. Holds at most 200 timestamps, however many names are probed. A time in the future (the clock moved back)
97
+ * no longer counts.
98
+ */
99
+ export class NameEvidenceLimiter {
100
+ private all: number[] = [];
101
+ private readonly by = new Map<string, number[]>();
102
+
103
+ allow(key: string, now: number): boolean {
104
+ this.all = this.all.filter((t) => live(t, now));
105
+ if (this.all.length >= NAME_EVIDENCE_PER_HOUR) return false;
106
+ const mine = (this.by.get(key) ?? []).filter((t) => live(t, now));
107
+ return mine.length < NAME_EVIDENCE_PER_PERSON_HOUR;
108
+ }
109
+
110
+ record(key: string, now: number): void {
111
+ this.all.push(now);
112
+ for (const [k, stamps] of this.by) {
113
+ const kept = stamps.filter((t) => live(t, now));
114
+ if (kept.length === 0) this.by.delete(k);
115
+ else this.by.set(k, kept);
116
+ }
117
+ this.by.set(key, [...(this.by.get(key) ?? []), now]);
118
+ }
119
+ }
120
+
121
+ const live = (t: number, now: number): boolean => t <= now && now - t < NAME_EVIDENCE_WINDOW_MS;