Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

middlewarified #184

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions www/.env.template
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,9 @@ NEXT_PUBLIC_STRIPE_ENABLED=false
STRIPE_SECRET_KEY=
NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY=
STRIPE_WEBHOOK_SECRET=
# Turnstile (optional)
NEXT_PUBLIC_TURNSTILE_SITE_KEY=
TURNSTILE_SECRET_KEY=
# Agent
AI_API_KEY=
MODEL=
Expand Down
92 changes: 56 additions & 36 deletions www/app/Chat.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import Swal from 'sweetalert2';
import { useRef, useEffect, useState, ElementRef, useMemo } from 'react';
import { useRouter } from 'next/navigation';
import { usePostHog } from 'posthog-js/react';
import Turnstile, { useTurnstile } from 'react-turnstile';

import { createClient } from '@/utils/supabase/client';
import { Reaction } from '@/components/messagebox';
Expand Down Expand Up @@ -129,6 +130,10 @@ export default function Chat({
const messageContainerRef = useRef<ElementRef<'section'>>(null);
const [, scrollToBottom] = useAutoScroll(messageContainerRef);

const turnstileEnabled = process.env.NEXT_PUBLIC_TURNSTILE_SITE_KEY !== null;
const turnstileSiteKey = process.env.NEXT_PUBLIC_TURNSTILE_SITE_KEY || '';
const turnstile = useTurnstile();

useEffect(() => {
if (typeof window !== 'undefined') {
posthog?.identify(initialUserId, { email: initialEmail });
Expand Down Expand Up @@ -318,7 +323,7 @@ export default function Chat({
honchoResponse
).json()) as HonchoResponse;

const pureThought = thoughtText
const pureThought = thoughtText;

thoughtText +=
'\n\nHoncho Dialectic Response:\n\n' + honchoContent.content;
Expand Down Expand Up @@ -491,10 +496,10 @@ export default function Chat({
/>
)}
</section>
<div className="p-3 pb-0 lg:p-5 lg:pb-0">
<div className="p-3 lg:p-5">
<form
id="send"
className="flex p-3 lg:p-5 gap-3 border-gray-300"
className="flex flex-col items-center gap-3 border-gray-300"
onSubmit={(e) => {
e.preventDefault();
if (canSend && input.current?.value && canUseApp) {
Expand All @@ -503,41 +508,56 @@ export default function Chat({
}
}}
>
<textarea
ref={input}
placeholder={
canUseApp ? 'Type a message...' : 'Subscribe to send messages'
}
className={`flex-1 px-3 py-1 lg:px-5 lg:py-3 bg-gray-100 dark:bg-gray-800 text-gray-400 rounded-2xl border-2 resize-none outline-none focus:outline-none ${canSend && canUseApp
? 'border-green-200 focus:border-green-200'
: 'border-red-200 focus:border-red-200 opacity-50'
{turnstileEnabled && (
<Turnstile
sitekey={turnstileSiteKey}
appearance="interaction-only"
onVerify={(token) => {
document.cookie = `cf-turnstile-response=${token}`;
turnstile.remove();
}}
/>
)}
VVoruganti marked this conversation as resolved.
Show resolved Hide resolved
<div className="flex gap-3 w-full">
<textarea
ref={input}
placeholder={
canUseApp
? 'Type a message...'
: 'Subscribe to send messages'
}
className={`flex-1 px-3 py-1 lg:px-5 lg:py-3 bg-gray-100 dark:bg-gray-800 text-gray-400 rounded-2xl border-2 resize-none ${
canSend && canUseApp
? 'border-green-200'
: 'border-red-200 opacity-50'
}`}
rows={1}
disabled={!canUseApp}
onKeyDown={(e) => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
if (canSend && input.current?.value && canUseApp) {
posthog.capture('user_sent_message');
chat();
rows={1}
disabled={!canUseApp}
onKeyDown={(e) => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
if (canSend && input.current?.value && canUseApp) {
posthog.capture('user_sent_message');
chat();
}
}
}
}}
/>
<button
className="bg-dark-green text-neon-green rounded-full px-4 py-2 lg:px-7 lg:py-3 flex justify-center items-center gap-2"
type="submit"
disabled={!canSend || !canUseApp}
>
<FaPaperPlane className="inline" />
</button>
<button
className="bg-dark-green text-neon-green rounded-full px-4 py-2 lg:px-7 lg:py-3 flex justify-center items-center gap-2"
onClick={() => setIsThoughtsOpen(true)}
type="button"
>
<FaLightbulb className="inline" />
</button>
}}
/>
<button
className="bg-dark-green text-neon-green rounded-full px-4 py-2 lg:px-7 lg:py-3 flex justify-center items-center gap-2"
type="submit"
disabled={!canSend || !canUseApp}
>
<FaPaperPlane className="inline" />
</button>
<button
className="bg-dark-green text-neon-green rounded-full px-4 py-2 lg:px-7 lg:py-3 flex justify-center items-center gap-2"
onClick={() => setIsThoughtsOpen(true)}
type="button"
>
<FaLightbulb className="inline" />
</button>
</div>
</form>
</div>
</div>
Expand Down
46 changes: 46 additions & 0 deletions www/app/captcha/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
'use client';
import Turnstile, { useTurnstile } from 'react-turnstile';
import { useSearchParams, useRouter } from 'next/navigation';
import { useEffect } from 'react';

export default function CaptchaPage() {
const turnstile = useTurnstile();
const router = useRouter();
const searchParams = useSearchParams();
const redirectUrl = searchParams.get('redirect') || '/';
const turnstileSiteKey = process.env.NEXT_PUBLIC_TURNSTILE_SITE_KEY;

useEffect(() => {
if (!turnstileSiteKey) {
router.push(redirectUrl);
}
}, [turnstileSiteKey, router, redirectUrl]);

if (!turnstileSiteKey) {
return null;
}

return (
<div className="h-full flex flex-col items-center justify-center bg-gray-50 dark:bg-gray-900">
<div className="max-w-md w-full p-8 bg-white dark:bg-gray-800 rounded-lg shadow-lg">
<h1 className="text-2xl font-bold text-center mb-6 text-gray-900 dark:text-white">
Verifying you're human
</h1>
<p className="text-gray-600 dark:text-gray-300 text-center mb-8">
Please complete the security check to continue
</p>
<div className="flex justify-center">
<Turnstile
sitekey={turnstileSiteKey}
appearance="interaction-only"
onVerify={async (token) => {
document.cookie = `cf-turnstile-response=${token}; path=/`;
turnstile.remove();
router.push(redirectUrl);
}}
/>
</div>
</div>
</div>
);
}
27 changes: 23 additions & 4 deletions www/middleware.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,27 @@
import { type NextRequest } from "next/server";
import { updateSession } from "@/utils/supabase/middleware";
import { NextResponse, type NextRequest } from 'next/server';
import { updateSession } from '@/utils/supabase/middleware';
import { verifyTurnstile } from './utils/turnstile';
import { ipAddress } from '@vercel/functions';

export async function middleware(request: NextRequest) {
if (request.nextUrl.pathname.startsWith('/captcha')) {
return NextResponse.next();
}
const response = await updateSession(request);
if (!request.nextUrl.pathname.startsWith('/captcha')) {
const token = request.cookies.get('cf-turnstile-response');
// console.log(token);
// console.log(request.cookies.getAll());
if (
token === undefined ||
!verifyTurnstile(token.value, ipAddress(request) as string)
) {
const url = request.nextUrl.clone();
url.pathname = '/captcha';
url.searchParams.set('redirect', request.nextUrl.pathname);
return NextResponse.redirect(url);
}
}
return response;
}

Expand All @@ -15,7 +34,7 @@ export const config = {
* - favicon.ico (favicon file)
* Feel free to modify this pattern to include more paths.
*/
"/((?!_next/static|_next/image|api/webhook|favicon.ico|.*\\.(?:svg|png|jpg|jpeg|gif|webp)$).*)",
"/auth/reset",
'/((?!_next/static|_next/image|api/webhook|favicon.ico|.*\\.(?:svg|png|jpg|jpeg|gif|webp)$).*)',
'/auth/reset',
],
};
2 changes: 2 additions & 0 deletions www/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
"@stripe/stripe-js": "^4.9.0",
"@supabase/ssr": "^0.5.2",
"@supabase/supabase-js": "^2.45.6",
"@vercel/functions": "^1.5.1",
VVoruganti marked this conversation as resolved.
Show resolved Hide resolved
"@vercel/speed-insights": "^1.1.0",
"ai": "^4.0.1",
"class-variance-authority": "^0.7.0",
Expand All @@ -36,6 +37,7 @@
"react-markdown": "^8.0.7",
"react-syntax-highlighter": "^15.6.1",
"react-toggle-dark-mode": "^1.1.1",
"react-turnstile": "^1.1.4",
"rehype-katex": "^7.0.1",
"remark-math": "^6.0.0",
"retry": "^0.13.1",
Expand Down
34 changes: 31 additions & 3 deletions www/pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

16 changes: 16 additions & 0 deletions www/utils/turnstile.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
export async function verifyTurnstile(token: string, ip: string) {
const formData = new FormData();
formData.append('secret', process.env.TURNSTILE_SECRET_KEY as string);
formData.append('response', token);
formData.append('remoteip', ip);

const url = 'https://challenges.cloudflare.com/turnstile/v0/siteverify';
const result = await fetch(url, {
body: formData,
method: 'POST',
});

const json = await result.json();

return json.success;
}
Loading