@neutralauth/internal-auth 0.10.11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +201 -0
- package/README.md +39 -0
- package/dist/auth-config.d.ts +43 -0
- package/dist/auth-config.d.ts.map +1 -0
- package/dist/auth-config.js +43 -0
- package/dist/auth-config.js.map +1 -0
- package/dist/auth-options.d.ts +3 -0
- package/dist/auth-options.d.ts.map +1 -0
- package/dist/auth-options.js +40 -0
- package/dist/auth-options.js.map +1 -0
- package/dist/auth.d.ts +2 -0
- package/dist/auth.d.ts.map +1 -0
- package/dist/auth.js +4 -0
- package/dist/auth.js.map +1 -0
- package/dist/client/adapter-utils.d.ts +66 -0
- package/dist/client/adapter-utils.d.ts.map +1 -0
- package/dist/client/adapter-utils.js +437 -0
- package/dist/client/adapter-utils.js.map +1 -0
- package/dist/client/adapter.d.ts +14 -0
- package/dist/client/adapter.d.ts.map +1 -0
- package/dist/client/adapter.js +274 -0
- package/dist/client/adapter.js.map +1 -0
- package/dist/client/create-api.d.ts +141 -0
- package/dist/client/create-api.d.ts.map +1 -0
- package/dist/client/create-api.js +205 -0
- package/dist/client/create-api.js.map +1 -0
- package/dist/client/create-client.d.ts +183 -0
- package/dist/client/create-client.d.ts.map +1 -0
- package/dist/client/create-client.js +311 -0
- package/dist/client/create-client.js.map +1 -0
- package/dist/client/create-schema.d.ts +19 -0
- package/dist/client/create-schema.d.ts.map +1 -0
- package/dist/client/create-schema.js +114 -0
- package/dist/client/create-schema.js.map +1 -0
- package/dist/client/index.d.ts +7 -0
- package/dist/client/index.d.ts.map +1 -0
- package/dist/client/index.js +10 -0
- package/dist/client/index.js.map +1 -0
- package/dist/client/plugins/index.d.ts +3 -0
- package/dist/client/plugins/index.d.ts.map +1 -0
- package/dist/client/plugins/index.js +3 -0
- package/dist/client/plugins/index.js.map +1 -0
- package/dist/component/_generated/api.d.ts +36 -0
- package/dist/component/_generated/api.d.ts.map +1 -0
- package/dist/component/_generated/api.js +31 -0
- package/dist/component/_generated/api.js.map +1 -0
- package/dist/component/_generated/component.d.ts +787 -0
- package/dist/component/_generated/component.d.ts.map +1 -0
- package/dist/component/_generated/component.js +11 -0
- package/dist/component/_generated/component.js.map +1 -0
- package/dist/component/_generated/dataModel.d.ts +46 -0
- package/dist/component/_generated/dataModel.d.ts.map +1 -0
- package/dist/component/_generated/dataModel.js +11 -0
- package/dist/component/_generated/dataModel.js.map +1 -0
- package/dist/component/_generated/server.d.ts +121 -0
- package/dist/component/_generated/server.d.ts.map +1 -0
- package/dist/component/_generated/server.js +78 -0
- package/dist/component/_generated/server.js.map +1 -0
- package/dist/component/adapter.d.ts +130 -0
- package/dist/component/adapter.d.ts.map +1 -0
- package/dist/component/adapter.js +5 -0
- package/dist/component/adapter.js.map +1 -0
- package/dist/component/adapterTest.d.ts +10 -0
- package/dist/component/adapterTest.d.ts.map +1 -0
- package/dist/component/adapterTest.js +409 -0
- package/dist/component/adapterTest.js.map +1 -0
- package/dist/component/convex.config.d.ts +3 -0
- package/dist/component/convex.config.d.ts.map +1 -0
- package/dist/component/convex.config.js +4 -0
- package/dist/component/convex.config.js.map +1 -0
- package/dist/component/schema.d.ts +474 -0
- package/dist/component/schema.d.ts.map +1 -0
- package/dist/component/schema.js +139 -0
- package/dist/component/schema.js.map +1 -0
- package/dist/nextjs/client.d.ts +4 -0
- package/dist/nextjs/client.d.ts.map +1 -0
- package/dist/nextjs/client.js +37 -0
- package/dist/nextjs/client.js.map +1 -0
- package/dist/nextjs/index.d.ts +22 -0
- package/dist/nextjs/index.d.ts.map +1 -0
- package/dist/nextjs/index.js +98 -0
- package/dist/nextjs/index.js.map +1 -0
- package/dist/plugins/convex/client.d.ts +6 -0
- package/dist/plugins/convex/client.d.ts.map +1 -0
- package/dist/plugins/convex/client.js +7 -0
- package/dist/plugins/convex/client.js.map +1 -0
- package/dist/plugins/convex/index.d.ts +322 -0
- package/dist/plugins/convex/index.d.ts.map +1 -0
- package/dist/plugins/convex/index.js +422 -0
- package/dist/plugins/convex/index.js.map +1 -0
- package/dist/plugins/cross-domain/client.d.ts +132 -0
- package/dist/plugins/cross-domain/client.d.ts.map +1 -0
- package/dist/plugins/cross-domain/client.js +192 -0
- package/dist/plugins/cross-domain/client.js.map +1 -0
- package/dist/plugins/cross-domain/index.d.ts +51 -0
- package/dist/plugins/cross-domain/index.d.ts.map +1 -0
- package/dist/plugins/cross-domain/index.js +173 -0
- package/dist/plugins/cross-domain/index.js.map +1 -0
- package/dist/plugins/index.d.ts +3 -0
- package/dist/plugins/index.d.ts.map +1 -0
- package/dist/plugins/index.js +3 -0
- package/dist/plugins/index.js.map +1 -0
- package/dist/react/index.d.ts +80 -0
- package/dist/react/index.d.ts.map +1 -0
- package/dist/react/index.js +190 -0
- package/dist/react/index.js.map +1 -0
- package/dist/react-start/index.d.ts +13 -0
- package/dist/react-start/index.d.ts.map +1 -0
- package/dist/react-start/index.js +101 -0
- package/dist/react-start/index.js.map +1 -0
- package/dist/utils/index.d.ts +33 -0
- package/dist/utils/index.d.ts.map +1 -0
- package/dist/utils/index.js +91 -0
- package/dist/utils/index.js.map +1 -0
- package/package.json +208 -0
- package/src/auth-config.ts +80 -0
- package/src/auth-options.ts +54 -0
- package/src/auth.ts +4 -0
- package/src/client/adapter-utils.ts +639 -0
- package/src/client/adapter.test.ts +83 -0
- package/src/client/adapter.ts +363 -0
- package/src/client/create-api.ts +339 -0
- package/src/client/create-client.ts +452 -0
- package/src/client/create-schema.ts +166 -0
- package/src/client/index.ts +22 -0
- package/src/client/plugins/index.ts +2 -0
- package/src/component/_generated/api.ts +52 -0
- package/src/component/_generated/component.ts +2008 -0
- package/src/component/_generated/dataModel.ts +60 -0
- package/src/component/_generated/server.ts +161 -0
- package/src/component/adapter.ts +13 -0
- package/src/component/adapterTest.ts +505 -0
- package/src/component/convex.config.ts +5 -0
- package/src/component/schema.ts +142 -0
- package/src/nextjs/client.tsx +54 -0
- package/src/nextjs/index.ts +152 -0
- package/src/plugins/convex/client.ts +9 -0
- package/src/plugins/convex/index.ts +596 -0
- package/src/plugins/cross-domain/client.test.ts +217 -0
- package/src/plugins/cross-domain/client.ts +234 -0
- package/src/plugins/cross-domain/index.ts +199 -0
- package/src/plugins/index.ts +2 -0
- package/src/react/index.tsx +304 -0
- package/src/react-start/index.ts +153 -0
- package/src/react-start/vite-env.d.ts +2 -0
- package/src/test.ts +18 -0
- package/src/utils/index.ts +171 -0
|
@@ -0,0 +1,596 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
BetterAuthPlugin,
|
|
3
|
+
Session,
|
|
4
|
+
User,
|
|
5
|
+
} from "better-auth";
|
|
6
|
+
import type { BetterAuthOptions } from "better-auth/minimal";
|
|
7
|
+
import { createAuthMiddleware, sessionMiddleware } from "better-auth/api";
|
|
8
|
+
import {
|
|
9
|
+
createAuthEndpoint,
|
|
10
|
+
jwt as jwtPlugin,
|
|
11
|
+
bearer as bearerPlugin,
|
|
12
|
+
oidcProvider as oidcProviderPlugin,
|
|
13
|
+
} from "better-auth/plugins";
|
|
14
|
+
import type { JwtOptions, Jwk } from "better-auth/plugins";
|
|
15
|
+
import { omit } from "convex-helpers";
|
|
16
|
+
import type { AuthConfig, AuthProvider } from "convex/server";
|
|
17
|
+
|
|
18
|
+
export const JWT_COOKIE_NAME = "convex_jwt";
|
|
19
|
+
|
|
20
|
+
const getJwksAlg = (authProvider: AuthProvider) => {
|
|
21
|
+
const isCustomJwt =
|
|
22
|
+
"type" in authProvider && authProvider.type === "customJwt";
|
|
23
|
+
if (isCustomJwt && authProvider.algorithm !== "RS256") {
|
|
24
|
+
throw new Error("Only RS256 is supported for custom JWT with Better Auth");
|
|
25
|
+
}
|
|
26
|
+
return isCustomJwt ? authProvider.algorithm : "EdDSA";
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
const parseAuthConfig = (authConfig: AuthConfig, opts: { jwks?: string }) => {
|
|
30
|
+
const providerConfigs = authConfig.providers.filter(
|
|
31
|
+
(provider) => provider.applicationID === "convex"
|
|
32
|
+
);
|
|
33
|
+
if (providerConfigs.length > 1) {
|
|
34
|
+
throw new Error(
|
|
35
|
+
"Multiple auth providers with applicationID 'convex' detected. Please use only one."
|
|
36
|
+
);
|
|
37
|
+
}
|
|
38
|
+
const providerConfig = providerConfigs[0];
|
|
39
|
+
if (!providerConfig) {
|
|
40
|
+
throw new Error(
|
|
41
|
+
"No auth provider with applicationID 'convex' found. Please add one to your auth config."
|
|
42
|
+
);
|
|
43
|
+
}
|
|
44
|
+
if (!("type" in providerConfig) || providerConfig.type !== "customJwt") {
|
|
45
|
+
return providerConfig;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const isDataUriJwks = providerConfig.jwks?.startsWith("data:text/");
|
|
49
|
+
|
|
50
|
+
if (isDataUriJwks && !opts.jwks) {
|
|
51
|
+
throw new Error(
|
|
52
|
+
"Static JWKS detected in auth config, but missing from Convex plugin"
|
|
53
|
+
);
|
|
54
|
+
}
|
|
55
|
+
if (!isDataUriJwks && opts.jwks) {
|
|
56
|
+
// eslint-disable-next-line no-console
|
|
57
|
+
console.warn(
|
|
58
|
+
"Static JWKS provided to Convex plugin, but not to auth config. This adds an unnecessary network request for token verification."
|
|
59
|
+
);
|
|
60
|
+
}
|
|
61
|
+
return providerConfig;
|
|
62
|
+
};
|
|
63
|
+
|
|
64
|
+
export const convex = (opts: {
|
|
65
|
+
/**
|
|
66
|
+
* @param {AuthConfig} authConfig - Auth config from your Convex project.
|
|
67
|
+
*
|
|
68
|
+
* Typically found in `convex/auth.config.ts`.
|
|
69
|
+
*
|
|
70
|
+
* @example
|
|
71
|
+
* ```ts
|
|
72
|
+
* // convex/auth.config.ts
|
|
73
|
+
* export default {
|
|
74
|
+
* providers: [getAuthConfigProvider({ jwks: process.env.JWKS })],
|
|
75
|
+
* } satisfies AuthConfig;
|
|
76
|
+
* ```
|
|
77
|
+
*
|
|
78
|
+
* @example
|
|
79
|
+
* ```ts
|
|
80
|
+
* // convex/auth.ts
|
|
81
|
+
* import authConfig from './auth.config';
|
|
82
|
+
* export const createAuth = (ctx: GenericCtx<DataModel>) => {
|
|
83
|
+
* return betterAuth({
|
|
84
|
+
* // ...
|
|
85
|
+
* plugins: [convex({ authConfig })],
|
|
86
|
+
* });
|
|
87
|
+
* };
|
|
88
|
+
* ```
|
|
89
|
+
*/
|
|
90
|
+
authConfig: AuthConfig;
|
|
91
|
+
/**
|
|
92
|
+
* @param {Object} jwt - JWT options.
|
|
93
|
+
* @param {number} jwt.expirationSeconds - JWT expiration seconds.
|
|
94
|
+
* @param {Function} jwt.definePayload - Function to define the JWT payload. `sessionId` and `iat` are added automatically.
|
|
95
|
+
*/
|
|
96
|
+
jwt?: {
|
|
97
|
+
expirationSeconds?: number;
|
|
98
|
+
definePayload?: (session: {
|
|
99
|
+
user: User & Record<string, any>;
|
|
100
|
+
session: Session & Record<string, any>;
|
|
101
|
+
}) => Promise<Record<string, any>> | Record<string, any> | undefined;
|
|
102
|
+
};
|
|
103
|
+
/**
|
|
104
|
+
* @deprecated Use jwt.expirationSeconds instead.
|
|
105
|
+
*/
|
|
106
|
+
jwtExpirationSeconds?: number;
|
|
107
|
+
/**
|
|
108
|
+
* @param {string} jwks - Optional static JWKS to avoid fetching from the database.
|
|
109
|
+
*
|
|
110
|
+
* This should be a stringified document from the Better Auth JWKS table. You
|
|
111
|
+
* can create one in the console.
|
|
112
|
+
*
|
|
113
|
+
* @example
|
|
114
|
+
* ```ts
|
|
115
|
+
* // convex/auth.ts
|
|
116
|
+
* export const rotateKeys = internalAction({
|
|
117
|
+
* args: {},
|
|
118
|
+
* handler: async (ctx) => {
|
|
119
|
+
* const auth = createAuth(ctx)
|
|
120
|
+
* return await auth.api.rotateKeys()
|
|
121
|
+
* },
|
|
122
|
+
* })
|
|
123
|
+
* ```
|
|
124
|
+
* Run the action and set the JWKS environment variable
|
|
125
|
+
*
|
|
126
|
+
* ```bash
|
|
127
|
+
* npx convex run auth:rotateKeys | npx convex env set JWKS
|
|
128
|
+
* ```
|
|
129
|
+
* Then use it in your auth config and Better Auth options:
|
|
130
|
+
*
|
|
131
|
+
* ```ts
|
|
132
|
+
* // convex/auth.config.ts
|
|
133
|
+
* export default {
|
|
134
|
+
* providers: [getAuthConfigProvider({ jwks: process.env.JWKS })],
|
|
135
|
+
* } satisfies AuthConfig;
|
|
136
|
+
*
|
|
137
|
+
* // convex/auth.ts
|
|
138
|
+
* export const createAuth = (ctx: GenericCtx<DataModel>) => {
|
|
139
|
+
* return betterAuth({
|
|
140
|
+
* // ...
|
|
141
|
+
* plugins: [convex({ authConfig, jwks: process.env.JWKS })],
|
|
142
|
+
* });
|
|
143
|
+
* };
|
|
144
|
+
* ```
|
|
145
|
+
*/
|
|
146
|
+
jwks?: string;
|
|
147
|
+
/**
|
|
148
|
+
* @param {boolean} jwksRotateOnTokenGenerationError - Whether to rotate the JWKS on token generation error.
|
|
149
|
+
*
|
|
150
|
+
* Does nothing if a static JWKS is provided.
|
|
151
|
+
*
|
|
152
|
+
* Handles error that occurs when existing JWKS key does not match configured
|
|
153
|
+
* algorithm, which will be common for 0.10 upgrades switching from EdDSA to RS256.
|
|
154
|
+
*
|
|
155
|
+
* @default true
|
|
156
|
+
*/
|
|
157
|
+
jwksRotateOnTokenGenerationError?: boolean;
|
|
158
|
+
/**
|
|
159
|
+
* @param {BetterAuthOptions} options - Better Auth options. Not required,
|
|
160
|
+
* currently used to pass the basePath to the oidcProvider plugin.
|
|
161
|
+
*/
|
|
162
|
+
options?: BetterAuthOptions;
|
|
163
|
+
}) => {
|
|
164
|
+
const jwtExpirationSeconds =
|
|
165
|
+
opts.jwt?.expirationSeconds ?? opts.jwtExpirationSeconds ?? 60 * 15;
|
|
166
|
+
const oidcProvider = oidcProviderPlugin({
|
|
167
|
+
loginPage: "/not-used",
|
|
168
|
+
metadata: {
|
|
169
|
+
issuer: `${process.env.CONVEX_SITE_URL}`,
|
|
170
|
+
jwks_uri: `${process.env.CONVEX_SITE_URL}${opts.options?.basePath ?? "/api/auth"}/convex/jwks`,
|
|
171
|
+
},
|
|
172
|
+
});
|
|
173
|
+
const providerConfig = parseAuthConfig(opts.authConfig, opts);
|
|
174
|
+
|
|
175
|
+
const jwtOptions = {
|
|
176
|
+
jwt: {
|
|
177
|
+
issuer: `${process.env.CONVEX_SITE_URL}`,
|
|
178
|
+
audience: "convex",
|
|
179
|
+
expirationTime: `${jwtExpirationSeconds}s`,
|
|
180
|
+
definePayload: ({ user, session }) => ({
|
|
181
|
+
...(opts.jwt?.definePayload
|
|
182
|
+
? opts.jwt.definePayload({ user, session })
|
|
183
|
+
: omit(user, ["id", "image"])),
|
|
184
|
+
sessionId: session.id,
|
|
185
|
+
iat: Math.floor(new Date().getTime() / 1000),
|
|
186
|
+
}),
|
|
187
|
+
},
|
|
188
|
+
jwks: {
|
|
189
|
+
keyPairConfig: {
|
|
190
|
+
alg: getJwksAlg(providerConfig),
|
|
191
|
+
},
|
|
192
|
+
},
|
|
193
|
+
} satisfies JwtOptions;
|
|
194
|
+
const jwks = opts.jwks ? JSON.parse(opts.jwks) : undefined;
|
|
195
|
+
const jwt = jwtPlugin({
|
|
196
|
+
...jwtOptions,
|
|
197
|
+
adapter: {
|
|
198
|
+
createJwk: async (webKey, ctx) => {
|
|
199
|
+
if (opts.jwks) {
|
|
200
|
+
throw new Error("Not implemented");
|
|
201
|
+
}
|
|
202
|
+
// TODO: remove when date parsing for jwks adapter is fixed upstream
|
|
203
|
+
return await ctx.context.adapter.create<Omit<Jwk, "id">, Jwk>({
|
|
204
|
+
model: "jwks",
|
|
205
|
+
data: {
|
|
206
|
+
...webKey,
|
|
207
|
+
createdAt: new Date(),
|
|
208
|
+
},
|
|
209
|
+
});
|
|
210
|
+
},
|
|
211
|
+
getJwks: async (ctx) => {
|
|
212
|
+
if (opts.jwks) {
|
|
213
|
+
return jwks;
|
|
214
|
+
}
|
|
215
|
+
// TODO: remove when date parsing for jwks adapter is fixed upstream
|
|
216
|
+
const keys: Jwk[] = await ctx.context.adapter.findMany<Jwk>({
|
|
217
|
+
model: "jwks",
|
|
218
|
+
sortBy: {
|
|
219
|
+
field: "createdAt",
|
|
220
|
+
direction: "desc",
|
|
221
|
+
},
|
|
222
|
+
});
|
|
223
|
+
return keys.map((key) => ({
|
|
224
|
+
...key,
|
|
225
|
+
createdAt: new Date(key.createdAt),
|
|
226
|
+
...(key.expiresAt ? { expiresAt: new Date(key.expiresAt) } : {}),
|
|
227
|
+
}));
|
|
228
|
+
},
|
|
229
|
+
},
|
|
230
|
+
});
|
|
231
|
+
// Bearer plugin converts the session token to a cookie
|
|
232
|
+
// for cross domain social login after code verification,
|
|
233
|
+
// and is required for the headers() helper to work.
|
|
234
|
+
const bearer = bearerPlugin();
|
|
235
|
+
const schema = {
|
|
236
|
+
user: {
|
|
237
|
+
fields: { userId: { type: "string", required: false, input: false } },
|
|
238
|
+
} as const,
|
|
239
|
+
...jwt.schema,
|
|
240
|
+
};
|
|
241
|
+
|
|
242
|
+
return {
|
|
243
|
+
id: "convex",
|
|
244
|
+
init: (ctx) => {
|
|
245
|
+
const { options, logger: _logger } = ctx;
|
|
246
|
+
if (options.basePath !== "/api/auth" && !opts.options?.basePath) {
|
|
247
|
+
// eslint-disable-next-line no-console
|
|
248
|
+
console.warn(
|
|
249
|
+
`Better Auth basePath set to ${options.basePath} but no basePath is set in the Convex plugin. This is probably a mistake.`
|
|
250
|
+
);
|
|
251
|
+
}
|
|
252
|
+
if (
|
|
253
|
+
opts.options?.basePath &&
|
|
254
|
+
options.basePath !== opts.options?.basePath
|
|
255
|
+
) {
|
|
256
|
+
// eslint-disable-next-line no-console
|
|
257
|
+
console.warn(
|
|
258
|
+
`Better Auth basePath ${options.basePath} does not match Convex plugin basePath ${opts.options?.basePath}. This is probably a mistake.`
|
|
259
|
+
);
|
|
260
|
+
}
|
|
261
|
+
},
|
|
262
|
+
hooks: {
|
|
263
|
+
before: [
|
|
264
|
+
...bearer.hooks.before,
|
|
265
|
+
// Don't attempt to refresh the session with a query ctx
|
|
266
|
+
{
|
|
267
|
+
matcher: (ctx) => {
|
|
268
|
+
return (
|
|
269
|
+
!ctx.context.adapter.options?.isRunMutationCtx &&
|
|
270
|
+
ctx.path === "/get-session"
|
|
271
|
+
);
|
|
272
|
+
},
|
|
273
|
+
handler: createAuthMiddleware(async (ctx) => {
|
|
274
|
+
ctx.query = { ...ctx.query, disableRefresh: true };
|
|
275
|
+
ctx.context.internalAdapter.deleteSession = async (
|
|
276
|
+
..._args: any[]
|
|
277
|
+
) => {
|
|
278
|
+
//skip
|
|
279
|
+
};
|
|
280
|
+
return { context: ctx };
|
|
281
|
+
}),
|
|
282
|
+
},
|
|
283
|
+
],
|
|
284
|
+
after: [
|
|
285
|
+
...oidcProvider.hooks.after,
|
|
286
|
+
{
|
|
287
|
+
matcher: (ctx) => {
|
|
288
|
+
return Boolean(
|
|
289
|
+
ctx.path.startsWith("/sign-in") ||
|
|
290
|
+
ctx.path.startsWith("/sign-up") ||
|
|
291
|
+
ctx.path.startsWith("/callback") ||
|
|
292
|
+
ctx.path.startsWith("/oauth2/callback") ||
|
|
293
|
+
ctx.path.startsWith("/magic-link/verify") ||
|
|
294
|
+
ctx.path.startsWith("/email-otp/verify-email") ||
|
|
295
|
+
ctx.path.startsWith("/phone-number/verify") ||
|
|
296
|
+
ctx.path.startsWith("/siwe/verify") ||
|
|
297
|
+
(ctx.path.startsWith("/get-session") && ctx.context.session)
|
|
298
|
+
);
|
|
299
|
+
},
|
|
300
|
+
handler: createAuthMiddleware(async (ctx) => {
|
|
301
|
+
// Set jwt cookie at login for authenticated ssr
|
|
302
|
+
const originalSession = ctx.context.session;
|
|
303
|
+
try {
|
|
304
|
+
ctx.context.session =
|
|
305
|
+
ctx.context.session ?? ctx.context.newSession;
|
|
306
|
+
const { token } = await jwt.endpoints.getToken({
|
|
307
|
+
...ctx,
|
|
308
|
+
headers: {},
|
|
309
|
+
method: "GET",
|
|
310
|
+
returnHeaders: false,
|
|
311
|
+
returnStatus: false,
|
|
312
|
+
});
|
|
313
|
+
const jwtCookie = ctx.context.createAuthCookie(JWT_COOKIE_NAME, {
|
|
314
|
+
maxAge: jwtExpirationSeconds,
|
|
315
|
+
});
|
|
316
|
+
ctx.setCookie(jwtCookie.name, token, jwtCookie.attributes);
|
|
317
|
+
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|
318
|
+
} catch (_err) {
|
|
319
|
+
// no-op, some sign-in calls (eg., when redirecting to 2fa)
|
|
320
|
+
// 401 here
|
|
321
|
+
}
|
|
322
|
+
ctx.context.session = originalSession;
|
|
323
|
+
}),
|
|
324
|
+
},
|
|
325
|
+
{
|
|
326
|
+
matcher: (ctx) => {
|
|
327
|
+
return (
|
|
328
|
+
ctx.path?.startsWith("/sign-out") ||
|
|
329
|
+
ctx.path?.startsWith("/delete-user") ||
|
|
330
|
+
(ctx.path?.startsWith("/get-session") && !ctx.context.session)
|
|
331
|
+
);
|
|
332
|
+
},
|
|
333
|
+
handler: createAuthMiddleware(async (ctx) => {
|
|
334
|
+
const jwtCookie = ctx.context.createAuthCookie(JWT_COOKIE_NAME, {
|
|
335
|
+
maxAge: 0,
|
|
336
|
+
});
|
|
337
|
+
ctx.setCookie(jwtCookie.name, "", jwtCookie.attributes);
|
|
338
|
+
}),
|
|
339
|
+
},
|
|
340
|
+
],
|
|
341
|
+
},
|
|
342
|
+
endpoints: {
|
|
343
|
+
getOpenIdConfig: createAuthEndpoint(
|
|
344
|
+
"/convex/.well-known/openid-configuration",
|
|
345
|
+
{
|
|
346
|
+
method: "GET",
|
|
347
|
+
metadata: {
|
|
348
|
+
isAction: false,
|
|
349
|
+
},
|
|
350
|
+
// TODO: properly type this
|
|
351
|
+
},
|
|
352
|
+
async (ctx) => {
|
|
353
|
+
const response = await oidcProvider.endpoints.getOpenIdConfig({
|
|
354
|
+
...ctx,
|
|
355
|
+
returnHeaders: false,
|
|
356
|
+
returnStatus: false,
|
|
357
|
+
});
|
|
358
|
+
return response;
|
|
359
|
+
}
|
|
360
|
+
),
|
|
361
|
+
getJwks: createAuthEndpoint(
|
|
362
|
+
"/convex/jwks",
|
|
363
|
+
{
|
|
364
|
+
method: "GET",
|
|
365
|
+
metadata: {
|
|
366
|
+
openapi: {
|
|
367
|
+
description: "Get the JSON Web Key Set",
|
|
368
|
+
responses: {
|
|
369
|
+
"200": {
|
|
370
|
+
description: "JSON Web Key Set retrieved successfully",
|
|
371
|
+
content: {
|
|
372
|
+
"application/json": {
|
|
373
|
+
schema: {
|
|
374
|
+
type: "object",
|
|
375
|
+
properties: {
|
|
376
|
+
keys: {
|
|
377
|
+
type: "array",
|
|
378
|
+
description: "Array of public JSON Web Keys",
|
|
379
|
+
items: {
|
|
380
|
+
type: "object",
|
|
381
|
+
properties: {
|
|
382
|
+
kid: {
|
|
383
|
+
type: "string",
|
|
384
|
+
description:
|
|
385
|
+
"Key ID uniquely identifying the key, corresponds to the 'id' from the stored Jwk",
|
|
386
|
+
},
|
|
387
|
+
kty: {
|
|
388
|
+
type: "string",
|
|
389
|
+
description:
|
|
390
|
+
"Key type (e.g., 'RSA', 'EC', 'OKP')",
|
|
391
|
+
},
|
|
392
|
+
alg: {
|
|
393
|
+
type: "string",
|
|
394
|
+
description:
|
|
395
|
+
"Algorithm intended for use with the key (e.g., 'EdDSA', 'RS256')",
|
|
396
|
+
},
|
|
397
|
+
use: {
|
|
398
|
+
type: "string",
|
|
399
|
+
description:
|
|
400
|
+
"Intended use of the public key (e.g., 'sig' for signature)",
|
|
401
|
+
enum: ["sig"],
|
|
402
|
+
nullable: true,
|
|
403
|
+
},
|
|
404
|
+
n: {
|
|
405
|
+
type: "string",
|
|
406
|
+
description:
|
|
407
|
+
"Modulus for RSA keys (base64url-encoded)",
|
|
408
|
+
nullable: true,
|
|
409
|
+
},
|
|
410
|
+
e: {
|
|
411
|
+
type: "string",
|
|
412
|
+
description:
|
|
413
|
+
"Exponent for RSA keys (base64url-encoded)",
|
|
414
|
+
nullable: true,
|
|
415
|
+
},
|
|
416
|
+
crv: {
|
|
417
|
+
type: "string",
|
|
418
|
+
description:
|
|
419
|
+
"Curve name for elliptic curve keys (e.g., 'Ed25519', 'P-256')",
|
|
420
|
+
nullable: true,
|
|
421
|
+
},
|
|
422
|
+
x: {
|
|
423
|
+
type: "string",
|
|
424
|
+
description:
|
|
425
|
+
"X coordinate for elliptic curve keys (base64url-encoded)",
|
|
426
|
+
nullable: true,
|
|
427
|
+
},
|
|
428
|
+
y: {
|
|
429
|
+
type: "string",
|
|
430
|
+
description:
|
|
431
|
+
"Y coordinate for elliptic curve keys (base64url-encoded)",
|
|
432
|
+
nullable: true,
|
|
433
|
+
},
|
|
434
|
+
},
|
|
435
|
+
required: ["kid", "kty", "alg"],
|
|
436
|
+
},
|
|
437
|
+
},
|
|
438
|
+
},
|
|
439
|
+
required: ["keys"],
|
|
440
|
+
},
|
|
441
|
+
},
|
|
442
|
+
},
|
|
443
|
+
},
|
|
444
|
+
},
|
|
445
|
+
},
|
|
446
|
+
},
|
|
447
|
+
},
|
|
448
|
+
async (ctx) => {
|
|
449
|
+
const response = await jwt.endpoints.getJwks({
|
|
450
|
+
...ctx,
|
|
451
|
+
returnHeaders: false,
|
|
452
|
+
returnStatus: false,
|
|
453
|
+
});
|
|
454
|
+
return response;
|
|
455
|
+
}
|
|
456
|
+
),
|
|
457
|
+
getLatestJwks: createAuthEndpoint(
|
|
458
|
+
// This path is inaccessible due to SERVER_ONLY: true, it's here to
|
|
459
|
+
// avoid errors that occur in all matchers when path is undefined.
|
|
460
|
+
"/convex/latest-jwks",
|
|
461
|
+
{
|
|
462
|
+
isAction: true,
|
|
463
|
+
method: "POST",
|
|
464
|
+
metadata: {
|
|
465
|
+
SERVER_ONLY: true,
|
|
466
|
+
openapi: {
|
|
467
|
+
description:
|
|
468
|
+
"Delete and regenerate JWKS, and return the new JWKS for static usage",
|
|
469
|
+
},
|
|
470
|
+
},
|
|
471
|
+
},
|
|
472
|
+
async (ctx) => {
|
|
473
|
+
// Ensure at least one key exists
|
|
474
|
+
await jwtPlugin(jwtOptions).endpoints.getJwks({
|
|
475
|
+
...ctx,
|
|
476
|
+
method: "GET",
|
|
477
|
+
});
|
|
478
|
+
const jwks: any[] = await ctx.context.adapter.findMany({
|
|
479
|
+
model: "jwks",
|
|
480
|
+
limit: 1,
|
|
481
|
+
sortBy: {
|
|
482
|
+
field: "createdAt",
|
|
483
|
+
direction: "desc",
|
|
484
|
+
},
|
|
485
|
+
});
|
|
486
|
+
// Add alg to jwks, otherwise Better Auth will default to EdDSA
|
|
487
|
+
jwks[0].alg = jwtOptions.jwks.keyPairConfig.alg;
|
|
488
|
+
return jwks;
|
|
489
|
+
}
|
|
490
|
+
),
|
|
491
|
+
rotateKeys: createAuthEndpoint(
|
|
492
|
+
// This path is inaccessible due to SERVER_ONLY: true, it's here to
|
|
493
|
+
// avoid errors that occur in all matchers when path is undefined.
|
|
494
|
+
"/convex/rotate-keys",
|
|
495
|
+
{
|
|
496
|
+
isAction: true,
|
|
497
|
+
method: "POST",
|
|
498
|
+
metadata: {
|
|
499
|
+
SERVER_ONLY: true,
|
|
500
|
+
openapi: {
|
|
501
|
+
description:
|
|
502
|
+
"Delete and regenerate JWKS, and return the new JWKS for static usage",
|
|
503
|
+
},
|
|
504
|
+
},
|
|
505
|
+
},
|
|
506
|
+
async (ctx) => {
|
|
507
|
+
await ctx.context.adapter.deleteMany({
|
|
508
|
+
model: "jwks",
|
|
509
|
+
where: [],
|
|
510
|
+
});
|
|
511
|
+
|
|
512
|
+
await jwtPlugin(jwtOptions).endpoints.getJwks({
|
|
513
|
+
...ctx,
|
|
514
|
+
method: "GET",
|
|
515
|
+
});
|
|
516
|
+
const jwks: any[] = await ctx.context.adapter.findMany({
|
|
517
|
+
model: "jwks",
|
|
518
|
+
limit: 1,
|
|
519
|
+
sortBy: {
|
|
520
|
+
field: "createdAt",
|
|
521
|
+
direction: "desc",
|
|
522
|
+
},
|
|
523
|
+
});
|
|
524
|
+
jwks[0].alg = jwtOptions.jwks.keyPairConfig.alg;
|
|
525
|
+
return jwks;
|
|
526
|
+
}
|
|
527
|
+
),
|
|
528
|
+
getToken: createAuthEndpoint(
|
|
529
|
+
"/convex/token",
|
|
530
|
+
{
|
|
531
|
+
method: "GET",
|
|
532
|
+
requireHeaders: true,
|
|
533
|
+
use: [sessionMiddleware],
|
|
534
|
+
metadata: {
|
|
535
|
+
openapi: {
|
|
536
|
+
description: "Get a JWT token",
|
|
537
|
+
responses: {
|
|
538
|
+
200: {
|
|
539
|
+
description: "Success",
|
|
540
|
+
content: {
|
|
541
|
+
"application/json": {
|
|
542
|
+
schema: {
|
|
543
|
+
type: "object",
|
|
544
|
+
properties: {
|
|
545
|
+
token: {
|
|
546
|
+
type: "string",
|
|
547
|
+
},
|
|
548
|
+
},
|
|
549
|
+
},
|
|
550
|
+
},
|
|
551
|
+
},
|
|
552
|
+
},
|
|
553
|
+
},
|
|
554
|
+
},
|
|
555
|
+
},
|
|
556
|
+
},
|
|
557
|
+
async (ctx) => {
|
|
558
|
+
const runEndpoint = async () => {
|
|
559
|
+
const response = await jwt.endpoints.getToken({
|
|
560
|
+
...ctx,
|
|
561
|
+
returnHeaders: false,
|
|
562
|
+
returnStatus: false,
|
|
563
|
+
});
|
|
564
|
+
const jwtCookie = ctx.context.createAuthCookie(JWT_COOKIE_NAME, {
|
|
565
|
+
maxAge: jwtExpirationSeconds,
|
|
566
|
+
});
|
|
567
|
+
ctx.setCookie(jwtCookie.name, response.token, jwtCookie.attributes);
|
|
568
|
+
return response;
|
|
569
|
+
};
|
|
570
|
+
try {
|
|
571
|
+
return await runEndpoint();
|
|
572
|
+
} catch (error: any) {
|
|
573
|
+
// If alg config has changed and no longer matches one or more keys,
|
|
574
|
+
// roll the keys
|
|
575
|
+
if (!opts.jwks && error?.code === "ERR_JOSE_NOT_SUPPORTED") {
|
|
576
|
+
if (opts.jwksRotateOnTokenGenerationError) {
|
|
577
|
+
await ctx.context.adapter.deleteMany({
|
|
578
|
+
model: "jwks",
|
|
579
|
+
where: [],
|
|
580
|
+
});
|
|
581
|
+
return await runEndpoint();
|
|
582
|
+
} else {
|
|
583
|
+
// eslint-disable-next-line no-console
|
|
584
|
+
console.error(
|
|
585
|
+
"Try temporarily setting jwksRotateOnTokenGenerationError: true on the Convex Better Auth plugin."
|
|
586
|
+
);
|
|
587
|
+
}
|
|
588
|
+
}
|
|
589
|
+
throw error;
|
|
590
|
+
}
|
|
591
|
+
}
|
|
592
|
+
),
|
|
593
|
+
},
|
|
594
|
+
schema,
|
|
595
|
+
} satisfies BetterAuthPlugin;
|
|
596
|
+
};
|