better-auth 0.5.3-beta.7 → 0.5.3-beta.9
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.ts +1 -1
- package/dist/adapters/drizzle.js +1 -1
- package/dist/adapters/drizzle.js.map +1 -1
- package/dist/adapters/kysely.d.ts +1 -1
- package/dist/adapters/mongodb.d.ts +1 -1
- package/dist/adapters/prisma.d.ts +1 -1
- package/dist/api.d.ts +1 -1
- package/dist/api.js +1 -1
- package/dist/api.js.map +1 -1
- package/dist/{auth-ChOWHZz7.d.ts → auth-B9t_YkMU.d.ts} +65 -19
- package/dist/client/plugins.d.ts +3 -3
- package/dist/client.d.ts +1 -1
- package/dist/client.js +1 -1
- package/dist/client.js.map +1 -1
- package/dist/cookies.d.ts +1 -1
- package/dist/cookies.js +1 -1
- package/dist/cookies.js.map +1 -1
- package/dist/db.d.ts +2 -2
- package/dist/db.js +1 -1
- package/dist/db.js.map +1 -1
- package/dist/{index-BwCQ9u_T.d.ts → index-ny_c9jGl.d.ts} +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +4 -4
- package/dist/index.js.map +1 -1
- package/dist/node.d.ts +1 -1
- package/dist/plugins.d.ts +3 -3
- package/dist/plugins.js +1 -1
- package/dist/plugins.js.map +1 -1
- package/dist/react.d.ts +1 -1
- package/dist/react.js +1 -1
- package/dist/react.js.map +1 -1
- package/dist/social.d.ts +2 -0
- package/dist/social.js +1 -1
- package/dist/social.js.map +1 -1
- package/dist/solid-start.d.ts +1 -1
- package/dist/solid.d.ts +1 -1
- package/dist/solid.js +1 -1
- package/dist/solid.js.map +1 -1
- package/dist/svelte-kit.d.ts +1 -1
- package/dist/svelte-kit.js +1 -1
- package/dist/svelte-kit.js.map +1 -1
- package/dist/svelte.d.ts +1 -1
- package/dist/svelte.js +1 -1
- package/dist/svelte.js.map +1 -1
- package/dist/types.d.ts +2 -2
- package/dist/vue.d.ts +1 -1
- package/dist/vue.js +1 -1
- package/dist/vue.js.map +1 -1
- package/package.json +1 -1
package/dist/adapters/drizzle.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{and as v,asc as P,desc as z,eq as p,or as A,inArray as y,like as w}from"drizzle-orm";var d=class extends Error{constructor(r,i){super(r),this.name="BetterAuthError",this.message=r,this.cause=i
|
|
1
|
+
import{and as v,asc as P,desc as z,eq as p,or as A,inArray as y,like as w}from"drizzle-orm";var d=class extends Error{constructor(r,i){super(r),this.name="BetterAuthError",this.message=r,this.cause=i}};function h(t,r){let i=r.schema;if(!i)throw new d("Drizzle adapter failed to initialize. Schema not found. Please provide a schema object in the adapter options object.");let c=r.usePlural?`${t}s`:t,n=i[c];if(!n)throw new d(`[# Drizzle Adapter]: The model "${t}" was not found in the schema object. Please pass the schema directly to the adapter options.`);return n}function m(t,r){if(!t)return[];if(t.length===1){let e=t[0];if(!e)return[];if(e.operator==="in"){if(!Array.isArray(e.value))throw new d(`The value for the field "${e.field}" must be an array when using the "in" operator.`);return[y(r[e.field],e.value)]}return e.operator==="contains"?[w(r[e.field],`%${e.value}%`)]:e.operator==="starts_with"?[w(r[e.field],`${e.value}%`)]:e.operator==="ends_with"?[w(r[e.field],`%${e.value}`)]:[p(r[e.field],e.value)]}let i=t.filter(e=>e.connector==="AND"||!e.connector),c=t.filter(e=>e.connector==="OR"),n=v(...i.map(e=>{if(e.operator==="in"){if(!Array.isArray(e.value))throw new d(`The value for the field "${e.field}" must be an array when using the "in" operator.`);return y(r[e.field],e.value)}return p(r[e.field],e.value)})),l=A(...c.map(e=>p(r[e.field],e.value))),s=[];return i.length&&s.push(n),c.length&&s.push(l),s}var S=(t,r)=>{let i=r.schema||t._.fullSchema,c=r?.provider;return{id:"drizzle",async create(n){let{model:l,data:s}=n,e=h(l,{schema:i,usePlural:r.usePlural});r.generateId!==void 0&&(s.id=r.generateId?r.generateId():void 0);let a=t.insert(e).values(s);return c!=="mysql"?(await a.returning())[0]:(await a,(await t.select().from(e).where(p(e.id,n.data.id)))[0])},async findOne(n){let{model:l,where:s,select:e}=n,a=h(l,{schema:i,usePlural:r.usePlural}),u=m(s,a),o=null;return e?.length?o=await t.select(...e.map(f=>({[f]:a[f]}))).from(a).where(...u):o=await t.select().from(a).where(...u),o.length?o[0]:null},async findMany(n){let{model:l,where:s,limit:e,offset:a,sortBy:u}=n,o=h(l,{schema:i,usePlural:r.usePlural}),f=s?m(s,o):[],g=u?.direction==="desc"?z:P;return await t.select().from(o).limit(e||100).offset(a||0).orderBy(g(o[u?.field||"id"])).where(...f.length?f:[])},async update(n){let{model:l,where:s,update:e}=n,a=h(l,{schema:i,usePlural:r.usePlural});e.id&&(e.id=void 0);let u=m(s,a),o=t.update(a).set(e).where(...u);return c!=="mysql"?(await o.returning())[0]:(await o,(await t.select().from(a).where(p(a.id,n.update.id)))[0])},async delete(n){let{model:l,where:s}=n,e=h(l,{schema:i,usePlural:r.usePlural}),a=m(s,e);return(await t.delete(e).where(...a))[0]},async deleteMany(n){let{model:l,where:s}=n,e=h(l,{schema:i,usePlural:r.usePlural}),a=m(s,e);await t.delete(e).where(...a)},options:r}};export{S as drizzleAdapter};
|
|
2
2
|
//# sourceMappingURL=drizzle.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/adapters/drizzle-adapter/index.ts","../../src/error/index.ts"],"sourcesContent":["import { and, asc, desc, eq, or, SQL, inArray, like } from \"drizzle-orm\";\nimport type { Adapter, Where } from \"../../types\";\nimport { BetterAuthError } from \"../../error\";\n\nexport interface DrizzleAdapterOptions {\n\tschema?: Record<string, any>;\n\tprovider: \"pg\" | \"mysql\" | \"sqlite\";\n\t/**\n\t * If the table names in the schema are plural\n\t * set this to true. For example, if the schema\n\t * has an object with a key \"users\" instead of \"user\"\n\t */\n\tusePlural?: boolean;\n\t/**\n\t * Custom generateId function.\n\t *\n\t * If not provided, nanoid will be used.\n\t * If set to false, the database's auto generated id will be used.\n\t *\n\t * @default nanoid\n\t */\n\tgenerateId?: ((size?: number) => string) | false;\n}\n\nfunction getSchema(\n\tmodelName: string,\n\toptions: {\n\t\tschema: Record<string, any>;\n\t\tusePlural?: boolean;\n\t},\n) {\n\tconst schema = options.schema;\n\tif (!schema) {\n\t\tthrow new BetterAuthError(\n\t\t\t\"Drizzle adapter failed to initialize. Schema not found. Please provide a schema object in the adapter options object.\",\n\t\t);\n\t}\n\tconst model = options.usePlural ? `${modelName}s` : modelName;\n\n\tconst schemaModel = schema[model];\n\tif (!schemaModel) {\n\t\tthrow new BetterAuthError(\n\t\t\t`[# Drizzle Adapter]: The model \"${modelName}\" was not found in the schema object. Please pass the schema directly to the adapter options.`,\n\t\t);\n\t}\n\treturn schemaModel;\n}\n\nfunction whereConvertor(where: Where[], schemaModel: any) {\n\tif (!where) return [];\n\tif (where.length === 1) {\n\t\tconst w = where[0];\n\t\tif (!w) {\n\t\t\treturn [];\n\t\t}\n\n\t\tif (w.operator === \"in\") {\n\t\t\tif (!Array.isArray(w.value)) {\n\t\t\t\tthrow new BetterAuthError(\n\t\t\t\t\t`The value for the field \"${w.field}\" must be an array when using the \"in\" operator.`,\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn [inArray(schemaModel[w.field], w.value)];\n\t\t}\n\n\t\tif (w.operator === \"contains\") {\n\t\t\treturn [like(schemaModel[w.field], `%${w.value}%`)];\n\t\t}\n\n\t\tif (w.operator === \"starts_with\") {\n\t\t\treturn [like(schemaModel[w.field], `${w.value}%`)];\n\t\t}\n\n\t\tif (w.operator === \"ends_with\") {\n\t\t\treturn [like(schemaModel[w.field], `%${w.value}`)];\n\t\t}\n\n\t\treturn [eq(schemaModel[w.field], w.value)];\n\t}\n\tconst andGroup = where.filter((w) => w.connector === \"AND\" || !w.connector);\n\tconst orGroup = where.filter((w) => w.connector === \"OR\");\n\n\tconst andClause = and(\n\t\t...andGroup.map((w) => {\n\t\t\tif (w.operator === \"in\") {\n\t\t\t\tif (!Array.isArray(w.value)) {\n\t\t\t\t\tthrow new BetterAuthError(\n\t\t\t\t\t\t`The value for the field \"${w.field}\" must be an array when using the \"in\" operator.`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\treturn inArray(schemaModel[w.field], w.value);\n\t\t\t}\n\t\t\treturn eq(schemaModel[w.field], w.value);\n\t\t}),\n\t);\n\tconst orClause = or(\n\t\t...orGroup.map((w) => {\n\t\t\treturn eq(schemaModel[w.field], w.value);\n\t\t}),\n\t);\n\n\tconst clause: SQL<unknown>[] = [];\n\n\tif (andGroup.length) clause.push(andClause!);\n\tif (orGroup.length) clause.push(orClause!);\n\treturn clause;\n}\n\ninterface DB {\n\t[key: string]: any;\n}\n\nexport const drizzleAdapter = (\n\tdb: DB,\n\toptions: DrizzleAdapterOptions,\n): Adapter => {\n\tconst schema = options.schema || db._.fullSchema;\n\tconst databaseType = options?.provider;\n\treturn {\n\t\tid: \"drizzle\",\n\t\tasync create(data) {\n\t\t\tconst { model, data: val } = data;\n\t\t\tconst schemaModel = getSchema(model, {\n\t\t\t\tschema,\n\t\t\t\tusePlural: options.usePlural,\n\t\t\t});\n\t\t\tif (options.generateId !== undefined) {\n\t\t\t\tval.id = options.generateId ? options.generateId() : undefined;\n\t\t\t}\n\n\t\t\tconst mutation = db.insert(schemaModel).values(val);\n\t\t\tif (databaseType !== \"mysql\") return (await mutation.returning())[0];\n\n\t\t\tawait mutation;\n\t\t\tconst res = await db\n\t\t\t\t.select()\n\t\t\t\t.from(schemaModel)\n\t\t\t\t.where(eq(schemaModel.id, (data.data as { id: string }).id));\n\t\t\treturn res[0];\n\t\t},\n\t\tasync findOne(data) {\n\t\t\tconst { model, where, select: included } = data;\n\n\t\t\tconst schemaModel = getSchema(model, {\n\t\t\t\tschema,\n\t\t\t\tusePlural: options.usePlural,\n\t\t\t});\n\n\t\t\tconst wheres = whereConvertor(where, schemaModel);\n\n\t\t\tlet res = null;\n\t\t\tif (!!included?.length) {\n\t\t\t\tres = await db\n\t\t\t\t\t.select(\n\t\t\t\t\t\t...included.map((include) => {\n\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\t[include]: schemaModel[include],\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t}),\n\t\t\t\t\t)\n\t\t\t\t\t.from(schemaModel)\n\t\t\t\t\t.where(...wheres);\n\t\t\t} else {\n\t\t\t\tres = await db\n\t\t\t\t\t.select()\n\t\t\t\t\t.from(schemaModel)\n\t\t\t\t\t.where(...wheres);\n\t\t\t}\n\n\t\t\tif (!!res.length) return res[0];\n\t\t\telse return null;\n\t\t},\n\t\tasync findMany(data) {\n\t\t\tconst { model, where, limit, offset, sortBy } = data;\n\t\t\tconst schemaModel = getSchema(model, {\n\t\t\t\tschema,\n\t\t\t\tusePlural: options.usePlural,\n\t\t\t});\n\t\t\tconst filters = where ? whereConvertor(where, schemaModel) : [];\n\t\t\tconst fn = sortBy?.direction === \"desc\" ? desc : asc;\n\t\t\tconst res = await db\n\t\t\t\t.select()\n\t\t\t\t.from(schemaModel)\n\t\t\t\t.limit(limit || 100)\n\t\t\t\t.offset(offset || 0)\n\t\t\t\t.orderBy(fn(schemaModel[sortBy?.field || \"id\"]))\n\t\t\t\t.where(...(filters.length ? filters : []));\n\n\t\t\treturn res;\n\t\t},\n\t\tasync update(data) {\n\t\t\tconst { model, where, update } = data;\n\t\t\tconst schemaModel = getSchema(model, {\n\t\t\t\tschema,\n\t\t\t\tusePlural: options.usePlural,\n\t\t\t});\n\t\t\tif (update.id) {\n\t\t\t\tupdate.id = undefined;\n\t\t\t}\n\t\t\tconst wheres = whereConvertor(where, schemaModel);\n\t\t\tconst mutation = db\n\t\t\t\t.update(schemaModel)\n\t\t\t\t.set(update)\n\t\t\t\t.where(...wheres);\n\t\t\tif (databaseType !== \"mysql\") return (await mutation.returning())[0];\n\n\t\t\tawait mutation;\n\t\t\tconst res = await db\n\t\t\t\t.select()\n\t\t\t\t.from(schemaModel)\n\t\t\t\t.where(eq(schemaModel.id, (data.update as { id: string }).id));\n\t\t\treturn res[0];\n\t\t},\n\t\tasync delete(data) {\n\t\t\tconst { model, where } = data;\n\t\t\tconst schemaModel = getSchema(model, {\n\t\t\t\tschema,\n\t\t\t\tusePlural: options.usePlural,\n\t\t\t});\n\t\t\tconst wheres = whereConvertor(where, schemaModel);\n\t\t\tconst res = await db.delete(schemaModel).where(...wheres);\n\n\t\t\treturn res[0];\n\t\t},\n\t\tasync deleteMany(data) {\n\t\t\tconst { model, where } = data;\n\t\t\tconst schemaModel = getSchema(model, {\n\t\t\t\tschema,\n\t\t\t\tusePlural: options.usePlural,\n\t\t\t});\n\t\t\tconst wheres = whereConvertor(where, schemaModel);\n\t\t\tawait db.delete(schemaModel).where(...wheres);\n\t\t},\n\t\toptions,\n\t};\n};\n","export class BetterAuthError extends Error {\n\tconstructor(message: string, cause?: string) {\n\t\tsuper(message);\n\t\tthis.name = \"BetterAuthError\";\n\t\tthis.message = message;\n\t\tthis.cause = cause;\n\t\tthis.stack = \"\";\n\t}\n}\nexport class MissingDependencyError extends BetterAuthError {\n\tconstructor(pkgName: string) {\n\t\tsuper(\n\t\t\t`The package \"${pkgName}\" is required. Make sure it is installed.`,\n\t\t\tpkgName,\n\t\t);\n\t}\n}\n"],"mappings":"AAAA,OAAS,OAAAA,EAAK,OAAAC,EAAK,QAAAC,EAAM,MAAAC,EAAI,MAAAC,EAAS,WAAAC,EAAS,QAAAC,MAAY,cCApD,IAAMC,EAAN,cAA8B,KAAM,CAC1C,YAAYC,EAAiBC,EAAgB,CAC5C,MAAMD,CAAO,EACb,KAAK,KAAO,kBACZ,KAAK,QAAUA,EACf,KAAK,MAAQC,EACb,KAAK,MAAQ,EACd,CACD,EDgBA,SAASC,EACRC,EACAC,EAIC,CACD,IAAMC,EAASD,EAAQ,OACvB,GAAI,CAACC,EACJ,MAAM,IAAIC,EACT,uHACD,EAED,IAAMC,EAAQH,EAAQ,UAAY,GAAGD,CAAS,IAAMA,EAE9CK,EAAcH,EAAOE,CAAK,EAChC,GAAI,CAACC,EACJ,MAAM,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nBjB,EAAcN,EAAUK,EAAO,CACpC,OAAAF,EACA,UAAWD,EAAQ,SACpB,CAAC,EACKyB,EAASpB,EAAeC,EAAOF,CAAW,EAGhD,OAFY,MAAMe,EAAG,OAAOf,CAAW,EAAE,MAAM,GAAGqB,CAAM,GAE7C,CAAC,CACb,EACA,MAAM,WAAWJ,EAAM,CACtB,GAAM,CAAE,MAAAlB,EAAO,MAAAG,CAAM,EAAIe,EACnBjB,EAAcN,EAAUK,EAAO,CACpC,OAAAF,EACA,UAAWD,EAAQ,SACpB,CAAC,EACKyB,EAASpB,EAAeC,EAAOF,CAAW,EAChD,MAAMe,EAAG,OAAOf,CAAW,EAAE,MAAM,GAAGqB,CAAM,CAC7C,EACA,QAAAzB,CACD,CACD","names":["and","asc","desc","eq","or","inArray","like","BetterAuthError","message","cause","getSchema","modelName","options","schema","BetterAuthError","model","schemaModel","whereConvertor","where","w","inArray","like","eq","andGroup","orGroup","andClause","and","orClause","or","clause","drizzleAdapter","db","databaseType","data","val","mutation","included","wheres","res","include","limit","offset","sortBy","filters","fn","desc","asc","update"]}
|
|
1
|
+
{"version":3,"sources":["../../src/adapters/drizzle-adapter/index.ts","../../src/error/index.ts"],"sourcesContent":["import { and, asc, desc, eq, or, SQL, inArray, like } from \"drizzle-orm\";\nimport type { Adapter, Where } from \"../../types\";\nimport { BetterAuthError } from \"../../error\";\n\nexport interface DrizzleAdapterOptions {\n\tschema?: Record<string, any>;\n\tprovider: \"pg\" | \"mysql\" | \"sqlite\";\n\t/**\n\t * If the table names in the schema are plural\n\t * set this to true. For example, if the schema\n\t * has an object with a key \"users\" instead of \"user\"\n\t */\n\tusePlural?: boolean;\n\t/**\n\t * Custom generateId function.\n\t *\n\t * If not provided, nanoid will be used.\n\t * If set to false, the database's auto generated id will be used.\n\t *\n\t * @default nanoid\n\t */\n\tgenerateId?: ((size?: number) => string) | false;\n}\n\nfunction getSchema(\n\tmodelName: string,\n\toptions: {\n\t\tschema: Record<string, any>;\n\t\tusePlural?: boolean;\n\t},\n) {\n\tconst schema = options.schema;\n\tif (!schema) {\n\t\tthrow new BetterAuthError(\n\t\t\t\"Drizzle adapter failed to initialize. Schema not found. Please provide a schema object in the adapter options object.\",\n\t\t);\n\t}\n\tconst model = options.usePlural ? `${modelName}s` : modelName;\n\n\tconst schemaModel = schema[model];\n\tif (!schemaModel) {\n\t\tthrow new BetterAuthError(\n\t\t\t`[# Drizzle Adapter]: The model \"${modelName}\" was not found in the schema object. Please pass the schema directly to the adapter options.`,\n\t\t);\n\t}\n\treturn schemaModel;\n}\n\nfunction whereConvertor(where: Where[], schemaModel: any) {\n\tif (!where) return [];\n\tif (where.length === 1) {\n\t\tconst w = where[0];\n\t\tif (!w) {\n\t\t\treturn [];\n\t\t}\n\n\t\tif (w.operator === \"in\") {\n\t\t\tif (!Array.isArray(w.value)) {\n\t\t\t\tthrow new BetterAuthError(\n\t\t\t\t\t`The value for the field \"${w.field}\" must be an array when using the \"in\" operator.`,\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn [inArray(schemaModel[w.field], w.value)];\n\t\t}\n\n\t\tif (w.operator === \"contains\") {\n\t\t\treturn [like(schemaModel[w.field], `%${w.value}%`)];\n\t\t}\n\n\t\tif (w.operator === \"starts_with\") {\n\t\t\treturn [like(schemaModel[w.field], `${w.value}%`)];\n\t\t}\n\n\t\tif (w.operator === \"ends_with\") {\n\t\t\treturn [like(schemaModel[w.field], `%${w.value}`)];\n\t\t}\n\n\t\treturn [eq(schemaModel[w.field], w.value)];\n\t}\n\tconst andGroup = where.filter((w) => w.connector === \"AND\" || !w.connector);\n\tconst orGroup = where.filter((w) => w.connector === \"OR\");\n\n\tconst andClause = and(\n\t\t...andGroup.map((w) => {\n\t\t\tif (w.operator === \"in\") {\n\t\t\t\tif (!Array.isArray(w.value)) {\n\t\t\t\t\tthrow new BetterAuthError(\n\t\t\t\t\t\t`The value for the field \"${w.field}\" must be an array when using the \"in\" operator.`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\treturn inArray(schemaModel[w.field], w.value);\n\t\t\t}\n\t\t\treturn eq(schemaModel[w.field], w.value);\n\t\t}),\n\t);\n\tconst orClause = or(\n\t\t...orGroup.map((w) => {\n\t\t\treturn eq(schemaModel[w.field], w.value);\n\t\t}),\n\t);\n\n\tconst clause: SQL<unknown>[] = [];\n\n\tif (andGroup.length) clause.push(andClause!);\n\tif (orGroup.length) clause.push(orClause!);\n\treturn clause;\n}\n\ninterface DB {\n\t[key: string]: any;\n}\n\nexport const drizzleAdapter = (\n\tdb: DB,\n\toptions: DrizzleAdapterOptions,\n): Adapter => {\n\tconst schema = options.schema || db._.fullSchema;\n\tconst databaseType = options?.provider;\n\treturn {\n\t\tid: \"drizzle\",\n\t\tasync create(data) {\n\t\t\tconst { model, data: val } = data;\n\t\t\tconst schemaModel = getSchema(model, {\n\t\t\t\tschema,\n\t\t\t\tusePlural: options.usePlural,\n\t\t\t});\n\t\t\tif (options.generateId !== undefined) {\n\t\t\t\tval.id = options.generateId ? options.generateId() : undefined;\n\t\t\t}\n\n\t\t\tconst mutation = db.insert(schemaModel).values(val);\n\t\t\tif (databaseType !== \"mysql\") return (await mutation.returning())[0];\n\n\t\t\tawait mutation;\n\t\t\tconst res = await db\n\t\t\t\t.select()\n\t\t\t\t.from(schemaModel)\n\t\t\t\t.where(eq(schemaModel.id, (data.data as { id: string }).id));\n\t\t\treturn res[0];\n\t\t},\n\t\tasync findOne(data) {\n\t\t\tconst { model, where, select: included } = data;\n\n\t\t\tconst schemaModel = getSchema(model, {\n\t\t\t\tschema,\n\t\t\t\tusePlural: options.usePlural,\n\t\t\t});\n\n\t\t\tconst wheres = whereConvertor(where, schemaModel);\n\n\t\t\tlet res = null;\n\t\t\tif (!!included?.length) {\n\t\t\t\tres = await db\n\t\t\t\t\t.select(\n\t\t\t\t\t\t...included.map((include) => {\n\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\t[include]: schemaModel[include],\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t}),\n\t\t\t\t\t)\n\t\t\t\t\t.from(schemaModel)\n\t\t\t\t\t.where(...wheres);\n\t\t\t} else {\n\t\t\t\tres = await db\n\t\t\t\t\t.select()\n\t\t\t\t\t.from(schemaModel)\n\t\t\t\t\t.where(...wheres);\n\t\t\t}\n\n\t\t\tif (!!res.length) return res[0];\n\t\t\telse return null;\n\t\t},\n\t\tasync findMany(data) {\n\t\t\tconst { model, where, limit, offset, sortBy } = data;\n\t\t\tconst schemaModel = getSchema(model, {\n\t\t\t\tschema,\n\t\t\t\tusePlural: options.usePlural,\n\t\t\t});\n\t\t\tconst filters = where ? whereConvertor(where, schemaModel) : [];\n\t\t\tconst fn = sortBy?.direction === \"desc\" ? desc : asc;\n\t\t\tconst res = await db\n\t\t\t\t.select()\n\t\t\t\t.from(schemaModel)\n\t\t\t\t.limit(limit || 100)\n\t\t\t\t.offset(offset || 0)\n\t\t\t\t.orderBy(fn(schemaModel[sortBy?.field || \"id\"]))\n\t\t\t\t.where(...(filters.length ? filters : []));\n\n\t\t\treturn res;\n\t\t},\n\t\tasync update(data) {\n\t\t\tconst { model, where, update } = data;\n\t\t\tconst schemaModel = getSchema(model, {\n\t\t\t\tschema,\n\t\t\t\tusePlural: options.usePlural,\n\t\t\t});\n\t\t\tif (update.id) {\n\t\t\t\tupdate.id = undefined;\n\t\t\t}\n\t\t\tconst wheres = whereConvertor(where, schemaModel);\n\t\t\tconst mutation = db\n\t\t\t\t.update(schemaModel)\n\t\t\t\t.set(update)\n\t\t\t\t.where(...wheres);\n\t\t\tif (databaseType !== \"mysql\") return (await mutation.returning())[0];\n\n\t\t\tawait mutation;\n\t\t\tconst res = await db\n\t\t\t\t.select()\n\t\t\t\t.from(schemaModel)\n\t\t\t\t.where(eq(schemaModel.id, (data.update as { id: string }).id));\n\t\t\treturn res[0];\n\t\t},\n\t\tasync delete(data) {\n\t\t\tconst { model, where } = data;\n\t\t\tconst schemaModel = getSchema(model, {\n\t\t\t\tschema,\n\t\t\t\tusePlural: options.usePlural,\n\t\t\t});\n\t\t\tconst wheres = whereConvertor(where, schemaModel);\n\t\t\tconst res = await db.delete(schemaModel).where(...wheres);\n\n\t\t\treturn res[0];\n\t\t},\n\t\tasync deleteMany(data) {\n\t\t\tconst { model, where } = data;\n\t\t\tconst schemaModel = getSchema(model, {\n\t\t\t\tschema,\n\t\t\t\tusePlural: options.usePlural,\n\t\t\t});\n\t\t\tconst wheres = whereConvertor(where, schemaModel);\n\t\t\tawait db.delete(schemaModel).where(...wheres);\n\t\t},\n\t\toptions,\n\t};\n};\n","export class BetterAuthError extends Error {\n\tconstructor(message: string, cause?: string) {\n\t\tsuper(message);\n\t\tthis.name = \"BetterAuthError\";\n\t\tthis.message = message;\n\t\tthis.cause = cause;\n\t}\n}\nexport class MissingDependencyError extends BetterAuthError {\n\tconstructor(pkgName: string) {\n\t\tsuper(\n\t\t\t`The package \"${pkgName}\" is required. Make sure it is installed.`,\n\t\t\tpkgName,\n\t\t);\n\t}\n}\n"],"mappings":"AAAA,OAAS,OAAAA,EAAK,OAAAC,EAAK,QAAAC,EAAM,MAAAC,EAAI,MAAAC,EAAS,WAAAC,EAAS,QAAAC,MAAY,cCApD,IAAMC,EAAN,cAA8B,KAAM,CAC1C,YAAYC,EAAiBC,EAAgB,CAC5C,MAAMD,CAAO,EACb,KAAK,KAAO,kBACZ,KAAK,QAAUA,EACf,KAAK,MAAQC,CACd,CACD,EDiBA,SAASC,EACRC,EACAC,EAIC,CACD,IAAMC,EAASD,EAAQ,OACvB,GAAI,CAACC,EACJ,MAAM,IAAIC,EACT,uHACD,EAED,IAAMC,EAAQH,EAAQ,UAAY,GAAGD,CAAS,IAAMA,EAE9CK,EAAcH,EAAOE,CAAK,EAChC,GAAI,CAACC,EACJ,MAAM,IAAIF,EACT,mCAAmCH,CAAS,+FAC7C,EAED,OAAOK,CACR,CAEA,SAASC,EAAeC,EAAgBF,EAAkB,CACzD,GAAI,CAACE,EAAO,MAAO,CAAC,EACpB,GAAIA,EAAM,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W,EAAE,MAAM,GAAGqB,CAAM,GAE7C,CAAC,CACb,EACA,MAAM,WAAWJ,EAAM,CACtB,GAAM,CAAE,MAAAlB,EAAO,MAAAG,CAAM,EAAIe,EACnBjB,EAAcN,EAAUK,EAAO,CACpC,OAAAF,EACA,UAAWD,EAAQ,SACpB,CAAC,EACKyB,EAASpB,EAAeC,EAAOF,CAAW,EAChD,MAAMe,EAAG,OAAOf,CAAW,EAAE,MAAM,GAAGqB,CAAM,CAC7C,EACA,QAAAzB,CACD,CACD","names":["and","asc","desc","eq","or","inArray","like","BetterAuthError","message","cause","getSchema","modelName","options","schema","BetterAuthError","model","schemaModel","whereConvertor","where","w","inArray","like","eq","andGroup","orGroup","andClause","and","orClause","or","clause","drizzleAdapter","db","databaseType","data","val","mutation","included","wheres","res","include","limit","offset","sortBy","filters","fn","desc","asc","update"]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { Kysely } from 'kysely';
|
|
2
|
-
import { B as BetterAuthOptions, K as KyselyDatabaseType, F as FieldAttribute, A as Adapter } from '../auth-
|
|
2
|
+
import { B as BetterAuthOptions, K as KyselyDatabaseType, F as FieldAttribute, A as Adapter } from '../auth-B9t_YkMU.js';
|
|
3
3
|
import 'zod';
|
|
4
4
|
import '../schema-Dkt0LqYs.js';
|
|
5
5
|
import 'better-call';
|
package/dist/api.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { e as AuthEndpoint, f as AuthMiddleware, a1 as callbackOAuth, aj as changeEmail, ag as changePassword, d as createAuthEndpoint, c as createAuthMiddleware, ac as createEmailVerificationToken, ao as csrfMiddleware, ai as deleteUser, al as error, a9 as forgetPassword, aa as forgetPasswordCallback, ak as getCSRFToken, Z as getEndpoints, a2 as getSession, a3 as getSessionFromCtx, a5 as listSessions, am as ok, o as optionsMiddleware, ab as resetPassword, a6 as revokeSession, a7 as revokeSessions, _ as router, ad as sendVerificationEmail, a4 as sessionMiddleware, ah as setPassword, a0 as signInEmail, $ as signInOAuth, a8 as signOut, an as signUpEmail, af as updateUser, ae as verifyEmail } from './auth-
|
|
1
|
+
export { e as AuthEndpoint, f as AuthMiddleware, a1 as callbackOAuth, aj as changeEmail, ag as changePassword, d as createAuthEndpoint, c as createAuthMiddleware, ac as createEmailVerificationToken, ao as csrfMiddleware, ai as deleteUser, al as error, a9 as forgetPassword, aa as forgetPasswordCallback, ak as getCSRFToken, Z as getEndpoints, a2 as getSession, a3 as getSessionFromCtx, a5 as listSessions, am as ok, o as optionsMiddleware, ab as resetPassword, a6 as revokeSession, a7 as revokeSessions, _ as router, ad as sendVerificationEmail, a4 as sessionMiddleware, ah as setPassword, a0 as signInEmail, $ as signInOAuth, a8 as signOut, an as signUpEmail, af as updateUser, ae as verifyEmail } from './auth-B9t_YkMU.js';
|
|
2
2
|
import './helper-DPDj8Nix.js';
|
|
3
3
|
export { APIError } from 'better-call';
|
|
4
4
|
import 'zod';
|
package/dist/api.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{APIError as nt,createRouter as qt,statusCode as Nt}from"better-call";import{APIError as J}from"better-call";import{z as de}from"zod";import{xchacha20poly1305 as or}from"@noble/ciphers/chacha";import{bytesToHex as ir,hexToBytes as sr,utf8ToBytes as ar}from"@noble/ciphers/utils";import{managedNonce as cr}from"@noble/ciphers/webcrypto";import{sha256 as ur}from"oslo/crypto";import ie from"uncrypto";function W(e,t){let r=new Uint8Array(e),o=new Uint8Array(t);if(r.length!==o.length)return!1;let n=0;for(let i=0;i<r.length;i++)n|=r[i]^o[i];return n===0}import{decodeHex as Zt,encodeHex as Qt}from"oslo/encoding";import{scryptAsync as Jt}from"@noble/hashes/scrypt";import{getRandomValues as Yt}from"uncrypto";import te from"uncrypto";function it(e){return e.toString(2).padStart(8,"0")}function st(e){return[...e].map(t=>it(t)).join("")}function re(e){return parseInt(st(e),2)}function at(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));te.getRandomValues(o),r!==0&&(o[0]&=(1<<r)-1);let n=re(o);for(;n>=e;)te.getRandomValues(o),r!==0&&(o[0]&=(1<<r)-1),n=re(o);return n}function oe(e,t){let r="";for(let o=0;o<e;o++)r+=t[at(t.length)];return r}function ne(...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 F(e,t){let r=new TextEncoder,o={name:"HMAC",hash:"SHA-256"},n=await ie.subtle.importKey("raw",r.encode(e),o,!1,["sign","verify"]),i=await ie.subtle.sign(o.name,n,r.encode(t));return btoa(String.fromCharCode(...new Uint8Array(i)))}import{createEndpointCreator as dt,createMiddleware as se,createMiddlewareCreator as ct}from"better-call";var ae=se(async()=>({})),$=ct({use:[ae,se(async()=>({}))]}),m=dt({use:[ae]});var ce=$({body:de.object({csrfToken:de.string().optional()}).optional()},async e=>{if(e.request?.method!=="POST"||e.context.options.advanced?.disableCSRFCheck)return;let t=e.headers?.get("origin")||"";if(t){let a=new URL(t).origin;if(e.context.trustedOrigins.includes(a))return}let r=e.body?.csrfToken;if(!r)throw new J("UNAUTHORIZED",{message:"CSRF Token is required"});let o=await e.getSignedCookie(e.context.authCookies.csrfToken.name,e.context.secret),[n,i]=o?.split("!")||[null,null];if(!r||!n||!i||n!==r)throw e.setCookie(e.context.authCookies.csrfToken.name,"",{maxAge:0}),new J("UNAUTHORIZED",{message:"Invalid CSRF Token"});let s=await F(e.context.secret,n);if(i!==s)throw e.setCookie(e.context.authCookies.csrfToken.name,"",{maxAge:0}),new J("UNAUTHORIZED",{message:"Invalid CSRF Token"})});import{APIError as S}from"better-call";import{generateCodeVerifier as _t}from"oslo/oauth2";import{z as T}from"zod";import{generateState as lt}from"oslo/oauth2";import{z as H}from"zod";import{sha256 as le}from"oslo/crypto";async function ue(e){let t=await le(typeof e=="string"?new TextEncoder().encode(e):e);return Buffer.from(t).toString("base64")}async function pe(e,t){let r=await le(typeof e=="string"?new TextEncoder().encode(e):e),o=Buffer.from(t,"base64");return W(r,o)}import"better-call";async function me(e){let t=lt(),r=JSON.stringify({code:t,callbackURL:e}),o=await ue(r);return{raw:r,hash:o}}function K(e){return H.object({code:H.string(),callbackURL:H.string().optional(),currentURL:H.string().optional()}).safeParse(JSON.parse(e))}import{TimeSpan as $r}from"oslo";var V=class extends Error{constructor(t,r){super(t),this.name="BetterAuthError",this.message=t,this.cause=r
|
|
1
|
+
import{APIError as nt,createRouter as qt,statusCode as Nt}from"better-call";import{APIError as J}from"better-call";import{z as de}from"zod";import{xchacha20poly1305 as or}from"@noble/ciphers/chacha";import{bytesToHex as ir,hexToBytes as sr,utf8ToBytes as ar}from"@noble/ciphers/utils";import{managedNonce as cr}from"@noble/ciphers/webcrypto";import{sha256 as ur}from"oslo/crypto";import ie from"uncrypto";function W(e,t){let r=new Uint8Array(e),o=new Uint8Array(t);if(r.length!==o.length)return!1;let n=0;for(let i=0;i<r.length;i++)n|=r[i]^o[i];return n===0}import{decodeHex as Zt,encodeHex as Qt}from"oslo/encoding";import{scryptAsync as Jt}from"@noble/hashes/scrypt";import{getRandomValues as Yt}from"uncrypto";import te from"uncrypto";function it(e){return e.toString(2).padStart(8,"0")}function st(e){return[...e].map(t=>it(t)).join("")}function re(e){return parseInt(st(e),2)}function at(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));te.getRandomValues(o),r!==0&&(o[0]&=(1<<r)-1);let n=re(o);for(;n>=e;)te.getRandomValues(o),r!==0&&(o[0]&=(1<<r)-1),n=re(o);return n}function oe(e,t){let r="";for(let o=0;o<e;o++)r+=t[at(t.length)];return r}function ne(...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 F(e,t){let r=new TextEncoder,o={name:"HMAC",hash:"SHA-256"},n=await ie.subtle.importKey("raw",r.encode(e),o,!1,["sign","verify"]),i=await ie.subtle.sign(o.name,n,r.encode(t));return btoa(String.fromCharCode(...new Uint8Array(i)))}import{createEndpointCreator as dt,createMiddleware as se,createMiddlewareCreator as ct}from"better-call";var ae=se(async()=>({})),$=ct({use:[ae,se(async()=>({}))]}),m=dt({use:[ae]});var ce=$({body:de.object({csrfToken:de.string().optional()}).optional()},async e=>{if(e.request?.method!=="POST"||e.context.options.advanced?.disableCSRFCheck)return;let t=e.headers?.get("origin")||"";if(t){let a=new URL(t).origin;if(e.context.trustedOrigins.includes(a))return}let r=e.body?.csrfToken;if(!r)throw new J("UNAUTHORIZED",{message:"CSRF Token is required"});let o=await e.getSignedCookie(e.context.authCookies.csrfToken.name,e.context.secret),[n,i]=o?.split("!")||[null,null];if(!r||!n||!i||n!==r)throw e.setCookie(e.context.authCookies.csrfToken.name,"",{maxAge:0}),new J("UNAUTHORIZED",{message:"Invalid CSRF Token"});let s=await F(e.context.secret,n);if(i!==s)throw e.setCookie(e.context.authCookies.csrfToken.name,"",{maxAge:0}),new J("UNAUTHORIZED",{message:"Invalid CSRF Token"})});import{APIError as S}from"better-call";import{generateCodeVerifier as _t}from"oslo/oauth2";import{z as T}from"zod";import{generateState as lt}from"oslo/oauth2";import{z as H}from"zod";import{sha256 as le}from"oslo/crypto";async function ue(e){let t=await le(typeof e=="string"?new TextEncoder().encode(e):e);return Buffer.from(t).toString("base64")}async function pe(e,t){let r=await le(typeof e=="string"?new TextEncoder().encode(e):e),o=Buffer.from(t,"base64");return W(r,o)}import"better-call";async function me(e){let t=lt(),r=JSON.stringify({code:t,callbackURL:e}),o=await ue(r);return{raw:r,hash:o}}function K(e){return H.object({code:H.string(),callbackURL:H.string().optional(),currentURL:H.string().optional()}).safeParse(JSON.parse(e))}import{TimeSpan as $r}from"oslo";var V=class extends Error{constructor(t,r){super(t),this.name="BetterAuthError",this.message=t,this.cause=r}};import{env as jr,isProduction as qr}from"std-env";async function O(e,t,r,o){let n=e.context.authCookies.sessionToken.options;n.maxAge=r?void 0:e.context.sessionConfig.expiresIn,await e.setSignedCookie(e.context.authCookies.sessionToken.name,t,e.context.secret,{...n,...o}),r&&await e.setSignedCookie(e.context.authCookies.dontRememberToken.name,"true",e.context.secret,e.context.authCookies.dontRememberToken.options)}function N(e){e.setCookie(e.context.authCookies.sessionToken.name,"",{maxAge:0}),e.setCookie(e.context.authCookies.dontRememberToken.name,"",{maxAge:0})}import{APIError as mt}from"better-call";import{createConsola as ut}from"consola";var D=ut({formatOptions:{date:!1,colors:!0,compact:!0},defaults:{tag:"Better Auth"}}),pt=e=>({log:(...t)=>{!e?.disabled&&D.log("",...t)},error:(...t)=>{!e?.disabled&&D.error("",...t)},warn:(...t)=>{!e?.disabled&&D.warn("",...t)},info:(...t)=>{!e?.disabled&&D.info("",...t)},debug:(...t)=>{!e?.disabled&&D.debug("",...t)},box:(...t)=>{!e?.disabled&&D.box("",...t)},success:(...t)=>{!e?.disabled&&D.success("",...t)},break:(...t)=>{!e?.disabled&&console.log(`
|
|
2
2
|
`)}}),w=pt();var U=$(async e=>{let{body:t,query:r,headers:o,context:n}=e,i=t?.callbackURL||r?.callbackURL||r?.redirectTo||t?.redirectTo,s=r?.currentURL||o?.get("referer")||n.baseURL,a=n.trustedOrigins,c=(d,l)=>{if(d?.startsWith("http")&&!a.some(g=>d.startsWith(g)))throw w.error(`Invalid ${l}`,{[l]:d,trustedOrigins:a}),new mt("FORBIDDEN",{message:`Invalid ${l}`})};c(i,"callbackURL"),c(s,"currentURL")});import{parseJWT as wt}from"oslo/jwt";import{sha256 as ft}from"oslo/crypto";import{base64url as gt}from"oslo/encoding";async function fe(e){let t=await ft(new TextEncoder().encode(e));return gt.encode(new Uint8Array(t),{includePadding:!1})}function ge(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:n,scopes:i,claims:s,disablePkce:a,redirectURI:c}){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",i.join(" ")),d.searchParams.set("redirect_uri",t.redirectURI||c),!a&&n){let l=await fe(n);d.searchParams.set("code_challenge_method","S256"),d.searchParams.set("code_challenge",l)}if(s){let l=s.reduce((h,g)=>(h[g]=null,h),{});d.searchParams.set("claims",JSON.stringify({id_token:{email:null,email_verified:null,...l}}))}return d}import{betterFetch as ht}from"@better-fetch/fetch";async function y({code:e,codeVerifier:t,redirectURI:r,options:o,tokenEndpoint:n}){let i=new URLSearchParams;i.set("grant_type","authorization_code"),i.set("code",e),t&&i.set("code_verifier",t),i.set("redirect_uri",r),i.set("client_id",o.clientId),i.set("client_secret",o.clientSecret);let{data:s,error:a}=await ht(n,{method:"POST",body:i,headers:{"content-type":"application/x-www-form-urlencoded",accept:"application/json","user-agent":"better-auth"}});if(a)throw a;return ge(s)}function Y(e){let t=e.accessToken,r=e.refreshToken,o;try{o=e.accessTokenExpiresAt}catch{}return{accessToken:t,refreshToken:r,expiresAt:o}}var he=e=>{let t="https://appleid.apple.com/auth/token";return{id:"apple",name:"Apple",createAuthorizationURL({state:r,scopes:o,redirectURI:n}){let i=e.scope||o||["email","name","openid"];return new URL(`https://appleid.apple.com/auth/authorize?client_id=${e.clientId}&response_type=code&redirect_uri=${n||e.redirectURI}&scope=${i.join(" ")}&state=${r}`)},validateAuthorizationCode:async({code:r,codeVerifier:o,redirectURI:n})=>y({code:r,codeVerifier:o,redirectURI:e.redirectURI||n,options:e,tokenEndpoint:t}),async getUserInfo(r){if(!r.idToken)return null;let o=wt(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 we=e=>({id:"discord",name:"Discord",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let n=e.scope||r||["identify","email"];return new URL(`https://discord.com/api/oauth2/authorize?scope=${n.join("+")}&response_type=code&client_id=${e.clientId}&redirect_uri=${encodeURIComponent(e.redirectURI||o)}&state=${t}`)},validateAuthorizationCode:async({code:t,redirectURI:r})=>y({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 n=r.discriminator==="0"?Number(BigInt(r.id)>>BigInt(22))%6:parseInt(r.discriminator)%5;r.image_url=`https://cdn.discordapp.com/embed/avatars/${n}.png`}else{let n=r.avatar.startsWith("a_")?"gif":"png";r.image_url=`https://cdn.discordapp.com/avatars/${r.id}/${r.avatar}.${n}`}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 bt}from"@better-fetch/fetch";var ye=e=>({id:"facebook",name:"Facebook",async createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let n=e.scope||r||["email","public_profile"];return await E({id:"facebook",options:e,authorizationEndpoint:"https://www.facebook.com/v21.0/dialog/oauth",scopes:n,state:t,redirectURI:o})},validateAuthorizationCode:async({code:t,redirectURI:r})=>y({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 bt("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,image:r.picture.data.url,emailVerified:r.email_verified},data:r}}});import{betterFetch as be}from"@better-fetch/fetch";var Ae=e=>{let t="https://github.com/login/oauth/access_token";return{id:"github",name:"Github",createAuthorizationURL({state:r,scopes:o,codeVerifier:n,redirectURI:i}){let s=e.scope||o||["user:email"];return E({id:"github",options:e,authorizationEndpoint:"https://github.com/login/oauth/authorize",scopes:s,state:r,redirectURI:i,codeVerifier:n})},validateAuthorizationCode:async({code:r,redirectURI:o})=>y({code:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:t}),async getUserInfo(r){let{data:o,error:n}=await be("https://api.github.com/user",{headers:{"User-Agent":"better-auth",authorization:`Bearer ${r.accessToken}`}});if(n)return null;let i=!1;if(!o.email){let{data:s,error:a}=await be("https://api.github.com/user/emails",{headers:{authorization:`Bearer ${r.accessToken}`,"User-Agent":"better-auth"}});a||(o.email=(s.find(c=>c.primary)??s[0])?.email,i=s.find(c=>c.email===o.email)?.verified??!1)}return{user:{id:o.id.toString(),name:o.name||o.login,email:o.email,image:o.avatar_url,emailVerified:i},data:o}}}};import{parseJWT as At}from"oslo/jwt";var ke=e=>({id:"google",name:"Google",createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:n}){if(!e.clientId||!e.clientSecret)throw w.error("Client Id and Client Secret is required for Google. Make sure to provide them in the options."),new V("CLIENT_ID_AND_SECRET_REQUIRED");if(!o)throw new V("codeVerifier is required for Google");let i=e.scope||r||["email","profile"];return E({id:"google",options:e,authorizationEndpoint:"https://accounts.google.com/o/oauth2/auth",scopes:i,state:t,codeVerifier:o,redirectURI:n})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>y({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=At(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 kt}from"@better-fetch/fetch";import{parseJWT as Rt}from"oslo/jwt";var Re=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(n){let i=e.scope||n.scopes||["openid","profile","email","User.Read"];return E({id:"microsoft",options:e,authorizationEndpoint:r,state:n.state,codeVerifier:n.codeVerifier,scopes:i,redirectURI:n.redirectURI})},validateAuthorizationCode({code:n,codeVerifier:i,redirectURI:s}){return y({code:n,codeVerifier:i,redirectURI:e.redirectURI||s,options:e,tokenEndpoint:o})},async getUserInfo(n){if(!n.idToken)return null;let i=Rt(n.idToken)?.payload,s=e.profilePhotoSize||48;return await kt(`https://graph.microsoft.com/v1.0/me/photos/${s}x${s}/$value`,{headers:{Authorization:`Bearer ${n.accessToken}`},async onResponse(a){if(!(e.disableProfilePhoto||!a.response.ok))try{let d=await a.response.clone().arrayBuffer(),l=Buffer.from(d).toString("base64");i.picture=`data:image/jpeg;base64, ${l}`}catch(c){w.error(c)}}}),{user:{id:i.sub,name:i.name,email:i.email,image:i.picture,emailVerified:!0},data:i}}}};import{betterFetch as Ut}from"@better-fetch/fetch";var Ue=e=>({id:"spotify",name:"Spotify",createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:n}){let i=e.scope||r||["user-read-email"];return E({id:"spotify",options:e,authorizationEndpoint:"https://accounts.spotify.com/authorize",scopes:i,state:t,codeVerifier:o,redirectURI:n})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>y({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 Ut("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";var C={isAction:!1};import{nanoid as Et}from"nanoid";var Ee=e=>Et(e);import{parseJWT as xt}from"oslo/jwt";var xe=e=>({id:"twitch",name:"Twitch",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let n=e.scope||r||["user:read:email","openid"];return E({id:"twitch",redirectURI:o,options:e,authorizationEndpoint:"https://id.twitch.tv/oauth2/authorize",scopes:n,state:t,claims:e.claims||["email","email_verified","preferred_username","picture"]})},validateAuthorizationCode:async({code:t,redirectURI:r})=>y({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 w.error("No idToken found in token"),null;let o=xt(r)?.payload;return{user:{id:o.sub,name:o.preferred_username,email:o.email,image:o.picture,emailVerified:!1},data:o}}});import{betterFetch as Tt}from"@better-fetch/fetch";var Te=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})=>y({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 Tt("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 vt={apple:he,discord:we,facebook:ye,github:Ae,microsoft:Re,google:ke,spotify:Ue,twitch:xe,twitter:Te},ve=Object.keys(vt);import{TimeSpan as St}from"oslo";import{createJWT as Pt,validateJWT as Ot}from"oslo/jwt";import{z as v}from"zod";import{APIError as z}from"better-call";import{APIError as M}from"better-call";var Z=(e,t="ms")=>new Date(Date.now()+(t==="sec"?e*1e3:e));import{z as Se}from"zod";var X=()=>m("/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 N(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 n=e.context.sessionConfig.expiresIn,i=e.context.sessionConfig.updateAge;if(r.session.expiresAt.valueOf()-n*1e3+i*1e3<=Date.now()){let c=await e.context.internalAdapter.updateSession(r.session.id,{expiresAt:Z(e.context.sessionConfig.expiresIn,"sec")});if(!c)return N(e),e.json(null,{status:401});let d=(c.expiresAt.valueOf()-Date.now())/1e3;return await O(e,c.id,!1,{maxAge:d}),e.json({session:c,user:r.user})}return e.json(r)}catch(t){return e.context.logger.error(t),e.json(null,{status:500})}}),ee=async e=>await X()({...e,_flag:"json",headers:e.headers}),_=$(async e=>{let t=await ee(e);if(!t?.session)throw new M("UNAUTHORIZED");return{session:t}}),Pe=()=>m("/user/list-sessions",{method:"GET",use:[_],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)}),Oe=m("/user/revoke-session",{method:"POST",body:Se.object({id:Se.string()}),use:[_],requireHeaders:!0},async e=>{let t=e.body.id,r=await e.context.internalAdapter.findSession(t);if(!r)throw new M("BAD_REQUEST",{message:"Session not found"});if(r.session.userId!==e.context.session.user.id)throw new M("UNAUTHORIZED");try{await e.context.internalAdapter.deleteSession(t)}catch(o){throw e.context.logger.error(o),new M("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),_e=m("/user/revoke-sessions",{method:"POST",use:[_],requireHeaders:!0},async e=>{try{await e.context.internalAdapter.deleteSessions(e.context.session.user.id)}catch(t){throw e.context.logger.error(t),new M("INTERNAL_SERVER_ERROR")}return e.json({status:!0})});async function L(e,t,r){return await Pt("HS256",Buffer.from(e),{email:t.toLowerCase(),updateTo:r},{expiresIn:new St(1,"h"),issuer:"better-auth",subject:"verify-email",audiences:[t],includeIssuedTimestamp:!0})}var Le=m("/send-verification-email",{method:"POST",query:v.object({currentURL:v.string().optional()}).optional(),body:v.object({email:v.string().email(),callbackURL:v.string().optional()}),use:[U]},async e=>{if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),new z("BAD_REQUEST",{message:"Verification email isn't enabled"});let{email:t}=e.body,r=await e.context.internalAdapter.findUserByEmail(t);if(!r)throw new z("BAD_REQUEST",{message:"User not found"});let o=await L(e.context.secret,t),n=`${e.context.baseURL}/verify-email?token=${o}&callbackURL=${e.body.callbackURL||e.query?.currentURL||"/"}`;return await e.context.options.emailVerification.sendVerificationEmail(r.user,n,o),e.json({status:!0})}),Ie=m("/verify-email",{method:"GET",query:v.object({token:v.string(),callbackURL:v.string().optional()}),use:[U]},async e=>{let{token:t}=e.query,r;try{r=await Ot("HS256",Buffer.from(e.context.secret),t)}catch(s){throw e.context.logger.error("Failed to verify email",s),new z("BAD_REQUEST",{message:"Invalid token"})}let n=v.object({email:v.string().email(),updateTo:v.string().optional()}).parse(r.payload);if(!await e.context.internalAdapter.findUserByEmail(n.email))throw new z("BAD_REQUEST",{message:"User not found"});if(n.updateTo){let s=await ee(e);if(!s)throw e.query.callbackURL?e.redirect(`${e.query.callbackURL}?error=unauthorized`):new z("UNAUTHORIZED",{message:"Session not found"});if(s.user.email!==n.email)throw e.query.callbackURL?e.redirect(`${e.query.callbackURL}?error=unauthorized`):new z("UNAUTHORIZED",{message:"Invalid session"});let a=await e.context.internalAdapter.updateUserByEmail(n.email,{email:n.updateTo});if(await e.context.options.emailVerification?.sendVerificationEmail?.(a,`${e.context.baseURL}/verify-email?token=${t}`,t),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({user:a,status:!0})}if(await e.context.internalAdapter.updateUserByEmail(n.email,{emailVerified:!0}),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({user:null,status:!0})});var Ce=m("/sign-in/social",{method:"POST",requireHeaders:!0,query:T.object({currentURL:T.string().optional()}).optional(),body:T.object({callbackURL:T.string().optional(),provider:T.enum(ve)}),use:[U]},async e=>{let t=e.context.socialProviders.find(c=>c.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 S("NOT_FOUND",{message:"Provider not found"});let r=e.context.authCookies,o=e.query?.currentURL?new URL(e.query?.currentURL):null,n=e.body.callbackURL?.startsWith("http")?e.body.callbackURL:`${o?.origin}${e.body.callbackURL||""}`,i=await me(n||o?.origin||e.context.options.baseURL);await e.setSignedCookie(r.state.name,i.hash,e.context.secret,r.state.options);let s=_t();await e.setSignedCookie(r.pkCodeVerifier.name,s,e.context.secret,r.pkCodeVerifier.options);let a=await t.createAuthorizationURL({state:i.raw,codeVerifier:s,redirectURI:`${e.context.baseURL}/callback/${t.id}`});return e.json({url:a.toString(),state:i,codeVerifier:s,redirect:!0})}),Be=m("/sign-in/email",{method:"POST",body:T.object({email:T.string(),password:T.string(),callbackURL:T.string().optional(),dontRememberMe:T.boolean().default(!1).optional()}),use:[U]},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 S("BAD_REQUEST",{message:"Email and password is not enabled"});let{email:t,password:r}=e.body;if(!T.string().email().safeParse(t).success)throw new S("BAD_REQUEST",{message:"Invalid email"});if(!T.string().email().safeParse(t).success)throw new S("BAD_REQUEST",{message:"Invalid email"});let i=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!i)throw await e.context.password.hash(r),e.context.logger.error("User not found",{email:t}),new S("UNAUTHORIZED",{message:"Invalid email or password"});let s=i.accounts.find(l=>l.providerId==="credential");if(!s)throw e.context.logger.error("Credential account not found",{email:t}),new S("UNAUTHORIZED",{message:"Invalid email or password"});let a=s?.password;if(!a)throw e.context.logger.error("Password not found",{email:t}),new S("UNAUTHORIZED",{message:"Unexpected error"});if(!await e.context.password.verify(a,r))throw e.context.logger.error("Invalid password"),new S("UNAUTHORIZED",{message:"Invalid email or password"});if(e.context.options?.emailAndPassword?.requireEmailVerification&&!i.user.emailVerified){if(!e.context.options?.emailVerification?.sendVerificationEmail)throw w.error("Email verification is required but no email verification handler is provided"),new S("INTERNAL_SERVER_ERROR",{message:"Email is not verified."});let l=await L(e.context.secret,i.user.email),h=`${e.context.options.baseURL}/verify-email?token=${l}`;throw await e.context.options.emailVerification.sendVerificationEmail(i.user,h,l),e.context.logger.error("Email not verified",{email:t}),new S("FORBIDDEN",{message:"Email is not verified. Check your email for a verification link"})}let d=await e.context.internalAdapter.createSession(i.user.id,e.headers,e.body.dontRememberMe);if(!d)throw e.context.logger.error("Failed to create session"),new S("UNAUTHORIZED",{message:"Failed to create session"});return await O(e,d.id,e.body.dontRememberMe),e.json({user:i.user,session:d,redirect:!!e.body.callbackURL,url:e.body.callbackURL})});import{z as Q}from"zod";import{z as f}from"zod";var Jn=f.object({id:f.string(),providerId:f.string(),accountId:f.string(),userId:f.string(),accessToken:f.string().nullable().optional(),refreshToken:f.string().nullable().optional(),idToken:f.string().nullable().optional(),expiresAt:f.date().nullable().optional(),password:f.string().optional().nullable()}),De=f.object({id:f.string(),email:f.string().transform(e=>e.toLowerCase()),emailVerified:f.boolean().default(!1),name:f.string(),image:f.string().optional(),createdAt:f.date().default(new Date),updatedAt:f.date().default(new Date)}),Kn=f.object({id:f.string(),userId:f.string(),expiresAt:f.date(),ipAddress:f.string().optional(),userAgent:f.string().optional()}),Yn=f.object({id:f.string(),value:f.string(),expiresAt:f.date(),identifier:f.string()});function $e(e,t){let r={...t==="user"?e.user?.additionalFields:{},...t==="session"?e.session?.additionalFields:{}};for(let o of e.plugins||[])o.schema&&o.schema[t]&&(r={...r,...o.schema[t].fields});return r}function Ve(e,t){let r=t.fields,o={};for(let n in r){if(n in e){if(r[n].input===!1){if(r[n].defaultValue){o[n]=r[n].defaultValue;continue}continue}o[n]=e[n];continue}if(r[n].defaultValue){o[n]=r[n].defaultValue;continue}}return o}function ze(e,t){let r=$e(e,"user");return Ve(t||{},{fields:r})}function je(e,t){let r=$e(e,"user");return Ve(t||{},{fields:r})}var qe=m("/callback/:id",{method:"GET",query:Q.object({state:Q.string(),code:Q.string().optional(),error:Q.string().optional()}),metadata:C},async e=>{if(e.query.error||!e.query.code){let k=K(e.query.state).data?.callbackURL||`${e.context.baseURL}/error`;throw e.context.logger.error(e.query.error,e.params.id),e.redirect(`${k}?error=${e.query.error||"oAuth_code_missing"}`)}let t=e.context.socialProviders.find(p=>p.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=K(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:n}}=r,i=await e.getSignedCookie(e.context.authCookies.state.name,e.context.secret);if(!i)throw w.error("No stored state found"),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);if(!await pe(e.query.state,i))throw w.error("OAuth state mismatch"),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);let a=await e.getSignedCookie(e.context.authCookies.pkCodeVerifier.name,e.context.secret),c;try{c=await t.validateAuthorizationCode({code:e.query.code,codeVerifier:a,redirectURI:`${e.context.baseURL}/callback/${t.id}`})}catch(p){throw e.context.logger.error(p),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`)}let d=await t.getUserInfo(c).then(p=>p?.user),l=Ee(),h=De.safeParse({...d,id:l});if(!d||h.success===!1)throw w.error("Unable to get user info",h.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 g(p){throw e.redirect(`${n||o||`${e.context.baseURL}/error`}?error=${p}`)}let u=await e.context.internalAdapter.findUserByEmail(d.email,{includeAccounts:!0}).catch(p=>{throw w.error(`Better auth was unable to query your database.
|
|
3
3
|
Error: `,p),e.redirect(`${e.context.baseURL}/error?error=internal_server_error`)}),b=u?.user.id;if(u){if(!u.accounts.find(k=>k.providerId===t.id)){(!e.context.options.account?.accountLinking?.trustedProviders?.includes(t.id)&&!d.emailVerified||!e.context.options.account?.accountLinking?.enabled)&&g("account_not_linked");try{await e.context.internalAdapter.linkAccount({providerId:t.id,accountId:d.id.toString(),id:`${t.id}:${d.id}`,userId:u.user.id,...Y(c)})}catch(B){w.error("Unable to link account",B),g("unable_to_link_account")}}}else try{let p=d.emailVerified||!1,k=await e.context.internalAdapter.createOAuthUser({...h.data,emailVerified:p},{...Y(c),providerId:t.id,accountId:d.id.toString()});if(b=k?.user.id,!p&&k&&e.context.options.emailVerification?.sendOnSignUp){let q=await L(e.context.secret,d.email),B=`${e.context.baseURL}/verify-email?token=${q}&callbackURL=${o}`;await e.context.options.emailVerification?.sendVerificationEmail?.(k.user,B,q)}}catch(p){w.error("Unable to create user",p),g("unable_to_create_user")}b||g("unable_to_create_user");let x=await e.context.internalAdapter.createSession(b,e.request);throw x||g("unable_to_create_session"),await O(e,x.id),e.redirect(o)});import"zod";import{APIError as Lt}from"better-call";var Ne=m("/sign-out",{method:"POST"},async e=>{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!t)throw new Lt("BAD_REQUEST",{message:"Session not found"});return await e.context.internalAdapter.deleteSession(t),N(e),e.json({success:!0})});import{z as P}from"zod";import{APIError as G}from"better-call";var Me=m("/forget-password",{method:"POST",body:P.object({email:P.string().email(),redirectTo:P.string()}),use:[U]},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 G("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 n=60*60*1,i=new Date(Date.now()+1e3*(e.context.options.emailAndPassword.resetPasswordTokenExpiresIn||n)),s=e.context.uuid();await e.context.internalAdapter.createVerificationValue({value:o.user.id,identifier:`reset-password:${s}`,expiresAt:i});let a=`${e.context.baseURL}/reset-password/${s}?callbackURL=${r}`;return await e.context.options.emailAndPassword.sendResetPassword(o.user,a),e.json({status:!0})}),Fe=m("/reset-password/:token",{method:"GET",query:P.object({callbackURL:P.string()}),use:[U]},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 n=await e.context.internalAdapter.findVerificationValue(`reset-password:${t}`);throw!n||n.expiresAt<new Date?e.redirect(`${o}?error=INVALID_TOKEN`):e.redirect(`${o}?token=${t}`)}),He=m("/reset-password",{query:P.optional(P.object({token:P.string().optional(),currentURL:P.string().optional()})),method:"POST",body:P.object({newPassword:P.string()})},async e=>{let t=e.query?.token||(e.query?.currentURL?new URL(e.query.currentURL).searchParams.get("token"):"");if(!t)throw new G("BAD_REQUEST",{message:"Token not found"});let{newPassword:r}=e.body,o=`reset-password:${t}`,n=await e.context.internalAdapter.findVerificationValue(o);if(!n||n.expiresAt<new Date)throw new G("BAD_REQUEST",{message:"Invalid token"});await e.context.internalAdapter.deleteVerificationValue(n.id);let i=n.value,s=await e.context.password.hash(r);if(!(await e.context.internalAdapter.findAccounts(i)).find(l=>l.providerId==="credential"))return await e.context.internalAdapter.createAccount({userId:i,providerId:"credential",password:s,accountId:e.context.uuid()}),e.json({status:!0});if(!await e.context.internalAdapter.updatePassword(i,s))throw new G("BAD_REQUEST",{message:"Failed to update password"});return e.json({status:!0})});import{z as A}from"zod";import{APIError as R}from"better-call";var Ze=()=>m("/user/update",{method:"POST",body:A.record(A.string(),A.any()),use:[_,U]},async e=>{let t=e.body;if(t.email)throw new R("BAD_REQUEST",{message:"You can't update email"});let{name:r,image:o,...n}=t,i=e.context.session;if(!o&&!r&&Object.keys(n).length===0)return e.json({user:i.user});let s=ze(e.context.options,n),a=await e.context.internalAdapter.updateUserByEmail(i.user.email,{name:r,image:o,...s});return e.json({user:a})}),Qe=m("/user/change-password",{method:"POST",body:A.object({newPassword:A.string(),currentPassword:A.string(),revokeOtherSessions:A.boolean().optional()}),use:[_]},async e=>{let{newPassword:t,currentPassword:r,revokeOtherSessions:o}=e.body,n=e.context.session,i=e.context.password.config.minPasswordLength;if(t.length<i)throw e.context.logger.error("Password is too short"),new R("BAD_REQUEST",{message:"Password is too short"});let s=e.context.password.config.maxPasswordLength;if(t.length>s)throw e.context.logger.error("Password is too long"),new R("BAD_REQUEST",{message:"Password too long"});let c=(await e.context.internalAdapter.findAccounts(n.user.id)).find(h=>h.providerId==="credential"&&h.password);if(!c||!c.password)throw new R("BAD_REQUEST",{message:"User does not have a password"});let d=await e.context.password.hash(t);if(!await e.context.password.verify(c.password,r))throw new R("BAD_REQUEST",{message:"Incorrect password"});if(await e.context.internalAdapter.updateAccount(c.id,{password:d}),o){await e.context.internalAdapter.deleteSessions(n.user.id);let h=await e.context.internalAdapter.createSession(n.user.id,e.headers);if(!h)throw new R("INTERNAL_SERVER_ERROR",{message:"Unable to create session"});await O(e,h.id)}return e.json(n.user)}),Ge=m("/user/set-password",{method:"POST",body:A.object({newPassword:A.string()}),use:[_]},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 R("BAD_REQUEST",{message:"Password is too short"});let n=e.context.password.config.maxPasswordLength;if(t.length>n)throw e.context.logger.error("Password is too long"),new R("BAD_REQUEST",{message:"Password too long"});let s=(await e.context.internalAdapter.findAccounts(r.user.id)).find(c=>c.providerId==="credential"&&c.password),a=await e.context.password.hash(t);if(!s)return await e.context.internalAdapter.linkAccount({userId:r.user.id,providerId:"credential",accountId:r.user.id,password:a}),e.json(r.user);throw new R("BAD_REQUEST",{message:"user already has a password"})}),We=m("/user/delete",{method:"POST",body:A.object({password:A.string()}),use:[_]},async e=>{let{password:t}=e.body,r=e.context.session,n=(await e.context.internalAdapter.findAccounts(r.user.id)).find(a=>a.providerId==="credential"&&a.password);if(!n||!n.password)throw new R("BAD_REQUEST",{message:"User does not have a password"});if(!await e.context.password.verify(n.password,t))throw new R("BAD_REQUEST",{message:"Incorrect password"});await e.context.internalAdapter.deleteUser(r.user.id),await e.context.internalAdapter.deleteSessions(r.user.id);let s=e.context.authCookies.sessionToken;return e.setCookie(s.name,"",{maxAge:0}),e.json(null)}),Je=m("/user/change-email",{method:"POST",query:A.object({currentURL:A.string().optional()}).optional(),body:A.object({newEmail:A.string().email(),callbackURL:A.string().optional()}),use:[_,U]},async e=>{if(!e.context.options.user?.changeEmail?.enabled)throw e.context.logger.error("Change email is disabled."),new R("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 R("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 R("BAD_REQUEST",{message:"Couldn't update your email"});if(e.context.session.user.emailVerified!==!0){let n=await e.context.internalAdapter.updateUserByEmail(e.context.session.user.email,{email:e.body.newEmail});return e.json({user:n,status:!0})}if(!e.context.options.user.changeEmail.sendChangeEmailVerification)throw e.context.logger.error("Verification email isn't enabled."),new R("BAD_REQUEST",{message:"Verification email isn't enabled"});let r=await L(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.user.changeEmail.sendChangeEmailVerification(e.context.session.user,e.body.newEmail,o,r),e.json({user:null,status:!0})});var Ke=m("/csrf",{method:"GET",metadata:C},async e=>{let t=await e.getSignedCookie(e.context.authCookies.csrfToken.name,e.context.secret);if(t){let[i,s]=t.split("!")||[null,null];return e.json({csrfToken:i})}let r=oe(32,ne("a-z","0-9","A-Z")),o=await F(e.context.secret,r),n=`${r}!${o}`;return await e.setSignedCookie(e.context.authCookies.csrfToken.name,n,e.context.secret,e.context.authCookies.csrfToken.options),e.json({csrfToken:r})});var It=(e="Unknown")=>`<!DOCTYPE html>
|
|
4
4
|
<html lang="en">
|