@joliegg/moderation 0.4.4 → 0.8.0

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 (55) hide show
  1. package/LICENSE.md +21 -118
  2. package/README.md +4 -6
  3. package/dist/actions.d.ts +28 -0
  4. package/dist/actions.js +48 -0
  5. package/dist/client.d.ts +19 -0
  6. package/dist/client.js +97 -0
  7. package/dist/{url-blacklist.json → data/url-blacklist.json} +1 -0
  8. package/dist/index.d.ts +3 -41
  9. package/dist/index.js +20 -213
  10. package/dist/providers/aws.d.ts +11 -0
  11. package/dist/providers/aws.js +58 -0
  12. package/dist/providers/google.d.ts +21 -0
  13. package/dist/providers/google.js +61 -0
  14. package/dist/providers/webrisk.d.ts +9 -0
  15. package/dist/providers/webrisk.js +33 -0
  16. package/dist/raid/age.d.ts +6 -0
  17. package/dist/raid/age.js +19 -0
  18. package/dist/raid/detector.d.ts +56 -0
  19. package/dist/raid/detector.js +88 -0
  20. package/dist/raid/index.d.ts +2 -0
  21. package/dist/raid/index.js +18 -0
  22. package/dist/spam/cache.d.ts +99 -0
  23. package/dist/spam/cache.js +210 -0
  24. package/dist/spam/index.d.ts +1 -0
  25. package/dist/spam/index.js +17 -0
  26. package/dist/text/index.d.ts +2 -0
  27. package/dist/text/index.js +18 -0
  28. package/dist/text/mentions.d.ts +31 -0
  29. package/dist/text/mentions.js +55 -0
  30. package/dist/text/normalize.d.ts +15 -0
  31. package/dist/text/normalize.js +45 -0
  32. package/dist/types/config.d.ts +13 -0
  33. package/dist/types/config.js +2 -0
  34. package/dist/types/index.d.ts +3 -10
  35. package/dist/types/index.js +15 -0
  36. package/package.json +61 -20
  37. package/src/actions.ts +50 -0
  38. package/src/client.ts +121 -0
  39. package/src/{url-blacklist.json → data/url-blacklist.json} +1 -0
  40. package/src/index.ts +3 -277
  41. package/src/providers/aws.ts +58 -0
  42. package/src/providers/google.ts +63 -0
  43. package/src/providers/webrisk.ts +30 -0
  44. package/src/raid/age.ts +19 -0
  45. package/src/raid/detector.ts +122 -0
  46. package/src/raid/index.ts +2 -0
  47. package/src/spam/cache.ts +342 -0
  48. package/src/spam/index.ts +1 -0
  49. package/src/text/index.ts +2 -0
  50. package/src/text/mentions.ts +91 -0
  51. package/src/text/normalize.ts +43 -0
  52. package/src/types/config.ts +14 -0
  53. package/src/types/index.ts +5 -11
  54. /package/dist/{url-shorteners.json → data/url-shorteners.json} +0 -0
  55. /package/src/{url-shorteners.json → data/url-shorteners.json} +0 -0
package/src/actions.ts ADDED
@@ -0,0 +1,50 @@
1
+ import type { Severity } from './types';
2
+
3
+ /**
4
+ * Moderation actions taxonomy. These should be stable so they can be persisted
5
+ * as a canonical list of actions.
6
+ */
7
+ export const ACTION_TYPES = {
8
+ TIMEOUT: 'timeout',
9
+ BAN: 'ban',
10
+ KICK: 'kick',
11
+ WARN: 'warn',
12
+ DELETE: 'delete',
13
+ RESTRICT: 'restrict',
14
+ APPEAL_APPROVE: 'appeal_approve',
15
+ APPEAL_DENY: 'appeal_deny',
16
+ MENTION_SPAM: 'mention_spam',
17
+ NEW_USER_RESTRICT: 'new_user_restrict',
18
+ SPAM_DETECTED: 'spam_detected',
19
+ ESCALATION: 'escalation',
20
+ RAID_DETECTED: 'raid_detected',
21
+ RAID_TIMEOUT: 'raid_timeout',
22
+ RAID_JOIN: 'raid_join',
23
+ PERMISSION_BLOCK: 'permission_block',
24
+ UNTIMEOUT: 'untimeout',
25
+ UNBAN: 'unban',
26
+ } as const;
27
+
28
+ export type ActionType = typeof ACTION_TYPES[keyof typeof ACTION_TYPES];
29
+
30
+ /** Default severity per action type. */
31
+ export const SEVERITY_BY_ACTION: Record<ActionType, Severity> = {
32
+ timeout: 'medium',
33
+ ban: 'critical',
34
+ kick: 'high',
35
+ warn: 'low',
36
+ delete: 'low',
37
+ restrict: 'medium',
38
+ appeal_approve: 'low',
39
+ appeal_deny: 'low',
40
+ mention_spam: 'medium',
41
+ new_user_restrict: 'low',
42
+ spam_detected: 'medium',
43
+ escalation: 'high',
44
+ raid_detected: 'critical',
45
+ raid_timeout: 'medium',
46
+ raid_join: 'low',
47
+ permission_block: 'low',
48
+ untimeout: 'low',
49
+ unban: 'low',
50
+ };
package/src/client.ts ADDED
@@ -0,0 +1,121 @@
1
+ import { Rekognition } from '@aws-sdk/client-rekognition';
2
+ import { LanguageServiceClient } from '@google-cloud/language';
3
+ import { SpeechClient } from '@google-cloud/speech';
4
+
5
+ import { GoogleLanguageProvider, GoogleSpeechProvider, fetchAudio } from './providers/google';
6
+ import { RekognitionProvider } from './providers/aws';
7
+ import { WebRiskProvider } from './providers/webrisk';
8
+ import URLBlackList from './data/url-blacklist.json';
9
+ import URLShortenerList from './data/url-shorteners.json';
10
+
11
+ import type { ModerationCategory, ModerationConfiguration, ModerationResult } from './types';
12
+
13
+ /**
14
+ * Composes text / image / link / audio moderation across the configured
15
+ * providers.
16
+ */
17
+ export class ModerationClient {
18
+ private googleLanguage?: GoogleLanguageProvider;
19
+ private googleSpeech?: GoogleSpeechProvider;
20
+ private aws?: RekognitionProvider;
21
+ private webRisk?: WebRiskProvider;
22
+ private banList: string[] = [];
23
+ private urlBlackList: string[] = [];
24
+
25
+ constructor(configuration: ModerationConfiguration) {
26
+ if (configuration.aws) {
27
+ this.aws = new RekognitionProvider(new Rekognition(configuration.aws));
28
+ }
29
+
30
+ if (typeof configuration.google?.keyFile === 'string') {
31
+ this.googleLanguage = new GoogleLanguageProvider(
32
+ new LanguageServiceClient({ keyFile: configuration.google.keyFile })
33
+ );
34
+
35
+ this.googleSpeech = new GoogleSpeechProvider(
36
+ new SpeechClient({ keyFile: configuration.google.keyFile })
37
+ );
38
+ }
39
+
40
+ if (typeof configuration.google?.apiKey === 'string') {
41
+ this.webRisk = new WebRiskProvider(configuration.google.apiKey);
42
+ }
43
+
44
+ if (Array.isArray(configuration.banList)) {
45
+ this.banList = configuration.banList;
46
+ }
47
+
48
+ if (Array.isArray(configuration.urlBlackList)) {
49
+ this.urlBlackList = configuration.urlBlackList;
50
+ }
51
+ }
52
+
53
+ async moderateText(text: string, minimumConfidence: number = 50): Promise<ModerationResult> {
54
+ const categories: ModerationCategory[] = [];
55
+ const normalized = text.toLowerCase();
56
+ const matches = this.banList.filter(w => normalized.includes(w));
57
+
58
+ if (matches.length > 0) {
59
+ const words = normalized.split(' ');
60
+ categories.push({ category: 'BAN_LIST', confidence: (matches.length / words.length) * 100 });
61
+ }
62
+
63
+ if (!this.googleLanguage) {
64
+ return { source: text, moderation: categories };
65
+ }
66
+
67
+ const googleCategories = await this.googleLanguage.moderateText(text, minimumConfidence);
68
+
69
+ return { source: text, moderation: [...categories, ...googleCategories] };
70
+ }
71
+
72
+ async moderateImage(url: string, minimumConfidence: number = 50): Promise<ModerationResult> {
73
+ if (!this.aws) {
74
+ return { source: url, moderation: [] };
75
+ }
76
+
77
+ const moderation = await this.aws.moderateImage(url, minimumConfidence);
78
+
79
+ return { source: url, moderation };
80
+ }
81
+
82
+ async moderateLink(url: string, allowShorteners = false): Promise<ModerationResult> {
83
+ try {
84
+ const domain = new URL(url).hostname;
85
+
86
+ if (this.urlBlackList.some(u => url.includes(u))) {
87
+ return { source: url, moderation: [{ category: 'CUSTOM_BLACK_LIST', confidence: 100 }] };
88
+ }
89
+
90
+ if (URLBlackList.some(u => u === domain)) {
91
+ return { source: url, moderation: [{ category: 'BLACK_LIST', confidence: 100 }] };
92
+ }
93
+
94
+ if (!allowShorteners && URLShortenerList.some(u => u === domain)) {
95
+ return { source: url, moderation: [{ category: 'URL_SHORTENER', confidence: 100 }] };
96
+ }
97
+ } catch {
98
+ return { source: url, moderation: [] };
99
+ }
100
+
101
+ if (!this.webRisk) {
102
+ return { source: url, moderation: [] };
103
+ }
104
+
105
+ const moderation = await this.webRisk.checkLink(url);
106
+ return { source: url, moderation };
107
+ }
108
+
109
+ async moderateAudio(url: string, language: string = 'en-US', minimumConfidence: number = 50): Promise<ModerationResult> {
110
+ if (!this.googleSpeech) {
111
+ return { source: url, moderation: [] };
112
+ }
113
+
114
+ const buffer = await fetchAudio(url);
115
+ const transcription = await this.googleSpeech.transcribe(buffer, language);
116
+
117
+ return this.moderateText(transcription, minimumConfidence);
118
+ }
119
+ }
120
+
121
+ export default ModerationClient;
@@ -42322,6 +42322,7 @@
42322
42322
  "getvalorant.fun",
42323
42323
  "getviplocals1.com",
42324
42324
  "getvottak.com",
42325
+ "getwix.pro",
42325
42326
  "getx2.net",
42326
42327
  "getx2tesla.com",
42327
42328
  "getxtrade.com",
package/src/index.ts CHANGED
@@ -1,277 +1,3 @@
1
- import axios from 'axios';
2
-
3
- import { Rekognition } from '@aws-sdk/client-rekognition';
4
- import { LanguageServiceClient } from '@google-cloud/language';
5
- import { SpeechClient, protos } from '@google-cloud/speech';
6
-
7
- import sharp from 'sharp';
8
-
9
- import URLBlackList from './url-blacklist.json';
10
- import URLShortenerList from './url-shorteners.json';
11
-
12
-
13
- import { ModerationCategory, ModerationConfiguration, ModerationResult, ThreatsResponse } from './types';
14
-
15
-
16
- type IRecognitionConfig = protos.google.cloud.speech.v1.IRecognitionConfig;
17
-
18
- type ISpeechRecognitionResult = protos.google.cloud.speech.v1.ISpeechRecognitionResult;
19
-
20
- const MAX_IMAGE_SIZE = 5 * 1024 * 1024; // 5MB in bytes for Rekognition limit
21
-
22
- /**
23
- * Moderation Client
24
- *
25
- * @class ModerationClient
26
- */
27
- class ModerationClient {
28
-
29
- private rekognitionClient?: Rekognition;
30
- private googleLanguageClient?: LanguageServiceClient;
31
- private googleSpeechClient?: SpeechClient;
32
- private googleAPIKey?: string;
33
- private banList?: string[] = [];
34
- private urlBlackList?: string[] = [];
35
-
36
- /**
37
- *
38
- * @param {ModerationConfiguration} configuration
39
- */
40
- constructor (configuration: ModerationConfiguration) {
41
- if (configuration.aws) {
42
- this.rekognitionClient = new Rekognition(configuration.aws);
43
- }
44
-
45
- if (typeof configuration.google?.keyFile === 'string') {
46
- this.googleLanguageClient = new LanguageServiceClient({ keyFile: configuration.google.keyFile });
47
- this.googleSpeechClient = new SpeechClient({ keyFile: configuration.google.keyFile });
48
- }
49
-
50
- if (typeof configuration.google?.apiKey === 'string') {
51
- this.googleAPIKey = configuration.google.apiKey;
52
- }
53
-
54
- if (Array.isArray(configuration.banList)) {
55
- this.banList = configuration.banList;
56
- }
57
-
58
- if (Array.isArray(configuration.urlBlackList)) {
59
- this.urlBlackList = configuration.urlBlackList;
60
- }
61
- }
62
-
63
- /**
64
- * Returns a list of moderation categories detected on a text
65
- *
66
- * @param {string} text The text to moderate
67
- * @param {number} [minimumConfidence = 50] The minimum confidence required for a category to be considered
68
- *
69
- * @returns {Promise<ModerationResult>} The list of results that were detected with the minimum confidence specified
70
- */
71
- async moderateText (text: string, minimumConfidence: number = 50): Promise<ModerationResult> {
72
- const categories: ModerationCategory[] = [];
73
-
74
- if (Array.isArray(this.banList)) {
75
- const normalizedText = text.toLowerCase();
76
- const matches = this.banList.filter(w => normalizedText.indexOf(w) > -1);
77
-
78
- if (matches.length > 0) {
79
- const words = normalizedText.split(' ');
80
-
81
- categories.push({
82
- category: 'BAN_LIST',
83
- confidence: (matches.length / words.length) * 100,
84
- });
85
- }
86
- }
87
-
88
-
89
- if (typeof this.googleLanguageClient === 'undefined') {
90
- return { source: text, moderation: categories };
91
- }
92
-
93
- const [ result ] = await this.googleLanguageClient.moderateText({
94
- document: {
95
- content: text,
96
- type: 'PLAIN_TEXT',
97
- },
98
- });
99
-
100
- if (result && 'moderationCategories' in result) {
101
- if (Array.isArray(result.moderationCategories)) {
102
- const results = result.moderationCategories.map(c => ({
103
- category: c.name ?? 'Unknown',
104
- confidence: (c.confidence ?? 0) * 100,
105
- })).filter(c => c.confidence >= minimumConfidence);
106
- return { source: text, moderation: [...categories, ...results] };
107
- }
108
- }
109
-
110
- return { source: text, moderation: [] };
111
- }
112
-
113
- /**
114
- * Returns a list of moderation categories detected on an image
115
- *
116
- * @param {string} url
117
- * @param {number} [minimumConfidence = 50] The minimum confidence required for a category to be considered
118
- *
119
- *
120
- * @returns {Promise<ModerationResult[]>} The list of results that were detected with the minimum confidence specified
121
- */
122
- async moderateImage (url: string, minimumConfidence: number = 50): Promise<ModerationResult> {
123
- if (typeof this.rekognitionClient === 'undefined') {
124
- return { source: url, moderation: [] };
125
- }
126
-
127
- const { data } = await axios.get<string>(url, { responseType: 'arraybuffer' });
128
-
129
- let buffer: Buffer | null = null;
130
-
131
- // GIFs will be split into frames
132
- if (url.toLowerCase().indexOf('.gif') > -1) {
133
- buffer = await sharp(data, { pages: -1 }).toFormat('png').toBuffer();
134
- } else if (url.toLowerCase().indexOf('.webp') > -1) {
135
- buffer = await sharp(data).toFormat('png').toBuffer();
136
- } else {
137
- // Download image as binary data
138
- buffer = Buffer.from(data, 'binary');
139
- }
140
-
141
- // Ensure image is not larger than 5MB (Rekognition limit)
142
- if (buffer.length > MAX_IMAGE_SIZE) {
143
- try {
144
- // Calculate new dimensions to reduce size
145
- const metadata = await sharp(buffer).metadata();
146
-
147
- const { width, height } = metadata;
148
-
149
- if (typeof width !== 'number' || typeof height !== 'number') {
150
- throw new Error('Invalid image metadata');
151
- }
152
-
153
- // Calculate the scaling factor
154
- const scalingFactor = Math.sqrt(MAX_IMAGE_SIZE / buffer.length);
155
-
156
- // Calculate new dimensions
157
- const newWidth = Math.floor(width * scalingFactor);
158
- const newHeight = Math.floor(height * scalingFactor);
159
-
160
- const resizedBuffer = await sharp(buffer)
161
- .resize(Math.round(newWidth), Math.round(newHeight))
162
- .toBuffer();
163
-
164
- buffer = resizedBuffer;
165
- } catch (error) {
166
- // We can't resize the image. We'll skip the resize and try to process it as is
167
- }
168
- }
169
-
170
- const { ModerationLabels } = await this.rekognitionClient.detectModerationLabels({
171
- Image: {
172
- Bytes: buffer
173
- },
174
- MinConfidence: minimumConfidence
175
- });
176
-
177
- if (Array.isArray(ModerationLabels)) {
178
- const moderation = ModerationLabels.map(l => ({
179
- category: l.Name ?? 'Unknown',
180
- confidence: l.Confidence ?? 0,
181
- }));
182
-
183
- return { source: url, moderation };
184
- }
185
-
186
- return { source: url, moderation: [] };
187
- }
188
-
189
- async moderateLink (url: string, allowShorteners = false): Promise<ModerationResult> {
190
- try {
191
- const domain = new URL(url).hostname;
192
-
193
- const blacklisted = this.urlBlackList?.some(u => url.indexOf(u) > -1);
194
-
195
- if (blacklisted) {
196
- return { source: url, moderation: [{ category: 'CUSTOM_BLACK_LIST', confidence: 100 }] };
197
- }
198
-
199
- const globallyBlacklisted = URLBlackList.some(u => u === domain);
200
-
201
- if (globallyBlacklisted) {
202
- return { source: url, moderation: [{ category: 'BLACK_LIST', confidence: 100 }] };
203
- }
204
-
205
- if (!allowShorteners) {
206
- const isShortened = URLShortenerList.some(u => u === domain);
207
-
208
- if (isShortened) {
209
- return { source: url, moderation: [{ category: 'URL_SHORTENER', confidence: 100 }] };
210
- }
211
- }
212
- } catch (error) {
213
- // Invalid URL
214
- return { source: url, moderation: [] };
215
- }
216
-
217
- if (typeof this.googleAPIKey !== 'string') {
218
- return { source: url, moderation: [] };
219
- }
220
-
221
- const types = [
222
- 'MALWARE',
223
- 'SOCIAL_ENGINEERING',
224
- 'UNWANTED_SOFTWARE',
225
- 'SOCIAL_ENGINEERING_EXTENDED_COVERAGE'
226
- ];
227
-
228
- const threatTypes = types.join('&threatTypes=');
229
- const requestUrl = `https://webrisk.googleapis.com/v1/uris:search?threatTypes=${threatTypes}&key=${this.googleAPIKey}`;
230
-
231
- const { data } = await axios.get<ThreatsResponse>(`${requestUrl}&uri=${encodeURIComponent(url)}`);
232
-
233
- const threats = data?.threat?.threatTypes;
234
-
235
- if (Array.isArray(threats)) {
236
- const moderation = threats.map(t => ({
237
- category: t,
238
- confidence: 100,
239
- }));
240
-
241
- return { source: url, moderation };
242
- }
243
-
244
- return { source: url, moderation: [] };
245
- }
246
-
247
- async moderateAudio (url: string, language: string = 'en-US', minimumConfidence: number = 50): Promise<ModerationResult> {
248
- if (typeof this.googleSpeechClient === 'undefined') {
249
- return { source: url, moderation: [] };
250
- }
251
-
252
- const { data } = await axios.get<string>(url, { responseType: 'arraybuffer' });
253
-
254
-
255
- const options: IRecognitionConfig = {
256
- encoding: 'OGG_OPUS',
257
- sampleRateHertz: 48000,
258
- languageCode: language,
259
- };
260
-
261
- const [ response ] = await this.googleSpeechClient.recognize ({
262
- audio: { content: Buffer.from(data, 'binary').toString('base64') },
263
- config: options,
264
- });
265
-
266
- if (!Array.isArray(response?.results)) {
267
- return { source: url, moderation: [] };
268
- }
269
-
270
- const transcription = response?.results?.map((result: ISpeechRecognitionResult) => result.alternatives?.at(0)?.transcript ?? '').join(' ');
271
-
272
- return this.moderateText(transcription, minimumConfidence);
273
- }
274
-
275
- }
276
-
277
- export default ModerationClient;
1
+ export { ModerationClient, default } from './client';
2
+ export * from './types';
3
+ export * from './actions';
@@ -0,0 +1,58 @@
1
+ import { Rekognition } from '@aws-sdk/client-rekognition';
2
+ import axios from 'axios';
3
+ import sharp from 'sharp';
4
+
5
+ import type { ModerationCategory } from '../types';
6
+
7
+ // AWS Rekognition 5MB inline-image limit
8
+ const MAX_IMAGE_SIZE = 5 * 1024 * 1024;
9
+
10
+ /**
11
+ * AWS Rekognition image moderation adapter. Handles GIF and WEBP
12
+ * conversion to PNG and downscales images over the 5 MB Rekognition limit.
13
+ */
14
+ export class RekognitionProvider {
15
+ constructor(private client: Rekognition) {}
16
+
17
+ async moderateImage(url: string, minimumConfidence: number): Promise<ModerationCategory[]> {
18
+ const { data } = await axios.get<ArrayBuffer>(url, { responseType: 'arraybuffer' });
19
+ let buffer: Buffer;
20
+
21
+ const lowered = url.toLowerCase();
22
+
23
+ if (lowered.includes('.gif')) {
24
+ buffer = await sharp(Buffer.from(data), { pages: -1 }).toFormat('png').toBuffer();
25
+ } else if (lowered.includes('.webp')) {
26
+ buffer = await sharp(Buffer.from(data)).toFormat('png').toBuffer();
27
+ } else {
28
+ buffer = Buffer.from(data);
29
+ }
30
+
31
+ if (buffer.length > MAX_IMAGE_SIZE) {
32
+ try {
33
+ const metadata = await sharp(buffer).metadata();
34
+ const { width, height } = metadata;
35
+
36
+ if (typeof width === 'number' && typeof height === 'number') {
37
+ const scalingFactor = Math.sqrt(MAX_IMAGE_SIZE / buffer.length);
38
+ buffer = await sharp(buffer)
39
+ .resize(Math.round(width * scalingFactor), Math.round(height * scalingFactor))
40
+ .toBuffer();
41
+ }
42
+ } catch {
43
+ // Resize failed, we will use the original buffer.
44
+ }
45
+ }
46
+
47
+ const { ModerationLabels } = await this.client.detectModerationLabels({
48
+ Image: { Bytes: buffer },
49
+ MinConfidence: minimumConfidence,
50
+ });
51
+
52
+ if (Array.isArray(ModerationLabels)) {
53
+ return ModerationLabels.map(l => ({ category: l.Name ?? 'Unknown', confidence: l.Confidence ?? 0 }));
54
+ }
55
+
56
+ return [];
57
+ }
58
+ }
@@ -0,0 +1,63 @@
1
+ import { LanguageServiceClient } from '@google-cloud/language';
2
+ import { SpeechClient, protos } from '@google-cloud/speech';
3
+ import axios from 'axios';
4
+
5
+ import type { ModerationCategory } from '../types';
6
+
7
+ type IRecognitionConfig = protos.google.cloud.speech.v1.IRecognitionConfig;
8
+ type ISpeechRecognitionResult = protos.google.cloud.speech.v1.ISpeechRecognitionResult;
9
+
10
+ /**
11
+ * Google Cloud Natural Language moderation adapter.
12
+ */
13
+ export class GoogleLanguageProvider {
14
+ constructor(private client: LanguageServiceClient) {}
15
+
16
+ async moderateText(text: string, minimumConfidence: number): Promise<ModerationCategory[]> {
17
+ const [result] = await this.client.moderateText({
18
+ document: { content: text, type: 'PLAIN_TEXT' },
19
+ });
20
+
21
+ if (!result || !('moderationCategories' in result) || !Array.isArray(result.moderationCategories)) {
22
+ return [];
23
+ }
24
+
25
+ return result.moderationCategories
26
+ .map(c => ({ category: c.name ?? 'Unknown', confidence: (c.confidence ?? 0) * 100 }))
27
+ .filter(c => c.confidence >= minimumConfidence);
28
+ }
29
+ }
30
+
31
+ /**
32
+ * Google Cloud Speech-to-Text adapter. Used for audio transcription
33
+ * before running the transcript through text moderation.
34
+ */
35
+ export class GoogleSpeechProvider {
36
+ constructor(private client: SpeechClient) {}
37
+
38
+ async transcribe(audioBuffer: Buffer, languageCode: string): Promise<string> {
39
+ const config: IRecognitionConfig = {
40
+ encoding: 'OGG_OPUS',
41
+ sampleRateHertz: 48000,
42
+ languageCode,
43
+ };
44
+
45
+ const [response] = await this.client.recognize({
46
+ audio: { content: audioBuffer.toString('base64') },
47
+ config,
48
+ });
49
+
50
+ if (!Array.isArray(response?.results)) {
51
+ return '';
52
+ }
53
+
54
+ return response.results
55
+ .map((r: ISpeechRecognitionResult) => r.alternatives?.at(0)?.transcript ?? '')
56
+ .join(' ');
57
+ }
58
+ }
59
+
60
+ export async function fetchAudio(url: string): Promise<Buffer> {
61
+ const { data } = await axios.get<ArrayBuffer>(url, { responseType: 'arraybuffer' });
62
+ return Buffer.from(data);
63
+ }
@@ -0,0 +1,30 @@
1
+ import axios from 'axios';
2
+ import type { ModerationCategory, ThreatsResponse } from '../types';
3
+
4
+ const THREAT_TYPES = [
5
+ 'MALWARE',
6
+ 'SOCIAL_ENGINEERING',
7
+ 'UNWANTED_SOFTWARE',
8
+ 'SOCIAL_ENGINEERING_EXTENDED_COVERAGE',
9
+ ];
10
+
11
+ /**
12
+ * Google Web Risk link moderation adapter.
13
+ */
14
+ export class WebRiskProvider {
15
+ constructor(private apiKey: string) {}
16
+
17
+ async checkLink(url: string): Promise<ModerationCategory[]> {
18
+ const threatTypes = THREAT_TYPES.join('&threatTypes=');
19
+ const requestUrl = `https://webrisk.googleapis.com/v1/uris:search?threatTypes=${threatTypes}&key=${this.apiKey}`;
20
+ const { data } = await axios.get<ThreatsResponse>(`${requestUrl}&uri=${encodeURIComponent(url)}`);
21
+
22
+ const threats = data?.threat?.threatTypes;
23
+
24
+ if (Array.isArray(threats)) {
25
+ return threats.map(t => ({ category: t, confidence: 100 }));
26
+ }
27
+
28
+ return [];
29
+ }
30
+ }
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Is a member's account "too new" for the given threshold?
3
+ *
4
+ * Returns `false` when both timestamps are missing.
5
+ */
6
+ export function isAccountTooNew(joinedTimestamp: number | null, createdTimestamp: number | null, minAgeDays: number): boolean {
7
+ // For raids, we care about join time, not account creation
8
+ // Altough we can derive some trust from that too.
9
+ const reference = joinedTimestamp ?? createdTimestamp;
10
+
11
+ if (reference === null) {
12
+ return false;
13
+ }
14
+
15
+ const age = Date.now() - reference;
16
+ const minAgeMs = minAgeDays * 24 * 60 * 60 * 1000;
17
+
18
+ return age < minAgeMs;
19
+ }