@kyro-cms/core 0.3.2 → 0.3.4

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.
Files changed (201) hide show
  1. package/dist/{WebhookService-BznDc2AT.d.ts → WebhookService-BCpW2dyL.d.ts} +1 -1
  2. package/dist/{WebhookService-mZZ75syh.d.cts → WebhookService-DxYSFvNg.d.cts} +1 -1
  3. package/dist/api-handler.cjs +52 -0
  4. package/dist/api-handler.cjs.map +1 -0
  5. package/dist/api-handler.d.cts +9 -0
  6. package/dist/api-handler.d.ts +9 -0
  7. package/dist/api-handler.js +46 -0
  8. package/dist/api-handler.js.map +1 -0
  9. package/dist/{base-Hu6ij8sZ.d.ts → base-DvvNqnM-.d.cts} +16 -5
  10. package/dist/{base-Db9LkB1N.d.cts → base-eVegJ_Pr.d.ts} +16 -5
  11. package/dist/bootstrap-DGJ3N7SO.js +6 -0
  12. package/dist/{bootstrap-LL6O7PWO.js.map → bootstrap-DGJ3N7SO.js.map} +1 -1
  13. package/dist/bootstrap-O5UGUTYU.cjs +31 -0
  14. package/dist/{bootstrap-BMWVB2T6.cjs.map → bootstrap-O5UGUTYU.cjs.map} +1 -1
  15. package/dist/{chunk-QKOFKITP.js → chunk-2HFJUUFZ.js} +3 -11
  16. package/dist/chunk-2HFJUUFZ.js.map +1 -0
  17. package/dist/chunk-2SJATAN4.js +5514 -0
  18. package/dist/chunk-2SJATAN4.js.map +1 -0
  19. package/dist/{chunk-DIC236EW.js → chunk-342BJNBI.js} +167 -24
  20. package/dist/chunk-342BJNBI.js.map +1 -0
  21. package/dist/{chunk-OUGKLCYF.js → chunk-3AJE4SEG.js} +4 -3
  22. package/dist/chunk-3AJE4SEG.js.map +1 -0
  23. package/dist/chunk-6LPNEC6D.js +617 -0
  24. package/dist/chunk-6LPNEC6D.js.map +1 -0
  25. package/dist/{chunk-BXMWDUED.js → chunk-A4USRVTQ.js} +2 -2
  26. package/dist/chunk-A4USRVTQ.js.map +1 -0
  27. package/dist/chunk-ADLJSJSN.cjs +13 -0
  28. package/dist/chunk-ADLJSJSN.cjs.map +1 -0
  29. package/dist/chunk-ATBOUGQP.cjs +513 -0
  30. package/dist/chunk-ATBOUGQP.cjs.map +1 -0
  31. package/dist/{chunk-KB6QF4HO.js → chunk-B76I67F3.js} +246 -141
  32. package/dist/chunk-B76I67F3.js.map +1 -0
  33. package/dist/chunk-BQ2T4WRS.js +140 -0
  34. package/dist/chunk-BQ2T4WRS.js.map +1 -0
  35. package/dist/chunk-CZ3HWX2X.cjs +622 -0
  36. package/dist/chunk-CZ3HWX2X.cjs.map +1 -0
  37. package/dist/{chunk-PNBZZ76A.cjs → chunk-DAIBBBOL.cjs} +246 -140
  38. package/dist/chunk-DAIBBBOL.cjs.map +1 -0
  39. package/dist/{chunk-U74F3YZU.js → chunk-DBUYB32X.js} +15 -3
  40. package/dist/chunk-DBUYB32X.js.map +1 -0
  41. package/dist/chunk-DLHUQO25.cjs +1746 -0
  42. package/dist/chunk-DLHUQO25.cjs.map +1 -0
  43. package/dist/{chunk-GE5DMB44.js → chunk-E3BZLMX6.js} +55 -49
  44. package/dist/chunk-E3BZLMX6.js.map +1 -0
  45. package/dist/{chunk-44BF6ALS.cjs → chunk-H4XCAPA6.cjs} +55 -49
  46. package/dist/chunk-H4XCAPA6.cjs.map +1 -0
  47. package/dist/{chunk-VIONYQ2K.cjs → chunk-IBG6V56E.cjs} +16 -32
  48. package/dist/chunk-IBG6V56E.cjs.map +1 -0
  49. package/dist/{chunk-LIJVWQKU.cjs → chunk-IX3ABYKZ.cjs} +43 -31
  50. package/dist/chunk-IX3ABYKZ.cjs.map +1 -0
  51. package/dist/chunk-JYGIFBBS.cjs +146 -0
  52. package/dist/chunk-JYGIFBBS.cjs.map +1 -0
  53. package/dist/{chunk-42JPONZU.cjs → chunk-K7JPTH3G.cjs} +17 -16
  54. package/dist/chunk-K7JPTH3G.cjs.map +1 -0
  55. package/dist/{chunk-RLTG4YZM.cjs → chunk-KOCTZKPV.cjs} +2 -2
  56. package/dist/chunk-KOCTZKPV.cjs.map +1 -0
  57. package/dist/chunk-MMYAIYHJ.cjs +5538 -0
  58. package/dist/chunk-MMYAIYHJ.cjs.map +1 -0
  59. package/dist/{chunk-EWP5AT6A.cjs → chunk-N4H37VN4.cjs} +2 -11
  60. package/dist/chunk-N4H37VN4.cjs.map +1 -0
  61. package/dist/chunk-P2YW545G.js +11 -0
  62. package/dist/chunk-P2YW545G.js.map +1 -0
  63. package/dist/chunk-Q23JB3KL.js +488 -0
  64. package/dist/chunk-Q23JB3KL.js.map +1 -0
  65. package/dist/{chunk-E5X75WNB.js → chunk-QXIQWPAP.js} +14 -30
  66. package/dist/chunk-QXIQWPAP.js.map +1 -0
  67. package/dist/chunk-R3XIBBAW.cjs +34 -0
  68. package/dist/chunk-R3XIBBAW.cjs.map +1 -0
  69. package/dist/{chunk-KWGNR4HM.js → chunk-REK7AYOC.js} +82 -9
  70. package/dist/chunk-REK7AYOC.js.map +1 -0
  71. package/dist/chunk-RGIQKTZ7.js +68 -0
  72. package/dist/chunk-RGIQKTZ7.js.map +1 -0
  73. package/dist/chunk-RYDGMBIG.js +1737 -0
  74. package/dist/chunk-RYDGMBIG.js.map +1 -0
  75. package/dist/chunk-SDMNUYVU.js +30 -0
  76. package/dist/chunk-SDMNUYVU.js.map +1 -0
  77. package/dist/chunk-VEI5KQVC.cjs +1246 -0
  78. package/dist/chunk-VEI5KQVC.cjs.map +1 -0
  79. package/dist/{chunk-FTSSDDZQ.cjs → chunk-VJT6P4N6.cjs} +82 -9
  80. package/dist/chunk-VJT6P4N6.cjs.map +1 -0
  81. package/dist/{chunk-HT6VE4NW.cjs → chunk-W3KPQX7V.cjs} +168 -25
  82. package/dist/chunk-W3KPQX7V.cjs.map +1 -0
  83. package/dist/{chunk-LTRCYJAG.js → chunk-WOWUL7ZY.js} +3 -2
  84. package/dist/chunk-WOWUL7ZY.js.map +1 -0
  85. package/dist/{chunk-7YITG2US.cjs → chunk-WQBRWOQT.cjs} +3 -2
  86. package/dist/chunk-WQBRWOQT.cjs.map +1 -0
  87. package/dist/chunk-X3CU27OO.cjs +78 -0
  88. package/dist/chunk-X3CU27OO.cjs.map +1 -0
  89. package/dist/chunk-XIXGJGQW.js +1228 -0
  90. package/dist/chunk-XIXGJGQW.js.map +1 -0
  91. package/dist/cli/index.cjs +2 -2
  92. package/dist/cli/index.js +2 -2
  93. package/dist/client.cjs +23 -13
  94. package/dist/client.d.cts +4 -2
  95. package/dist/client.d.ts +4 -2
  96. package/dist/client.js +3 -1
  97. package/dist/drizzle/index.cjs +20 -19
  98. package/dist/drizzle/index.d.cts +28 -7
  99. package/dist/drizzle/index.d.ts +28 -7
  100. package/dist/drizzle/index.js +5 -4
  101. package/dist/fields/index.cjs +105 -0
  102. package/dist/fields/index.cjs.map +1 -0
  103. package/dist/fields/index.d.cts +27 -0
  104. package/dist/fields/index.d.ts +27 -0
  105. package/dist/fields/index.js +4 -0
  106. package/dist/fields/index.js.map +1 -0
  107. package/dist/graphql/index.cjs +4 -3
  108. package/dist/graphql/index.d.cts +3 -2
  109. package/dist/graphql/index.d.ts +3 -2
  110. package/dist/graphql/index.js +2 -1
  111. package/dist/{index-Ci6r4xnN.d.ts → index-CLp-DRKA.d.ts} +2 -1
  112. package/dist/{index-11MDNKce.d.cts → index-DfO7G4kN.d.cts} +2 -1
  113. package/dist/index.cjs +2621 -6672
  114. package/dist/index.cjs.map +1 -1
  115. package/dist/index.d.cts +136 -47
  116. package/dist/index.d.ts +136 -47
  117. package/dist/index.js +2333 -6546
  118. package/dist/index.js.map +1 -1
  119. package/dist/integration.cjs +68 -0
  120. package/dist/integration.cjs.map +1 -0
  121. package/dist/integration.d.cts +27 -0
  122. package/dist/integration.d.ts +27 -0
  123. package/dist/integration.js +61 -0
  124. package/dist/integration.js.map +1 -0
  125. package/dist/mongodb/index.cjs +4 -4
  126. package/dist/mongodb/index.d.cts +20 -6
  127. package/dist/mongodb/index.d.ts +20 -6
  128. package/dist/mongodb/index.js +2 -2
  129. package/dist/postgres-auth-adapter-7F3ECO7I.js +5 -0
  130. package/dist/{postgres-auth-adapter-OTRWSTT5.js.map → postgres-auth-adapter-7F3ECO7I.js.map} +1 -1
  131. package/dist/postgres-auth-adapter-Z463NYJZ.cjs +14 -0
  132. package/dist/{postgres-auth-adapter-EVRPO7BQ.cjs.map → postgres-auth-adapter-Z463NYJZ.cjs.map} +1 -1
  133. package/dist/redis-adapter-LPUWLE4Y.cjs +13 -0
  134. package/dist/{redis-adapter-E7PMN5HW.cjs.map → redis-adapter-LPUWLE4Y.cjs.map} +1 -1
  135. package/dist/redis-adapter-THYDCGQR.js +4 -0
  136. package/dist/{redis-adapter-HOO67RBQ.js.map → redis-adapter-THYDCGQR.js.map} +1 -1
  137. package/dist/rest/index.cjs +8 -5
  138. package/dist/rest/index.d.cts +6 -3
  139. package/dist/rest/index.d.ts +6 -3
  140. package/dist/rest/index.js +6 -3
  141. package/dist/{schema-CNB2DDTX.js → schema-6Q4W6AE6.js} +3 -3
  142. package/dist/{schema-CNB2DDTX.js.map → schema-6Q4W6AE6.js.map} +1 -1
  143. package/dist/{schema-Y777CQQS.cjs → schema-TIYTCIKX.cjs} +14 -14
  144. package/dist/{schema-Y777CQQS.cjs.map → schema-TIYTCIKX.cjs.map} +1 -1
  145. package/dist/templates/index.cjs +27 -23
  146. package/dist/templates/index.d.cts +8 -2
  147. package/dist/templates/index.d.ts +8 -2
  148. package/dist/templates/index.js +1 -1
  149. package/dist/trpc/index.cjs +12 -11
  150. package/dist/trpc/index.d.cts +3 -2
  151. package/dist/trpc/index.d.ts +3 -2
  152. package/dist/trpc/index.js +3 -2
  153. package/dist/{types-kGfsGdos.d.cts → types-Bs1up4yP.d.ts} +76 -244
  154. package/dist/{types-1u353OHN.d.ts → types-Da83JLDk.d.cts} +6 -2
  155. package/dist/{types-1u353OHN.d.cts → types-Da83JLDk.d.ts} +6 -2
  156. package/dist/{types-kGfsGdos.d.ts → types-J3R9nVsZ.d.cts} +76 -244
  157. package/dist/types-VtjUxIMp.d.cts +246 -0
  158. package/dist/types-VtjUxIMp.d.ts +246 -0
  159. package/package.json +16 -9
  160. package/dist/bootstrap-BMWVB2T6.cjs +0 -31
  161. package/dist/bootstrap-LL6O7PWO.js +0 -6
  162. package/dist/chunk-42JPONZU.cjs.map +0 -1
  163. package/dist/chunk-44BF6ALS.cjs.map +0 -1
  164. package/dist/chunk-4M5PHMUE.cjs +0 -947
  165. package/dist/chunk-4M5PHMUE.cjs.map +0 -1
  166. package/dist/chunk-6MSSF46R.js +0 -941
  167. package/dist/chunk-6MSSF46R.js.map +0 -1
  168. package/dist/chunk-7YITG2US.cjs.map +0 -1
  169. package/dist/chunk-BTOE3VUK.js +0 -330
  170. package/dist/chunk-BTOE3VUK.js.map +0 -1
  171. package/dist/chunk-BXMWDUED.js.map +0 -1
  172. package/dist/chunk-DIC236EW.js.map +0 -1
  173. package/dist/chunk-E5X75WNB.js.map +0 -1
  174. package/dist/chunk-E63IF3MD.cjs +0 -951
  175. package/dist/chunk-E63IF3MD.cjs.map +0 -1
  176. package/dist/chunk-EWP5AT6A.cjs.map +0 -1
  177. package/dist/chunk-FTSSDDZQ.cjs.map +0 -1
  178. package/dist/chunk-GE5DMB44.js.map +0 -1
  179. package/dist/chunk-GVFB5C6O.cjs +0 -345
  180. package/dist/chunk-GVFB5C6O.cjs.map +0 -1
  181. package/dist/chunk-HT6VE4NW.cjs.map +0 -1
  182. package/dist/chunk-HVSQDZZJ.cjs +0 -765
  183. package/dist/chunk-HVSQDZZJ.cjs.map +0 -1
  184. package/dist/chunk-HYC4GNHX.js +0 -758
  185. package/dist/chunk-HYC4GNHX.js.map +0 -1
  186. package/dist/chunk-KB6QF4HO.js.map +0 -1
  187. package/dist/chunk-KWGNR4HM.js.map +0 -1
  188. package/dist/chunk-LIJVWQKU.cjs.map +0 -1
  189. package/dist/chunk-LTRCYJAG.js.map +0 -1
  190. package/dist/chunk-OUGKLCYF.js.map +0 -1
  191. package/dist/chunk-PNBZZ76A.cjs.map +0 -1
  192. package/dist/chunk-QKOFKITP.js.map +0 -1
  193. package/dist/chunk-RLTG4YZM.cjs.map +0 -1
  194. package/dist/chunk-RRYXQMZG.js +0 -935
  195. package/dist/chunk-RRYXQMZG.js.map +0 -1
  196. package/dist/chunk-U74F3YZU.js.map +0 -1
  197. package/dist/chunk-VIONYQ2K.cjs.map +0 -1
  198. package/dist/postgres-auth-adapter-EVRPO7BQ.cjs +0 -14
  199. package/dist/postgres-auth-adapter-OTRWSTT5.js +0 -5
  200. package/dist/redis-adapter-E7PMN5HW.cjs +0 -13
  201. package/dist/redis-adapter-HOO67RBQ.js +0 -4
@@ -0,0 +1,1737 @@
1
+ import { settings } from './chunk-YT7HXXVN.js';
2
+ import bcrypt from 'bcryptjs';
3
+ import { randomBytes } from 'crypto';
4
+ import { mkdirSync } from 'fs';
5
+ import { dirname } from 'path';
6
+
7
+ // src/config/ConfigService.ts
8
+ var ConfigService = class _ConfigService {
9
+ db;
10
+ cache = {};
11
+ static SENSITIVE_KEYS = [
12
+ "storage.s3.secret_access_key",
13
+ "storage.r2.secret_access_key",
14
+ "storage.gcs.private_key",
15
+ "storage.backblaze.application_key",
16
+ "storage.wasabi.secret_access_key",
17
+ "storage.ftp.password",
18
+ "storage.bunny.api_key",
19
+ "storage.cloudinary.api_secret",
20
+ "storage.imgix.sign_key",
21
+ "email.smtp.pass",
22
+ "auth.jwt_secret",
23
+ "auth.github_secret",
24
+ "auth.google_secret",
25
+ "auth.app_secret",
26
+ "database.url",
27
+ "redis.url",
28
+ "auth.admin_password"
29
+ ];
30
+ constructor(db) {
31
+ this.db = db;
32
+ }
33
+ /**
34
+ * Initialize the service by loading all settings from the database
35
+ */
36
+ async load() {
37
+ try {
38
+ if (typeof this.db?.select === "function") {
39
+ const allSettings = await this.db.select().from(settings);
40
+ this.cache = allSettings.reduce((acc, row) => {
41
+ acc[row.key] = row.value;
42
+ return acc;
43
+ }, {});
44
+ } else {
45
+ await this.loadFromGlobals();
46
+ }
47
+ } catch (error) {
48
+ console.warn(
49
+ "ConfigService: Could not load settings from database, using environment fallbacks.",
50
+ error
51
+ );
52
+ }
53
+ }
54
+ /**
55
+ * Load settings from the _globals_storage-settings table (SQLite fallback)
56
+ * Maps nested global structure to flat key-value cache
57
+ */
58
+ async loadFromGlobals() {
59
+ try {
60
+ const row = this.db.prepare(`SELECT * FROM "_globals_storage-settings" LIMIT 1`).get();
61
+ if (!row) return;
62
+ const parseJSON = (val) => {
63
+ if (!val) return null;
64
+ if (typeof val === "string") {
65
+ try {
66
+ return JSON.parse(val);
67
+ } catch {
68
+ return null;
69
+ }
70
+ }
71
+ return val;
72
+ };
73
+ const provider = row.provider || "local";
74
+ this.cache["storage.type"] = provider === "aws" ? "s3" : provider;
75
+ if (provider === "local") {
76
+ const local = parseJSON(row.local);
77
+ this.cache["storage.local.dir"] = local?.uploadDir || "./public/uploads";
78
+ this.cache["storage.local.url"] = local?.baseUrl || "/uploads";
79
+ }
80
+ if (provider === "aws") {
81
+ const aws = parseJSON(row.aws);
82
+ this.cache["storage.s3.bucket"] = aws?.bucket || "";
83
+ this.cache["storage.s3.region"] = aws?.region || "us-east-1";
84
+ this.cache["storage.s3.access_key_id"] = aws?.accessKeyId || "";
85
+ this.cache["storage.s3.secret_access_key"] = aws?.secretAccessKey || "";
86
+ this.cache["storage.s3.endpoint"] = aws?.endpoint || "";
87
+ this.cache["storage.s3.cdn_url"] = aws?.cdnUrl || "";
88
+ this.cache["storage.s3.prefix"] = aws?.prefix || "";
89
+ }
90
+ if (provider === "r2") {
91
+ const r2 = parseJSON(row.r2);
92
+ this.cache["storage.r2.account_id"] = r2?.accountId || "";
93
+ this.cache["storage.r2.access_key_id"] = r2?.accessKeyId || "";
94
+ this.cache["storage.r2.secret_access_key"] = r2?.secretAccessKey || "";
95
+ this.cache["storage.r2.bucket"] = r2?.bucket || "";
96
+ this.cache["storage.r2.cdn_url"] = r2?.cdnUrl || "";
97
+ this.cache["storage.r2.prefix"] = r2?.prefix || "";
98
+ }
99
+ if (provider === "cloudinary") {
100
+ const cloudinary = parseJSON(row.cloudinary);
101
+ this.cache["storage.cloudinary.cloud_name"] = cloudinary?.cloudName || "";
102
+ this.cache["storage.cloudinary.api_key"] = cloudinary?.apiKey || "";
103
+ this.cache["storage.cloudinary.api_secret"] = cloudinary?.apiSecret || "";
104
+ this.cache["storage.cloudinary.folder"] = cloudinary?.folder || "";
105
+ }
106
+ if (provider === "ftp") {
107
+ const ftp = parseJSON(row.ftp);
108
+ this.cache["storage.ftp.host"] = ftp?.host || "";
109
+ this.cache["storage.ftp.port"] = String(ftp?.port || "21");
110
+ this.cache["storage.ftp.user"] = ftp?.user || "";
111
+ this.cache["storage.ftp.password"] = ftp?.password || "";
112
+ this.cache["storage.ftp.secure"] = ftp?.secure ? "true" : "false";
113
+ this.cache["storage.ftp.base_url"] = ftp?.baseUrl || "";
114
+ this.cache["storage.ftp.prefix"] = ftp?.prefix || "";
115
+ }
116
+ } catch (error) {
117
+ console.warn("ConfigService: Could not load from globals table:", error);
118
+ }
119
+ }
120
+ /**
121
+ * Get a settings value with environment fallback
122
+ */
123
+ get(key, envKey, defaultValue) {
124
+ if (this.cache[key]) return this.cache[key];
125
+ if (envKey && process.env[envKey]) return process.env[envKey];
126
+ return defaultValue;
127
+ }
128
+ /**
129
+ * Get storage configuration
130
+ */
131
+ getStorageConfig() {
132
+ return {
133
+ type: this.get("storage.type", "STORAGE_TYPE", "local"),
134
+ s3: {
135
+ bucket: this.get("storage.s3.bucket", "STORAGE_BUCKET"),
136
+ region: this.get("storage.s3.region", "STORAGE_REGION", "us-east-1"),
137
+ accessKeyId: this.get(
138
+ "storage.s3.access_key_id",
139
+ "STORAGE_ACCESS_KEY_ID"
140
+ ),
141
+ secretAccessKey: this.get(
142
+ "storage.s3.secret_access_key",
143
+ "STORAGE_SECRET_ACCESS_KEY"
144
+ ),
145
+ endpoint: this.get("storage.s3.endpoint", "STORAGE_ENDPOINT"),
146
+ cdnUrl: this.get("storage.s3.cdn_url", "STORAGE_CDN_URL"),
147
+ prefix: this.get("storage.s3.prefix", "STORAGE_PREFIX")
148
+ },
149
+ r2: {
150
+ accountId: this.get("storage.r2.account_id", "R2_ACCOUNT_ID"),
151
+ accessKeyId: this.get("storage.r2.access_key_id", "R2_ACCESS_KEY_ID"),
152
+ secretAccessKey: this.get(
153
+ "storage.r2.secret_access_key",
154
+ "R2_SECRET_ACCESS_KEY"
155
+ ),
156
+ bucket: this.get("storage.r2.bucket", "R2_BUCKET"),
157
+ cdnUrl: this.get("storage.r2.cdn_url", "R2_CDN_URL"),
158
+ prefix: this.get("storage.r2.prefix", "R2_PREFIX")
159
+ },
160
+ gcs: {
161
+ bucket: this.get("storage.gcs.bucket", "GCS_BUCKET"),
162
+ projectId: this.get("storage.gcs.project_id", "GCS_PROJECT_ID"),
163
+ clientEmail: this.get("storage.gcs.client_email", "GCS_CLIENT_EMAIL"),
164
+ privateKey: this.get("storage.gcs.private_key", "GCS_PRIVATE_KEY"),
165
+ cdnUrl: this.get("storage.gcs.cdn_url", "GCS_CDN_URL"),
166
+ prefix: this.get("storage.gcs.prefix", "GCS_PREFIX")
167
+ },
168
+ digitalocean: {
169
+ bucket: this.get("storage.digitalocean.bucket", "DO_BUCKET"),
170
+ region: this.get("storage.digitalocean.region", "DO_REGION", "nyc3"),
171
+ accessKeyId: this.get(
172
+ "storage.digitalocean.access_key_id",
173
+ "DO_ACCESS_KEY_ID"
174
+ ),
175
+ secretAccessKey: this.get(
176
+ "storage.digitalocean.secret_access_key",
177
+ "DO_SECRET_ACCESS_KEY"
178
+ ),
179
+ cdnUrl: this.get("storage.digitalocean.cdn_url", "DO_CDN_URL"),
180
+ prefix: this.get("storage.digitalocean.prefix", "DO_PREFIX")
181
+ },
182
+ backblaze: {
183
+ bucket: this.get("storage.backblaze.bucket", "BB_BUCKET"),
184
+ accountId: this.get("storage.backblaze.account_id", "BB_ACCOUNT_ID"),
185
+ applicationKeyId: this.get(
186
+ "storage.backblaze.application_key_id",
187
+ "BB_APPLICATION_KEY_ID"
188
+ ),
189
+ applicationKey: this.get(
190
+ "storage.backblaze.application_key",
191
+ "BB_APPLICATION_KEY"
192
+ ),
193
+ cdnUrl: this.get("storage.backblaze.cdn_url", "BB_CDN_URL"),
194
+ prefix: this.get("storage.backblaze.prefix", "BB_PREFIX")
195
+ },
196
+ wasabi: {
197
+ bucket: this.get("storage.wasabi.bucket", "WASABI_BUCKET"),
198
+ region: this.get("storage.wasabi.region", "WASABI_REGION", "us-east-1"),
199
+ accessKeyId: this.get(
200
+ "storage.wasabi.access_key_id",
201
+ "WASABI_ACCESS_KEY_ID"
202
+ ),
203
+ secretAccessKey: this.get(
204
+ "storage.wasabi.secret_access_key",
205
+ "WASABI_SECRET_ACCESS_KEY"
206
+ ),
207
+ cdnUrl: this.get("storage.wasabi.cdn_url", "WASABI_CDN_URL"),
208
+ prefix: this.get("storage.wasabi.prefix", "WASABI_PREFIX")
209
+ },
210
+ bunny: {
211
+ storageZone: this.get(
212
+ "storage.bunny.storage_zone",
213
+ "BUNNY_STORAGE_ZONE"
214
+ ),
215
+ apiKey: this.get("storage.bunny.api_key", "BUNNY_API_KEY"),
216
+ cdnUrl: this.get("storage.bunny.cdn_url", "BUNNY_CDN_URL"),
217
+ prefix: this.get("storage.bunny.prefix", "BUNNY_PREFIX")
218
+ },
219
+ ftp: {
220
+ host: this.get("storage.ftp.host", "FTP_HOST"),
221
+ port: parseInt(this.get("storage.ftp.port", "FTP_PORT", "21"), 10),
222
+ user: this.get("storage.ftp.user", "FTP_USER"),
223
+ password: this.get("storage.ftp.password", "FTP_PASSWORD"),
224
+ secure: this.get("storage.ftp.secure", "FTP_SECURE") === "true",
225
+ baseUrl: this.get("storage.ftp.base_url", "FTP_BASE_URL"),
226
+ prefix: this.get("storage.ftp.prefix", "FTP_PREFIX")
227
+ },
228
+ cloudinary: {
229
+ cloudName: this.get(
230
+ "storage.cloudinary.cloud_name",
231
+ "CLOUDINARY_CLOUD_NAME"
232
+ ),
233
+ apiKey: this.get("storage.cloudinary.api_key", "CLOUDINARY_API_KEY"),
234
+ apiSecret: this.get(
235
+ "storage.cloudinary.api_secret",
236
+ "CLOUDINARY_API_SECRET"
237
+ ),
238
+ folder: this.get("storage.cloudinary.folder", "CLOUDINARY_FOLDER")
239
+ },
240
+ imgix: {
241
+ domain: this.get("storage.imgix.domain", "IMGIX_DOMAIN"),
242
+ signKey: this.get("storage.imgix.sign_key", "IMGIX_SIGN_KEY")
243
+ },
244
+ local: {
245
+ uploadDir: this.get("storage.local.dir", "STORAGE_LOCAL_DIR"),
246
+ baseUrl: this.get("storage.local.url", "STORAGE_LOCAL_URL", "/uploads")
247
+ }
248
+ };
249
+ }
250
+ /**
251
+ * Get email configuration
252
+ */
253
+ getEmailConfig() {
254
+ return {
255
+ provider: this.get("email.provider", "EMAIL_PROVIDER", "smtp"),
256
+ host: this.get("email.smtp.host", "SMTP_HOST"),
257
+ port: parseInt(this.get("email.smtp.port", "SMTP_PORT", "587"), 10),
258
+ secure: this.get("email.smtp.secure", "SMTP_SECURE") === "true",
259
+ user: this.get("email.smtp.user", "SMTP_USER"),
260
+ pass: this.get("email.smtp.pass", "SMTP_PASS"),
261
+ from: this.get("email.smtp.from", "SMTP_FROM", "noreply@example.com"),
262
+ fromName: this.get("email.smtp.from_name", "SMTP_FROM_NAME", "Kyro CMS"),
263
+ replyTo: this.get("email.smtp.reply_to", "SMTP_REPLY_TO")
264
+ };
265
+ }
266
+ /**
267
+ * Mask sensitive values for display
268
+ */
269
+ maskSensitive(key, value) {
270
+ if (!value) return value;
271
+ if (_ConfigService.SENSITIVE_KEYS.includes(key)) {
272
+ return "********";
273
+ }
274
+ return value;
275
+ }
276
+ /**
277
+ * Update a setting in the database
278
+ */
279
+ async set(key, value, description) {
280
+ await this.db.insert(settings).values({
281
+ key,
282
+ value,
283
+ description,
284
+ updatedAt: /* @__PURE__ */ new Date()
285
+ }).onConflictDoUpdate({
286
+ target: [settings.key],
287
+ set: { value, description, updatedAt: /* @__PURE__ */ new Date() }
288
+ });
289
+ this.cache[key] = value;
290
+ }
291
+ };
292
+
293
+ // src/auth/nodemailer-transport.ts
294
+ var defaultTemplates = {
295
+ verifyEmail: (link, userName = "User") => ({
296
+ subject: "Verify your email address",
297
+ html: `
298
+ <!DOCTYPE html>
299
+ <html>
300
+ <head>
301
+ <meta charset="utf-8">
302
+ <meta name="viewport" content="width=device-width, initial-scale=1">
303
+ <title>Verify Email</title>
304
+ <style>
305
+ body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; line-height: 1.6; color: #333; }
306
+ .container { max-width: 600px; margin: 0 auto; padding: 20px; }
307
+ .button { display: inline-block; padding: 12px 24px; background: #0b1222; color: white; text-decoration: none; border-radius: 6px; font-weight: 600; }
308
+ .footer { margin-top: 30px; font-size: 12px; color: #666; }
309
+ </style>
310
+ </head>
311
+ <body>
312
+ <div class="container">
313
+ <h1>Welcome, ${userName}!</h1>
314
+ <p>Please verify your email address by clicking the button below:</p>
315
+ <p style="text-align: center; margin: 30px 0;">
316
+ <a href="${link}" class="button">Verify Email</a>
317
+ </p>
318
+ <p>Or copy and paste this link into your browser:</p>
319
+ <p style="word-break: break-all; color: #666;">${link}</p>
320
+ <p>This link will expire in 24 hours.</p>
321
+ <div class="footer">
322
+ <p>If you didn't create an account, you can safely ignore this email.</p>
323
+ </div>
324
+ </div>
325
+ </body>
326
+ </html>
327
+ `,
328
+ text: `Welcome ${userName}!
329
+
330
+ Please verify your email by clicking this link: ${link}
331
+
332
+ This link will expire in 24 hours.
333
+
334
+ If you didn't create an account, you can safely ignore this email.`
335
+ }),
336
+ resetPassword: (link, userName = "User") => ({
337
+ subject: "Reset your password",
338
+ html: `
339
+ <!DOCTYPE html>
340
+ <html>
341
+ <head>
342
+ <meta charset="utf-8">
343
+ <meta name="viewport" content="width=device-width, initial-scale=1">
344
+ <title>Reset Password</title>
345
+ <style>
346
+ body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; line-height: 1.6; color: #333; }
347
+ .container { max-width: 600px; margin: 0 auto; padding: 20px; }
348
+ .button { display: inline-block; padding: 12px 24px; background: #dc2626; color: white; text-decoration: none; border-radius: 6px; font-weight: 600; }
349
+ .warning { background: #fef3c7; border: 1px solid #f59e0b; padding: 12px; border-radius: 6px; margin: 20px 0; }
350
+ .footer { margin-top: 30px; font-size: 12px; color: #666; }
351
+ </style>
352
+ </head>
353
+ <body>
354
+ <div class="container">
355
+ <h1>Password Reset Request</h1>
356
+ <p>Hello ${userName},</p>
357
+ <p>We received a request to reset your password. Click the button below to create a new password:</p>
358
+ <p style="text-align: center; margin: 30px 0;">
359
+ <a href="${link}" class="button">Reset Password</a>
360
+ </p>
361
+ <p>Or copy and paste this link into your browser:</p>
362
+ <p style="word-break: break-all; color: #666;">${link}</p>
363
+ <div class="warning">
364
+ <strong>\u26A0\uFE0F Important:</strong> This link will expire in 1 hour. If you didn't request a password reset, please ignore this email or contact support if you have concerns.
365
+ </div>
366
+ <div class="footer">
367
+ <p>For security reasons, please don't share this email with anyone.</p>
368
+ </div>
369
+ </div>
370
+ </body>
371
+ </html>
372
+ `,
373
+ text: `Password Reset Request
374
+
375
+ Hello ${userName},
376
+
377
+ We received a request to reset your password. Click this link to create a new password: ${link}
378
+
379
+ This link will expire in 1 hour.
380
+
381
+ If you didn't request a password reset, please ignore this email.`
382
+ }),
383
+ welcome: (userName = "User") => ({
384
+ subject: "Welcome to Kyro CMS",
385
+ html: `
386
+ <!DOCTYPE html>
387
+ <html>
388
+ <head>
389
+ <meta charset="utf-8">
390
+ <meta name="viewport" content="width=device-width, initial-scale=1">
391
+ <title>Welcome</title>
392
+ <style>
393
+ body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; line-height: 1.6; color: #333; }
394
+ .container { max-width: 600px; margin: 0 auto; padding: 20px; }
395
+ .button { display: inline-block; padding: 12px 24px; background: #0b1222; color: white; text-decoration: none; border-radius: 6px; font-weight: 600; }
396
+ </style>
397
+ </head>
398
+ <body>
399
+ <div class="container">
400
+ <h1>Welcome to Kyro CMS, ${userName}!</h1>
401
+ <p>Your account has been created successfully.</p>
402
+ <p>You can now:</p>
403
+ <ul>
404
+ <li>Manage your content collections</li>
405
+ <li>Upload and organize media</li>
406
+ <li>Configure settings</li>
407
+ <li>And much more...</li>
408
+ </ul>
409
+ <p style="text-align: center; margin: 30px 0;">
410
+ <a href="#" class="button">Get Started</a>
411
+ </p>
412
+ <p>If you have any questions, feel free to reach out to our support team.</p>
413
+ </div>
414
+ </body>
415
+ </html>
416
+ `,
417
+ text: `Welcome to Kyro CMS, ${userName}!
418
+
419
+ Your account has been created successfully.
420
+
421
+ You can now:
422
+ - Manage your content collections
423
+ - Upload and organize media
424
+ - Configure settings
425
+ - And much more...
426
+
427
+ Get started by logging into your dashboard.`
428
+ }),
429
+ accountLocked: (attempts, duration, userName = "User") => ({
430
+ subject: "Account Security Alert - Account Locked",
431
+ html: `
432
+ <!DOCTYPE html>
433
+ <html>
434
+ <head>
435
+ <meta charset="utf-8">
436
+ <meta name="viewport" content="width=device-width, initial-scale=1">
437
+ <title>Account Locked</title>
438
+ <style>
439
+ body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; line-height: 1.6; color: #333; }
440
+ .container { max-width: 600px; margin: 0 auto; padding: 20px; }
441
+ .alert { background: #fef2f2; border: 1px solid #ef4444; padding: 16px; border-radius: 8px; margin: 20px 0; }
442
+ .footer { margin-top: 30px; font-size: 12px; color: #666; }
443
+ </style>
444
+ </head>
445
+ <body>
446
+ <div class="container">
447
+ <h1>Account Security Alert</h1>
448
+ <p>Hello ${userName},</p>
449
+ <div class="alert">
450
+ <p><strong>\u26A0\uFE0F Your account has been temporarily locked due to multiple failed login attempts.</strong></p>
451
+ <p>Failed attempts: ${attempts}</p>
452
+ <p>Lockout duration: ${Math.round(duration / 6e4)} minutes</p>
453
+ </div>
454
+ <p>Your account will automatically unlock after the lockout period expires.</p>
455
+ <p>If this wasn't you, we recommend:</p>
456
+ <ul>
457
+ <li>Using a strong, unique password</li>
458
+ <li>Enabling two-factor authentication (coming soon)</li>
459
+ <li>Reviewing your recent account activity</li>
460
+ </ul>
461
+ <div class="footer">
462
+ <p>If you need immediate assistance, please contact support.</p>
463
+ </div>
464
+ </div>
465
+ </body>
466
+ </html>
467
+ `,
468
+ text: `Account Security Alert
469
+
470
+ Hello ${userName},
471
+
472
+ Your account has been temporarily locked due to multiple failed login attempts (${attempts}).
473
+
474
+ Lockout duration: ${Math.round(duration / 6e4)} minutes
475
+
476
+ Your account will automatically unlock after this period.
477
+
478
+ If this wasn't you, we recommend using a strong, unique password.`
479
+ }),
480
+ passwordChanged: (userName = "User") => ({
481
+ subject: "Your password has been changed",
482
+ html: `
483
+ <!DOCTYPE html>
484
+ <html>
485
+ <head>
486
+ <meta charset="utf-8">
487
+ <meta name="viewport" content="width=device-width, initial-scale=1">
488
+ <title>Password Changed</title>
489
+ <style>
490
+ body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; line-height: 1.6; color: #333; }
491
+ .container { max-width: 600px; margin: 0 auto; padding: 20px; }
492
+ .info { background: #f0fdf4; border: 1px solid #22c55e; padding: 12px; border-radius: 6px; margin: 20px 0; }
493
+ </style>
494
+ </head>
495
+ <body>
496
+ <div class="container">
497
+ <h1>Password Changed</h1>
498
+ <p>Hello ${userName},</p>
499
+ <div class="info">
500
+ <p>Your password was recently changed.</p>
501
+ </div>
502
+ <p>If you did this, you can safely ignore this email.</p>
503
+ <p><strong>If you didn't change your password</strong>, please contact our support team immediately as your account may have been compromised.</p>
504
+ </div>
505
+ </body>
506
+ </html>
507
+ `,
508
+ text: `Password Changed
509
+
510
+ Hello ${userName},
511
+
512
+ Your password was recently changed.
513
+
514
+ If you did this, you can safely ignore this email.
515
+
516
+ If you didn't change your password, please contact support immediately.`
517
+ }),
518
+ newLogin: (location, time, userName = "User") => ({
519
+ subject: "New login to your account",
520
+ html: `
521
+ <!DOCTYPE html>
522
+ <html>
523
+ <head>
524
+ <meta charset="utf-8">
525
+ <meta name="viewport" content="width=device-width, initial-scale=1">
526
+ <title>New Login</title>
527
+ <style>
528
+ body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; line-height: 1.6; color: #333; }
529
+ .container { max-width: 600px; margin: 0 auto; padding: 20px; }
530
+ .info-box { background: #f8fafc; border: 1px solid #e2e8f0; padding: 16px; border-radius: 8px; margin: 20px 0; }
531
+ .footer { margin-top: 30px; font-size: 12px; color: #666; }
532
+ </style>
533
+ </head>
534
+ <body>
535
+ <div class="container">
536
+ <h1>New Login Detected</h1>
537
+ <p>Hello ${userName},</p>
538
+ <p>We detected a new login to your account:</p>
539
+ <div class="info-box">
540
+ <p><strong>Location:</strong> ${location}</p>
541
+ <p><strong>Time:</strong> ${time}</p>
542
+ </div>
543
+ <p><strong>If this was you</strong>, no action is needed.</p>
544
+ <p><strong>If this wasn't you</strong>, your account may be compromised. Please:</p>
545
+ <ol>
546
+ <li>Change your password immediately</li>
547
+ <li>Review your recent account activity</li>
548
+ <li>Contact support if needed</li>
549
+ </ol>
550
+ <div class="footer">
551
+ <p>This is an automated security notification.</p>
552
+ </div>
553
+ </div>
554
+ </body>
555
+ </html>
556
+ `,
557
+ text: `New Login Detected
558
+
559
+ Hello ${userName},
560
+
561
+ We detected a new login to your account:
562
+
563
+ Location: ${location}
564
+ Time: ${time}
565
+
566
+ If this wasn't you, please change your password immediately and contact support.`
567
+ })
568
+ };
569
+ var EmailTransport = class _EmailTransport {
570
+ transporter;
571
+ config;
572
+ templates;
573
+ transporterInitialized = false;
574
+ constructor(config, templates) {
575
+ this.config = config;
576
+ this.templates = { ...defaultTemplates, ...templates };
577
+ }
578
+ async ensureTransporter() {
579
+ if (this.transporterInitialized) {
580
+ return this.transporter;
581
+ }
582
+ const { default: nodemailer } = await import('nodemailer');
583
+ if (this.config.provider === "smtp" && this.config.smtp) {
584
+ this.transporter = nodemailer.createTransport({
585
+ host: this.config.smtp.host,
586
+ port: this.config.smtp.port,
587
+ secure: this.config.smtp.secure,
588
+ auth: this.config.smtp.auth
589
+ });
590
+ } else if (this.config.provider === "ses" && this.config.ses) {
591
+ this.transporter = nodemailer.createTransport({
592
+ host: `email-smtp.${this.config.ses.region}.amazonaws.com`,
593
+ port: 587,
594
+ secure: false,
595
+ auth: {
596
+ user: this.config.ses.accessKeyId,
597
+ pass: this.config.ses.secretAccessKey
598
+ }
599
+ });
600
+ }
601
+ this.transporterInitialized = true;
602
+ return this.transporter;
603
+ }
604
+ async send(options) {
605
+ const { provider, from, fromName, replyTo: configReplyTo } = this.config;
606
+ const fromFull = `"${fromName || "Kyro CMS"}" <${from}>`;
607
+ const replyTo = options.replyTo || configReplyTo;
608
+ console.log(`[EmailTransport] Sending email via ${provider}...`);
609
+ console.log(
610
+ `[EmailTransport] To: ${Array.isArray(options.to) ? options.to.join(", ") : options.to}`
611
+ );
612
+ console.log(`[EmailTransport] Subject: ${options.subject}`);
613
+ try {
614
+ let result;
615
+ switch (provider) {
616
+ case "smtp":
617
+ case "ses":
618
+ {
619
+ const transporter = await this.ensureTransporter();
620
+ if (!transporter)
621
+ throw new Error(`${provider} transporter not initialized`);
622
+ result = await transporter.sendMail({
623
+ from: fromFull,
624
+ to: Array.isArray(options.to) ? options.to.join(", ") : options.to,
625
+ subject: options.subject,
626
+ html: options.html,
627
+ text: options.text,
628
+ replyTo
629
+ });
630
+ }
631
+ break;
632
+ case "resend":
633
+ result = await this.sendViaResend(fromFull, options, replyTo);
634
+ break;
635
+ case "sendgrid":
636
+ result = await this.sendViaSendGrid(fromFull, options, replyTo);
637
+ break;
638
+ case "mailgun":
639
+ result = await this.sendViaMailgun(fromFull, options, replyTo);
640
+ break;
641
+ default:
642
+ throw new Error(`Unsupported email provider: ${provider}`);
643
+ }
644
+ console.log(`[EmailTransport] Success! Provider response received.`);
645
+ return result;
646
+ } catch (error) {
647
+ console.error(`[EmailTransport] FAILED to send email:`, error.message);
648
+ if (error.response) {
649
+ console.error(
650
+ `[EmailTransport] Provider Error Detail:`,
651
+ JSON.stringify(error.response, null, 2)
652
+ );
653
+ }
654
+ throw error;
655
+ }
656
+ }
657
+ async sendViaResend(from, options, replyTo) {
658
+ const apiKey = this.config.resend?.apiKey;
659
+ if (!apiKey) throw new Error("Resend API Key missing");
660
+ const body = {
661
+ from,
662
+ to: options.to,
663
+ subject: options.subject,
664
+ html: options.html,
665
+ text: options.text,
666
+ reply_to: replyTo
667
+ };
668
+ console.log(`[EmailTransport] Calling Resend API...`);
669
+ const resp = await fetch("https://api.resend.com/emails", {
670
+ method: "POST",
671
+ headers: {
672
+ Authorization: `Bearer ${apiKey}`,
673
+ "Content-Type": "application/json"
674
+ },
675
+ body: JSON.stringify(body)
676
+ });
677
+ if (!resp.ok) {
678
+ const error = await resp.json();
679
+ throw new Error(`Resend Error: ${JSON.stringify(error)}`);
680
+ }
681
+ return resp.json();
682
+ }
683
+ async sendViaSendGrid(from, options, replyTo) {
684
+ const apiKey = this.config.sendgrid?.apiKey;
685
+ if (!apiKey) throw new Error("SendGrid API Key missing");
686
+ const body = {
687
+ personalizations: [
688
+ {
689
+ to: Array.isArray(options.to) ? options.to.map((email) => ({ email })) : [{ email: options.to }]
690
+ }
691
+ ],
692
+ from: {
693
+ email: from.match(/<(.+)>/)?.[1] || from,
694
+ name: from.match(/"(.+)"/)?.[1]
695
+ },
696
+ subject: options.subject,
697
+ content: [
698
+ { type: "text/plain", value: options.text || "" },
699
+ { type: "text/html", value: options.html }
700
+ ],
701
+ reply_to: replyTo ? { email: replyTo } : void 0
702
+ };
703
+ console.log(`[EmailTransport] Calling SendGrid API...`);
704
+ const resp = await fetch("https://api.sendgrid.com/v3/mail/send", {
705
+ method: "POST",
706
+ headers: {
707
+ Authorization: `Bearer ${apiKey}`,
708
+ "Content-Type": "application/json"
709
+ },
710
+ body: JSON.stringify(body)
711
+ });
712
+ if (!resp.ok) {
713
+ const error = await resp.json();
714
+ throw new Error(`SendGrid Error: ${JSON.stringify(error)}`);
715
+ }
716
+ return { success: true };
717
+ }
718
+ async sendViaMailgun(from, options, replyTo) {
719
+ const { apiKey, domain, region } = this.config.mailgun || {};
720
+ if (!apiKey || !domain) throw new Error("Mailgun config missing");
721
+ const base = region === "eu" ? "api.eu.mailgun.net" : "api.mailgun.net";
722
+ const auth = btoa(`api:${apiKey}`);
723
+ const formData = new URLSearchParams();
724
+ formData.append("from", from);
725
+ const to = Array.isArray(options.to) ? options.to.join(", ") : options.to;
726
+ formData.append("to", to);
727
+ formData.append("subject", options.subject);
728
+ formData.append("html", options.html);
729
+ if (options.text) formData.append("text", options.text);
730
+ if (replyTo) formData.append("h:Reply-To", replyTo);
731
+ console.log(`[EmailTransport] Calling Mailgun API (${region || "us"})...`);
732
+ const resp = await fetch(`https://${base}/v3/${domain}/messages`, {
733
+ method: "POST",
734
+ headers: {
735
+ Authorization: `Basic ${auth}`,
736
+ "Content-Type": "application/x-www-form-urlencoded"
737
+ },
738
+ body: formData
739
+ });
740
+ if (!resp.ok) {
741
+ const error = await resp.json();
742
+ throw new Error(`Mailgun Error: ${JSON.stringify(error)}`);
743
+ }
744
+ return resp.json();
745
+ }
746
+ getTemplates() {
747
+ return this.templates;
748
+ }
749
+ async verifyConnection() {
750
+ if (this.config.provider === "smtp" || this.config.provider === "ses") {
751
+ try {
752
+ const transporter = await this.ensureTransporter();
753
+ if (transporter) {
754
+ await transporter.verify();
755
+ return true;
756
+ }
757
+ } catch {
758
+ return false;
759
+ }
760
+ }
761
+ return !!(this.config.resend?.apiKey || this.config.sendgrid?.apiKey || this.config.mailgun?.apiKey);
762
+ }
763
+ static async fromConfig(db) {
764
+ const configService = new ConfigService(db);
765
+ await configService.load();
766
+ const config = configService.getEmailConfig();
767
+ if (!config.provider) {
768
+ return this.fromEnv();
769
+ }
770
+ const transformed = {
771
+ provider: config.provider || "smtp",
772
+ from: config.from || "noreply@example.com",
773
+ fromName: config.fromName,
774
+ replyTo: config.replyTo,
775
+ smtp: config.provider === "smtp" ? {
776
+ host: config.host || "",
777
+ port: config.port || 587,
778
+ secure: config.secure || false,
779
+ auth: { user: config.user || "", pass: config.pass || "" }
780
+ } : void 0,
781
+ resend: config.provider === "resend" ? { apiKey: config.pass || "" } : void 0,
782
+ sendgrid: config.provider === "sendgrid" ? { apiKey: config.pass || "" } : void 0,
783
+ mailgun: config.provider === "mailgun" ? {
784
+ apiKey: config.pass || "",
785
+ domain: config.host || "",
786
+ region: config.secure ? "eu" : "us"
787
+ } : void 0,
788
+ ses: config.provider === "ses" ? {
789
+ accessKeyId: config.user || "",
790
+ secretAccessKey: config.pass || "",
791
+ region: config.host || "us-east-1"
792
+ } : void 0
793
+ };
794
+ return new _EmailTransport(transformed);
795
+ }
796
+ static fromEnv() {
797
+ const provider = process.env.EMAIL_PROVIDER || "smtp";
798
+ const from = process.env.SMTP_FROM || process.env.DEFAULT_FROM || "noreply@example.com";
799
+ const fromName = process.env.SMTP_FROM_NAME || "Kyro CMS";
800
+ const replyTo = process.env.SMTP_REPLY_TO;
801
+ if (provider === "smtp") {
802
+ const host = process.env.SMTP_HOST;
803
+ const user = process.env.SMTP_USER;
804
+ const pass = process.env.SMTP_PASS;
805
+ if (!host || !user || !pass) return null;
806
+ return new _EmailTransport({
807
+ provider: "smtp",
808
+ from,
809
+ fromName,
810
+ replyTo,
811
+ smtp: {
812
+ host,
813
+ port: parseInt(process.env.SMTP_PORT || "587", 10),
814
+ secure: process.env.SMTP_SECURE === "true",
815
+ auth: { user, pass }
816
+ }
817
+ });
818
+ }
819
+ if (provider === "resend") {
820
+ const apiKey = process.env.RESEND_API_KEY || process.env.SMTP_PASS;
821
+ if (!apiKey) return null;
822
+ return new _EmailTransport({
823
+ provider: "resend",
824
+ from,
825
+ fromName,
826
+ replyTo,
827
+ resend: { apiKey }
828
+ });
829
+ }
830
+ if (provider === "sendgrid") {
831
+ const apiKey = process.env.SENDGRID_API_KEY || process.env.SMTP_PASS;
832
+ if (!apiKey) return null;
833
+ return new _EmailTransport({
834
+ provider: "sendgrid",
835
+ from,
836
+ fromName,
837
+ replyTo,
838
+ sendgrid: { apiKey }
839
+ });
840
+ }
841
+ if (provider === "mailgun") {
842
+ const apiKey = process.env.MAILGUN_API_KEY || process.env.SMTP_PASS;
843
+ const domain = process.env.MAILGUN_DOMAIN || process.env.SMTP_HOST;
844
+ if (!apiKey || !domain) return null;
845
+ return new _EmailTransport({
846
+ provider: "mailgun",
847
+ from,
848
+ fromName,
849
+ replyTo,
850
+ mailgun: {
851
+ apiKey,
852
+ domain,
853
+ region: process.env.MAILGUN_REGION || (process.env.SMTP_SECURE === "true" ? "eu" : "us")
854
+ }
855
+ });
856
+ }
857
+ if (provider === "ses") {
858
+ const accessKeyId = process.env.AWS_ACCESS_KEY_ID || process.env.SMTP_USER;
859
+ const secretAccessKey = process.env.AWS_SECRET_ACCESS_KEY || process.env.SMTP_PASS;
860
+ const region = process.env.AWS_REGION || process.env.SMTP_HOST || "us-east-1";
861
+ if (!accessKeyId || !secretAccessKey) return null;
862
+ return new _EmailTransport({
863
+ provider: "ses",
864
+ from,
865
+ fromName,
866
+ replyTo,
867
+ ses: { accessKeyId, secretAccessKey, region }
868
+ });
869
+ }
870
+ return null;
871
+ }
872
+ };
873
+
874
+ // src/auth/security/password-policy.ts
875
+ var DEFAULT_PASSWORD_POLICY = {
876
+ minLength: 12,
877
+ requireUppercase: true,
878
+ requireLowercase: true,
879
+ requireNumbers: true,
880
+ requireSpecialChars: true,
881
+ preventReuse: 5,
882
+ maxLength: 128
883
+ };
884
+ var PasswordPolicy = class {
885
+ config;
886
+ constructor(config = {}) {
887
+ this.config = { ...DEFAULT_PASSWORD_POLICY, ...config };
888
+ }
889
+ validate(password) {
890
+ const errors = [];
891
+ if (this.config.maxLength && password.length > this.config.maxLength) {
892
+ errors.push(
893
+ `Password must not exceed ${this.config.maxLength} characters`
894
+ );
895
+ }
896
+ if (password.length < this.config.minLength) {
897
+ errors.push(
898
+ `Password must be at least ${this.config.minLength} characters`
899
+ );
900
+ }
901
+ if (this.config.requireUppercase && !/[A-Z]/.test(password)) {
902
+ errors.push("Password must contain at least one uppercase letter");
903
+ }
904
+ if (this.config.requireLowercase && !/[a-z]/.test(password)) {
905
+ errors.push("Password must contain at least one lowercase letter");
906
+ }
907
+ if (this.config.requireNumbers && !/[0-9]/.test(password)) {
908
+ errors.push("Password must contain at least one number");
909
+ }
910
+ if (this.config.requireSpecialChars && !/[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/.test(password)) {
911
+ errors.push("Password must contain at least one special character");
912
+ }
913
+ const commonPasswords = [
914
+ "password",
915
+ "123456",
916
+ "12345678",
917
+ "qwerty",
918
+ "abc123",
919
+ "monkey",
920
+ "1234567",
921
+ "letmein",
922
+ "trustno1",
923
+ "dragon",
924
+ "baseball",
925
+ "iloveyou",
926
+ "master",
927
+ "sunshine",
928
+ "ashley",
929
+ "football",
930
+ "password1",
931
+ "shadow",
932
+ "123123",
933
+ "654321"
934
+ ];
935
+ if (commonPasswords.includes(password.toLowerCase())) {
936
+ errors.push(
937
+ "This password is too common. Please choose a more secure password"
938
+ );
939
+ }
940
+ if (/^[a-zA-Z]+$/.test(password) || /^[0-9]+$/.test(password)) {
941
+ errors.push(
942
+ "Password must contain a mix of letters, numbers, and/or special characters"
943
+ );
944
+ }
945
+ if (/(.)\1{2,}/.test(password)) {
946
+ errors.push(
947
+ "Password must not contain more than 2 consecutive identical characters"
948
+ );
949
+ }
950
+ if (/^(012|123|234|345|456|567|678|789|890|098|987|876|765|654|543|432|321|210)+$/i.test(
951
+ password
952
+ )) {
953
+ errors.push("Password must not contain sequential numbers or letters");
954
+ }
955
+ return {
956
+ valid: errors.length === 0,
957
+ errors
958
+ };
959
+ }
960
+ async checkReuse(passwordHash, history, verifyFn) {
961
+ return {
962
+ valid: true,
963
+ errors: []
964
+ };
965
+ }
966
+ async isInHistory(password, history, verifyFn) {
967
+ for (const hash of history) {
968
+ if (await verifyFn(password, hash)) {
969
+ return true;
970
+ }
971
+ }
972
+ return false;
973
+ }
974
+ generatePassword(length = 16) {
975
+ const uppercase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
976
+ const lowercase = "abcdefghijklmnopqrstuvwxyz";
977
+ const numbers = "0123456789";
978
+ const special = "!@#$%^&*()_+-=[]{}|;:,.<>?";
979
+ let password = "";
980
+ password += uppercase[Math.floor(Math.random() * uppercase.length)];
981
+ password += lowercase[Math.floor(Math.random() * lowercase.length)];
982
+ password += numbers[Math.floor(Math.random() * numbers.length)];
983
+ password += special[Math.floor(Math.random() * special.length)];
984
+ const allChars = uppercase + lowercase + numbers + special;
985
+ for (let i = password.length; i < length; i++) {
986
+ password += allChars[Math.floor(Math.random() * allChars.length)];
987
+ }
988
+ return password.split("").sort(() => Math.random() - 0.5).join("");
989
+ }
990
+ getStrength(password) {
991
+ let score = 0;
992
+ const feedback = [];
993
+ if (password.length >= 8) score += 1;
994
+ if (password.length >= 12) score += 1;
995
+ if (password.length >= 16) score += 1;
996
+ if (/[a-z]/.test(password)) score += 1;
997
+ if (/[A-Z]/.test(password)) score += 1;
998
+ if (/[0-9]/.test(password)) score += 1;
999
+ if (/[!@#$%^&*()_+\-=\[\]{}|;:,.<>?]/.test(password)) score += 1;
1000
+ if (password.length > 8) score += 1;
1001
+ if (password.length > 12) score += 1;
1002
+ const uniqueChars = new Set(password).size;
1003
+ if (uniqueChars > 6) score += 1;
1004
+ if (uniqueChars > 10) score += 1;
1005
+ let label;
1006
+ if (score <= 3) {
1007
+ label = "Weak";
1008
+ feedback.push("Add more characters");
1009
+ feedback.push("Include uppercase and lowercase letters");
1010
+ } else if (score <= 5) {
1011
+ label = "Fair";
1012
+ feedback.push("Add special characters");
1013
+ feedback.push("Consider making it longer");
1014
+ } else if (score <= 7) {
1015
+ label = "Good";
1016
+ feedback.push("Consider making it longer for extra security");
1017
+ } else {
1018
+ label = "Strong";
1019
+ }
1020
+ return { score, label, feedback };
1021
+ }
1022
+ setConfig(config) {
1023
+ this.config = { ...this.config, ...config };
1024
+ }
1025
+ getConfig() {
1026
+ return { ...this.config };
1027
+ }
1028
+ };
1029
+ var DEFAULT_BUSY_TIMEOUT = 5e3;
1030
+ var DEFAULT_WAL_CHECKPOINT = 1e3;
1031
+ var DEFAULT_CACHE_SIZE = -64e3;
1032
+ var DEFAULT_MMAP_SIZE = 268435456;
1033
+ var SQLiteAuthAdapter = class {
1034
+ db = null;
1035
+ path;
1036
+ saltRounds;
1037
+ externalDb;
1038
+ busyTimeout;
1039
+ walAutoCheckpoint;
1040
+ cacheSize;
1041
+ mmapSize;
1042
+ preparedStatements = /* @__PURE__ */ new Map();
1043
+ constructor(options = {}) {
1044
+ this.path = options.path || "./data/auth.db";
1045
+ this.saltRounds = options.saltRounds || 12;
1046
+ this.externalDb = !!options.db;
1047
+ this.busyTimeout = options.busyTimeout ?? DEFAULT_BUSY_TIMEOUT;
1048
+ this.walAutoCheckpoint = options.walAutoCheckpoint ?? DEFAULT_WAL_CHECKPOINT;
1049
+ this.cacheSize = options.cacheSize ?? DEFAULT_CACHE_SIZE;
1050
+ this.mmapSize = options.mmapSize ?? DEFAULT_MMAP_SIZE;
1051
+ if (options.db) {
1052
+ this.db = options.db;
1053
+ }
1054
+ }
1055
+ async connect() {
1056
+ if (this.db) return;
1057
+ const dir = dirname(this.path);
1058
+ if (dir && dir !== ".") {
1059
+ mkdirSync(dir, { recursive: true });
1060
+ }
1061
+ const { DatabaseSync } = await import('sqlite');
1062
+ this.db = new DatabaseSync(this.path);
1063
+ this.db.exec(`PRAGMA busy_timeout = ${this.busyTimeout}`);
1064
+ this.db.exec("PRAGMA journal_mode = WAL");
1065
+ this.db.exec("PRAGMA synchronous = NORMAL");
1066
+ this.db.exec("PRAGMA cache_size = " + this.cacheSize);
1067
+ this.db.exec("PRAGMA mmap_size = " + this.mmapSize);
1068
+ this.db.exec("PRAGMA wal_autocheckpoint = " + this.walAutoCheckpoint);
1069
+ this.db.exec("PRAGMA foreign_keys = ON");
1070
+ this.db.exec("PRAGMA temp_store = MEMORY");
1071
+ this.ensureTables();
1072
+ this.prepareStatements();
1073
+ }
1074
+ async disconnect() {
1075
+ if (this.db && !this.externalDb) {
1076
+ this.db.exec("PRAGMA wal_checkpoint(TRUNCATE)");
1077
+ this.db.close();
1078
+ this.db = null;
1079
+ this.preparedStatements.clear();
1080
+ }
1081
+ }
1082
+ async ensureConnected() {
1083
+ if (!this.db) {
1084
+ await this.connect();
1085
+ }
1086
+ if (!this.db) {
1087
+ throw new Error("Failed to connect to SQLite database");
1088
+ }
1089
+ return this.db;
1090
+ }
1091
+ ensureTables() {
1092
+ if (!this.db) return;
1093
+ this.db.exec(`
1094
+ CREATE TABLE IF NOT EXISTS kyro_users (
1095
+ id TEXT PRIMARY KEY,
1096
+ name TEXT,
1097
+ email TEXT UNIQUE NOT NULL,
1098
+ password_hash TEXT NOT NULL,
1099
+ role TEXT NOT NULL DEFAULT 'customer',
1100
+ tenant_id TEXT,
1101
+ email_verified INTEGER DEFAULT 0,
1102
+ locked INTEGER DEFAULT 0,
1103
+ last_login TEXT,
1104
+ failed_login_attempts INTEGER DEFAULT 0,
1105
+ locked_until TEXT,
1106
+ created_at TEXT NOT NULL,
1107
+ updated_at TEXT NOT NULL
1108
+ );
1109
+
1110
+ CREATE TABLE IF NOT EXISTS kyro_sessions (
1111
+ id TEXT PRIMARY KEY,
1112
+ user_id TEXT NOT NULL,
1113
+ token TEXT NOT NULL,
1114
+ refresh_token TEXT,
1115
+ expires_at TEXT NOT NULL,
1116
+ created_at TEXT NOT NULL,
1117
+ ip_address TEXT,
1118
+ user_agent TEXT,
1119
+ FOREIGN KEY (user_id) REFERENCES kyro_users(id) ON DELETE CASCADE
1120
+ );
1121
+
1122
+ CREATE TABLE IF NOT EXISTS kyro_password_history (
1123
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
1124
+ user_id TEXT NOT NULL,
1125
+ password_hash TEXT NOT NULL,
1126
+ created_at TEXT NOT NULL,
1127
+ FOREIGN KEY (user_id) REFERENCES kyro_users(id) ON DELETE CASCADE
1128
+ );
1129
+
1130
+ CREATE TABLE IF NOT EXISTS kyro_rate_limits (
1131
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
1132
+ key TEXT NOT NULL,
1133
+ window_start INTEGER NOT NULL,
1134
+ count INTEGER NOT NULL DEFAULT 1,
1135
+ UNIQUE(key, window_start)
1136
+ );
1137
+
1138
+ CREATE TABLE IF NOT EXISTS kyro_lockouts (
1139
+ user_id TEXT PRIMARY KEY,
1140
+ attempts INTEGER NOT NULL DEFAULT 0,
1141
+ last_attempt INTEGER,
1142
+ locked_at INTEGER,
1143
+ locked_until INTEGER
1144
+ );
1145
+
1146
+ CREATE TABLE IF NOT EXISTS kyro_audit_logs (
1147
+ id TEXT PRIMARY KEY,
1148
+ timestamp TEXT NOT NULL,
1149
+ action TEXT NOT NULL,
1150
+ user_id TEXT,
1151
+ user_email TEXT,
1152
+ role TEXT,
1153
+ resource TEXT NOT NULL,
1154
+ resource_id TEXT,
1155
+ ip_address TEXT,
1156
+ user_agent TEXT,
1157
+ success INTEGER NOT NULL,
1158
+ error TEXT,
1159
+ metadata TEXT,
1160
+ created_at TEXT NOT NULL DEFAULT (datetime('now'))
1161
+ );
1162
+
1163
+ CREATE INDEX IF NOT EXISTS idx_kyro_users_email ON kyro_users(email);
1164
+ CREATE INDEX IF NOT EXISTS idx_kyro_sessions_user_id ON kyro_sessions(user_id);
1165
+ CREATE INDEX IF NOT EXISTS idx_kyro_sessions_token ON kyro_sessions(token);
1166
+ CREATE INDEX IF NOT EXISTS idx_kyro_sessions_refresh_token ON kyro_sessions(refresh_token);
1167
+ CREATE INDEX IF NOT EXISTS idx_kyro_sessions_expires ON kyro_sessions(expires_at);
1168
+ CREATE INDEX IF NOT EXISTS idx_kyro_password_history_user_id ON kyro_password_history(user_id);
1169
+ CREATE INDEX IF NOT EXISTS idx_kyro_rate_limits_key ON kyro_rate_limits(key);
1170
+ CREATE INDEX IF NOT EXISTS idx_kyro_rate_limits_window ON kyro_rate_limits(window_start);
1171
+ CREATE INDEX IF NOT EXISTS idx_kyro_lockouts_locked_until ON kyro_lockouts(locked_until);
1172
+ CREATE INDEX IF NOT EXISTS idx_kyro_audit_logs_timestamp ON kyro_audit_logs(timestamp);
1173
+ CREATE INDEX IF NOT EXISTS idx_kyro_audit_logs_action ON kyro_audit_logs(action);
1174
+ CREATE INDEX IF NOT EXISTS idx_kyro_audit_logs_user_id ON kyro_audit_logs(user_id);
1175
+ CREATE INDEX IF NOT EXISTS idx_kyro_audit_logs_resource ON kyro_audit_logs(resource);
1176
+ `);
1177
+ try {
1178
+ this.db.exec(`ALTER TABLE kyro_users ADD COLUMN name TEXT`);
1179
+ } catch {
1180
+ }
1181
+ }
1182
+ prepareStatements() {
1183
+ if (!this.db) return;
1184
+ this.preparedStatements.set(
1185
+ "findUserByEmail",
1186
+ this.db.prepare("SELECT * FROM kyro_users WHERE email = ?")
1187
+ );
1188
+ this.preparedStatements.set(
1189
+ "findUserById",
1190
+ this.db.prepare("SELECT * FROM kyro_users WHERE id = ?")
1191
+ );
1192
+ this.preparedStatements.set(
1193
+ "findSessionByToken",
1194
+ this.db.prepare("SELECT * FROM kyro_sessions WHERE token = ?")
1195
+ );
1196
+ this.preparedStatements.set(
1197
+ "findSessionByRefreshToken",
1198
+ this.db.prepare("SELECT * FROM kyro_sessions WHERE refresh_token = ?")
1199
+ );
1200
+ this.preparedStatements.set(
1201
+ "deleteSession",
1202
+ this.db.prepare("DELETE FROM kyro_sessions WHERE id = ? OR token = ?")
1203
+ );
1204
+ this.preparedStatements.set(
1205
+ "deleteUserSessions",
1206
+ this.db.prepare("DELETE FROM kyro_sessions WHERE user_id = ?")
1207
+ );
1208
+ this.preparedStatements.set(
1209
+ "countUsers",
1210
+ this.db.prepare("SELECT COUNT(*) as count FROM kyro_users")
1211
+ );
1212
+ this.preparedStatements.set(
1213
+ "deleteUser",
1214
+ this.db.prepare("DELETE FROM kyro_users WHERE id = ?")
1215
+ );
1216
+ this.preparedStatements.set(
1217
+ "findUsersPaginated",
1218
+ this.db.prepare(
1219
+ "SELECT * FROM kyro_users ORDER BY created_at DESC LIMIT ? OFFSET ?"
1220
+ )
1221
+ );
1222
+ this.preparedStatements.set(
1223
+ "findUsersWithSearch",
1224
+ this.db.prepare(
1225
+ "SELECT * FROM kyro_users WHERE email LIKE ? ORDER BY created_at DESC LIMIT ? OFFSET ?"
1226
+ )
1227
+ );
1228
+ this.preparedStatements.set(
1229
+ "countUsersWithSearch",
1230
+ this.db.prepare(
1231
+ "SELECT COUNT(*) as count FROM kyro_users WHERE email LIKE ?"
1232
+ )
1233
+ );
1234
+ this.preparedStatements.set(
1235
+ "getPasswordHistory",
1236
+ this.db.prepare(
1237
+ "SELECT password_hash FROM kyro_password_history WHERE user_id = ? ORDER BY created_at DESC LIMIT ?"
1238
+ )
1239
+ );
1240
+ this.preparedStatements.set(
1241
+ "addPasswordHistory",
1242
+ this.db.prepare(
1243
+ "INSERT INTO kyro_password_history (user_id, password_hash, created_at) VALUES (?, ?, ?)"
1244
+ )
1245
+ );
1246
+ this.preparedStatements.set(
1247
+ "trimPasswordHistory",
1248
+ this.db.prepare(
1249
+ `DELETE FROM kyro_password_history WHERE id IN (
1250
+ SELECT id FROM kyro_password_history WHERE user_id = ? ORDER BY created_at DESC LIMIT -1 OFFSET 5
1251
+ )`
1252
+ )
1253
+ );
1254
+ this.preparedStatements.set(
1255
+ "deleteExpiredSessions",
1256
+ this.db.prepare("DELETE FROM kyro_sessions WHERE expires_at < ?")
1257
+ );
1258
+ this.preparedStatements.set(
1259
+ "cleanupOldAuditLogs",
1260
+ this.db.prepare("DELETE FROM kyro_audit_logs WHERE timestamp < ?")
1261
+ );
1262
+ this.preparedStatements.set(
1263
+ "cleanupExpiredLockouts",
1264
+ this.db.prepare(
1265
+ "UPDATE kyro_lockouts SET attempts = 0, locked_at = NULL, locked_until = NULL WHERE locked_until < ?"
1266
+ )
1267
+ );
1268
+ this.preparedStatements.set(
1269
+ "getLockout",
1270
+ this.db.prepare("SELECT * FROM kyro_lockouts WHERE user_id = ?")
1271
+ );
1272
+ this.preparedStatements.set(
1273
+ "upsertLockout",
1274
+ this.db.prepare(`
1275
+ INSERT INTO kyro_lockouts (user_id, attempts, last_attempt, locked_at, locked_until)
1276
+ VALUES (?, ?, ?, ?, ?)
1277
+ ON CONFLICT(user_id) DO UPDATE SET
1278
+ attempts = excluded.attempts,
1279
+ last_attempt = excluded.last_attempt,
1280
+ locked_at = excluded.locked_at,
1281
+ locked_until = excluded.locked_until
1282
+ `)
1283
+ );
1284
+ this.preparedStatements.set(
1285
+ "resetLockout",
1286
+ this.db.prepare(
1287
+ "UPDATE kyro_lockouts SET attempts = 0, locked_at = NULL, locked_until = NULL WHERE user_id = ?"
1288
+ )
1289
+ );
1290
+ }
1291
+ stmt(name) {
1292
+ const stmt = this.preparedStatements.get(name);
1293
+ if (!stmt) throw new Error(`Prepared statement not found: ${name}`);
1294
+ return stmt;
1295
+ }
1296
+ async cleanupExpiredSessions() {
1297
+ await this.ensureConnected();
1298
+ const result = this.stmt("deleteExpiredSessions").run(
1299
+ (/* @__PURE__ */ new Date()).toISOString()
1300
+ );
1301
+ return result.changes;
1302
+ }
1303
+ async cleanupOldAuditLogs(retentionDays = 30) {
1304
+ await this.ensureConnected();
1305
+ const cutoff = new Date(
1306
+ Date.now() - retentionDays * 24 * 60 * 60 * 1e3
1307
+ ).toISOString();
1308
+ const result = this.stmt("cleanupOldAuditLogs").run(cutoff);
1309
+ return result.changes;
1310
+ }
1311
+ async getStats() {
1312
+ await this.ensureConnected();
1313
+ const userCount = this.stmt("countUsers").get().count;
1314
+ const activeSessionCount = this.db.prepare(
1315
+ "SELECT COUNT(*) as count FROM kyro_sessions WHERE expires_at > ?"
1316
+ ).get((/* @__PURE__ */ new Date()).toISOString()).count;
1317
+ const auditLogCount = this.db.prepare(
1318
+ "SELECT COUNT(*) as count FROM kyro_audit_logs"
1319
+ ).get().count;
1320
+ return { userCount, activeSessionCount, auditLogCount };
1321
+ }
1322
+ async createUser(data) {
1323
+ await this.ensureConnected();
1324
+ const id = randomBytes(16).toString("hex");
1325
+ const now = (/* @__PURE__ */ new Date()).toISOString();
1326
+ const passwordHash = await this.hashPassword(data.password);
1327
+ const user = {
1328
+ id,
1329
+ name: data.name,
1330
+ email: data.email.toLowerCase(),
1331
+ passwordHash,
1332
+ role: data.role || "customer",
1333
+ tenantId: data.tenantId,
1334
+ createdAt: now,
1335
+ updatedAt: now
1336
+ };
1337
+ this.db.prepare(
1338
+ `INSERT INTO kyro_users (id, name, email, password_hash, role, tenant_id, created_at, updated_at)
1339
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)`
1340
+ ).run(
1341
+ id,
1342
+ user.name || null,
1343
+ user.email,
1344
+ user.passwordHash,
1345
+ user.role,
1346
+ user.tenantId,
1347
+ now,
1348
+ now
1349
+ );
1350
+ return user;
1351
+ }
1352
+ async findUserByEmail(email) {
1353
+ await this.ensureConnected();
1354
+ const row = this.stmt("findUserByEmail").get(email.toLowerCase());
1355
+ if (!row) return null;
1356
+ return this.rowToUser(row);
1357
+ }
1358
+ async findUserById(userId) {
1359
+ await this.ensureConnected();
1360
+ const row = this.stmt("findUserById").get(userId);
1361
+ if (!row) return null;
1362
+ return this.rowToUser(row);
1363
+ }
1364
+ async updateUser(userId, data) {
1365
+ await this.ensureConnected();
1366
+ const existing = await this.findUserById(userId);
1367
+ if (!existing) return null;
1368
+ const updates = [];
1369
+ const values = [];
1370
+ if (data.email !== void 0) {
1371
+ updates.push("email = ?");
1372
+ values.push(data.email.toLowerCase());
1373
+ }
1374
+ if (data.name !== void 0) {
1375
+ updates.push("name = ?");
1376
+ values.push(data.name);
1377
+ }
1378
+ if (data.passwordHash !== void 0) {
1379
+ updates.push("password_hash = ?");
1380
+ values.push(data.passwordHash);
1381
+ }
1382
+ if (data.role !== void 0) {
1383
+ updates.push("role = ?");
1384
+ values.push(data.role);
1385
+ }
1386
+ if (data.tenantId !== void 0) {
1387
+ updates.push("tenant_id = ?");
1388
+ values.push(data.tenantId);
1389
+ }
1390
+ if (data.emailVerified !== void 0) {
1391
+ updates.push("email_verified = ?");
1392
+ values.push(data.emailVerified ? 1 : 0);
1393
+ }
1394
+ if (data.locked !== void 0) {
1395
+ updates.push("locked = ?");
1396
+ values.push(data.locked ? 1 : 0);
1397
+ }
1398
+ if (data.lastLogin !== void 0) {
1399
+ updates.push("last_login = ?");
1400
+ values.push(data.lastLogin);
1401
+ }
1402
+ if (data.failedLoginAttempts !== void 0) {
1403
+ updates.push("failed_login_attempts = ?");
1404
+ values.push(data.failedLoginAttempts);
1405
+ }
1406
+ updates.push("updated_at = ?");
1407
+ values.push((/* @__PURE__ */ new Date()).toISOString());
1408
+ values.push(userId);
1409
+ this.db.prepare(
1410
+ `UPDATE kyro_users SET ${updates.join(", ")} WHERE id = ?`
1411
+ ).run(...values);
1412
+ return this.findUserById(userId);
1413
+ }
1414
+ async deleteUser(userId) {
1415
+ await this.ensureConnected();
1416
+ const result = this.stmt("deleteUser").run(userId);
1417
+ return result.changes > 0;
1418
+ }
1419
+ async hashPassword(password) {
1420
+ return bcrypt.hash(password, this.saltRounds);
1421
+ }
1422
+ async verifyPassword(email, password) {
1423
+ await this.ensureConnected();
1424
+ const user = await this.findUserByEmail(email);
1425
+ if (!user) return null;
1426
+ const stored = this.db.prepare(
1427
+ "SELECT password_hash FROM kyro_users WHERE id = ?"
1428
+ ).get(user.id);
1429
+ if (!stored?.password_hash) return null;
1430
+ const valid = await bcrypt.compare(password, stored.password_hash);
1431
+ return valid ? user : null;
1432
+ }
1433
+ async createSession(userId, data = {}) {
1434
+ await this.ensureConnected();
1435
+ const id = randomBytes(32).toString("hex");
1436
+ const token = randomBytes(32).toString("base64url");
1437
+ const refreshToken = randomBytes(32).toString("base64url");
1438
+ const now = /* @__PURE__ */ new Date();
1439
+ const expiresAt = new Date(now.getTime() + 864e5).toISOString();
1440
+ const session = {
1441
+ id,
1442
+ userId,
1443
+ token,
1444
+ refreshToken,
1445
+ expiresAt,
1446
+ createdAt: now.toISOString(),
1447
+ ipAddress: data.ipAddress,
1448
+ userAgent: data.userAgent
1449
+ };
1450
+ this.db.prepare(
1451
+ `INSERT INTO kyro_sessions (id, user_id, token, refresh_token, expires_at, created_at, ip_address, user_agent)
1452
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)`
1453
+ ).run(
1454
+ session.id,
1455
+ session.userId,
1456
+ session.token,
1457
+ session.refreshToken,
1458
+ session.expiresAt,
1459
+ session.createdAt,
1460
+ session.ipAddress,
1461
+ session.userAgent
1462
+ );
1463
+ return session;
1464
+ }
1465
+ async findSessionByToken(token) {
1466
+ await this.ensureConnected();
1467
+ const row = this.stmt("findSessionByToken").get(token);
1468
+ if (!row) return null;
1469
+ return this.rowToSession(row);
1470
+ }
1471
+ async findSessionByRefreshToken(refreshToken) {
1472
+ await this.ensureConnected();
1473
+ const row = this.stmt("findSessionByRefreshToken").get(refreshToken);
1474
+ if (!row) return null;
1475
+ return this.rowToSession(row);
1476
+ }
1477
+ async deleteSession(sessionId) {
1478
+ await this.ensureConnected();
1479
+ const result = this.stmt("deleteSession").run(sessionId, sessionId);
1480
+ return result.changes > 0;
1481
+ }
1482
+ async deleteUserSessions(userId) {
1483
+ await this.ensureConnected();
1484
+ const result = this.stmt("deleteUserSessions").run(userId);
1485
+ return result.changes;
1486
+ }
1487
+ async hasAnyUsers() {
1488
+ await this.ensureConnected();
1489
+ const row = this.stmt("countUsers").get();
1490
+ return row.count > 0;
1491
+ }
1492
+ async findUsers(options = {}) {
1493
+ await this.ensureConnected();
1494
+ const page = options.page ?? 1;
1495
+ const limit = options.limit ?? 10;
1496
+ const offset = (page - 1) * limit;
1497
+ const search = options.search;
1498
+ let total;
1499
+ let rows;
1500
+ if (search) {
1501
+ const searchPattern = `%${search}%`;
1502
+ total = this.stmt("countUsersWithSearch").get(searchPattern).count;
1503
+ rows = this.stmt("findUsersWithSearch").all(
1504
+ searchPattern,
1505
+ limit,
1506
+ offset
1507
+ );
1508
+ } else {
1509
+ total = this.stmt("countUsers").get().count;
1510
+ rows = this.stmt("findUsersPaginated").all(limit, offset);
1511
+ }
1512
+ return {
1513
+ users: rows.map((row) => this.rowToUser(row)),
1514
+ total
1515
+ };
1516
+ }
1517
+ async addPasswordToHistory(userId, passwordHash) {
1518
+ await this.ensureConnected();
1519
+ this.stmt("addPasswordHistory").run(
1520
+ userId,
1521
+ passwordHash,
1522
+ (/* @__PURE__ */ new Date()).toISOString()
1523
+ );
1524
+ this.stmt("trimPasswordHistory").run(userId);
1525
+ }
1526
+ async getPasswordHistory(userId, count = 5) {
1527
+ await this.ensureConnected();
1528
+ const rows = this.stmt("getPasswordHistory").all(userId, count);
1529
+ return rows.map((r) => r.password_hash);
1530
+ }
1531
+ async isPasswordInHistory(password, userId, historyCount = 5) {
1532
+ const history = await this.getPasswordHistory(userId, historyCount);
1533
+ for (const hash of history) {
1534
+ if (await bcrypt.compare(password, hash)) {
1535
+ return true;
1536
+ }
1537
+ }
1538
+ return false;
1539
+ }
1540
+ async recordFailedAttempt(userId) {
1541
+ await this.ensureConnected();
1542
+ const now = Date.now();
1543
+ const lockout = this.stmt("getLockout").get(userId);
1544
+ const attempts = (lockout?.attempts || 0) + 1;
1545
+ const lockedUntil = attempts >= 5 ? now + 15 * 60 * 1e3 : lockout?.locked_until || null;
1546
+ this.stmt("upsertLockout").run(
1547
+ userId,
1548
+ attempts,
1549
+ now,
1550
+ lockedUntil !== null ? now : null,
1551
+ lockedUntil
1552
+ );
1553
+ }
1554
+ async resetAttempts(userId) {
1555
+ await this.ensureConnected();
1556
+ this.stmt("resetLockout").run(userId);
1557
+ }
1558
+ async checkLockout(userId) {
1559
+ await this.ensureConnected();
1560
+ this.stmt("cleanupExpiredLockouts").run(Date.now());
1561
+ const lockout = this.stmt("getLockout").get(userId);
1562
+ if (!lockout) {
1563
+ return {
1564
+ locked: false,
1565
+ attemptsRemaining: 5,
1566
+ totalAttempts: 0
1567
+ };
1568
+ }
1569
+ if (lockout.locked_until !== null && lockout.locked_until > Date.now()) {
1570
+ return {
1571
+ locked: true,
1572
+ attemptsRemaining: 0,
1573
+ lockedUntil: new Date(lockout.locked_until),
1574
+ totalAttempts: lockout.attempts
1575
+ };
1576
+ }
1577
+ return {
1578
+ locked: false,
1579
+ attemptsRemaining: Math.max(0, 5 - lockout.attempts),
1580
+ totalAttempts: lockout.attempts
1581
+ };
1582
+ }
1583
+ async logAudit(data) {
1584
+ await this.ensureConnected();
1585
+ const id = randomBytes(16).toString("hex");
1586
+ const timestamp = (/* @__PURE__ */ new Date()).toISOString();
1587
+ this.db.prepare(
1588
+ `INSERT INTO kyro_audit_logs (
1589
+ id, timestamp, action, user_id, user_email, role, resource, resource_id,
1590
+ ip_address, user_agent, success, error, metadata, created_at
1591
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
1592
+ ).run(
1593
+ id,
1594
+ timestamp,
1595
+ data.action,
1596
+ data.userId || null,
1597
+ data.userEmail || null,
1598
+ data.role || null,
1599
+ data.resource,
1600
+ data.resourceId || null,
1601
+ data.ipAddress || null,
1602
+ data.userAgent || null,
1603
+ data.success ? 1 : 0,
1604
+ data.error || null,
1605
+ data.metadata ? JSON.stringify(data.metadata) : null,
1606
+ (/* @__PURE__ */ new Date()).toISOString()
1607
+ );
1608
+ return id;
1609
+ }
1610
+ async queryAuditLogs(options = {}) {
1611
+ await this.ensureConnected();
1612
+ const conditions = [];
1613
+ const params = [];
1614
+ if (options.action) {
1615
+ conditions.push("action = ?");
1616
+ params.push(options.action);
1617
+ }
1618
+ if (options.userId) {
1619
+ conditions.push("user_id = ?");
1620
+ params.push(options.userId);
1621
+ }
1622
+ if (options.resource) {
1623
+ conditions.push("resource = ?");
1624
+ params.push(options.resource);
1625
+ }
1626
+ if (options.success !== void 0) {
1627
+ conditions.push("success = ?");
1628
+ params.push(options.success ? 1 : 0);
1629
+ }
1630
+ if (options.startDate) {
1631
+ conditions.push("timestamp >= ?");
1632
+ params.push(options.startDate.toISOString());
1633
+ }
1634
+ if (options.endDate) {
1635
+ conditions.push("timestamp <= ?");
1636
+ params.push(options.endDate.toISOString());
1637
+ }
1638
+ const where = conditions.length > 0 ? "WHERE " + conditions.join(" AND ") : "";
1639
+ const limit = options.limit || 50;
1640
+ const offset = options.offset || 0;
1641
+ const totalResult = this.db.prepare(
1642
+ `SELECT COUNT(*) as count FROM kyro_audit_logs ${where}`
1643
+ ).get(...params);
1644
+ const rows = this.db.prepare(
1645
+ `SELECT * FROM kyro_audit_logs ${where} ORDER BY timestamp DESC LIMIT ? OFFSET ?`
1646
+ ).all(...params, limit, offset);
1647
+ return {
1648
+ total: totalResult.count,
1649
+ logs: rows.map((row) => ({
1650
+ id: row.id,
1651
+ timestamp: new Date(row.timestamp),
1652
+ action: row.action,
1653
+ userId: row.user_id || void 0,
1654
+ userEmail: row.user_email || void 0,
1655
+ resource: row.resource,
1656
+ resourceId: row.resource_id || void 0,
1657
+ ipAddress: row.ip_address || void 0,
1658
+ userAgent: row.user_agent || void 0,
1659
+ success: row.success === 1,
1660
+ error: row.error || void 0,
1661
+ metadata: row.metadata ? JSON.parse(row.metadata) : void 0
1662
+ }))
1663
+ };
1664
+ }
1665
+ rowToUser(row) {
1666
+ return {
1667
+ id: row.id,
1668
+ name: row.name || void 0,
1669
+ email: row.email,
1670
+ passwordHash: row.password_hash,
1671
+ role: row.role,
1672
+ tenantId: row.tenant_id,
1673
+ emailVerified: row.email_verified === 1,
1674
+ locked: row.locked === 1,
1675
+ lastLogin: row.last_login,
1676
+ failedLoginAttempts: row.failed_login_attempts || 0,
1677
+ createdAt: row.created_at,
1678
+ updatedAt: row.updated_at
1679
+ };
1680
+ }
1681
+ rowToSession(row) {
1682
+ return {
1683
+ id: row.id,
1684
+ userId: row.user_id,
1685
+ token: row.token,
1686
+ refreshToken: row.refresh_token,
1687
+ expiresAt: row.expires_at,
1688
+ createdAt: row.created_at,
1689
+ ipAddress: row.ip_address,
1690
+ userAgent: row.user_agent
1691
+ };
1692
+ }
1693
+ async findAuditLogs(filter) {
1694
+ const result = await this.queryAuditLogs({
1695
+ action: filter.action,
1696
+ userId: filter.userId,
1697
+ resource: filter.resource,
1698
+ success: filter.success,
1699
+ startDate: filter.startDate,
1700
+ endDate: filter.endDate,
1701
+ limit: filter.limit,
1702
+ offset: filter.offset
1703
+ });
1704
+ return {
1705
+ logs: result.logs.map((log) => ({
1706
+ ...log,
1707
+ action: log.action
1708
+ })),
1709
+ total: result.total
1710
+ };
1711
+ }
1712
+ async createAuditLog(data) {
1713
+ const id = await this.logAudit({
1714
+ action: data.action,
1715
+ userId: data.userId,
1716
+ userEmail: data.userEmail,
1717
+ role: data.role,
1718
+ resource: data.resource,
1719
+ resourceId: data.resourceId,
1720
+ ipAddress: data.ipAddress,
1721
+ userAgent: data.userAgent,
1722
+ success: data.success,
1723
+ error: data.error,
1724
+ metadata: data.metadata
1725
+ });
1726
+ const row = this.db?.prepare("SELECT * FROM kyro_audit_logs WHERE id = ?").get(id);
1727
+ return {
1728
+ ...data,
1729
+ id,
1730
+ timestamp: row ? new Date(row.timestamp) : /* @__PURE__ */ new Date()
1731
+ };
1732
+ }
1733
+ };
1734
+
1735
+ export { ConfigService, EmailTransport, PasswordPolicy, SQLiteAuthAdapter };
1736
+ //# sourceMappingURL=chunk-RYDGMBIG.js.map
1737
+ //# sourceMappingURL=chunk-RYDGMBIG.js.map