Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
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
2 changes: 1 addition & 1 deletion knip.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"$schema": "https://unpkg.com/knip@latest/schema.json",
"$schema": "https://unpkg.com/knip@5.37.1/schema.json",
"ignore": ["src/assets/**"],
"entry": ["src/**/*.{js,jsx,ts,tsx}", "postcss.config.js", "tailwind.config.js"],
"project": ["src/**/*.{js,jsx,ts,tsx}", "*.config.{js,ts}"]
Expand Down
5 changes: 4 additions & 1 deletion public/game/peanut-game.html
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

version pinned this

Original file line number Diff line number Diff line change
Expand Up @@ -2625,6 +2625,9 @@

<body id="t">
<script>
// Note: Facebook SDK version is pinned to v2.2 to match the API version used in FB.init.
// Using versioned SDK URL ensures consistent behavior. Consider upgrading to a newer
// version (e.g., v19.0) as v2.2 is deprecated, but test thoroughly before updating.
window.fbAsyncInit = function () {
FB.init({
appId: '576553495813787',
Expand All @@ -2640,7 +2643,7 @@
}
js = d.createElement(s)
js.id = id
js.src = '//connect.facebook.net/en_US/sdk.js'
js.src = '//connect.facebook.net/en_US/sdk/v2.2/sdk.js'
fjs.parentNode.insertBefore(js, fjs)
})(document, 'script', 'facebook-jssdk')
</script>
Expand Down
8 changes: 6 additions & 2 deletions public/onesignal/OneSignalSDKWorker.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
// use the stable v16 service worker path per onesignal docs
// note: onesignal does not publish minor-pinned sw paths; use v16 channel
// Version Pinning: OneSignal uses major version channels (v16) for their CDN.
// Per OneSignal documentation, they do not publish minor or patch-pinned service worker URLs.
// The v16 channel receives security updates and bug fixes automatically while maintaining
// API compatibility. This is the recommended approach per OneSignal's best practices.
// For stricter version control, we can consider self-hosting the SDK, but this requires manual updates.
// Reference: https://documentation.onesignal.com/docs/web-push-quickstart
importScripts('https://cdn.onesignal.com/sdks/web/v16/OneSignalSDK.sw.js')
6 changes: 2 additions & 4 deletions src/app/(mobile-ui)/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,7 @@ import { Banner } from '@/components/Global/Banner'
import { DeviceType, useDeviceType } from '@/hooks/useGetDeviceType'
import { useSetupStore } from '@/redux/hooks'
import ForceIOSPWAInstall from '@/components/ForceIOSPWAInstall'

// Allow access to some public paths without authentication
const publicPathRegex = /^\/(request\/pay|claim|pay\/.+$|support|invite|dev)/
import { PUBLIC_ROUTES_REGEX } from '@/constants/routes'

const Layout = ({ children }: { children: React.ReactNode }) => {
const pathName = usePathname()
Expand Down Expand Up @@ -78,7 +76,7 @@ const Layout = ({ children }: { children: React.ReactNode }) => {
}, [])

// Allow access to public paths without authentication
const isPublicPath = publicPathRegex.test(pathName)
const isPublicPath = PUBLIC_ROUTES_REGEX.test(pathName)

useEffect(() => {
if (!isPublicPath && !isFetchingUser && !user) {
Expand Down
265 changes: 265 additions & 0 deletions src/app/(mobile-ui)/qr/[code]/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,265 @@
'use client'

import { Button } from '@/components/0_Bruddle'
import Card from '@/components/Global/Card'
import NavHeader from '@/components/Global/NavHeader'
import { PEANUT_API_URL } from '@/constants'
import { useAuth } from '@/context/authContext'
import { useRouter, useParams } from 'next/navigation'
import { useCallback, useEffect, useState } from 'react'
import PeanutLoading from '@/components/Global/PeanutLoading'
import ErrorAlert from '@/components/Global/ErrorAlert'
import { Icon } from '@/components/Global/Icons/Icon'
import { saveRedirectUrl, generateInviteCodeLink, sanitizeRedirectURL } from '@/utils'
import { getShakeClass } from '@/utils/perk.utils'
import Cookies from 'js-cookie'
import { useRedirectQrStatus } from '@/hooks/useRedirectQrStatus'
import { useHoldToClaim } from '@/hooks/useHoldToClaim'

export default function RedirectQrClaimPage() {
const router = useRouter()
const params = useParams()
const code = params?.code as string
const { user } = useAuth()
const [isLoading, setIsLoading] = useState(false)
const [error, setError] = useState<string | null>(null)

// Fetch redirect QR status using shared hook
const { data: redirectQrData, isLoading: isCheckingStatus, error: redirectQrError } = useRedirectQrStatus(code)

// Handle redirects based on QR status and authentication
useEffect(() => {
// Wait for QR status to load
if (isCheckingStatus || !redirectQrData) {
return
}

// If QR is already claimed, redirect to the target URL
if (redirectQrData.claimed && redirectQrData.redirectUrl) {
// Sanitize redirect URL to prevent open redirect attacks
// For same-origin URLs, sanitizeRedirectURL returns safe path
// For external URLs, it returns null (we handle separately)
const sanitizedPath = sanitizeRedirectURL(redirectQrData.redirectUrl)

if (sanitizedPath) {
// Internal redirect - use sanitized path with Next.js router
router.push(sanitizedPath)
} else {
// External redirect - validate it's expected domain before redirecting
try {
const url = new URL(redirectQrData.redirectUrl)
// Allow external redirects ONLY for trusted domains (peanut.me)
// This relies on backend validation during QR claiming
if (url.hostname.includes('peanut.me') || url.hostname.includes('localhost')) {
window.location.href = redirectQrData.redirectUrl
} else {
console.error('Untrusted external redirect blocked:', redirectQrData.redirectUrl)
setError('Invalid QR code destination.')
}
} catch (error) {
console.error('Invalid redirect URL:', redirectQrData.redirectUrl)
setError('Invalid QR code destination.')
}
}
return
}

// QR is not claimed - check authentication
if (!user) {
// User not logged in - redirect to setup to create account/login
saveRedirectUrl()
router.push('/setup')
}
}, [isCheckingStatus, redirectQrData, user, router])

const handleClaim = useCallback(async () => {
// Auth check is already handled by useEffect above
// If we reach here, user is authenticated
setIsLoading(true)
setError(null)

try {
// Generate invite link with correct 3-digit suffix
const username = user?.user?.username
if (!username) {
throw new Error('Username not found')
}

const { inviteLink } = generateInviteCodeLink(username)

const response = await fetch(`${PEANUT_API_URL}/qr/${code}/claim`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${Cookies.get('jwt-token')}`,
},
body: JSON.stringify({
targetUrl: inviteLink, // Pass the correctly formatted invite link
}),
})

const data = await response.json()

if (!response.ok) {
// Log backend error for debugging but show generic message to user
console.error('Backend claim error:', data.message || data.error)
throw new Error('Failed to claim QR code. Please try again.')
}

// Success! Show success page, then redirect to invite (which goes to profile for logged-in users)
router.push(`/qr/${code}/success`)
} catch (err: any) {
console.error('Error claiming QR:', err)
// Always show generic error message (don't expose backend details)
setError('Failed to claim QR code. Please try again.')
} finally {
setIsLoading(false)
}
}, [code, router, user])

// Hold-to-claim mechanics with shake animation
const { holdProgress, isShaking, shakeIntensity, buttonProps } = useHoldToClaim({
onComplete: handleClaim,
disabled: isLoading,
})

// Show loading while checking status or if we're in the process of redirecting
if (isCheckingStatus || (redirectQrData?.claimed && redirectQrData?.redirectUrl)) {
return (
<div className={`flex min-h-[inherit] flex-col gap-8 ${getShakeClass(isShaking, shakeIntensity)}`}>
<NavHeader title="Claim QR Code" />
<div className="flex h-full items-center justify-center">
<PeanutLoading />
</div>
</div>
)
}

// If not logged in and QR is unclaimed, the useEffect above will redirect to setup
// This loading screen will show briefly during that redirect
if (!user) {
return (
<div className={`flex min-h-[inherit] flex-col gap-8 ${getShakeClass(isShaking, shakeIntensity)}`}>
<NavHeader title="Claim QR Code" />
<div className="flex h-full items-center justify-center">
<PeanutLoading />
</div>
</div>
)
}

// Show error only if there's an actual error or QR is not available (and not claimed)
if (redirectQrError || !redirectQrData || (!redirectQrData.available && !redirectQrData.claimed)) {
// Log error for debugging but don't expose details to user
if (redirectQrError) {
console.error('QR status check error:', redirectQrError)
}
return (
<div className={`flex min-h-[inherit] flex-col gap-8 ${getShakeClass(isShaking, shakeIntensity)}`}>
<NavHeader title="Claim QR Code" />
<div className="my-auto flex h-full flex-col justify-center space-y-4">
<Card className="space-y-4 p-6">
<div className="flex items-center justify-center">
<div className="bg-red-100 flex h-16 w-16 items-center justify-center rounded-full">
<Icon name="cancel" size={32} className="text-red-600" />
</div>
</div>
<div className="space-y-2 text-center">
<h1 className="text-2xl font-extrabold">QR Code Unavailable</h1>
<p className="text-base text-grey-1">
{redirectQrData?.claimed
? 'This QR code has already been claimed by another user.'
: 'This QR code is not available for claiming.'}
</p>
</div>
</Card>
<Button variant="purple" shadowSize="4" onClick={() => router.push('/home')} className="w-full">
Go to Home
</Button>
</div>
</div>
)
}

return (
<div className={`flex min-h-[inherit] flex-col gap-8 ${getShakeClass(isShaking, shakeIntensity)}`}>
<NavHeader title="Claim Your QR Code" />
<div className="my-auto flex h-full flex-col justify-center space-y-4">
{/* QR Code Visual */}
<Card className="space-y-4 p-6">
<div className="flex items-center justify-center">
<div className="flex h-20 w-20 items-center justify-center rounded-full">
<Icon name="qr-code" size={40} className="text-purple-600" />
</div>
</div>
<div className="space-y-2 text-center">
<h1 className="text-2xl font-extrabold">Claim Your Code</h1>
<p className="text-base text-grey-1">
This QR code will be permanently linked to your Peanut profile. Anyone who scans it will be
able to use your invite.
</p>
</div>
</Card>

{/* How it works */}
<Card className="space-y-3 p-6">
<h2 className="text-lg font-bold">How it works</h2>
<div className="space-y-3">
<div className="flex gap-3">
<div className="flex h-8 w-8 flex-shrink-0 items-center justify-center rounded-full bg-secondary-1 text-sm font-bold">
1
</div>
<p className="text-sm text-grey-1">You claim this QR code and it becomes yours forever</p>
</div>
<div className="flex gap-3">
<div className="flex h-8 w-8 flex-shrink-0 items-center justify-center rounded-full bg-secondary-1 text-sm font-bold">
2
</div>
<p className="text-sm text-grey-1">Put the sticker anywhere you want people to find you</p>
</div>
<div className="flex gap-3">
<div className="flex h-8 w-8 flex-shrink-0 items-center justify-center rounded-full bg-secondary-1 text-sm font-bold">
3
</div>
<p className="text-sm text-grey-1">
They can join Peanut with your invite and contribute towards your points, forever.
</p>
</div>
</div>
</Card>

{/* Important note */}
<Card className="border-2 border-secondary-1 bg-secondary-1/10 p-4">
<div className="flex gap-3">
<Icon name="info" size={20} className="flex-shrink-0 text-secondary-1" />
<p className="text-sm font-medium">
<strong>Important:</strong> Once claimed, this QR code cannot be transferred or changed.
</p>
</div>
</Card>

{/* Claim button - Hold to claim */}
<Button
{...buttonProps}
variant="purple"
shadowSize="4"
disabled={isLoading}
loading={isLoading}
className={`${buttonProps.className} w-full`}
>
{/* Black progress fill from left to right */}
<div
className="absolute inset-0 bg-black transition-all duration-100"
style={{
width: `${holdProgress}%`,
left: 0,
}}
/>
<span className="relative z-10">{isLoading ? 'Claiming...' : 'Hold to Claim QR Code'}</span>
</Button>

{error && <ErrorAlert description={error} />}
</div>
</div>
)
}
Loading
Loading