Skip to content

Commit 91c4349

Browse files
authored
Improve auth error handling and connection reset functionality (#1963)
# READ CAREFULLY THEN REMOVE Remove bullet points that are not relevant. PLEASE REFRAIN FROM USING AI TO WRITE YOUR CODE AND PR DESCRIPTION. IF YOU DO USE AI TO WRITE YOUR CODE PLEASE PROVIDE A DESCRIPTION AND REVIEW IT CAREFULLY. MAKE SURE YOU UNDERSTAND THE CODE YOU ARE SUBMITTING USING AI. - Pull requests that do not follow these guidelines will be closed without review or comment. - If you use AI to write your PR description your pr will be close without review or comment. - If you are unsure about anything, feel free to ask for clarification. ## Description Please provide a clear description of your changes. --- ## Type of Change Please delete options that are not relevant. - [ ] 🐛 Bug fix (non-breaking change which fixes an issue) - [ ] ✨ New feature (non-breaking change which adds functionality) - [ ] 💥 Breaking change (fix or feature with breaking changes) - [ ] 📝 Documentation update - [ ] 🎨 UI/UX improvement - [ ] 🔒 Security enhancement - [ ] ⚡ Performance improvement ## Areas Affected Please check all that apply: - [ ] Email Integration (Gmail, IMAP, etc.) - [ ] User Interface/Experience - [ ] Authentication/Authorization - [ ] Data Storage/Management - [ ] API Endpoints - [ ] Documentation - [ ] Testing Infrastructure - [ ] Development Workflow - [ ] Deployment/Infrastructure ## Testing Done Describe the tests you've done: - [ ] Unit tests added/updated - [ ] Integration tests added/updated - [ ] Manual testing performed - [ ] Cross-browser testing (if UI changes) - [ ] Mobile responsiveness verified (if UI changes) ## Security Considerations For changes involving data or authentication: - [ ] No sensitive data is exposed - [ ] Authentication checks are in place - [ ] Input validation is implemented - [ ] Rate limiting is considered (if applicable) ## Checklist - [ ] I have read the [CONTRIBUTING](https://github.com/Mail-0/Zero/blob/staging/.github/CONTRIBUTING.md) document - [ ] My code follows the project's style guidelines - [ ] I have performed a self-review of my code - [ ] I have commented my code, particularly in complex areas - [ ] I have updated the documentation - [ ] My changes generate no new warnings - [ ] I have added tests that prove my fix/feature works - [ ] All tests pass locally - [ ] Any dependent changes are merged and published ## Additional Notes Add any other context about the pull request here. ## Screenshots/Recordings Add screenshots or recordings here if applicable. --- _By submitting this pull request, I confirm that my contribution is made under the terms of the project's license._ <!-- This is an auto-generated description by cubic. --> --- ## Summary by cubic Improved authentication error handling and connection reset logic to provide clearer feedback and ensure user sessions are properly revoked when issues occur. - **Bug Fixes** - Added redirects and token revocation for failed user info fetches. - Improved handling when no connections are found for a user. - Triggered mailbox resync if inbox is empty after filtering. - **Dependencies** - Updated better-auth and related packages to the latest versions. <!-- End of auto-generated description by cubic. --> <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **Bug Fixes** * Improved error handling during authentication by revoking tokens, resetting connections, and redirecting users to the home page when user info retrieval fails or email is missing. * Enhanced session management by explicitly revoking and signing out sessions when no user connections are found. * **New Features** * Automatically triggers a forced inbox refresh if no threads are found in the inbox, ensuring the latest messages are displayed. * **Chores** * Updated the "better-auth" dependency to version ^1.3.4. <!-- end of auto-generated comment: release notes by coderabbit.ai -->
1 parent e17c3c7 commit 91c4349

File tree

5 files changed

+89
-32
lines changed

5 files changed

+89
-32
lines changed

apps/server/src/lib/auth.ts

Lines changed: 21 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -11,13 +11,13 @@ import { createAuthMiddleware, phoneNumber, jwt, bearer, mcp } from 'better-auth
1111
import { type Account, betterAuth, type BetterAuthOptions } from 'better-auth';
1212
import { getBrowserTimezone, isValidTimezone } from './timezones';
1313
import { drizzleAdapter } from 'better-auth/adapters/drizzle';
14+
import { getZeroDB, resetConnection } from './server-utils';
1415
import { getSocialProviders } from './auth-providers';
1516
import { redis, resend, twilio } from './services';
1617
import { dubAnalytics } from '@dub/better-auth';
1718
import { defaultUserSettings } from './schemas';
1819
import { disableBrainFunction } from './brain';
1920
import { APIError } from 'better-auth/api';
20-
import { getZeroDB } from './server-utils';
2121
import { type EProviders } from '../types';
2222
import { createDriver } from './driver';
2323
import { Autumn } from 'autumn-js';
@@ -91,7 +91,9 @@ const scheduleCampaign = (userInfo: { address: string; name: string }) =>
9191
const connectionHandlerHook = async (account: Account) => {
9292
if (!account.accessToken || !account.refreshToken) {
9393
console.error('Missing Access/Refresh Tokens', { account });
94-
throw new APIError('EXPECTATION_FAILED', { message: 'Missing Access/Refresh Tokens' });
94+
throw new APIError('EXPECTATION_FAILED', {
95+
message: 'Missing Access/Refresh Tokens, contact us on Discord for support',
96+
});
9597
}
9698

9799
const driver = createDriver(account.providerId, {
@@ -103,13 +105,26 @@ const connectionHandlerHook = async (account: Account) => {
103105
},
104106
});
105107

106-
const userInfo = await driver.getUserInfo().catch(() => {
107-
throw new APIError('UNAUTHORIZED', { message: 'Failed to get user info' });
108+
const userInfo = await driver.getUserInfo().catch(async () => {
109+
if (account.accessToken) {
110+
await driver.revokeToken(account.accessToken);
111+
await resetConnection(account.id);
112+
}
113+
throw new Response(null, { status: 301, headers: { Location: '/' } });
108114
});
109115

110116
if (!userInfo?.address) {
111-
console.error('Missing email in user info:', { userInfo });
112-
throw new APIError('BAD_REQUEST', { message: 'Missing "email" in user info' });
117+
try {
118+
await Promise.allSettled(
119+
[account.accessToken, account.refreshToken]
120+
.filter(Boolean)
121+
.map((t) => driver.revokeToken(t as string)),
122+
);
123+
await resetConnection(account.id);
124+
} catch (error) {
125+
console.error('Failed to revoke tokens:', error);
126+
}
127+
throw new Response(null, { status: 303, headers: { Location: '/' } });
113128
}
114129

115130
const updatingInfo = {

apps/server/src/lib/server-utils.ts

Lines changed: 14 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -360,10 +360,10 @@ export const forceReSync = async (connectionId: string) => {
360360
const registry = await getRegistryClient(connectionId);
361361
const allShards = await listShards(registry);
362362

363-
await Promise.all(
363+
await Promise.allSettled(
364364
allShards.map(async ({ shard_id: id }) => {
365365
const shard = await getShardClient(connectionId, id);
366-
await Promise.all([
366+
await Promise.allSettled([
367367
shard.exec(`DROP TABLE IF EXISTS threads`),
368368
shard.exec(`DROP TABLE IF EXISTS thread_labels`),
369369
shard.exec(`DROP TABLE IF EXISTS labels`),
@@ -374,22 +374,16 @@ export const forceReSync = async (connectionId: string) => {
374374
await deleteAllShards(registry);
375375

376376
const agent = await getZeroAgent(connectionId);
377-
await agent.stub.forceReSync();
377+
return agent.stub.forceReSync();
378378
};
379379

380380
export const reSyncThread = async (connectionId: string, threadId: string) => {
381381
try {
382-
const { result: thread, shardId } = await getThread(connectionId, threadId);
382+
const { shardId } = await getThread(connectionId, threadId);
383383
const agent = await getZeroAgentFromShard(connectionId, shardId);
384384
await agent.stub.syncThread({ threadId });
385385
} catch (error) {
386-
console.error(`[ZeroAgent] Thread not found for threadId: ${threadId}`);
387-
}
388-
if (thread) {
389-
const agent = await getZeroAgentFromShard(connectionId, shardId);
390-
await agent.stub.syncThread({ threadId });
391-
} else {
392-
console.error(`[ZeroAgent] Thread not found for threadId: ${threadId}`);
386+
console.error(`[ZeroAgent] Thread not found for threadId: ${threadId}`, error);
393387
}
394388
};
395389

@@ -527,11 +521,10 @@ export const getZeroSocketAgent = async (connectionId: string) => {
527521

528522
export const getActiveConnection = async () => {
529523
const c = getContext<HonoContext>();
530-
const { sessionUser } = c.var;
524+
const { sessionUser, auth } = c.var;
531525
if (!sessionUser) throw new Error('Session Not Found');
532526

533527
const db = await getZeroDB(sessionUser.id);
534-
535528
const userData = await db.findUser();
536529

537530
if (userData?.defaultConnectionId) {
@@ -541,6 +534,14 @@ export const getActiveConnection = async () => {
541534

542535
const firstConnection = await db.findFirstConnection();
543536
if (!firstConnection) {
537+
try {
538+
if (auth) {
539+
await auth.api.revokeSession({ headers: c.req.raw.headers });
540+
await auth.api.signOut({ headers: c.req.raw.headers });
541+
}
542+
} catch (err) {
543+
console.warn(`[getActiveConnection] Session cleanup failed for user ${sessionUser.id}:`, err);
544+
}
544545
console.error(`No connections found for user ${sessionUser.id}`);
545546
throw new Error('No connections found for user');
546547
}

apps/server/src/trpc/routes/mail.ts

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -151,6 +151,31 @@ export const mailRouter = router({
151151
threadsResponse.threads = filtered;
152152
console.debug('[listThreads] Snoozed threads after filtering:', filtered);
153153
}
154+
155+
if (threadsResponse.threads.length === 0 && folder === FOLDERS.INBOX && !q) {
156+
const now = Date.now();
157+
const cooldownKey = `resync_cooldown_${activeConnection.id}`;
158+
const lastResyncStr = await env.gmail_processing_threads.get(cooldownKey);
159+
const lastResync = lastResyncStr ? parseInt(lastResyncStr, 10) : 0;
160+
const RESYNC_COOLDOWN_MS = 30000;
161+
162+
if (now - lastResync > RESYNC_COOLDOWN_MS) {
163+
await env.gmail_processing_threads.put(cooldownKey, now.toString(), {
164+
expirationTtl: 60,
165+
});
166+
167+
getZeroAgent(activeConnection.id, executionCtx)
168+
.then((_agent) => {
169+
_agent.stub.forceReSync().catch((error) => {
170+
console.error('[listThreads] Async resync failed:', error);
171+
});
172+
})
173+
.catch((error) => {
174+
console.error('[listThreads] Failed to get agent for async resync:', error);
175+
});
176+
}
177+
}
178+
154179
console.debug('[listThreads] Returning threadsResponse:', threadsResponse);
155180
return threadsResponse;
156181
}),

pnpm-lock.yaml

Lines changed: 28 additions & 12 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

pnpm-workspace.yaml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ packages:
44
- scripts/*
55
catalog:
66
zod: ^3.25.42
7-
better-auth: ^1.2.9
7+
better-auth: ^1.3.4
88
autumn-js: ^0.0.48
99
superjson: ^2.2.2
1010
'@trpc/server': ^11.1.4

0 commit comments

Comments
 (0)