Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix: retry getSession on transient D1 errors instead of returning 401

Gener12c1fe8991e2
diff --git a/src/web/src/lib/middleware/auth.ts b/src/web/src/lib/middleware/auth.ts
index 384ace39a..b8417b2b2 100644
--- a/src/web/src/lib/middleware/auth.ts
+++ b/src/web/src/lib/middleware/auth.ts
@@ -52,19 +52,31 @@ export function withAuth(handler: AuthenticatedHandler) {
}
// Fall back to Better Auth session
- try {
- const auth = createAuth(cloudflareEnv)
- const session = await auth.api.getSession({ headers: req.headers })
- if (!session) {
- return NextResponse.json({ error: "unauthorized" }, { status: 401 })
- }
- const authCtx: AuthContext = {
- userId: session.user.id,
- email: session.user.email,
+ const auth = createAuth(cloudflareEnv)
+ let session: Awaited<ReturnType<typeof auth.api.getSession>> = null
+ let lastErr: unknown
+
+ for (let attempt = 0; attempt < 2; attempt++) {
+ try {
+ session = await auth.api.getSession({ headers: req.headers })
+ lastErr = undefined
+ break
+ } catch (err) {
+ lastErr = err
}
- return handler(req, { ...authCtx, params: resolvedParams })
- } catch {
+ }
+
+ if (lastErr) {
+ return NextResponse.json({ error: "session validation failed" }, { status: 503 })
+ }
+ if (!session) {
return NextResponse.json({ error: "unauthorized" }, { status: 401 })
}
+
+ const authCtx: AuthContext = {
+ userId: session.user.id,
+ email: session.user.email,
+ }
+ return handler(req, { ...authCtx, params: resolvedParams })
}
}