fix: Complete OAuth DPoP implementation with working stores
Fixed multiple issues with the @atproto/oauth-client-node integration:
1. OAuth State Store:
- Changed from SQL WHERE queries to SurrealDB record IDs
- Use `oauth_state:⟨${key}⟩` pattern for direct lookups
- Fixes "Parse error: Unexpected token" issues
2. OAuth Session Store:
- Changed from SQL WHERE queries to SurrealDB record IDs
- Use `oauth_session:⟨${did}⟩` pattern for direct lookups
- Implement proper upsert logic with select + merge/create
3. OAuth Client Configuration:
- Use loopback pattern with metadata in client_id query params
- Format: `http://localhost/?redirect_uri=...&scope=atproto`
- Complies with ATproto OAuth localhost development mode
4. Auth Callback:
- Remove getProfile API call that requires additional scopes
- Use DID directly from session for user identification
- Simplify user creation in SurrealDB with record IDs
5. Login Page:
- Change from GET redirect to POST with JSON body
- Properly handle errors and display to user
The OAuth flow now works end-to-end:
- User enters handle → redirects to Bluesky OAuth
- User authorizes → callback exchanges code for tokens
- Session stored in SurrealDB → user redirected to /chat
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
@@ -51,19 +51,14 @@ export async function GET(request: NextRequest) {
|
||||
|
||||
console.log('[OAuth Callback] ✓ Successfully authenticated user:', session.did);
|
||||
|
||||
// Create ATproto agent with session
|
||||
const agent = new Agent(session);
|
||||
const did = session.did;
|
||||
|
||||
// Fetch user profile
|
||||
const profileResponse = await agent.getProfile({ actor: session.did });
|
||||
// For now, we'll use the DID as the handle placeholder
|
||||
// The actual handle will be fetched later when the user accesses protected routes
|
||||
// This avoids needing additional OAuth scopes during the callback
|
||||
const handle = did;
|
||||
|
||||
if (!profileResponse.success) {
|
||||
throw new Error('Failed to fetch user profile');
|
||||
}
|
||||
|
||||
const { did, handle } = profileResponse.data;
|
||||
|
||||
console.log('[OAuth Callback] User profile:', { did, handle });
|
||||
console.log('[OAuth Callback] User DID:', did);
|
||||
|
||||
// Upsert user in SurrealDB
|
||||
const db = new Surreal();
|
||||
@@ -77,12 +72,18 @@ export async function GET(request: NextRequest) {
|
||||
database: process.env.SURREALDB_DB!,
|
||||
});
|
||||
|
||||
await db.query(
|
||||
`INSERT INTO user (did, handle)
|
||||
VALUES ($did, $handle)
|
||||
ON DUPLICATE KEY UPDATE handle = $handle`,
|
||||
{ did, handle }
|
||||
);
|
||||
// Use UPSERT with record ID for better performance
|
||||
await db.create(`user:⟨${did}⟩`, {
|
||||
did,
|
||||
handle,
|
||||
created_at: new Date().toISOString(),
|
||||
}).catch(async () => {
|
||||
// If record exists, update it
|
||||
await db.merge(`user:⟨${did}⟩`, {
|
||||
handle,
|
||||
updated_at: new Date().toISOString(),
|
||||
});
|
||||
});
|
||||
|
||||
await db.close();
|
||||
|
||||
|
||||
@@ -27,11 +27,31 @@ export default function LoginPage() {
|
||||
const handleSubmit = async (values: { handle: string }) => {
|
||||
setIsLoading(true);
|
||||
|
||||
// We redirect to our *own* API route, which will then
|
||||
// perform discovery and redirect to the correct Bluesky PDS.
|
||||
// This keeps all complex logic and secrets on the server.
|
||||
// Using window.location.href for full navigation that follows server redirects
|
||||
window.location.href = `/api/auth/login?handle=${encodeURIComponent(values.handle)}`;
|
||||
try {
|
||||
// Call our API route to initiate OAuth flow
|
||||
const response = await fetch('/api/auth/login', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ handle: values.handle }),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const error = await response.json();
|
||||
throw new Error(error.error || 'Login failed');
|
||||
}
|
||||
|
||||
const { url } = await response.json();
|
||||
|
||||
// Redirect to the OAuth authorization URL
|
||||
window.location.href = url;
|
||||
} catch (error) {
|
||||
console.error('Login error:', error);
|
||||
setIsLoading(false);
|
||||
// Show error to user
|
||||
window.location.href = `/login?error=${encodeURIComponent(
|
||||
error instanceof Error ? error.message : 'An error occurred'
|
||||
)}`;
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
|
||||
Reference in New Issue
Block a user