Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix(web): share auth initialization and skip runtime schema checks (#1023)

Gener6cae11765eaa
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 0edc7dec3..cf4c23d8b 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -401,8 +401,8 @@ importers:
specifier: 0.7.0
version: 0.7.0
better-auth:
- specifier: 1.7.9
+ specifier: 1.7.11
class-variance-authority:
specifier: ^0.7.1
version: 0.7.1
@@ -1156,8 +1156,8 @@ packages:
resolution: {integrity: sha512-6zABk/ECA/QYSCQ1NGiVwwbQerUCZ+TQbp64Q3AgmfNvurHH0j8TtXa1qbShXA6qqkpAj4V5W8pP6mLe1mcMqA==}
engines: {node: '>=18'}
- '@better-auth/[email protected]':
- resolution: {integrity: sha512-ZwkJRJOG0NkSoLudyDdy7PZUjpMxj5T5/AtNN6axJCwCXMEWYF1IX36yJJC2T0hIvrm/ORngDHd5QXh9DRRm2A==}
+ '@better-auth/[email protected]':
+ resolution: {integrity: sha512-HG08OUeiMIGbDE+qEiBGxEvZ3l0PNEKG2PZfC691UZjLpba/GMtWezP/jtHBP9W1YKZpDEjh5cav39+JGgDV8w==}
peerDependencies:
'@better-auth/utils': ^0.4.2 || ^0.5.0
'@better-fetch/fetch': 1.3.2
@@ -1170,46 +1170,46 @@ packages:
'@opentelemetry/api':
optional: true
- '@better-auth/[email protected]':
- resolution: {integrity: sha512-pjKw09MM/RftcSLIPuvW9Xz7PlMoKZE9tXEbnNqsv2cqZQvEJKrCPSYi32d3CCIWj7509Kccll1v0AyV8K05GQ==}
+ '@better-auth/[email protected]':
+ resolution: {integrity: sha512-CkTDxo4MDymXA4vfLKufkOdV+FgroTCqERE1CNp4XNghiIrBWNjM4Ph6J//AoL6aowWcbLdBqUtJM40/eLJFKg==}
peerDependencies:
- '@better-auth/core': ^1.7.9
+ '@better-auth/core': ^1.7.11
'@better-auth/utils': ^0.4.2 || ^0.5.0
drizzle-orm: ^0.45.2 || >=1.0.0-rc.1 <2.0.0
peerDependenciesMeta:
drizzle-orm:
optional: true
- '@better-auth/[email protected]':
- resolution: {integrity: sha512-e5pHavuUGIFTgboE7/j7dxq4HVkbuEOdLo2y3KZCeH5RjDdiYt7gReqq001kyHJSKwxv6xLIjgpoVZq/tirFpA==}
+ '@better-auth/[email protected]':
+ resolution: {integrity: sha512-KC/XJGRG2Zi9cSzzKbAU6vmzEiP9t/gd41Ct0e0OhFAlF0aKzfv5SuL0LlEzXlw+sLRAvylaLSxjgctzrCeEzg==}
peerDependencies:
- '@better-auth/core': ^1.7.9
+ '@better-auth/core': ^1.7.11
'@better-auth/utils': ^0.4.2 || ^0.5.0
kysely: ^0.28.17 || ^0.29.0
peerDependenciesMeta:
kysely:
optional: true
- '@better-auth/[email protected]':
- resolution: {integrity: sha512-UoPx/V4Ddj/fjlILXRfcQNXutHWqoKqrC2z8jHqvCrfdwpytxIrp+A1CcG3vXjZWHIynLK34+AcIjvwMEQLNwg==}
+ '@better-auth/[email protected]':
+ resolution: {integrity: sha512-rLSPKqQpXDwSE013UmgnJ2oTwDrQD95LkPon/TvwPLkCqnoz7wruNKfMsLCmLxaMhH8QEeZvvS+cE4cl3wqSuw==}
peerDependencies:
- '@better-auth/core': ^1.7.9
+ '@better-auth/core': ^1.7.11
'@better-auth/utils': ^0.4.2 || ^0.5.0
- '@better-auth/[email protected]':
- resolution: {integrity: sha512-gEqaFxOW5QUZswgPdBL/JqunhruTF6wG1xbPilNXyVd8ZpbeMstyDewuLmTgOeI20M6zEWC4b7BURVU91Gg7+A==}
+ '@better-auth/[email protected]':
+ resolution: {integrity: sha512-7fEFV7L0FGjfJ3CNi6SL1kmUwfANPHf05znzbPhTozCJ3kZSAP1FWHq7+kyI7xh6dOgaBQ/UdlCUKELqkrkAXQ==}
peerDependencies:
- '@better-auth/core': ^1.7.9
+ '@better-auth/core': ^1.7.11
'@better-auth/utils': ^0.4.2 || ^0.5.0
mongodb: ^6.0.0 || ^7.0.0
peerDependenciesMeta:
mongodb:
optional: true
- '@better-auth/[email protected]':
- resolution: {integrity: sha512-L/6Bq1hLjBhexUa4JSk7pDYNDuGksuiedWYnyvJc0alzdYavk0pAWvWWt/WI3DvblBr6YUIbgr3HqeHvVueUrA==}
+ '@better-auth/[email protected]':
+ resolution: {integrity: sha512-kjjiyr7H42z25vrTyAPc/Y19eMUZOByw6jrd5mDoAGZssj1Qm3KPCHZFFxFzTjapW8Saq288xPdt5dARf1rQCA==}
peerDependencies:
- '@better-auth/core': ^1.7.9
+ '@better-auth/core': ^1.7.11
'@better-auth/utils': ^0.4.2 || ^0.5.0
'@prisma/client': ^5.0.0 || ^6.0.0 || ^7.0.0
prisma: ^5.0.0 || ^6.0.0 || ^7.0.0
@@ -1219,10 +1219,10 @@ packages:
prisma:
optional: true
- '@better-auth/[email protected]':
- resolution: {integrity: sha512-OaHj8vM6rQYrdONCiPMMyUHGIx3BaEUNfHHXEmpukcZFboAWfRYTRm0GVt+O8Sz3+rgIUBWiY+/H7SehCFA3dQ==}
+ '@better-auth/[email protected]':
+ resolution: {integrity: sha512-VJWa9s0f9EIP/zWmHHd9Gv/PO4nwlXq1Xa5nXq5nsl0BrAJPrx/FbYVIPVWaZR4vDt8f0CWtrN4Qxln8lhpSbA==}
peerDependencies:
- '@better-auth/core': ^1.7.9
+ '@better-auth/core': ^1.7.11
'@better-auth/utils': ^0.4.2 || ^0.5.0
'@better-fetch/fetch': 1.3.2
@@ -4720,8 +4720,8 @@ packages:
resolution: {integrity: sha512-5K9eNNn7ywHPsYnFwjKgYH8Hf8B5emh7JKcPaVjjrMJFQQwGpwowEnZNEtHs7DfR7hCZsmaK3VA4HUK0YarT+w==}
engines: {node: '>=10.0.0'}
- resolution: {integrity: sha512-qJ+s5GxLKalCKzABtIFzhI9V5IWJ3vuTKnklU+bwIqzs08BZSeIVoli/py8UpCn2vbKmQ6d8i7mMPiqoc3z0+w==}
+ resolution: {integrity: sha512-V4OMDdoFvOuAGbOb/mjNzX/iFJoC3hEF1rpL8vdI5eTR24dMJr7AWJuuhr6dE1ib/CBECzegt64ehS3/ngKYpQ==}
peerDependencies:
'@lynx-js/react': '*'
'@prisma/client': ^5.0.0 || ^6.0.0 || ^7.0.0
@@ -10510,11 +10510,10 @@ snapshots:
'@bcoe/[email protected]': {}
dependencies:
'@better-auth/utils': 0.5.0
'@better-fetch/fetch': 1.3.2
- '@opentelemetry/semantic-conventions': 1.43.0
'@standard-schema/spec': 1.1.0
better-call: 1.4.2([email protected])
jose: 6.2.12
@@ -10524,38 +10523,38 @@ snapshots:
optionalDependencies:
'@opentelemetry/api': 1.9.1
dependencies:
'@better-auth/utils': 0.5.0
optionalDependencies:
dependencies:
'@better-auth/utils': 0.5.0
optionalDependencies:
kysely: 0.29.6
dependencies:
'@better-auth/utils': 0.5.0
dependencies:
'@better-auth/utils': 0.5.0
dependencies:
'@better-auth/utils': 0.5.0
dependencies:
'@better-auth/utils': 0.5.0
'@better-fetch/fetch': 1.3.2
@@ -13925,15 +13924,15 @@ snapshots:
dependencies:
- '@better-auth/memory-adapter': 1.7.9(@better-auth/[email protected](@better-auth/[email protected])(@better-fetch/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected]))(@better-auth/[email protected])
- '@better-auth/mongo-adapter': 1.7.9(@better-auth/[email protected](@better-auth/[email protected])(@better-fetch/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected]))(@better-auth/[email protected])
- '@better-auth/prisma-adapter': 1.7.9(@better-auth/[email protected](@better-auth/[email protected])(@better-fetch/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected]))(@better-auth/[email protected])
- '@better-auth/telemetry': 1.7.9(@better-auth/[email protected](@better-auth/[email protected])(@better-fetch/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected]))(@better-auth/[email protected])(@better-fetch/[email protected])
+ '@better-auth/memory-adapter': 1.7.11(@better-auth/[email protected](@better-auth/[email protected])(@better-fetch/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected]))(@better-auth/[email protected])
+ '@better-auth/mongo-adapter': 1.7.11(@better-auth/[email protected](@better-auth/[email protected])(@better-fetch/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected]))(@better-auth/[email protected])
+ '@better-auth/prisma-adapter': 1.7.11(@better-auth/[email protected](@better-auth/[email protected])(@better-fetch/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected]))(@better-auth/[email protected])
+ '@better-auth/telemetry': 1.7.11(@better-auth/[email protected](@better-auth/[email protected])(@better-fetch/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected]))(@better-auth/[email protected])(@better-fetch/[email protected])
'@better-auth/utils': 0.5.0
'@better-fetch/fetch': 1.3.2
'@noble/ciphers': 2.4.0
diff --git a/src/web/package.json b/src/web/package.json
index 97ac50872..64bfe413d 100644
--- a/src/web/package.json
+++ b/src/web/package.json
@@ -87,7 +87,7 @@
"@tiptap/suggestion": "3.32.0",
"@types/mdx": "^2.0.14",
"@typesafe-ai/sdk": "0.7.0",
- "better-auth": "1.7.9",
+ "better-auth": "1.7.11",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"emoji-mart": "^5.6.0",
diff --git a/src/web/src/lib/auth.test.ts b/src/web/src/lib/auth.test.ts
index c7d2201fd..e79e8f83f 100644
--- a/src/web/src/lib/auth.test.ts
+++ b/src/web/src/lib/auth.test.ts
@@ -238,8 +238,8 @@ describe("getAuth lifecycle", () => {
expect(second).not.toBe(first)
})
- it("starts a fresh lifecycle after a module reload", async () => {
- const env = makeEnv()
+ it("starts a fresh development lifecycle after a module reload", async () => {
+ const env = makeEnv({ NODE_ENV: "development" })
const firstModule = await loadAuthModule()
const first = firstModule.getAuth(env as never)
const secondModule = await loadAuthModule()
@@ -248,6 +248,38 @@ describe("getAuth lifecycle", () => {
expect(second).not.toBe(first)
})
+ it("shares the production instance across independently loaded module copies", async () => {
+ const env = makeEnv({
+ NODE_ENV: "production",
+ CF_VERSION_METADATA: { id: "shared-production-modules", tag: "", timestamp: "a" },
+ })
+ const firstModule = await loadAuthModule()
+ const first = firstModule.getAuth(env as never)
+ const secondModule = await loadAuthModule()
+ const second = secondModule.getAuth({ ...env, DB: {} } as never)
+ const { betterAuth } = await import("better-auth")
+
+ expect(second).toBe(first)
+ expect(betterAuth).toHaveBeenCalledTimes(1)
+ })
+
+ it("invalidates the shared production instance on version or provider changes", async () => {
+ const env = makeEnv({
+ NODE_ENV: "production",
+ CF_VERSION_METADATA: { id: "shared-generation-a", tag: "", timestamp: "a" },
+ })
+ const firstModule = await loadAuthModule()
+ const first = firstModule.getAuth(env as never)
+ const secondModule = await loadAuthModule()
+ const nextVersion = { ...env, CF_VERSION_METADATA: { id: "shared-generation-b", tag: "", timestamp: "b" } }
+ const second = secondModule.getAuth(nextVersion as never)
+ const third = firstModule.getAuth({ ...nextVersion, GITHUB_CLIENT_ID: "changed-provider" } as never)
+
+ expect(second).not.toBe(first)
+ expect(third).not.toBe(second)
+ expect(secondModule.getAuth({ ...nextVersion, GITHUB_CLIENT_ID: "changed-provider" } as never)).toBe(third)
+ })
+
it("rebuilds when optional contact configuration changes", async () => {
const { getAuth } = await loadAuthModule()
const absent = getAuth(makeEnv() as never)
diff --git a/src/web/src/lib/auth.ts b/src/web/src/lib/auth.ts
index bb1b9b6b3..2ae0b49b5 100644
--- a/src/web/src/lib/auth.ts
+++ b/src/web/src/lib/auth.ts
@@ -127,6 +127,11 @@ export function createAuth(env: Env) {
baseURL: env.BETTER_AUTH_URL,
database: env.DB,
secret: env.BETTER_AUTH_SECRET,
+ advanced: {
+ database: {
+ validateSchema: false,
+ },
+ },
// 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
@@ -414,7 +419,13 @@ type AuthLifecycleEntry = {
auth: AuthInstance
}
-let authLifecycleEntry: AuthLifecycleEntry | undefined
+type AuthLifecycle = { entry?: AuthLifecycleEntry }
+
+const moduleAuthLifecycle: AuthLifecycle = {}
+const workerAuthLifecycleKey = Symbol.for("alook.auth.lifecycle.v1")
+const workerGlobal = globalThis as typeof globalThis & {
+ [workerAuthLifecycleKey]?: AuthLifecycle
+}
function authConfiguration(env: Env): readonly (string | undefined)[] {
return [
@@ -462,8 +473,9 @@ function authVersionId(env: Env): string | undefined {
* bindings, and compatibility configuration, so its version-metadata ID is
* the binding-generation boundary. Scalar auth/provider configuration is
* compared explicitly for local development and tests, where those values can
- * change without a deployed version transition. A module/HMR reload naturally
- * starts a fresh lifecycle as well.
+ * change without a deployed version transition. Production module copies
+ * share one lifecycle in the Worker global. Development keeps a module-local
+ * lifecycle so an HMR reload starts fresh.
*
* Production fails safe when version metadata is unavailable: construct a
* request-local instance instead of retaining binding-derived objects behind
@@ -487,21 +499,26 @@ function resolveAuthInstance(env: Env): AuthInstance {
const lifecycleVersion = versionId ?? "local-module"
const configuration = authConfiguration(env)
+ const lifecycle = mode === "production"
+ ? workerGlobal[workerAuthLifecycleKey] ??= {}
+ : moduleAuthLifecycle
+ let entry = lifecycle.entry
if (
- !authLifecycleEntry
- || authLifecycleEntry.versionId !== lifecycleVersion
- || !sameAuthConfiguration(authLifecycleEntry.configuration, configuration)
+ !entry
+ || entry.versionId !== lifecycleVersion
+ || !sameAuthConfiguration(entry.configuration, configuration)
) {
- annotateWorkerSpan({ auth_instance: "created", auth_reuse_reason: !authLifecycleEntry ? "cold" : authLifecycleEntry.versionId !== lifecycleVersion ? "version_changed" : "configuration_changed" })
- authLifecycleEntry = {
+ annotateWorkerSpan({ auth_instance: "created", auth_reuse_reason: !entry ? "cold" : entry.versionId !== lifecycleVersion ? "version_changed" : "configuration_changed" })
+ entry = {
configuration,
versionId: lifecycleVersion,
auth: createAuth(env),
}
+ lifecycle.entry = entry
} else {
annotateWorkerSpan({ auth_instance: "reused", auth_reuse_reason: "match" })
}
- return authLifecycleEntry.auth
+ return entry.auth
}
export async function observeAuthSession<T>(auth: AuthInstance, execute: () => Promise<T>): Promise<T> {
diff --git a/src/web/test-runtime/auth-schema-validation.runtime.test.ts b/src/web/test-runtime/auth-schema-validation.runtime.test.ts
new file mode 100644
index 000000000..ef435754a
--- /dev/null
+++ b/src/web/test-runtime/auth-schema-validation.runtime.test.ts
@@ -0,0 +1,96 @@
+/// <reference types="@cloudflare/vitest-plugin/types" />
+
+import { env } from "cloudflare:workers"
+import { applySetCookies } from "better-auth/cookies"
+import { makeSignature } from "better-auth/crypto"
+import { afterEach, describe, expect, it } from "vitest"
+import { createAuth, getAuth } from "../src/lib/auth"
+
+const runtimeEnv = env as unknown as CloudflareEnv
+const users: string[] = []
+
+afterEach(async () => {
+ for (const id of users.splice(0)) {
+ await runtimeEnv.DB.prepare('DELETE FROM "user" WHERE id = ?').bind(id).run()
+ }
+})
+
+async function seedSession() {
+ const id = crypto.randomUUID()
+ const token = crypto.randomUUID()
+ const now = new Date().toISOString()
+ users.push(id)
+ await runtimeEnv.DB.prepare(
+ 'INSERT INTO "user" (id, name, email, emailVerified, createdAt, updatedAt) VALUES (?, ?, ?, 1, ?, ?)',
+ ).bind(id, `Auth ${id}`, `${id}@example.test`, now, now).run()
+ await runtimeEnv.DB.prepare(
+ 'INSERT INTO "session" (id, userId, token, expiresAt, createdAt, updatedAt) VALUES (?, ?, ?, ?, ?, ?)',
+ ).bind(crypto.randomUUID(), id, token, new Date(Date.now() + 3_600_000).toISOString(), now, now).run()
+ return { id, token }
+}
+
+function authEnvironment(statements: string[]): Env {
+ const DB = new Proxy(runtimeEnv.DB, {
+ get(target, property) {
+ if (property === "prepare") {
+ return (statement: string) => {
+ statements.push(statement)
+ if (/\b(?:sqlite_master|sqlite_schema|pragma_table_info|pragma_index_list|pragma_index_info)\b|\bPRAGMA\s+(?:table_info|index_list|index_info)\b/i.test(statement)) {
+ throw new Error("Auth requests must not introspect the database schema")
+ }
+ return target.prepare(statement)
+ }
+ }
+ const value = Reflect.get(target, property)
+ return typeof value === "function" ? value.bind(target) : value
+ },
+ })
+ return {
+ ...runtimeEnv,
+ NODE_ENV: "production",
+ DB,
+ BETTER_AUTH_URL: "https://auth-runtime.test",
+ BETTER_AUTH_SECRET: crypto.randomUUID() + crypto.randomUUID(),
+ CF_VERSION_METADATA: { id: crypto.randomUUID(), tag: "", timestamp: new Date().toISOString() },
+ }
+}
+
+describe("Auth sessions without runtime schema introspection", () => {
+ it("validates and refreshes sessions in independently constructed Auth instances", async () => {
+ const user = await seedSession()
+ const statements: string[] = []
+ const authEnv = authEnvironment(statements)
+ for (const auth of [createAuth(authEnv), createAuth(authEnv)]) {
+ const context = await auth.$context
+ const signed = encodeURIComponent(`${user.token}.${await makeSignature(user.token, authEnv.BETTER_AUTH_SECRET)}`)
+ const headers = new Headers({ cookie: `${context.authCookies.sessionToken.name}=${signed}` })
+ const result = await auth.api.getSession({
+ headers,
+ returnHeaders: true,
+ })
+ expect(result.response?.user.id).toBe(user.id)
+ expect(result.headers.getSetCookie().some((cookie) => cookie.includes("session_data="))).toBe(true)
+
+ const forwarded = new Headers(headers)
+ applySetCookies(forwarded, result.headers.getSetCookie())
+ expect((await auth.api.getSession({ headers: forwarded }))?.user.id).toBe(user.id)
+ }
+ expect(statements.some((statement) => /\bFROM\s+"session"/i.test(statement))).toBe(true)
+ })
+
+ it("isolates concurrent users and rejects missing, invalid, and expired sessions on one reused instance", async () => {
+ const first = await seedSession()
+ const second = await seedSession()
+ const expired = await seedSession()
+ await runtimeEnv.DB.prepare('UPDATE "session" SET expiresAt = ? WHERE token = ?')
+ .bind(new Date(Date.now() - 60_000).toISOString(), expired.token).run()
+ const statements: string[] = []
+ const authEnv = authEnvironment(statements)
+ const auth = getAuth(authEnv)
+ expect(getAuth({ ...authEnv })).toBe(auth)
+ const results = await Promise.all([first.token, second.token, undefined, "invalid-session-token", expired.token].map((token) =>
+ auth.api.getSession({ headers: new Headers(token ? { authorization: `Bearer ${token}` } : {}) }),
+ ))
+ expect(results.map((result) => result?.user.id ?? null)).toEqual([first.id, second.id, null, null, null])
+ })
+})