@marslanmustafa/input-shield 0.1.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.
- package/LICENSE +21 -0
- package/NODEMAILER.md +144 -0
- package/README.md +239 -0
- package/dist/builder-C10YQjbV.d.cts +123 -0
- package/dist/builder-C10YQjbV.d.ts +123 -0
- package/dist/chunk-67CBN3U4.cjs +520 -0
- package/dist/chunk-67CBN3U4.cjs.map +1 -0
- package/dist/chunk-ADGSP522.mjs +506 -0
- package/dist/chunk-ADGSP522.mjs.map +1 -0
- package/dist/chunk-KVXEPETW.cjs +28 -0
- package/dist/chunk-KVXEPETW.cjs.map +1 -0
- package/dist/chunk-WACGX73I.mjs +22 -0
- package/dist/chunk-WACGX73I.mjs.map +1 -0
- package/dist/email.cjs +48 -0
- package/dist/email.cjs.map +1 -0
- package/dist/email.d.cts +71 -0
- package/dist/email.d.ts +71 -0
- package/dist/email.mjs +45 -0
- package/dist/email.mjs.map +1 -0
- package/dist/index.cjs +81 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +217 -0
- package/dist/index.d.ts +217 -0
- package/dist/index.mjs +4 -0
- package/dist/index.mjs.map +1 -0
- package/dist/zod.cjs +59 -0
- package/dist/zod.cjs.map +1 -0
- package/dist/zod.d.cts +47 -0
- package/dist/zod.d.ts +47 -0
- package/dist/zod.mjs +53 -0
- package/dist/zod.mjs.map +1 -0
- package/package.json +105 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Muhammad Arslan
|
|
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/NODEMAILER.md
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
## Nodemailer Integration
|
|
2
|
+
|
|
3
|
+
`input-shield` works as the validation layer **before** content reaches Nodemailer.
|
|
4
|
+
|
|
5
|
+
> **Why this matters:** Nodemailer has zero content validation — it will send spam,
|
|
6
|
+
> profanity, or malicious URLs without throwing any error. Validation is 100% your
|
|
7
|
+
> responsibility before calling `sendMail()`.
|
|
8
|
+
|
|
9
|
+
### Install
|
|
10
|
+
|
|
11
|
+
```bash
|
|
12
|
+
npm install @marslanmustafa/input-shield nodemailer
|
|
13
|
+
npm install --save-dev @types/nodemailer
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
---
|
|
17
|
+
|
|
18
|
+
### Basic contact form
|
|
19
|
+
|
|
20
|
+
```typescript
|
|
21
|
+
import nodemailer from 'nodemailer';
|
|
22
|
+
import { createValidator } from '@marslanmustafa/input-shield';
|
|
23
|
+
|
|
24
|
+
// ─── Transporter setup ────────────────────────────────────────────────────────
|
|
25
|
+
const transporter = nodemailer.createTransport({
|
|
26
|
+
host: process.env.SMTP_HOST,
|
|
27
|
+
port: 587,
|
|
28
|
+
auth: {
|
|
29
|
+
user: process.env.SMTP_USER,
|
|
30
|
+
pass: process.env.SMTP_PASS,
|
|
31
|
+
},
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
// ─── Validators ───────────────────────────────────────────────────────────────
|
|
35
|
+
const nameValidator = createValidator()
|
|
36
|
+
.field('Name')
|
|
37
|
+
.min(2).max(60)
|
|
38
|
+
.noProfanity()
|
|
39
|
+
.noGibberish({ sensitivity: 'normal' })
|
|
40
|
+
.noLowQuality();
|
|
41
|
+
|
|
42
|
+
const subjectValidator = createValidator()
|
|
43
|
+
.field('Subject')
|
|
44
|
+
.min(5).max(150)
|
|
45
|
+
.noProfanity()
|
|
46
|
+
.noSpam();
|
|
47
|
+
|
|
48
|
+
const messageValidator = createValidator()
|
|
49
|
+
.field('Message')
|
|
50
|
+
.min(10).max(2000)
|
|
51
|
+
.noProfanity()
|
|
52
|
+
.noSpam(); // blocks: URLs, "free money", "buy now", "viagra", etc.
|
|
53
|
+
|
|
54
|
+
// ─── Send function ────────────────────────────────────────────────────────────
|
|
55
|
+
interface ContactFormData {
|
|
56
|
+
name: string;
|
|
57
|
+
email: string;
|
|
58
|
+
subject: string;
|
|
59
|
+
message: string;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export async function sendContactEmail(data: ContactFormData): Promise<void> {
|
|
63
|
+
// Validate every field BEFORE touching Nodemailer.
|
|
64
|
+
// If any check fails, throw immediately — sendMail() is never called.
|
|
65
|
+
const checks = [
|
|
66
|
+
nameValidator.validate(data.name),
|
|
67
|
+
subjectValidator.validate(data.subject),
|
|
68
|
+
messageValidator.validate(data.message),
|
|
69
|
+
];
|
|
70
|
+
|
|
71
|
+
for (const result of checks) {
|
|
72
|
+
if (!result.isValid) {
|
|
73
|
+
// result.reason → 'profanity' | 'spam' | 'gibberish' | ...
|
|
74
|
+
// result.message → "Message: appears to contain spam."
|
|
75
|
+
throw new Error(result.message);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
// ✅ All fields are clean — safe to send
|
|
80
|
+
await transporter.sendMail({
|
|
81
|
+
from: `"${data.name}" <${process.env.SMTP_USER}>`,
|
|
82
|
+
replyTo: data.email,
|
|
83
|
+
to: process.env.CONTACT_EMAIL,
|
|
84
|
+
subject: data.subject,
|
|
85
|
+
text: data.message,
|
|
86
|
+
});
|
|
87
|
+
}
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
---
|
|
91
|
+
|
|
92
|
+
### Express route example
|
|
93
|
+
|
|
94
|
+
```typescript
|
|
95
|
+
import express from 'express';
|
|
96
|
+
import { sendContactEmail } from './mailer';
|
|
97
|
+
|
|
98
|
+
const router = express.Router();
|
|
99
|
+
|
|
100
|
+
router.post('/contact', async (req, res) => {
|
|
101
|
+
try {
|
|
102
|
+
await sendContactEmail(req.body);
|
|
103
|
+
res.json({ success: true, message: 'Message sent.' });
|
|
104
|
+
} catch (err) {
|
|
105
|
+
// Validation errors and mail errors both surface here
|
|
106
|
+
res.status(400).json({
|
|
107
|
+
success: false,
|
|
108
|
+
message: err instanceof Error ? err.message : 'Failed to send message.',
|
|
109
|
+
});
|
|
110
|
+
}
|
|
111
|
+
});
|
|
112
|
+
|
|
113
|
+
export default router;
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
---
|
|
117
|
+
|
|
118
|
+
### What gets blocked before it reaches Nodemailer
|
|
119
|
+
|
|
120
|
+
| Input | Reason blocked |
|
|
121
|
+
|---|---|
|
|
122
|
+
| `"Buy vi4gra now!"` | `spam` — leet-evaded keyword |
|
|
123
|
+
| `"Check https://spam.com"` | `spam` — URL detected |
|
|
124
|
+
| `"Win fr33 m0n3y!"` | `spam` — leet-evaded phrase |
|
|
125
|
+
| `"sh!t service"` | `profanity` — leet-evaded |
|
|
126
|
+
| `"аsshole"` (Cyrillic а) | `profanity` — homoglyph bypass caught |
|
|
127
|
+
| `"asdfghjkl"` | `gibberish` — keyboard mash |
|
|
128
|
+
| `"test"` | `low_effort` — placeholder value |
|
|
129
|
+
|
|
130
|
+
---
|
|
131
|
+
|
|
132
|
+
### Without input-shield — what Nodemailer does
|
|
133
|
+
|
|
134
|
+
```typescript
|
|
135
|
+
// ❌ Nodemailer sends this with NO error — zero content validation
|
|
136
|
+
await transporter.sendMail({
|
|
137
|
+
to: 'you@example.com',
|
|
138
|
+
subject: 'Buy vi4gra now!!!',
|
|
139
|
+
text: 'Win fr33 m0n3y at https://spam.com click here now',
|
|
140
|
+
});
|
|
141
|
+
// → Delivered. No exception. No warning.
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
`input-shield` is the layer that stops this **before** `sendMail()` is ever called.
|
package/README.md
ADDED
|
@@ -0,0 +1,239 @@
|
|
|
1
|
+
# @marslanmustafa/input-shield
|
|
2
|
+
|
|
3
|
+
[](https://www.npmjs.com/package/@marslanmustafa/input-shield)
|
|
4
|
+
[](https://bundlephobia.com/package/@marslanmustafa/input-shield)
|
|
5
|
+
[](https://codecov.io/gh/marslanmustafa/input-shield)
|
|
6
|
+
[](LICENSE)
|
|
7
|
+
[](package.json)
|
|
8
|
+
|
|
9
|
+
> **One install. No config. Clean inputs.**
|
|
10
|
+
>
|
|
11
|
+
> Profanity · Spam · Gibberish · Leet-speak · Homoglyphs — all in one zero-dependency TypeScript package.
|
|
12
|
+
|
|
13
|
+
---
|
|
14
|
+
|
|
15
|
+
## Why @marslanmustafa/input-shield?
|
|
16
|
+
|
|
17
|
+
| Problem | Old way (3+ packages) | @marslanmustafa/input-shield |
|
|
18
|
+
|---|---|---|
|
|
19
|
+
| Block profanity | `npm i obscenity` | ✅ built in |
|
|
20
|
+
| Catch `f.u.c.k` / `f@ck` / `fuck` | Manual regex + leet map | ✅ 3-stage normalization |
|
|
21
|
+
| Catch Cyrillic `аss` (homoglyph bypass) | Nobody does this | ✅ NFKC + homoglyph map |
|
|
22
|
+
| Block spam URLs | `npm i validator` | ✅ built in |
|
|
23
|
+
| Detect keyboard mash | Hand-rolled heuristics | ✅ `loose/normal/strict` scale |
|
|
24
|
+
| Zod integration | 20 lines of glue code | ✅ `import from '@marslanmustafa/input-shield/zod'` |
|
|
25
|
+
| TypeScript types | Often partial | ✅ first-class, discriminated union |
|
|
26
|
+
| Tree-shakeable | Rarely | ✅ every function importable alone |
|
|
27
|
+
|
|
28
|
+
---
|
|
29
|
+
|
|
30
|
+
## Install
|
|
31
|
+
|
|
32
|
+
```bash
|
|
33
|
+
npm install @marslanmustafa/@marslanmustafa/input-shield
|
|
34
|
+
pnpm add @marslanmustafa/@marslanmustafa/input-shield
|
|
35
|
+
yarn add @marslanmustafa/@marslanmustafa/input-shield
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
---
|
|
39
|
+
|
|
40
|
+
## Quick start
|
|
41
|
+
|
|
42
|
+
```typescript
|
|
43
|
+
import { createValidator } from '@marslanmustafa/input-shield';
|
|
44
|
+
|
|
45
|
+
const usernameValidator = createValidator()
|
|
46
|
+
.field('Username')
|
|
47
|
+
.min(3).max(30)
|
|
48
|
+
.noProfanity()
|
|
49
|
+
.noGibberish({ sensitivity: 'strict' })
|
|
50
|
+
.noSpam();
|
|
51
|
+
|
|
52
|
+
const result = usernameValidator.validate(userInput);
|
|
53
|
+
|
|
54
|
+
if (!result.isValid) {
|
|
55
|
+
console.log(result.reason); // 'profanity' | 'gibberish' | 'spam' | ...
|
|
56
|
+
console.log(result.message); // "Username: contains inappropriate language."
|
|
57
|
+
}
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
---
|
|
61
|
+
|
|
62
|
+
## Presets (zero-config)
|
|
63
|
+
|
|
64
|
+
```typescript
|
|
65
|
+
import {
|
|
66
|
+
validateUsername,
|
|
67
|
+
validateBio,
|
|
68
|
+
validateShortText,
|
|
69
|
+
validateLongText,
|
|
70
|
+
validateSearchQuery,
|
|
71
|
+
} from '@marslanmustafa/input-shield';
|
|
72
|
+
|
|
73
|
+
validateUsername('alice_dev'); // { isValid: true }
|
|
74
|
+
validateUsername('f4ck3r'); // { isValid: false, reason: 'profanity', message: '...' }
|
|
75
|
+
validateBio('Software engineer from Lahore'); // { isValid: true }
|
|
76
|
+
validateShortText('test'); // { isValid: false, reason: 'low_effort', message: '...' }
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
---
|
|
80
|
+
|
|
81
|
+
## Integrations
|
|
82
|
+
|
|
83
|
+
- 📧 [Nodemailer — validate email content before sending](./NODEMAILER.md)
|
|
84
|
+
## Fluent builder API
|
|
85
|
+
|
|
86
|
+
```typescript
|
|
87
|
+
import { createValidator } from '@marslanmustafa/input-shield';
|
|
88
|
+
|
|
89
|
+
createValidator()
|
|
90
|
+
.field('Product Name') // shown in error messages
|
|
91
|
+
.min(2).max(60) // length bounds
|
|
92
|
+
.noProfanity() // catches leet, homoglyphs, dots (f.u.c.k), fullwidth (fuck)
|
|
93
|
+
.noSpam() // keywords + URLs (on raw text — not destroyed by normalization)
|
|
94
|
+
.noGibberish({ // sensitivity: 'loose' | 'normal' | 'strict'
|
|
95
|
+
sensitivity: 'normal', // default — good for most fields
|
|
96
|
+
})
|
|
97
|
+
.noLowQuality() // exact matches (test, asdf), excessive symbols, low letter ratio
|
|
98
|
+
.noRepeatedWords() // catches "cat cat cat" (ignores stop words)
|
|
99
|
+
.allow('nginx', 'kubectl') // allowlist bypasses ALL checks (brand names, tech terms)
|
|
100
|
+
.custom( // custom rule — return true to BLOCK
|
|
101
|
+
t => t.startsWith('@'),
|
|
102
|
+
'custom',
|
|
103
|
+
'names cannot start with @'
|
|
104
|
+
)
|
|
105
|
+
.validate(text); // → ValidationResult
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
---
|
|
109
|
+
|
|
110
|
+
## Zod integration
|
|
111
|
+
|
|
112
|
+
```bash
|
|
113
|
+
# zod is a peer dependency — install it separately
|
|
114
|
+
npm install zod @marslanmustafa/input-shield
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
```typescript
|
|
118
|
+
import { z } from 'zod';
|
|
119
|
+
import { shieldString, zodUsername, zodBio } from '@marslanmustafa/input-shield/zod';
|
|
120
|
+
|
|
121
|
+
// Preset schemas
|
|
122
|
+
const schema = z.object({
|
|
123
|
+
username: zodUsername(),
|
|
124
|
+
bio: zodBio(),
|
|
125
|
+
});
|
|
126
|
+
|
|
127
|
+
// Custom configured schema
|
|
128
|
+
const customSchema = z.object({
|
|
129
|
+
productName: shieldString(v =>
|
|
130
|
+
v.field('Product Name').min(2).max(60).noProfanity().noSpam()
|
|
131
|
+
),
|
|
132
|
+
});
|
|
133
|
+
|
|
134
|
+
// Usage with react-hook-form + zod resolver — zero extra code
|
|
135
|
+
```
|
|
136
|
+
|
|
137
|
+
---
|
|
138
|
+
|
|
139
|
+
## How the normalization pipeline works
|
|
140
|
+
|
|
141
|
+
This is the core innovation. Input is processed through 3 stages before any check runs:
|
|
142
|
+
|
|
143
|
+
```
|
|
144
|
+
Input: "P.0.r.n" or "fuck" or "аss" (Cyrillic а) or "f@ck"
|
|
145
|
+
│
|
|
146
|
+
▼ Stage 1: Unicode NFKC
|
|
147
|
+
Collapses fullwidth, math-bold, ligatures, zero-width chars
|
|
148
|
+
"fuck" → "fuck" | "𝐅𝐔𝐂𝐊" → "FUCK"
|
|
149
|
+
│
|
|
150
|
+
▼ Stage 2: Separator stripping
|
|
151
|
+
Removes dots/dashes between single chars
|
|
152
|
+
"P.0.r.n" → "P0rn" | "f-u-c-k" → "fuck"
|
|
153
|
+
│
|
|
154
|
+
▼ Stage 3: Homoglyph map (Cyrillic/Greek/Armenian → Latin)
|
|
155
|
+
"аss" (Cyrillic а U+0430) → "ass"
|
|
156
|
+
"ρorn" (Greek ρ) → "porn"
|
|
157
|
+
│
|
|
158
|
+
▼ Stage 4: Leet-speak substitution
|
|
159
|
+
"0" → "o", "@" → "a", "$" → "s", "!" → "i" …
|
|
160
|
+
"f@ck" → "fack" | "@ss" → "ass"
|
|
161
|
+
│
|
|
162
|
+
▼ Skeleton: "fuck" / "ass" / "porn"
|
|
163
|
+
Pattern matching runs here ───────────────► BLOCKED
|
|
164
|
+
Error messages reference ORIGINAL input ──► "f@ck"
|
|
165
|
+
```
|
|
166
|
+
|
|
167
|
+
---
|
|
168
|
+
|
|
169
|
+
## API Reference
|
|
170
|
+
|
|
171
|
+
### `createValidator(): InputShieldValidator`
|
|
172
|
+
Returns a new fluent builder instance.
|
|
173
|
+
|
|
174
|
+
### Builder methods
|
|
175
|
+
|
|
176
|
+
| Method | Description |
|
|
177
|
+
|---|---|
|
|
178
|
+
| `.field(name)` | Set field label for error messages |
|
|
179
|
+
| `.min(n)` | Minimum length. Default: 2 |
|
|
180
|
+
| `.max(n)` | Maximum length. Default: 500 |
|
|
181
|
+
| `.allow(...words)` | Allowlist — bypasses all checks |
|
|
182
|
+
| `.noProfanity()` | Block profanity (all evasions caught) |
|
|
183
|
+
| `.noSpam()` | Block spam keywords and URLs |
|
|
184
|
+
| `.noGibberish(opts?)` | Block keyboard mash. `opts.sensitivity`: `'loose'` / `'normal'` / `'strict'` |
|
|
185
|
+
| `.noLowQuality()` | Block exact low-effort matches, excessive symbols, low letter ratio |
|
|
186
|
+
| `.noRepeatedWords()` | Block inputs with many repeated content words |
|
|
187
|
+
| `.custom(fn, reason, msg)` | Custom rule. `fn(text) => true` to BLOCK |
|
|
188
|
+
| `.validate(text)` | Run all checks. Returns `ValidationResult` |
|
|
189
|
+
| `.validateOrThrow(text)` | Throws on invalid input. Useful in Zod `.superRefine()` |
|
|
190
|
+
|
|
191
|
+
### `ValidationResult` (discriminated union)
|
|
192
|
+
|
|
193
|
+
```typescript
|
|
194
|
+
type ValidationResult =
|
|
195
|
+
| { isValid: true }
|
|
196
|
+
| { isValid: false; reason: FailReason; message: string };
|
|
197
|
+
|
|
198
|
+
type FailReason =
|
|
199
|
+
| 'empty' | 'too_short' | 'too_long'
|
|
200
|
+
| 'profanity' | 'spam'
|
|
201
|
+
| 'gibberish' | 'low_effort' | 'repeating_chars' | 'excessive_symbols'
|
|
202
|
+
| 'homoglyph_attack' | 'custom';
|
|
203
|
+
```
|
|
204
|
+
|
|
205
|
+
### Sensitivity scale
|
|
206
|
+
|
|
207
|
+
| Sensitivity | Consonant run | Vowel ratio check | Best for |
|
|
208
|
+
|---|---|---|---|
|
|
209
|
+
| `'loose'` | 7+ in a row | ≥ 12 chars, < 5% vowels | Bio, non-English names |
|
|
210
|
+
| `'normal'` | 6+ in a row | ≥ 8 chars, < 10% vowels | Most fields |
|
|
211
|
+
| `'strict'` | 5+ in a row | ≥ 6 chars, < 15% vowels | Usernames, display names |
|
|
212
|
+
|
|
213
|
+
---
|
|
214
|
+
|
|
215
|
+
## Tree-shaking
|
|
216
|
+
|
|
217
|
+
Every module is independently importable:
|
|
218
|
+
|
|
219
|
+
```typescript
|
|
220
|
+
import { toSkeleton } from '@marslanmustafa/input-shield'; // normalization only
|
|
221
|
+
import { containsProfanity } from '@marslanmustafa/input-shield'; // profanity only
|
|
222
|
+
import { isGibberish } from '@marslanmustafa/input-shield'; // gibberish only
|
|
223
|
+
```
|
|
224
|
+
|
|
225
|
+
---
|
|
226
|
+
|
|
227
|
+
## Bundle size
|
|
228
|
+
|
|
229
|
+
| Import | Size (minzipped) |
|
|
230
|
+
|---|---|
|
|
231
|
+
| `createValidator` (full builder) | ~4 KB |
|
|
232
|
+
| `containsProfanity` only | ~1.5 KB |
|
|
233
|
+
| `@marslanmustafa/input-shield/zod` | +1 KB (zod external) |
|
|
234
|
+
|
|
235
|
+
---
|
|
236
|
+
|
|
237
|
+
## License
|
|
238
|
+
|
|
239
|
+
MIT © [Muhammad Arslan](https://marslanmustafa.com)
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
type FailReason = 'empty' | 'too_short' | 'too_long' | 'profanity' | 'spam' | 'gibberish' | 'low_effort' | 'repeating_chars' | 'excessive_symbols' | 'homoglyph_attack' | 'custom';
|
|
2
|
+
type ValidationResult = {
|
|
3
|
+
isValid: true;
|
|
4
|
+
} | {
|
|
5
|
+
isValid: false;
|
|
6
|
+
reason: FailReason;
|
|
7
|
+
message: string;
|
|
8
|
+
};
|
|
9
|
+
type GibberishSensitivity = 'loose' | 'normal' | 'strict';
|
|
10
|
+
interface ValidationOptions {
|
|
11
|
+
/** Display name used in error messages. Default: "Input" */
|
|
12
|
+
fieldName?: string;
|
|
13
|
+
/** Minimum character length (post-trim). Default: 2 */
|
|
14
|
+
minLength?: number;
|
|
15
|
+
/** Maximum character length. Default: 500 */
|
|
16
|
+
maxLength?: number;
|
|
17
|
+
/** Controls how aggressively gibberish is flagged. Default: "normal" */
|
|
18
|
+
gibberishSensitivity?: GibberishSensitivity;
|
|
19
|
+
/** Skip gibberish check entirely. Useful for short codes, IDs, non-English. */
|
|
20
|
+
skipGibberishCheck?: boolean;
|
|
21
|
+
/** Skip repeated-word detection. Useful for long-form natural language. */
|
|
22
|
+
skipRepeatWordCheck?: boolean;
|
|
23
|
+
/** Extra words/phrases to block (exact, case-insensitive). */
|
|
24
|
+
customBlocklist?: string[];
|
|
25
|
+
/** Strings always allowed, bypassing all checks (e.g. brand names, acronyms). */
|
|
26
|
+
allowlist?: string[];
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* builder.ts
|
|
31
|
+
*
|
|
32
|
+
* Fluent builder API — the primary way developers use input-shield.
|
|
33
|
+
*
|
|
34
|
+
* Usage:
|
|
35
|
+
* const validator = createValidator()
|
|
36
|
+
* .field('Username')
|
|
37
|
+
* .min(3).max(30)
|
|
38
|
+
* .noProfanity()
|
|
39
|
+
* .noGibberish({ sensitivity: 'strict' })
|
|
40
|
+
* .noSpam()
|
|
41
|
+
* .allow('nginx', 'kubectl');
|
|
42
|
+
*
|
|
43
|
+
* const result = validator.validate(userInput);
|
|
44
|
+
* if (!result.isValid) console.error(result.reason, result.message);
|
|
45
|
+
*
|
|
46
|
+
* Design principles:
|
|
47
|
+
* - Each check is opt-in via a chain method (not a giant options object)
|
|
48
|
+
* - Checks run in declaration order (you control the priority)
|
|
49
|
+
* - Returns typed FailReason, not just a boolean
|
|
50
|
+
* - Allowlist bypasses ALL checks (brand names, abbreviations, etc.)
|
|
51
|
+
* - Custom check via .custom() for domain-specific rules
|
|
52
|
+
*/
|
|
53
|
+
|
|
54
|
+
declare class InputShieldValidator {
|
|
55
|
+
private _fieldName;
|
|
56
|
+
private _min;
|
|
57
|
+
private _max;
|
|
58
|
+
private _allowlist;
|
|
59
|
+
private _checks;
|
|
60
|
+
private _spamCheck;
|
|
61
|
+
/** Set the field label used in error messages */
|
|
62
|
+
field(name: string): this;
|
|
63
|
+
/** Minimum character length (post-trim). Default: 2 */
|
|
64
|
+
min(n: number): this;
|
|
65
|
+
/** Maximum character length. Default: 500 */
|
|
66
|
+
max(n: number): this;
|
|
67
|
+
/**
|
|
68
|
+
* Add strings that always pass validation, regardless of other checks.
|
|
69
|
+
* Useful for brand names, tech terms, or known-good short strings.
|
|
70
|
+
* .allow('nginx', 'kubectl', 'QA', 'IT')
|
|
71
|
+
*/
|
|
72
|
+
allow(...words: string[]): this;
|
|
73
|
+
/** Block profanity, including leet-speak and homoglyph evasions */
|
|
74
|
+
noProfanity(): this;
|
|
75
|
+
/**
|
|
76
|
+
* Block spam keywords and URLs.
|
|
77
|
+
* Note: URL detection uses the raw string internally (not the skeleton),
|
|
78
|
+
* so you don't need to worry about URLs being missed.
|
|
79
|
+
*/
|
|
80
|
+
noSpam(): this;
|
|
81
|
+
/**
|
|
82
|
+
* Block gibberish / keyboard mash.
|
|
83
|
+
*
|
|
84
|
+
* @param options.sensitivity
|
|
85
|
+
* 'loose' — only catches extreme mashing (7+ consonants). Safe for names.
|
|
86
|
+
* 'normal' — default. Catches most mashing while allowing tech words.
|
|
87
|
+
* 'strict' — also catches low vowel-ratio words. Best for usernames.
|
|
88
|
+
*/
|
|
89
|
+
noGibberish(options?: {
|
|
90
|
+
sensitivity?: GibberishSensitivity;
|
|
91
|
+
}): this;
|
|
92
|
+
/** Block inputs that are structurally low quality (too many symbols, too few letters) */
|
|
93
|
+
noLowQuality(): this;
|
|
94
|
+
/** Block inputs that repeat content words excessively */
|
|
95
|
+
noRepeatedWords(): this;
|
|
96
|
+
/**
|
|
97
|
+
* Add a custom validation rule.
|
|
98
|
+
*
|
|
99
|
+
* @param fn - Returns true if the input is INVALID (should be blocked)
|
|
100
|
+
* @param reason - The FailReason code to return
|
|
101
|
+
* @param message - Human-readable message (do not include fieldName, it's prepended)
|
|
102
|
+
*
|
|
103
|
+
* @example
|
|
104
|
+
* .custom(t => t.includes('@'), 'custom', 'product names cannot contain @')
|
|
105
|
+
*/
|
|
106
|
+
custom(fn: (text: string) => boolean, reason: FailReason, message: string): this;
|
|
107
|
+
validate(text: string): ValidationResult;
|
|
108
|
+
/**
|
|
109
|
+
* Validate and throw if invalid. Useful in form libraries / Zod .superRefine().
|
|
110
|
+
* @throws Error with the validation message
|
|
111
|
+
*/
|
|
112
|
+
validateOrThrow(text: string): void;
|
|
113
|
+
}
|
|
114
|
+
/**
|
|
115
|
+
* Create a new fluent validator.
|
|
116
|
+
* No `new` keyword needed.
|
|
117
|
+
*
|
|
118
|
+
* @example
|
|
119
|
+
* const v = createValidator().field('Username').min(3).noProfanity().noGibberish();
|
|
120
|
+
*/
|
|
121
|
+
declare function createValidator(): InputShieldValidator;
|
|
122
|
+
|
|
123
|
+
export { type FailReason as F, type GibberishSensitivity as G, InputShieldValidator as I, type ValidationResult as V, type ValidationOptions as a, createValidator as c };
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
type FailReason = 'empty' | 'too_short' | 'too_long' | 'profanity' | 'spam' | 'gibberish' | 'low_effort' | 'repeating_chars' | 'excessive_symbols' | 'homoglyph_attack' | 'custom';
|
|
2
|
+
type ValidationResult = {
|
|
3
|
+
isValid: true;
|
|
4
|
+
} | {
|
|
5
|
+
isValid: false;
|
|
6
|
+
reason: FailReason;
|
|
7
|
+
message: string;
|
|
8
|
+
};
|
|
9
|
+
type GibberishSensitivity = 'loose' | 'normal' | 'strict';
|
|
10
|
+
interface ValidationOptions {
|
|
11
|
+
/** Display name used in error messages. Default: "Input" */
|
|
12
|
+
fieldName?: string;
|
|
13
|
+
/** Minimum character length (post-trim). Default: 2 */
|
|
14
|
+
minLength?: number;
|
|
15
|
+
/** Maximum character length. Default: 500 */
|
|
16
|
+
maxLength?: number;
|
|
17
|
+
/** Controls how aggressively gibberish is flagged. Default: "normal" */
|
|
18
|
+
gibberishSensitivity?: GibberishSensitivity;
|
|
19
|
+
/** Skip gibberish check entirely. Useful for short codes, IDs, non-English. */
|
|
20
|
+
skipGibberishCheck?: boolean;
|
|
21
|
+
/** Skip repeated-word detection. Useful for long-form natural language. */
|
|
22
|
+
skipRepeatWordCheck?: boolean;
|
|
23
|
+
/** Extra words/phrases to block (exact, case-insensitive). */
|
|
24
|
+
customBlocklist?: string[];
|
|
25
|
+
/** Strings always allowed, bypassing all checks (e.g. brand names, acronyms). */
|
|
26
|
+
allowlist?: string[];
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* builder.ts
|
|
31
|
+
*
|
|
32
|
+
* Fluent builder API — the primary way developers use input-shield.
|
|
33
|
+
*
|
|
34
|
+
* Usage:
|
|
35
|
+
* const validator = createValidator()
|
|
36
|
+
* .field('Username')
|
|
37
|
+
* .min(3).max(30)
|
|
38
|
+
* .noProfanity()
|
|
39
|
+
* .noGibberish({ sensitivity: 'strict' })
|
|
40
|
+
* .noSpam()
|
|
41
|
+
* .allow('nginx', 'kubectl');
|
|
42
|
+
*
|
|
43
|
+
* const result = validator.validate(userInput);
|
|
44
|
+
* if (!result.isValid) console.error(result.reason, result.message);
|
|
45
|
+
*
|
|
46
|
+
* Design principles:
|
|
47
|
+
* - Each check is opt-in via a chain method (not a giant options object)
|
|
48
|
+
* - Checks run in declaration order (you control the priority)
|
|
49
|
+
* - Returns typed FailReason, not just a boolean
|
|
50
|
+
* - Allowlist bypasses ALL checks (brand names, abbreviations, etc.)
|
|
51
|
+
* - Custom check via .custom() for domain-specific rules
|
|
52
|
+
*/
|
|
53
|
+
|
|
54
|
+
declare class InputShieldValidator {
|
|
55
|
+
private _fieldName;
|
|
56
|
+
private _min;
|
|
57
|
+
private _max;
|
|
58
|
+
private _allowlist;
|
|
59
|
+
private _checks;
|
|
60
|
+
private _spamCheck;
|
|
61
|
+
/** Set the field label used in error messages */
|
|
62
|
+
field(name: string): this;
|
|
63
|
+
/** Minimum character length (post-trim). Default: 2 */
|
|
64
|
+
min(n: number): this;
|
|
65
|
+
/** Maximum character length. Default: 500 */
|
|
66
|
+
max(n: number): this;
|
|
67
|
+
/**
|
|
68
|
+
* Add strings that always pass validation, regardless of other checks.
|
|
69
|
+
* Useful for brand names, tech terms, or known-good short strings.
|
|
70
|
+
* .allow('nginx', 'kubectl', 'QA', 'IT')
|
|
71
|
+
*/
|
|
72
|
+
allow(...words: string[]): this;
|
|
73
|
+
/** Block profanity, including leet-speak and homoglyph evasions */
|
|
74
|
+
noProfanity(): this;
|
|
75
|
+
/**
|
|
76
|
+
* Block spam keywords and URLs.
|
|
77
|
+
* Note: URL detection uses the raw string internally (not the skeleton),
|
|
78
|
+
* so you don't need to worry about URLs being missed.
|
|
79
|
+
*/
|
|
80
|
+
noSpam(): this;
|
|
81
|
+
/**
|
|
82
|
+
* Block gibberish / keyboard mash.
|
|
83
|
+
*
|
|
84
|
+
* @param options.sensitivity
|
|
85
|
+
* 'loose' — only catches extreme mashing (7+ consonants). Safe for names.
|
|
86
|
+
* 'normal' — default. Catches most mashing while allowing tech words.
|
|
87
|
+
* 'strict' — also catches low vowel-ratio words. Best for usernames.
|
|
88
|
+
*/
|
|
89
|
+
noGibberish(options?: {
|
|
90
|
+
sensitivity?: GibberishSensitivity;
|
|
91
|
+
}): this;
|
|
92
|
+
/** Block inputs that are structurally low quality (too many symbols, too few letters) */
|
|
93
|
+
noLowQuality(): this;
|
|
94
|
+
/** Block inputs that repeat content words excessively */
|
|
95
|
+
noRepeatedWords(): this;
|
|
96
|
+
/**
|
|
97
|
+
* Add a custom validation rule.
|
|
98
|
+
*
|
|
99
|
+
* @param fn - Returns true if the input is INVALID (should be blocked)
|
|
100
|
+
* @param reason - The FailReason code to return
|
|
101
|
+
* @param message - Human-readable message (do not include fieldName, it's prepended)
|
|
102
|
+
*
|
|
103
|
+
* @example
|
|
104
|
+
* .custom(t => t.includes('@'), 'custom', 'product names cannot contain @')
|
|
105
|
+
*/
|
|
106
|
+
custom(fn: (text: string) => boolean, reason: FailReason, message: string): this;
|
|
107
|
+
validate(text: string): ValidationResult;
|
|
108
|
+
/**
|
|
109
|
+
* Validate and throw if invalid. Useful in form libraries / Zod .superRefine().
|
|
110
|
+
* @throws Error with the validation message
|
|
111
|
+
*/
|
|
112
|
+
validateOrThrow(text: string): void;
|
|
113
|
+
}
|
|
114
|
+
/**
|
|
115
|
+
* Create a new fluent validator.
|
|
116
|
+
* No `new` keyword needed.
|
|
117
|
+
*
|
|
118
|
+
* @example
|
|
119
|
+
* const v = createValidator().field('Username').min(3).noProfanity().noGibberish();
|
|
120
|
+
*/
|
|
121
|
+
declare function createValidator(): InputShieldValidator;
|
|
122
|
+
|
|
123
|
+
export { type FailReason as F, type GibberishSensitivity as G, InputShieldValidator as I, type ValidationResult as V, type ValidationOptions as a, createValidator as c };
|