@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
package/src/crypto.ts ADDED
@@ -0,0 +1,206 @@
1
+ // Isomorphic crypto for @chatwarden/core: the same code runs in Node and in a browser.
2
+ //
3
+ // Randomness comes from the Web Crypto global (`globalThis.crypto.getRandomValues`), present in Node >= 19 and in
4
+ // every browser. SHA-256 and HMAC-SHA-256 use the node crypto built-in when this runtime has it (looked up through
5
+ // `process.getBuiltinModule`, so there is never a static or dynamic `import` of a node built-in and a browser
6
+ // bundler has nothing to resolve), and otherwise a small pure-JS implementation. Both paths give byte-identical
7
+ // output: identity hashes (see hasher.ts) are stored by Moxgate and must never change.
8
+ //
9
+ // Nothing in this file is exported from the package index; it is for the engine's own modules.
10
+
11
+ /** The slice of the node crypto built-in this file uses. Declared here so no type import of it is needed either. */
12
+ interface NodeCrypto {
13
+ createHash(algorithm: 'sha256'): { update(data: string): { digest(encoding: 'hex'): string } };
14
+ createHmac(algorithm: 'sha256', key: string): { update(data: string): { digest(encoding: 'hex'): string } };
15
+ }
16
+
17
+ let forcePure = false;
18
+ /** `undefined`: not looked up yet. `null`: looked up, this runtime has no usable node crypto. */
19
+ let nativeCache: NodeCrypto | null | undefined;
20
+
21
+ /**
22
+ * Test seam: `true` makes every hash use the pure-JS code even where the built-in exists, `false` goes back to
23
+ * detection. Either call also forgets the cached lookup.
24
+ * @internal
25
+ */
26
+ export function __forcePureJs(force: boolean): void {
27
+ forcePure = force;
28
+ nativeCache = undefined;
29
+ }
30
+
31
+ function native(): NodeCrypto | null {
32
+ if (forcePure) return null;
33
+ if (nativeCache === undefined) {
34
+ nativeCache = null;
35
+ try {
36
+ const proc = (globalThis as { process?: { getBuiltinModule?: (id: string) => unknown } }).process;
37
+ const mod = proc?.getBuiltinModule?.('node:crypto') as Partial<NodeCrypto> | undefined;
38
+ if (mod && typeof mod.createHash === 'function' && typeof mod.createHmac === 'function') {
39
+ nativeCache = mod as NodeCrypto;
40
+ }
41
+ } catch {
42
+ // No process, no getBuiltinModule, or it refused: use the pure-JS path.
43
+ }
44
+ }
45
+ return nativeCache;
46
+ }
47
+
48
+ // ---------------------------------------------------------------------------------------------------------------
49
+ // Randomness
50
+ // ---------------------------------------------------------------------------------------------------------------
51
+
52
+ const B64URL = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_';
53
+ /** `getRandomValues` refuses more than 65536 bytes per call. */
54
+ const MAX_FILL = 65_536;
55
+
56
+ /** The one Web Crypto method used. Declared here because the build has no DOM lib. */
57
+ interface WebCrypto {
58
+ getRandomValues(array: Uint8Array | Uint32Array): unknown;
59
+ }
60
+ function webCrypto(): WebCrypto {
61
+ const c = (globalThis as { crypto?: WebCrypto }).crypto;
62
+ if (!c || typeof c.getRandomValues !== 'function') throw new Error('chatwarden: no secure random source (globalThis.crypto)');
63
+ return c;
64
+ }
65
+
66
+ /** `bytes` random bytes as unpadded base64url: 16 bytes give 22 characters, like `randomBytes(16).toString('base64url')`. */
67
+ export function randomId(bytes = 16): string {
68
+ if (!Number.isInteger(bytes) || bytes < 0) throw new RangeError('randomId: bytes must be a non-negative integer');
69
+ const raw = new Uint8Array(bytes);
70
+ for (let off = 0; off < bytes; off += MAX_FILL) webCrypto().getRandomValues(raw.subarray(off, Math.min(bytes, off + MAX_FILL)));
71
+ let out = '';
72
+ let i = 0;
73
+ for (; i + 2 < bytes; i += 3) {
74
+ const n = (raw[i]! << 16) | (raw[i + 1]! << 8) | raw[i + 2]!;
75
+ out += B64URL[n >> 18]! + B64URL[(n >> 12) & 63]! + B64URL[(n >> 6) & 63]! + B64URL[n & 63]!;
76
+ }
77
+ if (bytes - i === 1) {
78
+ const n = raw[i]! << 16;
79
+ out += B64URL[n >> 18]! + B64URL[(n >> 12) & 63]!;
80
+ } else if (bytes - i === 2) {
81
+ const n = (raw[i]! << 16) | (raw[i + 1]! << 8);
82
+ out += B64URL[n >> 18]! + B64URL[(n >> 12) & 63]! + B64URL[(n >> 6) & 63]!;
83
+ }
84
+ return out;
85
+ }
86
+
87
+ const TWO_32 = 4_294_967_296;
88
+
89
+ /**
90
+ * A uniform integer in `[0, n)` for `1 <= n <= 2**32`. Rejection sampling over 32-bit draws: a draw in the uneven
91
+ * tail (`>= floor(2**32 / n) * n`) is thrown away, so there is no modulo bias.
92
+ */
93
+ export function randomIntBelow(n: number): number {
94
+ if (!Number.isInteger(n) || n < 1 || n > TWO_32) throw new RangeError('randomIntBelow: n must be an integer in [1, 2**32]');
95
+ const limit = Math.floor(TWO_32 / n) * n;
96
+ const draw = new Uint32Array(1);
97
+ for (;;) {
98
+ webCrypto().getRandomValues(draw);
99
+ const v = draw[0]!;
100
+ if (v < limit) return v % n;
101
+ }
102
+ }
103
+
104
+ // ---------------------------------------------------------------------------------------------------------------
105
+ // SHA-256 and HMAC-SHA-256, pure JS (FIPS 180-4, RFC 2104)
106
+ // ---------------------------------------------------------------------------------------------------------------
107
+
108
+ /** Round constants: the first 32 bits of the fractional parts of the cube roots of the first 64 primes. */
109
+ // prettier-ignore
110
+ const K = new Uint32Array([
111
+ 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
112
+ 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
113
+ 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
114
+ 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
115
+ 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
116
+ 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
117
+ 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
118
+ 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
119
+ ]);
120
+
121
+ /** Initial hash value: the first 32 bits of the fractional parts of the square roots of the first 8 primes. */
122
+ const H0 = [0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19] as const;
123
+
124
+ const rotr = (x: number, n: number): number => (x >>> n) | (x << (32 - n));
125
+
126
+ /** SHA-256 of `msg`: 32 bytes. */
127
+ export function __pureSha256(msg: Uint8Array): Uint8Array {
128
+ const len = msg.length;
129
+ // Pad: 0x80, zeros up to 56 mod 64, then the bit length as a 64-bit big-endian integer.
130
+ const total = Math.ceil((len + 9) / 64) * 64;
131
+ const buf = new Uint8Array(total);
132
+ buf.set(msg);
133
+ buf[len] = 0x80;
134
+ const view = new DataView(buf.buffer);
135
+ view.setUint32(total - 8, Math.floor((len * 8) / TWO_32));
136
+ view.setUint32(total - 4, (len * 8) >>> 0);
137
+
138
+ const h = Uint32Array.from(H0);
139
+ const w = new Uint32Array(64);
140
+ for (let off = 0; off < total; off += 64) {
141
+ for (let i = 0; i < 16; i++) w[i] = view.getUint32(off + i * 4);
142
+ for (let i = 16; i < 64; i++) {
143
+ const w15 = w[i - 15]!;
144
+ const w2 = w[i - 2]!;
145
+ const s0 = rotr(w15, 7) ^ rotr(w15, 18) ^ (w15 >>> 3);
146
+ const s1 = rotr(w2, 17) ^ rotr(w2, 19) ^ (w2 >>> 10);
147
+ w[i] = w[i - 16]! + s0 + w[i - 7]! + s1; // Uint32Array stores modulo 2**32
148
+ }
149
+ let a = h[0]!, b = h[1]!, c = h[2]!, d = h[3]!, e = h[4]!, f = h[5]!, g = h[6]!, hh = h[7]!;
150
+ for (let i = 0; i < 64; i++) {
151
+ const t1 = (hh + (rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25)) + ((e & f) ^ (~e & g)) + K[i]! + w[i]!) | 0;
152
+ const t2 = ((rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22)) + ((a & b) ^ (a & c) ^ (b & c))) | 0;
153
+ hh = g;
154
+ g = f;
155
+ f = e;
156
+ e = (d + t1) | 0;
157
+ d = c;
158
+ c = b;
159
+ b = a;
160
+ a = (t1 + t2) | 0;
161
+ }
162
+ h[0] = h[0]! + a; h[1] = h[1]! + b; h[2] = h[2]! + c; h[3] = h[3]! + d;
163
+ h[4] = h[4]! + e; h[5] = h[5]! + f; h[6] = h[6]! + g; h[7] = h[7]! + hh;
164
+ }
165
+ const out = new Uint8Array(32);
166
+ const ov = new DataView(out.buffer);
167
+ for (let i = 0; i < 8; i++) ov.setUint32(i * 4, h[i]!);
168
+ return out;
169
+ }
170
+
171
+ const BLOCK = 64;
172
+
173
+ /** HMAC-SHA-256 (RFC 2104): a key longer than the 64-byte block is hashed first, a shorter one is zero-padded. */
174
+ export function __pureHmacSha256(key: Uint8Array, data: Uint8Array): Uint8Array {
175
+ const k = new Uint8Array(BLOCK);
176
+ k.set(key.length > BLOCK ? __pureSha256(key) : key);
177
+ const inner = new Uint8Array(BLOCK + data.length);
178
+ const outer = new Uint8Array(BLOCK + 32);
179
+ for (let i = 0; i < BLOCK; i++) {
180
+ inner[i] = k[i]! ^ 0x36;
181
+ outer[i] = k[i]! ^ 0x5c;
182
+ }
183
+ inner.set(data, BLOCK);
184
+ outer.set(__pureSha256(inner), BLOCK);
185
+ return __pureSha256(outer);
186
+ }
187
+
188
+ const utf8 = new TextEncoder();
189
+
190
+ function toHex(bytes: Uint8Array): string {
191
+ let s = '';
192
+ for (let i = 0; i < bytes.length; i++) s += bytes[i]!.toString(16).padStart(2, '0');
193
+ return s;
194
+ }
195
+
196
+ /** SHA-256 of the UTF-8 text, as 64 lowercase hex characters. */
197
+ export function sha256Hex(data: string): string {
198
+ const nc = native();
199
+ return nc ? nc.createHash('sha256').update(data).digest('hex') : toHex(__pureSha256(utf8.encode(data)));
200
+ }
201
+
202
+ /** HMAC-SHA-256 of the UTF-8 text under the UTF-8 key, as 64 lowercase hex characters. */
203
+ export function hmacSha256Hex(key: string, data: string): string {
204
+ const nc = native();
205
+ return nc ? nc.createHmac('sha256', key).update(data).digest('hex') : toHex(__pureHmacSha256(utf8.encode(key), utf8.encode(data)));
206
+ }
package/src/decide.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { createHash } from 'node:crypto';
1
+ import { sha256Hex } from './crypto.js';
2
2
  import { safeWarn } from './log.js';
3
3
  import { ownLines } from './notices.js';
4
4
  import type { NoticeService } from './notices.js';
@@ -269,9 +269,7 @@ function keyOf(n: Normal): string {
269
269
  includeIp: a.includeIp,
270
270
  lineIds: a.lineIds,
271
271
  }));
272
- return createHash('sha256')
273
- .update(`${n.reportId}\u0000${n.verdict}\u0000${canonicalJSON(actions)}`)
274
- .digest('hex');
272
+ return sha256Hex(`${n.reportId}\u0000${n.verdict}\u0000${canonicalJSON(actions)}`);
275
273
  }
276
274
 
277
275
  /**
package/src/documents.ts CHANGED
@@ -1,7 +1,7 @@
1
- import { DEFAULT_SEVERE_RULES, lengthLabel, outcomeLabel } from './ladder.js';
1
+ import { DEFAULT_AREA_RULES, DEFAULT_SEVERE_RULES, lengthLabel, outcomeLabel } from './ladder.js';
2
2
  import type { LadderCell } from './ladder.js';
3
- import { validateProfile } from './profile.js';
4
- import type { GuidelineCover, GuidelineTier, ModerationProfile, Outcome } from './profile.js';
3
+ import { validateProfile, withDurationDefaults } from './profile.js';
4
+ import type { GuidelineCover, GuidelineTier, ModerationProfile, Outcome, ResolvedProfile } from './profile.js';
5
5
  import type { CommunityRule, CommunityRules } from './rules.js';
6
6
  import { CONDUCT_LEVELS } from './types.js';
7
7
  import type { ConductLevel } from './types.js';
@@ -34,15 +34,26 @@ export interface CodeOfConductOptions {
34
34
  contactUrl?: string;
35
35
  }
36
36
 
37
+ /**
38
+ * The sections of the moderator guide a caller may leave out: `rules` (the Community Rules list) and `ladder` (the escalation
39
+ * ladder: its heading, the step note, the table and the notes on area and severe rules). The moderator hub draws both from data
40
+ * and asks for the rest of the guide.
41
+ */
42
+ export const GUIDE_SECTIONS = ['rules', 'ladder'] as const;
43
+ export type GuideSection = (typeof GUIDE_SECTIONS)[number];
44
+
37
45
  /** Options for {@link moderatorGuide}. */
38
46
  export interface ModeratorGuideOptions {
39
47
  format: DocumentFormat;
48
+ /** Sections to leave out. Default none: the whole guide. The rest keeps its order. */
49
+ omitSections?: readonly GuideSection[];
40
50
  }
41
51
 
42
52
  /** The policy as data, for tools that import it. */
43
53
  export interface PolicyJson {
44
54
  version: 1;
45
- profile: ModerationProfile;
55
+ /** With `durations` and `customDuration` filled in, so a profile written for 0.1.1 reads back with the two new keys. */
56
+ profile: ResolvedProfile;
46
57
  /** Every rule, retired ones included, in number order. */
47
58
  rules: CommunityRule[];
48
59
  }
@@ -207,6 +218,14 @@ function render(blocks: readonly Block[], format: DocumentFormat): string {
207
218
  // ---------------------------------------------------------------------------------------------------------------
208
219
  // Checks
209
220
 
221
+ function checkSections(sections: unknown): ReadonlySet<GuideSection> {
222
+ if (sections === undefined) return new Set();
223
+ if (!Array.isArray(sections) || !sections.every((x) => typeof x === 'string' && (GUIDE_SECTIONS as readonly string[]).includes(x))) {
224
+ throw new RangeError(`omitSections must be a list of: ${GUIDE_SECTIONS.join(', ')}`);
225
+ }
226
+ return new Set(sections as GuideSection[]);
227
+ }
228
+
210
229
  function checkFormat(format: unknown): DocumentFormat {
211
230
  if (typeof format !== 'string' || !FORMATS.includes(format)) {
212
231
  throw new RangeError("A document format must be 'markdown', 'html' or 'text'");
@@ -214,15 +233,21 @@ function checkFormat(format: unknown): DocumentFormat {
214
233
  return format as DocumentFormat;
215
234
  }
216
235
 
217
- /** The policy must be one the kit could enforce: the profile is validated (a `ProfileError` names the field). */
218
- function checkPolicy(policy: DocumentPolicy): void {
236
+ /**
237
+ * The policy must be one the kit could enforce: the profile is validated (a `ProfileError` names the field). Returns the snapshot
238
+ * the document is built from: the profile read ONCE (it may be a live getter) with `durations` and `customDuration` filled in
239
+ * for a profile written before they existed, and the rules.
240
+ */
241
+ function checkPolicy(policy: DocumentPolicy): { profile: ResolvedProfile; rules: CommunityRules } {
219
242
  const p: unknown = policy;
220
243
  if (typeof p !== 'object' || p === null) throw new TypeError('A document policy needs a profile and rules');
221
244
  const rules = (p as { rules?: unknown }).rules;
222
245
  if (typeof rules !== 'object' || rules === null || typeof (rules as { active?: unknown }).active !== 'function') {
223
246
  throw new TypeError('A document policy needs a profile and rules');
224
247
  }
225
- validateProfile((p as { profile?: unknown }).profile);
248
+ const profile = (p as { profile?: unknown }).profile;
249
+ validateProfile(profile);
250
+ return { profile: withDurationDefaults(profile), rules: rules as CommunityRules };
226
251
  }
227
252
 
228
253
  /**
@@ -325,8 +350,6 @@ function ruleLabels(rules: CommunityRules, numbers: readonly number[] | undefine
325
350
  const RECORD_STEPS =
326
351
  '0 is notes only, 1 is a warning, 2 is a chat or area restriction under 7 days (or two warnings), 3 is a restriction of 7 days or more or a ban under 7 days, 4 is a ban of 7 to 29 days, 5 is a ban of 30 days or more or anything permanent';
327
352
 
328
- const DEFAULT_AREA_RULES: readonly number[] = [5, 6];
329
-
330
353
  function areaRuleList(policy: DocumentPolicy): Array<{ number: number; title: string }> {
331
354
  return ruleLabels(policy.rules, policy.profile.areaRules ?? DEFAULT_AREA_RULES);
332
355
  }
@@ -427,12 +450,12 @@ function swearingForPlayer(profile: ModerationProfile): string {
427
450
  * name and `ProfileError` for an invalid profile.
428
451
  */
429
452
  export function codeOfConduct(policy: DocumentPolicy, options: CodeOfConductOptions): string {
430
- checkPolicy(policy);
453
+ const snapshot = checkPolicy(policy);
431
454
  const format = checkFormat(options.format);
432
455
  const gameName = typeof options.gameName === 'string' ? clean(options.gameName) : '';
433
456
  if (gameName === '') throw new RangeError('A code of conduct needs a game name');
434
457
  const href = safeLink(options.contactUrl);
435
- const { profile, rules } = policy;
458
+ const { profile, rules } = snapshot;
436
459
  const firstRule = rules.active()[0];
437
460
  const example = firstRule === undefined ? '' : ` (for example, CR ${firstRule.number})`;
438
461
 
@@ -446,8 +469,8 @@ export function codeOfConduct(policy: DocumentPolicy, options: CodeOfConductOpti
446
469
  ];
447
470
  for (const tier of profile.guidelines) blocks.push(...playerTierBlocks(profile, tier));
448
471
 
449
- const area = areaRuleList(policy);
450
- const severe = severeRuleList(policy);
472
+ const area = areaRuleList(snapshot);
473
+ const severe = severeRuleList(snapshot);
451
474
  if (area.length > 0 || severe.length > 0) blocks.push({ k: 'h', level: 3, text: 'Some rules work differently' });
452
475
  if (area.length > 0) {
453
476
  const names = area.map((r) => `CR ${r.number} (${r.title})`).join(' or ');
@@ -518,9 +541,10 @@ function aiForModerators(profile: ModerationProfile): string {
518
541
  * Retired rules are omitted. Throws `RangeError` for an unknown format and `ProfileError` for an invalid profile.
519
542
  */
520
543
  export function moderatorGuide(policy: DocumentPolicy, options: ModeratorGuideOptions): string {
521
- checkPolicy(policy);
544
+ const snapshot = checkPolicy(policy);
522
545
  const format = checkFormat(options.format);
523
- const { profile, rules } = policy;
546
+ const omit = checkSections(options.omitSections);
547
+ const { profile, rules } = snapshot;
524
548
 
525
549
  const blocks: Block[] = [
526
550
  { k: 'h', level: 1, text: `Moderator guide: ${profile.name}` },
@@ -529,8 +553,7 @@ export function moderatorGuide(policy: DocumentPolicy, options: ModeratorGuideOp
529
553
  k: 'p',
530
554
  text: 'This guide is generated from the moderation profile and the Community Rules in force, so it matches what the kit enforces. It is for the moderation team: do not publish it.',
531
555
  },
532
- { k: 'h', level: 2, text: 'Community Rules' },
533
- { k: 'ul', items: ruleItems(rules) },
556
+ ...(omit.has('rules') ? [] : ([{ k: 'h', level: 2, text: 'Community Rules' }, { k: 'ul', items: ruleItems(rules) }] as Block[])),
534
557
  { k: 'h', level: 2, text: 'Conduct levels' },
535
558
  {
536
559
  k: 'table',
@@ -562,27 +585,31 @@ export function moderatorGuide(policy: DocumentPolicy, options: ModeratorGuideOp
562
585
  k: 'p',
563
586
  text: 'Repeated applies while the person has no warning or restriction on record; once they do, the ladder below applies. At least one earlier note is always needed. Revoked notes, and notes older than the window, do not count. An escalation is never milder than the first-offense outcome.',
564
587
  },
565
- { k: 'h', level: 2, text: 'Escalation ladder' },
566
- {
567
- k: 'p',
568
- text: `A person's step is the heaviest action on their record in the last 90 days. Step ${RECORD_STEPS}.`,
569
- },
570
- {
571
- k: 'table',
572
- head: ['Step', 'Low / medium (banter, rude)', 'High (hostile with a record, severe)'],
573
- rows: profile.ladder.map((row) => [String(row.step), clean(row.lowMedium.label), clean(row.high.label)]),
574
- },
575
588
  );
576
- const area = areaRuleList(policy);
577
- if (area.length > 0) {
578
- blocks.push({
579
- k: 'p',
580
- text: `Rules that turn a chat restriction into a ban from public rooms and matchmaking at the same length: ${area.map((r) => `CR ${r.number}. ${r.title}`).join('; ')}.`,
581
- });
582
- }
583
- const severe = severeRuleList(policy);
584
- if (severe.length > 0) {
585
- blocks.push({ k: 'p', text: `Rules that always read the High column: ${severe.map((r) => `CR ${r.number}. ${r.title}`).join('; ')}.` });
589
+ if (!omit.has('ladder')) {
590
+ blocks.push(
591
+ { k: 'h', level: 2, text: 'Escalation ladder' },
592
+ {
593
+ k: 'p',
594
+ text: `A person's step is the heaviest action on their record in the last 90 days. Step ${RECORD_STEPS}.`,
595
+ },
596
+ {
597
+ k: 'table',
598
+ head: ['Step', 'Low / medium (banter, rude)', 'High (hostile with a record, severe)'],
599
+ rows: profile.ladder.map((row) => [String(row.step), clean(row.lowMedium.label), clean(row.high.label)]),
600
+ },
601
+ );
602
+ const area = areaRuleList(snapshot);
603
+ if (area.length > 0) {
604
+ blocks.push({
605
+ k: 'p',
606
+ text: `Rules that turn a chat restriction into a ban from public rooms and matchmaking at the same length: ${area.map((r) => `CR ${r.number}. ${r.title}`).join('; ')}.`,
607
+ });
608
+ }
609
+ const severe = severeRuleList(snapshot);
610
+ if (severe.length > 0) {
611
+ blocks.push({ k: 'p', text: `Rules that always read the High column: ${severe.map((r) => `CR ${r.number}. ${r.title}`).join('; ')}.` });
612
+ }
586
613
  }
587
614
 
588
615
  blocks.push(
@@ -624,8 +651,8 @@ export function moderatorGuide(policy: DocumentPolicy, options: ModeratorGuideOp
624
651
  * team-written value cannot add a line of policy. Retired rules are omitted.
625
652
  */
626
653
  export function agentBrief(policy: DocumentPolicy): string {
627
- checkPolicy(policy);
628
- const { profile, rules } = policy;
654
+ const snapshot = checkPolicy(policy);
655
+ const { profile, rules } = snapshot;
629
656
  const lines: string[] = [
630
657
  `Moderation policy for ${clean(profile.name)} (generated by Chatwarden)`,
631
658
  `Summary: ${clean(profile.summary)}`,
@@ -648,11 +675,11 @@ export function agentBrief(policy: DocumentPolicy): string {
648
675
  'Escalation after the first offense. Step = heaviest action on the record in the last 90 days. Low = banter and rude; high = hostile once the record has a warning or restriction, and severe:',
649
676
  ...profile.ladder.map((row) => `- step ${row.step}: low ${clean(row.lowMedium.label)} | high ${clean(row.high.label)}`),
650
677
  ];
651
- const area = areaRuleList(policy);
678
+ const area = areaRuleList(snapshot);
652
679
  if (area.length > 0) {
653
680
  lines.push(`A chat restriction becomes a ban from public rooms and matchmaking (same length) for: ${area.map((r) => `CR ${r.number}`).join(', ')}.`);
654
681
  }
655
- const severe = severeRuleList(policy);
682
+ const severe = severeRuleList(snapshot);
656
683
  if (severe.length > 0) lines.push(`Always read the high column for: ${severe.map((r) => `CR ${r.number}`).join(', ')}.`);
657
684
  lines.push(
658
685
  'Guidelines:',
@@ -677,8 +704,8 @@ export function agentBrief(policy: DocumentPolicy): string {
677
704
  * into `defineProfile` and `defineRules`. Throws `ProfileError` for an invalid profile.
678
705
  */
679
706
  export function policyJson(policy: DocumentPolicy): PolicyJson {
680
- checkPolicy(policy);
681
- return { version: 1, profile: structuredClone(policy.profile), rules: policy.rules.all() };
707
+ const snapshot = checkPolicy(policy);
708
+ return { version: 1, profile: structuredClone(snapshot.profile), rules: snapshot.rules.all() };
682
709
  }
683
710
 
684
711
  /** The four documents bound to one policy, as `cw.documents` exposes them. */
package/src/events.ts CHANGED
@@ -19,7 +19,16 @@ export type StaffRef = SubjectId;
19
19
  */
20
20
  export type KitEvent =
21
21
  /** A report was stored. `roomTags` are the adopter's own room tags at the time, not player text. */
22
- | { type: 'report.created'; reportId: string; createdAt: number; category: ReportCategory; roomTags: Readonly<Record<string, string>> }
22
+ | {
23
+ type: 'report.created';
24
+ reportId: string;
25
+ createdAt: number;
26
+ /** The 0.1.1 category the report is kept under (derived from the reason; `'other'` when none). */
27
+ category: ReportCategory;
28
+ /** The reason id the reporter gave, or null when they gave none. A hint, never the truth. Never the note. Always set by the kit from 0.1.2; optional in the type so an event built by 0.1.1 code still type-checks. */
29
+ reportedReason?: string | null;
30
+ roomTags: Readonly<Record<string, string>>;
31
+ }
23
32
  /** A decision closed a report. Emitted once per decision, never for a replay. */
24
33
  | { type: 'report.closed'; reportId: string; verdict: 'upheld' | 'noted' | 'no_action' | 'bad_faith'; at: number }
25
34
  /**
package/src/hasher.ts CHANGED
@@ -2,7 +2,7 @@
2
2
  // byte-compatible with Moxgate's identity hasher. The internal kind strings
3
3
  // 'playerKey' and 'ipHash' are Moxgate's and must not change, or existing
4
4
  // hashes stop matching.
5
- import { createHmac } from 'node:crypto';
5
+ import { hmacSha256Hex } from './crypto.js';
6
6
  import type { Hasher, Identifiers, RawWho } from './types.js';
7
7
 
8
8
  // 128 bits of the HMAC: plenty to avoid collisions, short enough to index.
@@ -14,7 +14,7 @@ export function makeHasher(secret: string): Hasher {
14
14
  // The kind prefix keeps the two spaces apart: a client key that happened to
15
15
  // equal an IP string must not produce the same value in both columns.
16
16
  const mac = (kind: string, input: string): string =>
17
- createHmac('sha256', secret).update(`${kind}:${input}`).digest('hex').slice(0, HASH_HEX_LEN);
17
+ hmacSha256Hex(secret, `${kind}:${input}`).slice(0, HASH_HEX_LEN);
18
18
  return {
19
19
  clientKey: (raw) => mac('playerKey', raw),
20
20
  ip: (raw) => mac('ipHash', raw),