better-auth 0.5.2-beta.12 → 0.5.2-beta.13
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/dist/adapters/drizzle.d.cts +1 -1
- package/dist/adapters/drizzle.d.ts +1 -1
- package/dist/adapters/kysely.d.cts +1 -1
- package/dist/adapters/kysely.d.ts +1 -1
- package/dist/adapters/mongodb.d.cts +1 -1
- package/dist/adapters/mongodb.d.ts +1 -1
- package/dist/adapters/prisma.d.cts +1 -1
- package/dist/adapters/prisma.d.ts +1 -1
- package/dist/api.cjs +1 -1
- package/dist/api.d.cts +1 -1
- package/dist/api.d.ts +1 -1
- package/dist/api.js +1 -1
- package/dist/{auth-SMzIERpz.d.ts → auth-D1kVkHCi.d.ts} +24 -24
- package/dist/{auth-kXZUEU5B.d.cts → auth-D7_h4yVD.d.cts} +24 -24
- package/dist/client/plugins.d.cts +3 -3
- package/dist/client/plugins.d.ts +3 -3
- package/dist/client.d.cts +1 -1
- package/dist/client.d.ts +1 -1
- package/dist/cookies.d.cts +1 -1
- package/dist/cookies.d.ts +1 -1
- package/dist/db.d.cts +2 -2
- package/dist/db.d.ts +2 -2
- package/dist/{index-R4tR6ojQ.d.cts → index-BFsm4pYA.d.cts} +1 -1
- package/dist/{index-DOKc35nY.d.ts → index-Ctg062Fg.d.ts} +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/node.d.cts +1 -1
- package/dist/node.d.ts +1 -1
- package/dist/plugins.cjs +5 -5
- package/dist/plugins.d.cts +3 -3
- package/dist/plugins.d.ts +3 -3
- package/dist/plugins.js +5 -5
- package/dist/react.d.cts +1 -1
- package/dist/react.d.ts +1 -1
- package/dist/solid-start.d.cts +1 -1
- package/dist/solid-start.d.ts +1 -1
- package/dist/solid.d.cts +1 -1
- package/dist/solid.d.ts +1 -1
- package/dist/svelte-kit.d.cts +1 -1
- package/dist/svelte-kit.d.ts +1 -1
- package/dist/svelte.d.cts +1 -1
- package/dist/svelte.d.ts +1 -1
- package/dist/types.d.cts +2 -2
- package/dist/types.d.ts +2 -2
- package/dist/vue.d.cts +1 -1
- package/dist/vue.d.ts +1 -1
- package/package.json +1 -1
|
@@ -1253,12 +1253,12 @@ declare const signInOAuth: {
|
|
|
1253
1253
|
/**
|
|
1254
1254
|
* OAuth2 provider to use`
|
|
1255
1255
|
*/
|
|
1256
|
-
provider: z.ZodEnum<["github", ...("
|
|
1256
|
+
provider: z.ZodEnum<["github", ...("apple" | "discord" | "facebook" | "github" | "google" | "microsoft" | "spotify" | "twitch" | "twitter")[]]>;
|
|
1257
1257
|
}, "strip", z.ZodTypeAny, {
|
|
1258
|
-
provider: "
|
|
1258
|
+
provider: "apple" | "discord" | "facebook" | "github" | "google" | "microsoft" | "spotify" | "twitch" | "twitter";
|
|
1259
1259
|
callbackURL?: string | undefined;
|
|
1260
1260
|
}, {
|
|
1261
|
-
provider: "
|
|
1261
|
+
provider: "apple" | "discord" | "facebook" | "github" | "google" | "microsoft" | "spotify" | "twitch" | "twitter";
|
|
1262
1262
|
callbackURL?: string | undefined;
|
|
1263
1263
|
}>;
|
|
1264
1264
|
use: better_call.Endpoint<better_call.Handler<string, better_call.EndpointOptions, void>, better_call.EndpointOptions>[];
|
|
@@ -1296,12 +1296,12 @@ declare const signInOAuth: {
|
|
|
1296
1296
|
/**
|
|
1297
1297
|
* OAuth2 provider to use`
|
|
1298
1298
|
*/
|
|
1299
|
-
provider: z.ZodEnum<["github", ...("
|
|
1299
|
+
provider: z.ZodEnum<["github", ...("apple" | "discord" | "facebook" | "github" | "google" | "microsoft" | "spotify" | "twitch" | "twitter")[]]>;
|
|
1300
1300
|
}, "strip", z.ZodTypeAny, {
|
|
1301
|
-
provider: "
|
|
1301
|
+
provider: "apple" | "discord" | "facebook" | "github" | "google" | "microsoft" | "spotify" | "twitch" | "twitter";
|
|
1302
1302
|
callbackURL?: string | undefined;
|
|
1303
1303
|
}, {
|
|
1304
|
-
provider: "
|
|
1304
|
+
provider: "apple" | "discord" | "facebook" | "github" | "google" | "microsoft" | "spotify" | "twitch" | "twitter";
|
|
1305
1305
|
callbackURL?: string | undefined;
|
|
1306
1306
|
}>;
|
|
1307
1307
|
use: better_call.Endpoint<better_call.Handler<string, better_call.EndpointOptions, void>, better_call.EndpointOptions>[];
|
|
@@ -2595,12 +2595,12 @@ declare function getEndpoints<C extends AuthContext, Option extends BetterAuthOp
|
|
|
2595
2595
|
}>>;
|
|
2596
2596
|
body: zod.ZodObject<{
|
|
2597
2597
|
callbackURL: zod.ZodOptional<zod.ZodString>;
|
|
2598
|
-
provider: zod.ZodEnum<["github", ...("
|
|
2598
|
+
provider: zod.ZodEnum<["github", ...("apple" | "discord" | "facebook" | "github" | "google" | "microsoft" | "spotify" | "twitch" | "twitter")[]]>;
|
|
2599
2599
|
}, "strip", zod.ZodTypeAny, {
|
|
2600
|
-
provider: "
|
|
2600
|
+
provider: "apple" | "discord" | "facebook" | "github" | "google" | "microsoft" | "spotify" | "twitch" | "twitter";
|
|
2601
2601
|
callbackURL?: string | undefined;
|
|
2602
2602
|
}, {
|
|
2603
|
-
provider: "
|
|
2603
|
+
provider: "apple" | "discord" | "facebook" | "github" | "google" | "microsoft" | "spotify" | "twitch" | "twitter";
|
|
2604
2604
|
callbackURL?: string | undefined;
|
|
2605
2605
|
}>;
|
|
2606
2606
|
use: Endpoint<better_call.Handler<string, better_call.EndpointOptions, void>, better_call.EndpointOptions>[];
|
|
@@ -2628,12 +2628,12 @@ declare function getEndpoints<C extends AuthContext, Option extends BetterAuthOp
|
|
|
2628
2628
|
}>>;
|
|
2629
2629
|
body: zod.ZodObject<{
|
|
2630
2630
|
callbackURL: zod.ZodOptional<zod.ZodString>;
|
|
2631
|
-
provider: zod.ZodEnum<["github", ...("
|
|
2631
|
+
provider: zod.ZodEnum<["github", ...("apple" | "discord" | "facebook" | "github" | "google" | "microsoft" | "spotify" | "twitch" | "twitter")[]]>;
|
|
2632
2632
|
}, "strip", zod.ZodTypeAny, {
|
|
2633
|
-
provider: "
|
|
2633
|
+
provider: "apple" | "discord" | "facebook" | "github" | "google" | "microsoft" | "spotify" | "twitch" | "twitter";
|
|
2634
2634
|
callbackURL?: string | undefined;
|
|
2635
2635
|
}, {
|
|
2636
|
-
provider: "
|
|
2636
|
+
provider: "apple" | "discord" | "facebook" | "github" | "google" | "microsoft" | "spotify" | "twitch" | "twitter";
|
|
2637
2637
|
callbackURL?: string | undefined;
|
|
2638
2638
|
}>;
|
|
2639
2639
|
use: Endpoint<better_call.Handler<string, better_call.EndpointOptions, void>, better_call.EndpointOptions>[];
|
|
@@ -3783,12 +3783,12 @@ declare const router: <C extends AuthContext, Option extends BetterAuthOptions>(
|
|
|
3783
3783
|
}>>;
|
|
3784
3784
|
body: zod.ZodObject<{
|
|
3785
3785
|
callbackURL: zod.ZodOptional<zod.ZodString>;
|
|
3786
|
-
provider: zod.ZodEnum<["github", ...("
|
|
3786
|
+
provider: zod.ZodEnum<["github", ...("apple" | "discord" | "facebook" | "github" | "google" | "microsoft" | "spotify" | "twitch" | "twitter")[]]>;
|
|
3787
3787
|
}, "strip", zod.ZodTypeAny, {
|
|
3788
|
-
provider: "
|
|
3788
|
+
provider: "apple" | "discord" | "facebook" | "github" | "google" | "microsoft" | "spotify" | "twitch" | "twitter";
|
|
3789
3789
|
callbackURL?: string | undefined;
|
|
3790
3790
|
}, {
|
|
3791
|
-
provider: "
|
|
3791
|
+
provider: "apple" | "discord" | "facebook" | "github" | "google" | "microsoft" | "spotify" | "twitch" | "twitter";
|
|
3792
3792
|
callbackURL?: string | undefined;
|
|
3793
3793
|
}>;
|
|
3794
3794
|
use: Endpoint<better_call.Handler<string, better_call.EndpointOptions, void>, better_call.EndpointOptions>[];
|
|
@@ -3816,12 +3816,12 @@ declare const router: <C extends AuthContext, Option extends BetterAuthOptions>(
|
|
|
3816
3816
|
}>>;
|
|
3817
3817
|
body: zod.ZodObject<{
|
|
3818
3818
|
callbackURL: zod.ZodOptional<zod.ZodString>;
|
|
3819
|
-
provider: zod.ZodEnum<["github", ...("
|
|
3819
|
+
provider: zod.ZodEnum<["github", ...("apple" | "discord" | "facebook" | "github" | "google" | "microsoft" | "spotify" | "twitch" | "twitter")[]]>;
|
|
3820
3820
|
}, "strip", zod.ZodTypeAny, {
|
|
3821
|
-
provider: "
|
|
3821
|
+
provider: "apple" | "discord" | "facebook" | "github" | "google" | "microsoft" | "spotify" | "twitch" | "twitter";
|
|
3822
3822
|
callbackURL?: string | undefined;
|
|
3823
3823
|
}, {
|
|
3824
|
-
provider: "
|
|
3824
|
+
provider: "apple" | "discord" | "facebook" | "github" | "google" | "microsoft" | "spotify" | "twitch" | "twitter";
|
|
3825
3825
|
callbackURL?: string | undefined;
|
|
3826
3826
|
}>;
|
|
3827
3827
|
use: Endpoint<better_call.Handler<string, better_call.EndpointOptions, void>, better_call.EndpointOptions>[];
|
|
@@ -4973,12 +4973,12 @@ declare const betterAuth: <O extends BetterAuthOptions>(options: O) => {
|
|
|
4973
4973
|
}>>;
|
|
4974
4974
|
body: zod.ZodObject<{
|
|
4975
4975
|
callbackURL: zod.ZodOptional<zod.ZodString>;
|
|
4976
|
-
provider: zod.ZodEnum<["github", ...("
|
|
4976
|
+
provider: zod.ZodEnum<["github", ...("apple" | "discord" | "facebook" | "github" | "google" | "microsoft" | "spotify" | "twitch" | "twitter")[]]>;
|
|
4977
4977
|
}, "strip", zod.ZodTypeAny, {
|
|
4978
|
-
provider: "
|
|
4978
|
+
provider: "apple" | "discord" | "facebook" | "github" | "google" | "microsoft" | "spotify" | "twitch" | "twitter";
|
|
4979
4979
|
callbackURL?: string | undefined;
|
|
4980
4980
|
}, {
|
|
4981
|
-
provider: "
|
|
4981
|
+
provider: "apple" | "discord" | "facebook" | "github" | "google" | "microsoft" | "spotify" | "twitch" | "twitter";
|
|
4982
4982
|
callbackURL?: string | undefined;
|
|
4983
4983
|
}>;
|
|
4984
4984
|
use: Endpoint<better_call.Handler<string, better_call.EndpointOptions, void>, better_call.EndpointOptions>[];
|
|
@@ -5006,12 +5006,12 @@ declare const betterAuth: <O extends BetterAuthOptions>(options: O) => {
|
|
|
5006
5006
|
}>>;
|
|
5007
5007
|
body: zod.ZodObject<{
|
|
5008
5008
|
callbackURL: zod.ZodOptional<zod.ZodString>;
|
|
5009
|
-
provider: zod.ZodEnum<["github", ...("
|
|
5009
|
+
provider: zod.ZodEnum<["github", ...("apple" | "discord" | "facebook" | "github" | "google" | "microsoft" | "spotify" | "twitch" | "twitter")[]]>;
|
|
5010
5010
|
}, "strip", zod.ZodTypeAny, {
|
|
5011
|
-
provider: "
|
|
5011
|
+
provider: "apple" | "discord" | "facebook" | "github" | "google" | "microsoft" | "spotify" | "twitch" | "twitter";
|
|
5012
5012
|
callbackURL?: string | undefined;
|
|
5013
5013
|
}, {
|
|
5014
|
-
provider: "
|
|
5014
|
+
provider: "apple" | "discord" | "facebook" | "github" | "google" | "microsoft" | "spotify" | "twitch" | "twitter";
|
|
5015
5015
|
callbackURL?: string | undefined;
|
|
5016
5016
|
}>;
|
|
5017
5017
|
use: Endpoint<better_call.Handler<string, better_call.EndpointOptions, void>, better_call.EndpointOptions>[];
|
|
@@ -2,10 +2,10 @@ import * as nanostores from 'nanostores';
|
|
|
2
2
|
import { A as AccessControl, S as StatementsPrimitive, R as Role } from '../statement-Da_cxgTI.cjs';
|
|
3
3
|
import * as _better_fetch_fetch from '@better-fetch/fetch';
|
|
4
4
|
import { BetterFetchOption } from '@better-fetch/fetch';
|
|
5
|
-
import { o as organization, l as Organization, M as Member, I as Invitation, u as username, m as magicLink, d as phoneNumber, e as anonymous, i as admin, j as genericOAuth, k as multiSession } from '../index-
|
|
6
|
-
export { g as getPasskeyActions, c as passkeyClient, a as twoFactorClient } from '../index-
|
|
5
|
+
import { o as organization, l as Organization, M as Member, I as Invitation, u as username, m as magicLink, d as phoneNumber, e as anonymous, i as admin, j as genericOAuth, k as multiSession } from '../index-BFsm4pYA.cjs';
|
|
6
|
+
export { g as getPasskeyActions, c as passkeyClient, a as twoFactorClient } from '../index-BFsm4pYA.cjs';
|
|
7
7
|
import { P as Prettify } from '../helper-DPDj8Nix.cjs';
|
|
8
|
-
import { F as FieldAttribute, B as BetterAuthOptions, b as BetterAuthPlugin } from '../auth-
|
|
8
|
+
import { F as FieldAttribute, B as BetterAuthOptions, b as BetterAuthPlugin } from '../auth-D7_h4yVD.cjs';
|
|
9
9
|
import 'zod';
|
|
10
10
|
import '../schema-Dkt0LqYs.cjs';
|
|
11
11
|
import 'better-call';
|
package/dist/client/plugins.d.ts
CHANGED
|
@@ -2,10 +2,10 @@ import * as nanostores from 'nanostores';
|
|
|
2
2
|
import { A as AccessControl, S as StatementsPrimitive, R as Role } from '../statement-CfnyN34h.js';
|
|
3
3
|
import * as _better_fetch_fetch from '@better-fetch/fetch';
|
|
4
4
|
import { BetterFetchOption } from '@better-fetch/fetch';
|
|
5
|
-
import { o as organization, l as Organization, M as Member, I as Invitation, u as username, m as magicLink, d as phoneNumber, e as anonymous, i as admin, j as genericOAuth, k as multiSession } from '../index-
|
|
6
|
-
export { g as getPasskeyActions, c as passkeyClient, a as twoFactorClient } from '../index-
|
|
5
|
+
import { o as organization, l as Organization, M as Member, I as Invitation, u as username, m as magicLink, d as phoneNumber, e as anonymous, i as admin, j as genericOAuth, k as multiSession } from '../index-Ctg062Fg.js';
|
|
6
|
+
export { g as getPasskeyActions, c as passkeyClient, a as twoFactorClient } from '../index-Ctg062Fg.js';
|
|
7
7
|
import { P as Prettify } from '../helper-DPDj8Nix.js';
|
|
8
|
-
import { F as FieldAttribute, B as BetterAuthOptions, b as BetterAuthPlugin } from '../auth-
|
|
8
|
+
import { F as FieldAttribute, B as BetterAuthOptions, b as BetterAuthPlugin } from '../auth-D1kVkHCi.js';
|
|
9
9
|
import 'zod';
|
|
10
10
|
import '../schema-Dkt0LqYs.js';
|
|
11
11
|
import 'better-call';
|
package/dist/client.d.cts
CHANGED
|
@@ -6,7 +6,7 @@ import { BetterFetch, BetterFetchError, BetterFetchOption } from '@better-fetch/
|
|
|
6
6
|
import { U as UnionToIntersection, P as Prettify, S as StripEmptyObjects } from './helper-DPDj8Nix.cjs';
|
|
7
7
|
import { ClientOptions, InferClientAPI, InferActions, InferAdditionalFromClient, InferSessionFromClient, InferUserFromClient, BetterAuthClientPlugin, IsSignal } from './types.cjs';
|
|
8
8
|
export { AtomListener, InferPluginsFromClient } from './types.cjs';
|
|
9
|
-
import './auth-
|
|
9
|
+
import './auth-D7_h4yVD.cjs';
|
|
10
10
|
import 'kysely';
|
|
11
11
|
import './schema-Dkt0LqYs.cjs';
|
|
12
12
|
import 'better-call';
|
package/dist/client.d.ts
CHANGED
|
@@ -6,7 +6,7 @@ import { BetterFetch, BetterFetchError, BetterFetchOption } from '@better-fetch/
|
|
|
6
6
|
import { U as UnionToIntersection, P as Prettify, S as StripEmptyObjects } from './helper-DPDj8Nix.js';
|
|
7
7
|
import { ClientOptions, InferClientAPI, InferActions, InferAdditionalFromClient, InferSessionFromClient, InferUserFromClient, BetterAuthClientPlugin, IsSignal } from './types.js';
|
|
8
8
|
export { AtomListener, InferPluginsFromClient } from './types.js';
|
|
9
|
-
import './auth-
|
|
9
|
+
import './auth-D1kVkHCi.js';
|
|
10
10
|
import 'kysely';
|
|
11
11
|
import './schema-Dkt0LqYs.js';
|
|
12
12
|
import 'better-call';
|
package/dist/cookies.d.cts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import 'better-call';
|
|
2
|
-
export { s as BetterAuthCookies, E as EligibleCookies, r as createCookieGetter, u as deleteSessionCookie, q as getCookies, w as parseCookies, v as parseSetCookieHeader, t as setSessionCookie } from './auth-
|
|
2
|
+
export { s as BetterAuthCookies, E as EligibleCookies, r as createCookieGetter, u as deleteSessionCookie, q as getCookies, w as parseCookies, v as parseSetCookieHeader, t as setSessionCookie } from './auth-D7_h4yVD.cjs';
|
|
3
3
|
import 'zod';
|
|
4
4
|
import 'kysely';
|
|
5
5
|
import './schema-Dkt0LqYs.cjs';
|
package/dist/cookies.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import 'better-call';
|
|
2
|
-
export { s as BetterAuthCookies, E as EligibleCookies, r as createCookieGetter, u as deleteSessionCookie, q as getCookies, w as parseCookies, v as parseSetCookieHeader, t as setSessionCookie } from './auth-
|
|
2
|
+
export { s as BetterAuthCookies, E as EligibleCookies, r as createCookieGetter, u as deleteSessionCookie, q as getCookies, w as parseCookies, v as parseSetCookieHeader, t as setSessionCookie } from './auth-D1kVkHCi.js';
|
|
3
3
|
import 'zod';
|
|
4
4
|
import 'kysely';
|
|
5
5
|
import './schema-Dkt0LqYs.js';
|
package/dist/db.d.cts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { A as Adapter, B as BetterAuthOptions, W as Where, F as FieldAttribute, z as FieldType, K as KyselyDatabaseType } from './auth-
|
|
2
|
-
export { X as BetterAuthDbSchema, J as FieldAttributeConfig, V as InferFieldsFromOptions, U as InferFieldsFromPlugins, O as InferFieldsInput, Q as InferFieldsInputClient, N as InferFieldsOutput, M as InferValueType, D as InternalAdapter, T as PluginFieldAttribute, L as createFieldAttribute, C as createInternalAdapter, Y as getAuthTables } from './auth-
|
|
1
|
+
import { A as Adapter, B as BetterAuthOptions, W as Where, F as FieldAttribute, z as FieldType, K as KyselyDatabaseType } from './auth-D7_h4yVD.cjs';
|
|
2
|
+
export { X as BetterAuthDbSchema, J as FieldAttributeConfig, V as InferFieldsFromOptions, U as InferFieldsFromPlugins, O as InferFieldsInput, Q as InferFieldsInputClient, N as InferFieldsOutput, M as InferValueType, D as InternalAdapter, T as PluginFieldAttribute, L as createFieldAttribute, C as createInternalAdapter, Y as getAuthTables } from './auth-D7_h4yVD.cjs';
|
|
3
3
|
import { z } from 'zod';
|
|
4
4
|
import 'kysely';
|
|
5
5
|
import './schema-Dkt0LqYs.cjs';
|
package/dist/db.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { A as Adapter, B as BetterAuthOptions, W as Where, F as FieldAttribute, z as FieldType, K as KyselyDatabaseType } from './auth-
|
|
2
|
-
export { X as BetterAuthDbSchema, J as FieldAttributeConfig, V as InferFieldsFromOptions, U as InferFieldsFromPlugins, O as InferFieldsInput, Q as InferFieldsInputClient, N as InferFieldsOutput, M as InferValueType, D as InternalAdapter, T as PluginFieldAttribute, L as createFieldAttribute, C as createInternalAdapter, Y as getAuthTables } from './auth-
|
|
1
|
+
import { A as Adapter, B as BetterAuthOptions, W as Where, F as FieldAttribute, z as FieldType, K as KyselyDatabaseType } from './auth-D1kVkHCi.js';
|
|
2
|
+
export { X as BetterAuthDbSchema, J as FieldAttributeConfig, V as InferFieldsFromOptions, U as InferFieldsFromPlugins, O as InferFieldsInput, Q as InferFieldsInputClient, N as InferFieldsOutput, M as InferValueType, D as InternalAdapter, T as PluginFieldAttribute, L as createFieldAttribute, C as createInternalAdapter, Y as getAuthTables } from './auth-D1kVkHCi.js';
|
|
3
3
|
import { z } from 'zod';
|
|
4
4
|
import 'kysely';
|
|
5
5
|
import './schema-Dkt0LqYs.js';
|
|
@@ -5,7 +5,7 @@ import { P as Prettify } from './helper-DPDj8Nix.cjs';
|
|
|
5
5
|
import { A as AccessControl, R as Role, S as StatementsPrimitive, g as defaultRoles } from './statement-Da_cxgTI.cjs';
|
|
6
6
|
import * as _better_fetch_fetch from '@better-fetch/fetch';
|
|
7
7
|
import { BetterFetch, BetterFetchOption } from '@better-fetch/fetch';
|
|
8
|
-
import { H as HookEndpointContext, p as AuthContext } from './auth-
|
|
8
|
+
import { H as HookEndpointContext, p as AuthContext } from './auth-D7_h4yVD.cjs';
|
|
9
9
|
import * as nanostores from 'nanostores';
|
|
10
10
|
import { atom } from 'nanostores';
|
|
11
11
|
import * as _simplewebauthn_types from '@simplewebauthn/types';
|
|
@@ -5,7 +5,7 @@ import { P as Prettify } from './helper-DPDj8Nix.js';
|
|
|
5
5
|
import { A as AccessControl, R as Role, S as StatementsPrimitive, g as defaultRoles } from './statement-CfnyN34h.js';
|
|
6
6
|
import * as _better_fetch_fetch from '@better-fetch/fetch';
|
|
7
7
|
import { BetterFetch, BetterFetchOption } from '@better-fetch/fetch';
|
|
8
|
-
import { H as HookEndpointContext, p as AuthContext } from './auth-
|
|
8
|
+
import { H as HookEndpointContext, p as AuthContext } from './auth-D1kVkHCi.js';
|
|
9
9
|
import * as nanostores from 'nanostores';
|
|
10
10
|
import { atom } from 'nanostores';
|
|
11
11
|
import * as _simplewebauthn_types from '@simplewebauthn/types';
|
package/dist/index.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var ye=Object.defineProperty;var ir=Object.getOwnPropertyDescriptor;var sr=Object.getOwnPropertyNames;var ar=Object.prototype.hasOwnProperty;var dr=(e,t)=>{for(var r in t)ye(e,r,{get:t[r],enumerable:!0})},cr=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of sr(t))!ar.call(e,i)&&i!==r&&ye(e,i,{get:()=>t[i],enumerable:!(o=ir(t,i))||o.enumerable});return e};var lr=e=>cr(ye({},"__esModule",{value:!0}),e);var Br={};dr(Br,{BetterAuthError:()=>A,HIDE_METADATA:()=>C,MissingDependencyError:()=>Re,betterAuth:()=>Cr,capitalizeFirstLetter:()=>Ar,createCookieGetter:()=>xe,createLogger:()=>fe,deleteSessionCookie:()=>J,generateId:()=>x,generateState:()=>ke,getCookies:()=>Ue,logger:()=>b,parseCookies:()=>wr,parseSetCookieHeader:()=>yr,parseState:()=>pe,setSessionCookie:()=>L});module.exports=lr(Br);var G=require("better-call");var ue=require("better-call"),be=require("zod");var mr=require("@noble/ciphers/chacha"),we=require("@noble/ciphers/utils"),gr=require("@noble/ciphers/webcrypto"),hr=require("oslo/crypto");function ce(e,t){let r=new Uint8Array(e),o=new Uint8Array(t);if(r.length!==o.length)return!1;let i=0;for(let n=0;n<r.length;n++)i|=r[n]^o[n];return i===0}var ee=require("oslo/encoding");var Ne=require("@noble/hashes/scrypt"),W={N:16384,r:16,p:1,dkLen:64};async function Fe(e,t){return await(0,Ne.scryptAsync)(e.normalize("NFKC"),t,{N:W.N,p:W.p,r:W.r,dkLen:W.dkLen,maxmem:128*W.N*W.r*2})}var qe=async e=>{let t=(0,ee.encodeHex)(crypto.getRandomValues(new Uint8Array(16))),r=await Fe(e,t);return`${t}:${(0,ee.encodeHex)(r)}`},Ve=async(e,t)=>{let[r,o]=e.split(":"),i=await Fe(t,r);return ce(i,(0,ee.decodeHex)(o))};function ur(e){return e.toString(2).padStart(8,"0")}function pr(e){return[...e].map(t=>ur(t)).join("")}function $e(e){return parseInt(pr(e),2)}function fr(e){if(e<0||!Number.isInteger(e))throw new Error("Argument 'max' must be an integer greater than or equal to 0");let t=(e-1).toString(2).length,r=t%8,o=new Uint8Array(Math.ceil(t/8));crypto.getRandomValues(o),r!==0&&(o[0]&=(1<<r)-1);let i=$e(o);for(;i>=e;)crypto.getRandomValues(o),r!==0&&(o[0]&=(1<<r)-1),i=$e(o);return i}function je(e,t){let r="";for(let o=0;o<e;o++)r+=t[fr(t.length)];return r}function ze(...e){let t=new Set(e),r="";for(let o of t)o==="a-z"?r+="abcdefghijklmnopqrstuvwxyz":o==="A-Z"?r+="ABCDEFGHIJKLMNOPQRSTUVWXYZ":o==="0-9"?r+="0123456789":r+=o;return r}async function le(e,t){let r=new TextEncoder,o={name:"HMAC",hash:"SHA-256"},i=await crypto.subtle.importKey("raw",r.encode(e),o,!1,["sign","verify"]),n=await crypto.subtle.sign(o.name,i,r.encode(t));return btoa(String.fromCharCode(...new Uint8Array(n)))}var j=require("better-call"),Me=(0,j.createMiddleware)(async()=>({})),Z=(0,j.createMiddlewareCreator)({use:[Me,(0,j.createMiddleware)(async()=>({}))]}),y=(0,j.createEndpointCreator)({use:[Me]});var He=Z({body:be.z.object({csrfToken:be.z.string().optional()}).optional()},async e=>{if(e.request?.method!=="POST"||e.context.options.advanced?.disableCSRFCheck)return;let t=
|
|
1
|
+
"use strict";var ye=Object.defineProperty;var ir=Object.getOwnPropertyDescriptor;var sr=Object.getOwnPropertyNames;var ar=Object.prototype.hasOwnProperty;var dr=(e,t)=>{for(var r in t)ye(e,r,{get:t[r],enumerable:!0})},cr=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of sr(t))!ar.call(e,i)&&i!==r&&ye(e,i,{get:()=>t[i],enumerable:!(o=ir(t,i))||o.enumerable});return e};var lr=e=>cr(ye({},"__esModule",{value:!0}),e);var Br={};dr(Br,{BetterAuthError:()=>A,HIDE_METADATA:()=>C,MissingDependencyError:()=>Re,betterAuth:()=>Cr,capitalizeFirstLetter:()=>Ar,createCookieGetter:()=>xe,createLogger:()=>fe,deleteSessionCookie:()=>J,generateId:()=>x,generateState:()=>ke,getCookies:()=>Ue,logger:()=>b,parseCookies:()=>wr,parseSetCookieHeader:()=>yr,parseState:()=>pe,setSessionCookie:()=>L});module.exports=lr(Br);var G=require("better-call");var ue=require("better-call"),be=require("zod");var mr=require("@noble/ciphers/chacha"),we=require("@noble/ciphers/utils"),gr=require("@noble/ciphers/webcrypto"),hr=require("oslo/crypto");function ce(e,t){let r=new Uint8Array(e),o=new Uint8Array(t);if(r.length!==o.length)return!1;let i=0;for(let n=0;n<r.length;n++)i|=r[n]^o[n];return i===0}var ee=require("oslo/encoding");var Ne=require("@noble/hashes/scrypt"),W={N:16384,r:16,p:1,dkLen:64};async function Fe(e,t){return await(0,Ne.scryptAsync)(e.normalize("NFKC"),t,{N:W.N,p:W.p,r:W.r,dkLen:W.dkLen,maxmem:128*W.N*W.r*2})}var qe=async e=>{let t=(0,ee.encodeHex)(crypto.getRandomValues(new Uint8Array(16))),r=await Fe(e,t);return`${t}:${(0,ee.encodeHex)(r)}`},Ve=async(e,t)=>{let[r,o]=e.split(":"),i=await Fe(t,r);return ce(i,(0,ee.decodeHex)(o))};function ur(e){return e.toString(2).padStart(8,"0")}function pr(e){return[...e].map(t=>ur(t)).join("")}function $e(e){return parseInt(pr(e),2)}function fr(e){if(e<0||!Number.isInteger(e))throw new Error("Argument 'max' must be an integer greater than or equal to 0");let t=(e-1).toString(2).length,r=t%8,o=new Uint8Array(Math.ceil(t/8));crypto.getRandomValues(o),r!==0&&(o[0]&=(1<<r)-1);let i=$e(o);for(;i>=e;)crypto.getRandomValues(o),r!==0&&(o[0]&=(1<<r)-1),i=$e(o);return i}function je(e,t){let r="";for(let o=0;o<e;o++)r+=t[fr(t.length)];return r}function ze(...e){let t=new Set(e),r="";for(let o of t)o==="a-z"?r+="abcdefghijklmnopqrstuvwxyz":o==="A-Z"?r+="ABCDEFGHIJKLMNOPQRSTUVWXYZ":o==="0-9"?r+="0123456789":r+=o;return r}async function le(e,t){let r=new TextEncoder,o={name:"HMAC",hash:"SHA-256"},i=await crypto.subtle.importKey("raw",r.encode(e),o,!1,["sign","verify"]),n=await crypto.subtle.sign(o.name,i,r.encode(t));return btoa(String.fromCharCode(...new Uint8Array(n)))}var j=require("better-call"),Me=(0,j.createMiddleware)(async()=>({})),Z=(0,j.createMiddlewareCreator)({use:[Me,(0,j.createMiddleware)(async()=>({}))]}),y=(0,j.createEndpointCreator)({use:[Me]});var He=Z({body:be.z.object({csrfToken:be.z.string().optional()}).optional()},async e=>{if(e.request?.method!=="POST"||e.context.options.advanced?.disableCSRFCheck)return;let t=e.headers?.get("origin")||"";if(e.context.trustedOrigins.includes(t))return;let r=e.body?.csrfToken;if(!r)throw new ue.APIError("UNAUTHORIZED",{message:"CSRF Token is required"});let o=await e.getSignedCookie(e.context.authCookies.csrfToken.name,e.context.secret),[i,n]=o?.split("!")||[null,null];if(!r||!i||!n||i!==r)throw e.setCookie(e.context.authCookies.csrfToken.name,"",{maxAge:0}),new ue.APIError("UNAUTHORIZED",{message:"Invalid CSRF Token"});let a=await le(e.context.secret,i);if(n!==a)throw e.setCookie(e.context.authCookies.csrfToken.name,"",{maxAge:0}),new ue.APIError("UNAUTHORIZED",{message:"Invalid CSRF Token"})});var O=require("better-call"),It=require("oslo/oauth2"),P=require("zod");var Qe=require("oslo/oauth2"),te=require("zod");var Ae=require("oslo/crypto");async function Ke(e){let t=await(0,Ae.sha256)(typeof e=="string"?new TextEncoder().encode(e):e);return Buffer.from(t).toString("base64")}async function Ge(e,t){let r=await(0,Ae.sha256)(typeof e=="string"?new TextEncoder().encode(e):e),o=Buffer.from(t,"base64");return ce(r,o)}var eo=require("better-call");async function ke(e){let t=(0,Qe.generateState)(),r=JSON.stringify({code:t,callbackURL:e}),o=await Ke(r);return{raw:r,hash:o}}function pe(e){return te.z.object({code:te.z.string(),callbackURL:te.z.string().optional(),currentURL:te.z.string().optional()}).safeParse(JSON.parse(e))}var We=require("oslo");var A=class extends Error{constructor(t,r){super(t),this.name="BetterAuthError",this.message=t,this.cause=r,this.stack=""}},Re=class extends A{constructor(t){super(`The package "${t}" is required. Make sure it is installed.`,t)}};var re=require("std-env");function Ue(e){let r=(e.advanced?.useSecureCookies!==void 0?e.advanced?.useSecureCookies:e.baseURL!==void 0?!!e.baseURL.startsWith("https://"):re.isProduction)?"__Secure-":"",o="better-auth",i=e.session?.expiresIn||new We.TimeSpan(7,"d").seconds(),n=!!e.advanced?.crossSubDomainCookies?.enabled,a=n?e.advanced?.crossSubDomainCookies?.domain||(e.baseURL?new URL(e.baseURL).hostname:void 0):void 0;if(n&&!a)throw new A("baseURL is required when crossSubdomainCookies are enabled");let c=n?"none":"lax";return{sessionToken:{name:`${r}${o}.session_token`,options:{httpOnly:!0,sameSite:c,path:"/",secure:!!r,maxAge:i,...n?{domain:a}:{}}},csrfToken:{name:`${r}${o}.csrf_token`,options:{httpOnly:!0,sameSite:c,path:"/",secure:!!r,maxAge:60*60*24*7,...n?{domain:a}:{}}},state:{name:`${r}${o}.state`,options:{httpOnly:!0,sameSite:c,path:"/",secure:!!r,maxAge:60*15,...n?{domain:a}:{}}},pkCodeVerifier:{name:`${r}${o}.pk_code_verifier`,options:{httpOnly:!0,sameSite:c,path:"/",secure:!!r,maxAge:60*15,...n?{domain:a}:{}}},dontRememberToken:{name:`${r}${o}.dont_remember`,options:{httpOnly:!0,sameSite:c,path:"/",secure:!!r,...n?{domain:a}:{}}},nonce:{name:`${r}${o}.nonce`,options:{httpOnly:!0,sameSite:c,path:"/",secure:!!r,maxAge:60*15,...n?{domain:a}:{}}}}}function xe(e){let r=(e.advanced?.useSecureCookies!==void 0?e.advanced?.useSecureCookies:e.baseURL?.startsWith("https://")||re.isProduction)?"__Secure-":"",o="better-auth",i=e.advanced?.crossSubDomainCookies?.domain||(e.baseURL?new URL(e.baseURL).hostname:void 0);function n(a,c){let s=e.advanced?.crossSubDomainCookies?.enabled?e.advanced.crossSubDomainCookies.additionalCookies?.includes(a):void 0;return{name:re.env.NODE_ENV==="production"?`${r}${o}.${a}`:`${o}.${a}`,options:{secure:!!r,sameSite:"lax",path:"/",maxAge:60*15,...c,...s?{domain:i}:{}}}}return n}async function L(e,t,r,o){let i=e.context.authCookies.sessionToken.options;i.maxAge=r?void 0:e.context.sessionConfig.expiresIn,await e.setSignedCookie(e.context.authCookies.sessionToken.name,t,e.context.secret,{...i,...o}),r&&await e.setSignedCookie(e.context.authCookies.dontRememberToken.name,"true",e.context.secret,e.context.authCookies.dontRememberToken.options)}function J(e){e.setCookie(e.context.authCookies.sessionToken.name,"",{maxAge:0}),e.setCookie(e.context.authCookies.dontRememberToken.name,"",{maxAge:0})}function yr(e){let t=new Map;return e.split(", ").forEach(o=>{let[i,...n]=o.split("; "),[a,c]=i.split("="),s={value:c};n.forEach(d=>{let[l,p]=d.split("=");s[l.toLowerCase()]=p||!0}),t.set(a,s)}),t}function wr(e){let t=e.split("; "),r=new Map;return t.forEach(o=>{let[i,n]=o.split("=");r.set(i,n)}),r}var Te=require("better-call");var Ze=require("consola"),z=(0,Ze.createConsola)({formatOptions:{date:!1,colors:!0,compact:!0},defaults:{tag:"Better Auth"}}),fe=e=>({log:(...t)=>{!e?.disabled&&z.log("",...t)},error:(...t)=>{!e?.disabled&&z.error("",...t)},warn:(...t)=>{!e?.disabled&&z.warn("",...t)},info:(...t)=>{!e?.disabled&&z.info("",...t)},debug:(...t)=>{!e?.disabled&&z.debug("",...t)},box:(...t)=>{!e?.disabled&&z.box("",...t)},success:(...t)=>{!e?.disabled&&z.success("",...t)},break:(...t)=>{!e?.disabled&&console.log(`
|
|
2
2
|
`)}}),b=fe();var v=Z(async e=>{let t=e.body?.callbackURL||e.query?.callbackURL||e.query?.redirectTo||e.body?.redirectTo,r=e.headers?.get("referer"),o=e.query?.currentURL||r||e.context.baseURL,i=e.context.trustedOrigins;if(t?.includes("http")){let n=new URL(t).origin;if(!i.includes(n))throw b.error("Invalid callback URL",{callbackURL:t,trustedOrigins:i}),new Te.APIError("FORBIDDEN",{message:"Invalid callback URL"})}if(o!==e.context.baseURL){let n=new URL(o).origin;if(!i.includes(n))throw b.error("Invalid current URL",{currentURL:o,trustedOrigins:i}),new Te.APIError("FORBIDDEN",{message:"Invalid callback URL"})}});var rt=require("oslo/jwt");var Je=require("oslo/crypto");var q=require("std-env");function br(e){try{return new URL(e).pathname!=="/"}catch{throw new A(`Invalid base URL: ${e}. Please provide a valid base URL.`)}}function ve(e,t="/api/auth"){return br(e)?e:(t=t.startsWith("/")?t:`/${t}`,`${e}${t}`)}function oe(e,t){if(e)return ve(e,t);let r=q.env.BETTER_AUTH_URL||q.env.NEXT_PUBLIC_BETTER_AUTH_URL||q.env.PUBLIC_BETTER_AUTH_URL||q.env.NUXT_PUBLIC_BETTER_AUTH_URL||q.env.NUXT_PUBLIC_AUTH_URL||(q.env.BASE_URL!=="/"?q.env.BASE_URL:void 0);if(r)return ve(r,t);if(typeof window<"u")return ve(window.location.origin,t)}var Xe=require("oslo/encoding");async function Ye(e){let t=await(0,Je.sha256)(new TextEncoder().encode(e));return Xe.base64url.encode(new Uint8Array(t),{includePadding:!1})}function et(e){return{tokenType:e.token_type,accessToken:e.access_token,refreshToken:e.refresh_token,accessTokenExpiresAt:e.expires_at?new Date((Date.now()+e.expires_in)*1e3):void 0,scopes:e?.scope?typeof e.scope=="string"?e.scope.split(" "):e.scope:[],idToken:e.id_token}}async function E({id:e,options:t,authorizationEndpoint:r,state:o,codeVerifier:i,scopes:n,claims:a,disablePkce:c,redirectURI:s}){let d=new URL(r);if(d.searchParams.set("response_type","code"),d.searchParams.set("client_id",t.clientId),d.searchParams.set("state",o),d.searchParams.set("scope",n.join(" ")),d.searchParams.set("redirect_uri",t.redirectURI||s),!c&&i){let l=await Ye(i);d.searchParams.set("code_challenge_method","S256"),d.searchParams.set("code_challenge",l)}if(a){let l=a.reduce((p,u)=>(p[u]=null,p),{});d.searchParams.set("claims",JSON.stringify({id_token:{email:null,email_verified:null,...l}}))}return d}var tt=require("@better-fetch/fetch");async function k({code:e,codeVerifier:t,redirectURI:r,options:o,tokenEndpoint:i}){let n=new URLSearchParams;n.set("grant_type","authorization_code"),n.set("code",e),t&&n.set("code_verifier",t),n.set("redirect_uri",r),n.set("client_id",o.clientId),n.set("client_secret",o.clientSecret);let{data:a,error:c}=await(0,tt.betterFetch)(i,{method:"POST",body:n,headers:{"content-type":"application/x-www-form-urlencoded",accept:"application/json","user-agent":"better-auth"}});if(c)throw c;return et(a)}function Ee(e){let t=e.accessToken,r=e.refreshToken,o;try{o=e.accessTokenExpiresAt}catch{}return{accessToken:t,refreshToken:r,expiresAt:o}}var ot=e=>{let t="https://appleid.apple.com/auth/token";return{id:"apple",name:"Apple",createAuthorizationURL({state:r,scopes:o,redirectURI:i}){let n=e.scope||o||["email","name","openid"];return new URL(`https://appleid.apple.com/auth/authorize?client_id=${e.clientId}&response_type=code&redirect_uri=${i||e.redirectURI}&scope=${n.join(" ")}&state=${r}`)},validateAuthorizationCode:async({code:r,codeVerifier:o,redirectURI:i})=>k({code:r,codeVerifier:o,redirectURI:e.redirectURI||i,options:e,tokenEndpoint:t}),async getUserInfo(r){if(!r.idToken)return null;let o=(0,rt.parseJWT)(r.idToken)?.payload;return o?{user:{id:o.sub,name:o.name,email:o.email,emailVerified:o.email_verified==="true"},data:o}:null}}};var nt=require("@better-fetch/fetch");var it=e=>({id:"discord",name:"Discord",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let i=e.scope||r||["identify","email"];return new URL(`https://discord.com/api/oauth2/authorize?scope=${i.join("+")}&response_type=code&client_id=${e.clientId}&redirect_uri=${encodeURIComponent(e.redirectURI||o)}&state=${t}`)},validateAuthorizationCode:async({code:t,redirectURI:r})=>k({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://discord.com/api/oauth2/token"}),async getUserInfo(t){let{data:r,error:o}=await(0,nt.betterFetch)("https://discord.com/api/users/@me",{headers:{authorization:`Bearer ${t.accessToken}`}});if(o)return null;if(r.avatar===null){let i=r.discriminator==="0"?Number(BigInt(r.id)>>BigInt(22))%6:parseInt(r.discriminator)%5;r.image_url=`https://cdn.discordapp.com/embed/avatars/${i}.png`}else{let i=r.avatar.startsWith("a_")?"gif":"png";r.image_url=`https://cdn.discordapp.com/avatars/${r.id}/${r.avatar}.${i}`}return{user:{id:r.id,name:r.display_name||r.username||"",email:r.email,emailVerified:r.verified,image:r.image_url},data:r}}});var st=require("@better-fetch/fetch");var at=e=>({id:"facebook",name:"Facebook",async createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let i=e.scope||r||["email","public_profile"];return await E({id:"facebook",options:e,authorizationEndpoint:"https://www.facebook.com/v21.0/dialog/oauth",scopes:i,state:t,redirectURI:o})},validateAuthorizationCode:async({code:t,redirectURI:r})=>k({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://graph.facebook.com/oauth/access_token"}),async getUserInfo(t){let{data:r,error:o}=await(0,st.betterFetch)("https://graph.facebook.com/me?fields=id,name,email,picture",{auth:{type:"Bearer",token:t.accessToken}});return o?null:{user:{id:r.id,name:r.name,email:r.email,emailVerified:r.email_verified},data:r}}});var Ie=require("@better-fetch/fetch");var dt=e=>{let t="https://github.com/login/oauth/access_token";return{id:"github",name:"Github",createAuthorizationURL({state:r,scopes:o,codeVerifier:i,redirectURI:n}){let a=e.scope||o||["user:email"];return E({id:"github",options:e,authorizationEndpoint:"https://github.com/login/oauth/authorize",scopes:a,state:r,redirectURI:n,codeVerifier:i})},validateAuthorizationCode:async({code:r,redirectURI:o})=>k({code:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:t}),async getUserInfo(r){let{data:o,error:i}=await(0,Ie.betterFetch)("https://api.github.com/user",{headers:{"User-Agent":"better-auth",authorization:`Bearer ${r.accessToken}`}});if(i)return null;let n=!1;if(!o.email){let{data:a,error:c}=await(0,Ie.betterFetch)("https://api.github.com/user/emails",{headers:{authorization:`Bearer ${r.accessToken}`,"User-Agent":"better-auth"}});c||(o.email=(a.find(s=>s.primary)??a[0])?.email,n=a.find(s=>s.email===o.email)?.verified??!1)}return{user:{id:o.id.toString(),name:o.name||o.login,email:o.email,image:o.avatar_url,emailVerified:n},data:o}}}};var ct=require("oslo/jwt");var lt=e=>({id:"google",name:"Google",createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:i}){if(!e.clientId||!e.clientSecret)throw b.error("Client Id and Client Secret is required for Google. Make sure to provide them in the options."),new A("CLIENT_ID_AND_SECRET_REQUIRED");if(!o)throw new A("codeVerifier is required for Google");let n=e.scope||r||["email","profile"];return E({id:"google",options:e,authorizationEndpoint:"https://accounts.google.com/o/oauth2/auth",scopes:n,state:t,codeVerifier:o,redirectURI:i})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>k({code:t,codeVerifier:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://oauth2.googleapis.com/token"}),async getUserInfo(t){if(!t.idToken)return null;let r=(0,ct.parseJWT)(t.idToken)?.payload;return{user:{id:r.sub,name:r.name,email:r.email,image:r.picture,emailVerified:r.email_verified},data:r}}});var ut=require("@better-fetch/fetch"),pt=require("oslo/jwt");var ft=e=>{let t=e.tenantId||"common",r=`https://login.microsoftonline.com/${t}/oauth2/v2.0/authorize`,o=`https://login.microsoftonline.com/${t}/oauth2/v2.0/token`;return{id:"microsoft",name:"Microsoft EntraID",createAuthorizationURL(i){let n=e.scope||i.scopes||["openid","profile","email","User.Read"];return E({id:"microsoft",options:e,authorizationEndpoint:r,state:i.state,codeVerifier:i.codeVerifier,scopes:n,redirectURI:i.redirectURI})},validateAuthorizationCode({code:i,codeVerifier:n,redirectURI:a}){return k({code:i,codeVerifier:n,redirectURI:e.redirectURI||a,options:e,tokenEndpoint:o})},async getUserInfo(i){if(!i.idToken)return null;let n=(0,pt.parseJWT)(i.idToken)?.payload,a=e.profilePhotoSize||48;return await(0,ut.betterFetch)(`https://graph.microsoft.com/v1.0/me/photos/${a}x${a}/$value`,{headers:{Authorization:`Bearer ${i.accessToken}`},async onResponse(c){if(!(e.disableProfilePhoto||!c.response.ok))try{let d=await c.response.clone().arrayBuffer(),l=Buffer.from(d).toString("base64");n.picture=`data:image/jpeg;base64, ${l}`}catch(s){b.error(s)}}}),{user:{id:n.sub,name:n.name,email:n.email,image:n.picture,emailVerified:!0},data:n}}}};var mt=require("@better-fetch/fetch");var gt=e=>({id:"spotify",name:"Spotify",createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:i}){let n=e.scope||r||["user-read-email"];return E({id:"spotify",options:e,authorizationEndpoint:"https://accounts.spotify.com/authorize",scopes:n,state:t,codeVerifier:o,redirectURI:i})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>k({code:t,codeVerifier:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://accounts.spotify.com/api/token"}),async getUserInfo(t){let{data:r,error:o}=await(0,mt.betterFetch)("https://api.spotify.com/v1/me",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});return o?null:{user:{id:r.id,name:r.display_name,email:r.email,image:r.images[0]?.url,emailVerified:!1},data:r}}});var nn=require("@better-fetch/fetch");function Ar(e){return e.charAt(0).toUpperCase()+e.slice(1)}var C={isAction:!1};var ht=require("nanoid"),x=e=>(0,ht.nanoid)(e);var yt=require("oslo/jwt");var wt=e=>({id:"twitch",name:"Twitch",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let i=e.scope||r||["user:read:email","openid"];return E({id:"twitch",redirectURI:o,options:e,authorizationEndpoint:"https://id.twitch.tv/oauth2/authorize",scopes:i,state:t,claims:e.claims||["email","email_verified","preferred_username","picture"]})},validateAuthorizationCode:async({code:t,redirectURI:r})=>k({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://id.twitch.tv/oauth2/token"}),async getUserInfo(t){let r=t.idToken;if(!r)return b.error("No idToken found in token"),null;let o=(0,yt.parseJWT)(r)?.payload;return{user:{id:o.sub,name:o.preferred_username,email:o.email,image:o.picture,emailVerified:!1},data:o}}});var bt=require("@better-fetch/fetch");var At=e=>({id:"twitter",name:"Twitter",createAuthorizationURL(t){let r=e.scope||t.scopes||["account_info.read"];return E({id:"twitter",options:e,authorizationEndpoint:"https://twitter.com/i/oauth2/authorize",scopes:r,state:t.state,codeVerifier:t.codeVerifier,redirectURI:t.redirectURI})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>k({code:t,codeVerifier:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://id.twitch.tv/oauth2/token"}),async getUserInfo(t){let{data:r,error:o}=await(0,bt.betterFetch)("https://api.x.com/2/users/me?user.fields=profile_image_url",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});return o||!r.data.email?null:{user:{id:r.data.id,name:r.data.name,email:r.data.email,image:r.data.profile_image_url,emailVerified:r.data.verified||!1},data:r}}});var Pe={apple:ot,discord:it,facebook:at,github:dt,microsoft:ft,google:lt,spotify:gt,twitch:wt,twitter:At},kt=Object.keys(Pe);var Tt=require("oslo"),me=require("oslo/jwt"),S=require("zod");var H=require("better-call");var X=require("better-call");var M=(e,t="ms")=>new Date(Date.now()+(t==="sec"?e*1e3:e));var Se=require("zod"),Oe=()=>y("/session",{method:"GET",requireHeaders:!0},async e=>{try{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!t)return e.json(null,{status:401});let r=await e.context.internalAdapter.findSession(t);if(!r||r.session.expiresAt<new Date)return J(e),r&&await e.context.internalAdapter.deleteSession(r.session.id),e.json(null,{status:401});if(await e.getSignedCookie(e.context.authCookies.dontRememberToken.name,e.context.secret))return e.json(r);let i=e.context.sessionConfig.expiresIn,n=e.context.sessionConfig.updateAge;if(r.session.expiresAt.valueOf()-i*1e3+n*1e3<=Date.now()){let s=await e.context.internalAdapter.updateSession(r.session.id,{expiresAt:M(e.context.sessionConfig.expiresIn,"sec")});if(!s)return J(e),e.json(null,{status:401});let d=(s.expiresAt.valueOf()-Date.now())/1e3;return await L(e,s.id,!1,{maxAge:d}),e.json({session:s,user:r.user})}return e.json(r)}catch(t){return e.context.logger.error(t),e.json(null,{status:500})}}),Le=async e=>await Oe()({...e,_flag:"json",headers:e.headers}),B=Z(async e=>{let t=await Le(e);if(!t?.session)throw new X.APIError("UNAUTHORIZED");return{session:t}}),Rt=()=>y("/user/list-sessions",{method:"GET",use:[B],requireHeaders:!0},async e=>{let r=(await e.context.internalAdapter.listSessions(e.context.session.user.id)).filter(o=>o.expiresAt>new Date);return e.json(r)}),Ut=y("/user/revoke-session",{method:"POST",body:Se.z.object({id:Se.z.string()}),use:[B],requireHeaders:!0},async e=>{let t=e.body.id,r=await e.context.internalAdapter.findSession(t);if(!r)throw new X.APIError("BAD_REQUEST",{message:"Session not found"});if(r.session.userId!==e.context.session.user.id)throw new X.APIError("UNAUTHORIZED");try{await e.context.internalAdapter.deleteSession(t)}catch(o){throw e.context.logger.error(o),new X.APIError("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),xt=y("/user/revoke-sessions",{method:"POST",use:[B],requireHeaders:!0},async e=>{try{await e.context.internalAdapter.deleteSessions(e.context.session.user.id)}catch(t){throw e.context.logger.error(t),new X.APIError("INTERNAL_SERVER_ERROR")}return e.json({status:!0})});async function D(e,t,r){return await(0,me.createJWT)("HS256",Buffer.from(e),{email:t.toLowerCase(),updateTo:r},{expiresIn:new Tt.TimeSpan(1,"h"),issuer:"better-auth",subject:"verify-email",audiences:[t],includeIssuedTimestamp:!0})}var vt=y("/send-verification-email",{method:"POST",query:S.z.object({currentURL:S.z.string().optional()}).optional(),body:S.z.object({email:S.z.string().email(),callbackURL:S.z.string().optional()}),use:[v]},async e=>{if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),new H.APIError("BAD_REQUEST",{message:"Verification email isn't enabled"});let{email:t}=e.body,r=await e.context.internalAdapter.findUserByEmail(t);if(!r)throw new H.APIError("BAD_REQUEST",{message:"User not found"});let o=await D(e.context.secret,t),i=`${e.context.baseURL}/verify-email?token=${o}&callbackURL=${e.body.callbackURL||e.query?.currentURL||"/"}`;return await e.context.options.emailVerification.sendVerificationEmail(r.user,i,o),e.json({status:!0})}),Et=y("/verify-email",{method:"GET",query:S.z.object({token:S.z.string(),callbackURL:S.z.string().optional()}),use:[v]},async e=>{let{token:t}=e.query,r;try{r=await(0,me.validateJWT)("HS256",Buffer.from(e.context.secret),t)}catch(a){throw e.context.logger.error("Failed to verify email",a),new H.APIError("BAD_REQUEST",{message:"Invalid token"})}let i=S.z.object({email:S.z.string().email(),updateTo:S.z.string().optional()}).parse(r.payload);if(!await e.context.internalAdapter.findUserByEmail(i.email))throw new H.APIError("BAD_REQUEST",{message:"User not found"});if(i.updateTo){let a=await Le(e);if(!a)throw e.query.callbackURL?e.redirect(`${e.query.callbackURL}?error=unauthorized`):new H.APIError("UNAUTHORIZED",{message:"Session not found"});if(a.user.email!==i.email)throw e.query.callbackURL?e.redirect(`${e.query.callbackURL}?error=unauthorized`):new H.APIError("UNAUTHORIZED",{message:"Invalid session"});let c=await e.context.internalAdapter.updateUserByEmail(i.email,{email:i.updateTo});if(await e.context.options.emailVerification?.sendVerificationEmail?.(c,`${e.context.baseURL}/verify-email?token=${t}`,t),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({user:c,status:!0})}if(await e.context.internalAdapter.updateUserByEmail(i.email,{emailVerified:!0}),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({user:null,status:!0})});var Pt=y("/sign-in/social",{method:"POST",requireHeaders:!0,query:P.z.object({currentURL:P.z.string().optional()}).optional(),body:P.z.object({callbackURL:P.z.string().optional(),provider:P.z.enum(kt)}),use:[v]},async e=>{let t=e.context.socialProviders.find(s=>s.id===e.body.provider);if(!t)throw e.context.logger.error("Provider not found. Make sure to add the provider in your auth config",{provider:e.body.provider}),new O.APIError("NOT_FOUND",{message:"Provider not found"});let r=e.context.authCookies,o=e.query?.currentURL?new URL(e.query?.currentURL):null,i=e.body.callbackURL?.startsWith("http")?e.body.callbackURL:`${o?.origin}${e.body.callbackURL||""}`,n=await ke(i||o?.origin||e.context.options.baseURL);await e.setSignedCookie(r.state.name,n.hash,e.context.secret,r.state.options);let a=(0,It.generateCodeVerifier)();await e.setSignedCookie(r.pkCodeVerifier.name,a,e.context.secret,r.pkCodeVerifier.options);let c=await t.createAuthorizationURL({state:n.raw,codeVerifier:a,redirectURI:`${e.context.baseURL}/callback/${t.id}`});return e.json({url:c.toString(),state:n,codeVerifier:a,redirect:!0})}),St=y("/sign-in/email",{method:"POST",body:P.z.object({email:P.z.string(),password:P.z.string(),callbackURL:P.z.string().optional(),dontRememberMe:P.z.boolean().default(!1).optional()}),use:[v]},async e=>{if(!e.context.options?.emailAndPassword?.enabled)throw e.context.logger.error("Email and password is not enabled. Make sure to enable it in the options on you `auth.ts` file. Check `https://better-auth.com/docs/authentication/email-password` for more!"),new O.APIError("BAD_REQUEST",{message:"Email and password is not enabled"});let{email:t,password:r}=e.body;if(!P.z.string().email().safeParse(t).success)throw new O.APIError("BAD_REQUEST",{message:"Invalid email"});if(!P.z.string().email().safeParse(t).success)throw new O.APIError("BAD_REQUEST",{message:"Invalid email"});let n=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!n)throw await e.context.password.hash(r),e.context.logger.error("User not found",{email:t}),new O.APIError("UNAUTHORIZED",{message:"Invalid email or password"});let a=n.accounts.find(l=>l.providerId==="credential");if(!a)throw e.context.logger.error("Credential account not found",{email:t}),new O.APIError("UNAUTHORIZED",{message:"Invalid email or password"});let c=a?.password;if(!c)throw e.context.logger.error("Password not found",{email:t}),new O.APIError("UNAUTHORIZED",{message:"Unexpected error"});if(!await e.context.password.verify(c,r))throw e.context.logger.error("Invalid password"),new O.APIError("UNAUTHORIZED",{message:"Invalid email or password"});if(e.context.options?.emailAndPassword?.requireEmailVerification&&!n.user.emailVerified){if(!e.context.options?.emailVerification?.sendVerificationEmail)throw b.error("Email verification is required but no email verification handler is provided"),new O.APIError("INTERNAL_SERVER_ERROR",{message:"Email is not verified."});let l=await D(e.context.secret,n.user.email),p=`${e.context.options.baseURL}/verify-email?token=${l}`;throw await e.context.options.emailVerification.sendVerificationEmail(n.user,p,l),e.context.logger.error("Email not verified",{email:t}),new O.APIError("FORBIDDEN",{message:"Email is not verified. Check your email for a verification link"})}let d=await e.context.internalAdapter.createSession(n.user.id,e.headers,e.body.dontRememberMe);if(!d)throw e.context.logger.error("Failed to create session"),new O.APIError("UNAUTHORIZED",{message:"Failed to create session"});return await L(e,d.id,e.body.dontRememberMe),e.json({user:n.user,session:d,redirect:!!e.body.callbackURL,url:e.body.callbackURL})});var ne=require("zod");var w=require("zod"),Qn=w.z.object({id:w.z.string(),providerId:w.z.string(),accountId:w.z.string(),userId:w.z.string(),accessToken:w.z.string().nullable().optional(),refreshToken:w.z.string().nullable().optional(),idToken:w.z.string().nullable().optional(),expiresAt:w.z.date().nullable().optional(),password:w.z.string().optional().nullable()}),Ot=w.z.object({id:w.z.string(),email:w.z.string().transform(e=>e.toLowerCase()),emailVerified:w.z.boolean().default(!1),name:w.z.string(),image:w.z.string().optional(),createdAt:w.z.date().default(new Date),updatedAt:w.z.date().default(new Date)}),Wn=w.z.object({id:w.z.string(),userId:w.z.string(),expiresAt:w.z.date(),ipAddress:w.z.string().optional(),userAgent:w.z.string().optional()}),Zn=w.z.object({id:w.z.string(),value:w.z.string(),expiresAt:w.z.date(),identifier:w.z.string()});function kr(e,t){let r=t.fields,o={};for(let i in r){if(i in e){if(r[i].input===!1){if(r[i].defaultValue){o[i]=r[i].defaultValue;continue}continue}o[i]=e[i];continue}if(r[i].defaultValue){o[i]=r[i].defaultValue;continue}}return o}function Lt(e,t){let r={...e.user?.additionalFields};return kr(t||{},{fields:r})}var _t=y("/callback/:id",{method:"GET",query:ne.z.object({state:ne.z.string(),code:ne.z.string().optional(),error:ne.z.string().optional()}),metadata:C},async e=>{if(e.query.error||!e.query.code){let U=pe(e.query.state).data?.callbackURL||`${e.context.baseURL}/error`;throw e.context.logger.error(e.query.error,e.params.id),e.redirect(`${U}?error=${e.query.error||"oAuth_code_missing"}`)}let t=e.context.socialProviders.find(g=>g.id===e.params.id);if(!t)throw e.context.logger.error("Oauth provider with id",e.params.id,"not found"),e.redirect(`${e.context.baseURL}/error?error=oauth_provider_not_found`);let r=pe(e.query.state);if(!r.success)throw e.context.logger.error("Unable to parse state"),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);let{data:{callbackURL:o,currentURL:i}}=r,n=await e.getSignedCookie(e.context.authCookies.state.name,e.context.secret);if(!n)throw b.error("No stored state found"),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);if(!await Ge(e.query.state,n))throw b.error("OAuth state mismatch"),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);let c=await e.getSignedCookie(e.context.authCookies.pkCodeVerifier.name,e.context.secret),s;try{s=await t.validateAuthorizationCode({code:e.query.code,codeVerifier:c,redirectURI:`${e.context.baseURL}/callback/${t.id}`})}catch(g){throw e.context.logger.error(g),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`)}let d=await t.getUserInfo(s).then(g=>g?.user),l=x(),p=Ot.safeParse({...d,id:l});if(!d||p.success===!1)throw b.error("Unable to get user info",p.error),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);if(!o)throw e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);function u(g){throw e.redirect(`${i||o||`${e.context.baseURL}/error`}?error=${g}`)}let f=await e.context.internalAdapter.findUserByEmail(d.email,{includeAccounts:!0}).catch(g=>{throw b.error(`Better auth was unable to query your database.
|
|
3
3
|
Error: `,g),e.redirect(`${e.context.baseURL}/error?error=internal_server_error`)}),m=f?.user.id;if(f){if(!f.accounts.find(U=>U.providerId===t.id)){(!e.context.options.account?.accountLinking?.trustedProviders?.includes(t.id)&&!d.emailVerified||!e.context.options.account?.accountLinking?.enabled)&&u("account_not_linked");try{await e.context.internalAdapter.linkAccount({providerId:t.id,accountId:d.id.toString(),id:`${t.id}:${d.id}`,userId:f.user.id,...Ee(s)})}catch($){b.error("Unable to link account",$),u("unable_to_link_account")}}}else try{let g=d.emailVerified||!1,U=await e.context.internalAdapter.createOAuthUser({...p.data,emailVerified:g},{...Ee(s),providerId:t.id,accountId:d.id.toString()});if(m=U?.user.id,!g&&U&&e.context.options.emailVerification?.sendOnSignUp){let Y=await D(e.context.secret,d.email),$=`${e.context.baseURL}/verify-email?token=${Y}&callbackURL=${o}`;await e.context.options.emailVerification?.sendVerificationEmail?.(U.user,$,Y)}}catch(g){b.error("Unable to create user",g),u("unable_to_create_user")}m||u("unable_to_create_user");let h=await e.context.internalAdapter.createSession(m,e.request);throw h||u("unable_to_create_session"),await L(e,h.id),e.redirect(o)});var ci=require("zod");var Ct=require("better-call");var Bt=y("/sign-out",{method:"POST"},async e=>{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!t)throw new Ct.APIError("BAD_REQUEST",{message:"Session not found"});return await e.context.internalAdapter.deleteSession(t),J(e),e.json({success:!0})});var _=require("zod");var ie=require("better-call");var Dt=y("/forget-password",{method:"POST",body:_.z.object({email:_.z.string().email(),redirectTo:_.z.string()}),use:[v]},async e=>{if(!e.context.options.emailAndPassword?.sendResetPassword)throw e.context.logger.error("Reset password isn't enabled.Please pass an emailAndPassword.sendResetPasswordToken function in your auth config!"),new ie.APIError("BAD_REQUEST",{message:"Reset password isn't enabled"});let{email:t,redirectTo:r}=e.body,o=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!o)return e.context.logger.error("Reset Password: User not found",{email:t}),e.json({status:!1},{body:{status:!0}});let i=60*60*1,n=new Date(Date.now()+1e3*(e.context.options.emailAndPassword.resetPasswordTokenExpiresIn||i)),a=e.context.uuid();await e.context.internalAdapter.createVerificationValue({value:o.user.id,identifier:`reset-password:${a}`,expiresAt:n});let c=`${e.context.baseURL}/reset-password/${a}?callbackURL=${r}`;return await e.context.options.emailAndPassword.sendResetPassword(o.user,c),e.json({status:!0})}),Nt=y("/reset-password/:token",{method:"GET",query:_.z.object({callbackURL:_.z.string()}),use:[v]},async e=>{let{token:t}=e.params,r=e.query.callbackURL,o=r.startsWith("http")?r:`${e.context.options.baseURL}${r}`;if(!t||!r)throw e.redirect(`${e.context.baseURL}/error?error=INVALID_TOKEN`);let i=await e.context.internalAdapter.findVerificationValue(`reset-password:${t}`);throw!i||i.expiresAt<new Date?e.redirect(`${o}?error=INVALID_TOKEN`):e.redirect(`${o}?token=${t}`)}),Ft=y("/reset-password",{query:_.z.optional(_.z.object({token:_.z.string()})),method:"POST",body:_.z.object({newPassword:_.z.string()})},async e=>{let t=e.query?.token;if(!t)throw new ie.APIError("BAD_REQUEST",{message:"Token not found"});let{newPassword:r}=e.body,o=`reset-password:${t}`,i=await e.context.internalAdapter.findVerificationValue(o);if(!i||i.expiresAt<new Date)throw new ie.APIError("BAD_REQUEST",{message:"Invalid token"});await e.context.internalAdapter.deleteVerificationValue(i.id);let n=i.value,a=await e.context.password.hash(r);if(!(await e.context.internalAdapter.findAccounts(n)).find(l=>l.providerId==="credential"))return await e.context.internalAdapter.createAccount({userId:n,providerId:"credential",password:a,accountId:e.context.uuid()}),e.json({status:!0});if(!await e.context.internalAdapter.updatePassword(n,a))throw new ie.APIError("BAD_REQUEST",{message:"Failed to update password"});return e.json({status:!0})});var R=require("zod");var T=require("better-call");var qt=y("/user/update",{method:"POST",body:R.z.object({name:R.z.string().optional(),image:R.z.string().optional()}),use:[B,v]},async e=>{let{name:t,image:r}=e.body,o=e.context.session;if(!r&&!t)return e.json({user:o.user});let i=await e.context.internalAdapter.updateUserByEmail(o.user.email,{name:t,image:r});return e.json({user:i})}),Vt=y("/user/change-password",{method:"POST",body:R.z.object({newPassword:R.z.string(),currentPassword:R.z.string(),revokeOtherSessions:R.z.boolean().optional()}),use:[B]},async e=>{let{newPassword:t,currentPassword:r,revokeOtherSessions:o}=e.body,i=e.context.session,n=e.context.password.config.minPasswordLength;if(t.length<n)throw e.context.logger.error("Password is too short"),new T.APIError("BAD_REQUEST",{message:"Password is too short"});let a=e.context.password.config.maxPasswordLength;if(t.length>a)throw e.context.logger.error("Password is too long"),new T.APIError("BAD_REQUEST",{message:"Password too long"});let s=(await e.context.internalAdapter.findAccounts(i.user.id)).find(p=>p.providerId==="credential"&&p.password);if(!s||!s.password)throw new T.APIError("BAD_REQUEST",{message:"User does not have a password"});let d=await e.context.password.hash(t);if(!await e.context.password.verify(s.password,r))throw new T.APIError("BAD_REQUEST",{message:"Incorrect password"});if(await e.context.internalAdapter.updateAccount(s.id,{password:d}),o){await e.context.internalAdapter.deleteSessions(i.user.id);let p=await e.context.internalAdapter.createSession(i.user.id,e.headers);if(!p)throw new T.APIError("INTERNAL_SERVER_ERROR",{message:"Unable to create session"});await L(e,p.id)}return e.json(i.user)}),$t=y("/user/set-password",{method:"POST",body:R.z.object({newPassword:R.z.string()}),use:[B]},async e=>{let{newPassword:t}=e.body,r=e.context.session,o=e.context.password.config.minPasswordLength;if(t.length<o)throw e.context.logger.error("Password is too short"),new T.APIError("BAD_REQUEST",{message:"Password is too short"});let i=e.context.password.config.maxPasswordLength;if(t.length>i)throw e.context.logger.error("Password is too long"),new T.APIError("BAD_REQUEST",{message:"Password too long"});let a=(await e.context.internalAdapter.findAccounts(r.user.id)).find(s=>s.providerId==="credential"&&s.password),c=await e.context.password.hash(t);if(!a)return await e.context.internalAdapter.linkAccount({userId:r.user.id,providerId:"credential",accountId:r.user.id,password:c}),e.json(r.user);throw new T.APIError("BAD_REQUEST",{message:"user already has a password"})}),jt=y("/user/delete",{method:"POST",body:R.z.object({password:R.z.string()}),use:[B]},async e=>{let{password:t}=e.body,r=e.context.session,i=(await e.context.internalAdapter.findAccounts(r.user.id)).find(a=>a.providerId==="credential"&&a.password);if(!i||!i.password)throw new T.APIError("BAD_REQUEST",{message:"User does not have a password"});if(!await e.context.password.verify(i.password,t))throw new T.APIError("BAD_REQUEST",{message:"Incorrect password"});return await e.context.internalAdapter.deleteUser(r.user.id),await e.context.internalAdapter.deleteSessions(r.user.id),e.json(null)}),zt=y("/user/change-email",{method:"POST",query:R.z.object({currentURL:R.z.string().optional()}).optional(),body:R.z.object({newEmail:R.z.string().email(),callbackURL:R.z.string().optional()}),use:[B,v]},async e=>{if(!e.context.options.user?.changeEmail?.enabled)throw e.context.logger.error("Change email is disabled."),new T.APIError("BAD_REQUEST",{message:"Change email is disabled"});if(e.body.newEmail===e.context.session.user.email)throw e.context.logger.error("Email is the same"),new T.APIError("BAD_REQUEST",{message:"Email is the same"});if(await e.context.internalAdapter.findUserByEmail(e.body.newEmail))throw e.context.logger.error("Email already exists"),new T.APIError("BAD_REQUEST",{message:"Couldn't update your email"});if(e.context.session.user.emailVerified!==!0){let i=await e.context.internalAdapter.updateUserByEmail(e.context.session.user.email,{email:e.body.newEmail});return e.json({user:i,status:!0})}if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),new T.APIError("BAD_REQUEST",{message:"Verification email isn't enabled"});let r=await D(e.context.secret,e.context.session.user.email,e.body.newEmail),o=`${e.context.baseURL}/verify-email?token=${r}&callbackURL=${e.body.callbackURL||e.query?.currentURL||"/"}`;return await e.context.options.emailVerification.sendVerificationEmail(e.context.session.user,o,r),e.json({user:null,status:!0})});var Mt=y("/csrf",{method:"GET",metadata:C},async e=>{let t=await e.getSignedCookie(e.context.authCookies.csrfToken.name,e.context.secret);if(t){let[n,a]=t.split("!")||[null,null];return e.json({csrfToken:n})}let r=je(32,ze("a-z","0-9","A-Z")),o=await le(e.context.secret,r),i=`${r}!${o}`;return await e.setSignedCookie(e.context.authCookies.csrfToken.name,i,e.context.secret,e.context.authCookies.csrfToken.options),e.json({csrfToken:r})});var Rr=(e="Unknown")=>`<!DOCTYPE html>
|
|
4
4
|
<html lang="en">
|
package/dist/index.d.cts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { A as Adapter, j as AdditionalSessionFieldsInput, k as AdditionalSessionFieldsOutput, h as AdditionalUserFieldsInput, i as AdditionalUserFieldsOutput, a as Auth, p as AuthContext, s as BetterAuthCookies, B as BetterAuthOptions, b as BetterAuthPlugin, E as EligibleCookies, G as GenericEndpointContext, H as HookEndpointContext, m as InferPluginTypes, l as InferSession, I as InferUser, P as PluginSchema, R as RateLimit, S as SecondaryStorage, W as Where, g as betterAuth, r as createCookieGetter, x as createLogger, u as deleteSessionCookie, q as getCookies, n as init, y as logger, w as parseCookies, v as parseSetCookieHeader, t as setSessionCookie } from './auth-
|
|
1
|
+
export { A as Adapter, j as AdditionalSessionFieldsInput, k as AdditionalSessionFieldsOutput, h as AdditionalUserFieldsInput, i as AdditionalUserFieldsOutput, a as Auth, p as AuthContext, s as BetterAuthCookies, B as BetterAuthOptions, b as BetterAuthPlugin, E as EligibleCookies, G as GenericEndpointContext, H as HookEndpointContext, m as InferPluginTypes, l as InferSession, I as InferUser, P as PluginSchema, R as RateLimit, S as SecondaryStorage, W as Where, g as betterAuth, r as createCookieGetter, x as createLogger, u as deleteSessionCookie, q as getCookies, n as init, y as logger, w as parseCookies, v as parseSetCookieHeader, t as setSessionCookie } from './auth-D7_h4yVD.cjs';
|
|
2
2
|
export { D as DeepPartial, H as HasRequiredKeys, L as LiteralString, a as LiteralUnion, P as Prettify, R as RequiredKeysOf, S as StripEmptyObjects, U as UnionToIntersection, W as WithoutEmpty } from './helper-DPDj8Nix.cjs';
|
|
3
3
|
export { AtomListener, BetterAuthClientPlugin, ClientOptions, InferActions, InferAdditionalFromClient, InferClientAPI, InferPluginsFromClient, InferSessionFromClient, InferUserFromClient, IsSignal } from './types.cjs';
|
|
4
4
|
export { H as HIDE_METADATA } from './hide-metadata-DEHJp1rk.cjs';
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { A as Adapter, j as AdditionalSessionFieldsInput, k as AdditionalSessionFieldsOutput, h as AdditionalUserFieldsInput, i as AdditionalUserFieldsOutput, a as Auth, p as AuthContext, s as BetterAuthCookies, B as BetterAuthOptions, b as BetterAuthPlugin, E as EligibleCookies, G as GenericEndpointContext, H as HookEndpointContext, m as InferPluginTypes, l as InferSession, I as InferUser, P as PluginSchema, R as RateLimit, S as SecondaryStorage, W as Where, g as betterAuth, r as createCookieGetter, x as createLogger, u as deleteSessionCookie, q as getCookies, n as init, y as logger, w as parseCookies, v as parseSetCookieHeader, t as setSessionCookie } from './auth-
|
|
1
|
+
export { A as Adapter, j as AdditionalSessionFieldsInput, k as AdditionalSessionFieldsOutput, h as AdditionalUserFieldsInput, i as AdditionalUserFieldsOutput, a as Auth, p as AuthContext, s as BetterAuthCookies, B as BetterAuthOptions, b as BetterAuthPlugin, E as EligibleCookies, G as GenericEndpointContext, H as HookEndpointContext, m as InferPluginTypes, l as InferSession, I as InferUser, P as PluginSchema, R as RateLimit, S as SecondaryStorage, W as Where, g as betterAuth, r as createCookieGetter, x as createLogger, u as deleteSessionCookie, q as getCookies, n as init, y as logger, w as parseCookies, v as parseSetCookieHeader, t as setSessionCookie } from './auth-D1kVkHCi.js';
|
|
2
2
|
export { D as DeepPartial, H as HasRequiredKeys, L as LiteralString, a as LiteralUnion, P as Prettify, R as RequiredKeysOf, S as StripEmptyObjects, U as UnionToIntersection, W as WithoutEmpty } from './helper-DPDj8Nix.js';
|
|
3
3
|
export { AtomListener, BetterAuthClientPlugin, ClientOptions, InferActions, InferAdditionalFromClient, InferClientAPI, InferPluginsFromClient, InferSessionFromClient, InferUserFromClient, IsSignal } from './types.js';
|
|
4
4
|
export { H as HIDE_METADATA } from './hide-metadata-DEHJp1rk.js';
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{APIError as xt,createRouter as Rr,statusCode as Ur}from"better-call";import{APIError as se}from"better-call";import{z as Ie}from"zod";import{xchacha20poly1305 as Dr}from"@noble/ciphers/chacha";import{bytesToHex as Fr,hexToBytes as qr,utf8ToBytes as Vr}from"@noble/ciphers/utils";import{managedNonce as jr}from"@noble/ciphers/webcrypto";import{sha256 as Mr}from"oslo/crypto";function Y(e,t){let r=new Uint8Array(e),o=new Uint8Array(t);if(r.length!==o.length)return!1;let i=0;for(let n=0;n<r.length;n++)i|=r[n]^o[n];return i===0}import{decodeHex as Nt,encodeHex as be}from"oslo/encoding";import{scryptAsync as Ft}from"@noble/hashes/scrypt";var z={N:16384,r:16,p:1,dkLen:64};async function Ae(e,t){return await Ft(e.normalize("NFKC"),t,{N:z.N,p:z.p,r:z.r,dkLen:z.dkLen,maxmem:128*z.N*z.r*2})}var ke=async e=>{let t=be(crypto.getRandomValues(new Uint8Array(16))),r=await Ae(e,t);return`${t}:${be(r)}`},Re=async(e,t)=>{let[r,o]=e.split(":"),i=await Ae(t,r);return Y(i,Nt(o))};function qt(e){return e.toString(2).padStart(8,"0")}function Vt(e){return[...e].map(t=>qt(t)).join("")}function Ue(e){return parseInt(Vt(e),2)}function $t(e){if(e<0||!Number.isInteger(e))throw new Error("Argument 'max' must be an integer greater than or equal to 0");let t=(e-1).toString(2).length,r=t%8,o=new Uint8Array(Math.ceil(t/8));crypto.getRandomValues(o),r!==0&&(o[0]&=(1<<r)-1);let i=Ue(o);for(;i>=e;)crypto.getRandomValues(o),r!==0&&(o[0]&=(1<<r)-1),i=Ue(o);return i}function xe(e,t){let r="";for(let o=0;o<e;o++)r+=t[$t(t.length)];return r}function Te(...e){let t=new Set(e),r="";for(let o of t)o==="a-z"?r+="abcdefghijklmnopqrstuvwxyz":o==="A-Z"?r+="ABCDEFGHIJKLMNOPQRSTUVWXYZ":o==="0-9"?r+="0123456789":r+=o;return r}async function ee(e,t){let r=new TextEncoder,o={name:"HMAC",hash:"SHA-256"},i=await crypto.subtle.importKey("raw",r.encode(e),o,!1,["sign","verify"]),n=await crypto.subtle.sign(o.name,i,r.encode(t));return btoa(String.fromCharCode(...new Uint8Array(n)))}import{createEndpointCreator as jt,createMiddleware as ve,createMiddlewareCreator as zt}from"better-call";var Ee=ve(async()=>({})),M=zt({use:[Ee,ve(async()=>({}))]}),y=jt({use:[Ee]});var Pe=M({body:Ie.object({csrfToken:Ie.string().optional()}).optional()},async e=>{if(e.request?.method!=="POST"||e.context.options.advanced?.disableCSRFCheck)return;let t=
|
|
1
|
+
import{APIError as xt,createRouter as Rr,statusCode as Ur}from"better-call";import{APIError as se}from"better-call";import{z as Ie}from"zod";import{xchacha20poly1305 as Dr}from"@noble/ciphers/chacha";import{bytesToHex as Fr,hexToBytes as qr,utf8ToBytes as Vr}from"@noble/ciphers/utils";import{managedNonce as jr}from"@noble/ciphers/webcrypto";import{sha256 as Mr}from"oslo/crypto";function Y(e,t){let r=new Uint8Array(e),o=new Uint8Array(t);if(r.length!==o.length)return!1;let i=0;for(let n=0;n<r.length;n++)i|=r[n]^o[n];return i===0}import{decodeHex as Nt,encodeHex as be}from"oslo/encoding";import{scryptAsync as Ft}from"@noble/hashes/scrypt";var z={N:16384,r:16,p:1,dkLen:64};async function Ae(e,t){return await Ft(e.normalize("NFKC"),t,{N:z.N,p:z.p,r:z.r,dkLen:z.dkLen,maxmem:128*z.N*z.r*2})}var ke=async e=>{let t=be(crypto.getRandomValues(new Uint8Array(16))),r=await Ae(e,t);return`${t}:${be(r)}`},Re=async(e,t)=>{let[r,o]=e.split(":"),i=await Ae(t,r);return Y(i,Nt(o))};function qt(e){return e.toString(2).padStart(8,"0")}function Vt(e){return[...e].map(t=>qt(t)).join("")}function Ue(e){return parseInt(Vt(e),2)}function $t(e){if(e<0||!Number.isInteger(e))throw new Error("Argument 'max' must be an integer greater than or equal to 0");let t=(e-1).toString(2).length,r=t%8,o=new Uint8Array(Math.ceil(t/8));crypto.getRandomValues(o),r!==0&&(o[0]&=(1<<r)-1);let i=Ue(o);for(;i>=e;)crypto.getRandomValues(o),r!==0&&(o[0]&=(1<<r)-1),i=Ue(o);return i}function xe(e,t){let r="";for(let o=0;o<e;o++)r+=t[$t(t.length)];return r}function Te(...e){let t=new Set(e),r="";for(let o of t)o==="a-z"?r+="abcdefghijklmnopqrstuvwxyz":o==="A-Z"?r+="ABCDEFGHIJKLMNOPQRSTUVWXYZ":o==="0-9"?r+="0123456789":r+=o;return r}async function ee(e,t){let r=new TextEncoder,o={name:"HMAC",hash:"SHA-256"},i=await crypto.subtle.importKey("raw",r.encode(e),o,!1,["sign","verify"]),n=await crypto.subtle.sign(o.name,i,r.encode(t));return btoa(String.fromCharCode(...new Uint8Array(n)))}import{createEndpointCreator as jt,createMiddleware as ve,createMiddlewareCreator as zt}from"better-call";var Ee=ve(async()=>({})),M=zt({use:[Ee,ve(async()=>({}))]}),y=jt({use:[Ee]});var Pe=M({body:Ie.object({csrfToken:Ie.string().optional()}).optional()},async e=>{if(e.request?.method!=="POST"||e.context.options.advanced?.disableCSRFCheck)return;let t=e.headers?.get("origin")||"";if(e.context.trustedOrigins.includes(t))return;let r=e.body?.csrfToken;if(!r)throw new se("UNAUTHORIZED",{message:"CSRF Token is required"});let o=await e.getSignedCookie(e.context.authCookies.csrfToken.name,e.context.secret),[i,n]=o?.split("!")||[null,null];if(!r||!i||!n||i!==r)throw e.setCookie(e.context.authCookies.csrfToken.name,"",{maxAge:0}),new se("UNAUTHORIZED",{message:"Invalid CSRF Token"});let a=await ee(e.context.secret,i);if(n!==a)throw e.setCookie(e.context.authCookies.csrfToken.name,"",{maxAge:0}),new se("UNAUTHORIZED",{message:"Invalid CSRF Token"})});import{APIError as O}from"better-call";import{generateCodeVerifier as ur}from"oslo/oauth2";import{z as P}from"zod";import{generateState as Mt}from"oslo/oauth2";import{z as te}from"zod";import{sha256 as Se}from"oslo/crypto";async function Oe(e){let t=await Se(typeof e=="string"?new TextEncoder().encode(e):e);return Buffer.from(t).toString("base64")}async function Le(e,t){let r=await Se(typeof e=="string"?new TextEncoder().encode(e):e),o=Buffer.from(t,"base64");return Y(r,o)}import"better-call";async function _e(e){let t=Mt(),r=JSON.stringify({code:t,callbackURL:e}),o=await Oe(r);return{raw:r,hash:o}}function ae(e){return te.object({code:te.string(),callbackURL:te.string().optional(),currentURL:te.string().optional()}).safeParse(JSON.parse(e))}import{TimeSpan as Ht}from"oslo";var k=class extends Error{constructor(t,r){super(t),this.name="BetterAuthError",this.message=t,this.cause=r,this.stack=""}},Ce=class extends k{constructor(t){super(`The package "${t}" is required. Make sure it is installed.`,t)}};import{env as Kt,isProduction as Be}from"std-env";function De(e){let r=(e.advanced?.useSecureCookies!==void 0?e.advanced?.useSecureCookies:e.baseURL!==void 0?!!e.baseURL.startsWith("https://"):Be)?"__Secure-":"",o="better-auth",i=e.session?.expiresIn||new Ht(7,"d").seconds(),n=!!e.advanced?.crossSubDomainCookies?.enabled,a=n?e.advanced?.crossSubDomainCookies?.domain||(e.baseURL?new URL(e.baseURL).hostname:void 0):void 0;if(n&&!a)throw new k("baseURL is required when crossSubdomainCookies are enabled");let c=n?"none":"lax";return{sessionToken:{name:`${r}${o}.session_token`,options:{httpOnly:!0,sameSite:c,path:"/",secure:!!r,maxAge:i,...n?{domain:a}:{}}},csrfToken:{name:`${r}${o}.csrf_token`,options:{httpOnly:!0,sameSite:c,path:"/",secure:!!r,maxAge:60*60*24*7,...n?{domain:a}:{}}},state:{name:`${r}${o}.state`,options:{httpOnly:!0,sameSite:c,path:"/",secure:!!r,maxAge:60*15,...n?{domain:a}:{}}},pkCodeVerifier:{name:`${r}${o}.pk_code_verifier`,options:{httpOnly:!0,sameSite:c,path:"/",secure:!!r,maxAge:60*15,...n?{domain:a}:{}}},dontRememberToken:{name:`${r}${o}.dont_remember`,options:{httpOnly:!0,sameSite:c,path:"/",secure:!!r,...n?{domain:a}:{}}},nonce:{name:`${r}${o}.nonce`,options:{httpOnly:!0,sameSite:c,path:"/",secure:!!r,maxAge:60*15,...n?{domain:a}:{}}}}}function Ne(e){let r=(e.advanced?.useSecureCookies!==void 0?e.advanced?.useSecureCookies:e.baseURL?.startsWith("https://")||Be)?"__Secure-":"",o="better-auth",i=e.advanced?.crossSubDomainCookies?.domain||(e.baseURL?new URL(e.baseURL).hostname:void 0);function n(a,c){let s=e.advanced?.crossSubDomainCookies?.enabled?e.advanced.crossSubDomainCookies.additionalCookies?.includes(a):void 0;return{name:Kt.NODE_ENV==="production"?`${r}${o}.${a}`:`${o}.${a}`,options:{secure:!!r,sameSite:"lax",path:"/",maxAge:60*15,...c,...s?{domain:i}:{}}}}return n}async function L(e,t,r,o){let i=e.context.authCookies.sessionToken.options;i.maxAge=r?void 0:e.context.sessionConfig.expiresIn,await e.setSignedCookie(e.context.authCookies.sessionToken.name,t,e.context.secret,{...i,...o}),r&&await e.setSignedCookie(e.context.authCookies.dontRememberToken.name,"true",e.context.secret,e.context.authCookies.dontRememberToken.options)}function Q(e){e.setCookie(e.context.authCookies.sessionToken.name,"",{maxAge:0}),e.setCookie(e.context.authCookies.dontRememberToken.name,"",{maxAge:0})}function wo(e){let t=new Map;return e.split(", ").forEach(o=>{let[i,...n]=o.split("; "),[a,c]=i.split("="),s={value:c};n.forEach(d=>{let[l,p]=d.split("=");s[l.toLowerCase()]=p||!0}),t.set(a,s)}),t}function bo(e){let t=e.split("; "),r=new Map;return t.forEach(o=>{let[i,n]=o.split("=");r.set(i,n)}),r}import{APIError as Fe}from"better-call";import{createConsola as Gt}from"consola";var q=Gt({formatOptions:{date:!1,colors:!0,compact:!0},defaults:{tag:"Better Auth"}}),de=e=>({log:(...t)=>{!e?.disabled&&q.log("",...t)},error:(...t)=>{!e?.disabled&&q.error("",...t)},warn:(...t)=>{!e?.disabled&&q.warn("",...t)},info:(...t)=>{!e?.disabled&&q.info("",...t)},debug:(...t)=>{!e?.disabled&&q.debug("",...t)},box:(...t)=>{!e?.disabled&&q.box("",...t)},success:(...t)=>{!e?.disabled&&q.success("",...t)},break:(...t)=>{!e?.disabled&&console.log(`
|
|
2
2
|
`)}}),b=de();var x=M(async e=>{let t=e.body?.callbackURL||e.query?.callbackURL||e.query?.redirectTo||e.body?.redirectTo,r=e.headers?.get("referer"),o=e.query?.currentURL||r||e.context.baseURL,i=e.context.trustedOrigins;if(t?.includes("http")){let n=new URL(t).origin;if(!i.includes(n))throw b.error("Invalid callback URL",{callbackURL:t,trustedOrigins:i}),new Fe("FORBIDDEN",{message:"Invalid callback URL"})}if(o!==e.context.baseURL){let n=new URL(o).origin;if(!i.includes(n))throw b.error("Invalid current URL",{currentURL:o,trustedOrigins:i}),new Fe("FORBIDDEN",{message:"Invalid callback URL"})}});import{parseJWT as Xt}from"oslo/jwt";import{sha256 as Wt}from"oslo/crypto";import{env as V}from"std-env";function Qt(e){try{return new URL(e).pathname!=="/"}catch{throw new k(`Invalid base URL: ${e}. Please provide a valid base URL.`)}}function ce(e,t="/api/auth"){return Qt(e)?e:(t=t.startsWith("/")?t:`/${t}`,`${e}${t}`)}function W(e,t){if(e)return ce(e,t);let r=V.BETTER_AUTH_URL||V.NEXT_PUBLIC_BETTER_AUTH_URL||V.PUBLIC_BETTER_AUTH_URL||V.NUXT_PUBLIC_BETTER_AUTH_URL||V.NUXT_PUBLIC_AUTH_URL||(V.BASE_URL!=="/"?V.BASE_URL:void 0);if(r)return ce(r,t);if(typeof window<"u")return ce(window.location.origin,t)}import{base64url as Zt}from"oslo/encoding";async function qe(e){let t=await Wt(new TextEncoder().encode(e));return Zt.encode(new Uint8Array(t),{includePadding:!1})}function Ve(e){return{tokenType:e.token_type,accessToken:e.access_token,refreshToken:e.refresh_token,accessTokenExpiresAt:e.expires_at?new Date((Date.now()+e.expires_in)*1e3):void 0,scopes:e?.scope?typeof e.scope=="string"?e.scope.split(" "):e.scope:[],idToken:e.id_token}}async function T({id:e,options:t,authorizationEndpoint:r,state:o,codeVerifier:i,scopes:n,claims:a,disablePkce:c,redirectURI:s}){let d=new URL(r);if(d.searchParams.set("response_type","code"),d.searchParams.set("client_id",t.clientId),d.searchParams.set("state",o),d.searchParams.set("scope",n.join(" ")),d.searchParams.set("redirect_uri",t.redirectURI||s),!c&&i){let l=await qe(i);d.searchParams.set("code_challenge_method","S256"),d.searchParams.set("code_challenge",l)}if(a){let l=a.reduce((p,u)=>(p[u]=null,p),{});d.searchParams.set("claims",JSON.stringify({id_token:{email:null,email_verified:null,...l}}))}return d}import{betterFetch as Jt}from"@better-fetch/fetch";async function A({code:e,codeVerifier:t,redirectURI:r,options:o,tokenEndpoint:i}){let n=new URLSearchParams;n.set("grant_type","authorization_code"),n.set("code",e),t&&n.set("code_verifier",t),n.set("redirect_uri",r),n.set("client_id",o.clientId),n.set("client_secret",o.clientSecret);let{data:a,error:c}=await Jt(i,{method:"POST",body:n,headers:{"content-type":"application/x-www-form-urlencoded",accept:"application/json","user-agent":"better-auth"}});if(c)throw c;return Ve(a)}function le(e){let t=e.accessToken,r=e.refreshToken,o;try{o=e.accessTokenExpiresAt}catch{}return{accessToken:t,refreshToken:r,expiresAt:o}}var $e=e=>{let t="https://appleid.apple.com/auth/token";return{id:"apple",name:"Apple",createAuthorizationURL({state:r,scopes:o,redirectURI:i}){let n=e.scope||o||["email","name","openid"];return new URL(`https://appleid.apple.com/auth/authorize?client_id=${e.clientId}&response_type=code&redirect_uri=${i||e.redirectURI}&scope=${n.join(" ")}&state=${r}`)},validateAuthorizationCode:async({code:r,codeVerifier:o,redirectURI:i})=>A({code:r,codeVerifier:o,redirectURI:e.redirectURI||i,options:e,tokenEndpoint:t}),async getUserInfo(r){if(!r.idToken)return null;let o=Xt(r.idToken)?.payload;return o?{user:{id:o.sub,name:o.name,email:o.email,emailVerified:o.email_verified==="true"},data:o}:null}}};import{betterFetch as Yt}from"@better-fetch/fetch";var je=e=>({id:"discord",name:"Discord",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let i=e.scope||r||["identify","email"];return new URL(`https://discord.com/api/oauth2/authorize?scope=${i.join("+")}&response_type=code&client_id=${e.clientId}&redirect_uri=${encodeURIComponent(e.redirectURI||o)}&state=${t}`)},validateAuthorizationCode:async({code:t,redirectURI:r})=>A({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://discord.com/api/oauth2/token"}),async getUserInfo(t){let{data:r,error:o}=await Yt("https://discord.com/api/users/@me",{headers:{authorization:`Bearer ${t.accessToken}`}});if(o)return null;if(r.avatar===null){let i=r.discriminator==="0"?Number(BigInt(r.id)>>BigInt(22))%6:parseInt(r.discriminator)%5;r.image_url=`https://cdn.discordapp.com/embed/avatars/${i}.png`}else{let i=r.avatar.startsWith("a_")?"gif":"png";r.image_url=`https://cdn.discordapp.com/avatars/${r.id}/${r.avatar}.${i}`}return{user:{id:r.id,name:r.display_name||r.username||"",email:r.email,emailVerified:r.verified,image:r.image_url},data:r}}});import{betterFetch as er}from"@better-fetch/fetch";var ze=e=>({id:"facebook",name:"Facebook",async createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let i=e.scope||r||["email","public_profile"];return await T({id:"facebook",options:e,authorizationEndpoint:"https://www.facebook.com/v21.0/dialog/oauth",scopes:i,state:t,redirectURI:o})},validateAuthorizationCode:async({code:t,redirectURI:r})=>A({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://graph.facebook.com/oauth/access_token"}),async getUserInfo(t){let{data:r,error:o}=await er("https://graph.facebook.com/me?fields=id,name,email,picture",{auth:{type:"Bearer",token:t.accessToken}});return o?null:{user:{id:r.id,name:r.name,email:r.email,emailVerified:r.email_verified},data:r}}});import{betterFetch as Me}from"@better-fetch/fetch";var He=e=>{let t="https://github.com/login/oauth/access_token";return{id:"github",name:"Github",createAuthorizationURL({state:r,scopes:o,codeVerifier:i,redirectURI:n}){let a=e.scope||o||["user:email"];return T({id:"github",options:e,authorizationEndpoint:"https://github.com/login/oauth/authorize",scopes:a,state:r,redirectURI:n,codeVerifier:i})},validateAuthorizationCode:async({code:r,redirectURI:o})=>A({code:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:t}),async getUserInfo(r){let{data:o,error:i}=await Me("https://api.github.com/user",{headers:{"User-Agent":"better-auth",authorization:`Bearer ${r.accessToken}`}});if(i)return null;let n=!1;if(!o.email){let{data:a,error:c}=await Me("https://api.github.com/user/emails",{headers:{authorization:`Bearer ${r.accessToken}`,"User-Agent":"better-auth"}});c||(o.email=(a.find(s=>s.primary)??a[0])?.email,n=a.find(s=>s.email===o.email)?.verified??!1)}return{user:{id:o.id.toString(),name:o.name||o.login,email:o.email,image:o.avatar_url,emailVerified:n},data:o}}}};import{parseJWT as tr}from"oslo/jwt";var Ke=e=>({id:"google",name:"Google",createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:i}){if(!e.clientId||!e.clientSecret)throw b.error("Client Id and Client Secret is required for Google. Make sure to provide them in the options."),new k("CLIENT_ID_AND_SECRET_REQUIRED");if(!o)throw new k("codeVerifier is required for Google");let n=e.scope||r||["email","profile"];return T({id:"google",options:e,authorizationEndpoint:"https://accounts.google.com/o/oauth2/auth",scopes:n,state:t,codeVerifier:o,redirectURI:i})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>A({code:t,codeVerifier:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://oauth2.googleapis.com/token"}),async getUserInfo(t){if(!t.idToken)return null;let r=tr(t.idToken)?.payload;return{user:{id:r.sub,name:r.name,email:r.email,image:r.picture,emailVerified:r.email_verified},data:r}}});import{betterFetch as rr}from"@better-fetch/fetch";import{parseJWT as or}from"oslo/jwt";var Ge=e=>{let t=e.tenantId||"common",r=`https://login.microsoftonline.com/${t}/oauth2/v2.0/authorize`,o=`https://login.microsoftonline.com/${t}/oauth2/v2.0/token`;return{id:"microsoft",name:"Microsoft EntraID",createAuthorizationURL(i){let n=e.scope||i.scopes||["openid","profile","email","User.Read"];return T({id:"microsoft",options:e,authorizationEndpoint:r,state:i.state,codeVerifier:i.codeVerifier,scopes:n,redirectURI:i.redirectURI})},validateAuthorizationCode({code:i,codeVerifier:n,redirectURI:a}){return A({code:i,codeVerifier:n,redirectURI:e.redirectURI||a,options:e,tokenEndpoint:o})},async getUserInfo(i){if(!i.idToken)return null;let n=or(i.idToken)?.payload,a=e.profilePhotoSize||48;return await rr(`https://graph.microsoft.com/v1.0/me/photos/${a}x${a}/$value`,{headers:{Authorization:`Bearer ${i.accessToken}`},async onResponse(c){if(!(e.disableProfilePhoto||!c.response.ok))try{let d=await c.response.clone().arrayBuffer(),l=Buffer.from(d).toString("base64");n.picture=`data:image/jpeg;base64, ${l}`}catch(s){b.error(s)}}}),{user:{id:n.sub,name:n.name,email:n.email,image:n.picture,emailVerified:!0},data:n}}}};import{betterFetch as nr}from"@better-fetch/fetch";var Qe=e=>({id:"spotify",name:"Spotify",createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:i}){let n=e.scope||r||["user-read-email"];return T({id:"spotify",options:e,authorizationEndpoint:"https://accounts.spotify.com/authorize",scopes:n,state:t,codeVerifier:o,redirectURI:i})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>A({code:t,codeVerifier:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://accounts.spotify.com/api/token"}),async getUserInfo(t){let{data:r,error:o}=await nr("https://api.spotify.com/v1/me",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});return o?null:{user:{id:r.id,name:r.display_name,email:r.email,image:r.images[0]?.url,emailVerified:!1},data:r}}});import"@better-fetch/fetch";function An(e){return e.charAt(0).toUpperCase()+e.slice(1)}var N={isAction:!1};import{nanoid as ir}from"nanoid";var v=e=>ir(e);import{parseJWT as sr}from"oslo/jwt";var We=e=>({id:"twitch",name:"Twitch",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let i=e.scope||r||["user:read:email","openid"];return T({id:"twitch",redirectURI:o,options:e,authorizationEndpoint:"https://id.twitch.tv/oauth2/authorize",scopes:i,state:t,claims:e.claims||["email","email_verified","preferred_username","picture"]})},validateAuthorizationCode:async({code:t,redirectURI:r})=>A({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://id.twitch.tv/oauth2/token"}),async getUserInfo(t){let r=t.idToken;if(!r)return b.error("No idToken found in token"),null;let o=sr(r)?.payload;return{user:{id:o.sub,name:o.preferred_username,email:o.email,image:o.picture,emailVerified:!1},data:o}}});import{betterFetch as ar}from"@better-fetch/fetch";var Ze=e=>({id:"twitter",name:"Twitter",createAuthorizationURL(t){let r=e.scope||t.scopes||["account_info.read"];return T({id:"twitter",options:e,authorizationEndpoint:"https://twitter.com/i/oauth2/authorize",scopes:r,state:t.state,codeVerifier:t.codeVerifier,redirectURI:t.redirectURI})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>A({code:t,codeVerifier:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://id.twitch.tv/oauth2/token"}),async getUserInfo(t){let{data:r,error:o}=await ar("https://api.x.com/2/users/me?user.fields=profile_image_url",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});return o||!r.data.email?null:{user:{id:r.data.id,name:r.data.name,email:r.data.email,image:r.data.profile_image_url,emailVerified:r.data.verified||!1},data:r}}});var ue={apple:$e,discord:je,facebook:ze,github:He,microsoft:Ge,google:Ke,spotify:Qe,twitch:We,twitter:Ze},Je=Object.keys(ue);import{TimeSpan as dr}from"oslo";import{createJWT as cr,validateJWT as lr}from"oslo/jwt";import{z as S}from"zod";import{APIError as H}from"better-call";import{APIError as Z}from"better-call";var $=(e,t="ms")=>new Date(Date.now()+(t==="sec"?e*1e3:e));import{z as Xe}from"zod";var pe=()=>y("/session",{method:"GET",requireHeaders:!0},async e=>{try{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!t)return e.json(null,{status:401});let r=await e.context.internalAdapter.findSession(t);if(!r||r.session.expiresAt<new Date)return Q(e),r&&await e.context.internalAdapter.deleteSession(r.session.id),e.json(null,{status:401});if(await e.getSignedCookie(e.context.authCookies.dontRememberToken.name,e.context.secret))return e.json(r);let i=e.context.sessionConfig.expiresIn,n=e.context.sessionConfig.updateAge;if(r.session.expiresAt.valueOf()-i*1e3+n*1e3<=Date.now()){let s=await e.context.internalAdapter.updateSession(r.session.id,{expiresAt:$(e.context.sessionConfig.expiresIn,"sec")});if(!s)return Q(e),e.json(null,{status:401});let d=(s.expiresAt.valueOf()-Date.now())/1e3;return await L(e,s.id,!1,{maxAge:d}),e.json({session:s,user:r.user})}return e.json(r)}catch(t){return e.context.logger.error(t),e.json(null,{status:500})}}),fe=async e=>await pe()({...e,_flag:"json",headers:e.headers}),C=M(async e=>{let t=await fe(e);if(!t?.session)throw new Z("UNAUTHORIZED");return{session:t}}),Ye=()=>y("/user/list-sessions",{method:"GET",use:[C],requireHeaders:!0},async e=>{let r=(await e.context.internalAdapter.listSessions(e.context.session.user.id)).filter(o=>o.expiresAt>new Date);return e.json(r)}),et=y("/user/revoke-session",{method:"POST",body:Xe.object({id:Xe.string()}),use:[C],requireHeaders:!0},async e=>{let t=e.body.id,r=await e.context.internalAdapter.findSession(t);if(!r)throw new Z("BAD_REQUEST",{message:"Session not found"});if(r.session.userId!==e.context.session.user.id)throw new Z("UNAUTHORIZED");try{await e.context.internalAdapter.deleteSession(t)}catch(o){throw e.context.logger.error(o),new Z("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),tt=y("/user/revoke-sessions",{method:"POST",use:[C],requireHeaders:!0},async e=>{try{await e.context.internalAdapter.deleteSessions(e.context.session.user.id)}catch(t){throw e.context.logger.error(t),new Z("INTERNAL_SERVER_ERROR")}return e.json({status:!0})});async function B(e,t,r){return await cr("HS256",Buffer.from(e),{email:t.toLowerCase(),updateTo:r},{expiresIn:new dr(1,"h"),issuer:"better-auth",subject:"verify-email",audiences:[t],includeIssuedTimestamp:!0})}var rt=y("/send-verification-email",{method:"POST",query:S.object({currentURL:S.string().optional()}).optional(),body:S.object({email:S.string().email(),callbackURL:S.string().optional()}),use:[x]},async e=>{if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),new H("BAD_REQUEST",{message:"Verification email isn't enabled"});let{email:t}=e.body,r=await e.context.internalAdapter.findUserByEmail(t);if(!r)throw new H("BAD_REQUEST",{message:"User not found"});let o=await B(e.context.secret,t),i=`${e.context.baseURL}/verify-email?token=${o}&callbackURL=${e.body.callbackURL||e.query?.currentURL||"/"}`;return await e.context.options.emailVerification.sendVerificationEmail(r.user,i,o),e.json({status:!0})}),ot=y("/verify-email",{method:"GET",query:S.object({token:S.string(),callbackURL:S.string().optional()}),use:[x]},async e=>{let{token:t}=e.query,r;try{r=await lr("HS256",Buffer.from(e.context.secret),t)}catch(a){throw e.context.logger.error("Failed to verify email",a),new H("BAD_REQUEST",{message:"Invalid token"})}let i=S.object({email:S.string().email(),updateTo:S.string().optional()}).parse(r.payload);if(!await e.context.internalAdapter.findUserByEmail(i.email))throw new H("BAD_REQUEST",{message:"User not found"});if(i.updateTo){let a=await fe(e);if(!a)throw e.query.callbackURL?e.redirect(`${e.query.callbackURL}?error=unauthorized`):new H("UNAUTHORIZED",{message:"Session not found"});if(a.user.email!==i.email)throw e.query.callbackURL?e.redirect(`${e.query.callbackURL}?error=unauthorized`):new H("UNAUTHORIZED",{message:"Invalid session"});let c=await e.context.internalAdapter.updateUserByEmail(i.email,{email:i.updateTo});if(await e.context.options.emailVerification?.sendVerificationEmail?.(c,`${e.context.baseURL}/verify-email?token=${t}`,t),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({user:c,status:!0})}if(await e.context.internalAdapter.updateUserByEmail(i.email,{emailVerified:!0}),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({user:null,status:!0})});var nt=y("/sign-in/social",{method:"POST",requireHeaders:!0,query:P.object({currentURL:P.string().optional()}).optional(),body:P.object({callbackURL:P.string().optional(),provider:P.enum(Je)}),use:[x]},async e=>{let t=e.context.socialProviders.find(s=>s.id===e.body.provider);if(!t)throw e.context.logger.error("Provider not found. Make sure to add the provider in your auth config",{provider:e.body.provider}),new O("NOT_FOUND",{message:"Provider not found"});let r=e.context.authCookies,o=e.query?.currentURL?new URL(e.query?.currentURL):null,i=e.body.callbackURL?.startsWith("http")?e.body.callbackURL:`${o?.origin}${e.body.callbackURL||""}`,n=await _e(i||o?.origin||e.context.options.baseURL);await e.setSignedCookie(r.state.name,n.hash,e.context.secret,r.state.options);let a=ur();await e.setSignedCookie(r.pkCodeVerifier.name,a,e.context.secret,r.pkCodeVerifier.options);let c=await t.createAuthorizationURL({state:n.raw,codeVerifier:a,redirectURI:`${e.context.baseURL}/callback/${t.id}`});return e.json({url:c.toString(),state:n,codeVerifier:a,redirect:!0})}),it=y("/sign-in/email",{method:"POST",body:P.object({email:P.string(),password:P.string(),callbackURL:P.string().optional(),dontRememberMe:P.boolean().default(!1).optional()}),use:[x]},async e=>{if(!e.context.options?.emailAndPassword?.enabled)throw e.context.logger.error("Email and password is not enabled. Make sure to enable it in the options on you `auth.ts` file. Check `https://better-auth.com/docs/authentication/email-password` for more!"),new O("BAD_REQUEST",{message:"Email and password is not enabled"});let{email:t,password:r}=e.body;if(!P.string().email().safeParse(t).success)throw new O("BAD_REQUEST",{message:"Invalid email"});if(!P.string().email().safeParse(t).success)throw new O("BAD_REQUEST",{message:"Invalid email"});let n=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!n)throw await e.context.password.hash(r),e.context.logger.error("User not found",{email:t}),new O("UNAUTHORIZED",{message:"Invalid email or password"});let a=n.accounts.find(l=>l.providerId==="credential");if(!a)throw e.context.logger.error("Credential account not found",{email:t}),new O("UNAUTHORIZED",{message:"Invalid email or password"});let c=a?.password;if(!c)throw e.context.logger.error("Password not found",{email:t}),new O("UNAUTHORIZED",{message:"Unexpected error"});if(!await e.context.password.verify(c,r))throw e.context.logger.error("Invalid password"),new O("UNAUTHORIZED",{message:"Invalid email or password"});if(e.context.options?.emailAndPassword?.requireEmailVerification&&!n.user.emailVerified){if(!e.context.options?.emailVerification?.sendVerificationEmail)throw b.error("Email verification is required but no email verification handler is provided"),new O("INTERNAL_SERVER_ERROR",{message:"Email is not verified."});let l=await B(e.context.secret,n.user.email),p=`${e.context.options.baseURL}/verify-email?token=${l}`;throw await e.context.options.emailVerification.sendVerificationEmail(n.user,p,l),e.context.logger.error("Email not verified",{email:t}),new O("FORBIDDEN",{message:"Email is not verified. Check your email for a verification link"})}let d=await e.context.internalAdapter.createSession(n.user.id,e.headers,e.body.dontRememberMe);if(!d)throw e.context.logger.error("Failed to create session"),new O("UNAUTHORIZED",{message:"Failed to create session"});return await L(e,d.id,e.body.dontRememberMe),e.json({user:n.user,session:d,redirect:!!e.body.callbackURL,url:e.body.callbackURL})});import{z as re}from"zod";import{z as w}from"zod";var Di=w.object({id:w.string(),providerId:w.string(),accountId:w.string(),userId:w.string(),accessToken:w.string().nullable().optional(),refreshToken:w.string().nullable().optional(),idToken:w.string().nullable().optional(),expiresAt:w.date().nullable().optional(),password:w.string().optional().nullable()}),st=w.object({id:w.string(),email:w.string().transform(e=>e.toLowerCase()),emailVerified:w.boolean().default(!1),name:w.string(),image:w.string().optional(),createdAt:w.date().default(new Date),updatedAt:w.date().default(new Date)}),Ni=w.object({id:w.string(),userId:w.string(),expiresAt:w.date(),ipAddress:w.string().optional(),userAgent:w.string().optional()}),Fi=w.object({id:w.string(),value:w.string(),expiresAt:w.date(),identifier:w.string()});function pr(e,t){let r=t.fields,o={};for(let i in r){if(i in e){if(r[i].input===!1){if(r[i].defaultValue){o[i]=r[i].defaultValue;continue}continue}o[i]=e[i];continue}if(r[i].defaultValue){o[i]=r[i].defaultValue;continue}}return o}function at(e,t){let r={...e.user?.additionalFields};return pr(t||{},{fields:r})}var dt=y("/callback/:id",{method:"GET",query:re.object({state:re.string(),code:re.string().optional(),error:re.string().optional()}),metadata:N},async e=>{if(e.query.error||!e.query.code){let U=ae(e.query.state).data?.callbackURL||`${e.context.baseURL}/error`;throw e.context.logger.error(e.query.error,e.params.id),e.redirect(`${U}?error=${e.query.error||"oAuth_code_missing"}`)}let t=e.context.socialProviders.find(g=>g.id===e.params.id);if(!t)throw e.context.logger.error("Oauth provider with id",e.params.id,"not found"),e.redirect(`${e.context.baseURL}/error?error=oauth_provider_not_found`);let r=ae(e.query.state);if(!r.success)throw e.context.logger.error("Unable to parse state"),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);let{data:{callbackURL:o,currentURL:i}}=r,n=await e.getSignedCookie(e.context.authCookies.state.name,e.context.secret);if(!n)throw b.error("No stored state found"),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);if(!await Le(e.query.state,n))throw b.error("OAuth state mismatch"),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);let c=await e.getSignedCookie(e.context.authCookies.pkCodeVerifier.name,e.context.secret),s;try{s=await t.validateAuthorizationCode({code:e.query.code,codeVerifier:c,redirectURI:`${e.context.baseURL}/callback/${t.id}`})}catch(g){throw e.context.logger.error(g),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`)}let d=await t.getUserInfo(s).then(g=>g?.user),l=v(),p=st.safeParse({...d,id:l});if(!d||p.success===!1)throw b.error("Unable to get user info",p.error),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);if(!o)throw e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);function u(g){throw e.redirect(`${i||o||`${e.context.baseURL}/error`}?error=${g}`)}let f=await e.context.internalAdapter.findUserByEmail(d.email,{includeAccounts:!0}).catch(g=>{throw b.error(`Better auth was unable to query your database.
|
|
3
3
|
Error: `,g),e.redirect(`${e.context.baseURL}/error?error=internal_server_error`)}),m=f?.user.id;if(f){if(!f.accounts.find(U=>U.providerId===t.id)){(!e.context.options.account?.accountLinking?.trustedProviders?.includes(t.id)&&!d.emailVerified||!e.context.options.account?.accountLinking?.enabled)&&u("account_not_linked");try{await e.context.internalAdapter.linkAccount({providerId:t.id,accountId:d.id.toString(),id:`${t.id}:${d.id}`,userId:f.user.id,...le(s)})}catch(F){b.error("Unable to link account",F),u("unable_to_link_account")}}}else try{let g=d.emailVerified||!1,U=await e.context.internalAdapter.createOAuthUser({...p.data,emailVerified:g},{...le(s),providerId:t.id,accountId:d.id.toString()});if(m=U?.user.id,!g&&U&&e.context.options.emailVerification?.sendOnSignUp){let G=await B(e.context.secret,d.email),F=`${e.context.baseURL}/verify-email?token=${G}&callbackURL=${o}`;await e.context.options.emailVerification?.sendVerificationEmail?.(U.user,F,G)}}catch(g){b.error("Unable to create user",g),u("unable_to_create_user")}m||u("unable_to_create_user");let h=await e.context.internalAdapter.createSession(m,e.request);throw h||u("unable_to_create_session"),await L(e,h.id),e.redirect(o)});import"zod";import{APIError as fr}from"better-call";var ct=y("/sign-out",{method:"POST"},async e=>{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!t)throw new fr("BAD_REQUEST",{message:"Session not found"});return await e.context.internalAdapter.deleteSession(t),Q(e),e.json({success:!0})});import{z as _}from"zod";import{APIError as oe}from"better-call";var lt=y("/forget-password",{method:"POST",body:_.object({email:_.string().email(),redirectTo:_.string()}),use:[x]},async e=>{if(!e.context.options.emailAndPassword?.sendResetPassword)throw e.context.logger.error("Reset password isn't enabled.Please pass an emailAndPassword.sendResetPasswordToken function in your auth config!"),new oe("BAD_REQUEST",{message:"Reset password isn't enabled"});let{email:t,redirectTo:r}=e.body,o=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!o)return e.context.logger.error("Reset Password: User not found",{email:t}),e.json({status:!1},{body:{status:!0}});let i=60*60*1,n=new Date(Date.now()+1e3*(e.context.options.emailAndPassword.resetPasswordTokenExpiresIn||i)),a=e.context.uuid();await e.context.internalAdapter.createVerificationValue({value:o.user.id,identifier:`reset-password:${a}`,expiresAt:n});let c=`${e.context.baseURL}/reset-password/${a}?callbackURL=${r}`;return await e.context.options.emailAndPassword.sendResetPassword(o.user,c),e.json({status:!0})}),ut=y("/reset-password/:token",{method:"GET",query:_.object({callbackURL:_.string()}),use:[x]},async e=>{let{token:t}=e.params,r=e.query.callbackURL,o=r.startsWith("http")?r:`${e.context.options.baseURL}${r}`;if(!t||!r)throw e.redirect(`${e.context.baseURL}/error?error=INVALID_TOKEN`);let i=await e.context.internalAdapter.findVerificationValue(`reset-password:${t}`);throw!i||i.expiresAt<new Date?e.redirect(`${o}?error=INVALID_TOKEN`):e.redirect(`${o}?token=${t}`)}),pt=y("/reset-password",{query:_.optional(_.object({token:_.string()})),method:"POST",body:_.object({newPassword:_.string()})},async e=>{let t=e.query?.token;if(!t)throw new oe("BAD_REQUEST",{message:"Token not found"});let{newPassword:r}=e.body,o=`reset-password:${t}`,i=await e.context.internalAdapter.findVerificationValue(o);if(!i||i.expiresAt<new Date)throw new oe("BAD_REQUEST",{message:"Invalid token"});await e.context.internalAdapter.deleteVerificationValue(i.id);let n=i.value,a=await e.context.password.hash(r);if(!(await e.context.internalAdapter.findAccounts(n)).find(l=>l.providerId==="credential"))return await e.context.internalAdapter.createAccount({userId:n,providerId:"credential",password:a,accountId:e.context.uuid()}),e.json({status:!0});if(!await e.context.internalAdapter.updatePassword(n,a))throw new oe("BAD_REQUEST",{message:"Failed to update password"});return e.json({status:!0})});import{z as R}from"zod";import{APIError as E}from"better-call";var ft=y("/user/update",{method:"POST",body:R.object({name:R.string().optional(),image:R.string().optional()}),use:[C,x]},async e=>{let{name:t,image:r}=e.body,o=e.context.session;if(!r&&!t)return e.json({user:o.user});let i=await e.context.internalAdapter.updateUserByEmail(o.user.email,{name:t,image:r});return e.json({user:i})}),mt=y("/user/change-password",{method:"POST",body:R.object({newPassword:R.string(),currentPassword:R.string(),revokeOtherSessions:R.boolean().optional()}),use:[C]},async e=>{let{newPassword:t,currentPassword:r,revokeOtherSessions:o}=e.body,i=e.context.session,n=e.context.password.config.minPasswordLength;if(t.length<n)throw e.context.logger.error("Password is too short"),new E("BAD_REQUEST",{message:"Password is too short"});let a=e.context.password.config.maxPasswordLength;if(t.length>a)throw e.context.logger.error("Password is too long"),new E("BAD_REQUEST",{message:"Password too long"});let s=(await e.context.internalAdapter.findAccounts(i.user.id)).find(p=>p.providerId==="credential"&&p.password);if(!s||!s.password)throw new E("BAD_REQUEST",{message:"User does not have a password"});let d=await e.context.password.hash(t);if(!await e.context.password.verify(s.password,r))throw new E("BAD_REQUEST",{message:"Incorrect password"});if(await e.context.internalAdapter.updateAccount(s.id,{password:d}),o){await e.context.internalAdapter.deleteSessions(i.user.id);let p=await e.context.internalAdapter.createSession(i.user.id,e.headers);if(!p)throw new E("INTERNAL_SERVER_ERROR",{message:"Unable to create session"});await L(e,p.id)}return e.json(i.user)}),gt=y("/user/set-password",{method:"POST",body:R.object({newPassword:R.string()}),use:[C]},async e=>{let{newPassword:t}=e.body,r=e.context.session,o=e.context.password.config.minPasswordLength;if(t.length<o)throw e.context.logger.error("Password is too short"),new E("BAD_REQUEST",{message:"Password is too short"});let i=e.context.password.config.maxPasswordLength;if(t.length>i)throw e.context.logger.error("Password is too long"),new E("BAD_REQUEST",{message:"Password too long"});let a=(await e.context.internalAdapter.findAccounts(r.user.id)).find(s=>s.providerId==="credential"&&s.password),c=await e.context.password.hash(t);if(!a)return await e.context.internalAdapter.linkAccount({userId:r.user.id,providerId:"credential",accountId:r.user.id,password:c}),e.json(r.user);throw new E("BAD_REQUEST",{message:"user already has a password"})}),ht=y("/user/delete",{method:"POST",body:R.object({password:R.string()}),use:[C]},async e=>{let{password:t}=e.body,r=e.context.session,i=(await e.context.internalAdapter.findAccounts(r.user.id)).find(a=>a.providerId==="credential"&&a.password);if(!i||!i.password)throw new E("BAD_REQUEST",{message:"User does not have a password"});if(!await e.context.password.verify(i.password,t))throw new E("BAD_REQUEST",{message:"Incorrect password"});return await e.context.internalAdapter.deleteUser(r.user.id),await e.context.internalAdapter.deleteSessions(r.user.id),e.json(null)}),yt=y("/user/change-email",{method:"POST",query:R.object({currentURL:R.string().optional()}).optional(),body:R.object({newEmail:R.string().email(),callbackURL:R.string().optional()}),use:[C,x]},async e=>{if(!e.context.options.user?.changeEmail?.enabled)throw e.context.logger.error("Change email is disabled."),new E("BAD_REQUEST",{message:"Change email is disabled"});if(e.body.newEmail===e.context.session.user.email)throw e.context.logger.error("Email is the same"),new E("BAD_REQUEST",{message:"Email is the same"});if(await e.context.internalAdapter.findUserByEmail(e.body.newEmail))throw e.context.logger.error("Email already exists"),new E("BAD_REQUEST",{message:"Couldn't update your email"});if(e.context.session.user.emailVerified!==!0){let i=await e.context.internalAdapter.updateUserByEmail(e.context.session.user.email,{email:e.body.newEmail});return e.json({user:i,status:!0})}if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),new E("BAD_REQUEST",{message:"Verification email isn't enabled"});let r=await B(e.context.secret,e.context.session.user.email,e.body.newEmail),o=`${e.context.baseURL}/verify-email?token=${r}&callbackURL=${e.body.callbackURL||e.query?.currentURL||"/"}`;return await e.context.options.emailVerification.sendVerificationEmail(e.context.session.user,o,r),e.json({user:null,status:!0})});var wt=y("/csrf",{method:"GET",metadata:N},async e=>{let t=await e.getSignedCookie(e.context.authCookies.csrfToken.name,e.context.secret);if(t){let[n,a]=t.split("!")||[null,null];return e.json({csrfToken:n})}let r=xe(32,Te("a-z","0-9","A-Z")),o=await ee(e.context.secret,r),i=`${r}!${o}`;return await e.setSignedCookie(e.context.authCookies.csrfToken.name,i,e.context.secret,e.context.authCookies.csrfToken.options),e.json({csrfToken:r})});var mr=(e="Unknown")=>`<!DOCTYPE html>
|
|
4
4
|
<html lang="en">
|
package/dist/node.d.cts
CHANGED
package/dist/node.d.ts
CHANGED