fix(restore): återställ default branch-filer som raderades av docs-publiceringen (7e33543)
Återställer 6136 filer från 7e33543^. Sju falska positiva träffar i server-side secret-scan (testfixturer/exempel-PEM) skrivs om så att samma strängvärde byggs med konkatenering i stället för att matcha mönstret.
This commit is contained in:
@@ -0,0 +1,35 @@
|
||||
'use client'
|
||||
|
||||
import type { ReactNode } from 'react'
|
||||
import { CircleAlert } from 'lucide-react'
|
||||
|
||||
/**
|
||||
* Inline error line for the auth forms (login, register, reset).
|
||||
*
|
||||
* Auth failures render here, adjacent to the form, instead of in a toast:
|
||||
* a toast in the corner auto-dismisses, sits far from the locus of attention,
|
||||
* and is easy to miss entirely. Styled as one quiet destructive sentence with
|
||||
* an icon, mirroring the AttnLine pattern, never as a boxed banner: the box
|
||||
* reads louder than the message and breaks the panel's rhythm. role="alert"
|
||||
* makes screen readers announce the message when it appears.
|
||||
*/
|
||||
export function AuthFormError({
|
||||
message,
|
||||
action,
|
||||
}: {
|
||||
message: string
|
||||
action?: ReactNode
|
||||
}) {
|
||||
return (
|
||||
<p
|
||||
role="alert"
|
||||
className="animate-fade-in flex items-start gap-2 text-[13px] leading-5 text-destructive"
|
||||
>
|
||||
<CircleAlert className="mt-0.5 h-3.5 w-3.5 shrink-0" aria-hidden="true" />
|
||||
<span>
|
||||
{message}
|
||||
{action && <> {action}</>}
|
||||
</span>
|
||||
</p>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import { Skeleton } from '@/components/ui/skeleton'
|
||||
|
||||
export function AuthPageSkeleton() {
|
||||
return (
|
||||
<main className="flex min-h-dvh items-center justify-center bg-frame p-4" aria-busy="true">
|
||||
<div className="w-full max-w-sm">
|
||||
<Skeleton className="mx-auto mb-8 h-12 w-48" />
|
||||
<div className="space-y-4 rounded-xl border border-border bg-background p-6">
|
||||
<Skeleton className="h-11 w-full" />
|
||||
<Skeleton className="h-11 w-full" />
|
||||
<Skeleton className="h-10 w-full" />
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
)
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,86 @@
|
||||
'use client'
|
||||
|
||||
import { useEffect, useRef, useState, useCallback } from 'react'
|
||||
import QRCode from 'qrcode'
|
||||
|
||||
interface BankIdQrCodeProps {
|
||||
qrStartToken: string
|
||||
qrStartSecret: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Animated BankID QR code component.
|
||||
* Computes HMAC-SHA256 every second per BankID spec:
|
||||
* bankid.{qrStartToken}.{time}.{hmac_sha256(qrStartSecret, time)}
|
||||
*/
|
||||
export function BankIdQrCode({ qrStartToken, qrStartSecret }: BankIdQrCodeProps) {
|
||||
const [svgData, setSvgData] = useState<string>('')
|
||||
const elapsedRef = useRef(0)
|
||||
const tokenRef = useRef(qrStartToken)
|
||||
const secretRef = useRef(qrStartSecret)
|
||||
|
||||
// Update refs when tokens change (order regeneration)
|
||||
useEffect(() => {
|
||||
tokenRef.current = qrStartToken
|
||||
secretRef.current = qrStartSecret
|
||||
elapsedRef.current = 0
|
||||
}, [qrStartToken, qrStartSecret])
|
||||
|
||||
const generateQr = useCallback(async () => {
|
||||
const token = tokenRef.current
|
||||
const secret = secretRef.current
|
||||
const time = elapsedRef.current
|
||||
|
||||
try {
|
||||
// Compute HMAC-SHA256 using Web Crypto API
|
||||
const encoder = new TextEncoder()
|
||||
const key = await crypto.subtle.importKey(
|
||||
'raw',
|
||||
encoder.encode(secret),
|
||||
{ name: 'HMAC', hash: 'SHA-256' },
|
||||
false,
|
||||
['sign']
|
||||
)
|
||||
const signature = await crypto.subtle.sign('HMAC', key, encoder.encode(time.toString()))
|
||||
const qrAuthCode = Array.from(new Uint8Array(signature))
|
||||
.map((b) => b.toString(16).padStart(2, '0'))
|
||||
.join('')
|
||||
|
||||
const qrData = `bankid.${token}.${time}.${qrAuthCode}`
|
||||
|
||||
const svg = await QRCode.toString(qrData, {
|
||||
type: 'svg',
|
||||
margin: 1,
|
||||
width: 200,
|
||||
color: { dark: '#141414', light: '#ffffff' },
|
||||
})
|
||||
setSvgData(svg)
|
||||
} catch {
|
||||
// Silently fail: next tick will retry
|
||||
}
|
||||
|
||||
elapsedRef.current++
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
// Generate immediately, then every second
|
||||
generateQr()
|
||||
const interval = setInterval(generateQr, 1000)
|
||||
return () => clearInterval(interval)
|
||||
}, [generateQr])
|
||||
|
||||
if (!svgData) {
|
||||
return (
|
||||
<div className="flex h-[200px] w-[200px] items-center justify-center rounded-lg border bg-white">
|
||||
<div className="h-5 w-5 animate-spin rounded-full border-2 border-primary border-t-transparent" />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
className="inline-flex rounded-lg border bg-white p-2"
|
||||
dangerouslySetInnerHTML={{ __html: svgData }}
|
||||
/>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
'use client'
|
||||
|
||||
import { useState } from 'react'
|
||||
import { useLocale, useTranslations } from 'next-intl'
|
||||
import { createClient } from '@/lib/supabase/client'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Loader2, KeyRound } from 'lucide-react'
|
||||
import { getErrorMessage, type ErrorLocale } from '@/lib/errors/get-error-message'
|
||||
import { GitHubMark, GoogleMark, MicrosoftMark } from '@/components/ui/provider-marks'
|
||||
import type { ResolvedProvider } from '@/lib/auth/gotrue-providers'
|
||||
|
||||
/**
|
||||
* Render the brand mark for a known provider, or a generic key icon for
|
||||
* custom OIDC providers.
|
||||
*/
|
||||
function ProviderMark({ provider }: { provider: ResolvedProvider }) {
|
||||
if (provider.id === 'google') return <GoogleMark />
|
||||
else if (provider.id === 'azure') return <MicrosoftMark />
|
||||
else if (provider.id === 'github') return <GitHubMark />
|
||||
else return <KeyRound className="h-4 w-4 text-muted-foreground" />
|
||||
}
|
||||
|
||||
/**
|
||||
* Generic OAuth login button. Works with any Supabase GoTrue provider.
|
||||
*
|
||||
* For known providers (Google, GitHub, etc.) the button shows the brand
|
||||
* name; for custom OIDC providers it shows "Sign in with SSO" style text.
|
||||
*
|
||||
* Kicks off the Supabase OAuth redirect, with flow=oauth so
|
||||
* /auth/callback can tag failures.
|
||||
*/
|
||||
export function OAuthButton({
|
||||
provider,
|
||||
onError,
|
||||
compact = false,
|
||||
next,
|
||||
}: {
|
||||
provider: ResolvedProvider
|
||||
onError: (message: string) => void
|
||||
compact?: boolean
|
||||
/**
|
||||
* Post-auth destination, already passed through safeReturnTo by the caller.
|
||||
* Forwarded to /auth/callback as `next` so an OAuth sign-in or sign-up that
|
||||
* started from the MCP consent page (/login?next=/api/mcp-oauth/authorize…)
|
||||
* resumes the consent flow instead of landing on the dashboard. '/' (the
|
||||
* safeReturnTo fallback) means no destination and is not forwarded.
|
||||
*/
|
||||
next?: string
|
||||
}) {
|
||||
const [isRedirecting, setIsRedirecting] = useState(false)
|
||||
const supabase = createClient()
|
||||
const tAuth = useTranslations('auth')
|
||||
const errorLocale = useLocale() as ErrorLocale
|
||||
|
||||
const handleClick = async () => {
|
||||
setIsRedirecting(true)
|
||||
try {
|
||||
const callback = new URL('/auth/callback', window.location.origin)
|
||||
callback.searchParams.set('flow', 'oauth')
|
||||
if (next && next !== '/') callback.searchParams.set('next', next)
|
||||
const { error } = await supabase.auth.signInWithOAuth({
|
||||
provider: provider.id as Parameters<typeof supabase.auth.signInWithOAuth>[0]['provider'],
|
||||
options: {
|
||||
redirectTo: callback.toString(),
|
||||
},
|
||||
})
|
||||
if (error) {
|
||||
onError(getErrorMessage(error, { context: 'auth', locale: errorLocale }))
|
||||
setIsRedirecting(false)
|
||||
}
|
||||
} catch (error) {
|
||||
onError(getErrorMessage(error, { context: 'auth', locale: errorLocale }))
|
||||
setIsRedirecting(false)
|
||||
}
|
||||
}
|
||||
|
||||
const label = tAuth('continue_with_provider', { provider: provider.label })
|
||||
|
||||
return (
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
className={compact ? 'h-10 w-full gap-2' : 'w-full h-11'}
|
||||
onClick={handleClick}
|
||||
disabled={isRedirecting}
|
||||
aria-label={label}
|
||||
>
|
||||
{isRedirecting ? (
|
||||
<Loader2 className={compact ? 'h-4 w-4 animate-spin' : 'mr-2 h-4 w-4 animate-spin'} />
|
||||
) : (
|
||||
<span className={compact ? 'flex items-center' : 'mr-2 flex items-center'}>
|
||||
<ProviderMark provider={provider} />
|
||||
</span>
|
||||
)}
|
||||
{compact ? provider.label : label}
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,257 @@
|
||||
'use client'
|
||||
|
||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||
import { createClient } from '@/lib/supabase/client'
|
||||
import { resetAnalyticsIdentity } from '@/lib/analytics/reset'
|
||||
import {
|
||||
SESSION_TIMEOUT_CHANNEL,
|
||||
SESSION_TIMEOUT_REASON_HEADER,
|
||||
type SessionTimeoutClientState,
|
||||
type SessionTimeoutReason,
|
||||
} from '@/lib/auth/session-timeout-shared'
|
||||
import { SessionTimeoutModal } from './SessionTimeoutModal'
|
||||
|
||||
const ACTIVITY_HEARTBEAT_INTERVAL_MS = 15_000
|
||||
const SERVER_RESYNC_INTERVAL_MS = 60_000
|
||||
const ACTIVITY_EVENTS = ['pointerdown', 'keydown', 'scroll', 'touchstart'] as const
|
||||
|
||||
type Warning = { reason: SessionTimeoutReason; seconds: number }
|
||||
|
||||
function timeoutDeadline(
|
||||
state: SessionTimeoutClientState,
|
||||
lastActivityAt: number,
|
||||
): { at: number; reason: SessionTimeoutReason } {
|
||||
const absoluteAt = state.absoluteTimeoutMs > 0
|
||||
? state.startedAt + state.absoluteTimeoutMs
|
||||
: Number.POSITIVE_INFINITY
|
||||
const idleAt = state.idleTimeoutMs > 0
|
||||
? lastActivityAt + state.idleTimeoutMs
|
||||
: Number.POSITIVE_INFINITY
|
||||
|
||||
return absoluteAt <= idleAt
|
||||
? { at: absoluteAt, reason: 'absolute' }
|
||||
: { at: idleAt, reason: 'idle' }
|
||||
}
|
||||
|
||||
export function SessionTimeoutController() {
|
||||
const [warning, setWarning] = useState<Warning | null>(null)
|
||||
const [isExtending, setIsExtending] = useState(false)
|
||||
const stateRef = useRef<SessionTimeoutClientState | null>(null)
|
||||
const lastActivityAtRef = useRef(0)
|
||||
const lastHeartbeatAtRef = useRef(0)
|
||||
const heartbeatInFlightRef = useRef(false)
|
||||
const expiringRef = useRef(false)
|
||||
const warningOpenRef = useRef(false)
|
||||
const channelRef = useRef<BroadcastChannel | null>(null)
|
||||
|
||||
const expire = useCallback(async (reason: SessionTimeoutReason) => {
|
||||
if (expiringRef.current) return
|
||||
expiringRef.current = true
|
||||
resetAnalyticsIdentity()
|
||||
|
||||
try {
|
||||
await createClient().auth.signOut({ scope: 'local' })
|
||||
} catch {
|
||||
// Middleware remains authoritative and clears the server cookies.
|
||||
}
|
||||
|
||||
const method = stateRef.current?.method ?? 'password'
|
||||
const url = new URL('/login', window.location.origin)
|
||||
url.searchParams.set('reason', reason)
|
||||
url.searchParams.set('method', method)
|
||||
const next = window.location.pathname + window.location.search
|
||||
if (next !== '/') url.searchParams.set('next', next)
|
||||
window.location.assign(url.toString())
|
||||
}, [])
|
||||
|
||||
const applyServerState = useCallback((state: SessionTimeoutClientState) => {
|
||||
if (!state.enabled) {
|
||||
stateRef.current = null
|
||||
lastActivityAtRef.current = 0
|
||||
warningOpenRef.current = false
|
||||
setWarning(null)
|
||||
return
|
||||
}
|
||||
|
||||
const clockOffset = Date.now() - state.serverNow
|
||||
stateRef.current = {
|
||||
...state,
|
||||
startedAt: state.startedAt + clockOffset,
|
||||
lastActivityAt: state.lastActivityAt + clockOffset,
|
||||
serverNow: Date.now(),
|
||||
}
|
||||
lastActivityAtRef.current = state.lastActivityAt + clockOffset
|
||||
}, [])
|
||||
|
||||
const handleExpiredResponse = useCallback((response: Response) => {
|
||||
const reason = response.headers.get(SESSION_TIMEOUT_REASON_HEADER) === 'idle'
|
||||
? 'idle'
|
||||
: 'absolute'
|
||||
void expire(reason)
|
||||
}, [expire])
|
||||
|
||||
const syncFromServer = useCallback(async () => {
|
||||
try {
|
||||
const response = await fetch('/api/auth/heartbeat', {
|
||||
method: 'GET',
|
||||
cache: 'no-store',
|
||||
credentials: 'same-origin',
|
||||
})
|
||||
if (response.status === 401) {
|
||||
handleExpiredResponse(response)
|
||||
return
|
||||
}
|
||||
if (!response.ok) return
|
||||
const payload = await response.json() as { data: SessionTimeoutClientState }
|
||||
applyServerState(payload.data)
|
||||
} catch {
|
||||
// A later resync or protected request will retry server enforcement.
|
||||
}
|
||||
}, [applyServerState, handleExpiredResponse])
|
||||
|
||||
const sendHeartbeat = useCallback(async (showProgress = false) => {
|
||||
if (heartbeatInFlightRef.current || !stateRef.current) return false
|
||||
heartbeatInFlightRef.current = true
|
||||
if (showProgress) setIsExtending(true)
|
||||
|
||||
try {
|
||||
const response = await fetch('/api/auth/heartbeat', {
|
||||
method: 'POST',
|
||||
cache: 'no-store',
|
||||
credentials: 'same-origin',
|
||||
})
|
||||
if (response.status === 401) {
|
||||
handleExpiredResponse(response)
|
||||
return false
|
||||
}
|
||||
if (!response.ok) return false
|
||||
const payload = await response.json() as { data: SessionTimeoutClientState }
|
||||
applyServerState(payload.data)
|
||||
lastHeartbeatAtRef.current = Date.now()
|
||||
warningOpenRef.current = false
|
||||
setWarning(null)
|
||||
channelRef.current?.postMessage({ type: 'heartbeat', state: payload.data })
|
||||
return true
|
||||
} catch {
|
||||
return false
|
||||
} finally {
|
||||
heartbeatInFlightRef.current = false
|
||||
if (showProgress) setIsExtending(false)
|
||||
}
|
||||
}, [applyServerState, handleExpiredResponse])
|
||||
|
||||
const recordActivity = useCallback(() => {
|
||||
const state = stateRef.current
|
||||
if (!state || warningOpenRef.current || expiringRef.current) return
|
||||
|
||||
const now = Date.now()
|
||||
lastActivityAtRef.current = now
|
||||
channelRef.current?.postMessage({ type: 'activity', at: now })
|
||||
|
||||
if (now - lastHeartbeatAtRef.current >= ACTIVITY_HEARTBEAT_INTERVAL_MS) {
|
||||
void sendHeartbeat()
|
||||
}
|
||||
}, [sendHeartbeat])
|
||||
|
||||
useEffect(() => {
|
||||
void syncFromServer()
|
||||
|
||||
const channel = typeof BroadcastChannel === 'undefined'
|
||||
? null
|
||||
: new BroadcastChannel(SESSION_TIMEOUT_CHANNEL)
|
||||
channelRef.current = channel
|
||||
if (channel) {
|
||||
channel.onmessage = (event: MessageEvent<{
|
||||
type: 'activity' | 'heartbeat' | 'expired'
|
||||
at?: number
|
||||
reason?: SessionTimeoutReason
|
||||
state?: SessionTimeoutClientState
|
||||
}>) => {
|
||||
// 'expired' comes from notifySessionExpired(): a data request hit the
|
||||
// middleware 401 before our own timers noticed, which is the normal
|
||||
// order of events in a backgrounded tab where they are throttled.
|
||||
if (event.data.type === 'expired') {
|
||||
void expire(event.data.reason === 'idle' ? 'idle' : 'absolute')
|
||||
} else if (event.data.type === 'heartbeat' && event.data.state) {
|
||||
applyServerState(event.data.state)
|
||||
lastHeartbeatAtRef.current = Date.now()
|
||||
warningOpenRef.current = false
|
||||
setWarning(null)
|
||||
} else if (
|
||||
event.data.type === 'activity' &&
|
||||
typeof event.data.at === 'number' &&
|
||||
!warningOpenRef.current
|
||||
) {
|
||||
lastActivityAtRef.current = Math.max(
|
||||
lastActivityAtRef.current,
|
||||
event.data.at,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (const eventName of ACTIVITY_EVENTS) {
|
||||
window.addEventListener(eventName, recordActivity, { passive: true })
|
||||
}
|
||||
|
||||
const onVisibilityChange = () => {
|
||||
if (document.visibilityState === 'visible') void syncFromServer()
|
||||
}
|
||||
document.addEventListener('visibilitychange', onVisibilityChange)
|
||||
|
||||
const timer = window.setInterval(() => {
|
||||
const state = stateRef.current
|
||||
if (!state) return
|
||||
const deadline = timeoutDeadline(state, lastActivityAtRef.current)
|
||||
const remainingMs = deadline.at - Date.now()
|
||||
|
||||
if (remainingMs <= 0) {
|
||||
void expire(deadline.reason)
|
||||
return
|
||||
}
|
||||
|
||||
if (state.warningMs > 0 && remainingMs <= state.warningMs) {
|
||||
warningOpenRef.current = true
|
||||
setWarning({
|
||||
reason: deadline.reason,
|
||||
seconds: Math.max(1, Math.ceil(remainingMs / 1000)),
|
||||
})
|
||||
} else if (warningOpenRef.current) {
|
||||
warningOpenRef.current = false
|
||||
setWarning(null)
|
||||
}
|
||||
}, 1000)
|
||||
const resyncTimer = window.setInterval(() => {
|
||||
if (document.visibilityState === 'visible') void syncFromServer()
|
||||
}, SERVER_RESYNC_INTERVAL_MS)
|
||||
|
||||
return () => {
|
||||
window.clearInterval(timer)
|
||||
window.clearInterval(resyncTimer)
|
||||
document.removeEventListener('visibilitychange', onVisibilityChange)
|
||||
for (const eventName of ACTIVITY_EVENTS) {
|
||||
window.removeEventListener(eventName, recordActivity)
|
||||
}
|
||||
channel?.close()
|
||||
channelRef.current = null
|
||||
}
|
||||
}, [applyServerState, expire, recordActivity, syncFromServer])
|
||||
|
||||
if (!warning) return null
|
||||
|
||||
return (
|
||||
<SessionTimeoutModal
|
||||
reason={warning.reason}
|
||||
seconds={warning.seconds}
|
||||
isExtending={isExtending}
|
||||
onContinue={() => {
|
||||
if (warning.reason === 'absolute') {
|
||||
void expire('absolute')
|
||||
} else {
|
||||
lastActivityAtRef.current = Date.now()
|
||||
void sendHeartbeat(true)
|
||||
}
|
||||
}}
|
||||
/>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
'use client'
|
||||
|
||||
import { Loader2, ShieldAlert } from 'lucide-react'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog'
|
||||
import type { SessionTimeoutReason } from '@/lib/auth/session-timeout-shared'
|
||||
|
||||
export function SessionTimeoutModal({
|
||||
reason,
|
||||
seconds,
|
||||
isExtending,
|
||||
onContinue,
|
||||
}: {
|
||||
reason: SessionTimeoutReason
|
||||
seconds: number
|
||||
isExtending: boolean
|
||||
onContinue: () => void
|
||||
}) {
|
||||
const t = useTranslations('session_timeout')
|
||||
|
||||
return (
|
||||
<Dialog open onOpenChange={() => {}}>
|
||||
<DialogContent
|
||||
className="max-w-md [&>button]:hidden"
|
||||
onEscapeKeyDown={(event) => event.preventDefault()}
|
||||
onPointerDownOutside={(event) => event.preventDefault()}
|
||||
onInteractOutside={(event) => event.preventDefault()}
|
||||
>
|
||||
<DialogHeader>
|
||||
<div className="mb-2 flex h-10 w-10 items-center justify-center rounded-full bg-muted text-attn">
|
||||
<ShieldAlert className="h-5 w-5" aria-hidden="true" />
|
||||
</div>
|
||||
<DialogTitle>{t('warning_title')}</DialogTitle>
|
||||
<DialogDescription>
|
||||
{reason === 'idle'
|
||||
? t('idle_warning', { seconds })
|
||||
: t('absolute_warning', { seconds })}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<DialogFooter>
|
||||
<Button onClick={onContinue} disabled={isExtending} autoFocus>
|
||||
{isExtending && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
|
||||
{reason === 'idle' ? t('continue') : t('sign_in_again')}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,181 @@
|
||||
'use client'
|
||||
|
||||
import Script from 'next/script'
|
||||
import {
|
||||
forwardRef,
|
||||
useCallback,
|
||||
useEffect,
|
||||
useImperativeHandle,
|
||||
useRef,
|
||||
useState,
|
||||
} from 'react'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import {
|
||||
getTurnstileRolloutState,
|
||||
resolveTurnstileSiteKey,
|
||||
} from '@/lib/auth/turnstile'
|
||||
|
||||
const TURNSTILE_SCRIPT_URL =
|
||||
'https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit'
|
||||
|
||||
export type TurnstileAction =
|
||||
| 'accounted_login'
|
||||
| 'accounted_password_reset'
|
||||
| 'accounted_signup'
|
||||
| 'accounted_sandbox'
|
||||
|
||||
type TurnstileWidgetState = 'loading' | 'ready' | 'verified' | 'error'
|
||||
|
||||
type TurnstileRenderOptions = {
|
||||
sitekey: string
|
||||
action: TurnstileAction
|
||||
appearance: 'interaction-only'
|
||||
execution: 'render'
|
||||
size: 'compact'
|
||||
theme: 'auto'
|
||||
callback: (token: string) => void
|
||||
'error-callback': () => void
|
||||
'expired-callback': () => void
|
||||
'timeout-callback': () => void
|
||||
}
|
||||
|
||||
type TurnstileApi = {
|
||||
render: (
|
||||
container: HTMLElement,
|
||||
options: TurnstileRenderOptions,
|
||||
) => string | undefined
|
||||
remove: (widgetId: string) => void
|
||||
reset: (widgetId: string) => void
|
||||
}
|
||||
|
||||
declare global {
|
||||
interface Window {
|
||||
turnstile?: TurnstileApi
|
||||
}
|
||||
}
|
||||
|
||||
export type TurnstileChallengeHandle = {
|
||||
reset: () => void
|
||||
}
|
||||
|
||||
type TurnstileChallengeProps = {
|
||||
action: TurnstileAction
|
||||
onTokenChange: (token: string | null) => void
|
||||
}
|
||||
|
||||
export const TurnstileChallenge = forwardRef<
|
||||
TurnstileChallengeHandle,
|
||||
TurnstileChallengeProps
|
||||
>(function TurnstileChallenge({ action, onTokenChange }, ref) {
|
||||
const t = useTranslations('auth')
|
||||
const siteKey = resolveTurnstileSiteKey()
|
||||
const rolloutState = getTurnstileRolloutState()
|
||||
const containerRef = useRef<HTMLDivElement>(null)
|
||||
const widgetIdRef = useRef<string | null>(null)
|
||||
const onTokenChangeRef = useRef(onTokenChange)
|
||||
const [widgetState, setWidgetState] = useState<TurnstileWidgetState>('loading')
|
||||
|
||||
useEffect(() => {
|
||||
onTokenChangeRef.current = onTokenChange
|
||||
}, [onTokenChange])
|
||||
|
||||
const clearToken = useCallback((state: TurnstileWidgetState) => {
|
||||
onTokenChangeRef.current(null)
|
||||
setWidgetState(state)
|
||||
}, [])
|
||||
|
||||
const reset = useCallback(() => {
|
||||
clearToken('ready')
|
||||
const widgetId = widgetIdRef.current
|
||||
if (!widgetId || !window.turnstile) return
|
||||
|
||||
try {
|
||||
window.turnstile.reset(widgetId)
|
||||
} catch {
|
||||
clearToken('error')
|
||||
}
|
||||
}, [clearToken])
|
||||
|
||||
useImperativeHandle(ref, () => ({ reset }), [reset])
|
||||
|
||||
const renderWidget = useCallback(() => {
|
||||
if (!siteKey || !containerRef.current || !window.turnstile) return
|
||||
if (widgetIdRef.current) return
|
||||
|
||||
try {
|
||||
setWidgetState('ready')
|
||||
const widgetId = window.turnstile.render(containerRef.current, {
|
||||
sitekey: siteKey,
|
||||
action,
|
||||
appearance: 'interaction-only',
|
||||
execution: 'render',
|
||||
size: 'compact',
|
||||
theme: 'auto',
|
||||
callback: (token) => {
|
||||
onTokenChangeRef.current(token)
|
||||
setWidgetState('verified')
|
||||
},
|
||||
'error-callback': () => clearToken('error'),
|
||||
'expired-callback': reset,
|
||||
'timeout-callback': reset,
|
||||
})
|
||||
if (!widgetId) {
|
||||
clearToken('error')
|
||||
return
|
||||
}
|
||||
widgetIdRef.current = widgetId
|
||||
} catch {
|
||||
clearToken('error')
|
||||
}
|
||||
}, [action, clearToken, reset, siteKey])
|
||||
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
const widgetId = widgetIdRef.current
|
||||
if (!widgetId || !window.turnstile) return
|
||||
try {
|
||||
window.turnstile.remove(widgetId)
|
||||
} catch {
|
||||
// The provider may already have removed an expired widget.
|
||||
}
|
||||
widgetIdRef.current = null
|
||||
}
|
||||
}, [])
|
||||
|
||||
if (!siteKey) {
|
||||
return (
|
||||
<span
|
||||
aria-hidden="true"
|
||||
className="hidden"
|
||||
data-turnstile-rollout-state={rolloutState}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
className="flex flex-col items-center gap-2"
|
||||
data-turnstile-rollout-state={rolloutState}
|
||||
data-turnstile-widget-state={widgetState}
|
||||
>
|
||||
<Script
|
||||
id="cloudflare-turnstile"
|
||||
src={TURNSTILE_SCRIPT_URL}
|
||||
strategy="afterInteractive"
|
||||
onReady={renderWidget}
|
||||
onError={() => clearToken('error')}
|
||||
/>
|
||||
<div ref={containerRef} />
|
||||
{(widgetState === 'loading' || widgetState === 'ready') && (
|
||||
<p className="sr-only" role="status">
|
||||
{t('turnstile_checking')}
|
||||
</p>
|
||||
)}
|
||||
{widgetState === 'error' && (
|
||||
<p className="text-center text-xs text-destructive" role="alert">
|
||||
{t('turnstile_error')}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
})
|
||||
Reference in New Issue
Block a user