Repository navigation
feat: implement WebAuthn/Passkey authentication #680
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
Closed
Closed
Changes from all commits
Commits
Show all changes
17 commits
Select commit
Hold shift + click to select a range
37f9b42
feat: add third-party integration system with OAuth, tool resolution,…
2witstudios 0bd6280
fix: resolve 5 integration system bugs (audit log, OAuth callback, dr…
2witstudios c9d91e2
fix: guard drive integration resolution against non-member access
2witstudios acc834c
Merge remote-tracking branch 'origin/master' into api
2witstudios bbcd967
chore: re-generate migration 0073 for nullable audit log driveId afte…
2witstudios 2c9a543
fix: resolve 5 integration system bugs (audit log, OAuth callback, dr…
2witstudios c300ea0
fix: address all CodeRabbit review findings across integration system
2witstudios 1ecb94e
Merge remote-tracking branch 'origin/master' into api
2witstudios cff9ab6
Merge remote-tracking branch 'origin/master' into api
2witstudios 065e06a
Merge remote-tracking branch 'origin/master' into api
2witstudios 0d457d1
feat: implement passwordless magic link authentication
2witstudios a584832
fix: set emailVerified in test setup for existing user
2witstudios 2e70342
fix: address CodeRabbit security review for magic link auth
2witstudios 404ccbb
fix: address remaining CodeRabbit security review items
2witstudios 38b279f
Merge remote-tracking branch 'origin/master' into feat/magic-link-auth
2witstudios ee81535
feat: implement WebAuthn/Passkey authentication
2witstudios 72ba048
fix: resolve TypeScript error in passkey-service.test.ts
2witstudios File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,204 @@ | ||
| import { NextResponse } from 'next/server'; | ||
| import { z } from 'zod/v4'; | ||
| import { deletePasskey, updatePasskeyName, validateCSRFToken } from '@pagespace/lib/auth'; | ||
| import { loggers } from '@pagespace/lib/server'; | ||
| import { trackAuthEvent } from '@pagespace/lib/activity-tracker'; | ||
| import { | ||
| authenticateSessionRequest, | ||
| isAuthError, | ||
| isSessionAuthResult, | ||
| getClientIP, | ||
| } from '@/lib/auth'; | ||
|
|
||
| const updateNameSchema = z.object({ | ||
| name: z.string().min(1).max(255), | ||
| }); | ||
|
|
||
| /** | ||
| * DELETE /api/auth/passkey/[passkeyId] | ||
| * | ||
| * Delete a passkey owned by the authenticated user. | ||
| * Requires session authentication and CSRF token. | ||
| */ | ||
| export async function DELETE( | ||
| req: Request, | ||
| context: { params: Promise<{ passkeyId: string }> } | ||
| ) { | ||
| try { | ||
| const { passkeyId } = await context.params; | ||
| const clientIP = getClientIP(req); | ||
|
|
||
| // Verify session auth | ||
| const authResult = await authenticateSessionRequest(req); | ||
| if (isAuthError(authResult)) { | ||
| return authResult.error; | ||
| } | ||
|
|
||
| const userId = authResult.userId; | ||
| const sessionId = isSessionAuthResult(authResult) ? authResult.sessionId : null; | ||
|
|
||
| // Verify CSRF token (skip for Bearer token auth - not vulnerable to CSRF) | ||
| const hasBearerAuth = !!req.headers.get('authorization'); | ||
| if (!hasBearerAuth && sessionId) { | ||
| const csrfToken = req.headers.get('x-csrf-token'); | ||
| if (!csrfToken || !validateCSRFToken(csrfToken, sessionId)) { | ||
| loggers.auth.warn('CSRF validation failed for passkey deletion', { | ||
| userId, | ||
| passkeyId, | ||
| ip: clientIP, | ||
| }); | ||
| return NextResponse.json( | ||
| { error: 'Invalid CSRF token' }, | ||
| { status: 403 } | ||
| ); | ||
| } | ||
| } | ||
|
|
||
| // Delete passkey | ||
| const result = await deletePasskey({ userId, passkeyId }); | ||
|
|
||
| if (!result.ok) { | ||
| if (result.error.code === 'PASSKEY_NOT_FOUND') { | ||
| return NextResponse.json( | ||
| { error: 'Passkey not found' }, | ||
| { status: 404 } | ||
| ); | ||
| } | ||
|
|
||
| loggers.auth.warn('Failed to delete passkey', { | ||
| userId, | ||
| passkeyId, | ||
| error: result.error.code, | ||
| ip: clientIP, | ||
| }); | ||
|
|
||
| return NextResponse.json( | ||
| { error: 'Failed to delete passkey' }, | ||
| { status: 500 } | ||
| ); | ||
| } | ||
|
|
||
| // Track passkey deletion | ||
| trackAuthEvent(userId, 'passkey_deleted', { | ||
| ip: clientIP, | ||
| passkeyId, | ||
| userAgent: req.headers.get('user-agent'), | ||
| }); | ||
|
|
||
| loggers.auth.info('Passkey deleted', { | ||
| userId, | ||
| passkeyId, | ||
| ip: clientIP, | ||
| }); | ||
|
|
||
| return NextResponse.json({ success: true }); | ||
|
|
||
| } catch (error) { | ||
| loggers.auth.error('Delete passkey error', error as Error); | ||
| return NextResponse.json( | ||
| { error: 'Internal server error' }, | ||
| { status: 500 } | ||
| ); | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * PATCH /api/auth/passkey/[passkeyId] | ||
| * | ||
| * Update passkey name. | ||
| * Requires session authentication and CSRF token. | ||
| */ | ||
| export async function PATCH( | ||
| req: Request, | ||
| context: { params: Promise<{ passkeyId: string }> } | ||
| ) { | ||
| try { | ||
| const { passkeyId } = await context.params; | ||
| const clientIP = getClientIP(req); | ||
|
|
||
| // Verify session auth | ||
| const authResult = await authenticateSessionRequest(req); | ||
| if (isAuthError(authResult)) { | ||
| return authResult.error; | ||
| } | ||
|
|
||
| const userId = authResult.userId; | ||
| const sessionId = isSessionAuthResult(authResult) ? authResult.sessionId : null; | ||
|
|
||
| // Verify CSRF token (skip for Bearer token auth - not vulnerable to CSRF) | ||
| const hasBearerAuth = !!req.headers.get('authorization'); | ||
| if (!hasBearerAuth && sessionId) { | ||
| const csrfToken = req.headers.get('x-csrf-token'); | ||
| if (!csrfToken || !validateCSRFToken(csrfToken, sessionId)) { | ||
| loggers.auth.warn('CSRF validation failed for passkey update', { | ||
| userId, | ||
| passkeyId, | ||
| ip: clientIP, | ||
| }); | ||
| return NextResponse.json( | ||
| { error: 'Invalid CSRF token' }, | ||
| { status: 403 } | ||
| ); | ||
| } | ||
| } | ||
|
|
||
| // Parse and validate request body | ||
| const body = await req.json(); | ||
| const validation = updateNameSchema.safeParse(body); | ||
|
|
||
| if (!validation.success) { | ||
| return NextResponse.json( | ||
| { error: 'Invalid request body', details: validation.error.issues }, | ||
| { status: 400 } | ||
| ); | ||
| } | ||
|
|
||
| const { name } = validation.data; | ||
|
|
||
| // Update passkey name | ||
| const result = await updatePasskeyName({ userId, passkeyId, name }); | ||
|
|
||
| if (!result.ok) { | ||
| if (result.error.code === 'PASSKEY_NOT_FOUND') { | ||
| return NextResponse.json( | ||
| { error: 'Passkey not found' }, | ||
| { status: 404 } | ||
| ); | ||
| } | ||
|
|
||
| if (result.error.code === 'VALIDATION_FAILED') { | ||
| return NextResponse.json( | ||
| { error: 'Invalid name' }, | ||
| { status: 400 } | ||
| ); | ||
| } | ||
|
|
||
| loggers.auth.warn('Failed to update passkey name', { | ||
| userId, | ||
| passkeyId, | ||
| error: result.error.code, | ||
| ip: clientIP, | ||
| }); | ||
|
|
||
| return NextResponse.json( | ||
| { error: 'Failed to update passkey' }, | ||
| { status: 500 } | ||
| ); | ||
| } | ||
|
|
||
| loggers.auth.info('Passkey renamed', { | ||
| userId, | ||
| passkeyId, | ||
| ip: clientIP, | ||
| }); | ||
|
|
||
| return NextResponse.json({ success: true }); | ||
|
|
||
| } catch (error) { | ||
| loggers.auth.error('Update passkey error', error as Error); | ||
| return NextResponse.json( | ||
| { error: 'Internal server error' }, | ||
| { status: 500 } | ||
| ); | ||
| } | ||
| } |
102 changes: 102 additions & 0 deletions
102
apps/web/src/app/api/auth/passkey/authenticate/options/route.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,102 @@ | ||
| import { NextResponse } from 'next/server'; | ||
| import { z } from 'zod/v4'; | ||
| import { generateAuthenticationOptions } from '@pagespace/lib/auth'; | ||
| import { loggers } from '@pagespace/lib/server'; | ||
| import { | ||
| checkDistributedRateLimit, | ||
| DISTRIBUTED_RATE_LIMITS, | ||
| } from '@pagespace/lib/security'; | ||
| import { validateLoginCSRFToken, getClientIP } from '@/lib/auth'; | ||
|
|
||
| const optionsSchema = z.object({ | ||
| email: z.string().email().optional(), | ||
| csrfToken: z.string().min(1), | ||
| }); | ||
|
|
||
| /** | ||
| * POST /api/auth/passkey/authenticate/options | ||
| * | ||
| * Generate WebAuthn authentication options for passkey login. | ||
| * Public endpoint (unauthenticated) - requires login CSRF token. | ||
| * Email is optional - if provided, filters allowCredentials to that user's passkeys. | ||
| */ | ||
| export async function POST(req: Request) { | ||
| try { | ||
| const clientIP = getClientIP(req); | ||
|
|
||
| // Rate limiting by IP | ||
| const rateLimitKey = `passkey_auth:${clientIP}`; | ||
| const rateLimitResult = await checkDistributedRateLimit( | ||
| rateLimitKey, | ||
| DISTRIBUTED_RATE_LIMITS.PASSKEY_AUTH | ||
| ); | ||
|
|
||
| if (!rateLimitResult.allowed) { | ||
| loggers.auth.warn('Passkey auth options rate limited', { | ||
| ip: clientIP, | ||
| retryAfter: rateLimitResult.retryAfter, | ||
| }); | ||
| return NextResponse.json( | ||
| { error: 'Too many requests', retryAfter: rateLimitResult.retryAfter }, | ||
| { status: 429 } | ||
| ); | ||
| } | ||
|
|
||
| // Parse and validate request body | ||
| const body = await req.json(); | ||
| const validation = optionsSchema.safeParse(body); | ||
|
|
||
| if (!validation.success) { | ||
| return NextResponse.json( | ||
| { error: 'Invalid request body', details: validation.error.issues }, | ||
| { status: 400 } | ||
| ); | ||
| } | ||
|
|
||
| const { email, csrfToken } = validation.data; | ||
|
|
||
| // Verify login CSRF token | ||
| if (!validateLoginCSRFToken(csrfToken)) { | ||
| loggers.auth.warn('Login CSRF validation failed for passkey auth', { | ||
| ip: clientIP, | ||
| email: email ? email.substring(0, 3) + '***' : undefined, | ||
| }); | ||
| return NextResponse.json( | ||
| { error: 'Invalid CSRF token' }, | ||
| { status: 403 } | ||
| ); | ||
| } | ||
|
|
||
| // Generate authentication options | ||
| const result = await generateAuthenticationOptions({ email }); | ||
|
|
||
| if (!result.ok) { | ||
| loggers.auth.warn('Passkey auth options failed', { | ||
| error: result.error.code, | ||
| ip: clientIP, | ||
| }); | ||
|
|
||
| return NextResponse.json( | ||
| { error: 'Failed to generate options' }, | ||
| { status: 500 } | ||
| ); | ||
| } | ||
|
|
||
| loggers.auth.info('Passkey auth options generated', { | ||
| ip: clientIP, | ||
| hasEmail: !!email, | ||
| }); | ||
|
|
||
| return NextResponse.json({ | ||
| options: result.data.options, | ||
| challengeId: result.data.challengeId, | ||
| }); | ||
|
|
||
| } catch (error) { | ||
| loggers.auth.error('Passkey auth options error', error as Error); | ||
| return NextResponse.json( | ||
| { error: 'Internal server error' }, | ||
| { status: 500 } | ||
| ); | ||
| } | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
req.json()can throw on malformed JSON, returning 500 instead of 400.If the request body is not valid JSON,
req.json()throws before Zod validation runs. The outercatchblock returns a generic 500. Consider catching the parse error separately to return a 400.Proposed fix
📝 Committable suggestion
🤖 Prompt for AI Agents