@chatwarden/core 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (138) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +254 -2
  3. package/dist/src/audit.d.ts +119 -0
  4. package/dist/src/audit.d.ts.map +1 -0
  5. package/dist/src/audit.js +157 -0
  6. package/dist/src/audit.js.map +1 -0
  7. package/dist/src/chat.d.ts +232 -0
  8. package/dist/src/chat.d.ts.map +1 -0
  9. package/dist/src/chat.js +539 -0
  10. package/dist/src/chat.js.map +1 -0
  11. package/dist/src/chatwarden.d.ts +387 -0
  12. package/dist/src/chatwarden.d.ts.map +1 -0
  13. package/dist/src/chatwarden.js +458 -0
  14. package/dist/src/chatwarden.js.map +1 -0
  15. package/dist/src/crypto.d.ts +22 -0
  16. package/dist/src/crypto.d.ts.map +1 -0
  17. package/dist/src/crypto.js +193 -0
  18. package/dist/src/crypto.js.map +1 -0
  19. package/dist/src/decide.d.ts +188 -0
  20. package/dist/src/decide.d.ts.map +1 -0
  21. package/dist/src/decide.js +384 -0
  22. package/dist/src/decide.js.map +1 -0
  23. package/dist/src/documents.d.ts +78 -0
  24. package/dist/src/documents.d.ts.map +1 -0
  25. package/dist/src/documents.js +569 -0
  26. package/dist/src/documents.js.map +1 -0
  27. package/dist/src/doors.d.ts +57 -0
  28. package/dist/src/doors.d.ts.map +1 -0
  29. package/dist/src/doors.js +109 -0
  30. package/dist/src/doors.js.map +1 -0
  31. package/dist/src/events.d.ts +112 -0
  32. package/dist/src/events.d.ts.map +1 -0
  33. package/dist/src/events.js +75 -0
  34. package/dist/src/events.js.map +1 -0
  35. package/dist/src/evidence.d.ts +72 -0
  36. package/dist/src/evidence.d.ts.map +1 -0
  37. package/dist/src/evidence.js +100 -0
  38. package/dist/src/evidence.js.map +1 -0
  39. package/dist/src/hasher.d.ts +11 -0
  40. package/dist/src/hasher.d.ts.map +1 -0
  41. package/dist/src/hasher.js +33 -0
  42. package/dist/src/hasher.js.map +1 -0
  43. package/dist/src/index.d.ts +48 -0
  44. package/dist/src/index.d.ts.map +1 -0
  45. package/dist/src/index.js +28 -0
  46. package/dist/src/index.js.map +1 -0
  47. package/dist/src/ladder.d.ts +111 -0
  48. package/dist/src/ladder.d.ts.map +1 -0
  49. package/dist/src/ladder.js +292 -0
  50. package/dist/src/ladder.js.map +1 -0
  51. package/dist/src/limits.d.ts +52 -0
  52. package/dist/src/limits.d.ts.map +1 -0
  53. package/dist/src/limits.js +89 -0
  54. package/dist/src/limits.js.map +1 -0
  55. package/dist/src/log.d.ts +34 -0
  56. package/dist/src/log.d.ts.map +1 -0
  57. package/dist/src/log.js +75 -0
  58. package/dist/src/log.js.map +1 -0
  59. package/dist/src/mask.d.ts +12 -0
  60. package/dist/src/mask.d.ts.map +1 -0
  61. package/dist/src/mask.js +33 -0
  62. package/dist/src/mask.js.map +1 -0
  63. package/dist/src/mutes.d.ts +48 -0
  64. package/dist/src/mutes.d.ts.map +1 -0
  65. package/dist/src/mutes.js +193 -0
  66. package/dist/src/mutes.js.map +1 -0
  67. package/dist/src/notices.d.ts +168 -0
  68. package/dist/src/notices.d.ts.map +1 -0
  69. package/dist/src/notices.js +357 -0
  70. package/dist/src/notices.js.map +1 -0
  71. package/dist/src/profile.d.ts +133 -0
  72. package/dist/src/profile.d.ts.map +1 -0
  73. package/dist/src/profile.js +581 -0
  74. package/dist/src/profile.js.map +1 -0
  75. package/dist/src/rateLimit.d.ts +13 -0
  76. package/dist/src/rateLimit.d.ts.map +1 -0
  77. package/dist/src/rateLimit.js +35 -0
  78. package/dist/src/rateLimit.js.map +1 -0
  79. package/dist/src/reports.d.ts +112 -0
  80. package/dist/src/reports.d.ts.map +1 -0
  81. package/dist/src/reports.js +266 -0
  82. package/dist/src/reports.js.map +1 -0
  83. package/dist/src/retention.d.ts +70 -0
  84. package/dist/src/retention.d.ts.map +1 -0
  85. package/dist/src/retention.js +105 -0
  86. package/dist/src/retention.js.map +1 -0
  87. package/dist/src/rules.d.ts +74 -0
  88. package/dist/src/rules.d.ts.map +1 -0
  89. package/dist/src/rules.js +193 -0
  90. package/dist/src/rules.js.map +1 -0
  91. package/dist/src/sanctions.d.ts +155 -0
  92. package/dist/src/sanctions.d.ts.map +1 -0
  93. package/dist/src/sanctions.js +329 -0
  94. package/dist/src/sanctions.js.map +1 -0
  95. package/dist/src/staffReports.d.ts +72 -0
  96. package/dist/src/staffReports.d.ts.map +1 -0
  97. package/dist/src/staffReports.js +98 -0
  98. package/dist/src/staffReports.js.map +1 -0
  99. package/dist/src/strikes.d.ts +87 -0
  100. package/dist/src/strikes.d.ts.map +1 -0
  101. package/dist/src/strikes.js +219 -0
  102. package/dist/src/strikes.js.map +1 -0
  103. package/dist/src/subjects.d.ts +102 -0
  104. package/dist/src/subjects.d.ts.map +1 -0
  105. package/dist/src/subjects.js +334 -0
  106. package/dist/src/subjects.js.map +1 -0
  107. package/dist/src/types.d.ts +624 -0
  108. package/dist/src/types.d.ts.map +1 -0
  109. package/dist/src/types.js +7 -0
  110. package/dist/src/types.js.map +1 -0
  111. package/package.json +49 -4
  112. package/src/audit.ts +240 -0
  113. package/src/chat.ts +698 -0
  114. package/src/chatwarden.ts +826 -0
  115. package/src/crypto.ts +206 -0
  116. package/src/decide.ts +544 -0
  117. package/src/documents.ts +692 -0
  118. package/src/doors.ts +144 -0
  119. package/src/events.ts +154 -0
  120. package/src/evidence.ts +166 -0
  121. package/src/hasher.ts +36 -0
  122. package/src/index.ts +201 -0
  123. package/src/ladder.ts +365 -0
  124. package/src/limits.ts +146 -0
  125. package/src/log.ts +78 -0
  126. package/src/mask.ts +30 -0
  127. package/src/mutes.ts +190 -0
  128. package/src/notices.ts +450 -0
  129. package/src/profile.ts +717 -0
  130. package/src/rateLimit.ts +45 -0
  131. package/src/reports.ts +350 -0
  132. package/src/retention.ts +153 -0
  133. package/src/rules.ts +224 -0
  134. package/src/sanctions.ts +439 -0
  135. package/src/staffReports.ts +148 -0
  136. package/src/strikes.ts +236 -0
  137. package/src/subjects.ts +350 -0
  138. package/src/types.ts +749 -0
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,255 @@
1
- # Temporary Holding Version
1
+ # @chatwarden/core
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The moderation engine of Chatwarden, the open-source chat moderation kit for games. You give it your chat lines, your reports
4
+ and a small description of how to tell players apart. It decides what to deliver, what to refuse, who to time out, and what a
5
+ moderator sees. It does not open sockets, serve HTTP or touch a disk: those are the other packages.
6
+
7
+ What it does:
8
+
9
+ - **Chat.** Checks each line against your matcher, a length and rate limit, and the sanctions in force. A line is delivered, or
10
+ refused with a reason.
11
+ - **Reports.** Players report each other. The kit keeps the evidence, limits abuse of the report button, and builds the
12
+ moderators' queue.
13
+ - **Decisions and sanctions.** A moderator decides a report. The kit writes the warnings, timeouts and bans, with a notice for
14
+ the player and an audit row for the staff.
15
+ - **A written standard.** One preset (`relaxed`, `standard` or `strict`) sets the ladder, the starter Community Rules and the
16
+ code of conduct players read.
17
+ - **Identity without identifiers.** Client keys and IP addresses are hashed on the way in, and people are tracked by an opaque
18
+ subject id.
19
+
20
+ It has no runtime dependencies and imports no `node:` module, so it also runs in a browser.
21
+
22
+ Status: pre-release, as-is, no support promise.
23
+
24
+ ## Install
25
+
26
+ ```sh
27
+ npm install @chatwarden/core
28
+ ```
29
+
30
+ Core stores nothing itself. To run the quick start below you also need a store and a matcher:
31
+
32
+ ```sh
33
+ npm install @chatwarden/core @chatwarden/store-sqlite @chatwarden/matcher
34
+ ```
35
+
36
+ `@chatwarden/store-sqlite` and `@chatwarden/matcher` (and the other kit packages) list `@chatwarden/core` as a peer dependency,
37
+ so your project has exactly one copy of it. Node 22.13 or newer. The package is ESM only; a CommonJS app can `require()` it on
38
+ Node 22.13 or newer (see the [root README](https://github.com/hainix/chatwarden#commonjs)).
39
+
40
+ ## Quick start
41
+
42
+ Copy this, then change `platform.identify` to read your own connections.
43
+
44
+ ```ts
45
+ import { createChatwarden, type Platform } from '@chatwarden/core';
46
+ import { LiveTerms } from '@chatwarden/matcher';
47
+ import { syntheticTermPack } from '@chatwarden/matcher/fixtures';
48
+ import { openStore } from '@chatwarden/store-sqlite';
49
+
50
+ // What one of your connections looks like. Yours may be a socket, a session or a request.
51
+ interface Connection {
52
+ playerToken: string; // a stable, secret per-player value (not shown to other players)
53
+ remoteAddress: string; // the REAL client address; behind a proxy, parse X-Forwarded-For yourself
54
+ }
55
+
56
+ // How to find out who is behind a connection. Give raw values: the kit hashes them before it stores anything.
57
+ const platform: Platform = {
58
+ identify: (ctx) => {
59
+ const conn = ctx as Connection;
60
+ return { clientKey: conn.playerToken, ip: conn.remoteAddress };
61
+ },
62
+ };
63
+
64
+ const store = openStore({ path: './chatwarden.db' });
65
+
66
+ // The slur matcher. This demo uses the invented test words; use your own term pack in production.
67
+ const matcher = new LiveTerms({ store, pack: syntheticTermPack(), clock: { now: () => Date.now() } });
68
+ await matcher.load();
69
+
70
+ const cw = await createChatwarden({
71
+ store,
72
+ secret: process.env.CHATWARDEN_SECRET!, // 32+ random characters; keep it stable and private
73
+ platform,
74
+ matcher,
75
+ profile: 'standard', // 'relaxed', 'standard' or 'strict'
76
+ });
77
+
78
+ // A player connects: seat them in a room under a display name.
79
+ const connection: Connection = { playerToken: 'token-from-your-login', remoteAddress: '203.0.113.7' };
80
+ cw.rooms.seatConnection('lobby', 'seat-1', connection, 'Ada');
81
+ cw.rooms.seat('lobby', 'seat-2', { clientKey: 'another-players-token', ip: '198.51.100.4' }, 'Bo'); // or by raw identity
82
+
83
+ // A chat line arrives: ask the kit what to do with it.
84
+ const result = cw.chat.accept('lobby', 'seat-1', 'hello everyone');
85
+ if ('deliver' in result) {
86
+ console.log('send to the room:', result.deliver.text); // may be starred if you turned profanity starring on
87
+ } else {
88
+ console.log('tell this player only:', result.refuse.reason); // 'blocked', 'rate', 'restricted', ...
89
+ }
90
+
91
+ // Ada reports Bo from inside your game.
92
+ const filed = await cw.reports.submit({
93
+ roomId: 'lobby',
94
+ reporterSeat: 'seat-1',
95
+ targetSeat: 'seat-2',
96
+ category: 'harassment',
97
+ note: 'kept at it after I asked them to stop',
98
+ });
99
+ console.log(filed.ok ? `report ${filed.reportId} filed` : `not filed: ${filed.refused}`);
100
+
101
+ await cw.close(); // flushes background writes and closes the store; call it on shutdown
102
+ ```
103
+
104
+ For the moderators' screens and the player's notices, mount the routes in
105
+ [`@chatwarden/http`](https://github.com/hainix/chatwarden/tree/main/packages/http) rather than calling the facade by hand.
106
+
107
+ ## What you get back
108
+
109
+ `createChatwarden` resolves to one object, `cw`, with these parts (the TypeScript types are the full reference):
110
+
111
+ | Part | What it is for |
112
+ | --- | --- |
113
+ | `cw.rooms` | `seat`, `seatConnection`, `unseat`, `close`: who is in which seat of which room. |
114
+ | `cw.chat.accept(room, seat, text)` | The answer for one line: `{ deliver }` or `{ refuse: { reason } }`. `visibleTo` applies a viewer's mutes. `restricted(who)` says whether a person is chat-restricted, for typing indicators. |
115
+ | `cw.mutes` | A player mutes another player for themselves only. |
116
+ | `cw.reports` | `submit` (players), `list` and `get` (staff). |
117
+ | `cw.decide(input)` | A moderator closes a report and writes the sanctions and notices in one transaction. Safe to send twice. |
118
+ | `cw.sanctions` | `apply` and `revoke`, for a moderator who acts without a report. |
119
+ | `cw.notices` | A player's pending notices, acknowledgements and "My record". Built so no identifier can leak. |
120
+ | `cw.doors` | `check` a person at the door (login, join) against bans. |
121
+ | `cw.names.check` | May a player use this as a name? |
122
+ | `cw.history`, `cw.suggest` | A person's recent record, and what the preset suggests as the next step. |
123
+ | `cw.rules`, `cw.profile`, `cw.limits`, `cw.summary`, `cw.documents` | The rules, standard and numbers in force, and the written code of conduct and guides. |
124
+ | `cw.gaps`, `cw.audit` | Rule gaps for the periodic review, and the staff audit trail. |
125
+ | `cw.on(type, listener)` | Events: `report.created`, `report.closed`, `sanction.applied`, `sanction.revoked`, `gap.created`, `auto.restricted`. |
126
+ | `cw.purge`, `cw.ready`, `cw.flush`, `cw.close` | Housekeeping. |
127
+
128
+ ## Deciding a report
129
+
130
+ A moderator reads a report and decides it with one call. `cw.decide` closes the report, writes the sanction, writes the player's
131
+ notice and tells the people involved, all in one transaction, and sending the same decision twice applies nothing twice.
132
+
133
+ ```ts
134
+ import type { DecisionResult } from '@chatwarden/core';
135
+
136
+ // The moderator decides the open report: a warning that shows the player their latest line.
137
+ const report = cw.reports.list({ status: 'open' }).items[0]!;
138
+ const decided: DecisionResult = await cw.decide({
139
+ reportId: report.id,
140
+ verdict: 'upheld', // 'noted', 'no_action' and 'bad_faith' are the others
141
+ actor: 'moderator@example.com', // who decided, for the audit trail
142
+ reason: 'kept insulting a teammate', // private: a player never sees it
143
+ actions: [{ subject: report.targetPerson, kind: 'warning', durationMs: null, rule: 2, lineIds: report.ownLineIds[report.targetPerson]?.slice(-1) }],
144
+ });
145
+ console.log(decided.ok ? `applied ${decided.groups.length} action` : `not applied: ${decided.error}`);
146
+ ```
147
+
148
+ `subject` is the staff reference the report names (`report.targetPerson`); it never goes to a player. `rule` must be an active Community
149
+ Rule, or `'uncovered'` with a `gapNote`. `lineIds` picks up to five of that player's own lines in the report to quote in their notice,
150
+ with blocked words starred out. A timeout is `kind: 'chat'` with `durationMs`. `cw.suggest(subject, level, rule)` says what the preset
151
+ would do next, for a moderator who wants a starting point. A failing store rejects the call, so catch it.
152
+
153
+ ## Typing indicators
154
+
155
+ Do not show a "typing..." indicator for a player who cannot chat. `cw.chat.restricted(who, { roomId, seatId })` runs the
156
+ same decision as `accept` (a chat restriction, a ban, or the automatic timeout), without sending a line. It is
157
+ synchronous and has no side effects: it spends no rate budget and writes no evidence, strike, event or notice.
158
+
159
+ ```ts
160
+ import type { Chatwarden, RawWho } from '@chatwarden/core';
161
+
162
+ // Call it when a client says "I am typing", after `cw.rooms.seat` for that seat. `who` is what your platform's
163
+ // `identify` returned for this connection on the server, never a key or account the client sent.
164
+ function relayTyping(cw: Chatwarden, who: RawWho, roomId: string, seatId: string, tell: () => void): void {
165
+ const { restricted, until, kind } = cw.chat.restricted(who, { roomId, seatId });
166
+ if (restricted) return; // drop it quietly: do not broadcast their typing
167
+ tell();
168
+ void until; // epoch ms when it ends (null = permanent), only for the person's own sanction
169
+ void kind; // 'chat', 'ban' or 'auto' (the automatic timeout), only for their own sanction
170
+ }
171
+ ```
172
+
173
+ With both `roomId` and `seatId` the answer equals what `accept` would say for that seat. Leave them out and an
174
+ automatic timeout that was kept only in memory (the store could not take it, or a guest with no key and no account earned
175
+ it) is looked up by person instead; a guest cannot be found that way, because one guest cannot be told from another.
176
+ The `gate` option is not consulted: a gate refusal is not a restriction.
177
+
178
+ It is safe to answer a player about themselves from their own client, because it reveals nothing about anyone else. A
179
+ player who is restricted only because they share an address with someone else's sanction gets
180
+ `{ restricted: true, until: null, kind: null }`: they cannot chat, and they are told nothing about the other person. The
181
+ address checked is the one `seat` last recorded for the person (as in `accept`), not `who.ip`, and an address alone finds
182
+ nobody. A lookup that fails reads as `restricted: false` and is logged at most once a minute (error class only, with a count of
183
+ the failures held back).
184
+
185
+ ## Browser support
186
+
187
+ The package imports no `node:` module, so a bundler (esbuild, Vite, webpack) builds it for a browser with nothing external and no
188
+ polyfill. Pair it with [`@chatwarden/store-memory`](https://github.com/hainix/chatwarden/tree/main/packages/store-memory), which
189
+ is also browser-safe, and with `@chatwarden/matcher` for the live matcher. That is what the repository's CI bundles and runs,
190
+ in a context with no `process`, `Buffer` or `require`, through a full report, decision and notice flow.
191
+
192
+ The hashing of client keys and IP addresses uses `node:crypto` when the runtime offers it (looked up at run time through
193
+ `process.getBuiltinModule`, never imported) and a small pure-JS SHA-256 and HMAC-SHA256 where it does not. Both give the same
194
+ bytes, and they match the hashes of 0.1.0, so moving a store between a server and a browser build never unlinks a stored hash.
195
+ The pure-JS path is slower, which only matters for a very large number of lookups. A browser build is meant for tests, demos and
196
+ tools; the kit still decides on a server you control, because anything running on a player's machine can be changed by that
197
+ player. `cw.chat.restricted(who, { roomId, seatId })` (see "Typing indicators") is a plain synchronous call and works the same
198
+ in a browser.
199
+
200
+ ## Options
201
+
202
+ `createChatwarden(options)`. Only `store`, `secret` and `platform` are required.
203
+
204
+ | Option | What it does |
205
+ | --- | --- |
206
+ | `store` | Where moderation state lives, for example `openStore(...)` from `@chatwarden/store-sqlite`. |
207
+ | `secret` | Keys the client-key and IP hashes. Keep it stable: changing it unlinks every stored hash. |
208
+ | `platform` | `identify(ctx)` returns `{ clientKey?, accountId?, ip? }` for a connection; optional `notify(subject, event)` tells you a player has notices waiting. |
209
+ | `matcher` | Your slur matcher (`LiveTerms` from `@chatwarden/matcher`). Without one, nothing is ever blocked. |
210
+ | `profanity` | A ready profanity filter. What happens to a profane line is the profile's call (`allow`, `star` or `refuse`). |
211
+ | `profanityPackage` | `{ createProfanityFilter }` from `@chatwarden/profanity`; the kit builds the filter from the profile. Not used when `profanity` is given. |
212
+ | `clock` | `{ now() }`. Defaults to the system clock; tests pass their own. |
213
+ | `enabled` | A kill switch, read on every call. Return false to stop enforcement and report intake. |
214
+ | `gate` | `(roomId, subject) => boolean`: who may chat. False refuses the line with `'gate'`. |
215
+ | `onReport` | Told once for each stored report. It carries subject ids and the evidence: staff channels only. |
216
+ | `onAutoRestrict` | Told when a blocked line earned an automatic timeout. The same moment is also the `auto.restricted` event. |
217
+ | `retention` | How long rows are kept and how often the purge runs (every 6 hours by default), or `false` to run `purge()` yourself. Defaults: reports 90 days, strikes 30, notices 90, audit 365. Floors apply. |
218
+ | `profile` | `'relaxed'`, `'standard'` (default), `'strict'`, or your own profile from `defineProfile`. |
219
+ | `overrides` | Changes to the profile, merged onto it (`{ profanity: { mode: 'allow' } }`). A list you give replaces the preset's list. |
220
+ | `limits` | The numbers the kit enforces: line length and rate, strikes and timeouts, report limits. Each must be a whole number above 0. |
221
+ | `logger` | `{ warn(event, detail?) }`. Defaults to `console.warn`. It only ever receives an event name and an error class. |
222
+ | `rules` | The numbered Community Rules, from `defineRules`. Defaults to the preset's starter set. |
223
+ | `autoRestrictRule` | The rule number the automatic slur filter cites (default 1). Must be an active rule. |
224
+
225
+ Bad options throw at creation (`ProfileError`, `RangeError`), before the store is touched.
226
+
227
+ ## Security notes
228
+
229
+ - **What is hashed.** A client key and an IP address are hashed with HMAC-SHA256 under your `secret` (the first 128 bits, with a
230
+ separate key space for each kind) before they are stored or compared. The raw values are never written. An account id is not
231
+ hashed: it is stored exactly as you give it, so pass an opaque id, never an email address or a name.
232
+ - **The secret.** Keep `secret` out of your repository and your logs. Anyone who holds both the secret and the database can
233
+ test a guessed IP address against the stored hashes. Changing it unlinks everyone's history, so rotate it on purpose, not by accident.
234
+ - **What is never logged.** The kit never logs chat text, a client key, an IP address, a hash, a subject id, a term or a reason.
235
+ A log line carries an event name and, at most, the error class (`chatwarden.purge_failed`, `error: 'Error'`). A logger that
236
+ throws is swallowed and never breaks chat.
237
+ - **Subject ids are staff-only.** A subject id names a person. It appears in staff reads (`cw.reports`, `cw.decide`, `cw.history`,
238
+ `cw.on` events, `onReport`) and in `platform.notify`, where you use it only on the server to find that player's connection.
239
+ Never send a subject id to a player, a public channel or a browser. Everything meant for a player (`cw.notices`, the code of
240
+ conduct, a refusal) is built without one.
241
+ - **Chat text is kept in two places only.** An evidence buffer in memory (the last 100 lines or 15 minutes of each room), and the
242
+ excerpt copied into a report or a notice when one is made. Reports and notices are deleted by retention. A player's notice
243
+ quotes only their own lines.
244
+ - **Moderators' words stay with moderators.** A decision's reason, a gap note, a reporter's note and a moderator's identity are
245
+ never shown to a player.
246
+ - **The kit enforces nothing about who may call it.** It has no login. Put your own authentication in front of every staff read,
247
+ which is what the `authorize` hook of `@chatwarden/http` is for.
248
+
249
+ ## Links
250
+
251
+ - [Chatwarden on GitHub](https://github.com/hainix/chatwarden) and the [root README](https://github.com/hainix/chatwarden#readme)
252
+ - [`@chatwarden/http`](https://github.com/hainix/chatwarden/tree/main/packages/http): routes for moderators and players, health probes, webhooks
253
+ - [`@chatwarden/store-sqlite`](https://github.com/hainix/chatwarden/tree/main/packages/store-sqlite), [`@chatwarden/matcher`](https://github.com/hainix/chatwarden/tree/main/packages/matcher), [`@chatwarden/profanity`](https://github.com/hainix/chatwarden/tree/main/packages/profanity), [`@chatwarden/discord`](https://github.com/hainix/chatwarden/tree/main/packages/discord)
254
+ - [Report a problem](https://github.com/hainix/chatwarden/issues)
255
+ - [Licence: Apache-2.0](https://github.com/hainix/chatwarden/blob/main/LICENSE)
@@ -0,0 +1,119 @@
1
+ import type { Clock, Logger, Store } from './types.js';
2
+ /** What a staff member may do. Ordered from least to most. */
3
+ export declare const ROLES: readonly ["moderator", "senior", "owner"];
4
+ export type Role = (typeof ROLES)[number];
5
+ /**
6
+ * The closed list of things the audit trail records. The `term.*` and `exception.*` names also cover the rows the
7
+ * term editor (`LiveTerms`) wrote before the trail existed.
8
+ */
9
+ export declare const AUDIT_ACTIONS: readonly ["report.view", "report.decide", "sanction.apply", "sanction.revoke", "gap.close", "term.add", "term.update", "term.toggle", "exception.add", "exception.update", "exception.toggle", "history.view", "suggest", "policy.view"];
10
+ export type AuditAction = (typeof AUDIT_ACTIONS)[number];
11
+ /** What an entry points at: a report id, a sanction group id, a person (a staff ref), a term id or an exception id. */
12
+ export declare const AUDIT_TARGET_TYPES: readonly ["report", "sanction", "person", "term", "exception"];
13
+ export type AuditTargetType = (typeof AUDIT_TARGET_TYPES)[number];
14
+ export interface AuditTarget {
15
+ type: AuditTargetType;
16
+ /**
17
+ * An id: 1..64 characters of `A-Z a-z 0-9 _ . : -`. It holds ids only (a report id, a sanction group id, a
18
+ * subject id, a term id), never text: pass the id of a term, not the term.
19
+ */
20
+ ref: string;
21
+ }
22
+ /** What {@link AuditService.record} takes. Nothing else is read, so nothing else can be stored. */
23
+ export interface AuditRecordInput {
24
+ /**
25
+ * The staff member: a staff ref or login, 1..128 characters of `A-Z a-z 0-9 _ . : @ + -`, no whitespace. Never a
26
+ * display name or any message. (Rows written before the trail existed may carry other actors; `list` returns
27
+ * them as they are.)
28
+ */
29
+ actor: string;
30
+ role: Role;
31
+ action: AuditAction;
32
+ target?: AuditTarget;
33
+ }
34
+ /** One entry as the store keeps and returns it. There is no field for chat text, a reason or a note. */
35
+ export interface AuditRow {
36
+ id: string;
37
+ /** Epoch ms. */
38
+ at: number;
39
+ actor: string;
40
+ /** Null for an entry written before roles existed. */
41
+ role: Role | null;
42
+ action: AuditAction;
43
+ target: AuditTarget | null;
44
+ }
45
+ /** What {@link Store.listAudit} takes. */
46
+ export interface AuditListQuery {
47
+ /** Epoch ms; only entries before this (exclusive), or at it with an id below `beforeId`. */
48
+ before?: number;
49
+ beforeId?: string;
50
+ /** Clamped to 1..200 by the store. */
51
+ limit: number;
52
+ actor?: string;
53
+ action?: AuditAction;
54
+ }
55
+ /** One entry of `cw.audit.list`: `target` is absent when the entry had none. */
56
+ export interface AuditItem {
57
+ id: string;
58
+ at: number;
59
+ actor: string;
60
+ role: Role | null;
61
+ action: AuditAction;
62
+ target?: AuditTarget;
63
+ }
64
+ /** What `cw.audit.list` takes. `limit` is required. */
65
+ export interface AuditQuery {
66
+ /** The `next` of the previous page. Omit or null for the first page. */
67
+ before?: string | null;
68
+ /** An integer from 1 to 200; anything else throws `RangeError`. */
69
+ limit: number;
70
+ actor?: string;
71
+ action?: AuditAction;
72
+ }
73
+ /** One page, newest first. `next` is an opaque cursor for `before`, or null when this page was not full. */
74
+ export interface AuditPage {
75
+ items: AuditItem[];
76
+ next: string | null;
77
+ }
78
+ /** The largest page. */
79
+ export declare const AUDIT_PAGE_MAX = 200;
80
+ /** A list query that cannot be answered: a `before` cursor we did not issue, or an unknown `action` / bad `actor`. */
81
+ export declare class AuditQueryError extends Error {
82
+ readonly field: 'before' | 'action' | 'actor';
83
+ constructor(field: 'before' | 'action' | 'actor');
84
+ }
85
+ /** True when `actor` is a string the audit trail accepts: 1..128 characters of `A-Z a-z 0-9 _ . : @ + -`. */
86
+ export declare const isValidAuditActor: (actor: unknown) => actor is string;
87
+ /** The opaque cursor for "older than this entry": base64url of `at:id`. */
88
+ export declare function encodeAuditCursor(at: number, id: string): string;
89
+ /** Read a cursor made by {@link encodeAuditCursor}; throws {@link AuditQueryError} for anything else. */
90
+ export declare function decodeAuditCursor(cursor: unknown): {
91
+ at: number;
92
+ id: string;
93
+ };
94
+ /**
95
+ * The staff audit trail: who (actor and role) did what (a name from {@link AUDIT_ACTIONS}) to which id, and when.
96
+ * It stores no chat text, reason, note or evidence: there is no field for any, and a target must look like an id.
97
+ */
98
+ export declare class AuditService {
99
+ private readonly store;
100
+ private readonly clock;
101
+ private readonly logger;
102
+ constructor(deps: {
103
+ store: Store;
104
+ clock: Clock;
105
+ logger?: Logger | undefined;
106
+ });
107
+ /**
108
+ * Write one entry, now. Synchronous and fenced: it never throws, and returns false (nothing written, one log line
109
+ * carrying the event name and at most the error class) for an input outside the closed lists or a store failure.
110
+ */
111
+ record(input: AuditRecordInput): boolean;
112
+ /**
113
+ * One page of the trail, newest first (ties on `at` by id, newest id first). `limit` must be an integer from 1 to
114
+ * 200 (`RangeError` otherwise). An unknown `action`, a bad `actor` or a `before` we did not issue is an
115
+ * {@link AuditQueryError}. Messages never echo the input.
116
+ */
117
+ list(q: AuditQuery): AuditPage;
118
+ }
119
+ //# sourceMappingURL=audit.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"audit.d.ts","sourceRoot":"","sources":["../../src/audit.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,YAAY,CAAC;AAEvD,8DAA8D;AAC9D,eAAO,MAAM,KAAK,2CAA4C,CAAC;AAC/D,MAAM,MAAM,IAAI,GAAG,CAAC,OAAO,KAAK,CAAC,CAAC,MAAM,CAAC,CAAC;AAE1C;;;GAGG;AACH,eAAO,MAAM,aAAa,0OAehB,CAAC;AACX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