bareun-mal 0.0.0-stage → 1.0.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Bestmemory Studio
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,24 @@
1
- # Temporary Holding Version
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.
1
+ # bareun-mal
2
+ **Bareun-mal Profanity Filter Library** A lightweight JavaScript and TypeScript library for detecting and filtering Korean and English profanity, slurs, and obfuscated bypass patterns. Built for clean text moderation with zero external dependencies and full TypeScript support.
3
+
4
+ ## Installation
5
+ ```bash
6
+ npm install bareun-mal
7
+ ```
8
+
9
+ ## Usage
10
+ ```js
11
+ const bareunMal = require('bareun-mal');
12
+
13
+ const filter = new bareunMal();
14
+ const result = filter.checkSync('Sample text');
15
+ console.log(result);
16
+ ```
17
+
18
+ ## Test
19
+ ```bash
20
+ node test.js
21
+ ```
22
+
23
+ ## License
24
+ MIT License
package/index.d.ts ADDED
@@ -0,0 +1,45 @@
1
+ export type FilterCategory = 'profanity' | 'slang' | 'sexual' | 'hate' | 'english';
2
+
3
+ export interface FilterHit {
4
+ category: FilterCategory;
5
+ root: string;
6
+ matchedBy: 'exact' | 'jamo' | 'chosung' | 'qwerty' | 'qwerty-chosung' | 'word' | 'embedded' | 'context' | 'emoji';
7
+ score: number;
8
+ }
9
+
10
+ export interface FilterResult {
11
+ isProfane: boolean;
12
+ action: 'allow' | 'review' | 'block';
13
+ score: number;
14
+ categories: FilterCategory[];
15
+ hits: FilterHit[];
16
+ source: string;
17
+ }
18
+
19
+ export interface FilterOptions {
20
+ enableCategories?: FilterCategory[];
21
+ blockThreshold?: number;
22
+ reviewThreshold?: number;
23
+ skipBuiltDictionary?: boolean;
24
+ customDictionary?: Partial<Record<FilterCategory, string[]>>;
25
+ customExceptions?: string[];
26
+ aiClassifier?: (text: string, ruleResult: Omit<FilterResult, 'source'>) => Promise<{
27
+ isProfane: boolean;
28
+ score?: number;
29
+ category?: FilterCategory;
30
+ }>;
31
+ }
32
+
33
+ export class bareunMal {
34
+ constructor(options?: FilterOptions);
35
+ addWords(category: FilterCategory, words: string[]): void;
36
+ addExceptions(words: string[]): void;
37
+ loadDictionary(data: {
38
+ dictionary?: Partial<Record<FilterCategory, string[]>>;
39
+ exceptions?: string[];
40
+ }): void;
41
+ check(text: string): Promise<FilterResult>;
42
+ checkSync(text: string): FilterResult;
43
+ }
44
+
45
+ export default bareunMal;
package/package.json CHANGED
@@ -1,6 +1,24 @@
1
- {
2
- "name": "bareun-mal",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
1
+ {
2
+ "name": "bareun-mal",
3
+ "version": "1.0.2",
4
+ "description": "Bareun-mal Profanity Filter Library",
5
+ "main": "./src/index.js",
6
+ "types": "./index.d.ts",
7
+ "files": [
8
+ "src/",
9
+ "index.d.ts"
10
+ ],
11
+ "scripts": {
12
+ "build:dict": "node scripts/build-dictionary.js",
13
+ "prepublishOnly": "npm run build:dict",
14
+ "test": "node test.js"
15
+ },
16
+ "keywords": [
17
+ "bareun-mal",
18
+ "profanity-filter",
19
+ "korean-profanity",
20
+ "english-profanity",
21
+ "hate-speech"
22
+ ],
23
+ "license": "MIT"
6
24
  }
package/src/engine.js ADDED
@@ -0,0 +1,339 @@
1
+ const { decomposeHangul, createTextViews } = require('./normalizer');
2
+
3
+ const CATEGORY_WEIGHTS = {
4
+ profanity: 0.95,
5
+ hate: 0.95,
6
+ sexual: 0.92,
7
+ slang: 0.85,
8
+ english: 0.9
9
+ };
10
+
11
+ const AMBIGUOUS_LOW_CONFIDENCE_WORDS = new Set([
12
+ '게이', '레즈', '레즈비언', '니가', '내가', '너가', '우리가', '운지', '고추'
13
+ ]);
14
+
15
+ const BUILTIN_ENGLISH_CORE = [
16
+ 'fuck', 'fuk', 'fack', 'shit', 'bitch', 'asshole', 'dumbass', 'jackass', 'bastard',
17
+ 'dick', 'cock', 'pussy', 'passy', 'cunt', 'slut', 'whore', 'retard', 'faggot',
18
+ 'nigger', 'nigga', 'chink', 'gook', 'spic', 'kike', 'wetback', 'motherfucker',
19
+ 'bullshit', 'dipshit', 'cocksucker', 'twat', 'wanker', 'bollocks', 'prick',
20
+ 'douchebag', 'scumbag', 'skank', 'blowjob', 'handjob', 'rimjob', 'dildo',
21
+ 'porn', 'hentai', 'rape', 'rapist', 'pedophile', 'nazi', 'cumshot'
22
+ ];
23
+
24
+ const DIRECT_BYPASS_PATTERNS = [
25
+ { category: 'profanity', root: '뻐큐(기호)', pattern: /🖕|凸/ },
26
+ { category: 'hate', root: '나치(심볼)', pattern: /卐|卍/ },
27
+ { category: 'english', root: 'dumbass', pattern: /dumb\s*ass/i },
28
+ { category: 'english', root: 'asshole', pattern: /a\s*[$s5§]\s*[$s5§]\s*h\s*o\s*l\s*e/i },
29
+ { category: 'profanity', root: '18놈/10새끼(숫자우회)', pattern: /(?:18|①⑧|10|⑩)\s*(?:놈|새끼|새키|팔|년|련)/ },
30
+ { category: 'profanity', root: '반초성-시발', pattern: /(?:^|[^가-힣])(?:ㅅ|人)발|시(?:ㅂ|1)(?:$|[^가-힣])/ },
31
+ { category: 'profanity', root: '반초성-병신', pattern: /(?:^|[^가-힣])ㅂ신|병(?:ㅅ|1)(?:$|[^가-힣])/ },
32
+ { category: 'profanity', root: '반초성-지랄', pattern: /(?:^|[^가-힣])지(?:ㄹr|랄)|ㅈ랄/i },
33
+ { category: 'slang', root: '반초성-닥쳐', pattern: /(?:^|[^가-힣])ㄷ(?:r|ㅏ)쳐/i },
34
+ { category: 'profanity', root: '느그마(변형)', pattern: /느(?:그|rm|ㄱㅡ)마/i },
35
+ { category: 'profanity', root: '애미(패드립)', pattern: /(?:^|[^가-힣])애(?:미|ㅁㅣ)(?:$|[^가-힣])/ }
36
+ ];
37
+
38
+ const STANDALONE_REVERSED_WORDS = new Map([
39
+ ['발시', { category: 'profanity', root: '시발(역순)' }],
40
+ ['신병', { category: 'profanity', root: '병신(역순)' }],
41
+ ['랄지', { category: 'profanity', root: '지랄(역순)' }],
42
+ ['끼새', { category: 'profanity', root: '새끼(역순)' }],
43
+ ['나존', { category: 'profanity', root: '존나(역순)' }]
44
+ ]);
45
+
46
+ const CONTEXTUAL_RULES = [
47
+ {
48
+ category: 'profanity',
49
+ root: '패드립-부모비하문맥',
50
+ pattern: /(엄마|어머니|애미|아빠|아버지|애비|부모).{0,12}(하늘나라|뒤졌|죽었|없냐|없네|없는|가셨|창녀|창년|걸레|보지|자지)/
51
+ },
52
+ {
53
+ category: 'profanity',
54
+ root: '패드립-가족모욕',
55
+ pattern: /(니|너|느그|너희).{0,4}(엄마|어머니|애미|아빠|아버지|애비|할미|할애비|누나|여동생)/
56
+ },
57
+ {
58
+ category: 'sexual',
59
+ root: '성희롱-신체접촉요구',
60
+ pattern: /(가슴|엉덩이|몸매|팬티|속옷|다리를|다리).{0,10}(만져|만지|보여|벗어|벌려|핥아|빨아)/
61
+ },
62
+ {
63
+ category: 'sexual',
64
+ root: '성희롱-성행위암시',
65
+ pattern: /(나랑|같이|오늘밤|모텔|침대).{0,10}(자자|할래|하자|먹자|따먹|박자|갈래)/
66
+ },
67
+ {
68
+ category: 'slang',
69
+ root: '위협-자해사망유도',
70
+ pattern: /(나가|그냥|빨리|어서|go).{0,8}(뒤져|죽어|뒈져|자살|kill yourself)/i
71
+ },
72
+ {
73
+ category: 'english',
74
+ root: 'english-insult-phrase',
75
+ pattern: /\b(eat my ass|suck my dick|shut the fuck up|piece of shit|dumb ass)\b/i
76
+ }
77
+ ];
78
+
79
+ const EXTRA_SAFE_EXCEPTIONS = [
80
+ '날씨발표',
81
+ '병신년',
82
+ '8등신',
83
+ '출발기차',
84
+ '지랄탄'
85
+ ];
86
+
87
+ function createTrie() {
88
+ return { children: Object.create(null), items: [] };
89
+ }
90
+
91
+ function insertTrie(root, pattern, item) {
92
+ let node = root;
93
+ for (let i = 0; i < pattern.length; i++) {
94
+ const ch = pattern[i];
95
+ if (!node.children[ch]) {
96
+ node.children[ch] = createTrie();
97
+ }
98
+ node = node.children[ch];
99
+ }
100
+ node.items.push(item);
101
+ }
102
+
103
+ function searchTrie(root, text, onMatch) {
104
+ for (let i = 0; i < text.length; i++) {
105
+ let node = root;
106
+ for (let j = i; j < text.length; j++) {
107
+ node = node.children[text[j]];
108
+ if (!node) break;
109
+ if (node.items.length > 0) {
110
+ for (let k = 0; k < node.items.length; k++) {
111
+ onMatch(node.items[k]);
112
+ }
113
+ }
114
+ }
115
+ }
116
+ }
117
+
118
+ function prepareExceptions(exceptions) {
119
+ const merged = [...exceptions, ...EXTRA_SAFE_EXCEPTIONS];
120
+ const sorted = [...new Set(merged)]
121
+ .map((e) => String(e || '').trim())
122
+ .filter((e) => e.length >= 2)
123
+ .sort((a, b) => b.length - a.length);
124
+
125
+ return sorted.map((ex) => {
126
+ const clean = ex.replace(/\s+/g, '').toLowerCase();
127
+ const chars = [...clean];
128
+ const pattern = chars
129
+ .map((c) => c.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))
130
+ .join('[\\s0-9()\\[\\]{}._-]*');
131
+ return {
132
+ clean,
133
+ regex: new RegExp(pattern, 'gi')
134
+ };
135
+ });
136
+ }
137
+
138
+ function buildIndex(dictionary, exceptions = new Set()) {
139
+ const index = {
140
+ koreanExactTrie: createTrie(),
141
+ koreanJamoTrie: createTrie(),
142
+ koreanChosungTrie: createTrie(),
143
+ englishSet: new Map(),
144
+ englishLongRoots: [],
145
+ exceptionEntries: prepareExceptions(exceptions)
146
+ };
147
+
148
+ const exceptionLowerSet = new Set(
149
+ [...exceptions].map((e) => String(e || '').trim().toLowerCase())
150
+ );
151
+
152
+ for (const coreWord of BUILTIN_ENGLISH_CORE) {
153
+ if (!exceptionLowerSet.has(coreWord)) {
154
+ index.englishSet.set(coreWord, { category: 'english', root: coreWord });
155
+ if (coreWord.length >= 4) {
156
+ index.englishLongRoots.push({ category: 'english', root: coreWord, clean: coreWord });
157
+ }
158
+ }
159
+ }
160
+
161
+ for (const [category, words] of Object.entries(dictionary)) {
162
+ if (!Array.isArray(words)) continue;
163
+
164
+ for (const rawWord of words) {
165
+ const word = String(rawWord || '').trim().toLowerCase();
166
+ if (!word) continue;
167
+
168
+ if (category === 'english') {
169
+ const cleanEn = word.replace(/[^a-z0-9]/g, '');
170
+ if (!cleanEn) continue;
171
+ index.englishSet.set(cleanEn, { category, root: word });
172
+ if (cleanEn.length >= 4 && !index.englishLongRoots.some((x) => x.clean === cleanEn)) {
173
+ index.englishLongRoots.push({ category, root: word, clean: cleanEn });
174
+ }
175
+ continue;
176
+ }
177
+
178
+ const compact = word.replace(/[^a-z0-9가-힣ㄱ-ㅎㅏ-ㅣ]/g, '');
179
+ if (!compact) continue;
180
+
181
+ if (/^[ㄱ-ㅎ]+$/.test(compact)) {
182
+ const { standaloneConsonants } = decomposeHangul(compact);
183
+ insertTrie(index.koreanChosungTrie, standaloneConsonants || compact, { category, root: word });
184
+ } else {
185
+ const { jamo } = decomposeHangul(compact);
186
+ insertTrie(index.koreanExactTrie, compact, { category, root: word });
187
+ if (compact.length >= 2 && jamo.length >= 4) {
188
+ insertTrie(index.koreanJamoTrie, jamo, { category, root: word });
189
+ }
190
+ }
191
+ }
192
+ }
193
+
194
+ return index;
195
+ }
196
+
197
+ function maskExceptions(text, exceptionEntries) {
198
+ let masked = String(text || '');
199
+ const compactAlnum = masked.replace(/[^a-zA-Z0-9가-힣]/g, '').toLowerCase();
200
+ const compactAlphaHangul = masked.replace(/[^a-zA-Z가-힣]/g, '').toLowerCase();
201
+
202
+ for (const entry of exceptionEntries) {
203
+ if (!entry.clean) continue;
204
+ if (!compactAlnum.includes(entry.clean) && !compactAlphaHangul.includes(entry.clean)) continue;
205
+ masked = masked.replace(entry.regex, (match) => {
206
+ if (/새끼$/.test(entry.clean)) {
207
+ const idx = masked.indexOf(match);
208
+ const after = masked.slice(idx + match.length);
209
+ if (/^\s*(같은|놈|년|야|아|들)/.test(after)) {
210
+ return match.replace(/새끼$/, ' 새끼');
211
+ }
212
+ }
213
+ return ' ';
214
+ });
215
+ }
216
+ return masked;
217
+ }
218
+
219
+ function evaluateText(rawText, index, enabledCategories) {
220
+ const rawStr = String(rawText || '');
221
+ const urlStripped = rawStr.replace(/https?:\/\/\S+|www\.\S+/gi, ' ');
222
+ const safeText = maskExceptions(urlStripped, index.exceptionEntries || []);
223
+ const views = createTextViews(safeText, true);
224
+ const hits = [];
225
+ const seen = new Set();
226
+
227
+ const recordHit = (category, root, matchedBy, multiplier) => {
228
+ if (!enabledCategories.has(category)) return;
229
+ const key = `${category}:${root}`;
230
+ if (seen.has(key)) return;
231
+ seen.add(key);
232
+ const weight = CATEGORY_WEIGHTS[category] || 0.85;
233
+ const ambiguityPenalty = AMBIGUOUS_LOW_CONFIDENCE_WORDS.has(root) ? 0.55 : 1.0;
234
+ hits.push({
235
+ category,
236
+ root,
237
+ matchedBy,
238
+ score: Number((weight * multiplier * ambiguityPenalty).toFixed(2))
239
+ });
240
+ };
241
+
242
+ const trimmedRaw = rawStr.trim();
243
+ const revHit = STANDALONE_REVERSED_WORDS.get(trimmedRaw);
244
+ if (revHit) {
245
+ recordHit(revHit.category, revHit.root, 'reversed', 0.95);
246
+ }
247
+
248
+ if (/dumb\s*ass/i.test(rawStr)) {
249
+ recordHit('english', 'dumbass', 'bypass', 1.0);
250
+ }
251
+
252
+ for (const bp of DIRECT_BYPASS_PATTERNS) {
253
+ if (bp.pattern.test(safeText)) {
254
+ recordHit(bp.category, bp.root, 'bypass', 1.0);
255
+ }
256
+ }
257
+
258
+ for (const emojiHit of views.emojiHits) {
259
+ recordHit(emojiHit.category, emojiHit.root, 'emoji', 1.0);
260
+ }
261
+
262
+ for (const qwHit of views.qwertyDirectHits) {
263
+ recordHit(qwHit.category, qwHit.root, 'qwerty', 0.95);
264
+ }
265
+
266
+ for (const rule of CONTEXTUAL_RULES) {
267
+ if (rule.pattern.test(safeText) || rule.pattern.test(views.krNoDigits)) {
268
+ recordHit(rule.category, rule.root, 'context', 1.0);
269
+ }
270
+ }
271
+
272
+ searchTrie(index.koreanExactTrie, views.krCompact, (item) => {
273
+ recordHit(item.category, item.root, 'exact', 1.0);
274
+ });
275
+ if (views.krNoDigits !== views.krCompact) {
276
+ searchTrie(index.koreanExactTrie, views.krNoDigits, (item) => {
277
+ recordHit(item.category, item.root, 'exact', 1.0);
278
+ });
279
+ }
280
+
281
+ const isPureEnglishSentence =
282
+ !/[가-힣ㄱ-ㅎㅏ-ㅣ]/.test(safeText) &&
283
+ views.enTokens.length >= 2 &&
284
+ views.enTokens.every((t) => index.englishSet.has(t) || /^[a-z]{2,}$/.test(t));
285
+
286
+ searchTrie(index.koreanJamoTrie, views.jamo, (item) => {
287
+ recordHit(item.category, item.root, 'jamo', 0.95);
288
+ });
289
+ if (views.stretchedJamo !== views.jamo) {
290
+ searchTrie(index.koreanJamoTrie, views.stretchedJamo, (item) => {
291
+ recordHit(item.category, item.root, 'jamo', 0.95);
292
+ });
293
+ }
294
+ if (!isPureEnglishSentence && views.qwertyJamo) {
295
+ searchTrie(index.koreanJamoTrie, views.qwertyJamo, (item) => {
296
+ recordHit(item.category, item.root, 'qwerty', 0.9);
297
+ });
298
+ }
299
+
300
+ if (views.standaloneConsonants) {
301
+ searchTrie(index.koreanChosungTrie, views.standaloneConsonants, (item) => {
302
+ recordHit(item.category, item.root, 'chosung', 0.88);
303
+ });
304
+ }
305
+ if (!isPureEnglishSentence && views.qwertyConsonants) {
306
+ searchTrie(index.koreanChosungTrie, views.qwertyConsonants, (item) => {
307
+ recordHit(item.category, item.root, 'qwerty-chosung', 0.85);
308
+ });
309
+ }
310
+
311
+ if (enabledCategories.has('english')) {
312
+ for (const token of views.enTokens) {
313
+ const matched = index.englishSet.get(token);
314
+ if (matched) {
315
+ recordHit('english', matched.root, 'word', 1.0);
316
+ }
317
+ }
318
+
319
+ for (const item of index.englishLongRoots) {
320
+ if (views.enCompact.includes(item.clean)) {
321
+ recordHit('english', item.root, 'embedded', 0.9);
322
+ }
323
+ }
324
+ }
325
+
326
+ const maxScore = hits.reduce((max, h) => Math.max(max, h.score), 0);
327
+ const categories = [...new Set(hits.map((h) => h.category))];
328
+
329
+ return {
330
+ score: maxScore,
331
+ categories,
332
+ hits
333
+ };
334
+ }
335
+
336
+ module.exports = {
337
+ buildIndex,
338
+ evaluateText
339
+ };