fix: harden auth, cron secrets, and provider flows (GNU-17) (#148)
- Replace === with crypto.timingSafeEqual in all 7 cron routes via shared lib/auth/cron.ts - Add in-memory rate limiting (60 req/min) and expires_at support to calendar feed - Add exponential backoff on MFA verify after 3 failed attempts - Add 60s cooldown on password reset requests - Validate bank callback auth code format before API call - Redact session IDs from bank sync and callback logs - Validate OAuth redirect_uris against allowlist (claude.ai, claude.com, localhost) - Remove excessive PII/debug console logging from login page Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
+22
-64
@@ -1,6 +1,6 @@
|
||||
'use client'
|
||||
|
||||
import { useState } from 'react'
|
||||
import { useState, useEffect } from 'react'
|
||||
import { useRouter } from 'next/navigation'
|
||||
import Link from 'next/link'
|
||||
import { createClient } from '@/lib/supabase/client'
|
||||
@@ -18,10 +18,25 @@ export default function LoginPage() {
|
||||
const [isLoading, setIsLoading] = useState(false)
|
||||
const [isEmailSent, setIsEmailSent] = useState(false)
|
||||
const [showResetPassword, setShowResetPassword] = useState(false)
|
||||
const [resetCooldownUntil, setResetCooldownUntil] = useState<number | null>(null)
|
||||
const [resetCooldownRemaining, setResetCooldownRemaining] = useState(0)
|
||||
const { toast } = useToast()
|
||||
const router = useRouter()
|
||||
const supabase = createClient()
|
||||
|
||||
// Reset cooldown timer
|
||||
useEffect(() => {
|
||||
if (!resetCooldownUntil) return
|
||||
const tick = () => {
|
||||
const remaining = Math.max(0, Math.ceil((resetCooldownUntil - Date.now()) / 1000))
|
||||
setResetCooldownRemaining(remaining)
|
||||
if (remaining <= 0) setResetCooldownUntil(null)
|
||||
}
|
||||
tick()
|
||||
const interval = setInterval(tick, 1000)
|
||||
return () => clearInterval(interval)
|
||||
}, [resetCooldownUntil])
|
||||
|
||||
const handlePasswordLogin = async (e: React.FormEvent<HTMLFormElement>) => {
|
||||
e.preventDefault()
|
||||
setIsLoading(true)
|
||||
@@ -31,27 +46,12 @@ export default function LoginPage() {
|
||||
const passwordValue = (formData.get('password') as string) || password
|
||||
|
||||
try {
|
||||
console.log('[login] attempting signInWithPassword', {
|
||||
email: emailValue,
|
||||
hasPassword: !!passwordValue,
|
||||
supabaseUrl: process.env.NEXT_PUBLIC_SUPABASE_URL,
|
||||
})
|
||||
|
||||
const { data, error } = await supabase.auth.signInWithPassword({
|
||||
const { error } = await supabase.auth.signInWithPassword({
|
||||
email: emailValue,
|
||||
password: passwordValue,
|
||||
})
|
||||
|
||||
if (error) {
|
||||
console.error('[login] signInWithPassword error', {
|
||||
message: error.message,
|
||||
code: error.code,
|
||||
status: error.status,
|
||||
name: error.name,
|
||||
stack: error.stack,
|
||||
cause: error.cause,
|
||||
fullError: JSON.stringify(error, Object.getOwnPropertyNames(error)),
|
||||
})
|
||||
toast({
|
||||
title: 'Inloggning misslyckades',
|
||||
description: error.message === 'Invalid login credentials'
|
||||
@@ -62,24 +62,8 @@ export default function LoginPage() {
|
||||
return
|
||||
}
|
||||
|
||||
console.log('[login] signInWithPassword success', {
|
||||
userId: data.user?.id,
|
||||
email: data.user?.email,
|
||||
hasSession: !!data.session,
|
||||
provider: data.user?.app_metadata?.provider,
|
||||
})
|
||||
|
||||
// Check MFA status
|
||||
const { data: aal, error: mfaError } = await supabase.auth.mfa.getAuthenticatorAssuranceLevel()
|
||||
if (mfaError) {
|
||||
console.error('[login] MFA check error', {
|
||||
message: mfaError.message,
|
||||
code: mfaError.code,
|
||||
status: mfaError.status,
|
||||
fullError: JSON.stringify(mfaError, Object.getOwnPropertyNames(mfaError)),
|
||||
})
|
||||
}
|
||||
console.log('[login] MFA status', { currentLevel: aal?.currentLevel, nextLevel: aal?.nextLevel })
|
||||
const { data: aal } = await supabase.auth.mfa.getAuthenticatorAssuranceLevel()
|
||||
|
||||
if (aal?.nextLevel === 'aal2' && aal?.currentLevel === 'aal1') {
|
||||
router.push('/mfa/verify')
|
||||
@@ -89,13 +73,6 @@ export default function LoginPage() {
|
||||
router.push('/')
|
||||
router.refresh()
|
||||
} catch (error) {
|
||||
console.error('[login] unexpected exception', {
|
||||
error,
|
||||
message: error instanceof Error ? error.message : String(error),
|
||||
stack: error instanceof Error ? error.stack : undefined,
|
||||
type: typeof error,
|
||||
constructor: error?.constructor?.name,
|
||||
})
|
||||
toast({
|
||||
title: 'Inloggning misslyckades',
|
||||
description: getErrorMessage(error, { context: 'auth' }),
|
||||
@@ -114,25 +91,11 @@ export default function LoginPage() {
|
||||
const emailValue = (formData.get('email') as string) || email
|
||||
|
||||
try {
|
||||
console.log('[login] attempting resetPasswordForEmail', {
|
||||
email: emailValue,
|
||||
redirectTo: `${window.location.origin}/auth/callback?next=/reset-password`,
|
||||
})
|
||||
|
||||
const { error } = await supabase.auth.resetPasswordForEmail(emailValue, {
|
||||
redirectTo: `${window.location.origin}/auth/callback?next=/reset-password`,
|
||||
})
|
||||
|
||||
if (error) {
|
||||
console.error('[login] resetPasswordForEmail error', {
|
||||
message: error.message,
|
||||
code: error.code,
|
||||
status: error.status,
|
||||
name: error.name,
|
||||
stack: error.stack,
|
||||
cause: error.cause,
|
||||
fullError: JSON.stringify(error, Object.getOwnPropertyNames(error)),
|
||||
})
|
||||
toast({
|
||||
title: 'Kunde inte skicka återställningslänk',
|
||||
description: getErrorMessage(error, { context: 'auth' }),
|
||||
@@ -141,21 +104,14 @@ export default function LoginPage() {
|
||||
return
|
||||
}
|
||||
|
||||
console.log('[login] resetPasswordForEmail success', { email: emailValue })
|
||||
setEmail(emailValue)
|
||||
setResetCooldownUntil(Date.now() + 60_000)
|
||||
setIsEmailSent(true)
|
||||
toast({
|
||||
title: 'Återställningslänk skickad!',
|
||||
description: 'Kolla din inkorg för att återställa lösenordet.',
|
||||
})
|
||||
} catch (error) {
|
||||
console.error('[login] resetPasswordForEmail unexpected exception', {
|
||||
error,
|
||||
message: error instanceof Error ? error.message : String(error),
|
||||
stack: error instanceof Error ? error.stack : undefined,
|
||||
type: typeof error,
|
||||
constructor: error?.constructor?.name,
|
||||
})
|
||||
toast({
|
||||
title: 'Kunde inte skicka återställningslänk',
|
||||
description: getErrorMessage(error, { context: 'auth' }),
|
||||
@@ -242,12 +198,14 @@ export default function LoginPage() {
|
||||
className="h-11"
|
||||
/>
|
||||
</div>
|
||||
<Button type="submit" className="w-full h-11" disabled={isLoading}>
|
||||
<Button type="submit" className="w-full h-11" disabled={isLoading || !!resetCooldownUntil}>
|
||||
{isLoading ? (
|
||||
<>
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||
Skickar...
|
||||
</>
|
||||
) : resetCooldownUntil ? (
|
||||
`Vänta ${resetCooldownRemaining}s`
|
||||
) : (
|
||||
'Skicka återställningslänk'
|
||||
)}
|
||||
|
||||
@@ -14,6 +14,9 @@ export default function MfaVerifyPage() {
|
||||
const [code, setCode] = useState('')
|
||||
const [isLoading, setIsLoading] = useState(false)
|
||||
const [factorId, setFactorId] = useState<string | null>(null)
|
||||
const [failedAttempts, setFailedAttempts] = useState(0)
|
||||
const [lockoutUntil, setLockoutUntil] = useState<number | null>(null)
|
||||
const [lockoutRemaining, setLockoutRemaining] = useState(0)
|
||||
const inputRef = useRef<HTMLInputElement>(null)
|
||||
const { toast } = useToast()
|
||||
const router = useRouter()
|
||||
@@ -35,6 +38,19 @@ export default function MfaVerifyPage() {
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [])
|
||||
|
||||
// Lockout countdown timer
|
||||
useEffect(() => {
|
||||
if (!lockoutUntil) return
|
||||
const tick = () => {
|
||||
const remaining = Math.max(0, Math.ceil((lockoutUntil - Date.now()) / 1000))
|
||||
setLockoutRemaining(remaining)
|
||||
if (remaining <= 0) setLockoutUntil(null)
|
||||
}
|
||||
tick()
|
||||
const interval = setInterval(tick, 1000)
|
||||
return () => clearInterval(interval)
|
||||
}, [lockoutUntil])
|
||||
|
||||
const handleVerify = async (e: React.FormEvent<HTMLFormElement>) => {
|
||||
e.preventDefault()
|
||||
if (!factorId || code.length !== 6) return
|
||||
@@ -63,6 +79,16 @@ export default function MfaVerifyPage() {
|
||||
})
|
||||
|
||||
if (verifyError) {
|
||||
const attempts = failedAttempts + 1
|
||||
setFailedAttempts(attempts)
|
||||
|
||||
// Exponential backoff after 3 failed attempts: 5s, 15s, 30s
|
||||
if (attempts >= 3) {
|
||||
const delays = [5_000, 15_000, 30_000]
|
||||
const delay = delays[Math.min(attempts - 3, delays.length - 1)]
|
||||
setLockoutUntil(Date.now() + delay)
|
||||
}
|
||||
|
||||
toast({
|
||||
title: 'Fel kod',
|
||||
description: 'Kontrollera koden och försök igen.',
|
||||
@@ -130,13 +156,15 @@ export default function MfaVerifyPage() {
|
||||
<Button
|
||||
type="submit"
|
||||
className="w-full h-11"
|
||||
disabled={isLoading || code.length !== 6}
|
||||
disabled={isLoading || code.length !== 6 || !!lockoutUntil}
|
||||
>
|
||||
{isLoading ? (
|
||||
<>
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||
Verifierar...
|
||||
</>
|
||||
) : lockoutUntil ? (
|
||||
`Vänta ${lockoutRemaining}s`
|
||||
) : (
|
||||
'Verifiera'
|
||||
)}
|
||||
|
||||
@@ -1,16 +1,13 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { extensionRegistry } from '@/lib/extensions/registry'
|
||||
import { ensureInitialized } from '@/lib/init'
|
||||
import { verifyCronSecret } from '@/lib/auth/cron'
|
||||
|
||||
ensureInitialized()
|
||||
|
||||
export async function POST(request: Request) {
|
||||
const authHeader = request.headers.get('authorization')
|
||||
const cronSecret = process.env.CRON_SECRET
|
||||
|
||||
if (!cronSecret || authHeader !== `Bearer ${cronSecret}`) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
const authError = verifyCronSecret(request)
|
||||
if (authError) return authError
|
||||
|
||||
const aiExt = extensionRegistry.get('ai-categorization')
|
||||
if (!aiExt?.services?.seedAllTemplateEmbeddings || !aiExt?.services?.getSchemaVersion) {
|
||||
|
||||
@@ -2,6 +2,22 @@ import { createClient } from '@supabase/supabase-js'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { generateCalendarFeed } from '@/lib/calendar/ics-generator'
|
||||
|
||||
// In-memory rate limiting: token -> { count, resetAt }
|
||||
const rateLimitMap = new Map<string, { count: number; resetAt: number }>()
|
||||
const RATE_LIMIT_WINDOW_MS = 60_000 // 1 minute
|
||||
const RATE_LIMIT_MAX = 60 // 60 requests per minute per token
|
||||
|
||||
// Periodic cleanup to prevent memory leaks (every 5 minutes)
|
||||
let lastCleanup = Date.now()
|
||||
function cleanupRateLimitMap() {
|
||||
const now = Date.now()
|
||||
if (now - lastCleanup < 5 * 60_000) return
|
||||
lastCleanup = now
|
||||
for (const [key, value] of rateLimitMap) {
|
||||
if (now > value.resetAt) rateLimitMap.delete(key)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* GET /api/calendar/feed/[token]
|
||||
* Returns an ICS calendar feed for the given token
|
||||
@@ -19,6 +35,19 @@ export async function GET(
|
||||
return new NextResponse('Invalid token', { status: 400 })
|
||||
}
|
||||
|
||||
// Rate limiting per token
|
||||
cleanupRateLimitMap()
|
||||
const nowMs = Date.now()
|
||||
const rateEntry = rateLimitMap.get(token)
|
||||
if (rateEntry && nowMs < rateEntry.resetAt) {
|
||||
if (rateEntry.count >= RATE_LIMIT_MAX) {
|
||||
return new NextResponse('Too many requests', { status: 429 })
|
||||
}
|
||||
rateEntry.count++
|
||||
} else {
|
||||
rateLimitMap.set(token, { count: 1, resetAt: nowMs + RATE_LIMIT_WINDOW_MS })
|
||||
}
|
||||
|
||||
// Create service client (no user auth required)
|
||||
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL
|
||||
const supabaseServiceKey = process.env.SUPABASE_SERVICE_ROLE_KEY
|
||||
@@ -41,6 +70,11 @@ export async function GET(
|
||||
return new NextResponse('Feed not found or inactive', { status: 404 })
|
||||
}
|
||||
|
||||
// Check token expiry
|
||||
if (feed.expires_at && new Date(feed.expires_at) < new Date()) {
|
||||
return new NextResponse('Feed token has expired', { status: 410 })
|
||||
}
|
||||
|
||||
// Update access tracking
|
||||
await supabase
|
||||
.from('calendar_feeds')
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { createClient } from '@supabase/supabase-js'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { updateDeadlineStatuses } from '@/lib/deadlines/status-engine'
|
||||
import { verifyCronSecret } from '@/lib/auth/cron'
|
||||
|
||||
/**
|
||||
* GET /api/deadlines/status/cron
|
||||
@@ -10,13 +11,8 @@ import { updateDeadlineStatuses } from '@/lib/deadlines/status-engine'
|
||||
* Vercel Cron: "0 6 * * *"
|
||||
*/
|
||||
export async function GET(request: Request) {
|
||||
// Verify cron secret for security
|
||||
const authHeader = request.headers.get('authorization')
|
||||
const cronSecret = process.env.CRON_SECRET
|
||||
|
||||
if (!cronSecret || authHeader !== `Bearer ${cronSecret}`) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
const authError = verifyCronSecret(request)
|
||||
if (authError) return authError
|
||||
|
||||
// Create a service role client for accessing all user data
|
||||
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { createClient } from '@supabase/supabase-js'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { verifyCronSecret } from '@/lib/auth/cron'
|
||||
|
||||
/**
|
||||
* GET /api/documents/verify/cron
|
||||
@@ -12,13 +13,8 @@ import { NextResponse } from 'next/server'
|
||||
* Uses service role for cross-user verification (RLS bypass).
|
||||
*/
|
||||
export async function GET(request: Request) {
|
||||
// Verify cron secret
|
||||
const authHeader = request.headers.get('authorization')
|
||||
const cronSecret = process.env.CRON_SECRET
|
||||
|
||||
if (!cronSecret || authHeader !== `Bearer ${cronSecret}`) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
const authError = verifyCronSecret(request)
|
||||
if (authError) return authError
|
||||
|
||||
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL
|
||||
const supabaseServiceKey = process.env.SUPABASE_SERVICE_ROLE_KEY
|
||||
|
||||
@@ -69,6 +69,12 @@ export async function GET(request: Request) {
|
||||
return NextResponse.redirect(`${baseUrl}/settings?bank_error=missing_parameters`)
|
||||
}
|
||||
|
||||
// Validate authorization code format
|
||||
const codePattern = /^[a-zA-Z0-9._~+\/-]{8,2048}$/
|
||||
if (!codePattern.test(code)) {
|
||||
return NextResponse.redirect(`${baseUrl}/settings?bank_error=invalid_code_format`)
|
||||
}
|
||||
|
||||
const supabase = await createServiceClient()
|
||||
|
||||
try {
|
||||
@@ -105,7 +111,7 @@ export async function GET(request: Request) {
|
||||
|
||||
console.log('[enable-banking] Session created successfully', {
|
||||
connectionId: pendingConnection.id,
|
||||
sessionId: session_id,
|
||||
sessionId: '[REDACTED]',
|
||||
accountCount: accounts.length,
|
||||
consentExpiresAt,
|
||||
})
|
||||
@@ -150,7 +156,7 @@ export async function GET(request: Request) {
|
||||
console.error('[enable-banking] Failed to update connection after session creation', {
|
||||
connectionId: pendingConnection.id,
|
||||
updateError: { message: updateError.message, code: updateError.code, details: updateError.details },
|
||||
sessionId: session_id,
|
||||
sessionId: '[REDACTED]',
|
||||
})
|
||||
throw new Error(`Failed to update connection: ${updateError.message}`)
|
||||
}
|
||||
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
generateConsentExpiryEmailSubject,
|
||||
} from '@/lib/email/consent-notification-templates'
|
||||
import { ensureInitialized } from '@/lib/init'
|
||||
import { verifyCronSecret } from '@/lib/auth/cron'
|
||||
import type { StoredAccount } from '@/extensions/general/enable-banking/types'
|
||||
|
||||
ensureInitialized()
|
||||
@@ -24,13 +25,8 @@ ensureInitialized()
|
||||
* Deduplication via external_id makes repeated runs safe.
|
||||
*/
|
||||
export async function GET(request: Request) {
|
||||
// Verify cron secret
|
||||
const authHeader = request.headers.get('authorization')
|
||||
const cronSecret = process.env.CRON_SECRET
|
||||
|
||||
if (!cronSecret || authHeader !== `Bearer ${cronSecret}`) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
const authError = verifyCronSecret(request)
|
||||
if (authError) return authError
|
||||
|
||||
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL
|
||||
const supabaseServiceKey = process.env.SUPABASE_SERVICE_ROLE_KEY
|
||||
@@ -212,7 +208,7 @@ export async function GET(request: Request) {
|
||||
connectionId: connection.id,
|
||||
userId: connection.user_id,
|
||||
bankName: connection.bank_name,
|
||||
sessionId: connection.session_id,
|
||||
sessionId: '[REDACTED]',
|
||||
consentExpires: connection.consent_expires,
|
||||
lastSyncedAt: connection.last_synced_at,
|
||||
message,
|
||||
|
||||
@@ -1,34 +1,11 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { processOverdueReminders } from '@/lib/invoices/reminder-processor'
|
||||
import { getEmailService } from '@/lib/email/service'
|
||||
|
||||
// Verify cron secret for security
|
||||
function verifyCronSecret(request: Request): boolean {
|
||||
const authHeader = request.headers.get('authorization')
|
||||
const cronSecret = process.env.CRON_SECRET
|
||||
|
||||
if (!cronSecret) {
|
||||
console.error('CRON_SECRET not configured')
|
||||
return false
|
||||
}
|
||||
|
||||
if (!authHeader) {
|
||||
return false
|
||||
}
|
||||
|
||||
// Support both "Bearer <token>" and just "<token>" formats
|
||||
const token = authHeader.startsWith('Bearer ')
|
||||
? authHeader.substring(7)
|
||||
: authHeader
|
||||
|
||||
return token === cronSecret
|
||||
}
|
||||
import { verifyCronSecret } from '@/lib/auth/cron'
|
||||
|
||||
export async function GET(request: Request) {
|
||||
// Verify cron authentication
|
||||
if (!verifyCronSecret(request)) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
const authError = verifyCronSecret(request)
|
||||
if (authError) return authError
|
||||
|
||||
// Check if email service is configured
|
||||
if (!getEmailService().isConfigured()) {
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { POST } from '../route'
|
||||
|
||||
function createRequest(body: unknown) {
|
||||
return new Request('http://localhost/api/mcp-oauth/register', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(body),
|
||||
})
|
||||
}
|
||||
|
||||
describe('POST /api/mcp-oauth/register', () => {
|
||||
it('returns 400 for invalid JSON', async () => {
|
||||
const request = new Request('http://localhost/api/mcp-oauth/register', {
|
||||
method: 'POST',
|
||||
body: 'not json',
|
||||
})
|
||||
const response = await POST(request)
|
||||
expect(response.status).toBe(400)
|
||||
})
|
||||
|
||||
it('accepts registration with valid claude.ai redirect_uris', async () => {
|
||||
const response = await POST(createRequest({
|
||||
client_name: 'Test Client',
|
||||
redirect_uris: ['https://claude.ai/api/oauth/callback'],
|
||||
}))
|
||||
expect(response.status).toBe(201)
|
||||
const body = await response.json()
|
||||
expect(body.client_id).toBeDefined()
|
||||
expect(body.redirect_uris).toEqual(['https://claude.ai/api/oauth/callback'])
|
||||
})
|
||||
|
||||
it('accepts registration with localhost redirect_uris', async () => {
|
||||
const response = await POST(createRequest({
|
||||
redirect_uris: ['http://localhost:3000/callback'],
|
||||
}))
|
||||
expect(response.status).toBe(201)
|
||||
})
|
||||
|
||||
it('accepts registration with 127.0.0.1 redirect_uris', async () => {
|
||||
const response = await POST(createRequest({
|
||||
redirect_uris: ['http://127.0.0.1:8080/callback'],
|
||||
}))
|
||||
expect(response.status).toBe(201)
|
||||
})
|
||||
|
||||
it('accepts registration with claude.com redirect_uris', async () => {
|
||||
const response = await POST(createRequest({
|
||||
redirect_uris: ['https://claude.com/api/oauth/callback'],
|
||||
}))
|
||||
expect(response.status).toBe(201)
|
||||
})
|
||||
|
||||
it('rejects registration with disallowed redirect_uris', async () => {
|
||||
const response = await POST(createRequest({
|
||||
redirect_uris: ['https://evil.com/callback'],
|
||||
}))
|
||||
expect(response.status).toBe(400)
|
||||
const body = await response.json()
|
||||
expect(body.error).toBe('invalid_redirect_uri')
|
||||
})
|
||||
|
||||
it('rejects if any redirect_uri in array is invalid', async () => {
|
||||
const response = await POST(createRequest({
|
||||
redirect_uris: [
|
||||
'https://claude.ai/api/callback',
|
||||
'https://evil.com/steal',
|
||||
],
|
||||
}))
|
||||
expect(response.status).toBe(400)
|
||||
})
|
||||
|
||||
it('accepts registration with no redirect_uris', async () => {
|
||||
const response = await POST(createRequest({
|
||||
client_name: 'No URIs',
|
||||
}))
|
||||
expect(response.status).toBe(201)
|
||||
const body = await response.json()
|
||||
expect(body.redirect_uris).toEqual([])
|
||||
})
|
||||
|
||||
it('defaults client_name to MCP Client', async () => {
|
||||
const response = await POST(createRequest({}))
|
||||
expect(response.status).toBe(201)
|
||||
const body = await response.json()
|
||||
expect(body.client_name).toBe('MCP Client')
|
||||
})
|
||||
})
|
||||
@@ -1,10 +1,22 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import crypto from 'crypto'
|
||||
|
||||
// Allowed redirect URI patterns (must match CLAUDE.md allowlist)
|
||||
const ALLOWED_REDIRECT_PATTERNS = [
|
||||
/^https:\/\/claude\.ai\/api\//,
|
||||
/^https:\/\/claude\.com\/api\//,
|
||||
/^http:\/\/localhost(:\d+)?(\/|$)/,
|
||||
/^http:\/\/127\.0\.0\.1(:\d+)?(\/|$)/,
|
||||
]
|
||||
|
||||
function isRedirectUriAllowed(uri: string): boolean {
|
||||
return ALLOWED_REDIRECT_PATTERNS.some(pattern => pattern.test(uri))
|
||||
}
|
||||
|
||||
/**
|
||||
* RFC 7591 — Dynamic Client Registration.
|
||||
* Claude Desktop registers itself as an OAuth client before starting the auth flow.
|
||||
* We accept any registration and return a client_id.
|
||||
* Validates redirect_uris against the allowlist before accepting registration.
|
||||
*/
|
||||
export async function POST(request: Request) {
|
||||
let body: Record<string, unknown>
|
||||
@@ -14,12 +26,23 @@ export async function POST(request: Request) {
|
||||
return NextResponse.json({ error: 'invalid_request' }, { status: 400 })
|
||||
}
|
||||
|
||||
// Validate redirect_uris against allowlist
|
||||
const redirectUris = Array.isArray(body.redirect_uris) ? body.redirect_uris : []
|
||||
for (const uri of redirectUris) {
|
||||
if (typeof uri !== 'string' || !isRedirectUriAllowed(uri)) {
|
||||
return NextResponse.json(
|
||||
{ error: 'invalid_redirect_uri', error_description: `Redirect URI not allowed: ${uri}` },
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
const clientId = crypto.randomUUID()
|
||||
|
||||
return NextResponse.json({
|
||||
client_id: clientId,
|
||||
client_name: (body.client_name as string) || 'MCP Client',
|
||||
redirect_uris: body.redirect_uris || [],
|
||||
redirect_uris: redirectUris,
|
||||
grant_types: ['authorization_code'],
|
||||
response_types: ['code'],
|
||||
token_endpoint_auth_method: 'none',
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { createClient } from '@supabase/supabase-js'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { verifyCronSecret } from '@/lib/auth/cron'
|
||||
|
||||
/**
|
||||
* GET /api/sandbox/cleanup/cron
|
||||
@@ -7,12 +8,8 @@ import { NextResponse } from 'next/server'
|
||||
* Runs at 04:00 UTC every day.
|
||||
*/
|
||||
export async function GET(request: Request) {
|
||||
const authHeader = request.headers.get('authorization')
|
||||
const cronSecret = process.env.CRON_SECRET
|
||||
|
||||
if (!cronSecret || authHeader !== `Bearer ${cronSecret}`) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
const authError = verifyCronSecret(request)
|
||||
if (authError) return authError
|
||||
|
||||
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL
|
||||
const supabaseServiceKey = process.env.SUPABASE_SERVICE_ROLE_KEY
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { createClient } from '@supabase/supabase-js'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { generateNewYearDeadlines } from '@/lib/tax/deadline-generator'
|
||||
import { verifyCronSecret } from '@/lib/auth/cron'
|
||||
|
||||
/**
|
||||
* GET /api/tax-deadlines/cron
|
||||
@@ -10,13 +11,8 @@ import { generateNewYearDeadlines } from '@/lib/tax/deadline-generator'
|
||||
* Vercel Cron: "0 0 2 1 *" (midnight on January 2nd)
|
||||
*/
|
||||
export async function GET(request: Request) {
|
||||
// Verify cron secret for security
|
||||
const authHeader = request.headers.get('authorization')
|
||||
const cronSecret = process.env.CRON_SECRET
|
||||
|
||||
if (!cronSecret || authHeader !== `Bearer ${cronSecret}`) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
const authError = verifyCronSecret(request)
|
||||
if (authError) return authError
|
||||
|
||||
// Create a service role client for accessing all user data
|
||||
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest'
|
||||
import { verifyCronSecret } from '../cron'
|
||||
|
||||
describe('verifyCronSecret', () => {
|
||||
beforeEach(() => {
|
||||
vi.unstubAllEnvs()
|
||||
})
|
||||
|
||||
it('returns 401 when CRON_SECRET is not set', () => {
|
||||
vi.stubEnv('CRON_SECRET', '')
|
||||
const request = new Request('http://localhost/api/cron', {
|
||||
headers: { authorization: 'Bearer test-secret' },
|
||||
})
|
||||
const result = verifyCronSecret(request)
|
||||
expect(result).not.toBeNull()
|
||||
expect(result!.status).toBe(401)
|
||||
})
|
||||
|
||||
it('returns 401 when no authorization header is provided', () => {
|
||||
vi.stubEnv('CRON_SECRET', 'test-secret')
|
||||
const request = new Request('http://localhost/api/cron')
|
||||
const result = verifyCronSecret(request)
|
||||
expect(result).not.toBeNull()
|
||||
expect(result!.status).toBe(401)
|
||||
})
|
||||
|
||||
it('returns 401 when token does not match', () => {
|
||||
vi.stubEnv('CRON_SECRET', 'correct-secret')
|
||||
const request = new Request('http://localhost/api/cron', {
|
||||
headers: { authorization: 'Bearer wrong-secret' },
|
||||
})
|
||||
const result = verifyCronSecret(request)
|
||||
expect(result).not.toBeNull()
|
||||
expect(result!.status).toBe(401)
|
||||
})
|
||||
|
||||
it('returns null (authorized) when Bearer token matches', () => {
|
||||
vi.stubEnv('CRON_SECRET', 'correct-secret')
|
||||
const request = new Request('http://localhost/api/cron', {
|
||||
headers: { authorization: 'Bearer correct-secret' },
|
||||
})
|
||||
const result = verifyCronSecret(request)
|
||||
expect(result).toBeNull()
|
||||
})
|
||||
|
||||
it('returns null (authorized) when bare token matches', () => {
|
||||
vi.stubEnv('CRON_SECRET', 'correct-secret')
|
||||
const request = new Request('http://localhost/api/cron', {
|
||||
headers: { authorization: 'correct-secret' },
|
||||
})
|
||||
const result = verifyCronSecret(request)
|
||||
expect(result).toBeNull()
|
||||
})
|
||||
|
||||
it('handles tokens of different lengths safely', () => {
|
||||
vi.stubEnv('CRON_SECRET', 'short')
|
||||
const request = new Request('http://localhost/api/cron', {
|
||||
headers: { authorization: 'Bearer a-much-longer-token-that-differs-in-length' },
|
||||
})
|
||||
const result = verifyCronSecret(request)
|
||||
expect(result).not.toBeNull()
|
||||
expect(result!.status).toBe(401)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,32 @@
|
||||
import crypto from 'crypto'
|
||||
import { NextResponse } from 'next/server'
|
||||
|
||||
/**
|
||||
* Verify cron secret using constant-time comparison to prevent timing attacks.
|
||||
* Expects `Authorization: Bearer <CRON_SECRET>` header.
|
||||
*
|
||||
* Returns null if authorized, or a 401 NextResponse if not.
|
||||
*/
|
||||
export function verifyCronSecret(request: Request): NextResponse | null {
|
||||
const authHeader = request.headers.get('authorization')
|
||||
const cronSecret = process.env.CRON_SECRET
|
||||
|
||||
if (!cronSecret || !authHeader) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const token = authHeader.startsWith('Bearer ')
|
||||
? authHeader.substring(7)
|
||||
: authHeader
|
||||
|
||||
// Use timingSafeEqual to prevent timing-based secret extraction.
|
||||
// Encode both to buffers of equal length by hashing with SHA-256.
|
||||
const tokenHash = crypto.createHash('sha256').update(token).digest()
|
||||
const secretHash = crypto.createHash('sha256').update(cronSecret).digest()
|
||||
|
||||
if (!crypto.timingSafeEqual(tokenHash, secretHash)) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
-- Add optional expiry to calendar feed tokens
|
||||
-- Null = no expiry (preserves existing tokens)
|
||||
ALTER TABLE calendar_feeds
|
||||
ADD COLUMN IF NOT EXISTS expires_at TIMESTAMPTZ DEFAULT NULL;
|
||||
|
||||
COMMENT ON COLUMN calendar_feeds.expires_at IS 'Optional token expiry. Null means the token never expires.';
|
||||
Reference in New Issue
Block a user