Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix(web): enable Better Auth session cookie cache

Gener1dbac63a90ca
diff --git a/src/web/src/lib/auth.test.ts b/src/web/src/lib/auth.test.ts
index 760259b17..98d53618b 100644
--- a/src/web/src/lib/auth.test.ts
+++ b/src/web/src/lib/auth.test.ts
@@ -60,6 +60,12 @@ type AuthOptions = {
set: (key: string, value: RateLimitValue) => Promise<void>
}
}
+ session?: {
+ cookieCache?: {
+ enabled?: boolean
+ maxAge?: number
+ }
+ }
}
async function loadCreateAuth(nodeEnv: "production" | "development" | "test") {
@@ -160,3 +166,23 @@ describe("createAuth rate limiting", () => {
expect(kv.store.get("k")?.expirationTtl).toBe(180)
})
})
+
+describe("createAuth session cookie cache", () => {
+ beforeEach(() => vi.clearAllMocks())
+
+ // The signed session-data cookie lets `auth.api.getSession()` validate without
+ // a D1 round-trip. Without it, the first request after a fresh OTP sign-up
+ // can 401 because the just-written `user` row hasn't replicated yet.
+ it("enables the signed session-data cookie with a positive maxAge", async () => {
+ const createAuth = await loadCreateAuth("production")
+ const opts = (createAuth(makeEnv() as never) as { __options: AuthOptions }).__options
+ expect(opts.session?.cookieCache?.enabled).toBe(true)
+ expect(opts.session?.cookieCache?.maxAge).toBeGreaterThan(0)
+ })
+
+ it("enables cookieCache in development too so local sign-up doesn't 401", async () => {
+ const createAuth = await loadCreateAuth("development")
+ const opts = (createAuth(makeEnv() as never) as { __options: AuthOptions }).__options
+ expect(opts.session?.cookieCache?.enabled).toBe(true)
+ })
+})
diff --git a/src/web/src/lib/auth.ts b/src/web/src/lib/auth.ts
index 53975116d..08b5461cd 100644
--- a/src/web/src/lib/auth.ts
+++ b/src/web/src/lib/auth.ts
@@ -29,6 +29,16 @@ export function createAuth(env: Env) {
baseURL: env.BETTER_AUTH_URL,
database: env.DB,
secret: env.BETTER_AUTH_SECRET,
+ // Signed session-data cookie lets getSession() validate without hitting D1.
+ // Fixes first-login 401 for newly-registered users: the just-written user row
+ // may not yet be visible on a D1 read-replica, but the signed cookie carries
+ // the session payload set by the sign-in handler itself.
+ session: {
+ cookieCache: {
+ enabled: true,
+ maxAge: 5 * 60,
+ },
+ },
emailAndPassword: {
enabled: !isProd,
requireEmailVerification: false,