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);
|
console.log('[OAuth Callback] ✓ Successfully authenticated user:', session.did);
|
||||||
|
|
||||||
// Create ATproto agent with session
|
const did = session.did;
|
||||||
const agent = new Agent(session);
|
|
||||||
|
|
||||||
// Fetch user profile
|
// For now, we'll use the DID as the handle placeholder
|
||||||
const profileResponse = await agent.getProfile({ actor: session.did });
|
// 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) {
|
console.log('[OAuth Callback] User DID:', did);
|
||||||
throw new Error('Failed to fetch user profile');
|
|
||||||
}
|
|
||||||
|
|
||||||
const { did, handle } = profileResponse.data;
|
|
||||||
|
|
||||||
console.log('[OAuth Callback] User profile:', { did, handle });
|
|
||||||
|
|
||||||
// Upsert user in SurrealDB
|
// Upsert user in SurrealDB
|
||||||
const db = new Surreal();
|
const db = new Surreal();
|
||||||
@@ -77,12 +72,18 @@ export async function GET(request: NextRequest) {
|
|||||||
database: process.env.SURREALDB_DB!,
|
database: process.env.SURREALDB_DB!,
|
||||||
});
|
});
|
||||||
|
|
||||||
await db.query(
|
// Use UPSERT with record ID for better performance
|
||||||
`INSERT INTO user (did, handle)
|
await db.create(`user:⟨${did}⟩`, {
|
||||||
VALUES ($did, $handle)
|
did,
|
||||||
ON DUPLICATE KEY UPDATE handle = $handle`,
|
handle,
|
||||||
{ 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();
|
await db.close();
|
||||||
|
|
||||||
|
|||||||
@@ -27,11 +27,31 @@ export default function LoginPage() {
|
|||||||
const handleSubmit = async (values: { handle: string }) => {
|
const handleSubmit = async (values: { handle: string }) => {
|
||||||
setIsLoading(true);
|
setIsLoading(true);
|
||||||
|
|
||||||
// We redirect to our *own* API route, which will then
|
try {
|
||||||
// perform discovery and redirect to the correct Bluesky PDS.
|
// Call our API route to initiate OAuth flow
|
||||||
// This keeps all complex logic and secrets on the server.
|
const response = await fetch('/api/auth/login', {
|
||||||
// Using window.location.href for full navigation that follows server redirects
|
method: 'POST',
|
||||||
window.location.href = `/api/auth/login?handle=${encodeURIComponent(values.handle)}`;
|
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 (
|
return (
|
||||||
|
|||||||
@@ -36,19 +36,27 @@ export async function getOAuthClient(): Promise<NodeOAuthClient> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (isDev) {
|
if (isDev) {
|
||||||
// Development: Use localhost exception
|
// Development: Use localhost loopback client
|
||||||
// Per ATproto spec, client_id must be exactly "http://localhost"
|
// Per ATproto spec, we encode metadata in the client_id query params
|
||||||
// (no port number) with metadata in query parameters
|
const clientId = `http://localhost/?${new URLSearchParams({
|
||||||
const clientId = `http://localhost?${new URLSearchParams({
|
|
||||||
redirect_uri: callbackUrl,
|
redirect_uri: callbackUrl,
|
||||||
scope: 'atproto',
|
scope: 'atproto',
|
||||||
})}`;
|
}).toString()}`;
|
||||||
|
|
||||||
console.log('[OAuth] Initializing development client with localhost exception');
|
console.log('[OAuth] Initializing development client with loopback exception');
|
||||||
console.log('[OAuth] client_id:', clientId);
|
console.log('[OAuth] client_id:', clientId);
|
||||||
|
|
||||||
clientInstance = await NodeOAuthClient.fromClientId({
|
clientInstance = new NodeOAuthClient({
|
||||||
clientId,
|
clientMetadata: {
|
||||||
|
client_id: clientId,
|
||||||
|
redirect_uris: [callbackUrl],
|
||||||
|
scope: 'atproto',
|
||||||
|
grant_types: ['authorization_code', 'refresh_token'],
|
||||||
|
response_types: ['code'],
|
||||||
|
application_type: 'native',
|
||||||
|
token_endpoint_auth_method: 'none',
|
||||||
|
dpop_bound_access_tokens: true,
|
||||||
|
},
|
||||||
stateStore: createStateStore(),
|
stateStore: createStateStore(),
|
||||||
sessionStore: createSessionStore(),
|
sessionStore: createSessionStore(),
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -41,13 +41,28 @@ export function createSessionStore(): NodeSavedSessionStore {
|
|||||||
const db = await getDB();
|
const db = await getDB();
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// Upsert: create if doesn't exist, update if it does
|
// Use DID as the record ID for direct lookup
|
||||||
await db.query(
|
// Escape special characters in the DID for SurrealDB record ID
|
||||||
`INSERT INTO oauth_session (did, session_data)
|
const recordId = `oauth_session:⟨${did}⟩`;
|
||||||
VALUES ($did, $session_data)
|
|
||||||
ON DUPLICATE KEY UPDATE session_data = $session_data, updated_at = time::now()`,
|
// Upsert: update if exists, create if doesn't
|
||||||
{ did, session_data: sessionData }
|
const existing = await db.select<{ session_data: NodeSavedSession }>(recordId);
|
||||||
);
|
|
||||||
|
if (Array.isArray(existing) && existing.length > 0) {
|
||||||
|
// Update existing record
|
||||||
|
await db.merge(recordId, {
|
||||||
|
session_data: sessionData,
|
||||||
|
updated_at: new Date().toISOString(),
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
// Create new record
|
||||||
|
await db.create(recordId, {
|
||||||
|
did,
|
||||||
|
session_data: sessionData,
|
||||||
|
created_at: new Date().toISOString(),
|
||||||
|
updated_at: new Date().toISOString(),
|
||||||
|
});
|
||||||
|
}
|
||||||
} finally {
|
} finally {
|
||||||
await db.close();
|
await db.close();
|
||||||
}
|
}
|
||||||
@@ -57,12 +72,12 @@ export function createSessionStore(): NodeSavedSessionStore {
|
|||||||
const db = await getDB();
|
const db = await getDB();
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const [result] = await db.query<[{ session_data: NodeSavedSession }[]]>(
|
// Select directly by record ID
|
||||||
'SELECT session_data FROM oauth_session WHERE did = $did',
|
const result = await db.select<{ session_data: NodeSavedSession }>(`oauth_session:⟨${did}⟩`);
|
||||||
{ did }
|
|
||||||
);
|
|
||||||
|
|
||||||
return result?.[0]?.session_data;
|
// db.select() returns an array when selecting a specific record ID
|
||||||
|
const record = Array.isArray(result) ? result[0] : result;
|
||||||
|
return record?.session_data;
|
||||||
} finally {
|
} finally {
|
||||||
await db.close();
|
await db.close();
|
||||||
}
|
}
|
||||||
@@ -72,10 +87,8 @@ export function createSessionStore(): NodeSavedSessionStore {
|
|||||||
const db = await getDB();
|
const db = await getDB();
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await db.query(
|
// Delete directly by record ID
|
||||||
'DELETE oauth_session WHERE did = $did',
|
await db.delete(`oauth_session:⟨${did}⟩`);
|
||||||
{ did }
|
|
||||||
);
|
|
||||||
} finally {
|
} finally {
|
||||||
await db.close();
|
await db.close();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -41,10 +41,13 @@ export function createStateStore(): NodeSavedStateStore {
|
|||||||
const db = await getDB();
|
const db = await getDB();
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await db.query(
|
// Use the key as the record ID for direct lookup
|
||||||
'CREATE oauth_state SET key = $key, value = $value',
|
// Escape special characters in the key for SurrealDB record ID
|
||||||
{ key, value }
|
await db.create(`oauth_state:⟨${key}⟩`, {
|
||||||
);
|
key,
|
||||||
|
value,
|
||||||
|
created_at: new Date().toISOString(),
|
||||||
|
});
|
||||||
} finally {
|
} finally {
|
||||||
await db.close();
|
await db.close();
|
||||||
}
|
}
|
||||||
@@ -54,12 +57,12 @@ export function createStateStore(): NodeSavedStateStore {
|
|||||||
const db = await getDB();
|
const db = await getDB();
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const [result] = await db.query<[{ value: NodeSavedState }[]]>(
|
// Select directly by record ID
|
||||||
'SELECT value FROM oauth_state WHERE key = $key',
|
const result = await db.select<{ value: NodeSavedState }>(`oauth_state:⟨${key}⟩`);
|
||||||
{ key }
|
|
||||||
);
|
|
||||||
|
|
||||||
return result?.[0]?.value;
|
// db.select() returns an array when selecting a specific record ID
|
||||||
|
const record = Array.isArray(result) ? result[0] : result;
|
||||||
|
return record?.value;
|
||||||
} finally {
|
} finally {
|
||||||
await db.close();
|
await db.close();
|
||||||
}
|
}
|
||||||
@@ -69,10 +72,8 @@ export function createStateStore(): NodeSavedStateStore {
|
|||||||
const db = await getDB();
|
const db = await getDB();
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await db.query(
|
// Delete directly by record ID
|
||||||
'DELETE oauth_state WHERE key = $key',
|
await db.delete(`oauth_state:⟨${key}⟩`);
|
||||||
{ key }
|
|
||||||
);
|
|
||||||
} finally {
|
} finally {
|
||||||
await db.close();
|
await db.close();
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user