Multi-Agent Collaboration for Team and Friends
TypeScript agent-automationagent-orchestrationagent-workflowai-agentsai-collaborationai-memoryai-workforceautonomous-agentsclaude-codeclaude-code-skillscodexcoding-agentmulti-agentmultiple-agentone-person-businessone-person-companyone-person-teamopencodesolopreneur
perf(auth): read isBot/deletedAt off the session user instead of a per-request D1
Claudetteb6363ea37787
diff --git a/src/web/src/lib/auth.ts b/src/web/src/lib/auth.tsindex 3a0e3ee0e..56605736f 100644--- a/src/web/src/lib/auth.ts+++ b/src/web/src/lib/auth.ts@@ -76,6 +76,23 @@ export function createAuth(env: Env) {required: false,input: false,},+ // Carried on the session user (and its signed cookie) so `withAuth`'s+ // session guard reads isBot/deletedAt off `getSession().user` instead+ // of a dedicated per-request `getUserInternal` D1 read. `input: false`+ // keeps them server-owned (never settable via signup/update). Their+ // freshness = the session cookie-cache period (prod 5min) — the guard+ // comment documents that revocation latency is bounded by it and NOT+ // loosened beyond today's getSession cookie window.+ isBot: {+ type: "boolean",+ required: false,+ input: false,+ },+ deletedAt: {+ type: "string",+ required: false,+ input: false,+ },},},socialProviders: {diff --git a/src/web/src/lib/middleware/auth.test.ts b/src/web/src/lib/middleware/auth.test.tsindex fb3050691..2c2fc19a6 100644--- a/src/web/src/lib/middleware/auth.test.ts+++ b/src/web/src/lib/middleware/auth.test.ts@@ -111,6 +111,38 @@ describe("withAuth middleware", () => {expect(testHandler).toHaveBeenCalledOnce();});+ it("rejects a session whose user carries isBot=true (guard reads it off the session user, no getUserInternal)", async () => {+ mockGetSession.mockResolvedValue({+ headers: new Headers(),+ response: { user: { id: "bot-1", email: "[email protected]", isBot: true, deletedAt: null } },+ });++ const req = new NextRequest("http://localhost/api/test", {+ headers: { Authorization: "Bearer some-session-token" },+ });+ const res = await wrapped(req);++ expect(res.status).toBe(401);+ expect((await res.json()).error).toBe("session no longer valid");+ expect(testHandler).not.toHaveBeenCalled();+ });++ it("rejects a session whose user is soft-deleted (deletedAt set)", async () => {+ mockGetSession.mockResolvedValue({+ headers: new Headers(),+ response: { user: { id: "user-x", email: "[email protected]", isBot: false, deletedAt: "2026-07-29T00:00:00.000Z" } },+ });++ const req = new NextRequest("http://localhost/api/test", {+ headers: { Authorization: "Bearer some-session-token" },+ });+ const res = await wrapped(req);++ expect(res.status).toBe(401);+ expect((await res.json()).error).toBe("session no longer valid");+ expect(testHandler).not.toHaveBeenCalled();+ });+it("returns 401 when Better Auth session is null", async () => {mockGetSession.mockResolvedValue({ headers: new Headers(), response: null });diff --git a/src/web/src/lib/middleware/auth.ts b/src/web/src/lib/middleware/auth.tsindex cfda7c5ce..cd0047754 100644--- a/src/web/src/lib/middleware/auth.ts+++ b/src/web/src/lib/middleware/auth.ts@@ -203,35 +203,32 @@ export function withAuth(handler: AuthenticatedHandler) {// - deletedAt != null → session invalid// - isBot === true → session invalid (bots must never sign in)// Belt-and-braces with the databaseHooks.session.create.before hook.- let sessionUserIsBot = false- try {- const db = getDb(cloudflareEnv.DB)- const internal = await queries.user.getUserInternal(- db,- sessionResult.response.user.id,- )- sessionUserIsBot = internal?.isBot === true- if (!internal || internal.deletedAt !== null || internal.isBot === true) {- // Best-effort server-side invalidation. Cookie clear happens via the- // 401 response below; Better-Auth will see the missing session next- // request.- try {- await auth.api.signOut({ headers: req.headers })- } catch {- // ignore — signOut best-effort- }- const invalid = NextResponse.json(- { error: "session no longer valid" },- { status: 401 },- )- // Clear known Better-Auth cookie names to prevent replay.- invalid.cookies.set("better-auth.session_token", "", { maxAge: 0, path: "/" })- invalid.cookies.set("better-auth.session_data", "", { maxAge: 0, path: "/" })- return invalid+ // isBot/deletedAt ride the session user via better-auth `additionalFields`+ // (see auth.ts) — no dedicated per-request `getUserInternal` D1 read. Their+ // freshness = the session cookie-cache period (prod 5min); revocation+ // latency is therefore bounded by that window and is NOT loosened beyond+ // today's getSession cookie cache. (Bots never mint a session — the+ // session.create hook blocks them — so the isBot check is belt-and-braces;+ // deletedAt is the one with a real, ≤cookie-period latency.)+ const guardUser = sessionResult.response.user as { isBot?: boolean | null; deletedAt?: string | null }+ const sessionUserIsBot = guardUser.isBot === true+ if (sessionUserIsBot || (guardUser.deletedAt ?? null) !== null) {+ // Best-effort server-side invalidation. Cookie clear happens via the+ // 401 response below; Better-Auth will see the missing session next+ // request.+ try {+ await auth.api.signOut({ headers: req.headers })+ } catch {+ // ignore — signOut best-effort}- } catch {- // Fall through — if the guard read fails, session validation already- // succeeded and we don't want to break auth for an incidental read error.+ const invalid = NextResponse.json(+ { error: "session no longer valid" },+ { status: 401 },+ )+ // Clear known Better-Auth cookie names to prevent replay.+ invalid.cookies.set("better-auth.session_token", "", { maxAge: 0, path: "/" })+ invalid.cookies.set("better-auth.session_data", "", { maxAge: 0, path: "/" })+ return invalid}const authCtx: AuthContext = {