@chatwarden/core 0.1.0 → 0.1.2

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 (105) hide show
  1. package/README.md +202 -6
  2. package/dist/src/audit.d.ts +27 -5
  3. package/dist/src/audit.d.ts.map +1 -1
  4. package/dist/src/audit.js +59 -8
  5. package/dist/src/audit.js.map +1 -1
  6. package/dist/src/chat.d.ts +48 -0
  7. package/dist/src/chat.d.ts.map +1 -1
  8. package/dist/src/chat.js +94 -10
  9. package/dist/src/chat.js.map +1 -1
  10. package/dist/src/chatwarden.d.ts +209 -12
  11. package/dist/src/chatwarden.d.ts.map +1 -1
  12. package/dist/src/chatwarden.js +77 -11
  13. package/dist/src/chatwarden.js.map +1 -1
  14. package/dist/src/crypto.d.ts +22 -0
  15. package/dist/src/crypto.d.ts.map +1 -0
  16. package/dist/src/crypto.js +193 -0
  17. package/dist/src/crypto.js.map +1 -0
  18. package/dist/src/decide.d.ts.map +1 -1
  19. package/dist/src/decide.js +2 -4
  20. package/dist/src/decide.js.map +1 -1
  21. package/dist/src/documents.d.ts +12 -2
  22. package/dist/src/documents.d.ts.map +1 -1
  23. package/dist/src/documents.js +56 -34
  24. package/dist/src/documents.js.map +1 -1
  25. package/dist/src/events.d.ts +3 -0
  26. package/dist/src/events.d.ts.map +1 -1
  27. package/dist/src/events.js.map +1 -1
  28. package/dist/src/hasher.js +2 -2
  29. package/dist/src/hasher.js.map +1 -1
  30. package/dist/src/index.d.ts +21 -12
  31. package/dist/src/index.d.ts.map +1 -1
  32. package/dist/src/index.js +11 -6
  33. package/dist/src/index.js.map +1 -1
  34. package/dist/src/ladder.d.ts +2 -0
  35. package/dist/src/ladder.d.ts.map +1 -1
  36. package/dist/src/ladder.js +1 -1
  37. package/dist/src/ladder.js.map +1 -1
  38. package/dist/src/log.d.ts +16 -0
  39. package/dist/src/log.d.ts.map +1 -1
  40. package/dist/src/log.js +34 -0
  41. package/dist/src/log.js.map +1 -1
  42. package/dist/src/notices.js +2 -2
  43. package/dist/src/notices.js.map +1 -1
  44. package/dist/src/policy.d.ts +129 -0
  45. package/dist/src/policy.d.ts.map +1 -0
  46. package/dist/src/policy.js +242 -0
  47. package/dist/src/policy.js.map +1 -0
  48. package/dist/src/profile.d.ts +120 -7
  49. package/dist/src/profile.d.ts.map +1 -1
  50. package/dist/src/profile.js +295 -7
  51. package/dist/src/profile.js.map +1 -1
  52. package/dist/src/reporting.d.ts +127 -0
  53. package/dist/src/reporting.d.ts.map +1 -0
  54. package/dist/src/reporting.js +172 -0
  55. package/dist/src/reporting.js.map +1 -0
  56. package/dist/src/reports.d.ts +80 -4
  57. package/dist/src/reports.d.ts.map +1 -1
  58. package/dist/src/reports.js +122 -8
  59. package/dist/src/reports.js.map +1 -1
  60. package/dist/src/sanctions.js +3 -3
  61. package/dist/src/sanctions.js.map +1 -1
  62. package/dist/src/staffReports.d.ts +17 -5
  63. package/dist/src/staffReports.d.ts.map +1 -1
  64. package/dist/src/staffReports.js +22 -5
  65. package/dist/src/staffReports.js.map +1 -1
  66. package/dist/src/staffViews.d.ts +138 -0
  67. package/dist/src/staffViews.d.ts.map +1 -0
  68. package/dist/src/staffViews.js +205 -0
  69. package/dist/src/staffViews.js.map +1 -0
  70. package/dist/src/strikes.js +2 -2
  71. package/dist/src/strikes.js.map +1 -1
  72. package/dist/src/subjects.js +2 -2
  73. package/dist/src/subjects.js.map +1 -1
  74. package/dist/src/team.d.ts +149 -0
  75. package/dist/src/team.d.ts.map +1 -0
  76. package/dist/src/team.js +385 -0
  77. package/dist/src/team.js.map +1 -0
  78. package/dist/src/types.d.ts +245 -4
  79. package/dist/src/types.d.ts.map +1 -1
  80. package/dist/src/types.js +5 -0
  81. package/dist/src/types.js.map +1 -1
  82. package/package.json +4 -1
  83. package/src/audit.ts +73 -9
  84. package/src/chat.ts +109 -9
  85. package/src/chatwarden.ts +279 -22
  86. package/src/crypto.ts +206 -0
  87. package/src/decide.ts +2 -4
  88. package/src/documents.ts +70 -43
  89. package/src/events.ts +10 -1
  90. package/src/hasher.ts +2 -2
  91. package/src/index.ts +110 -5
  92. package/src/ladder.ts +1 -1
  93. package/src/log.ts +37 -0
  94. package/src/notices.ts +2 -2
  95. package/src/policy.ts +288 -0
  96. package/src/profile.ts +369 -14
  97. package/src/reporting.ts +251 -0
  98. package/src/reports.ts +165 -12
  99. package/src/sanctions.ts +3 -3
  100. package/src/staffReports.ts +33 -7
  101. package/src/staffViews.ts +325 -0
  102. package/src/strikes.ts +2 -2
  103. package/src/subjects.ts +2 -2
  104. package/src/team.ts +422 -0
  105. package/src/types.ts +257 -4
@@ -0,0 +1,251 @@
1
+ import type { ReportCategory } from './types.js';
2
+
3
+ // The reporting settings: how a player reports (the flow), what they may say it is for (the reasons), and what they are
4
+ // told afterwards (the thank-you). Pure data and lookups: no store, no IO. The validation lives with the rest of the profile
5
+ // checks in profile.ts, which also applies the defaults below; this file has the shapes, the defaults and the lookups.
6
+ //
7
+ // The reporter's reason is a HINT, never the truth: it is stored as `reportedReason` and what settles a case is the
8
+ // moderator's decision (or, later, the AI read).
9
+
10
+ /** How the player's reporting screen works. The kit treats `one_tap` and `reason_first` the same; only `reason_required` refuses. */
11
+ export type ReportFlow = 'one_tap' | 'reason_first' | 'reason_required';
12
+
13
+ /** Every flow, in the order a settings screen lists them. */
14
+ export const REPORT_FLOWS: readonly ReportFlow[] = ['one_tap', 'reason_first', 'reason_required'];
15
+
16
+ /** The default flow: "Report this message" sends at once; a reason is offered afterwards and is optional. */
17
+ export const DEFAULT_REPORT_FLOW: ReportFlow = 'one_tap';
18
+
19
+ /** The default thank-you shown to the reporter. */
20
+ export const DEFAULT_REPORT_THANKS = "Thanks for the report. We'll look into it.";
21
+
22
+ /** The most reasons a profile may list. */
23
+ export const MAX_REPORT_REASONS = 20;
24
+ /** The longest reason id, label, hint, group and thank-you, in characters. */
25
+ export const REPORT_ID_MAX = 32;
26
+ export const REPORT_LABEL_MAX = 60;
27
+ export const REPORT_HINT_MAX = 160;
28
+ export const REPORT_GROUP_MAX = 40;
29
+ export const REPORT_THANKS_MAX = 300;
30
+ /** The most Community Rule numbers one reason may map to. */
31
+ export const MAX_REASON_RULES = 20;
32
+
33
+ /** True for a well-formed reason id: a lowercase slug of letters, digits, `_` and `-` (at most 32 characters), and not `none`. */
34
+ export function isReasonId(v: unknown): v is string {
35
+ return typeof v === 'string' && v.length <= REPORT_ID_MAX && /^[a-z0-9]+(?:[_-][a-z0-9]+)*$/.test(v) && v !== 'none';
36
+ }
37
+
38
+ /** The id of the reason that can never be removed or switched off: the fallback and what an old `other` category reads as. */
39
+ export const OTHER_REASON_ID = 'other';
40
+
41
+ /**
42
+ * One reason as you write it. `id` (a lowercase slug, unique) and `label` are required; the rest default to
43
+ * `hint: ''`, `group: ''` (no group), `rules: []`, `asksNote: false` and `enabled: true`.
44
+ */
45
+ export interface ReportReasonInput {
46
+ /** A unique lowercase slug of letters, digits, `_` and `-` (at most 32 characters). `none` is reserved. */
47
+ id: string;
48
+ /** What the player sees (at most 60 characters). */
49
+ label: string;
50
+ /** One line under the label (at most 160 characters). */
51
+ hint?: string;
52
+ /** The heading the reason is listed under, for example `Chat` or `Gameplay`; `''` lists it with no heading (at most 40 characters). */
53
+ group?: string;
54
+ /** The Community Rule numbers this reason usually means. The first one is the moderator's suggested rule; a decision under any of them counts as "matched" for the reporter. */
55
+ rules?: number[];
56
+ /** Ask the player for a short note when they pick it. */
57
+ asksNote?: boolean;
58
+ /** Offered to players. A switched-off reason stays valid for reports already filed. */
59
+ enabled?: boolean;
60
+ }
61
+
62
+ /** One reason with every field filled in. */
63
+ export interface ReportReason {
64
+ id: string;
65
+ label: string;
66
+ hint: string;
67
+ group: string;
68
+ rules: number[];
69
+ asksNote: boolean;
70
+ enabled: boolean;
71
+ }
72
+
73
+ /** The reporting settings as you write them: every field is optional and defaulted. */
74
+ export interface ReportingSettings {
75
+ /** Default `'one_tap'`. */
76
+ flow?: ReportFlow;
77
+ /** The whole ordered list (a layer or an override replaces it, never merges). Default {@link DEFAULT_REPORT_REASONS}. 1 to 20 reasons, at least one enabled, and `other` present and enabled. */
78
+ reasons?: ReportReasonInput[];
79
+ /** What the reporter is told after sending a report (at most 300 characters). Default {@link DEFAULT_REPORT_THANKS}. */
80
+ thanks?: string;
81
+ }
82
+
83
+ /** The reporting settings in force: every field filled in. */
84
+ export interface ResolvedReporting {
85
+ flow: ReportFlow;
86
+ reasons: ReportReason[];
87
+ thanks: string;
88
+ }
89
+
90
+ /** What a player's client may read: the enabled reasons and nothing of the staff side (no rule mapping). */
91
+ export interface PlayerReporting {
92
+ flow: ReportFlow;
93
+ reasons: Array<{ id: string; label: string; hint: string; group: string; asksNote: boolean }>;
94
+ thanks: string;
95
+ }
96
+
97
+ const reason = (id: string, label: string, hint: string, group: string, rules: number[], asksNote = false): ReportReason => ({
98
+ id,
99
+ label,
100
+ hint,
101
+ group,
102
+ rules,
103
+ asksNote,
104
+ enabled: true,
105
+ });
106
+
107
+ /**
108
+ * The default reasons, deep-frozen: Chat (insults or harassment, hate, sexual content, threats, spam or ads, sharing personal
109
+ * info), Gameplay (cheating, throwing or griefing, leaving or AFK), then Something else. Each maps to the starter Community
110
+ * Rules it usually means: harassment, threats and personal info to CR 2, hate to CR 1, sexual content to CR 3, spam to CR 4,
111
+ * cheating to CR 5, griefing and AFK to CR 6. `other` maps to none.
112
+ */
113
+ export const DEFAULT_REPORT_REASONS: readonly Readonly<ReportReason>[] = Object.freeze(
114
+ [
115
+ reason('harassment', 'Insults or harassment', 'Insults, put-downs or picking on someone', 'Chat', [2]),
116
+ reason('hate', 'Hate', 'Hate aimed at who someone is', 'Chat', [1]),
117
+ reason('sexual', 'Sexual content', 'Sexual messages or pressure', 'Chat', [3]),
118
+ reason('threat', 'Threats', 'Threatening someone', 'Chat', [2]),
119
+ reason('spam', 'Spam or ads', 'Repeated messages, flooding or advertising', 'Chat', [4]),
120
+ reason('personal_info', 'Sharing personal info', "Posting someone's private details", 'Chat', [2]),
121
+ reason('cheating', 'Cheating', 'Cheating or exploiting a bug', 'Gameplay', [5]),
122
+ reason('griefing', 'Throwing or griefing', 'Losing on purpose or ruining the game', 'Gameplay', [6]),
123
+ reason('afk', 'Leaving or AFK', 'Leaving the game or not playing', 'Gameplay', [6]),
124
+ reason(OTHER_REASON_ID, 'Something else', 'Anything else you want us to look at', '', [], true),
125
+ ].map((r) => Object.freeze({ ...r, rules: Object.freeze([...r.rules]) as unknown as number[] })),
126
+ );
127
+
128
+ /** A fresh, unfrozen copy of the default reporting settings. */
129
+ export function defaultReporting(): ResolvedReporting {
130
+ return {
131
+ flow: DEFAULT_REPORT_FLOW,
132
+ reasons: DEFAULT_REPORT_REASONS.map((r) => ({ ...r, rules: [...r.rules] })),
133
+ thanks: DEFAULT_REPORT_THANKS,
134
+ };
135
+ }
136
+
137
+ /**
138
+ * Old ids that read as a new one. `disruption` (the 0.1.1 category) is `griefing`. An exact id in the list always wins, so a
139
+ * studio that defines its own `disruption` reason keeps it.
140
+ */
141
+ export const LEGACY_REASON_ALIASES: Readonly<Record<string, string>> = Object.freeze({ disruption: 'griefing' });
142
+
143
+ /** The six 0.1.1 categories. They stay valid reason ids (through {@link LEGACY_REASON_ALIASES} for `disruption`). */
144
+ export const LEGACY_CATEGORIES: readonly ReportCategory[] = ['harassment', 'hate', 'cheating', 'spam', 'disruption', 'other'];
145
+
146
+ /** The reason in `reasons` that `id` names (exactly, else as an old alias), or undefined. Disabled reasons are found too. */
147
+ export function findReason(reasons: readonly ReportReason[], id: string): ReportReason | undefined {
148
+ const exact = reasons.find((r) => r.id === id);
149
+ if (exact !== undefined) return exact;
150
+ const alias = Object.hasOwn(LEGACY_REASON_ALIASES, id) ? LEGACY_REASON_ALIASES[id] : undefined;
151
+ return alias === undefined ? undefined : reasons.find((r) => r.id === alias);
152
+ }
153
+
154
+ /** The id `id` stands for in `reasons` (`disruption` becomes `griefing` unless the list has its own), or `id` itself when it is in no list. */
155
+ export function canonicalReasonId(reasons: readonly ReportReason[], id: string): string {
156
+ return findReason(reasons, id)?.id ?? id;
157
+ }
158
+
159
+ /** The player-facing label of a reason id (an old alias included), or null when there is no such reason. */
160
+ export function reasonLabel(reasons: readonly ReportReason[], id: string | null): string | null {
161
+ return id === null ? null : (findReason(reasons, id)?.label ?? null);
162
+ }
163
+
164
+ /**
165
+ * The 0.1.1 category a reason id is kept under in the stored report's `category` column (which old consumers still read): the
166
+ * six old ids are themselves, `griefing` and `afk` are `disruption`, `threat` is `harassment`, and everything else (no reason,
167
+ * `sexual`, `personal_info`, a studio's own) is `other`.
168
+ */
169
+ export function legacyCategoryOf(id: string | null): ReportCategory {
170
+ switch (id) {
171
+ case 'harassment':
172
+ case 'hate':
173
+ case 'cheating':
174
+ case 'spam':
175
+ case 'other':
176
+ return id;
177
+ case 'griefing':
178
+ case 'afk':
179
+ case 'disruption':
180
+ return 'disruption';
181
+ case 'threat':
182
+ return 'harassment';
183
+ default:
184
+ return 'other';
185
+ }
186
+ }
187
+
188
+ /** The reason id a stored 0.1.1 category reads as: `disruption` is `griefing`, the others are themselves. */
189
+ export function reasonOfCategory(category: string): string {
190
+ return Object.hasOwn(LEGACY_REASON_ALIASES, category) ? (LEGACY_REASON_ALIASES[category] as string) : category;
191
+ }
192
+
193
+ /**
194
+ * The Community Rule a moderator is suggested for a reported reason: the first of the reason's rules that is still citable, or
195
+ * `'uncovered'` (no reason, an unknown reason, a reason with no rules). The report is never decided by it.
196
+ */
197
+ export function suggestedRule(
198
+ reasons: readonly ReportReason[],
199
+ id: string | null,
200
+ rules: { isCitable(ref: number): boolean },
201
+ ): number | 'uncovered' {
202
+ if (id === null) return 'uncovered';
203
+ const found = findReason(reasons, id);
204
+ if (found === undefined) return 'uncovered';
205
+ return found.rules.find((n) => rules.isCitable(n)) ?? 'uncovered';
206
+ }
207
+
208
+ /** What a player may read: the enabled reasons in order, with no rule mapping. Each field is copied by name, so nothing added later leaks. */
209
+ export function playerReporting(reporting: ResolvedReporting): PlayerReporting {
210
+ return {
211
+ flow: reporting.flow,
212
+ reasons: reporting.reasons
213
+ .filter((r) => r.enabled)
214
+ .map((r) => ({ id: r.id, label: r.label, hint: r.hint, group: r.group, asksNote: r.asksNote })),
215
+ thanks: reporting.thanks,
216
+ };
217
+ }
218
+
219
+ const isObj = (v: unknown): v is Record<string, unknown> => typeof v === 'object' && v !== null && !Array.isArray(v);
220
+
221
+ /**
222
+ * Fill the optional parts of reporting settings: a missing flow, thank-you, reason list or reason field gets its default. It never
223
+ * throws and never judges: anything of the wrong shape is returned as it is, for the profile validator to name. Copies.
224
+ */
225
+ export function fillReporting(value: unknown): unknown {
226
+ if (value === undefined) return defaultReporting();
227
+ if (!isObj(value)) return value;
228
+ const out: Record<string, unknown> = { ...value };
229
+ if (!Object.hasOwn(out, 'flow')) out['flow'] = DEFAULT_REPORT_FLOW;
230
+ if (!Object.hasOwn(out, 'thanks')) out['thanks'] = DEFAULT_REPORT_THANKS;
231
+ if (!Object.hasOwn(out, 'reasons')) {
232
+ out['reasons'] = defaultReporting().reasons;
233
+ } else if (Array.isArray(out['reasons'])) {
234
+ out['reasons'] = (out['reasons'] as unknown[]).map((r) => {
235
+ if (!isObj(r)) return r;
236
+ const filled: Record<string, unknown> = { ...r };
237
+ if (!Object.hasOwn(filled, 'hint')) filled['hint'] = '';
238
+ if (!Object.hasOwn(filled, 'group')) filled['group'] = '';
239
+ if (!Object.hasOwn(filled, 'rules')) filled['rules'] = [];
240
+ if (!Object.hasOwn(filled, 'asksNote')) filled['asksNote'] = false;
241
+ if (!Object.hasOwn(filled, 'enabled')) filled['enabled'] = true;
242
+ return filled;
243
+ });
244
+ }
245
+ return out;
246
+ }
247
+
248
+ /** {@link fillReporting} for settings already known to be valid: the typed result. */
249
+ export function resolveReporting(settings: ReportingSettings | undefined): ResolvedReporting {
250
+ return fillReporting(settings) as ResolvedReporting;
251
+ }
package/src/reports.ts CHANGED
@@ -1,7 +1,9 @@
1
- import { randomBytes } from 'node:crypto';
1
+ import { randomId } from './crypto.js';
2
2
  import type { EvidenceBuffer, RoomRoster } from './evidence.js';
3
3
  import type { Limits } from './limits.js';
4
4
  import { safeWarn } from './log.js';
5
+ import { defaultReporting, findReason, legacyCategoryOf, OTHER_REASON_ID } from './reporting.js';
6
+ import type { ResolvedReporting } from './reporting.js';
5
7
  import type { SubjectIndex } from './subjects.js';
6
8
  import type {
7
9
  Clock,
@@ -37,11 +39,35 @@ export const SUSPEND_WINDOW_MS = 30 * DAY_MS;
37
39
  /** A note is trimmed, then cut to this many characters. */
38
40
  export const REPORT_NOTE_MAX = 500;
39
41
 
40
- /** Every category a report can carry; anything else is stored as `'other'`. */
42
+ /** The 0.1.1 categories. A report's stored `category` is always one of these (see `legacyCategoryOf`); they stay valid ids for `ReportInput.category`. */
41
43
  export const REPORT_CATEGORIES: readonly ReportCategory[] = ['harassment', 'hate', 'cheating', 'spam', 'disruption', 'other'];
42
44
 
43
45
  /** Why a report was not taken. In the order they are checked. */
44
- export type ReportRefusal = 'off' | 'not_player' | 'self' | 'suspended' | 'rate' | 'duplicate';
46
+ export type ReportRefusal =
47
+ | 'off'
48
+ /** The `reason_required` flow, and no reason was given. */
49
+ | 'reason_required'
50
+ /** A reason that is not an enabled id in the profile's reporting reasons (in every flow). */
51
+ | 'reason_unknown'
52
+ | 'not_player'
53
+ | 'self'
54
+ | 'suspended'
55
+ | 'rate'
56
+ | 'duplicate';
57
+
58
+ /** How long after a report its reporter may add their one follow-up: 10 minutes. */
59
+ export const REPORT_DETAIL_WINDOW_MS = 10 * 60_000;
60
+
61
+ /** The follow-up a reporter may add to their report: a reason, a note, or both. Both are optional; a blank one is "not given". */
62
+ export interface ReportDetailInput {
63
+ reason?: string | null;
64
+ note?: string | null;
65
+ }
66
+
67
+ /** Why a follow-up was not taken, in the order they are checked. */
68
+ export type ReportDetailRefusal = 'off' | 'not_found' | 'not_reporter' | 'too_late' | 'already_added' | 'reason_unknown';
69
+
70
+ export type ReportDetailResult = { ok: true } | { ok: false; refused: ReportDetailRefusal };
45
71
 
46
72
  export interface ReportInput {
47
73
  roomId: string;
@@ -49,14 +75,28 @@ export interface ReportInput {
49
75
  reporterSeat: string;
50
76
  /** The seat reported. Ignored when `lineId` names a line still in the evidence buffer. */
51
77
  targetSeat: string;
52
- category: ReportCategory;
78
+ /**
79
+ * Why the player is reporting: an enabled id from the profile's reporting reasons. Optional: with the default `one_tap` flow
80
+ * and with `reason_first` a report with no reason (missing, null or blank) is taken; with `reason_required` it is refused
81
+ * `reason_required`. An id that is not an enabled reason is `reason_unknown`, in every flow. It is a hint for the moderator
82
+ * and never decides the case.
83
+ */
84
+ reason?: string | null;
85
+ /**
86
+ * The 0.1.1 name for `reason`, still accepted as an alias (the six old ids are valid; `disruption` reads as `griefing`) and still
87
+ * lenient: an unknown, non-text or switched-off id is taken as `other`. `reason` wins when both are given; a blank `reason` falls back to this.
88
+ */
89
+ category?: string | null;
53
90
  note?: string;
54
91
  lineId?: string;
55
92
  }
56
93
 
57
94
  export type ReportResult =
58
- /** `remaining` is how many more reports the reporter may file today, this one counted. */
59
- | { ok: true; reportId: string; remaining: number }
95
+ /**
96
+ * `remaining` is how many more reports the reporter may file today, this one counted. `detailUntil` (epoch ms) is the last instant
97
+ * `addDetail` still takes a follow-up (the filing time plus `REPORT_DETAIL_WINDOW_MS`); a screen can stop offering one after it.
98
+ */
99
+ | { ok: true; reportId: string; remaining: number; detailUntil?: number }
60
100
  /** `remaining` is present on `'rate'` (always 0). */
61
101
  | { ok: false; refused: ReportRefusal; remaining?: number };
62
102
 
@@ -78,6 +118,8 @@ export interface ReportServiceDeps {
78
118
  clock: Clock;
79
119
  /** Read per call, so a kill switch works live. Defaults to always on. */
80
120
  enabled?: () => boolean;
121
+ /** The reporting settings in force, read per call so an edit applies to the next report. Defaults to the built-in reporting defaults. */
122
+ reporting?: () => ResolvedReporting;
81
123
  /**
82
124
  * Called once for each stored report, after the result is decided. Fenced: a synchronous throw or an async
83
125
  * rejection is logged and never reaches the reporter. It receives a copy of the report.
@@ -92,7 +134,7 @@ export interface ReportServiceDeps {
92
134
  limits?: Limits['reports'];
93
135
  }
94
136
 
95
- const newId = (): string => randomBytes(16).toString('base64url');
137
+ const newId = (): string => randomId(16);
96
138
 
97
139
  const errName = (err: unknown): string => (err instanceof Error ? err.name : typeof err);
98
140
 
@@ -125,6 +167,23 @@ const copyReport = (r: StoredReport): StoredReport => ({
125
167
  people: [...r.people],
126
168
  });
127
169
 
170
+ /**
171
+ * When a reporter's suspension ends, or null when they are not suspended. `marks` are the `actionedAt` times of the
172
+ * reporter's bad-faith dismissals that are still inside the window (the rows `loadBadFaithMarks` returns for it).
173
+ * Suspended means `suspendAfter` or more of them; the suspension lifts once enough of the oldest have aged out for the
174
+ * count to fall below `suspendAfter`, that is one millisecond after the window has passed the first mark that must go
175
+ * (a mark counts while `actionedAt >= now - suspendWindowMs`). The single place the rule lives: intake refuses with it
176
+ * and the staff view reports it.
177
+ */
178
+ export function reporterSuspendedUntil(
179
+ marks: readonly number[],
180
+ limits: Pick<Limits['reports'], 'suspendAfter' | 'suspendWindowMs'>,
181
+ ): number | null {
182
+ if (marks.length < limits.suspendAfter) return null;
183
+ const sorted = [...marks].sort((a, b) => a - b);
184
+ return sorted[sorted.length - limits.suspendAfter]! + limits.suspendWindowMs + 1;
185
+ }
186
+
128
187
  export class ReportService {
129
188
  private readonly roster: RoomRoster;
130
189
  private readonly buffer: EvidenceBuffer;
@@ -132,6 +191,7 @@ export class ReportService {
132
191
  private readonly store: Store;
133
192
  private readonly clock: Clock;
134
193
  private readonly enabled: () => boolean;
194
+ private readonly reporting: () => ResolvedReporting;
135
195
  private readonly onReport: ReportServiceDeps['onReport'];
136
196
  private readonly logger: Logger | undefined;
137
197
  private readonly limits: Limits['reports'];
@@ -143,6 +203,7 @@ export class ReportService {
143
203
  this.store = deps.store;
144
204
  this.clock = deps.clock;
145
205
  this.enabled = deps.enabled ?? (() => true);
206
+ this.reporting = deps.reporting ?? defaultReporting;
146
207
  this.onReport = deps.onReport;
147
208
  this.logger = deps.logger;
148
209
  this.limits = deps.limits ?? {
@@ -157,6 +218,10 @@ export class ReportService {
157
218
  *
158
219
  * - `off`: moderation is disabled, the reporter's seat has no occupant or no subject (nothing to count or
159
220
  * dedupe their reports by), or the store failed (logged by event and error class only).
221
+ * - `reason_required`: the flow is `reason_required` and the report names no reason (see {@link ReportInput.reason}).
222
+ * - `reason_unknown`: `reason` is not an enabled reason, in every flow. A refused reason uses up nothing: it never counts toward
223
+ * the daily allowance. The 0.1.1 `category` alias is not refused for this: an id that is not an enabled reason (or not text) is
224
+ * taken as `other`, as it was in 0.1.1. A blank `reason` falls back to `category`.
160
225
  * - `not_player`: the target seat has no occupant, or the occupant (or the line's author) has no subject.
161
226
  * - `self`: reporter and target are the same canonical subject.
162
227
  * - `suspended`: three or more of the reporter's reports were dismissed as bad faith within 30 days.
@@ -178,8 +243,91 @@ export class ReportService {
178
243
  }
179
244
  }
180
245
 
246
+ /**
247
+ * Add the reporter's one follow-up to their report: a reason, a note, or both. Never rejects. Refusals, in this order:
248
+ *
249
+ * - `off`: moderation is disabled, the store cannot take a follow-up (it has no `addReportDetail`), or it failed (logged by
250
+ * event and error class only).
251
+ * - `not_found`: no such report.
252
+ * - `not_reporter`: `reporterSeat` is not the seat the report was filed from, or that seat, in the report's room, no longer
253
+ * holds the reporter (the same canonical person; a merged alias counts). The player must still be in the room.
254
+ * - `too_late`: more than ten minutes after the report (`REPORT_DETAIL_WINDOW_MS`; exactly ten is still in time), or the
255
+ * report has been decided.
256
+ * - `already_added`: the follow-up was already taken once.
257
+ * - `reason_unknown`: the reason is not an enabled reason.
258
+ *
259
+ * A reason given replaces the report's reported reason (it is only a hint); a note replaces its note (trimmed and cut like a
260
+ * report note). One left out (missing, null or blank) keeps what the report had. A follow-up that gives neither is `ok: true`
261
+ * and changes nothing, and does not use up the one allowed. It never changes the target, the excerpt or the line, and
262
+ * announces nothing.
263
+ */
264
+ async addDetail(reportId: string, reporterSeat: string, detail: ReportDetailInput): Promise<ReportDetailResult> {
265
+ try {
266
+ return this.runDetail(reportId, reporterSeat, detail);
267
+ } catch (err) {
268
+ this.warn('reports.detail_failed', { error: errName(err) });
269
+ return { ok: false, refused: 'off' };
270
+ }
271
+ }
272
+
181
273
  // --- internals -----------------------------------------------------------
182
274
 
275
+ /**
276
+ * The reason a report names: `{ id }` (an enabled one; null for none), or why it cannot be taken. A blank reason is none; the
277
+ * `category` alias is read when there is no `reason`. A match is exact, after trimming; an old `disruption` finds `griefing`.
278
+ */
279
+ private readReason(input: { reason?: unknown; category?: unknown }): { id: string | null } | 'required' | 'unknown' {
280
+ const reporting = this.reporting();
281
+ const none = reporting.flow === 'reason_required' ? 'required' : { id: null };
282
+ const blank = (v: unknown): boolean => v === undefined || v === null || (typeof v === 'string' && v.trim() === '');
283
+ if (!blank(input.reason)) {
284
+ // The new field is strict: anything that is not an enabled reason is refused.
285
+ if (typeof input.reason !== 'string') return 'unknown';
286
+ const found = findReason(reporting.reasons, input.reason.trim());
287
+ return found !== undefined && found.enabled ? { id: found.id } : 'unknown';
288
+ }
289
+ if (blank(input.category)) return none;
290
+ // The 0.1.1 alias keeps its 0.1.1 behaviour: an id that is not an enabled reason (or not text at all) is taken as `other`.
291
+ const found = typeof input.category === 'string' ? findReason(reporting.reasons, input.category.trim()) : undefined;
292
+ return found !== undefined && found.enabled ? { id: found.id } : { id: OTHER_REASON_ID };
293
+ }
294
+
295
+ private runDetail(reportId: string, reporterSeat: string, detail: ReportDetailInput | null | undefined): ReportDetailResult {
296
+ if (!this.enabled()) return { ok: false, refused: 'off' };
297
+ const store = this.store;
298
+ if (typeof store.addReportDetail !== 'function') return { ok: false, refused: 'off' };
299
+ const report = typeof reportId === 'string' && reportId !== '' ? store.loadReport(reportId) : null;
300
+ if (report === null) return { ok: false, refused: 'not_found' };
301
+
302
+ // The reporter, in the room and the seat the report was filed from. Looked up in the report's own room.
303
+ const occ = typeof reporterSeat === 'string' && reporterSeat === report.reporterSeat ? this.roster.occupant(report.roomId, reporterSeat) : null;
304
+ if (occ === null || !present(occ.subject) || this.subjects.canonical(occ.subject) !== this.subjects.canonical(report.reporterSubject)) {
305
+ return { ok: false, refused: 'not_reporter' };
306
+ }
307
+ const now = this.clock.now();
308
+ if (report.status !== 'open' || now - report.createdAt > REPORT_DETAIL_WINDOW_MS) return { ok: false, refused: 'too_late' };
309
+ if ((report.detailAt ?? null) !== null) return { ok: false, refused: 'already_added' };
310
+
311
+ const d: ReportDetailInput = typeof detail === 'object' && detail !== null ? detail : {};
312
+ const picked = this.readReason({ reason: d.reason });
313
+ if (picked === 'unknown') return { ok: false, refused: 'reason_unknown' };
314
+ // In the `reason_required` flow a follow-up with no reason is not a refusal: the report has its reason already.
315
+ const reason = picked === 'required' || picked.id === null ? null : picked.id;
316
+ const note = cleanNote(d.note);
317
+ if (reason === null && note === null) return { ok: true };
318
+
319
+ const finalReason = reason ?? report.reportedReason ?? null;
320
+ const written = store.transaction(() =>
321
+ store.addReportDetail?.(report.id, {
322
+ reportedReason: finalReason,
323
+ category: legacyCategoryOf(finalReason),
324
+ note: note ?? report.note,
325
+ at: now,
326
+ }),
327
+ );
328
+ return written === true ? { ok: true } : { ok: false, refused: 'already_added' };
329
+ }
330
+
183
331
  private run(input: ReportInput): ReportResult {
184
332
  if (!this.enabled()) return refuse('off');
185
333
 
@@ -188,6 +336,10 @@ export class ReportService {
188
336
  if (reporterOcc === null || !present(reporterOcc.subject)) return refuse('off');
189
337
  const reporter = this.subjects.canonical(reporterOcc.subject);
190
338
 
339
+ const given = this.readReason(input);
340
+ if (given === 'required') return refuse('reason_required');
341
+ if (given === 'unknown') return refuse('reason_unknown');
342
+
191
343
  let line = typeof input.lineId === 'string' ? this.buffer.get(roomId, input.lineId) : undefined;
192
344
  // A reporter cannot cite a line they never saw: one sent to a limited audience that left their seat out is
193
345
  // ignored, and the target falls back to the targetSeat occupant.
@@ -252,7 +404,8 @@ export class ReportService {
252
404
  targetSubject: targetPerson,
253
405
  targetSeat: target.seat,
254
406
  targetHandle: target.handle,
255
- category: REPORT_CATEGORIES.includes(input.category) ? input.category : 'other',
407
+ category: legacyCategoryOf(given.id),
408
+ reportedReason: given.id,
256
409
  note: cleanNote(input.note),
257
410
  lineId: line === undefined ? null : line.lineId,
258
411
  excerpt,
@@ -270,7 +423,7 @@ export class ReportService {
270
423
  }
271
424
 
272
425
  this.notify(row, targetPerson, now);
273
- return { ok: true, reportId: row.id, remaining };
426
+ return { ok: true, reportId: row.id, remaining, detailUntil: row.createdAt + REPORT_DETAIL_WINDOW_MS };
274
427
  }
275
428
 
276
429
  /**
@@ -284,9 +437,9 @@ export class ReportService {
284
437
  now: number,
285
438
  ): { refusal: ReportResult } | { used: number } {
286
439
  const marks = this.store.loadBadFaithMarks(now - this.limits.suspendWindowMs);
287
- let bad = 0;
288
- for (const m of marks) if (this.subjects.canonical(m.reporter) === reporter) bad++;
289
- if (bad >= this.limits.suspendAfter) return { refusal: refuse('suspended') };
440
+ const bad: number[] = [];
441
+ for (const m of marks) if (this.subjects.canonical(m.reporter) === reporter) bad.push(m.actionedAt);
442
+ if (reporterSuspendedUntil(bad, this.limits) !== null) return { refusal: refuse('suspended') };
290
443
 
291
444
  const used = this.reportsByInLastDay(reporter, now);
292
445
  if (used >= this.limits.perDay) return { refusal: refuse('rate', 0) };
package/src/sanctions.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { randomBytes, randomInt } from 'node:crypto';
1
+ import { randomId, randomIntBelow } from './crypto.js';
2
2
  import type { Identifiers, SanctionKind, SanctionRow, Source, Store, SubjectId } from './types.js';
3
3
  import type { RuleRef } from './rules.js';
4
4
  import type { SubjectIndex } from './subjects.js';
@@ -99,12 +99,12 @@ export interface ActiveSanction {
99
99
  own: boolean;
100
100
  }
101
101
 
102
- const newId = (): string => randomBytes(16).toString('base64url');
102
+ const newId = (): string => randomId(16);
103
103
 
104
104
  /** `M-` plus 5 characters from an unambiguous alphabet. Uniqueness is enforced at write time, not here. */
105
105
  export function refCode(): string {
106
106
  let out = 'M-';
107
- for (let i = 0; i < 5; i++) out += REF_ALPHABET[randomInt(REF_ALPHABET.length)];
107
+ for (let i = 0; i < 5; i++) out += REF_ALPHABET[randomIntBelow(REF_ALPHABET.length)];
108
108
  return out;
109
109
  }
110
110
 
@@ -1,4 +1,6 @@
1
1
  import { ownLineIdsByPerson } from './notices.js';
2
+ import { canonicalReasonId, isReasonId, reasonOfCategory } from './reporting.js';
3
+ import type { ReportReason } from './reporting.js';
2
4
  import type { SubjectIndex } from './subjects.js';
3
5
  import type { ReportRecord, Store, SubjectId } from './types.js';
4
6
 
@@ -10,18 +12,21 @@ export const REPORT_PAGE_MAX = 200;
10
12
  const STATUSES: ReadonlyArray<ReportRecord['status']> = ['open', 'actioned', 'dismissed'];
11
13
 
12
14
  /**
13
- * A report query that cannot be answered: an unknown `status`, a `before` cursor that is not one we issued, or a `person`
14
- * that is not a subject id (or one combined with a `status` / `before`, which a person query does not take).
15
+ * A report query that cannot be answered: an unknown `status`, a `before` cursor that is not one we issued, a `reason` that is
16
+ * not a well-formed id, or a `person` that is not a subject id (or one combined with a `status` / `before` / `reason`, which a
17
+ * person query does not take).
15
18
  */
16
19
  export class ReportQueryError extends Error {
17
- readonly field: 'status' | 'before' | 'person';
18
- constructor(field: 'status' | 'before' | 'person') {
20
+ readonly field: 'status' | 'before' | 'person' | 'reason';
21
+ constructor(field: 'status' | 'before' | 'person' | 'reason') {
19
22
  super(
20
23
  field === 'status'
21
24
  ? 'reports.list: unknown status'
22
25
  : field === 'person'
23
26
  ? 'reports.list: invalid person'
24
- : 'reports.list: invalid cursor',
27
+ : field === 'reason'
28
+ ? 'reports.list: invalid reason'
29
+ : 'reports.list: invalid cursor',
25
30
  );
26
31
  this.name = 'ReportQueryError';
27
32
  this.field = field;
@@ -44,6 +49,10 @@ export class ReportQueryError extends Error {
44
49
  * Carries subject ids: staff channels only, never send to a player.
45
50
  */
46
51
  export interface StaffReport extends ReportRecord {
52
+ /** When the reporter added their one follow-up, or null. Always present here. */
53
+ detailAt: number | null;
54
+ /** The reason the reporter gave (an id from the profile's reasons, an old category read as its new id), or null when they gave none. A hint, never the truth. */
55
+ reportedReason: string | null;
47
56
  targetPerson: SubjectId;
48
57
  reporterPerson: SubjectId;
49
58
  ownLineIds: Record<SubjectId, string[]>;
@@ -63,6 +72,12 @@ export interface ReportQuery {
63
72
  * (`ReportQueryError`).
64
73
  */
65
74
  person?: SubjectId;
75
+ /**
76
+ * Only reports whose reported reason is this id (the old `disruption` finds `griefing`), or, with `null`, only those with no
77
+ * reason given. An id that is no reason any more still finds its old reports. A malformed id is `ReportQueryError`; a person
78
+ * query does not take it.
79
+ */
80
+ reason?: string | null;
66
81
  }
67
82
 
68
83
  /**
@@ -114,8 +129,12 @@ const clampLimit = (limit: unknown): number => {
114
129
 
115
130
  /** A stored record as the staff queue shows it (see {@link StaffReport}). Copies; the record is not touched. */
116
131
  export function staffReport(record: ReportRecord, subjects: SubjectIndex): StaffReport {
132
+ // A record from a store that predates `reportedReason` has none at all (not even null): its category is the reason it was filed under.
133
+ const stored = (record as { reportedReason?: string | null }).reportedReason;
117
134
  return {
118
135
  ...structuredClone(record),
136
+ reportedReason: stored === undefined ? reasonOfCategory(record.category) : stored,
137
+ detailAt: record.detailAt ?? null,
119
138
  people: record.people.map((p) => subjects.canonical(p)),
120
139
  targetPerson: subjects.canonical(record.targetSubject),
121
140
  reporterPerson: subjects.canonical(record.reporterSubject),
@@ -124,25 +143,32 @@ export function staffReport(record: ReportRecord, subjects: SubjectIndex): Staff
124
143
  }
125
144
 
126
145
  /** One page of the staff queue. Throws {@link ReportQueryError} for an unknown status or a bad cursor. */
127
- export function listStaffReports(store: Store, subjects: SubjectIndex, q: ReportQuery = {}): ReportPage {
146
+ export function listStaffReports(store: Store, subjects: SubjectIndex, q: ReportQuery = {}, reasons: readonly ReportReason[] = []): ReportPage {
128
147
  if (q.person !== undefined) {
129
148
  if (typeof q.person !== 'string' || q.person === '') throw new ReportQueryError('person');
130
149
  if (q.status !== undefined) throw new ReportQueryError('status');
150
+ if (q.reason !== undefined) throw new ReportQueryError('reason');
131
151
  if (q.before !== undefined && q.before !== null) throw new ReportQueryError('before');
132
152
  const rows = store.listReportsByPerson(subjects.aliasesOf(q.person), clampLimit(q.limit));
133
153
  return { items: rows.map((r) => staffReport(r, subjects)), next: null };
134
154
  }
135
155
  if (q.status !== undefined && !STATUSES.includes(q.status)) throw new ReportQueryError('status');
156
+ if (q.reason !== undefined && q.reason !== null && !isReasonId(q.reason)) throw new ReportQueryError('reason');
136
157
  const cursor = q.before === undefined || q.before === null ? null : decodeReportCursor(q.before);
137
158
  const limit = clampLimit(q.limit);
159
+ const reason = q.reason === undefined || q.reason === null ? q.reason : canonicalReasonId(reasons, q.reason);
138
160
  const rows = store.listReports({
139
161
  ...(q.status === undefined ? {} : { status: q.status }),
140
162
  ...(cursor === null ? {} : { before: cursor.createdAt, beforeId: cursor.id }),
163
+ ...(reason === undefined ? {} : { reason }),
141
164
  limit,
142
165
  });
143
166
  const last = rows[rows.length - 1];
167
+ // The cursor and "is there more" follow the rows the store gave; the filter is applied again to what it returned, so a store
168
+ // that does not know `reason` still cannot show the wrong reports.
169
+ const items = rows.map((r) => staffReport(r, subjects));
144
170
  return {
145
- items: rows.map((r) => staffReport(r, subjects)),
171
+ items: reason === undefined ? items : items.filter((r) => r.reportedReason === reason),
146
172
  next: rows.length === limit && last !== undefined ? encodeReportCursor(last.createdAt, last.id) : null,
147
173
  };
148
174
  }