diff --git a/.changeset/upgrade-0-10.md b/.changeset/upgrade-0-10.md new file mode 100644 index 0000000..a858803 --- /dev/null +++ b/.changeset/upgrade-0-10.md @@ -0,0 +1,111 @@ +--- +"better-auth-convex": minor +--- + +### @convex-dev/better-auth 0.10 + +This release updates better-auth-convex to work with `@convex-dev/better-auth@0.10.4` and `better-auth@1.4.7`. + +For the upstream migration guide, see: https://labs.convex.dev/better-auth/migrations/migrate-to-0-10 + +### Breaking Changes + +#### `createApi` signature changed + +The second parameter is now `createAuth` function instead of spread auth options: + +```ts +// Before +export const { create, ... } = createApi(schema, { + ...auth.options, + skipValidation: true, +}); + +// After +export const { create, ... } = createApi(schema, createAuth, { + skipValidation: true, +}); +``` + +#### `authClient.adapter` signature changed + +Now takes `createAuthOptions` function instead of options object: + +```ts +// Before +database: authClient.adapter(ctx, auth.options), + +// After +database: authClient.adapter(ctx, createAuthOptions), +``` + +#### `createAuth` pattern replaced + +The static `auth` instance with `optionsOnly` is replaced by `createAuthOptions` factory: + +```ts +// Before +export const createAuth = (ctx, { optionsOnly } = { optionsOnly: false }) => { + return betterAuth({ ... }); +}; +export const auth = createAuth({}, { optionsOnly: true }); + +// After +export const createAuthOptions = (ctx) => ({ + baseURL: process.env.SITE_URL!, + plugins: [convex({ authConfig, jwks: process.env.JWKS })], + // ... +}) satisfies BetterAuthOptions; + +export const createAuth = (ctx) => betterAuth(createAuthOptions(ctx)); +``` + +### New Features + +#### Static JWKS exports + +`createApi` now exports `getLatestJwks` and `rotateKeys` for static JWKS management: + +```ts +export const { + create, + // ... other exports + getLatestJwks, + rotateKeys, +} = createApi(schema, createAuth, { skipValidation: true }); +``` + +After deploying, generate JWKS: + +```bash +npx convex run auth:getLatestJwks | npx convex env set JWKS +``` + +### Migration Steps + +1. Update dependencies: + + ```bash + pnpm add better-auth@1.4.7 @convex-dev/better-auth@0.10.4 + ``` + +2. Update `convex/auth.config.ts`: + + ```ts + export default { + providers: [getAuthConfigProvider({ jwks: process.env.JWKS })], + } satisfies AuthConfig; + ``` + +3. Update `convex/auth.ts`: + - Replace `auth` static instance with `createAuthOptions` factory + - Update `createApi` call signature + - Update `getAuth` to use `createAuthOptions` + - Add `getLatestJwks` and `rotateKeys` to exports + +4. Deploy and generate JWKS: + ```bash + npx convex run auth:getLatestJwks | npx convex env set JWKS + ``` + +See the [README](https://github.com/udecode/better-auth-convex) for complete setup examples. diff --git a/.claude/commands/sync-fork-full.md b/.claude/commands/sync-fork-full.md new file mode 100644 index 0000000..93c7d67 --- /dev/null +++ b/.claude/commands/sync-fork-full.md @@ -0,0 +1,87 @@ +# Migration Plan: Full Sync from External Repository Comparison + +**Objective** +Compare two external repositories and identify both improvements to integrated code AND new features that can be added to this project. + +## Context + +- This project has integrated a subset of features from an external repository +- We want to track improvements in that external repository (or its forks) +- We also want to identify new features added from scratch +- We DON'T want changes to features we deliberately didn't integrate + +## Usage + +Provide a GitHub compare URL in the format: + +``` +https://github.com/OWNER/REPO/compare/BASE...HEAD +``` + +**Example:** + +``` +https://github.com/zbeyens/sparka/compare/main...FranciscoMoretti:sparka:main +``` + +## Workflow + +1. **Parse the compare URL** to extract: + - Repository owner and name + - Base branch + - Head branch (may include fork reference) + +2. **Fetch the diff** using GitHub CLI: + + ```bash + gh api repos/OWNER/REPO/compare/BASE...HEAD --jq '.files[] | "\(.filename)\n\(.patch)\n"' + ``` + +3. **Analyze changes** against this project: + - Identify which files/features from the comparison exist in this project + - Identify entirely new files/features (created from scratch) + - Ignore changes to files/features that exist in external repo but not in this project + +4. **Categorize changes into TWO sections**: + + ### Section A: Improvements to Integrated Features + - Bug fixes (for code we have) + - Performance improvements (for code we have) + - Code quality improvements (for code we have) + - Refactoring (for code we have) + - Documentation updates (for features we have) + + ### Section B: New Features (From Scratch) + - Entirely new components/files + - New functionality that doesn't exist anywhere in this project + - New capabilities added from scratch + + ### IGNORE: + - Changes to features that exist in external repo but NOT in this project + - Updates to files we deliberately didn't integrate + +5. **Create a prioritized migration plan** with: + - **Section A: Improvements to sync** (what to backport) + - **Section B: New features to consider** (what to add) + - Value and rationale for each change + - Any potential conflicts or integration concerns + - Recommended order of migration + - File mappings (external repo → this project) + +## Constraints + +- **Section A**: Sync only improvements to features already in this project +- **Section B**: Include only features created from scratch (not updates to un-adopted features) +- **Exclude**: All changes to features that exist in external repo but not in this project +- Focus on keeping our integrated subset up-to-date AND identifying valuable additions +- Consider our project's specific architecture and patterns + +## Key Distinction + +- ✅ **Include**: New feature X created from scratch +- ✅ **Include**: Improvement to feature Y we already have +- ❌ **Exclude**: Change to feature Z that exists in external repo but we never integrated + +--- + +**Please provide a GitHub compare URL to begin the analysis.** diff --git a/README.md b/README.md index 5261997..b087601 100644 --- a/README.md +++ b/README.md @@ -18,38 +18,49 @@ The official `@convex-dev/better-auth` component stores auth tables in a compone ## Prerequisites -- Follow the [official Better Auth + Convex setup guide](https://convex-better-auth.netlify.app/) first -- Choose your [framework guide](https://convex-better-auth.netlify.app/framework-guides/next) +- Follow the [official Better Auth + Convex setup guide](https://labs.convex.dev/better-auth) first +- Choose your [framework guide](https://labs.convex.dev/better-auth/framework-guides/next) - **IGNORE these steps from the framework guide**: - Step 2: "Register the component" - We don't use the component approach - Step 5: `convex/auth.ts` - We'll use a different setup - - Step 7: `convex/http.ts` - We use different route registration + - Step 8: `convex/http.ts` - We use different route registration - Then come back here to install locally ## Installation ```bash -pnpm add better-auth@1.3.34 better-auth-convex +pnpm add better-auth@1.4.7 better-auth-convex ``` ## Local Setup You'll need `convex/auth.config.ts` and update your files to install Better Auth directly in your app: +```ts +// convex/auth.config.ts +import { getAuthConfigProvider } from "@convex-dev/better-auth/auth-config"; +import type { AuthConfig } from "convex/server"; + +export default { + providers: [getAuthConfigProvider({ jwks: process.env.JWKS })], +} satisfies AuthConfig; +``` + ```ts // convex/auth.ts -import { betterAuth } from 'better-auth'; -import { convex } from '@convex-dev/better-auth/plugins'; -import { admin, organization } from 'better-auth/plugins'; // Optional plugins +import { betterAuth, type BetterAuthOptions } from "better-auth"; +import { convex } from "@convex-dev/better-auth/plugins"; +import { admin, organization } from "better-auth/plugins"; // Optional plugins import { type AuthFunctions, createClient, createApi, -} from 'better-auth-convex'; -import { internal } from './_generated/api'; -import type { MutationCtx, QueryCtx, GenericCtx } from './_generated/server'; -import type { DataModel } from './_generated/dataModel'; -import schema from './schema'; // YOUR app schema with auth tables +} from "better-auth-convex"; +import { internal } from "./_generated/api"; +import type { MutationCtx, QueryCtx, GenericCtx } from "./_generated/server"; +import type { DataModel } from "./_generated/dataModel"; +import schema from "./schema"; // YOUR app schema with auth tables +import authConfig from "./auth.config"; // 1. Internal API functions for auth operations const authFunctions: AuthFunctions = internal.auth; @@ -64,7 +75,7 @@ export const authClient = createClient({ // Ensure every user has a username, filling in a simple fallback const username = data.username?.trim() || - data.email?.split('@')[0] || + data.email?.split("@")[0] || `user-${Date.now()}`; return { @@ -75,7 +86,7 @@ export const authClient = createClient({ onCreate: async (ctx, user) => { // Direct access to your database // Example: Create personal organization - const orgId = await ctx.db.insert('organization', { + const orgId = await ctx.db.insert("organization", { name: `${user.name}'s Workspace`, slug: `personal-${user._id}`, // ... other fields @@ -112,18 +123,15 @@ export const authClient = createClient({ }, }); -// 3. Create auth configuration (with options for HTTP-only mode) -export const createAuth = ( - ctx: GenericCtx, - { optionsOnly } = { optionsOnly: false } -) => { - const baseURL = process.env.NEXT_PUBLIC_SITE_URL!; - - return betterAuth({ - baseURL, - logger: { disabled: optionsOnly }, +// 3. Auth options factory +export const createAuthOptions = (ctx: GenericCtx) => + ({ + baseURL: process.env.SITE_URL!, plugins: [ - convex(), // Required + convex({ + authConfig, + jwks: process.env.JWKS, + }), admin(), organization({ // Organization plugin config @@ -135,17 +143,17 @@ export const createAuth = ( }, database: authClient.httpAdapter(ctx), // ... other config (social providers, user fields, etc.) - }); -}; + }) satisfies BetterAuthOptions; -// 4. Static auth instance for configuration -export const auth = createAuth({} as any, { optionsOnly: true }); +// 4. Create auth instance +export const createAuth = (ctx: GenericCtx) => + betterAuth(createAuthOptions(ctx)); // 5. IMPORTANT: Use getAuth for queries/mutations (direct DB access) export const getAuth = (ctx: Ctx) => { return betterAuth({ - ...auth.options, - database: authClient.adapter(ctx, auth.options), + ...createAuthOptions({} as any), + database: authClient.adapter(ctx, createAuthOptions), }); }; @@ -168,8 +176,9 @@ export const { findOne, updateMany, updateOne, -} = createApi(schema, { - ...auth.options, + getLatestJwks, + rotateKeys, +} = createApi(schema, createAuth, { // Optional: Skip input validation for smaller generated types // Since these are internal functions, validation is optional skipValidation: true, @@ -184,8 +193,7 @@ export const { // triggers: { ... } // }); // -// export const { create, ... } = createApi(schema, { -// ...auth.options, +// export const { create, ... } = createApi(schema, createAuth, { // internalMutation: myCustomInternalMutation, // }); ``` @@ -194,9 +202,9 @@ The trigger API exposes both `before*` and `on*` hooks. The `before` variants ru ```ts // convex/http.ts -import { httpRouter } from 'convex/server'; -import { registerRoutes } from 'better-auth-convex'; -import { createAuth } from './auth'; +import { httpRouter } from "convex/server"; +import { registerRoutes } from "better-auth-convex"; +import { createAuth } from "./auth"; const http = httpRouter(); @@ -205,6 +213,24 @@ registerRoutes(http, createAuth); export default http; ``` +### Generate JWKS + +After deploying, generate and set the JWKS env var: + +```bash +# Development +npx convex run auth:getLatestJwks | npx convex env set JWKS + +# Production +npx convex run auth:getLatestJwks --prod | npx convex env set JWKS --prod +``` + +To rotate keys (invalidates all existing tokens, forces re-authentication): + +```bash +npx convex run auth:rotateKeys | npx convex env set JWKS +``` + ## Key Concepts ### Direct DB Access vs HTTP Adapter @@ -247,7 +273,7 @@ export const someAction = action({ All helpers are exported from the main package: ```ts -import { getAuthUserId, getSession, getHeaders } from 'better-auth-convex'; +import { getAuthUserId, getSession, getHeaders } from "better-auth-convex"; // Get current user ID const userId = await getAuthUserId(ctx); @@ -266,8 +292,7 @@ const headers = await getHeaders(ctx); The `createApi` function accepts a `skipValidation` option that uses generic validators instead of typed validators: ```ts -export const { create, ... } = createApi(schema, { - ...auth.options, +export const { create, ... } = createApi(schema, createAuth, { skipValidation: true, // Smaller generated types }); ``` @@ -281,6 +306,7 @@ Both `createClient` and `createApi` accept an optional `internalMutation` parame ### Use Cases This is useful when you need to: + - Wrap database operations with custom context (e.g., triggers, logging) - Apply middleware to all auth mutations - Inject dependencies or configuration @@ -311,8 +337,7 @@ export const authClient = createClient({ }); // Pass to createApi -export const { create, updateOne, ... } = createApi(schema, { - ...auth.options, +export const { create, updateOne, ... } = createApi(schema, createAuth, { internalMutation, // Use same custom mutation builder }); ``` @@ -332,8 +357,8 @@ cd convex && npx @better-auth/cli generate -y --output authSchema.ts Import the generated schema in your `convex/schema.ts`: ```ts -import { authSchema } from './authSchema'; -import { defineSchema } from 'convex/server'; +import { authSchema } from "./authSchema"; +import { defineSchema } from "convex/server"; export default defineSchema({ ...authSchema, @@ -347,15 +372,15 @@ Alternatively, use the generated schema as a reference to manually update your e ```ts // Example: Adding a missing field discovered from generated schema -import { defineSchema, defineTable } from 'convex/server'; -import { v } from 'convex/values'; +import { defineSchema, defineTable } from "convex/server"; +import { v } from "convex/values"; export default defineSchema({ user: defineTable({ // ... existing fields twoFactorEnabled: v.optional(v.union(v.null(), v.boolean())), // New field from Better Auth update // ... rest of your schema - }).index('email_name', ['email', 'name']), + }).index("email_name", ["email", "name"]), // ... other indexes }); ``` @@ -366,13 +391,13 @@ Better Auth may log warnings about missing indexes for certain queries. You can ```ts // convex/schema.ts -import { authSchema } from './authSchema'; -import { defineSchema } from 'convex/server'; +import { authSchema } from "./authSchema"; +import { defineSchema } from "convex/server"; export default defineSchema({ ...authSchema, // Override with custom indexes - user: authSchema.user.index('username', ['username']), + user: authSchema.user.index("username", ["username"]), // Your other tables }); ``` @@ -381,4 +406,4 @@ export default defineSchema({ ## Credits -Built on top of [Better Auth](https://better-auth.com) and [@convex-dev/better-auth](https://github.com/get-convex/better-auth), optimized for [Convex](https://convex.dev). +Built on top of [Better Auth](https://www.better-auth.com) and [@convex-dev/better-auth](https://labs.convex.dev/better-auth), optimized for [Convex](https://www.convex.dev). diff --git a/bun.lock b/bun.lock index c1b4286..08323fa 100644 --- a/bun.lock +++ b/bun.lock @@ -25,7 +25,7 @@ "ultracite": "6.3.9", }, "peerDependencies": { - "@convex-dev/better-auth": "^0.9.11", + "@convex-dev/better-auth": ">=0.9.11", }, }, }, diff --git a/package.json b/package.json index 5d35c0b..43b1f2d 100644 --- a/package.json +++ b/package.json @@ -64,7 +64,7 @@ "ultracite": "6.3.9" }, "peerDependencies": { - "@convex-dev/better-auth": ">=0.9.11" + "@convex-dev/better-auth": ">=0.10.4" }, "packageManager": "bun@1.3.3", "publishConfig": { diff --git a/src/adapterUtils.ts b/src/adapter-utils.ts similarity index 100% rename from src/adapterUtils.ts rename to src/adapter-utils.ts diff --git a/src/adapter.ts b/src/adapter.ts index be7b034..1ee0366 100644 --- a/src/adapter.ts +++ b/src/adapter.ts @@ -26,8 +26,8 @@ import { findOneHandler, updateManyHandler, updateOneHandler, -} from './api'; -import type { AuthFunctions, Triggers } from './client'; +} from './create-api'; +import type { AuthFunctions, Triggers } from './create-client'; export const handlePagination = async ( next: ({ @@ -124,10 +124,9 @@ export const adapterConfig = { supportsNumericIds: false, transaction: false, usePlural: false, - // With supportsDates: false, dates are stored as strings, - // we convert them to numbers here. This aligns with how - // Convex stores _creationTime, and avoids a breaking change. + // Dates provided as strings supportsDates: false, + // Convert dates to numbers. This aligns with how Convex stores _creationTime and avoids a breaking change. customTransformInput: ({ data, fieldAttributes }) => { if (data && fieldAttributes.type === 'date') { return new Date(data).getTime(); @@ -228,7 +227,7 @@ export const httpAdapter = < }); }, createSchema: async ({ file, tables }) => { - const { createSchema } = await import('./createSchema'); + const { createSchema } = await import('./create-schema'); return createSchema({ file, tables }); }, @@ -425,7 +424,7 @@ export const dbAdapter = < Schema extends SchemaDefinition, >( ctx: GenericCtx, - options: BetterAuthOptions, + createAuthOptions: (ctx: any) => BetterAuthOptions, { authFunctions, debugLogs, @@ -438,7 +437,7 @@ export const dbAdapter = < triggers?: Triggers; } ) => { - const betterAuthSchema = getAuthTables(options); + const betterAuthSchema = getAuthTables(createAuthOptions({} as any)); return createAdapterFactory({ config: { @@ -519,7 +518,7 @@ export const dbAdapter = < ); }, createSchema: async ({ file, tables }) => { - const { createSchema } = await import('./createSchema'); + const { createSchema } = await import('./create-schema'); return createSchema({ file, tables }); }, diff --git a/src/api.ts b/src/create-api.ts similarity index 95% rename from src/api.ts rename to src/create-api.ts index 9ddb13a..02e5ada 100644 --- a/src/api.ts +++ b/src/create-api.ts @@ -1,8 +1,7 @@ -import type { BetterAuthOptions } from 'better-auth'; - import { getAuthTables } from 'better-auth/db'; import { type FunctionHandle, + internalActionGeneric, internalMutationGeneric, internalQueryGeneric, paginationOptsValidator, @@ -19,7 +18,8 @@ import { listOne, paginate, selectFields, -} from './adapterUtils'; +} from './adapter-utils'; +import type { CreateAuth } from './types'; type Schema = SchemaDefinition; @@ -391,17 +391,15 @@ export const deleteManyHandler = async ( export const createApi = >( schema: Schema, - { - internalMutation, - skipValidation, - ...authOptions - }: BetterAuthOptions & { + createAuth: CreateAuth, + options?: { internalMutation?: typeof internalMutationGeneric; /** Skip input validation for smaller generated types. Since these are internal functions, validation is optional. */ skipValidation?: boolean; } ) => { - const betterAuthSchema = getAuthTables(authOptions); + const betterAuthSchema = getAuthTables(createAuth({} as any).options); + const { internalMutation, skipValidation } = options ?? {}; const mutationBuilder = internalMutation ?? internalMutationGeneric; // Generic validators for skipValidation mode (much smaller generated types) @@ -547,5 +545,21 @@ export const createApi = >( handler: async (ctx, args) => updateOneHandler(ctx, args, schema, betterAuthSchema), }), + getLatestJwks: mutationBuilder({ + args: {}, + handler: async (ctx) => { + const auth = createAuth(ctx); + + return (auth.api as any).getLatestJwks(); + }, + }), + rotateKeys: internalActionGeneric({ + args: {}, + handler: async (ctx) => { + const auth = createAuth(ctx); + + return (auth.api as any).rotateKeys(); + }, + }), }; }; diff --git a/src/client.ts b/src/create-client.ts similarity index 97% rename from src/client.ts rename to src/create-client.ts index 32ef12a..63667d6 100644 --- a/src/client.ts +++ b/src/create-client.ts @@ -84,8 +84,10 @@ export const createClient = < }) => ({ authFunctions: config.authFunctions, triggers: config.triggers, - adapter: (ctx: GenericCtx, options: BetterAuthOptions) => - dbAdapter(ctx, options, config), + adapter: ( + ctx: GenericCtx, + createAuthOptions: (ctx: any) => BetterAuthOptions + ) => dbAdapter(ctx, createAuthOptions, config), httpAdapter: (ctx: GenericCtx) => httpAdapter(ctx, config), triggersApi: () => { const mutationBuilder = config.internalMutation ?? internalMutationGeneric; diff --git a/src/createSchema.ts b/src/create-schema.ts similarity index 99% rename from src/createSchema.ts rename to src/create-schema.ts index 0828a9c..315260b 100644 --- a/src/createSchema.ts +++ b/src/create-schema.ts @@ -20,7 +20,7 @@ const specialFields = (tables: BetterAuthDBSchema) => const fields = Object.fromEntries( Object.entries(table.fields) .map(([fieldKey, field]) => [ - fieldKey, + field.fieldName ?? fieldKey, { ...(field.sortable ? { sortable: true } : {}), ...(field.unique ? { unique: true } : {}), diff --git a/src/index.ts b/src/index.ts index 528a993..c9383b6 100644 --- a/src/index.ts +++ b/src/index.ts @@ -3,9 +3,10 @@ */ export * from './adapter'; -export * from './adapterUtils'; -export * from './api'; -export * from './client'; -export * from './createSchema'; +export * from './adapter-utils'; +export * from './create-api'; +export * from './create-client'; +export * from './create-schema'; export * from './helpers'; export * from './registerRoutes'; +export * from './types'; diff --git a/src/registerRoutes.ts b/src/registerRoutes.ts index b6b22ee..501b083 100644 --- a/src/registerRoutes.ts +++ b/src/registerRoutes.ts @@ -1,17 +1,8 @@ /** biome-ignore-all lint/suspicious/noConsole: lib */ -import type { betterAuth } from 'better-auth'; import { type HttpRouter, httpActionGeneric } from 'convex/server'; import { corsRouter } from 'convex-helpers/server/cors'; -export type CreateAuth = - | ((ctx: any) => ReturnType) - | (( - ctx: any, - opts?: { optionsOnly?: boolean } - ) => ReturnType); - -export const getStaticAuth = (createAuth: CreateAuth) => - createAuth({}, { optionsOnly: true }); +import type { CreateAuth } from './types'; export const registerRoutes = ( http: HttpRouter, @@ -19,8 +10,8 @@ export const registerRoutes = ( opts: { cors?: | { - allowedHeaders?: string[]; // These values are appended to the default values + allowedHeaders?: string[]; allowedOrigins?: string[]; exposedHeaders?: string[]; } @@ -28,7 +19,7 @@ export const registerRoutes = ( verbose?: boolean; } = {} ) => { - const staticAuth = getStaticAuth(createAuth); + const staticAuth = createAuth({} as any); const path = staticAuth.options.basePath ?? '/api/auth'; const authRequestHandler = httpActionGeneric(async (ctx, request) => { if (opts?.verbose) { diff --git a/src/types.ts b/src/types.ts new file mode 100644 index 0000000..1d102aa --- /dev/null +++ b/src/types.ts @@ -0,0 +1,3 @@ +import type { betterAuth } from 'better-auth'; + +export type CreateAuth = (ctx: any) => ReturnType;