faire-auth 1.0.3 → 1.1.0
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/{adapter-factory-lKIOf2OR.mjs → adapter-factory-qPVW8x9-.mjs} +34 -36
- package/dist/{adapter-factory-D1I7joki.cjs → adapter-factory-u8r3oTez.cjs} +66 -68
- package/dist/adapters/drizzle-adapter/index.cjs +34 -40
- package/dist/adapters/drizzle-adapter/index.d.cts +4 -9
- package/dist/adapters/drizzle-adapter/index.d.mts +4 -9
- package/dist/adapters/drizzle-adapter/index.mjs +20 -26
- package/dist/adapters/index.cjs +11 -16
- package/dist/adapters/index.d.cts +11 -37
- package/dist/adapters/index.d.mts +11 -37
- package/dist/adapters/index.mjs +4 -13
- package/dist/adapters/kysely-adapter/index.cjs +270 -11
- package/dist/adapters/kysely-adapter/index.d.cts +9 -19
- package/dist/adapters/kysely-adapter/index.d.mts +9 -19
- package/dist/adapters/kysely-adapter/index.mjs +267 -9
- package/dist/adapters/memory-adapter/index.cjs +146 -9
- package/dist/adapters/memory-adapter/index.d.cts +4 -10
- package/dist/adapters/memory-adapter/index.d.mts +4 -10
- package/dist/adapters/memory-adapter/index.mjs +145 -9
- package/dist/adapters/mongodb-adapter/index.cjs +13 -21
- package/dist/adapters/mongodb-adapter/index.d.cts +3 -8
- package/dist/adapters/mongodb-adapter/index.d.mts +4 -9
- package/dist/adapters/mongodb-adapter/index.mjs +12 -20
- package/dist/adapters/prisma-adapter/index.cjs +12 -20
- package/dist/adapters/prisma-adapter/index.d.cts +4 -8
- package/dist/adapters/prisma-adapter/index.d.mts +4 -8
- package/dist/adapters/prisma-adapter/index.mjs +5 -13
- package/dist/adapters/test.cjs +86 -69
- package/dist/adapters/test.d.cts +7 -11
- package/dist/adapters/test.d.mts +7 -11
- package/dist/adapters/test.mjs +83 -66
- package/dist/api/index.cjs +3 -20
- package/dist/api/index.d.cts +2 -3
- package/dist/api/index.d.mts +2 -3
- package/dist/api/index.mjs +1 -20
- package/dist/api/middleware/index.cjs +4 -11
- package/dist/api/middleware/index.d.cts +3 -9
- package/dist/api/middleware/index.d.mts +3 -9
- package/dist/api/middleware/index.mjs +3 -11
- package/dist/{api-B4RDwBty.mjs → api-0f-F-Fi2.mjs} +292 -189
- package/dist/{api-CaRC1Gio.cjs → api-LjfH6hQi.cjs} +557 -452
- package/dist/{test-utils/bun-sqlite-dialect-BZBvHchL.cjs → bun-sqlite-dialect-BHkarnxN.cjs} +5 -9
- package/dist/{test-utils/bun-sqlite-dialect-BSWhhKNs.mjs → bun-sqlite-dialect-BiZBuEF6.mjs} +6 -9
- package/dist/client/index.cjs +8 -15
- package/dist/client/index.d.cts +9 -14
- package/dist/client/index.d.mts +9 -14
- package/dist/client/index.mjs +7 -15
- package/dist/client/lynx/index.cjs +10 -18
- package/dist/client/lynx/index.d.cts +402 -71
- package/dist/client/lynx/index.d.mts +402 -71
- package/dist/client/lynx/index.mjs +5 -13
- package/dist/client/plugins/index.cjs +3 -5
- package/dist/client/plugins/index.d.cts +5 -10
- package/dist/client/plugins/index.d.mts +5 -10
- package/dist/client/plugins/index.mjs +2 -4
- package/dist/client/react/index.cjs +6 -14
- package/dist/client/react/index.d.cts +402 -71
- package/dist/client/react/index.d.mts +402 -71
- package/dist/client/react/index.mjs +5 -13
- package/dist/client/solid/index.cjs +6 -14
- package/dist/client/solid/index.d.cts +393 -57
- package/dist/client/solid/index.d.mts +393 -57
- package/dist/client/solid/index.mjs +5 -13
- package/dist/client/svelte/index.cjs +5 -10
- package/dist/client/svelte/index.d.cts +400 -67
- package/dist/client/svelte/index.d.mts +400 -67
- package/dist/client/svelte/index.mjs +4 -10
- package/dist/client/vue/index.cjs +6 -14
- package/dist/client/vue/index.d.cts +401 -68
- package/dist/client/vue/index.d.mts +401 -68
- package/dist/client/vue/index.mjs +5 -13
- package/dist/{cookies-BTs1o992.mjs → cookies-D9aY_gJh.mjs} +25 -21
- package/dist/{cookies-BTl72THv.cjs → cookies-DQ52rcOy.cjs} +119 -115
- package/dist/crypto/index.cjs +10 -8
- package/dist/crypto/index.d.cts +5 -13
- package/dist/crypto/index.d.mts +5 -13
- package/dist/crypto/index.mjs +2 -5
- package/dist/{crypto-DH2Aa7jN.mjs → crypto-BH-hD0lJ.mjs} +7 -10
- package/dist/{crypto-DpSCnrTp.cjs → crypto-BITfWVwD.cjs} +24 -27
- package/dist/db/index.cjs +1135 -29
- package/dist/db/index.d.cts +1 -2
- package/dist/db/index.d.mts +1 -2
- package/dist/db/index.mjs +1115 -16
- package/dist/defu-D2h4S3X-.mjs +87 -0
- package/dist/defu-DWS5RPWt.cjs +134 -0
- package/dist/{email-verification-DI_0H4JC.cjs → email-verification-DOPnSgbI.cjs} +65 -71
- package/dist/{email-verification-C_lBu_JY.mjs → email-verification-YSR5n5lb.mjs} +23 -29
- package/dist/{hono-CO-zsqI-.mjs → hono-BAV2wQkK.mjs} +16 -33
- package/dist/hono-SVQuc5Ru.mjs +4 -0
- package/dist/hono-pgK4H_U1.cjs +9 -0
- package/dist/{hono-DnW5crl1.cjs → hono-tyFFJFdS.cjs} +42 -60
- package/dist/index-B86Cy0dE.d.cts +2 -0
- package/dist/index-B86Cy0dE.d.mts +2 -0
- package/dist/index.cjs +115 -150
- package/dist/index.d.cts +4 -5
- package/dist/index.d.mts +4 -5
- package/dist/index.mjs +46 -81
- package/dist/integrations/next-js.cjs +5 -9
- package/dist/integrations/next-js.d.cts +6 -14
- package/dist/integrations/next-js.d.mts +6 -14
- package/dist/integrations/next-js.mjs +4 -9
- package/dist/integrations/node.cjs +16 -14
- package/dist/integrations/node.d.cts +6 -14
- package/dist/integrations/node.d.mts +6 -14
- package/dist/integrations/node.mjs +15 -13
- package/dist/integrations/react-start.cjs +7 -11
- package/dist/integrations/react-start.d.cts +5 -13
- package/dist/integrations/react-start.d.mts +5 -13
- package/dist/integrations/react-start.mjs +6 -11
- package/dist/integrations/solid-start.cjs +3 -5
- package/dist/integrations/solid-start.d.cts +2 -5
- package/dist/integrations/solid-start.d.mts +2 -5
- package/dist/integrations/solid-start.mjs +2 -4
- package/dist/integrations/svelte-kit.cjs +6 -10
- package/dist/integrations/svelte-kit.d.cts +11 -23
- package/dist/integrations/svelte-kit.d.mts +11 -23
- package/dist/integrations/svelte-kit.mjs +5 -10
- package/dist/{ip-BjNYspCH.mjs → ip-6Lv2o42m.mjs} +4 -9
- package/dist/{ip-C17Qdq-G.cjs → ip-DPydExzV.cjs} +21 -27
- package/dist/{json--tl7Grvs.cjs → json-D3aq-nH2.cjs} +9 -13
- package/dist/{json-B1v2qRTQ.mjs → json-DooGMtnJ.mjs} +2 -5
- package/dist/{logged-CyGfp8_H.mjs → logged-B83SzMnJ.mjs} +6 -10
- package/dist/{logged-Dv3st5qc.cjs → logged-BIpCpnVY.cjs} +13 -18
- package/dist/{middleware-CE6OhDkq.mjs → middleware-Cakg4e1D.mjs} +2 -4
- package/dist/{middleware-CWvRH4EW.cjs → middleware-Cd-VkNxB.cjs} +17 -20
- package/dist/{node-sqlite-dialect-w4DAg0PH.mjs → node-sqlite-dialect-BMVOjEMh.mjs} +6 -9
- package/dist/{test-utils/node-sqlite-dialect-BgJqjBOu.cjs → node-sqlite-dialect-D3QPFROH.cjs} +5 -9
- package/dist/oauth2/index.cjs +166 -22
- package/dist/oauth2/index.d.cts +5 -17
- package/dist/oauth2/index.d.mts +5 -17
- package/dist/oauth2/index.mjs +156 -16
- package/dist/{origin-check-DjLTuZQ8.cjs → origin-check-BflGhEEN.cjs} +34 -38
- package/dist/{origin-check-8Gajklvh.mjs → origin-check-CRgs1M7k.mjs} +13 -16
- package/dist/{parser-B25ylT5u.mjs → parser-CqwvpF6l.cjs} +12 -10
- package/dist/{parser-B_wxvaAr.cjs → parser-DcKDjjHO.mjs} +7 -22
- package/dist/plugins/access/index.cjs +38 -4
- package/dist/plugins/access/index.d.cts +36 -2
- package/dist/plugins/access/index.d.mts +36 -2
- package/dist/plugins/access/index.mjs +36 -3
- package/dist/plugins/bearer/index.cjs +52 -7
- package/dist/plugins/bearer/index.d.cts +27 -4
- package/dist/plugins/bearer/index.d.mts +27 -4
- package/dist/plugins/bearer/index.mjs +51 -7
- package/dist/plugins/index.cjs +1385 -842
- package/dist/plugins/index.d.cts +489 -7566
- package/dist/plugins/index.d.mts +489 -7566
- package/dist/plugins/index.mjs +1118 -576
- package/dist/plugins/passkey/index.cjs +551 -15
- package/dist/plugins/passkey/index.d.cts +123 -4
- package/dist/plugins/passkey/index.d.mts +123 -4
- package/dist/plugins/passkey/index.mjs +547 -15
- package/dist/{chunk-BFnQceUY.mjs → rolldown-runtime-BKpuH2hG.mjs} +6 -7
- package/dist/{chunk-fPmz2rbM.cjs → rolldown-runtime-C_Pgydhf.cjs} +22 -24
- package/dist/{schema-DTIwLLmf.mjs → schema-CFCpv0tK.mjs} +3 -6
- package/dist/{schema-CirKflVs.cjs → schema-b-lKhMkG.cjs} +51 -55
- package/dist/{session-CM3rmOYF.mjs → session-BGjJgihS.mjs} +51 -74
- package/dist/{session-Cwrj4GfV.cjs → session-CzZSMmQC.cjs} +197 -219
- package/dist/shared.d.cts +1581 -0
- package/dist/shared.d.mts +1581 -0
- package/dist/social-providers/index.cjs +9 -9
- package/dist/social-providers/index.d.cts +1 -1
- package/dist/social-providers/index.d.mts +1 -1
- package/dist/social-providers/index.mjs +3 -5
- package/dist/social-providers-CjPww-qf.mjs +6 -0
- package/dist/social-providers-D7w_7Ym8.cjs +10 -0
- package/dist/{state-CvSihlVT.cjs → state-2OrNjOO-.cjs} +24 -24
- package/dist/{state-CQghgH9I.mjs → state-Dooeisfq.mjs} +17 -17
- package/dist/{bun-sqlite-dialect-DPgTzc0w.cjs → test-utils/bun-sqlite-dialect-BHkarnxN.cjs} +5 -9
- package/dist/{bun-sqlite-dialect-6NqeV3px.mjs → test-utils/bun-sqlite-dialect-BiZBuEF6.mjs} +6 -9
- package/dist/test-utils/index.cjs +8831 -7941
- package/dist/test-utils/index.d.cts +310 -12440
- package/dist/test-utils/index.d.mts +313 -12440
- package/dist/test-utils/index.mjs +8591 -7701
- package/dist/test-utils/{node-sqlite-dialect-DAQXiobH.mjs → node-sqlite-dialect-BMVOjEMh.mjs} +6 -9
- package/dist/{node-sqlite-dialect-DP11CB0y.cjs → test-utils/node-sqlite-dialect-D3QPFROH.cjs} +5 -9
- package/dist/types/index.d.cts +2 -3
- package/dist/types/index.d.mts +2 -3
- package/dist/types/index.mjs +1 -1
- package/dist/{url-BoUuoIwZ.mjs → url-CJtdrrUu.mjs} +12 -13
- package/dist/{url-Ce7CVaQD.cjs → url-DjCmCUHS.cjs} +42 -44
- package/dist/utils/cookies.cjs +29 -30
- package/dist/utils/cookies.d.cts +21 -25
- package/dist/utils/cookies.d.mts +20 -24
- package/dist/utils/cookies.mjs +2 -7
- package/dist/utils-C7OHyfHa.mjs +4 -0
- package/dist/utils-iX0Vy_UL.cjs +3 -0
- package/package.json +40 -30
- package/dist/access-BZ7-AbTM.cjs +0 -51
- package/dist/access-D0DRqUKC.mjs +0 -39
- package/dist/bearer-DDzrp5M7.cjs +0 -60
- package/dist/bearer-WZcs7gxL.mjs +0 -54
- package/dist/db-4tUsQJXd.mjs +0 -1119
- package/dist/db-ChMbb_U-.cjs +0 -1180
- package/dist/defu-BmOYq4PU.cjs +0 -34
- package/dist/defu-D9ZTXqlo.mjs +0 -28
- package/dist/hono-C14rpOEa.cjs +0 -13
- package/dist/hono-CoKYWnXA.mjs +0 -7
- package/dist/hono-D0VqxVy1.d.mts +0 -18
- package/dist/hono-DOM31WQz.d.cts +0 -18
- package/dist/index-BCTFWP_o.d.mts +0 -992
- package/dist/index-BDhhaE6Y.d.cts +0 -3
- package/dist/index-BVRfQy6L.d.mts +0 -992
- package/dist/index-Baarsq5J.d.mts +0 -33
- package/dist/index-By364WbF.d.cts +0 -992
- package/dist/index-BzWwMgxr.d.cts +0 -992
- package/dist/index-CF9iq55a.d.mts +0 -3
- package/dist/index-CJD2yB-W.d.cts +0 -33
- package/dist/index-CRt_fppq.d.mts +0 -41
- package/dist/index-CdLyn7qP.d.cts +0 -41
- package/dist/index-CsWF3f7U.d.cts +0 -13350
- package/dist/index-CzidsAyA.d.mts +0 -13350
- package/dist/index-DvW-GCcI.d.cts +0 -33
- package/dist/index-f-5OJ9yV.d.cts +0 -13350
- package/dist/index-rFv8Hxld.d.mts +0 -13350
- package/dist/index-ztVZPQdV.d.mts +0 -33
- package/dist/kysely-adapter-CtIdoHa8.mjs +0 -270
- package/dist/kysely-adapter-QZTx077T.cjs +0 -288
- package/dist/memory-adapter-17RZd5df.cjs +0 -154
- package/dist/memory-adapter-Dp4XdCZK.mjs +0 -148
- package/dist/oauth2-5RL4cVNS.cjs +0 -177
- package/dist/oauth2-C56wz-n9.mjs +0 -159
- package/dist/passkey-BTT-v5c-.cjs +0 -512
- package/dist/passkey-CzY_W2us.mjs +0 -505
- package/dist/request-1NL_1lyJ.mjs +0 -58
- package/dist/request-CPNlp-DK.cjs +0 -100
- package/dist/social-providers-B8RK5yqI.mjs +0 -9
- package/dist/social-providers-BmFOIIPk.cjs +0 -13
- package/dist/utils-44aDDP8f.cjs +0 -2
- package/dist/utils-D4vZd1-9.mjs +0 -4
package/dist/db/index.cjs
CHANGED
|
@@ -1,26 +1,1130 @@
|
|
|
1
|
-
|
|
2
|
-
require(
|
|
3
|
-
require(
|
|
4
|
-
require(
|
|
5
|
-
require(
|
|
6
|
-
require(
|
|
7
|
-
require(
|
|
8
|
-
const
|
|
9
|
-
require(
|
|
10
|
-
const
|
|
11
|
-
|
|
12
|
-
require(
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
+
const require_rolldown_runtime = require("../rolldown-runtime-C_Pgydhf.cjs");
|
|
3
|
+
const require_adapters_kysely_adapter_index = require("../adapters/kysely-adapter/index.cjs");
|
|
4
|
+
const require_adapter_factory = require("../adapter-factory-u8r3oTez.cjs");
|
|
5
|
+
const require_hono = require("../hono-pgK4H_U1.cjs");
|
|
6
|
+
const require_ip = require("../ip-DPydExzV.cjs");
|
|
7
|
+
require("../utils-iX0Vy_UL.cjs");
|
|
8
|
+
const require_json = require("../json-D3aq-nH2.cjs");
|
|
9
|
+
const require_schema = require("../schema-b-lKhMkG.cjs");
|
|
10
|
+
const require_adapters_memory_adapter_index = require("../adapters/memory-adapter/index.cjs");
|
|
11
|
+
let _faire_auth_core_env = require("@faire-auth/core/env");
|
|
12
|
+
let _faire_auth_core_error = require("@faire-auth/core/error");
|
|
13
|
+
let _faire_auth_core_static = require("@faire-auth/core/static");
|
|
14
|
+
let _faire_auth_core_utils = require("@faire-auth/core/utils");
|
|
15
|
+
let zod = require("zod");
|
|
16
|
+
zod = require_rolldown_runtime.__toESM(zod, 1);
|
|
17
|
+
let kysely = require("kysely");
|
|
18
|
+
let _faire_auth_core_crypto = require("@faire-auth/core/crypto");
|
|
19
|
+
// src/db/field.ts
|
|
20
|
+
const createFieldAttribute = (type, config) => {
|
|
21
|
+
return {
|
|
22
|
+
type,
|
|
23
|
+
...config
|
|
24
|
+
};
|
|
25
|
+
};
|
|
26
|
+
// src/db/get-schema.ts
|
|
27
|
+
function getSchema(config) {
|
|
28
|
+
const tables = require_adapter_factory.getAuthTables(config);
|
|
29
|
+
let schema = {};
|
|
30
|
+
for (const key in tables) {
|
|
31
|
+
const table = tables[key];
|
|
32
|
+
const fields = table.fields;
|
|
33
|
+
let actualFields = {};
|
|
34
|
+
Object.entries(fields).forEach(([key, field]) => {
|
|
35
|
+
actualFields[field.fieldName || key] = field;
|
|
36
|
+
if (field.references) {
|
|
37
|
+
const refTable = tables[field.references.model];
|
|
38
|
+
if (refTable) actualFields[field.fieldName || key].references = {
|
|
39
|
+
...field.references,
|
|
40
|
+
model: refTable.modelName,
|
|
41
|
+
field: field.references.field
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
});
|
|
45
|
+
if (schema[table.modelName]) {
|
|
46
|
+
schema[table.modelName].fields = {
|
|
47
|
+
...schema[table.modelName].fields,
|
|
48
|
+
...actualFields
|
|
49
|
+
};
|
|
50
|
+
continue;
|
|
51
|
+
}
|
|
52
|
+
schema[table.modelName] = {
|
|
53
|
+
fields: actualFields,
|
|
54
|
+
order: table.order || Infinity
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
return schema;
|
|
58
|
+
}
|
|
59
|
+
// src/db/get-migration.ts
|
|
60
|
+
const map = {
|
|
61
|
+
postgres: {
|
|
62
|
+
string: [
|
|
63
|
+
"character varying",
|
|
64
|
+
"varchar",
|
|
65
|
+
"text"
|
|
66
|
+
],
|
|
67
|
+
number: [
|
|
68
|
+
"int4",
|
|
69
|
+
"integer",
|
|
70
|
+
"bigint",
|
|
71
|
+
"smallint",
|
|
72
|
+
"numeric",
|
|
73
|
+
"real",
|
|
74
|
+
"double precision"
|
|
75
|
+
],
|
|
76
|
+
boolean: ["bool", "boolean"],
|
|
77
|
+
date: [
|
|
78
|
+
"timestamptz",
|
|
79
|
+
"timestamp",
|
|
80
|
+
"date"
|
|
81
|
+
],
|
|
82
|
+
json: ["json", "jsonb"]
|
|
83
|
+
},
|
|
84
|
+
mysql: {
|
|
85
|
+
string: ["varchar", "text"],
|
|
86
|
+
number: [
|
|
87
|
+
"integer",
|
|
88
|
+
"int",
|
|
89
|
+
"bigint",
|
|
90
|
+
"smallint",
|
|
91
|
+
"decimal",
|
|
92
|
+
"float",
|
|
93
|
+
"double"
|
|
94
|
+
],
|
|
95
|
+
boolean: ["boolean", "tinyint"],
|
|
96
|
+
date: [
|
|
97
|
+
"timestamp",
|
|
98
|
+
"datetime",
|
|
99
|
+
"date"
|
|
100
|
+
],
|
|
101
|
+
json: ["json"]
|
|
102
|
+
},
|
|
103
|
+
sqlite: {
|
|
104
|
+
string: ["TEXT"],
|
|
105
|
+
number: ["INTEGER", "REAL"],
|
|
106
|
+
boolean: ["INTEGER", "BOOLEAN"],
|
|
107
|
+
date: ["DATE", "INTEGER"],
|
|
108
|
+
json: ["TEXT"]
|
|
109
|
+
},
|
|
110
|
+
mssql: {
|
|
111
|
+
string: ["varchar", "nvarchar"],
|
|
112
|
+
number: [
|
|
113
|
+
"int",
|
|
114
|
+
"bigint",
|
|
115
|
+
"smallint",
|
|
116
|
+
"decimal",
|
|
117
|
+
"float",
|
|
118
|
+
"double"
|
|
119
|
+
],
|
|
120
|
+
boolean: ["bit", "smallint"],
|
|
121
|
+
date: [
|
|
122
|
+
"datetime2",
|
|
123
|
+
"date",
|
|
124
|
+
"datetime"
|
|
125
|
+
],
|
|
126
|
+
json: ["varchar", "nvarchar"]
|
|
127
|
+
}
|
|
128
|
+
};
|
|
129
|
+
function matchType(columnDataType, fieldType, dbType) {
|
|
130
|
+
function normalize(type) {
|
|
131
|
+
return type.toLowerCase().split("(")[0].trim();
|
|
132
|
+
}
|
|
133
|
+
if (fieldType === "string[]" || fieldType === "number[]") return columnDataType.toLowerCase().includes("json");
|
|
134
|
+
const types = map[dbType];
|
|
135
|
+
return (Array.isArray(fieldType) ? types["string"].map((t) => t.toLowerCase()) : types[fieldType].map((t) => t.toLowerCase())).includes(normalize(columnDataType));
|
|
136
|
+
}
|
|
137
|
+
/**
|
|
138
|
+
* Get the current PostgreSQL schema (search_path) for the database connection
|
|
139
|
+
* Returns the first schema in the search_path, defaulting to 'public' if not found
|
|
140
|
+
*/
|
|
141
|
+
async function getPostgresSchema(db) {
|
|
142
|
+
try {
|
|
143
|
+
const result = await kysely.sql`SHOW search_path`.execute(db);
|
|
144
|
+
if (result.rows[0]?.search_path) return result.rows[0].search_path.split(",").map((s) => s.trim()).map((s) => s.replace(/^["']|["']$/g, "")).filter((s) => !s.startsWith("$"))[0] || "public";
|
|
145
|
+
} catch (error) {}
|
|
146
|
+
return "public";
|
|
147
|
+
}
|
|
148
|
+
async function getMigrations(config) {
|
|
149
|
+
const betterAuthSchema = getSchema(config);
|
|
150
|
+
const logger = (0, _faire_auth_core_env.createLogger)(config.logger);
|
|
151
|
+
const adapter = require_adapters_kysely_adapter_index.createKyselyAdapter(config);
|
|
152
|
+
if ("initialize" in adapter) await adapter.initialize();
|
|
153
|
+
let { kysely: db, databaseType: dbType } = adapter;
|
|
154
|
+
if (!dbType) {
|
|
155
|
+
logger.warn("Could not determine database type, defaulting to sqlite. Please provide a type in the database options to avoid this.");
|
|
156
|
+
dbType = "sqlite";
|
|
157
|
+
}
|
|
158
|
+
if (!db) {
|
|
159
|
+
logger.error("Only kysely adapter is supported for migrations. You can use `generate` command to generate the schema, if you're using a different adapter.");
|
|
160
|
+
process.exit(1);
|
|
161
|
+
}
|
|
162
|
+
let currentSchema = "public";
|
|
163
|
+
if (dbType === "postgres") {
|
|
164
|
+
currentSchema = await getPostgresSchema(db);
|
|
165
|
+
logger.debug(`PostgreSQL migration: Using schema '${currentSchema}' (from search_path)`);
|
|
166
|
+
try {
|
|
167
|
+
if (!(await kysely.sql`
|
|
168
|
+
SELECT schema_name
|
|
169
|
+
FROM information_schema.schemata
|
|
170
|
+
WHERE schema_name = ${currentSchema}
|
|
171
|
+
`.execute(db)).rows[0]) logger.warn(`Schema '${currentSchema}' does not exist. Tables will be inspected from available schemas. Consider creating the schema first or checking your database configuration.`);
|
|
172
|
+
} catch (error) {
|
|
173
|
+
logger.debug(`Could not verify schema existence: ${error instanceof Error ? error.message : String(error)}`);
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
const allTableMetadata = await db.introspection.getTables();
|
|
177
|
+
let tableMetadata = allTableMetadata;
|
|
178
|
+
if (dbType === "postgres") try {
|
|
179
|
+
const tablesInSchema = await kysely.sql`
|
|
180
|
+
SELECT table_name
|
|
181
|
+
FROM information_schema.tables
|
|
182
|
+
WHERE table_schema = ${currentSchema}
|
|
183
|
+
AND table_type = 'BASE TABLE'
|
|
184
|
+
`.execute(db);
|
|
185
|
+
const tableNamesInSchema = new Set(tablesInSchema.rows.map((row) => row.table_name));
|
|
186
|
+
tableMetadata = allTableMetadata.filter((table) => table.schema === currentSchema && tableNamesInSchema.has(table.name));
|
|
187
|
+
logger.debug(`Found ${tableMetadata.length} table(s) in schema '${currentSchema}': ${tableMetadata.map((t) => t.name).join(", ") || "(none)"}`);
|
|
188
|
+
} catch (error) {
|
|
189
|
+
logger.warn(`Could not filter tables by schema. Using all discovered tables. Error: ${error instanceof Error ? error.message : String(error)}`);
|
|
190
|
+
}
|
|
191
|
+
const toBeCreated = [];
|
|
192
|
+
const toBeAdded = [];
|
|
193
|
+
for (const [key, value] of Object.entries(betterAuthSchema)) {
|
|
194
|
+
const table = tableMetadata.find((t) => t.name === key);
|
|
195
|
+
if (!table) {
|
|
196
|
+
const tIndex = toBeCreated.findIndex((t) => t.table === key);
|
|
197
|
+
const tableData = {
|
|
198
|
+
table: key,
|
|
199
|
+
fields: value.fields,
|
|
200
|
+
order: value.order || Infinity
|
|
201
|
+
};
|
|
202
|
+
const insertIndex = toBeCreated.findIndex((t) => (t.order || Infinity) > tableData.order);
|
|
203
|
+
if (insertIndex === -1) {
|
|
204
|
+
if (tIndex === -1) toBeCreated.push(tableData);
|
|
205
|
+
else toBeCreated[tIndex].fields = {
|
|
206
|
+
...toBeCreated[tIndex].fields,
|
|
207
|
+
...value.fields
|
|
208
|
+
};
|
|
209
|
+
} else toBeCreated.splice(insertIndex, 0, tableData);
|
|
210
|
+
continue;
|
|
211
|
+
}
|
|
212
|
+
let toBeAddedFields = {};
|
|
213
|
+
for (const [fieldName, field] of Object.entries(value.fields)) {
|
|
214
|
+
const column = table.columns.find((c) => c.name === fieldName);
|
|
215
|
+
if (!column) {
|
|
216
|
+
toBeAddedFields[fieldName] = field;
|
|
217
|
+
continue;
|
|
218
|
+
}
|
|
219
|
+
if (matchType(column.dataType, field.type, dbType)) continue;
|
|
220
|
+
else logger.warn(`Field ${fieldName} in table ${key} has a different type in the database. Expected ${field.type} but got ${column.dataType}.`);
|
|
221
|
+
}
|
|
222
|
+
if (Object.keys(toBeAddedFields).length > 0) toBeAdded.push({
|
|
223
|
+
table: key,
|
|
224
|
+
fields: toBeAddedFields,
|
|
225
|
+
order: value.order || Infinity
|
|
226
|
+
});
|
|
227
|
+
}
|
|
228
|
+
const migrations = [];
|
|
229
|
+
function getType(field, fieldName) {
|
|
230
|
+
const type = field.type;
|
|
231
|
+
const typeMap = {
|
|
232
|
+
string: {
|
|
233
|
+
sqlite: "text",
|
|
234
|
+
postgres: "text",
|
|
235
|
+
mysql: field.unique ? "varchar(255)" : field.references ? "varchar(36)" : "text",
|
|
236
|
+
mssql: field.unique || field.sortable ? "varchar(255)" : field.references ? "varchar(36)" : "varchar(8000)"
|
|
237
|
+
},
|
|
238
|
+
boolean: {
|
|
239
|
+
sqlite: "integer",
|
|
240
|
+
postgres: "boolean",
|
|
241
|
+
mysql: "boolean",
|
|
242
|
+
mssql: "smallint"
|
|
243
|
+
},
|
|
244
|
+
number: {
|
|
245
|
+
sqlite: field.bigint ? "bigint" : "integer",
|
|
246
|
+
postgres: field.bigint ? "bigint" : "integer",
|
|
247
|
+
mysql: field.bigint ? "bigint" : "integer",
|
|
248
|
+
mssql: field.bigint ? "bigint" : "integer"
|
|
249
|
+
},
|
|
250
|
+
date: {
|
|
251
|
+
sqlite: "date",
|
|
252
|
+
postgres: "timestamptz",
|
|
253
|
+
mysql: "timestamp(3)",
|
|
254
|
+
mssql: kysely.sql`datetime2(3)`
|
|
255
|
+
},
|
|
256
|
+
json: {
|
|
257
|
+
sqlite: "text",
|
|
258
|
+
postgres: "jsonb",
|
|
259
|
+
mysql: "json",
|
|
260
|
+
mssql: "varchar(8000)"
|
|
261
|
+
},
|
|
262
|
+
id: {
|
|
263
|
+
postgres: config.advanced?.database?.useNumberId ? "serial" : "text",
|
|
264
|
+
mysql: config.advanced?.database?.useNumberId ? "integer" : "varchar(36)",
|
|
265
|
+
mssql: config.advanced?.database?.useNumberId ? "integer" : "varchar(36)",
|
|
266
|
+
sqlite: config.advanced?.database?.useNumberId ? "integer" : "text"
|
|
267
|
+
},
|
|
268
|
+
foreignKeyId: {
|
|
269
|
+
postgres: config.advanced?.database?.useNumberId ? "integer" : "text",
|
|
270
|
+
mysql: config.advanced?.database?.useNumberId ? "integer" : "varchar(36)",
|
|
271
|
+
mssql: config.advanced?.database?.useNumberId ? "integer" : "varchar(36)",
|
|
272
|
+
sqlite: config.advanced?.database?.useNumberId ? "integer" : "text"
|
|
273
|
+
}
|
|
274
|
+
};
|
|
275
|
+
if (fieldName === "id" || field.references?.field === "id") {
|
|
276
|
+
if (fieldName === "id") return typeMap.id[dbType];
|
|
277
|
+
return typeMap.foreignKeyId[dbType];
|
|
278
|
+
}
|
|
279
|
+
if (dbType === "sqlite" && (type === "string[]" || type === "number[]")) return "text";
|
|
280
|
+
if (type === "string[]" || type === "number[]") return "jsonb";
|
|
281
|
+
if (Array.isArray(type)) return "text";
|
|
282
|
+
return typeMap[type][dbType || "sqlite"];
|
|
283
|
+
}
|
|
284
|
+
if (toBeAdded.length) for (const table of toBeAdded) for (const [fieldName, field] of Object.entries(table.fields)) {
|
|
285
|
+
const type = getType(field, fieldName);
|
|
286
|
+
const exec = db.schema.alterTable(table.table).addColumn(fieldName, type, (col) => {
|
|
287
|
+
col = field.required !== false ? col.notNull() : col;
|
|
288
|
+
if (field.references) col = col.references(`${field.references.model}.${field.references.field}`).onDelete(field.references.onDelete || "cascade");
|
|
289
|
+
if (field.unique) col = col.unique();
|
|
290
|
+
if (field.type === "date" && typeof field.defaultValue === "function" && (dbType === "postgres" || dbType === "mysql" || dbType === "mssql")) {
|
|
291
|
+
if (dbType === "mysql") col = col.defaultTo(kysely.sql`CURRENT_TIMESTAMP(3)`);
|
|
292
|
+
else col = col.defaultTo(kysely.sql`CURRENT_TIMESTAMP`);
|
|
293
|
+
}
|
|
294
|
+
return col;
|
|
295
|
+
});
|
|
296
|
+
migrations.push(exec);
|
|
297
|
+
}
|
|
298
|
+
if (toBeCreated.length) for (const table of toBeCreated) {
|
|
299
|
+
let dbT = db.schema.createTable(table.table).addColumn("id", config.advanced?.database?.useNumberId ? dbType === "postgres" ? "serial" : "integer" : dbType === "mysql" || dbType === "mssql" ? "varchar(36)" : "text", (col) => {
|
|
300
|
+
if (config.advanced?.database?.useNumberId) {
|
|
301
|
+
if (dbType === "postgres" || dbType === "sqlite") return col.primaryKey().notNull();
|
|
302
|
+
else if (dbType === "mssql") return col.identity().primaryKey().notNull();
|
|
303
|
+
return col.autoIncrement().primaryKey().notNull();
|
|
304
|
+
}
|
|
305
|
+
return col.primaryKey().notNull();
|
|
306
|
+
});
|
|
307
|
+
for (const [fieldName, field] of Object.entries(table.fields)) {
|
|
308
|
+
const type = getType(field, fieldName);
|
|
309
|
+
dbT = dbT.addColumn(fieldName, type, (col) => {
|
|
310
|
+
col = field.required !== false ? col.notNull() : col;
|
|
311
|
+
if (field.references) col = col.references(`${field.references.model}.${field.references.field}`).onDelete(field.references.onDelete || "cascade");
|
|
312
|
+
if (field.unique) col = col.unique();
|
|
313
|
+
if (field.type === "date" && typeof field.defaultValue === "function" && (dbType === "postgres" || dbType === "mysql" || dbType === "mssql")) {
|
|
314
|
+
if (dbType === "mysql") col = col.defaultTo(kysely.sql`CURRENT_TIMESTAMP(3)`);
|
|
315
|
+
else col = col.defaultTo(kysely.sql`CURRENT_TIMESTAMP`);
|
|
316
|
+
}
|
|
317
|
+
return col;
|
|
318
|
+
});
|
|
319
|
+
}
|
|
320
|
+
migrations.push(dbT);
|
|
321
|
+
}
|
|
322
|
+
async function runMigrations() {
|
|
323
|
+
for (const migration of migrations) await migration.execute();
|
|
324
|
+
}
|
|
325
|
+
async function compileMigrations() {
|
|
326
|
+
return migrations.map((m) => m.compile().sql).join(";\n\n") + ";";
|
|
327
|
+
}
|
|
328
|
+
return {
|
|
329
|
+
toBeCreated,
|
|
330
|
+
toBeAdded,
|
|
331
|
+
runMigrations,
|
|
332
|
+
compileMigrations
|
|
333
|
+
};
|
|
334
|
+
}
|
|
335
|
+
// src/db/with-hooks.ts
|
|
336
|
+
const getWithHooks = (adapter, hooks = []) => ({
|
|
337
|
+
async createWithHooks(data, model, customCreateFn) {
|
|
338
|
+
const ctx = require_hono.getContext();
|
|
339
|
+
let actualData = data;
|
|
340
|
+
for (const hook of hooks) {
|
|
341
|
+
const toRun = hook[model]?.create?.before;
|
|
342
|
+
if (toRun) {
|
|
343
|
+
const result = await toRun(actualData, ctx);
|
|
344
|
+
if (result === false) return null;
|
|
345
|
+
if (typeof result === "object" && "data" in result) actualData = {
|
|
346
|
+
...actualData,
|
|
347
|
+
...result.data
|
|
348
|
+
};
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
const customCreated = customCreateFn ? await customCreateFn.fn(actualData) : null;
|
|
352
|
+
const created = !customCreateFn || customCreateFn.executeMainFn ? await require_ip.getCurrentAdapter(adapter).create({
|
|
353
|
+
model,
|
|
354
|
+
data: actualData,
|
|
355
|
+
forceAllowId: true
|
|
356
|
+
}) : customCreated;
|
|
357
|
+
for (const hook of hooks) {
|
|
358
|
+
const toRun = hook[model]?.create?.after;
|
|
359
|
+
if (toRun) await toRun(created, ctx);
|
|
360
|
+
}
|
|
361
|
+
return created;
|
|
362
|
+
},
|
|
363
|
+
async updateWithHooks(data, where, model, customUpdateFn) {
|
|
364
|
+
const ctx = require_hono.getContext();
|
|
365
|
+
let actualData = data;
|
|
366
|
+
for (const hook of hooks) {
|
|
367
|
+
const toRun = hook[model]?.update?.before;
|
|
368
|
+
if (toRun) {
|
|
369
|
+
const result = await toRun(data, ctx);
|
|
370
|
+
if (result === false) return null;
|
|
371
|
+
actualData = typeof result === "object" ? result.data : result;
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
const customUpdated = customUpdateFn ? await customUpdateFn.fn(actualData) : null;
|
|
375
|
+
const updated = !customUpdateFn || customUpdateFn.executeMainFn ? await require_ip.getCurrentAdapter(adapter).update({
|
|
376
|
+
model,
|
|
377
|
+
update: actualData,
|
|
378
|
+
where
|
|
379
|
+
}) : customUpdated;
|
|
380
|
+
for (const hook of hooks) {
|
|
381
|
+
const toRun = hook[model]?.update?.after;
|
|
382
|
+
if (toRun) await toRun(updated, ctx);
|
|
383
|
+
}
|
|
384
|
+
return updated;
|
|
385
|
+
},
|
|
386
|
+
async updateManyWithHooks(data, where, model, customUpdateFn) {
|
|
387
|
+
const ctx = require_hono.getContext();
|
|
388
|
+
let actualData = data;
|
|
389
|
+
for (const hook of hooks) {
|
|
390
|
+
const toRun = hook[model]?.update?.before;
|
|
391
|
+
if (toRun) {
|
|
392
|
+
const result = await toRun(data, ctx);
|
|
393
|
+
if (result === false) return null;
|
|
394
|
+
actualData = typeof result === "object" ? result.data : result;
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
const customUpdated = customUpdateFn ? await customUpdateFn.fn(actualData) : null;
|
|
398
|
+
const updated = !customUpdateFn || customUpdateFn.executeMainFn ? await require_ip.getCurrentAdapter(adapter).updateMany({
|
|
399
|
+
model,
|
|
400
|
+
update: actualData,
|
|
401
|
+
where
|
|
402
|
+
}) : customUpdated;
|
|
403
|
+
for (const hook of hooks) {
|
|
404
|
+
const toRun = hook[model]?.update?.after;
|
|
405
|
+
if (toRun) await toRun(updated, ctx);
|
|
406
|
+
}
|
|
407
|
+
return updated;
|
|
408
|
+
},
|
|
409
|
+
async deleteWithHooks(where, model, customDeleteFn) {
|
|
410
|
+
const ctx = require_hono.getContext();
|
|
411
|
+
let entityToDelete = null;
|
|
412
|
+
try {
|
|
413
|
+
entityToDelete = (await require_ip.getCurrentAdapter(adapter).findMany({
|
|
414
|
+
model,
|
|
415
|
+
where,
|
|
416
|
+
limit: 1
|
|
417
|
+
}))[0] ?? null;
|
|
418
|
+
} catch (error) {}
|
|
419
|
+
if (entityToDelete) for (const hook of hooks) {
|
|
420
|
+
const toRun = hook[model]?.delete?.before;
|
|
421
|
+
if (toRun) {
|
|
422
|
+
if (await toRun(entityToDelete, ctx) === false) return null;
|
|
423
|
+
}
|
|
424
|
+
}
|
|
425
|
+
const customDeleted = customDeleteFn ? await customDeleteFn.fn(where) : null;
|
|
426
|
+
const deleted = !customDeleteFn || customDeleteFn.executeMainFn ? await require_ip.getCurrentAdapter(adapter).delete({
|
|
427
|
+
model,
|
|
428
|
+
where
|
|
429
|
+
}) : customDeleted;
|
|
430
|
+
if (entityToDelete) for (const hook of hooks) {
|
|
431
|
+
const toRun = hook[model]?.delete?.after;
|
|
432
|
+
if (toRun) await toRun(entityToDelete, ctx);
|
|
433
|
+
}
|
|
434
|
+
return deleted;
|
|
435
|
+
},
|
|
436
|
+
async deleteManyWithHooks(where, model, customDeleteFn) {
|
|
437
|
+
const ctx = require_hono.getContext();
|
|
438
|
+
let entitiesToDelete = [];
|
|
439
|
+
try {
|
|
440
|
+
entitiesToDelete = await require_ip.getCurrentAdapter(adapter).findMany({
|
|
441
|
+
model,
|
|
442
|
+
where
|
|
443
|
+
});
|
|
444
|
+
} catch (error) {}
|
|
445
|
+
for (const entity of entitiesToDelete) for (const hook of hooks) {
|
|
446
|
+
const toRun = hook[model]?.delete?.before;
|
|
447
|
+
if (toRun) {
|
|
448
|
+
if (await toRun(entity, ctx) === false) return null;
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
const customDeleted = customDeleteFn ? await customDeleteFn.fn(where) : null;
|
|
452
|
+
const deleted = !customDeleteFn || customDeleteFn.executeMainFn ? await require_ip.getCurrentAdapter(adapter).deleteMany({
|
|
453
|
+
model,
|
|
454
|
+
where
|
|
455
|
+
}) : customDeleted;
|
|
456
|
+
for (const entity of entitiesToDelete) for (const hook of hooks) {
|
|
457
|
+
const toRun = hook[model]?.delete?.after;
|
|
458
|
+
if (toRun) await toRun(entity, ctx);
|
|
459
|
+
}
|
|
460
|
+
return deleted;
|
|
461
|
+
}
|
|
462
|
+
});
|
|
463
|
+
// src/db/internal-adapter.ts
|
|
464
|
+
const createInternalAdapter = (adapter, options, context, hooks) => {
|
|
465
|
+
const secondaryStorage = context.secondaryStorage;
|
|
466
|
+
const sessionExpiration = context.sessionConfig.expiresIn;
|
|
467
|
+
const { createWithHooks, updateWithHooks, updateManyWithHooks, deleteWithHooks, deleteManyWithHooks } = getWithHooks(adapter, hooks);
|
|
468
|
+
async function refreshUserSessions(user) {
|
|
469
|
+
if (!secondaryStorage) return;
|
|
470
|
+
if (!user.id) return;
|
|
471
|
+
const listRaw = await secondaryStorage.get(`active-sessions-${user.id}`);
|
|
472
|
+
if (!listRaw) return;
|
|
473
|
+
const now = Date.now();
|
|
474
|
+
const validSessions = (require_json.safeJSONParse(listRaw) || []).filter((s) => s.expiresAt > now);
|
|
475
|
+
await Promise.all(validSessions.map(async ({ token }) => {
|
|
476
|
+
const cached = await secondaryStorage.get(token);
|
|
477
|
+
if (!cached) return;
|
|
478
|
+
const parsed = require_json.safeJSONParse(cached);
|
|
479
|
+
if (!parsed) return;
|
|
480
|
+
const sessionTTL = Math.max(Math.floor(new Date(parsed.session.expiresAt).getTime() - now) / 1e3, 0);
|
|
481
|
+
await secondaryStorage.set(token, JSON.stringify({
|
|
482
|
+
session: parsed.session,
|
|
483
|
+
user
|
|
484
|
+
}), Math.floor(sessionTTL));
|
|
485
|
+
}));
|
|
486
|
+
}
|
|
487
|
+
return {
|
|
488
|
+
createOAuthUser: async (user, account) => {
|
|
489
|
+
return require_ip.runWithTransaction(adapter, async () => {
|
|
490
|
+
const createdUser = await createWithHooks({
|
|
491
|
+
...user,
|
|
492
|
+
createdAt: user.createdAt ? new Date(user.createdAt) : /* @__PURE__ */ new Date(),
|
|
493
|
+
updatedAt: user.updatedAt ? new Date(user.updatedAt) : /* @__PURE__ */ new Date()
|
|
494
|
+
}, "user");
|
|
495
|
+
return {
|
|
496
|
+
user: createdUser,
|
|
497
|
+
account: await createWithHooks({
|
|
498
|
+
...account,
|
|
499
|
+
userId: createdUser.id,
|
|
500
|
+
createdAt: account.createdAt ? new Date(account.createdAt) : /* @__PURE__ */ new Date(),
|
|
501
|
+
updatedAt: account.updatedAt ? new Date(account.updatedAt) : /* @__PURE__ */ new Date()
|
|
502
|
+
}, "account")
|
|
503
|
+
};
|
|
504
|
+
});
|
|
505
|
+
},
|
|
506
|
+
createUser: async (user) => {
|
|
507
|
+
return await createWithHooks({
|
|
508
|
+
...user,
|
|
509
|
+
createdAt: user.createdAt ? new Date(user.createdAt) : /* @__PURE__ */ new Date(),
|
|
510
|
+
updatedAt: user.updatedAt ? new Date(user.updatedAt) : /* @__PURE__ */ new Date(),
|
|
511
|
+
...user.email && { email: user.email.toLowerCase() }
|
|
512
|
+
}, "user");
|
|
513
|
+
},
|
|
514
|
+
createAccount: async (account) => {
|
|
515
|
+
return await createWithHooks({
|
|
516
|
+
...account,
|
|
517
|
+
createdAt: account.createdAt ? new Date(account.createdAt) : /* @__PURE__ */ new Date(),
|
|
518
|
+
updatedAt: account.updatedAt ? new Date(account.updatedAt) : /* @__PURE__ */ new Date()
|
|
519
|
+
}, "account");
|
|
520
|
+
},
|
|
521
|
+
listSessions: async (userId) => {
|
|
522
|
+
if (secondaryStorage) {
|
|
523
|
+
const currentList = await secondaryStorage.get(`active-sessions-${userId}`);
|
|
524
|
+
if (!currentList) return [];
|
|
525
|
+
const list = require_json.safeJSONParse(currentList) || [];
|
|
526
|
+
const now = Date.now();
|
|
527
|
+
const validSessions = list.filter((s) => s.expiresAt > now);
|
|
528
|
+
const sessions = [];
|
|
529
|
+
for (const session of validSessions) {
|
|
530
|
+
const sessionStringified = await secondaryStorage.get(session.token);
|
|
531
|
+
if (sessionStringified) {
|
|
532
|
+
const s = require_json.safeJSONParse(sessionStringified);
|
|
533
|
+
if (!s) return [];
|
|
534
|
+
const parsedSession = require_schema.parseSessionOutput(options, {
|
|
535
|
+
...s.session,
|
|
536
|
+
expiresAt: new Date(s.session.expiresAt)
|
|
537
|
+
});
|
|
538
|
+
sessions.push(parsedSession);
|
|
539
|
+
}
|
|
540
|
+
}
|
|
541
|
+
return sessions;
|
|
542
|
+
}
|
|
543
|
+
return await require_ip.getCurrentAdapter(adapter).findMany({
|
|
544
|
+
model: "session",
|
|
545
|
+
where: [{
|
|
546
|
+
field: "userId",
|
|
547
|
+
value: userId
|
|
548
|
+
}]
|
|
549
|
+
});
|
|
550
|
+
},
|
|
551
|
+
listUsers: async (limit, offset, sortBy, where) => {
|
|
552
|
+
return await require_ip.getCurrentAdapter(adapter).findMany({
|
|
553
|
+
model: "user",
|
|
554
|
+
...limit && { limit },
|
|
555
|
+
...offset && { offset },
|
|
556
|
+
...sortBy && { sortBy },
|
|
557
|
+
...where && { where }
|
|
558
|
+
});
|
|
559
|
+
},
|
|
560
|
+
countTotalUsers: async (where) => {
|
|
561
|
+
const total = await require_ip.getCurrentAdapter(adapter).count({
|
|
562
|
+
model: "user",
|
|
563
|
+
...where && { where }
|
|
564
|
+
});
|
|
565
|
+
if (typeof total === "string") return parseInt(total);
|
|
566
|
+
return total;
|
|
567
|
+
},
|
|
568
|
+
deleteUser: async (userId) => {
|
|
569
|
+
if (secondaryStorage) await secondaryStorage.delete(`active-sessions-${userId}`);
|
|
570
|
+
if (!secondaryStorage || options.session?.storeSessionInDatabase) await deleteManyWithHooks([{
|
|
571
|
+
field: "userId",
|
|
572
|
+
value: userId
|
|
573
|
+
}], "session");
|
|
574
|
+
await deleteManyWithHooks([{
|
|
575
|
+
field: "userId",
|
|
576
|
+
value: userId
|
|
577
|
+
}], "account");
|
|
578
|
+
await deleteWithHooks([{
|
|
579
|
+
field: "id",
|
|
580
|
+
value: userId
|
|
581
|
+
}], "user");
|
|
582
|
+
},
|
|
583
|
+
createSession: async (userId, dontRememberMe, override, overrideAll) => {
|
|
584
|
+
const ctx = require_hono.getContext();
|
|
585
|
+
const ip = require_ip.getIp(ctx.req, options);
|
|
586
|
+
const ua = ctx.req.header("user-agent");
|
|
587
|
+
const { id: _, ...rest } = override || {};
|
|
588
|
+
const data = {
|
|
589
|
+
...ip && { ipAddress: ip },
|
|
590
|
+
...ua && { userAgent: ua },
|
|
591
|
+
...rest,
|
|
592
|
+
/**
|
|
593
|
+
* If the user doesn't want to be remembered
|
|
594
|
+
* set the session to expire in 1 day.
|
|
595
|
+
* The cookie will be set to expire at the end of the session
|
|
596
|
+
*/
|
|
597
|
+
expiresAt: dontRememberMe ? (0, _faire_auth_core_utils.getDate)(86400, "sec") : (0, _faire_auth_core_utils.getDate)(sessionExpiration, "sec"),
|
|
598
|
+
userId,
|
|
599
|
+
token: (0, _faire_auth_core_crypto.generateId)(32),
|
|
600
|
+
createdAt: /* @__PURE__ */ new Date(),
|
|
601
|
+
updatedAt: /* @__PURE__ */ new Date(),
|
|
602
|
+
...overrideAll ? rest : {}
|
|
603
|
+
};
|
|
604
|
+
return await createWithHooks(data, "session", secondaryStorage ? {
|
|
605
|
+
fn: async (sessionData) => {
|
|
606
|
+
/**
|
|
607
|
+
* store the session token for the user
|
|
608
|
+
* so we can retrieve it later for listing sessions
|
|
609
|
+
*/
|
|
610
|
+
const currentList = await secondaryStorage.get(`active-sessions-${userId}`);
|
|
611
|
+
let list = [];
|
|
612
|
+
const now = Date.now();
|
|
613
|
+
if (currentList) {
|
|
614
|
+
list = require_json.safeJSONParse(currentList) || [];
|
|
615
|
+
list = list.filter((session) => session.expiresAt > now);
|
|
616
|
+
}
|
|
617
|
+
const sorted = list.sort((a, b) => a.expiresAt - b.expiresAt);
|
|
618
|
+
let furthestSessionExp = sorted.at(-1)?.expiresAt;
|
|
619
|
+
sorted.push({
|
|
620
|
+
token: data.token,
|
|
621
|
+
expiresAt: data.expiresAt.getTime()
|
|
622
|
+
});
|
|
623
|
+
if (!furthestSessionExp || furthestSessionExp < data.expiresAt.getTime()) furthestSessionExp = data.expiresAt.getTime();
|
|
624
|
+
const furthestSessionTTL = Math.max(Math.floor((furthestSessionExp - now) / 1e3), 0);
|
|
625
|
+
if (furthestSessionTTL > 0) await secondaryStorage.set(`active-sessions-${userId}`, JSON.stringify(sorted), furthestSessionTTL);
|
|
626
|
+
const user = await adapter.findOne({
|
|
627
|
+
model: "user",
|
|
628
|
+
where: [{
|
|
629
|
+
field: "id",
|
|
630
|
+
value: userId
|
|
631
|
+
}]
|
|
632
|
+
});
|
|
633
|
+
const sessionTTL = Math.max(Math.floor((data.expiresAt.getTime() - now) / 1e3), 0);
|
|
634
|
+
if (sessionTTL > 0) await secondaryStorage.set(data.token, JSON.stringify({
|
|
635
|
+
session: sessionData,
|
|
636
|
+
user
|
|
637
|
+
}), sessionTTL);
|
|
638
|
+
return sessionData;
|
|
639
|
+
},
|
|
640
|
+
executeMainFn: options.session?.storeSessionInDatabase === true
|
|
641
|
+
} : void 0);
|
|
642
|
+
},
|
|
643
|
+
findSession: async (token) => {
|
|
644
|
+
if (secondaryStorage) {
|
|
645
|
+
const sessionStringified = await secondaryStorage.get(token);
|
|
646
|
+
if (!sessionStringified && !options.session?.storeSessionInDatabase) return null;
|
|
647
|
+
if (sessionStringified) {
|
|
648
|
+
const s = require_json.safeJSONParse(sessionStringified);
|
|
649
|
+
if (!s) return null;
|
|
650
|
+
return {
|
|
651
|
+
session: require_schema.parseSessionOutput(options, {
|
|
652
|
+
...s.session,
|
|
653
|
+
expiresAt: new Date(s.session.expiresAt),
|
|
654
|
+
createdAt: new Date(s.session.createdAt),
|
|
655
|
+
updatedAt: new Date(s.session.updatedAt)
|
|
656
|
+
}),
|
|
657
|
+
user: require_schema.parseUserOutput(options, {
|
|
658
|
+
...s.user,
|
|
659
|
+
createdAt: new Date(s.user.createdAt),
|
|
660
|
+
updatedAt: new Date(s.user.updatedAt)
|
|
661
|
+
})
|
|
662
|
+
};
|
|
663
|
+
}
|
|
664
|
+
}
|
|
665
|
+
const session = await require_ip.getCurrentAdapter(adapter).findOne({
|
|
666
|
+
model: "session",
|
|
667
|
+
where: [{
|
|
668
|
+
value: token,
|
|
669
|
+
field: "token"
|
|
670
|
+
}]
|
|
671
|
+
});
|
|
672
|
+
if (!session) return null;
|
|
673
|
+
const user = await require_ip.getCurrentAdapter(adapter).findOne({
|
|
674
|
+
model: "user",
|
|
675
|
+
where: [{
|
|
676
|
+
value: session.userId,
|
|
677
|
+
field: "id"
|
|
678
|
+
}]
|
|
679
|
+
});
|
|
680
|
+
if (!user) return null;
|
|
681
|
+
return {
|
|
682
|
+
session: require_schema.parseSessionOutput(options, session),
|
|
683
|
+
user: require_schema.parseUserOutput(options, user)
|
|
684
|
+
};
|
|
685
|
+
},
|
|
686
|
+
findSessions: async (sessionTokens) => {
|
|
687
|
+
if (secondaryStorage) {
|
|
688
|
+
const sessions = [];
|
|
689
|
+
for (const sessionToken of sessionTokens) {
|
|
690
|
+
const sessionStringified = await secondaryStorage.get(sessionToken);
|
|
691
|
+
if (sessionStringified) {
|
|
692
|
+
const s = require_json.safeJSONParse(sessionStringified);
|
|
693
|
+
if (!s) return [];
|
|
694
|
+
const session = {
|
|
695
|
+
session: {
|
|
696
|
+
...s.session,
|
|
697
|
+
expiresAt: new Date(s.session.expiresAt)
|
|
698
|
+
},
|
|
699
|
+
user: {
|
|
700
|
+
...s.user,
|
|
701
|
+
createdAt: new Date(s.user.createdAt),
|
|
702
|
+
updatedAt: new Date(s.user.updatedAt)
|
|
703
|
+
}
|
|
704
|
+
};
|
|
705
|
+
sessions.push(session);
|
|
706
|
+
}
|
|
707
|
+
}
|
|
708
|
+
return sessions;
|
|
709
|
+
}
|
|
710
|
+
const sessions = await require_ip.getCurrentAdapter(adapter).findMany({
|
|
711
|
+
model: "session",
|
|
712
|
+
where: [{
|
|
713
|
+
field: "token",
|
|
714
|
+
value: sessionTokens,
|
|
715
|
+
operator: "in"
|
|
716
|
+
}]
|
|
717
|
+
});
|
|
718
|
+
const userIds = sessions.map((session) => {
|
|
719
|
+
return session.userId;
|
|
720
|
+
});
|
|
721
|
+
if (!userIds.length) return [];
|
|
722
|
+
const users = await require_ip.getCurrentAdapter(adapter).findMany({
|
|
723
|
+
model: "user",
|
|
724
|
+
where: [{
|
|
725
|
+
field: "id",
|
|
726
|
+
value: userIds,
|
|
727
|
+
operator: "in"
|
|
728
|
+
}]
|
|
729
|
+
});
|
|
730
|
+
return sessions.map((session) => {
|
|
731
|
+
const user = users.find((u) => u.id === session.userId);
|
|
732
|
+
if (!user) return null;
|
|
733
|
+
return {
|
|
734
|
+
session,
|
|
735
|
+
user
|
|
736
|
+
};
|
|
737
|
+
});
|
|
738
|
+
},
|
|
739
|
+
updateSession: async (sessionToken, session) => {
|
|
740
|
+
return await updateWithHooks(session, [{
|
|
741
|
+
field: "token",
|
|
742
|
+
value: sessionToken
|
|
743
|
+
}], "session", secondaryStorage ? {
|
|
744
|
+
fn: async (data) => {
|
|
745
|
+
const currentSession = await secondaryStorage.get(sessionToken);
|
|
746
|
+
let updatedSession;
|
|
747
|
+
if (currentSession) {
|
|
748
|
+
const parsedSession = require_json.safeJSONParse(currentSession);
|
|
749
|
+
if (!parsedSession) return;
|
|
750
|
+
updatedSession = {
|
|
751
|
+
...parsedSession.session,
|
|
752
|
+
...data
|
|
753
|
+
};
|
|
754
|
+
return updatedSession;
|
|
755
|
+
}
|
|
756
|
+
},
|
|
757
|
+
executeMainFn: options.session?.storeSessionInDatabase === true
|
|
758
|
+
} : void 0);
|
|
759
|
+
},
|
|
760
|
+
deleteSession: async (token) => {
|
|
761
|
+
if (secondaryStorage) {
|
|
762
|
+
const data = await secondaryStorage.get(token);
|
|
763
|
+
if (data) {
|
|
764
|
+
const { session } = require_json.safeJSONParse(data) ?? {};
|
|
765
|
+
if (!session) {
|
|
766
|
+
context.logger.error("Session not found in secondary storage");
|
|
767
|
+
return;
|
|
768
|
+
}
|
|
769
|
+
const userId = session.userId;
|
|
770
|
+
const currentList = await secondaryStorage.get(`active-sessions-${userId}`);
|
|
771
|
+
if (currentList) {
|
|
772
|
+
let list = require_json.safeJSONParse(currentList) || [];
|
|
773
|
+
const now = Date.now();
|
|
774
|
+
const filtered = list.filter((session) => session.expiresAt > now && session.token !== token);
|
|
775
|
+
const furthestSessionExp = filtered.sort((a, b) => a.expiresAt - b.expiresAt).at(-1)?.expiresAt;
|
|
776
|
+
if (filtered.length > 0 && furthestSessionExp && furthestSessionExp > Date.now()) await secondaryStorage.set(`active-sessions-${userId}`, JSON.stringify(filtered), Math.floor((furthestSessionExp - now) / 1e3));
|
|
777
|
+
else await secondaryStorage.delete(`active-sessions-${userId}`);
|
|
778
|
+
} else context.logger.error("Active sessions list not found in secondary storage");
|
|
779
|
+
}
|
|
780
|
+
await secondaryStorage.delete(token);
|
|
781
|
+
if (!options.session?.storeSessionInDatabase || options.session?.preserveSessionInDatabase) return;
|
|
782
|
+
}
|
|
783
|
+
await require_ip.getCurrentAdapter(adapter).delete({
|
|
784
|
+
model: "session",
|
|
785
|
+
where: [{
|
|
786
|
+
field: "token",
|
|
787
|
+
value: token
|
|
788
|
+
}]
|
|
789
|
+
});
|
|
790
|
+
},
|
|
791
|
+
deleteAccounts: async (userId) => {
|
|
792
|
+
await deleteManyWithHooks([{
|
|
793
|
+
field: "userId",
|
|
794
|
+
value: userId
|
|
795
|
+
}], "account");
|
|
796
|
+
},
|
|
797
|
+
deleteAccount: async (accountId) => {
|
|
798
|
+
await deleteWithHooks([{
|
|
799
|
+
field: "id",
|
|
800
|
+
value: accountId
|
|
801
|
+
}], "account");
|
|
802
|
+
},
|
|
803
|
+
deleteSessions: async (userIdOrSessionTokens) => {
|
|
804
|
+
if (secondaryStorage) {
|
|
805
|
+
if (typeof userIdOrSessionTokens === "string") {
|
|
806
|
+
const activeSession = await secondaryStorage.get(`active-sessions-${userIdOrSessionTokens}`);
|
|
807
|
+
const sessions = activeSession ? require_json.safeJSONParse(activeSession) : [];
|
|
808
|
+
if (!sessions) return;
|
|
809
|
+
for (const session of sessions) await secondaryStorage.delete(session.token);
|
|
810
|
+
} else for (const sessionToken of userIdOrSessionTokens) if (await secondaryStorage.get(sessionToken)) await secondaryStorage.delete(sessionToken);
|
|
811
|
+
if (!options.session?.storeSessionInDatabase || options.session?.preserveSessionInDatabase) return;
|
|
812
|
+
}
|
|
813
|
+
await deleteManyWithHooks([{
|
|
814
|
+
field: Array.isArray(userIdOrSessionTokens) ? "token" : "userId",
|
|
815
|
+
value: userIdOrSessionTokens,
|
|
816
|
+
...Array.isArray(userIdOrSessionTokens) && { operator: "in" }
|
|
817
|
+
}], "session");
|
|
818
|
+
},
|
|
819
|
+
findOAuthUser: async (email, accountId, providerId) => {
|
|
820
|
+
const account = await require_ip.getCurrentAdapter(adapter).findMany({
|
|
821
|
+
model: "account",
|
|
822
|
+
where: [{
|
|
823
|
+
value: accountId,
|
|
824
|
+
field: "accountId"
|
|
825
|
+
}]
|
|
826
|
+
}).then((accounts) => {
|
|
827
|
+
return accounts.find((a) => a.providerId === providerId);
|
|
828
|
+
});
|
|
829
|
+
if (account) {
|
|
830
|
+
const user = await require_ip.getCurrentAdapter(adapter).findOne({
|
|
831
|
+
model: "user",
|
|
832
|
+
where: [{
|
|
833
|
+
value: account.userId,
|
|
834
|
+
field: "id"
|
|
835
|
+
}]
|
|
836
|
+
});
|
|
837
|
+
if (user) return {
|
|
838
|
+
user,
|
|
839
|
+
accounts: [account]
|
|
840
|
+
};
|
|
841
|
+
else {
|
|
842
|
+
const user = await require_ip.getCurrentAdapter(adapter).findOne({
|
|
843
|
+
model: "user",
|
|
844
|
+
where: [{
|
|
845
|
+
value: email.toLowerCase(),
|
|
846
|
+
field: "email"
|
|
847
|
+
}]
|
|
848
|
+
});
|
|
849
|
+
if (user) return {
|
|
850
|
+
user,
|
|
851
|
+
accounts: [account]
|
|
852
|
+
};
|
|
853
|
+
return null;
|
|
854
|
+
}
|
|
855
|
+
} else {
|
|
856
|
+
const user = await require_ip.getCurrentAdapter(adapter).findOne({
|
|
857
|
+
model: "user",
|
|
858
|
+
where: [{
|
|
859
|
+
value: email.toLowerCase(),
|
|
860
|
+
field: "email"
|
|
861
|
+
}]
|
|
862
|
+
});
|
|
863
|
+
if (user) return {
|
|
864
|
+
user,
|
|
865
|
+
accounts: await require_ip.getCurrentAdapter(adapter).findMany({
|
|
866
|
+
model: "account",
|
|
867
|
+
where: [{
|
|
868
|
+
value: user.id,
|
|
869
|
+
field: "userId"
|
|
870
|
+
}]
|
|
871
|
+
}) || []
|
|
872
|
+
};
|
|
873
|
+
else return null;
|
|
874
|
+
}
|
|
875
|
+
},
|
|
876
|
+
findUserByEmail: async (email, options) => {
|
|
877
|
+
const user = await require_ip.getCurrentAdapter(adapter).findOne({
|
|
878
|
+
model: "user",
|
|
879
|
+
where: [{
|
|
880
|
+
value: email.toLowerCase(),
|
|
881
|
+
field: "email"
|
|
882
|
+
}]
|
|
883
|
+
});
|
|
884
|
+
if (!user) return null;
|
|
885
|
+
if (options?.includeAccounts) return {
|
|
886
|
+
user,
|
|
887
|
+
accounts: await require_ip.getCurrentAdapter(adapter).findMany({
|
|
888
|
+
model: "account",
|
|
889
|
+
where: [{
|
|
890
|
+
value: user.id,
|
|
891
|
+
field: "userId"
|
|
892
|
+
}]
|
|
893
|
+
})
|
|
894
|
+
};
|
|
895
|
+
return {
|
|
896
|
+
user,
|
|
897
|
+
accounts: []
|
|
898
|
+
};
|
|
899
|
+
},
|
|
900
|
+
findUserById: async (userId) => {
|
|
901
|
+
return await require_ip.getCurrentAdapter(adapter).findOne({
|
|
902
|
+
model: "user",
|
|
903
|
+
where: [{
|
|
904
|
+
field: "id",
|
|
905
|
+
value: userId
|
|
906
|
+
}]
|
|
907
|
+
});
|
|
908
|
+
},
|
|
909
|
+
linkAccount: async (account) => {
|
|
910
|
+
return await createWithHooks({
|
|
911
|
+
...account,
|
|
912
|
+
createdAt: account.createdAt ? new Date(account.createdAt) : /* @__PURE__ */ new Date(),
|
|
913
|
+
updatedAt: account.updatedAt ? new Date(account.updatedAt) : /* @__PURE__ */ new Date()
|
|
914
|
+
}, "account");
|
|
915
|
+
},
|
|
916
|
+
updateUser: async (userId, data) => {
|
|
917
|
+
const user = await updateWithHooks(data, [{
|
|
918
|
+
field: "id",
|
|
919
|
+
value: userId
|
|
920
|
+
}], "user");
|
|
921
|
+
if (user) {
|
|
922
|
+
await refreshUserSessions(user);
|
|
923
|
+
await refreshUserSessions(user);
|
|
924
|
+
}
|
|
925
|
+
return user;
|
|
926
|
+
},
|
|
927
|
+
updateUserByEmail: async (email, data) => {
|
|
928
|
+
const user = await updateWithHooks(data, [{
|
|
929
|
+
field: "email",
|
|
930
|
+
value: email.toLowerCase()
|
|
931
|
+
}], "user");
|
|
932
|
+
if (user) {
|
|
933
|
+
await refreshUserSessions(user);
|
|
934
|
+
await refreshUserSessions(user);
|
|
935
|
+
}
|
|
936
|
+
return user;
|
|
937
|
+
},
|
|
938
|
+
updatePassword: async (userId, password) => {
|
|
939
|
+
await updateManyWithHooks({ password }, [{
|
|
940
|
+
field: "userId",
|
|
941
|
+
value: userId
|
|
942
|
+
}, {
|
|
943
|
+
field: "providerId",
|
|
944
|
+
value: "credential"
|
|
945
|
+
}], "account");
|
|
946
|
+
},
|
|
947
|
+
findAccounts: async (userId) => {
|
|
948
|
+
return await require_ip.getCurrentAdapter(adapter).findMany({
|
|
949
|
+
model: "account",
|
|
950
|
+
where: [{
|
|
951
|
+
field: "userId",
|
|
952
|
+
value: userId
|
|
953
|
+
}]
|
|
954
|
+
});
|
|
955
|
+
},
|
|
956
|
+
findAccount: async (accountId) => {
|
|
957
|
+
return await require_ip.getCurrentAdapter(adapter).findOne({
|
|
958
|
+
model: "account",
|
|
959
|
+
where: [{
|
|
960
|
+
field: "accountId",
|
|
961
|
+
value: accountId
|
|
962
|
+
}]
|
|
963
|
+
});
|
|
964
|
+
},
|
|
965
|
+
findAccountByProviderId: async (accountId, providerId) => {
|
|
966
|
+
return await require_ip.getCurrentAdapter(adapter).findOne({
|
|
967
|
+
model: "account",
|
|
968
|
+
where: [{
|
|
969
|
+
field: "accountId",
|
|
970
|
+
value: accountId
|
|
971
|
+
}, {
|
|
972
|
+
field: "providerId",
|
|
973
|
+
value: providerId
|
|
974
|
+
}]
|
|
975
|
+
});
|
|
976
|
+
},
|
|
977
|
+
findAccountByUserId: async (userId) => {
|
|
978
|
+
return await require_ip.getCurrentAdapter(adapter).findMany({
|
|
979
|
+
model: "account",
|
|
980
|
+
where: [{
|
|
981
|
+
field: "userId",
|
|
982
|
+
value: userId
|
|
983
|
+
}]
|
|
984
|
+
});
|
|
985
|
+
},
|
|
986
|
+
updateAccount: async (id, data) => {
|
|
987
|
+
return await updateWithHooks(data, [{
|
|
988
|
+
field: "id",
|
|
989
|
+
value: id
|
|
990
|
+
}], "account");
|
|
991
|
+
},
|
|
992
|
+
createVerificationValue: async (data) => {
|
|
993
|
+
return await createWithHooks({
|
|
994
|
+
createdAt: /* @__PURE__ */ new Date(),
|
|
995
|
+
updatedAt: /* @__PURE__ */ new Date(),
|
|
996
|
+
...data
|
|
997
|
+
}, "verification");
|
|
998
|
+
},
|
|
999
|
+
findVerificationValue: async (identifier) => {
|
|
1000
|
+
const verification = await require_ip.getCurrentAdapter(adapter).findMany({
|
|
1001
|
+
model: "verification",
|
|
1002
|
+
where: [{
|
|
1003
|
+
field: "identifier",
|
|
1004
|
+
value: identifier
|
|
1005
|
+
}],
|
|
1006
|
+
sortBy: {
|
|
1007
|
+
field: "createdAt",
|
|
1008
|
+
direction: "desc"
|
|
1009
|
+
},
|
|
1010
|
+
limit: 1
|
|
1011
|
+
});
|
|
1012
|
+
if (!options.verification?.disableCleanup) await require_ip.getCurrentAdapter(adapter).deleteMany({
|
|
1013
|
+
model: "verification",
|
|
1014
|
+
where: [{
|
|
1015
|
+
field: "expiresAt",
|
|
1016
|
+
value: /* @__PURE__ */ new Date(),
|
|
1017
|
+
operator: "lt"
|
|
1018
|
+
}]
|
|
1019
|
+
});
|
|
1020
|
+
return verification[0] ?? null;
|
|
1021
|
+
},
|
|
1022
|
+
deleteVerificationValue: async (id) => {
|
|
1023
|
+
await require_ip.getCurrentAdapter(adapter).delete({
|
|
1024
|
+
model: "verification",
|
|
1025
|
+
where: [{
|
|
1026
|
+
field: "id",
|
|
1027
|
+
value: id
|
|
1028
|
+
}]
|
|
1029
|
+
});
|
|
1030
|
+
},
|
|
1031
|
+
deleteVerificationByIdentifier: async (identifier) => {
|
|
1032
|
+
await require_ip.getCurrentAdapter(adapter).delete({
|
|
1033
|
+
model: "verification",
|
|
1034
|
+
where: [{
|
|
1035
|
+
field: "identifier",
|
|
1036
|
+
value: identifier
|
|
1037
|
+
}]
|
|
1038
|
+
});
|
|
1039
|
+
},
|
|
1040
|
+
updateVerificationValue: async (id, data) => {
|
|
1041
|
+
return await updateWithHooks(data, [{
|
|
1042
|
+
field: "id",
|
|
1043
|
+
value: id
|
|
1044
|
+
}], "verification");
|
|
1045
|
+
}
|
|
1046
|
+
};
|
|
1047
|
+
};
|
|
1048
|
+
// src/db/to-zod.ts
|
|
1049
|
+
function toZodSchema({ fields, isClientSide }) {
|
|
1050
|
+
const zodFields = Object.keys(fields).reduce((acc, key) => {
|
|
1051
|
+
const field = fields[key];
|
|
1052
|
+
if (!field) return acc;
|
|
1053
|
+
if (isClientSide && field.input === false) return acc;
|
|
1054
|
+
let schema;
|
|
1055
|
+
if (field.type === "json") schema = zod.json ? zod.json() : zod.any();
|
|
1056
|
+
else if (field.type === "string[]" || field.type === "number[]") schema = zod.array(field.type === "string[]" ? zod.string() : zod.number());
|
|
1057
|
+
else if (Array.isArray(field.type)) schema = zod.any();
|
|
1058
|
+
else schema = zod[field.type]();
|
|
1059
|
+
if (field?.required === false) schema = schema.optional();
|
|
1060
|
+
if (field?.returned === false) return acc;
|
|
1061
|
+
return {
|
|
1062
|
+
...acc,
|
|
1063
|
+
[key]: schema
|
|
1064
|
+
};
|
|
1065
|
+
}, {});
|
|
1066
|
+
return zod.object(zodFields);
|
|
1067
|
+
}
|
|
1068
|
+
// src/db/utils.ts
|
|
1069
|
+
function patchAdapterTransaction(adapter) {
|
|
1070
|
+
if (!adapter.transaction) {
|
|
1071
|
+
_faire_auth_core_env.logger.warn("Adapter does not correctly implement transaction function, patching it automatically. Please update your adapter implementation.");
|
|
1072
|
+
adapter.transaction = (cb) => {
|
|
1073
|
+
const res = cb(adapter);
|
|
1074
|
+
return (0, _faire_auth_core_static.isPromise)(res) ? res : Promise.resolve(res);
|
|
1075
|
+
};
|
|
1076
|
+
}
|
|
1077
|
+
return adapter;
|
|
1078
|
+
}
|
|
1079
|
+
function getAdapter(options) {
|
|
1080
|
+
if (!options.database) {
|
|
1081
|
+
const tables = require_adapter_factory.getAuthTables(options);
|
|
1082
|
+
const memoryDB = Object.keys(tables).reduce((acc, key) => {
|
|
1083
|
+
acc[key] = [];
|
|
1084
|
+
return acc;
|
|
1085
|
+
}, {});
|
|
1086
|
+
if (options.logger && options.logger.log) options.logger.log("debug", "No database configuration provided. Using memory adapter in development");
|
|
1087
|
+
else _faire_auth_core_env.logger.debug("No database configuration provided. Using memory adapter in development");
|
|
1088
|
+
return patchAdapterTransaction(require_adapters_memory_adapter_index.memoryAdapter(memoryDB)(options));
|
|
1089
|
+
}
|
|
1090
|
+
if (typeof options.database === "function") return patchAdapterTransaction(options.database(options));
|
|
1091
|
+
const adapter = require_adapters_kysely_adapter_index.createKyselyAdapter(options);
|
|
1092
|
+
const checkKysely = () => {
|
|
1093
|
+
if (!adapter.kysely) throw new _faire_auth_core_error.FaireAuthError("Failed to initialize database adapter");
|
|
1094
|
+
return adapter.kysely;
|
|
1095
|
+
};
|
|
1096
|
+
return patchAdapterTransaction(require_adapters_kysely_adapter_index.kyselyAdapter("initialize" in adapter ? adapter.initialize().then(checkKysely) : checkKysely(), {
|
|
1097
|
+
type: adapter.databaseType ?? "sqlite",
|
|
1098
|
+
debugLogs: "debugLogs" in options.database ? options.database.debugLogs : false,
|
|
1099
|
+
transaction: adapter.transaction
|
|
1100
|
+
})(options));
|
|
1101
|
+
}
|
|
1102
|
+
function convertToDB(fields, values) {
|
|
1103
|
+
let result = values.id ? { id: values.id } : {};
|
|
1104
|
+
for (const key in fields) {
|
|
1105
|
+
const field = fields[key];
|
|
1106
|
+
const value = values[key];
|
|
1107
|
+
if (value === void 0) continue;
|
|
1108
|
+
result[field.fieldName || key] = value;
|
|
1109
|
+
}
|
|
1110
|
+
return result;
|
|
1111
|
+
}
|
|
1112
|
+
function convertFromDB(fields, values) {
|
|
1113
|
+
if (!values) return null;
|
|
1114
|
+
let result = { id: values.id };
|
|
1115
|
+
for (const [key, value] of Object.entries(fields)) result[key] = values[value.fieldName || key];
|
|
1116
|
+
return result;
|
|
1117
|
+
}
|
|
1118
|
+
exports.convertFromDB = convertFromDB;
|
|
1119
|
+
exports.convertToDB = convertToDB;
|
|
1120
|
+
exports.createFieldAttribute = createFieldAttribute;
|
|
1121
|
+
exports.createInternalAdapter = createInternalAdapter;
|
|
1122
|
+
exports.getAdapter = getAdapter;
|
|
19
1123
|
exports.getAuthTables = require_adapter_factory.getAuthTables;
|
|
20
|
-
exports.getMigrations =
|
|
21
|
-
exports.getSchema =
|
|
22
|
-
exports.getWithHooks =
|
|
23
|
-
exports.matchType =
|
|
1124
|
+
exports.getMigrations = getMigrations;
|
|
1125
|
+
exports.getSchema = getSchema;
|
|
1126
|
+
exports.getWithHooks = getWithHooks;
|
|
1127
|
+
exports.matchType = matchType;
|
|
24
1128
|
exports.mergeSchema = require_schema.mergeSchema;
|
|
25
1129
|
exports.parseAccountInput = require_schema.parseAccountInput;
|
|
26
1130
|
exports.parseAccountOutput = require_schema.parseAccountOutput;
|
|
@@ -30,11 +1134,13 @@ exports.parseSessionInput = require_schema.parseSessionInput;
|
|
|
30
1134
|
exports.parseSessionOutput = require_schema.parseSessionOutput;
|
|
31
1135
|
exports.parseUserInput = require_schema.parseUserInput;
|
|
32
1136
|
exports.parseUserOutput = require_schema.parseUserOutput;
|
|
33
|
-
exports.toZodSchema =
|
|
34
|
-
var
|
|
35
|
-
Object.keys(
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
1137
|
+
exports.toZodSchema = toZodSchema;
|
|
1138
|
+
var _faire_auth_core_db = require("@faire-auth/core/db");
|
|
1139
|
+
Object.keys(_faire_auth_core_db).forEach(function(k) {
|
|
1140
|
+
if (k !== "default" && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, {
|
|
1141
|
+
enumerable: true,
|
|
1142
|
+
get: function() {
|
|
1143
|
+
return _faire_auth_core_db[k];
|
|
1144
|
+
}
|
|
1145
|
+
});
|
|
40
1146
|
});
|