Skip to content
Closed
Show file tree
Hide file tree
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 Feb 6, 2026
0bd6280
fix: resolve 5 integration system bugs (audit log, OAuth callback, dr…
2witstudios Feb 6, 2026
c9d91e2
fix: guard drive integration resolution against non-member access
2witstudios Feb 6, 2026
acc834c
Merge remote-tracking branch 'origin/master' into api
2witstudios Feb 6, 2026
bbcd967
chore: re-generate migration 0073 for nullable audit log driveId afte…
2witstudios Feb 6, 2026
2c9a543
fix: resolve 5 integration system bugs (audit log, OAuth callback, dr…
2witstudios Feb 6, 2026
c300ea0
fix: address all CodeRabbit review findings across integration system
2witstudios Feb 6, 2026
1ecb94e
Merge remote-tracking branch 'origin/master' into api
2witstudios Feb 13, 2026
cff9ab6
Merge remote-tracking branch 'origin/master' into api
2witstudios Feb 13, 2026
065e06a
Merge remote-tracking branch 'origin/master' into api
2witstudios Feb 13, 2026
0d457d1
feat: implement passwordless magic link authentication
2witstudios Feb 13, 2026
a584832
fix: set emailVerified in test setup for existing user
2witstudios Feb 13, 2026
2e70342
fix: address CodeRabbit security review for magic link auth
2witstudios Feb 13, 2026
404ccbb
fix: address remaining CodeRabbit security review items
2witstudios Feb 13, 2026
38b279f
Merge remote-tracking branch 'origin/master' into feat/magic-link-auth
2witstudios Feb 13, 2026
ee81535
feat: implement WebAuthn/Passkey authentication
2witstudios Feb 13, 2026
72ba048
fix: resolve TypeScript error in passkey-service.test.ts
2witstudios Feb 13, 2026
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
1 change: 1 addition & 0 deletions apps/web/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@
"@radix-ui/react-toggle": "^1.1.10",
"@radix-ui/react-tooltip": "^1.2.8",
"@radix-ui/react-use-controllable-state": "^1.2.2",
"@simplewebauthn/browser": "^13.2.2",
"@stripe/react-stripe-js": "^5.4.1",
"@stripe/stripe-js": "^8.5.3",
"@tanstack/react-virtual": "^3.13.18",
Expand Down
204 changes: 204 additions & 0 deletions apps/web/src/app/api/auth/passkey/[passkeyId]/route.ts
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 apps/web/src/app/api/auth/passkey/authenticate/options/route.ts
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 }
);
}
Comment on lines +45 to +54

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

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 outer catch block returns a generic 500. Consider catching the parse error separately to return a 400.

Proposed fix
     // Parse and validate request body
-    const body = await req.json();
+    let body: unknown;
+    try {
+      body = await req.json();
+    } catch {
+      return NextResponse.json(
+        { error: 'Invalid JSON body' },
+        { status: 400 }
+      );
+    }
     const validation = optionsSchema.safeParse(body);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// 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 }
);
}
// Parse and validate request body
let body: unknown;
try {
body = await req.json();
} catch {
return NextResponse.json(
{ error: 'Invalid JSON body' },
{ status: 400 }
);
}
const validation = optionsSchema.safeParse(body);
if (!validation.success) {
return NextResponse.json(
{ error: 'Invalid request body', details: validation.error.issues },
{ status: 400 }
);
}
🤖 Prompt for AI Agents
In `@apps/web/src/app/api/auth/passkey/authenticate/options/route.ts` around lines
45 - 54, The code currently calls req.json() which can throw on malformed JSON
and bubble up to the outer catch producing a 500; change the flow in the route
handler to catch parse errors separately: wrap the await req.json() in a
try/catch (or use a safe JSON parse helper) and if parsing fails return
NextResponse.json({ error: 'Invalid JSON' }, { status: 400 }) before running
optionsSchema.safeParse; keep the subsequent Zod validation using optionsSchema
and return the existing 400 with validation.error.issues when safeParse fails so
malformed JSON yields 400 instead of 500.


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 }
);
}
}
Loading
Loading