@dupecom/botcha-cloudflare 0.2.0 → 0.3.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.
@@ -246,3 +246,394 @@ export async function validateLandingToken(token, kv) {
246
246
  export async function solveSpeedChallenge(problems) {
247
247
  return Promise.all(problems.map(n => sha256First(n.toString(), 8)));
248
248
  }
249
+ // ============ REASONING CHALLENGE ============
250
+ // In-memory storage for reasoning challenges
251
+ const reasoningChallenges = new Map();
252
+ // Question bank - LLMs can answer these, simple scripts cannot
253
+ const QUESTION_BANK = [
254
+ // Analogies
255
+ {
256
+ id: 'analogy-1',
257
+ question: 'Complete the analogy: Book is to library as car is to ___',
258
+ category: 'analogy',
259
+ acceptedAnswers: ['garage', 'parking lot', 'dealership', 'parking garage', 'lot'],
260
+ },
261
+ {
262
+ id: 'analogy-2',
263
+ question: 'Complete the analogy: Painter is to brush as writer is to ___',
264
+ category: 'analogy',
265
+ acceptedAnswers: ['pen', 'pencil', 'keyboard', 'typewriter', 'quill'],
266
+ },
267
+ {
268
+ id: 'analogy-3',
269
+ question: 'Complete the analogy: Fish is to water as bird is to ___',
270
+ category: 'analogy',
271
+ acceptedAnswers: ['air', 'sky', 'atmosphere'],
272
+ },
273
+ {
274
+ id: 'analogy-4',
275
+ question: 'Complete the analogy: Eye is to see as ear is to ___',
276
+ category: 'analogy',
277
+ acceptedAnswers: ['hear', 'listen', 'hearing', 'listening'],
278
+ },
279
+ // Wordplay
280
+ {
281
+ id: 'wordplay-1',
282
+ question: 'What single word connects: apple, Newton, gravity?',
283
+ category: 'wordplay',
284
+ acceptedAnswers: ['tree', 'fall', 'falling'],
285
+ },
286
+ {
287
+ id: 'wordplay-2',
288
+ question: 'What single word connects: key, piano, computer?',
289
+ category: 'wordplay',
290
+ acceptedAnswers: ['keyboard', 'board', 'keys'],
291
+ },
292
+ {
293
+ id: 'wordplay-3',
294
+ question: 'What single word connects: river, money, blood?',
295
+ category: 'wordplay',
296
+ acceptedAnswers: ['bank', 'flow', 'stream'],
297
+ },
298
+ {
299
+ id: 'wordplay-4',
300
+ question: 'What word can precede: light, house, shine?',
301
+ category: 'wordplay',
302
+ acceptedAnswers: ['sun', 'moon'],
303
+ },
304
+ // Logic
305
+ {
306
+ id: 'logic-1',
307
+ question: 'If all Bloops are Razzies and all Razzies are Lazzies, are all Bloops definitely Lazzies? Answer yes or no.',
308
+ category: 'logic',
309
+ acceptedAnswers: ['yes'],
310
+ },
311
+ {
312
+ id: 'logic-2',
313
+ question: 'If some Widgets are Gadgets, and all Gadgets are blue, can some Widgets be blue? Answer yes or no.',
314
+ category: 'logic',
315
+ acceptedAnswers: ['yes'],
316
+ },
317
+ {
318
+ id: 'logic-3',
319
+ question: 'I have a bee in my hand. What do I have in my eye? (Think about the saying)',
320
+ category: 'logic',
321
+ acceptedAnswers: ['beauty', 'beholder'],
322
+ },
323
+ {
324
+ id: 'logic-4',
325
+ question: 'A farmer has 17 sheep. All but 9 run away. How many sheep does he have left?',
326
+ category: 'logic',
327
+ acceptedAnswers: ['9', 'nine'],
328
+ },
329
+ // Math
330
+ {
331
+ id: 'math-1',
332
+ question: 'A bat and ball cost $1.10 total. The bat costs $1.00 more than the ball. How much does the ball cost in cents?',
333
+ category: 'math',
334
+ acceptedAnswers: ['5', '5 cents', 'five', 'five cents', '0.05', '$0.05'],
335
+ },
336
+ {
337
+ id: 'math-2',
338
+ question: 'If it takes 5 machines 5 minutes to make 5 widgets, how many minutes would it take 100 machines to make 100 widgets?',
339
+ category: 'math',
340
+ acceptedAnswers: ['5', 'five', '5 minutes', 'five minutes'],
341
+ },
342
+ {
343
+ id: 'math-3',
344
+ question: 'In a lake, there is a patch of lily pads. Every day, the patch doubles in size. If it takes 48 days for the patch to cover the entire lake, how many days would it take for the patch to cover half of the lake?',
345
+ category: 'math',
346
+ acceptedAnswers: ['47', 'forty-seven', 'forty seven', '47 days'],
347
+ },
348
+ // Code
349
+ {
350
+ id: 'code-1',
351
+ question: 'What is wrong with this code: if (x = 5) { doSomething(); }',
352
+ category: 'code',
353
+ acceptedAnswers: ['assignment', 'single equals', '= instead of ==', 'should be ==', 'should be ===', 'equality', 'comparison'],
354
+ },
355
+ {
356
+ id: 'code-2',
357
+ question: 'In most programming languages, what does the modulo operator % return for 17 % 5?',
358
+ category: 'code',
359
+ acceptedAnswers: ['2', 'two'],
360
+ },
361
+ {
362
+ id: 'code-3',
363
+ question: 'What data structure uses LIFO (Last In, First Out)?',
364
+ category: 'code',
365
+ acceptedAnswers: ['stack', 'a stack'],
366
+ },
367
+ // Common sense
368
+ {
369
+ id: 'sense-1',
370
+ question: 'If you are running a race and you pass the person in second place, what place are you in now?',
371
+ category: 'common-sense',
372
+ acceptedAnswers: ['second', '2nd', '2', 'two'],
373
+ },
374
+ {
375
+ id: 'sense-2',
376
+ question: 'What gets wetter the more it dries?',
377
+ category: 'common-sense',
378
+ acceptedAnswers: ['towel', 'a towel', 'cloth', 'rag'],
379
+ },
380
+ {
381
+ id: 'sense-3',
382
+ question: 'What can you catch but not throw?',
383
+ category: 'common-sense',
384
+ acceptedAnswers: ['cold', 'a cold', 'breath', 'your breath', 'feelings', 'disease'],
385
+ },
386
+ ];
387
+ /**
388
+ * Generate a reasoning challenge: 3 random questions requiring LLM capabilities
389
+ */
390
+ export async function generateReasoningChallenge(kv) {
391
+ cleanExpired();
392
+ const id = uuid();
393
+ // Pick 3 random questions from different categories
394
+ const shuffled = [...QUESTION_BANK].sort(() => Math.random() - 0.5);
395
+ const selectedCategories = new Set();
396
+ const selectedQuestions = [];
397
+ for (const q of shuffled) {
398
+ if (selectedQuestions.length >= 3)
399
+ break;
400
+ if (selectedQuestions.length < 2 || !selectedCategories.has(q.category)) {
401
+ selectedQuestions.push(q);
402
+ selectedCategories.add(q.category);
403
+ }
404
+ }
405
+ while (selectedQuestions.length < 3 && shuffled.length > selectedQuestions.length) {
406
+ const q = shuffled.find(sq => !selectedQuestions.includes(sq));
407
+ if (q)
408
+ selectedQuestions.push(q);
409
+ }
410
+ const expectedAnswers = {};
411
+ const questions = selectedQuestions.map(q => {
412
+ expectedAnswers[q.id] = q.acceptedAnswers;
413
+ return {
414
+ id: q.id,
415
+ question: q.question,
416
+ category: q.category,
417
+ };
418
+ });
419
+ const timeLimit = 30000; // 30 seconds
420
+ const challenge = {
421
+ id,
422
+ questions,
423
+ expectedAnswers,
424
+ issuedAt: Date.now(),
425
+ expiresAt: Date.now() + timeLimit + 5000,
426
+ };
427
+ // Store in KV or memory
428
+ if (kv) {
429
+ await kv.put(`challenge:${id}`, JSON.stringify(challenge), { expirationTtl: 300 });
430
+ }
431
+ else {
432
+ reasoningChallenges.set(id, challenge);
433
+ }
434
+ return {
435
+ id,
436
+ questions,
437
+ timeLimit,
438
+ instructions: 'Answer all 3 questions. These require reasoning that LLMs can do but simple scripts cannot. You have 30 seconds.',
439
+ };
440
+ }
441
+ /**
442
+ * Normalize answer for comparison
443
+ */
444
+ function normalizeAnswer(answer) {
445
+ return answer
446
+ .toLowerCase()
447
+ .trim()
448
+ .replace(/[.,!?'"]/g, '')
449
+ .replace(/\s+/g, ' ');
450
+ }
451
+ /**
452
+ * Check if an answer matches any accepted answer
453
+ */
454
+ function isAnswerAccepted(answer, acceptedAnswers) {
455
+ const normalized = normalizeAnswer(answer);
456
+ for (const accepted of acceptedAnswers) {
457
+ const normalizedAccepted = normalizeAnswer(accepted);
458
+ if (normalized === normalizedAccepted)
459
+ return true;
460
+ if (normalized.includes(normalizedAccepted))
461
+ return true;
462
+ if (normalizedAccepted.includes(normalized) && normalized.length > 2)
463
+ return true;
464
+ }
465
+ return false;
466
+ }
467
+ /**
468
+ * Verify a reasoning challenge response
469
+ */
470
+ export async function verifyReasoningChallenge(id, answers, kv) {
471
+ let challenge = null;
472
+ if (kv) {
473
+ const data = await kv.get(`challenge:${id}`);
474
+ challenge = data ? JSON.parse(data) : null;
475
+ }
476
+ else {
477
+ cleanExpired();
478
+ challenge = reasoningChallenges.get(id) || null;
479
+ }
480
+ if (!challenge) {
481
+ return { valid: false, reason: 'Challenge not found or expired' };
482
+ }
483
+ const now = Date.now();
484
+ const solveTimeMs = now - challenge.issuedAt;
485
+ // Delete challenge
486
+ if (kv) {
487
+ await kv.delete(`challenge:${id}`);
488
+ }
489
+ else {
490
+ reasoningChallenges.delete(id);
491
+ }
492
+ if (now > challenge.expiresAt) {
493
+ return { valid: false, reason: `Too slow! Took ${solveTimeMs}ms, limit was 30 seconds` };
494
+ }
495
+ if (!answers || typeof answers !== 'object') {
496
+ return { valid: false, reason: 'Answers must be an object mapping question IDs to answers' };
497
+ }
498
+ let correctCount = 0;
499
+ const totalCount = challenge.questions.length;
500
+ const wrongQuestions = [];
501
+ for (const q of challenge.questions) {
502
+ const userAnswer = answers[q.id];
503
+ const acceptedAnswers = challenge.expectedAnswers[q.id] || [];
504
+ if (!userAnswer) {
505
+ wrongQuestions.push(q.id);
506
+ continue;
507
+ }
508
+ if (isAnswerAccepted(userAnswer, acceptedAnswers)) {
509
+ correctCount++;
510
+ }
511
+ else {
512
+ wrongQuestions.push(q.id);
513
+ }
514
+ }
515
+ if (correctCount < totalCount) {
516
+ return {
517
+ valid: false,
518
+ reason: `Only ${correctCount}/${totalCount} correct. Wrong: ${wrongQuestions.join(', ')}`,
519
+ solveTimeMs,
520
+ correctCount,
521
+ totalCount,
522
+ };
523
+ }
524
+ return {
525
+ valid: true,
526
+ solveTimeMs,
527
+ correctCount,
528
+ totalCount,
529
+ };
530
+ }
531
+ // ============ HYBRID CHALLENGE ============
532
+ const hybridChallenges = new Map();
533
+ /**
534
+ * Generate a hybrid challenge: speed + reasoning combined
535
+ */
536
+ export async function generateHybridChallenge(kv) {
537
+ cleanExpired();
538
+ const id = uuid();
539
+ // Generate both sub-challenges
540
+ const speedChallenge = await generateSpeedChallenge(kv);
541
+ const reasoningChallenge = await generateReasoningChallenge(kv);
542
+ const hybrid = {
543
+ id,
544
+ speedChallengeId: speedChallenge.id,
545
+ reasoningChallengeId: reasoningChallenge.id,
546
+ issuedAt: Date.now(),
547
+ expiresAt: Date.now() + 35000,
548
+ };
549
+ // Store in KV or memory
550
+ if (kv) {
551
+ await kv.put(`hybrid:${id}`, JSON.stringify(hybrid), { expirationTtl: 300 });
552
+ }
553
+ else {
554
+ hybridChallenges.set(id, hybrid);
555
+ }
556
+ return {
557
+ id,
558
+ speed: {
559
+ problems: speedChallenge.problems,
560
+ timeLimit: speedChallenge.timeLimit,
561
+ },
562
+ reasoning: {
563
+ questions: reasoningChallenge.questions,
564
+ timeLimit: reasoningChallenge.timeLimit,
565
+ },
566
+ instructions: 'Solve ALL speed problems (SHA256) in <500ms AND answer ALL reasoning questions. Submit both together.',
567
+ };
568
+ }
569
+ /**
570
+ * Verify a hybrid challenge response
571
+ */
572
+ export async function verifyHybridChallenge(id, speedAnswers, reasoningAnswers, kv) {
573
+ let hybrid = null;
574
+ if (kv) {
575
+ const data = await kv.get(`hybrid:${id}`);
576
+ hybrid = data ? JSON.parse(data) : null;
577
+ }
578
+ else {
579
+ cleanExpired();
580
+ hybrid = hybridChallenges.get(id) || null;
581
+ }
582
+ if (!hybrid) {
583
+ return {
584
+ valid: false,
585
+ reason: 'Hybrid challenge not found or expired',
586
+ speed: { passed: false, reason: 'Challenge not found' },
587
+ reasoning: { passed: false, reason: 'Challenge not found' },
588
+ };
589
+ }
590
+ const now = Date.now();
591
+ const totalTimeMs = now - hybrid.issuedAt;
592
+ if (now > hybrid.expiresAt) {
593
+ if (kv) {
594
+ await kv.delete(`hybrid:${id}`);
595
+ }
596
+ else {
597
+ hybridChallenges.delete(id);
598
+ }
599
+ return {
600
+ valid: false,
601
+ reason: 'Hybrid challenge expired',
602
+ speed: { passed: false, reason: 'Expired' },
603
+ reasoning: { passed: false, reason: 'Expired' },
604
+ totalTimeMs,
605
+ };
606
+ }
607
+ // Verify speed challenge
608
+ const speedResult = await verifySpeedChallenge(hybrid.speedChallengeId, speedAnswers, kv);
609
+ // Verify reasoning challenge
610
+ const reasoningResult = await verifyReasoningChallenge(hybrid.reasoningChallengeId, reasoningAnswers, kv);
611
+ // Clean up hybrid
612
+ if (kv) {
613
+ await kv.delete(`hybrid:${id}`);
614
+ }
615
+ else {
616
+ hybridChallenges.delete(id);
617
+ }
618
+ const speedPassed = speedResult.valid;
619
+ const reasoningPassed = reasoningResult.valid;
620
+ const bothPassed = speedPassed && reasoningPassed;
621
+ return {
622
+ valid: bothPassed,
623
+ reason: bothPassed
624
+ ? undefined
625
+ : `Failed: ${!speedPassed ? 'speed' : ''}${!speedPassed && !reasoningPassed ? ' + ' : ''}${!reasoningPassed ? 'reasoning' : ''}`,
626
+ speed: {
627
+ passed: speedPassed,
628
+ solveTimeMs: speedResult.solveTimeMs,
629
+ reason: speedResult.reason,
630
+ },
631
+ reasoning: {
632
+ passed: reasoningPassed,
633
+ score: reasoningResult.valid ? `${reasoningResult.correctCount}/${reasoningResult.totalCount}` : undefined,
634
+ solveTimeMs: reasoningResult.solveTimeMs,
635
+ reason: reasoningResult.reason,
636
+ },
637
+ totalTimeMs,
638
+ };
639
+ }
package/dist/index.d.ts CHANGED
@@ -27,7 +27,8 @@ declare const app: Hono<{
27
27
  Variables: Variables;
28
28
  }, import("hono/types").BlankSchema, "/">;
29
29
  export default app;
30
- export { generateSpeedChallenge, verifySpeedChallenge, generateStandardChallenge, verifyStandardChallenge, solveSpeedChallenge, } from './challenges';
30
+ export { generateSpeedChallenge, verifySpeedChallenge, generateStandardChallenge, verifyStandardChallenge, generateReasoningChallenge, verifyReasoningChallenge, generateHybridChallenge, verifyHybridChallenge, solveSpeedChallenge, } from './challenges';
31
31
  export { generateToken, verifyToken } from './auth';
32
32
  export { checkRateLimit } from './rate-limit';
33
+ export { generateBadge, verifyBadge, createBadgeResponse, generateBadgeSvg, generateBadgeHtml, generateShareText, type BadgeMethod, type BadgePayload, type Badge, type ShareFormats, } from './badge';
33
34
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"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