@better-auth/oauth-provider 1.7.0-beta.0 → 1.7.0-beta.10

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.
@@ -1,417 +0,0 @@
1
- import { APIError } from "better-call";
2
- import { constantTimeEqual, makeSignature, symmetricDecrypt, symmetricEncrypt } from "better-auth/crypto";
3
- import { BetterAuthError } from "@better-auth/core/error";
4
- import { base64, base64Url } from "@better-auth/utils/base64";
5
- import { createHash } from "@better-auth/utils/hash";
6
- //#region src/utils/index.ts
7
- var TTLCache = class {
8
- cache = /* @__PURE__ */ new Map();
9
- constructor() {}
10
- set(key, value) {
11
- this.cache.set(key, value);
12
- }
13
- get(key) {
14
- const entry = this.cache.get(key);
15
- if (!entry) return void 0;
16
- if (entry.expiresAt && entry.expiresAt < /* @__PURE__ */ new Date()) {
17
- this.cache.delete(key);
18
- return;
19
- }
20
- return entry;
21
- }
22
- };
23
- /**
24
- * Gets the oAuth Provider Plugin
25
- * @internal
26
- */
27
- const getOAuthProviderPlugin = (ctx) => {
28
- return ctx.getPlugin("oauth-provider");
29
- };
30
- /**
31
- * Gets the JWT Plugin
32
- * @internal
33
- */
34
- const getJwtPlugin = (ctx) => {
35
- const plugin = ctx.getPlugin("jwt");
36
- if (!plugin) throw new BetterAuthError("jwt_config");
37
- return plugin;
38
- };
39
- /**
40
- * Normalizes timestamp-like values returned by adapters.
41
- *
42
- * Accepts Date instances, epoch milliseconds as numbers, and strings that are
43
- * either ISO dates or numeric millisecond values such as "1774295570569.0".
44
- */
45
- function normalizeTimestampValue(value) {
46
- if (value == null) return;
47
- if (value instanceof Date) return Number.isFinite(value.getTime()) ? value : void 0;
48
- if (typeof value === "number") {
49
- if (!Number.isFinite(value)) return;
50
- const parsed = new Date(value);
51
- return Number.isFinite(parsed.getTime()) ? parsed : void 0;
52
- }
53
- if (typeof value === "string") {
54
- const trimmed = value.trim();
55
- if (!trimmed.length) return;
56
- const numeric = Number(trimmed);
57
- if (Number.isFinite(numeric)) {
58
- const parsed = new Date(numeric);
59
- return Number.isFinite(parsed.getTime()) ? parsed : void 0;
60
- }
61
- const parsed = new Date(trimmed);
62
- return Number.isFinite(parsed.getTime()) ? parsed : void 0;
63
- }
64
- }
65
- /**
66
- * Resolves a session auth time from common adapter return shapes.
67
- */
68
- function resolveSessionAuthTime(value) {
69
- if (value instanceof Date) return normalizeTimestampValue(value);
70
- if (!value || typeof value !== "object") return normalizeTimestampValue(value);
71
- const direct = normalizeTimestampValue(value.createdAt) ?? normalizeTimestampValue(value.created_at);
72
- if (direct) return direct;
73
- const nested = value.session;
74
- if (!nested || typeof nested !== "object") return;
75
- return normalizeTimestampValue(nested.createdAt) ?? normalizeTimestampValue(nested.created_at);
76
- }
77
- const cachedTrustedClients = new TTLCache();
78
- async function verifyOAuthQueryParams(oauth_query, secret) {
79
- const queryParams = new URLSearchParams(oauth_query);
80
- const sig = queryParams.get("sig");
81
- const exp = Number(queryParams.get("exp"));
82
- queryParams.delete("sig");
83
- const verifySig = await makeSignature(queryParams.toString(), secret);
84
- return !!sig && constantTimeEqual(sig, verifySig) && /* @__PURE__ */ new Date(exp * 1e3) >= /* @__PURE__ */ new Date();
85
- }
86
- /**
87
- * Get a client by ID, checking trusted clients first, then database
88
- */
89
- async function getClient(ctx, options, clientId) {
90
- const trustedClient = cachedTrustedClients.get(clientId);
91
- if (trustedClient) return Object.assign({}, trustedClient);
92
- const dbClient = await ctx.context.adapter.findOne({
93
- model: options.schema?.oauthClient?.modelName ?? "oauthClient",
94
- where: [{
95
- field: "clientId",
96
- value: clientId
97
- }]
98
- });
99
- if (dbClient && options.cachedTrustedClients?.has(clientId)) cachedTrustedClients.set(clientId, Object.assign({}, dbClient));
100
- return dbClient;
101
- }
102
- /**
103
- * Default client secret hasher using SHA-256
104
- *
105
- * @internal
106
- */
107
- const defaultHasher = async (value) => {
108
- const hash = await createHash("SHA-256").digest(new TextEncoder().encode(value));
109
- return base64Url.encode(new Uint8Array(hash), { padding: false });
110
- };
111
- /**
112
- * Decrypts a storedClientSecret for signing
113
- *
114
- * @internal
115
- */
116
- async function decryptStoredClientSecret(ctx, storageMethod, storedClientSecret) {
117
- if (storageMethod === "encrypted") return await symmetricDecrypt({
118
- key: ctx.context.secretConfig,
119
- data: storedClientSecret
120
- });
121
- else if (typeof storageMethod === "object" && "decrypt" in storageMethod) return await storageMethod.decrypt(storedClientSecret);
122
- throw new BetterAuthError(`Unsupported decryption storageMethod type '${storageMethod}'`);
123
- }
124
- /**
125
- * Verify stored client secret against provided client secret
126
- *
127
- * @internal
128
- */
129
- async function verifyStoredClientSecret(ctx, opts, storedClientSecret, clientSecret) {
130
- const storageMethod = opts.storeClientSecret ?? (opts.disableJwtPlugin ? "encrypted" : "hashed");
131
- if (clientSecret && opts.prefix?.clientSecret) if (clientSecret.startsWith(opts.prefix?.clientSecret)) clientSecret = clientSecret.replace(opts.prefix.clientSecret, "");
132
- else throw new APIError("UNAUTHORIZED", {
133
- error_description: "invalid client_secret",
134
- error: "invalid_client"
135
- });
136
- if (storageMethod === "hashed") {
137
- const hashedClientSecret = clientSecret ? await defaultHasher(clientSecret) : void 0;
138
- return !!hashedClientSecret && constantTimeEqual(hashedClientSecret, storedClientSecret);
139
- } else if (typeof storageMethod === "object" && "hash" in storageMethod) if (storageMethod.verify) return !!clientSecret && await storageMethod.verify(clientSecret, storedClientSecret);
140
- else {
141
- const hashedClientSecret = clientSecret ? await storageMethod.hash(clientSecret) : void 0;
142
- return !!hashedClientSecret && constantTimeEqual(hashedClientSecret, storedClientSecret);
143
- }
144
- else if (storageMethod === "encrypted") try {
145
- const decryptedClientSecret = await decryptStoredClientSecret(ctx, storageMethod, storedClientSecret);
146
- return !!clientSecret && constantTimeEqual(decryptedClientSecret, clientSecret);
147
- } catch {
148
- return false;
149
- }
150
- else if (typeof storageMethod === "object" && "decrypt" in storageMethod) {
151
- const decryptedClientSecret = await decryptStoredClientSecret(ctx, storageMethod, storedClientSecret);
152
- return !!clientSecret && constantTimeEqual(decryptedClientSecret, clientSecret);
153
- }
154
- throw new BetterAuthError(`Unsupported verify storageMethod type '${storageMethod}'`);
155
- }
156
- /**
157
- * Store client secret according to the configured storage method
158
- *
159
- * @internal
160
- */
161
- async function storeClientSecret(ctx, opts, clientSecret) {
162
- const storageMethod = opts.storeClientSecret ?? (opts.disableJwtPlugin ? "encrypted" : "hashed");
163
- if (storageMethod === "encrypted") return await symmetricEncrypt({
164
- key: ctx.context.secretConfig,
165
- data: clientSecret
166
- });
167
- else if (storageMethod === "hashed") return await defaultHasher(clientSecret);
168
- else if (typeof storageMethod === "object" && "hash" in storageMethod) return await storageMethod.hash(clientSecret);
169
- else if (typeof storageMethod === "object" && "encrypt" in storageMethod) return await storageMethod.encrypt(clientSecret);
170
- throw new BetterAuthError(`Unsupported storeClientSecret type '${storageMethod}'`);
171
- }
172
- /**
173
- * Stores a token value (ie opaque tokens, refresh tokens, transaction tokens, verification codes)
174
- * on the database in a secure hashed format.
175
- *
176
- * @internal
177
- */
178
- async function storeToken(storageMethod = "hashed", token, type) {
179
- if (storageMethod === "hashed") return await defaultHasher(token);
180
- else if (typeof storageMethod === "object" && "hash" in storageMethod) return await storageMethod.hash(token, type);
181
- throw new BetterAuthError(`storeToken: unsupported storageMethod type '${storageMethod}'`);
182
- }
183
- /**
184
- * Gets a hashed token value to find on the database.
185
- *
186
- * @internal
187
- */
188
- async function getStoredToken(storageMethod = "hashed", token, type) {
189
- if (storageMethod === "hashed") return await defaultHasher(token);
190
- else if (typeof storageMethod === "object" && "hash" in storageMethod) return await storageMethod.hash(token, type);
191
- throw new BetterAuthError(`getStoredToken: unsupported storageMethod type '${storageMethod}'`);
192
- }
193
- /**
194
- * Converts a BASIC authorization header
195
- * into its client_id and client_secret representation
196
- *
197
- * @internal
198
- */
199
- function basicToClientCredentials(authorization) {
200
- if (authorization.startsWith("Basic ")) {
201
- const encoded = authorization.replace("Basic ", "");
202
- const decoded = new TextDecoder().decode(base64.decode(encoded));
203
- if (!decoded.includes(":")) throw new APIError("BAD_REQUEST", {
204
- error_description: "invalid authorization header format",
205
- error: "invalid_client"
206
- });
207
- const [id, secret] = decoded.split(":", 2);
208
- if (!id || !secret) throw new APIError("BAD_REQUEST", {
209
- error_description: "invalid authorization header format",
210
- error: "invalid_client"
211
- });
212
- return {
213
- client_id: id,
214
- client_secret: secret
215
- };
216
- }
217
- }
218
- /**
219
- * Validates client credentials failing on mismatches
220
- * and incorrectly provided information
221
- *
222
- * @internal
223
- */
224
- async function validateClientCredentials(ctx, options, clientId, clientSecret, scopes, preVerifiedClient) {
225
- const client = preVerifiedClient ?? await getClient(ctx, options, clientId);
226
- if (!client) throw new APIError("BAD_REQUEST", {
227
- error_description: "missing client",
228
- error: "invalid_client"
229
- });
230
- if (client.disabled) throw new APIError("BAD_REQUEST", {
231
- error_description: "client is disabled",
232
- error: "invalid_client"
233
- });
234
- if (client.tokenEndpointAuthMethod === "private_key_jwt" && !preVerifiedClient) throw new APIError("BAD_REQUEST", {
235
- error_description: "client registered for private_key_jwt must use client_assertion",
236
- error: "invalid_client"
237
- });
238
- if (!preVerifiedClient) {
239
- if (!client.public && !clientSecret) throw new APIError("BAD_REQUEST", {
240
- error_description: "client secret must be provided",
241
- error: "invalid_client"
242
- });
243
- if (clientSecret && !client.clientSecret) throw new APIError("BAD_REQUEST", {
244
- error_description: "public client, client secret should not be received",
245
- error: "invalid_client"
246
- });
247
- if (clientSecret && !await verifyStoredClientSecret(ctx, options, client.clientSecret, clientSecret)) throw new APIError("UNAUTHORIZED", {
248
- error_description: "invalid client_secret",
249
- error: "invalid_client"
250
- });
251
- }
252
- if (scopes && client.scopes) {
253
- const validScopes = new Set(client.scopes);
254
- for (const sc of scopes) if (!validScopes.has(sc)) throw new APIError("BAD_REQUEST", {
255
- error_description: `client does not allow scope ${sc}`,
256
- error: "invalid_scope"
257
- });
258
- }
259
- return client;
260
- }
261
- /**
262
- * Parse client metadata that may be stored as JSON string or already parsed object.
263
- * Handles database adapters that auto-parse JSON columns.
264
- *
265
- * @internal
266
- */
267
- function parseClientMetadata(metadata) {
268
- if (!metadata) return void 0;
269
- return typeof metadata === "string" ? JSON.parse(metadata) : metadata;
270
- }
271
- /** Unwraps ExtractedCredentials into the fields each grant handler needs. */
272
- function destructureCredentials(credentials) {
273
- return {
274
- clientId: credentials?.clientId,
275
- clientSecret: credentials?.method === "client_secret_basic" || credentials?.method === "client_secret_post" ? credentials.clientSecret : void 0,
276
- preVerifiedClient: credentials?.method === "private_key_jwt" ? credentials.client : void 0
277
- };
278
- }
279
- /**
280
- * Extracts and resolves client credentials from the request.
281
- * Supports: client_secret_basic, client_secret_post, private_key_jwt, and none (public).
282
- */
283
- async function extractClientCredentials(ctx, opts, expectedAudience) {
284
- const body = ctx.body ?? {};
285
- const authorization = ctx.request?.headers.get("authorization") ?? void 0;
286
- if (body.client_assertion_type || body.client_assertion) {
287
- if (!body.client_assertion || !body.client_assertion_type) throw new APIError("BAD_REQUEST", {
288
- error_description: "client_assertion and client_assertion_type must both be provided",
289
- error: "invalid_client"
290
- });
291
- if (body.client_secret || authorization?.startsWith("Basic ")) throw new APIError("BAD_REQUEST", {
292
- error_description: "client_assertion cannot be combined with client_secret or Basic auth",
293
- error: "invalid_client"
294
- });
295
- const { verifyClientAssertion: verify } = await import("./client-assertion-DZqo-L5j.mjs").then((n) => n.t);
296
- const result = await verify(ctx, opts, body.client_assertion, body.client_assertion_type, body.client_id, expectedAudience);
297
- return {
298
- method: "private_key_jwt",
299
- clientId: result.clientId,
300
- client: result.client
301
- };
302
- }
303
- if (authorization?.startsWith("Basic ")) {
304
- const res = basicToClientCredentials(authorization);
305
- if (res) return {
306
- method: "client_secret_basic",
307
- clientId: res.client_id,
308
- clientSecret: res.client_secret
309
- };
310
- }
311
- if (body.client_id && body.client_secret) return {
312
- method: "client_secret_post",
313
- clientId: body.client_id,
314
- clientSecret: body.client_secret
315
- };
316
- if (body.client_id) return {
317
- method: "none",
318
- clientId: body.client_id
319
- };
320
- return null;
321
- }
322
- /**
323
- * Parse space-separated prompt string into a set of prompts
324
- *
325
- * @param prompt
326
- */
327
- function parsePrompt(prompt) {
328
- const prompts = prompt.split(" ").map((p) => p.trim());
329
- const set = /* @__PURE__ */ new Set();
330
- for (const p of prompts) if (p === "login" || p === "consent" || p === "create" || p === "select_account" || p === "none") set.add(p);
331
- return new Set(set);
332
- }
333
- /**
334
- * Extracts the sector identifier (hostname) from a client's first redirect URI.
335
- *
336
- * @see https://openid.net/specs/openid-connect-core-1_0.html#PairwiseAlg
337
- * @internal
338
- */
339
- function getSectorIdentifier(client) {
340
- const uri = client.redirectUris?.[0];
341
- if (!uri) throw new BetterAuthError("Client has no redirect URIs for sector identifier");
342
- return new URL(uri).host;
343
- }
344
- /**
345
- * Computes a pairwise subject identifier using HMAC-SHA256.
346
- *
347
- * @see https://openid.net/specs/openid-connect-core-1_0.html#PairwiseAlg
348
- * @internal
349
- */
350
- async function computePairwiseSub(userId, client, secret) {
351
- return makeSignature(`${getSectorIdentifier(client)}.${userId}`, secret);
352
- }
353
- /**
354
- * Returns the appropriate subject identifier for a user+client pair.
355
- * Uses pairwise when the client opts in and the server has a secret configured.
356
- *
357
- * @internal
358
- */
359
- async function resolveSubjectIdentifier(userId, client, opts) {
360
- if (client.subjectType === "pairwise" && opts.pairwiseSecret) return computePairwiseSub(userId, client, opts.pairwiseSecret);
361
- return userId;
362
- }
363
- /**
364
- * Converts URLSearchParams to a plain object, preserving
365
- * multi-valued keys as arrays instead of discarding duplicates.
366
- */
367
- function searchParamsToQuery(params) {
368
- const result = Object.create(null);
369
- for (const key of new Set(params.keys())) {
370
- const values = params.getAll(key);
371
- result[key] = values.length === 1 ? values[0] : values;
372
- }
373
- return result;
374
- }
375
- /**
376
- * Deletes a prompt value
377
- *
378
- * @param ctx
379
- * @param prompt - the prompt value to delete
380
- */
381
- function deleteFromPrompt(query, prompt) {
382
- const prompts = query.get("prompt")?.split(" ");
383
- const foundPrompt = prompts?.findIndex((v) => v === prompt) ?? -1;
384
- if (foundPrompt >= 0) {
385
- prompts?.splice(foundPrompt, 1);
386
- prompts?.length ? query.set("prompt", prompts.join(" ")) : query.delete("prompt");
387
- }
388
- return searchParamsToQuery(query);
389
- }
390
- var PKCERequirementErrors = /* @__PURE__ */ function(PKCERequirementErrors) {
391
- PKCERequirementErrors["PUBLIC_CLIENT"] = "pkce is required for public clients";
392
- PKCERequirementErrors["OFFLINE_ACCESS_SCOPE"] = "pkce is required when requesting offline_access scope";
393
- PKCERequirementErrors["CLIENT_REQUIRE_PKCE"] = "pkce is required for this client";
394
- return PKCERequirementErrors;
395
- }(PKCERequirementErrors || {});
396
- /**
397
- * Determines if PKCE is required for a given client and scope.
398
- *
399
- * PKCE is always required for:
400
- * 1. Public clients (cannot securely store client_secret)
401
- * 2. Requests with offline_access scope (refresh token security)
402
- *
403
- * For confidential clients without offline_access:
404
- * - Uses client.requirePKCE if set (defaults to true)
405
- *
406
- * Returns false if PKCE is not required, or the reason it is required.
407
- *
408
- * @internal
409
- */
410
- function isPKCERequired(client, requestedScopes) {
411
- if (client.tokenEndpointAuthMethod === "none" || client.type === "native" || client.type === "user-agent-based" || client.public === true) return PKCERequirementErrors.PUBLIC_CLIENT;
412
- if (requestedScopes?.includes("offline_access")) return PKCERequirementErrors.OFFLINE_ACCESS_SCOPE;
413
- if (client.requirePKCE ?? true) return PKCERequirementErrors.CLIENT_REQUIRE_PKCE;
414
- return false;
415
- }
416
- //#endregion
417
- export { storeToken as _, getClient as a, getStoredToken as c, parseClientMetadata as d, parsePrompt as f, storeClientSecret as g, searchParamsToQuery as h, extractClientCredentials as i, isPKCERequired as l, resolveSubjectIdentifier as m, deleteFromPrompt as n, getJwtPlugin as o, resolveSessionAuthTime as p, destructureCredentials as r, getOAuthProviderPlugin as s, decryptStoredClientSecret as t, normalizeTimestampValue as u, validateClientCredentials as v, verifyOAuthQueryParams as y };