k9guard 1.0.2 → 1.0.4

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.
@@ -1,298 +0,0 @@
1
- import { createHash, randomBytes } from '../utils/crypto';
2
- import { Random } from '../utils/random';
3
- import { SequenceGenerator } from '../utils/sequenceGenerator';
4
- import { ScrambleGenerator } from '../utils/scrambleGenerator';
5
- import { ReverseGenerator } from '../utils/reverseGenerator';
6
- import { CustomQuestionGenerator } from '../utils/customQuestionGenerator';
7
- import { CustomQuestionValidator } from '../validators/customQuestionValidator';
8
- import { ImageGenerator } from '../utils/imageGenerator';
9
- import { EmojiGenerator } from '../utils/emojiGenerator';
10
- import type { K9GuardOptions, K9GuardCustomOptions, CaptchaChallenge, StoredChallenge, MathCaptcha, TextCaptcha, SequenceCaptcha, ScrambleCaptcha, ReverseCaptcha, MixedCaptcha, CustomCaptcha, ImageCaptcha, EmojiCaptcha, CustomQuestion } from '../types';
11
-
12
- // Bounded nonce store: evicts the oldest entry once capacity is reached to
13
- // prevent unbounded memory growth while still blocking same-process replays.
14
- const NONCE_STORE_MAX = 10_000;
15
-
16
- export class CaptchaGenerator {
17
- private standardOptions: K9GuardOptions | null = null;
18
- private customOptions: K9GuardCustomOptions | null = null;
19
- private customGenerator: CustomQuestionGenerator | null = null;
20
- // Keyed by nonce; stores the full server-side record including answer hash and salt.
21
- // answer, hashedAnswer and salt are never included in the public CaptchaChallenge.
22
- private store: Map<string, StoredChallenge> = new Map();
23
-
24
- // set up the generator and check custom questions if they exist
25
- constructor(options: K9GuardOptions | K9GuardCustomOptions) {
26
- if (this.isCustomOptions(options)) {
27
- this.customOptions = options;
28
- const validation = CustomQuestionValidator.validate(options.questions);
29
- if (!validation.valid) {
30
- throw new Error(`Invalid custom questions: ${validation.error}`);
31
- }
32
- const sanitized = CustomQuestionValidator.sanitize(options.questions);
33
- this.customGenerator = new CustomQuestionGenerator(sanitized);
34
- } else {
35
- this.standardOptions = options;
36
- }
37
- }
38
-
39
- // check if we got custom captcha options
40
- private isCustomOptions(options: unknown): options is K9GuardCustomOptions {
41
- if (typeof options !== 'object' || options === null) {
42
- return false;
43
- }
44
- const opt = options as Record<string, unknown>;
45
- return opt.type === 'custom' && Array.isArray(opt.questions);
46
- }
47
-
48
- private getDifficulty(): 'easy' | 'medium' | 'hard' {
49
- if (!this.standardOptions) {
50
- return 'easy';
51
- }
52
- return this.standardOptions.difficulty;
53
- }
54
-
55
- // Look up the internal StoredChallenge by nonce for use during validation.
56
- lookup(nonce: string): StoredChallenge | undefined {
57
- return this.store.get(nonce);
58
- }
59
-
60
- // Stores the full record server-side; returns a public CaptchaChallenge
61
- // that is safe to send to the client (no answer, hashedAnswer or salt).
62
- private createChallenge(base: Omit<StoredChallenge, 'nonce' | 'expiry' | 'hashedAnswer' | 'salt'>): CaptchaChallenge {
63
- let nonce: string;
64
- do {
65
- nonce = Random.generateNonce();
66
- } while (this.store.has(nonce));
67
-
68
- // evict oldest entry before inserting to cap memory at NONCE_STORE_MAX
69
- if (this.store.size >= NONCE_STORE_MAX) {
70
- const oldest = this.store.keys().next().value;
71
- if (oldest !== undefined) {
72
- this.store.delete(oldest);
73
- }
74
- }
75
-
76
- const expiry = Date.now() + 5 * 60 * 1000;
77
- const salt = Random.generateSalt();
78
- // answer is never sent to the client; only its salted hash is stored
79
- const hashedAnswer = createHash('sha256').update(base.answer.toString() + salt).digest('hex');
80
-
81
- const stored: StoredChallenge = { ...base, nonce, expiry, hashedAnswer, salt };
82
- this.store.set(nonce, stored);
83
-
84
- // strip sensitive fields before returning to caller
85
- const { answer: _answer, hashedAnswer: _ha, salt: _salt, ...publicChallenge } = stored;
86
- return publicChallenge as CaptchaChallenge;
87
- }
88
-
89
- // evaluate arithmetic expression for the math captcha type
90
- private calculateMath(a: number, op: string, b: number): number {
91
- if (op === '+') {
92
- return a + b;
93
- }
94
- if (op === '-') {
95
- return a - b;
96
- }
97
- if (op === '*') {
98
- return a * b;
99
- }
100
- if (op === '/') {
101
- if (b === 0) {
102
- return Number.NaN;
103
- }
104
- // round to 2 decimals to avoid floating point representation issues
105
- return Math.round((a / b) * 100) / 100;
106
- }
107
- return 0;
108
- }
109
-
110
- // dispatch to the correct generator based on configured captcha type
111
- generate(): CaptchaChallenge {
112
- if (this.customOptions) {
113
- return this.generateCustom();
114
- }
115
-
116
- if (!this.standardOptions) {
117
- throw new Error('Generator not properly initialized');
118
- }
119
-
120
- const captchaType = this.standardOptions.type;
121
-
122
- if (captchaType === 'math') {
123
- return this.generateMath();
124
- }
125
- if (captchaType === 'text') {
126
- return this.generateText();
127
- }
128
- if (captchaType === 'sequence') {
129
- return this.generateSequence();
130
- }
131
- if (captchaType === 'scramble') {
132
- return this.generateScramble();
133
- }
134
- if (captchaType === 'reverse') {
135
- return this.generateReverse();
136
- }
137
- if (captchaType === 'multi') {
138
- return this.generateMulti();
139
- }
140
- if (captchaType === 'image') {
141
- return this.generateImage();
142
- }
143
- if (captchaType === 'emoji') {
144
- return this.generateEmoji();
145
- }
146
- return this.generateMixed();
147
- }
148
-
149
- private generateCustom(): CustomCaptcha {
150
- if (!this.customGenerator) {
151
- throw new Error('Custom generator not initialized');
152
- }
153
-
154
- const custom = this.customGenerator.generate();
155
-
156
- // an empty answer would allow bypass with any blank input; reject early
157
- if (!custom.question || !custom.answer) {
158
- throw new Error('Custom question pool returned an empty question or answer');
159
- }
160
-
161
- return this.createChallenge({ type: 'custom', question: custom.question, answer: custom.answer }) as CustomCaptcha;
162
- }
163
-
164
- private generateMath(): MathCaptcha {
165
- const difficulty = this.getDifficulty();
166
- let num1 = Random.getRandomNumber(difficulty);
167
- let num2 = Random.getRandomNumber(difficulty);
168
- const operator = Random.getRandomOperator();
169
-
170
- // guarantee non-zero divisor; add 1 so the result is always >= 1
171
- if (operator === '/' && num2 === 0) {
172
- num2 = Random.getRandomNumber(difficulty) + 1;
173
- }
174
-
175
- const answer = this.calculateMath(num1, operator, num2);
176
-
177
- // calculateMath only returns NaN for division by zero, which is already
178
- // prevented above — but guard here avoids any future regression without
179
- // unbounded recursion: iterate instead of recurse
180
- if (isNaN(answer) || !isFinite(answer)) {
181
- num1 = Random.getRandomNumber(difficulty);
182
- num2 = Random.getRandomNumber(difficulty) + 1;
183
- return this.createChallenge({
184
- type: 'math',
185
- question: `${num1} + ${num2}`,
186
- answer: num1 + num2
187
- }) as MathCaptcha;
188
- }
189
-
190
- return this.createChallenge({ type: 'math', question: `${num1} ${operator} ${num2}`, answer }) as MathCaptcha;
191
- }
192
-
193
- private generateText(): TextCaptcha {
194
- const text = Random.generateRandomString(this.getDifficulty());
195
- return this.createChallenge({ type: 'text', question: text, answer: text }) as TextCaptcha;
196
- }
197
-
198
- private generateSequence(): SequenceCaptcha {
199
- const seq = SequenceGenerator.generate(this.getDifficulty());
200
- return this.createChallenge({ type: 'sequence', question: seq.question, answer: seq.answer }) as SequenceCaptcha;
201
- }
202
-
203
- private generateScramble(): ScrambleCaptcha {
204
- const scr = ScrambleGenerator.generate(this.getDifficulty());
205
- return this.createChallenge({ type: 'scramble', question: scr.question, answer: scr.answer }) as ScrambleCaptcha;
206
- }
207
-
208
- private generateReverse(): ReverseCaptcha {
209
- const rev = ReverseGenerator.generate(this.getDifficulty());
210
- return this.createChallenge({ type: 'reverse', question: rev.question, answer: rev.answer }) as ReverseCaptcha;
211
- }
212
-
213
- // randomly selects one of the available non-compound types
214
- private generateMixed(): MixedCaptcha {
215
- const types = ['math', 'text', 'sequence', 'scramble', 'reverse'] as const;
216
- const buffer = randomBytes(1) as any;
217
- const randomType = types[buffer[0]! % types.length]!;
218
-
219
- // resolve the raw answer directly so we can pass it to createChallenge;
220
- // avoids mutating this.standardOptions and prevents race conditions
221
- let question: string;
222
- let answer: string | number;
223
-
224
- if (randomType === 'math') {
225
- const difficulty = this.getDifficulty();
226
- let num1 = Random.getRandomNumber(difficulty);
227
- let num2 = Random.getRandomNumber(difficulty);
228
- const operator = Random.getRandomOperator();
229
- if (operator === '/' && num2 === 0) {
230
- num2 = Random.getRandomNumber(difficulty) + 1;
231
- }
232
- const result = this.calculateMath(num1, operator, num2);
233
- if (isNaN(result) || !isFinite(result)) {
234
- num1 = Random.getRandomNumber(difficulty);
235
- num2 = Random.getRandomNumber(difficulty) + 1;
236
- question = `${num1} + ${num2}`;
237
- answer = num1 + num2;
238
- } else {
239
- question = `${num1} ${operator} ${num2}`;
240
- answer = result;
241
- }
242
- } else if (randomType === 'text') {
243
- const text = Random.generateRandomString(this.getDifficulty());
244
- question = text;
245
- answer = text;
246
- } else if (randomType === 'sequence') {
247
- const seq = SequenceGenerator.generate(this.getDifficulty());
248
- question = seq.question;
249
- answer = seq.answer;
250
- } else if (randomType === 'scramble') {
251
- const scr = ScrambleGenerator.generate(this.getDifficulty());
252
- question = scr.question;
253
- answer = scr.answer;
254
- } else {
255
- const rev = ReverseGenerator.generate(this.getDifficulty());
256
- question = rev.question;
257
- answer = rev.answer;
258
- }
259
-
260
- return this.createChallenge({ type: 'mixed', question, answer }) as MixedCaptcha;
261
- }
262
-
263
- // two-step captcha: math + scramble, both must be solved correctly
264
- private generateMulti(): CaptchaChallenge {
265
- const step1 = this.store.get(this.generateMath().nonce)!;
266
- const step2 = this.store.get(this.generateScramble().nonce)!;
267
-
268
- return this.createChallenge({
269
- type: 'multi',
270
- question: 'Complete two steps',
271
- answer: '',
272
- steps: [step1, step2]
273
- });
274
- }
275
-
276
- // generates an SVG-based visual CAPTCHA immune to trivial OCR attacks
277
- private generateImage(): ImageCaptcha {
278
- const result = ImageGenerator.generate(this.getDifficulty());
279
- return this.createChallenge({
280
- type: 'image',
281
- question: result.question,
282
- answer: result.answer,
283
- image: result.image
284
- }) as ImageCaptcha;
285
- }
286
-
287
- // generates an emoji selection CAPTCHA: user picks all emojis from a given category
288
- private generateEmoji(): EmojiCaptcha {
289
- const result = EmojiGenerator.generate(this.getDifficulty());
290
- return this.createChallenge({
291
- type: 'emoji',
292
- question: result.question,
293
- answer: result.answer,
294
- emojis: result.emojis,
295
- category: result.category
296
- }) as EmojiCaptcha;
297
- }
298
- }
@@ -1,182 +0,0 @@
1
- import { createHash } from '../utils/crypto';
2
- import { timingSafeEqual } from 'node:crypto';
3
- import type { StoredChallenge } from '../types';
4
-
5
- export class CaptchaValidator {
6
- private static readonly MAX_INPUT_LENGTH = 1000;
7
- private static readonly VALID_CHAR_REGEX = /^[a-zA-Z0-9\s\-çÇğĞıİöÖşŞüÜ.,'!?]*$/;
8
-
9
- // main validation entry point, routes to the correct validator based on challenge type
10
- static validate(challenge: StoredChallenge, userInput: string): boolean {
11
- if (!this.isValidInput(userInput)) {
12
- return false;
13
- }
14
-
15
- if (challenge.type === 'multi') {
16
- return this.validateMulti(challenge, userInput);
17
- }
18
-
19
- if (challenge.type === 'custom') {
20
- return this.validateCustom(challenge, userInput);
21
- }
22
-
23
- if (challenge.type === 'image') {
24
- return this.validateImage(challenge, userInput);
25
- }
26
-
27
- if (challenge.type === 'emoji') {
28
- return this.validateEmoji(challenge, userInput);
29
- }
30
-
31
- if (this.isNumericChallenge(challenge)) {
32
- return this.validateNumeric(challenge, userInput);
33
- }
34
-
35
- return this.validateText(challenge, userInput);
36
- }
37
-
38
- private static isValidInput(input: unknown): boolean {
39
- if (typeof input !== 'string') {
40
- return false;
41
- }
42
- if (input.length === 0 || input.length > this.MAX_INPUT_LENGTH) {
43
- return false;
44
- }
45
- return true;
46
- }
47
-
48
- // validates multi step captchas by checking each step individually
49
- private static validateMulti(challenge: StoredChallenge, userInput: string): boolean {
50
- if (!challenge.steps || challenge.steps.length === 0) {
51
- return false;
52
- }
53
-
54
- let parsed: unknown;
55
- try {
56
- // NOTE: user input should be a JSON array of answers
57
- parsed = JSON.parse(userInput);
58
- } catch {
59
- return false;
60
- }
61
-
62
- if (!Array.isArray(parsed) || parsed.length !== challenge.steps.length) {
63
- return false;
64
- }
65
-
66
- // check each step answer matches its challenge
67
- for (let i = 0; i < challenge.steps.length; i++) {
68
- const step = challenge.steps[i];
69
- const input = parsed[i];
70
-
71
- if (!step || typeof input !== 'string') {
72
- return false;
73
- }
74
-
75
- if (!this.validate(step, input)) {
76
- return false;
77
- }
78
- }
79
-
80
- return true;
81
- }
82
-
83
- private static isNumericChallenge(challenge: StoredChallenge): boolean {
84
- // sequence can return string answers (e.g. letters for medium difficulty), so check the actual answer type
85
- return challenge.type === 'math' ||
86
- (challenge.type === 'sequence' && typeof challenge.answer === 'number') ||
87
- (challenge.type === 'mixed' && typeof challenge.answer === 'number');
88
- }
89
-
90
- private static validateNumeric(challenge: StoredChallenge, userInput: string): boolean {
91
- const inputNum = parseFloat(userInput);
92
-
93
- // make sure we got a valid number, not NaN or Infinity
94
- if (isNaN(inputNum) || !isFinite(inputNum)) {
95
- return false;
96
- }
97
-
98
- return this.verifyAnswer(challenge, inputNum.toString());
99
- }
100
-
101
- private static validateText(challenge: StoredChallenge, userInput: string): boolean {
102
- const sanitized = userInput.trim();
103
-
104
- if (!this.VALID_CHAR_REGEX.test(sanitized)) {
105
- return false;
106
- }
107
-
108
- return this.verifyAnswer(challenge, sanitized);
109
- }
110
-
111
- // hash the user input with the same salt and compare using a constant-time
112
- // equality check to eliminate timing side-channels
113
- private static verifyAnswer(challenge: StoredChallenge, userInput: string): boolean {
114
- const userHash = createHash('sha256')
115
- .update(userInput + challenge.salt)
116
- .digest('hex');
117
-
118
- // both buffers must be the same length for timingSafeEqual; hex-encoded
119
- // SHA-256 is always 64 chars so this holds unless hashedAnswer is corrupted
120
- if (userHash.length !== challenge.hashedAnswer.length) {
121
- return false;
122
- }
123
-
124
- return timingSafeEqual(
125
- Buffer.from(userHash, 'hex'),
126
- Buffer.from(challenge.hashedAnswer, 'hex')
127
- );
128
- }
129
-
130
- private static validateCustom(challenge: StoredChallenge, userInput: string): boolean {
131
- const sanitized = userInput.trim();
132
-
133
- if (!this.VALID_CHAR_REGEX.test(sanitized)) {
134
- return false;
135
- }
136
-
137
- return this.verifyAnswer(challenge, sanitized);
138
- }
139
-
140
- // image answers are case-insensitive; only alphanumeric chars are accepted
141
- private static validateImage(challenge: StoredChallenge, userInput: string): boolean {
142
- const sanitized = userInput.trim().toLowerCase();
143
-
144
- if (!/^[a-z0-9]+$/.test(sanitized)) {
145
- return false;
146
- }
147
-
148
- if (sanitized.length < 1 || sanitized.length > 20) {
149
- return false;
150
- }
151
-
152
- return this.verifyAnswer(challenge, sanitized);
153
- }
154
-
155
- // emoji answers: comma-separated zero-based indices e.g. "0,2,4"
156
- // parsed, deduplicated, sorted numerically then re-joined to produce the canonical form
157
- private static validateEmoji(challenge: StoredChallenge, userInput: string): boolean {
158
- const trimmed = userInput.trim();
159
-
160
- // only digits and commas are valid; reject anything else to prevent injection
161
- if (!/^[0-9,]+$/.test(trimmed)) {
162
- return false;
163
- }
164
-
165
- const parts = trimmed.split(',').filter(s => s.length > 0);
166
-
167
- if (parts.length === 0 || parts.length > 20) {
168
- return false;
169
- }
170
-
171
- const indices = parts.map(Number);
172
-
173
- if (indices.some(n => isNaN(n) || n < 0 || !Number.isInteger(n))) {
174
- return false;
175
- }
176
-
177
- // canonical form matches what EmojiGenerator stored: sorted unique indices
178
- const normalized = [...new Set(indices)].sort((a, b) => a - b).join(',');
179
-
180
- return this.verifyAnswer(challenge, normalized);
181
- }
182
- }
@@ -1,84 +0,0 @@
1
- export interface K9GuardOptions {
2
- type: 'math' | 'text' | 'sequence' | 'scramble' | 'reverse' | 'mixed' | 'multi' | 'image' | 'emoji';
3
- difficulty: 'easy' | 'medium' | 'hard';
4
- }
5
-
6
- export interface CustomQuestion {
7
- question: string;
8
- answer: string;
9
- difficulty: 'easy' | 'medium' | 'hard';
10
- }
11
-
12
- export interface K9GuardCustomOptions {
13
- type: 'custom';
14
- questions: CustomQuestion[];
15
- }
16
-
17
- // Internal: full challenge record kept server-side only.
18
- // answer, hashedAnswer and salt must never leave the server.
19
- export interface StoredChallenge {
20
- type: 'math' | 'text' | 'sequence' | 'scramble' | 'reverse' | 'mixed' | 'multi' | 'custom' | 'image' | 'emoji';
21
- question: string;
22
- answer: string | number;
23
- nonce: string;
24
- expiry: number;
25
- hashedAnswer: string;
26
- salt: string;
27
- steps?: StoredChallenge[];
28
- image?: string;
29
- emojis?: string[];
30
- category?: string;
31
- }
32
-
33
- // Public: safe subset sent to the client.
34
- // answer, hashedAnswer and salt are intentionally omitted to prevent
35
- // hash-injection attacks where an attacker forges hashedAnswer on the client.
36
- export interface CaptchaChallenge {
37
- type: StoredChallenge['type'];
38
- question: string;
39
- nonce: string;
40
- expiry: number;
41
- steps?: CaptchaChallenge[];
42
- image?: string;
43
- emojis?: string[];
44
- category?: string;
45
- }
46
-
47
- export interface ImageCaptcha extends CaptchaChallenge {
48
- type: 'image';
49
- image: string;
50
- }
51
-
52
- export interface MathCaptcha extends CaptchaChallenge {
53
- type: 'math';
54
- }
55
-
56
- export interface TextCaptcha extends CaptchaChallenge {
57
- type: 'text';
58
- }
59
-
60
- export interface SequenceCaptcha extends CaptchaChallenge {
61
- type: 'sequence';
62
- }
63
-
64
- export interface ScrambleCaptcha extends CaptchaChallenge {
65
- type: 'scramble';
66
- }
67
-
68
- export interface ReverseCaptcha extends CaptchaChallenge {
69
- type: 'reverse';
70
- }
71
-
72
- export interface MixedCaptcha extends CaptchaChallenge {
73
- type: 'mixed';
74
- }
75
-
76
- export interface CustomCaptcha extends CaptchaChallenge {
77
- type: 'custom';
78
- }
79
-
80
- export interface EmojiCaptcha extends CaptchaChallenge {
81
- type: 'emoji';
82
- emojis: string[];
83
- category: string;
84
- }