@kyro-cms/core 0.6.0 → 0.7.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.
Files changed (145) hide show
  1. package/dist/api-handler.cjs +75 -35
  2. package/dist/api-handler.cjs.map +1 -1
  3. package/dist/api-handler.d.cts +2 -5
  4. package/dist/api-handler.d.ts +2 -5
  5. package/dist/api-handler.js +75 -36
  6. package/dist/api-handler.js.map +1 -1
  7. package/dist/bootstrap-AKAUP6F6.cjs +32 -0
  8. package/dist/{bootstrap-EE6BJZWL.cjs.map → bootstrap-AKAUP6F6.cjs.map} +1 -1
  9. package/dist/bootstrap-JCML6NFO.js +7 -0
  10. package/dist/{bootstrap-4MH44YKG.js.map → bootstrap-JCML6NFO.js.map} +1 -1
  11. package/dist/{chunk-WVPOPOEQ.cjs → chunk-2KVHZE6O.cjs} +286 -126
  12. package/dist/chunk-2KVHZE6O.cjs.map +1 -0
  13. package/dist/{chunk-RALQO47U.cjs → chunk-2OL4O2TH.cjs} +55 -2
  14. package/dist/chunk-2OL4O2TH.cjs.map +1 -0
  15. package/dist/{chunk-XU7AFF6V.js → chunk-35U3FROB.js} +982 -4
  16. package/dist/chunk-35U3FROB.js.map +1 -0
  17. package/dist/{chunk-WSCJQI2B.js → chunk-3J4MFTI3.js} +27 -11
  18. package/dist/chunk-3J4MFTI3.js.map +1 -0
  19. package/dist/chunk-3ZFYL34R.js +391 -0
  20. package/dist/chunk-3ZFYL34R.js.map +1 -0
  21. package/dist/chunk-4DA7QPLA.cjs +356 -0
  22. package/dist/chunk-4DA7QPLA.cjs.map +1 -0
  23. package/dist/{chunk-TP5YQFIX.js → chunk-57P6MJKC.js} +3 -715
  24. package/dist/chunk-57P6MJKC.js.map +1 -0
  25. package/dist/{chunk-R2YHJN6W.cjs → chunk-5KVM3WEY.cjs} +34 -208
  26. package/dist/chunk-5KVM3WEY.cjs.map +1 -0
  27. package/dist/{chunk-Z2OVHWHB.cjs → chunk-6IMPH6WV.cjs} +28 -11
  28. package/dist/chunk-6IMPH6WV.cjs.map +1 -0
  29. package/dist/{chunk-QKVA2SOG.js → chunk-DXHRBMGB.js} +27 -284
  30. package/dist/chunk-DXHRBMGB.js.map +1 -0
  31. package/dist/{chunk-E3BZLMX6.js → chunk-ES5HNFFT.js} +43 -2
  32. package/dist/chunk-ES5HNFFT.js.map +1 -0
  33. package/dist/{chunk-QYZKIPSD.js → chunk-FXYP2HA6.js} +34 -3
  34. package/dist/chunk-FXYP2HA6.js.map +1 -0
  35. package/dist/chunk-H727JIG7.js +809 -0
  36. package/dist/chunk-H727JIG7.js.map +1 -0
  37. package/dist/{chunk-AM4JKIPP.js → chunk-HXRD4B37.js} +9 -183
  38. package/dist/chunk-HXRD4B37.js.map +1 -0
  39. package/dist/chunk-I7HHI6QV.cjs +816 -0
  40. package/dist/chunk-I7HHI6QV.cjs.map +1 -0
  41. package/dist/{chunk-RDRJVCL5.cjs → chunk-IA6AU5PI.cjs} +2 -720
  42. package/dist/chunk-IA6AU5PI.cjs.map +1 -0
  43. package/dist/{chunk-55BNRTLW.cjs → chunk-LINKCEG4.cjs} +985 -4
  44. package/dist/chunk-LINKCEG4.cjs.map +1 -0
  45. package/dist/{chunk-TVVYZ2TH.js → chunk-OHVB4AJ7.js} +56 -3
  46. package/dist/chunk-OHVB4AJ7.js.map +1 -0
  47. package/dist/{chunk-XAEBVZTI.cjs → chunk-PDYFVNUX.cjs} +26 -289
  48. package/dist/chunk-PDYFVNUX.cjs.map +1 -0
  49. package/dist/{chunk-6WXQRYTW.js → chunk-QPPDLRNR.js} +286 -126
  50. package/dist/chunk-QPPDLRNR.js.map +1 -0
  51. package/dist/{chunk-WBCIEYHC.cjs → chunk-QUW2RZTM.cjs} +35 -4
  52. package/dist/chunk-QUW2RZTM.cjs.map +1 -0
  53. package/dist/chunk-SA7NSSIQ.cjs +397 -0
  54. package/dist/chunk-SA7NSSIQ.cjs.map +1 -0
  55. package/dist/{chunk-H4XCAPA6.cjs → chunk-V3LKPM3O.cjs} +43 -2
  56. package/dist/chunk-V3LKPM3O.cjs.map +1 -0
  57. package/dist/chunk-Y3N7UUDO.js +349 -0
  58. package/dist/chunk-Y3N7UUDO.js.map +1 -0
  59. package/dist/{chunk-S3FG2NY7.js → chunk-Y3QQN7PN.js} +4 -3
  60. package/dist/chunk-Y3QQN7PN.js.map +1 -0
  61. package/dist/{chunk-5HA5OMFH.cjs → chunk-YVUJBEXE.cjs} +7 -6
  62. package/dist/chunk-YVUJBEXE.cjs.map +1 -0
  63. package/dist/cli/index.cjs +103 -20
  64. package/dist/cli/index.cjs.map +1 -1
  65. package/dist/cli/index.js +103 -20
  66. package/dist/cli/index.js.map +1 -1
  67. package/dist/client.d.cts +1 -1
  68. package/dist/client.d.ts +1 -1
  69. package/dist/drizzle/index.cjs +12 -12
  70. package/dist/drizzle/index.d.cts +23 -2
  71. package/dist/drizzle/index.d.ts +23 -2
  72. package/dist/drizzle/index.js +3 -3
  73. package/dist/index.cjs +174 -1054
  74. package/dist/index.cjs.map +1 -1
  75. package/dist/index.d.cts +85 -7
  76. package/dist/index.d.ts +85 -7
  77. package/dist/index.js +91 -980
  78. package/dist/index.js.map +1 -1
  79. package/dist/integration.cjs +2 -2
  80. package/dist/integration.d.cts +3 -16
  81. package/dist/integration.d.ts +3 -16
  82. package/dist/integration.js +1 -1
  83. package/dist/mongo-auth-adapter-NHHUJHVH.cjs +17 -0
  84. package/dist/mongo-auth-adapter-NHHUJHVH.cjs.map +1 -0
  85. package/dist/mongo-auth-adapter-NJQUUCTP.js +4 -0
  86. package/dist/mongo-auth-adapter-NJQUUCTP.js.map +1 -0
  87. package/dist/mongodb/index.cjs +9 -8
  88. package/dist/mongodb/index.d.cts +86 -5
  89. package/dist/mongodb/index.d.ts +86 -5
  90. package/dist/mongodb/index.js +3 -2
  91. package/dist/postgres-auth-adapter-3T2NKTSE.js +5 -0
  92. package/dist/{postgres-auth-adapter-B65BULNS.js.map → postgres-auth-adapter-3T2NKTSE.js.map} +1 -1
  93. package/dist/postgres-auth-adapter-7IEENCKQ.cjs +14 -0
  94. package/dist/{postgres-auth-adapter-6742WDCF.cjs.map → postgres-auth-adapter-7IEENCKQ.cjs.map} +1 -1
  95. package/dist/redis-adapter-D2E2S3GB.cjs +13 -0
  96. package/dist/{redis-adapter-LPUWLE4Y.cjs.map → redis-adapter-D2E2S3GB.cjs.map} +1 -1
  97. package/dist/redis-adapter-VQXD7ESY.js +4 -0
  98. package/dist/{redis-adapter-THYDCGQR.js.map → redis-adapter-VQXD7ESY.js.map} +1 -1
  99. package/dist/rest/index.cjs +10 -8
  100. package/dist/rest/index.js +8 -6
  101. package/dist/sqlite-adapter-LVK5PS4T.cjs +13 -0
  102. package/dist/sqlite-adapter-LVK5PS4T.cjs.map +1 -0
  103. package/dist/sqlite-adapter-TR3U3W6Q.js +4 -0
  104. package/dist/sqlite-adapter-TR3U3W6Q.js.map +1 -0
  105. package/dist/templates/index.cjs +31 -27
  106. package/dist/templates/index.d.cts +8 -5
  107. package/dist/templates/index.d.ts +8 -5
  108. package/dist/templates/index.js +1 -1
  109. package/dist/{base-eVegJ_Pr.d.ts → tenant-B1YB0Jy8.d.ts} +10 -1
  110. package/dist/{base-DvvNqnM-.d.cts → tenant-Cpeveji6.d.cts} +10 -1
  111. package/dist/{types-DqN4ckOC.d.cts → types-D6ZLRGbH.d.cts} +19 -1
  112. package/dist/{types-DqN4ckOC.d.ts → types-D6ZLRGbH.d.ts} +19 -1
  113. package/package.json +56 -9
  114. package/dist/adapter-BSvBudTG.d.cts +0 -65
  115. package/dist/adapter-CXGB2Elb.d.ts +0 -65
  116. package/dist/bootstrap-4MH44YKG.js +0 -6
  117. package/dist/bootstrap-EE6BJZWL.cjs +0 -31
  118. package/dist/chunk-55BNRTLW.cjs.map +0 -1
  119. package/dist/chunk-5HA5OMFH.cjs.map +0 -1
  120. package/dist/chunk-6WXQRYTW.js.map +0 -1
  121. package/dist/chunk-A4USRVTQ.js +0 -115
  122. package/dist/chunk-A4USRVTQ.js.map +0 -1
  123. package/dist/chunk-AM4JKIPP.js.map +0 -1
  124. package/dist/chunk-E3BZLMX6.js.map +0 -1
  125. package/dist/chunk-H4XCAPA6.cjs.map +0 -1
  126. package/dist/chunk-KOCTZKPV.cjs +0 -117
  127. package/dist/chunk-KOCTZKPV.cjs.map +0 -1
  128. package/dist/chunk-QKVA2SOG.js.map +0 -1
  129. package/dist/chunk-QYZKIPSD.js.map +0 -1
  130. package/dist/chunk-R2YHJN6W.cjs.map +0 -1
  131. package/dist/chunk-RALQO47U.cjs.map +0 -1
  132. package/dist/chunk-RDRJVCL5.cjs.map +0 -1
  133. package/dist/chunk-S3FG2NY7.js.map +0 -1
  134. package/dist/chunk-TP5YQFIX.js.map +0 -1
  135. package/dist/chunk-TVVYZ2TH.js.map +0 -1
  136. package/dist/chunk-WBCIEYHC.cjs.map +0 -1
  137. package/dist/chunk-WSCJQI2B.js.map +0 -1
  138. package/dist/chunk-WVPOPOEQ.cjs.map +0 -1
  139. package/dist/chunk-XAEBVZTI.cjs.map +0 -1
  140. package/dist/chunk-XU7AFF6V.js.map +0 -1
  141. package/dist/chunk-Z2OVHWHB.cjs.map +0 -1
  142. package/dist/postgres-auth-adapter-6742WDCF.cjs +0 -14
  143. package/dist/postgres-auth-adapter-B65BULNS.js +0 -5
  144. package/dist/redis-adapter-LPUWLE4Y.cjs +0 -13
  145. package/dist/redis-adapter-THYDCGQR.js +0 -4
@@ -0,0 +1,809 @@
1
+ import bcrypt from 'bcryptjs';
2
+ import { randomBytes } from 'crypto';
3
+ import { mkdirSync } from 'fs';
4
+ import { dirname } from 'path';
5
+ import { createRequire } from 'module';
6
+
7
+ // src/auth/sqlite-adapter.ts
8
+ var _require = createRequire(import.meta.url);
9
+ var modPath = "node:sqlite";
10
+ var { DatabaseSync } = _require(modPath);
11
+ var DEFAULT_BUSY_TIMEOUT = 5e3;
12
+ var DEFAULT_WAL_CHECKPOINT = 1e3;
13
+ var DEFAULT_CACHE_SIZE = -64e3;
14
+ var DEFAULT_MMAP_SIZE = 268435456;
15
+ var SQLiteAuthAdapter = class {
16
+ db = null;
17
+ path;
18
+ saltRounds;
19
+ externalDb;
20
+ busyTimeout;
21
+ walAutoCheckpoint;
22
+ cacheSize;
23
+ mmapSize;
24
+ preparedStatements = /* @__PURE__ */ new Map();
25
+ constructor(options = {}) {
26
+ this.path = options.path || "./data/auth.db";
27
+ this.saltRounds = options.saltRounds || 12;
28
+ this.externalDb = !!options.db;
29
+ this.busyTimeout = options.busyTimeout ?? DEFAULT_BUSY_TIMEOUT;
30
+ this.walAutoCheckpoint = options.walAutoCheckpoint ?? DEFAULT_WAL_CHECKPOINT;
31
+ this.cacheSize = options.cacheSize ?? DEFAULT_CACHE_SIZE;
32
+ this.mmapSize = options.mmapSize ?? DEFAULT_MMAP_SIZE;
33
+ if (options.db) {
34
+ this.db = options.db;
35
+ }
36
+ }
37
+ async connect() {
38
+ if (this.db) return;
39
+ const dir = dirname(this.path);
40
+ if (dir && dir !== ".") {
41
+ mkdirSync(dir, { recursive: true });
42
+ }
43
+ this.db = new DatabaseSync(this.path);
44
+ this.db.exec(`PRAGMA busy_timeout = ${this.busyTimeout}`);
45
+ this.db.exec("PRAGMA journal_mode = WAL");
46
+ this.db.exec("PRAGMA synchronous = NORMAL");
47
+ this.db.exec("PRAGMA cache_size = " + this.cacheSize);
48
+ this.db.exec("PRAGMA mmap_size = " + this.mmapSize);
49
+ this.db.exec("PRAGMA wal_autocheckpoint = " + this.walAutoCheckpoint);
50
+ this.db.exec("PRAGMA foreign_keys = ON");
51
+ this.db.exec("PRAGMA temp_store = MEMORY");
52
+ this.ensureTables();
53
+ this.prepareStatements();
54
+ }
55
+ async disconnect() {
56
+ if (this.db && !this.externalDb) {
57
+ this.db.exec("PRAGMA wal_checkpoint(TRUNCATE)");
58
+ this.db.close();
59
+ this.db = null;
60
+ this.preparedStatements.clear();
61
+ }
62
+ }
63
+ async ensureConnected() {
64
+ if (!this.db) {
65
+ await this.connect();
66
+ }
67
+ if (!this.db) {
68
+ throw new Error("Failed to connect to SQLite database");
69
+ }
70
+ return this.db;
71
+ }
72
+ ensureTables() {
73
+ if (!this.db) return;
74
+ this.db.exec(`
75
+ CREATE TABLE IF NOT EXISTS kyro_users (
76
+ id TEXT PRIMARY KEY,
77
+ name TEXT,
78
+ email TEXT UNIQUE NOT NULL,
79
+ password_hash TEXT NOT NULL,
80
+ role TEXT NOT NULL DEFAULT 'customer',
81
+ tenant_id TEXT,
82
+ email_verified INTEGER DEFAULT 0,
83
+ locked INTEGER DEFAULT 0,
84
+ last_login TEXT,
85
+ failed_login_attempts INTEGER DEFAULT 0,
86
+ locked_until TEXT,
87
+ created_at TEXT NOT NULL,
88
+ updated_at TEXT NOT NULL
89
+ );
90
+
91
+ CREATE TABLE IF NOT EXISTS kyro_sessions (
92
+ id TEXT PRIMARY KEY,
93
+ user_id TEXT NOT NULL,
94
+ token TEXT NOT NULL,
95
+ refresh_token TEXT,
96
+ expires_at TEXT NOT NULL,
97
+ created_at TEXT NOT NULL,
98
+ ip_address TEXT,
99
+ user_agent TEXT,
100
+ FOREIGN KEY (user_id) REFERENCES kyro_users(id) ON DELETE CASCADE
101
+ );
102
+
103
+ CREATE TABLE IF NOT EXISTS kyro_password_history (
104
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
105
+ user_id TEXT NOT NULL,
106
+ password_hash TEXT NOT NULL,
107
+ created_at TEXT NOT NULL,
108
+ FOREIGN KEY (user_id) REFERENCES kyro_users(id) ON DELETE CASCADE
109
+ );
110
+
111
+ CREATE TABLE IF NOT EXISTS kyro_rate_limits (
112
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
113
+ key TEXT NOT NULL,
114
+ window_start INTEGER NOT NULL,
115
+ count INTEGER NOT NULL DEFAULT 1,
116
+ UNIQUE(key, window_start)
117
+ );
118
+
119
+ CREATE TABLE IF NOT EXISTS kyro_lockouts (
120
+ user_id TEXT PRIMARY KEY,
121
+ attempts INTEGER NOT NULL DEFAULT 0,
122
+ last_attempt INTEGER,
123
+ locked_at INTEGER,
124
+ locked_until INTEGER
125
+ );
126
+
127
+ CREATE TABLE IF NOT EXISTS kyro_audit_logs (
128
+ id TEXT PRIMARY KEY,
129
+ timestamp TEXT NOT NULL,
130
+ action TEXT NOT NULL,
131
+ user_id TEXT,
132
+ user_email TEXT,
133
+ role TEXT,
134
+ resource TEXT NOT NULL,
135
+ resource_id TEXT,
136
+ ip_address TEXT,
137
+ user_agent TEXT,
138
+ success INTEGER NOT NULL,
139
+ error TEXT,
140
+ metadata TEXT,
141
+ created_at TEXT NOT NULL DEFAULT (datetime('now'))
142
+ );
143
+
144
+ CREATE INDEX IF NOT EXISTS idx_kyro_users_email ON kyro_users(email);
145
+ CREATE INDEX IF NOT EXISTS idx_kyro_sessions_user_id ON kyro_sessions(user_id);
146
+ CREATE INDEX IF NOT EXISTS idx_kyro_sessions_token ON kyro_sessions(token);
147
+ CREATE INDEX IF NOT EXISTS idx_kyro_sessions_refresh_token ON kyro_sessions(refresh_token);
148
+ CREATE INDEX IF NOT EXISTS idx_kyro_sessions_expires ON kyro_sessions(expires_at);
149
+ CREATE INDEX IF NOT EXISTS idx_kyro_password_history_user_id ON kyro_password_history(user_id);
150
+ CREATE INDEX IF NOT EXISTS idx_kyro_rate_limits_key ON kyro_rate_limits(key);
151
+ CREATE INDEX IF NOT EXISTS idx_kyro_rate_limits_window ON kyro_rate_limits(window_start);
152
+ CREATE INDEX IF NOT EXISTS idx_kyro_lockouts_locked_until ON kyro_lockouts(locked_until);
153
+ CREATE INDEX IF NOT EXISTS idx_kyro_audit_logs_timestamp ON kyro_audit_logs(timestamp);
154
+ CREATE INDEX IF NOT EXISTS idx_kyro_audit_logs_action ON kyro_audit_logs(action);
155
+ CREATE INDEX IF NOT EXISTS idx_kyro_audit_logs_user_id ON kyro_audit_logs(user_id);
156
+ CREATE INDEX IF NOT EXISTS idx_kyro_audit_logs_resource ON kyro_audit_logs(resource);
157
+
158
+ CREATE TABLE IF NOT EXISTS kyro_email_verifications (
159
+ id TEXT PRIMARY KEY,
160
+ user_id TEXT NOT NULL,
161
+ token TEXT UNIQUE NOT NULL,
162
+ expires_at TEXT NOT NULL,
163
+ created_at TEXT NOT NULL DEFAULT (datetime('now')),
164
+ FOREIGN KEY (user_id) REFERENCES kyro_users(id) ON DELETE CASCADE
165
+ );
166
+
167
+ CREATE TABLE IF NOT EXISTS kyro_password_resets (
168
+ id TEXT PRIMARY KEY,
169
+ user_id TEXT NOT NULL,
170
+ token TEXT UNIQUE NOT NULL,
171
+ expires_at TEXT NOT NULL,
172
+ used_at TEXT,
173
+ created_at TEXT NOT NULL DEFAULT (datetime('now')),
174
+ FOREIGN KEY (user_id) REFERENCES kyro_users(id) ON DELETE CASCADE
175
+ );
176
+
177
+ CREATE INDEX IF NOT EXISTS idx_kyro_email_verifications_token ON kyro_email_verifications(token);
178
+ CREATE INDEX IF NOT EXISTS idx_kyro_password_resets_token ON kyro_password_resets(token);
179
+ `);
180
+ try {
181
+ this.db.exec(`ALTER TABLE kyro_users ADD COLUMN name TEXT`);
182
+ } catch {
183
+ }
184
+ }
185
+ prepareStatements() {
186
+ if (!this.db) return;
187
+ this.preparedStatements.set(
188
+ "findUserByEmail",
189
+ this.db.prepare("SELECT * FROM kyro_users WHERE email = ?")
190
+ );
191
+ this.preparedStatements.set(
192
+ "findUserById",
193
+ this.db.prepare("SELECT * FROM kyro_users WHERE id = ?")
194
+ );
195
+ this.preparedStatements.set(
196
+ "findSessionByToken",
197
+ this.db.prepare("SELECT * FROM kyro_sessions WHERE token = ?")
198
+ );
199
+ this.preparedStatements.set(
200
+ "findSessionByRefreshToken",
201
+ this.db.prepare("SELECT * FROM kyro_sessions WHERE refresh_token = ?")
202
+ );
203
+ this.preparedStatements.set(
204
+ "deleteSession",
205
+ this.db.prepare("DELETE FROM kyro_sessions WHERE id = ? OR token = ?")
206
+ );
207
+ this.preparedStatements.set(
208
+ "deleteUserSessions",
209
+ this.db.prepare("DELETE FROM kyro_sessions WHERE user_id = ?")
210
+ );
211
+ this.preparedStatements.set(
212
+ "countUsers",
213
+ this.db.prepare("SELECT COUNT(*) as count FROM kyro_users")
214
+ );
215
+ this.preparedStatements.set(
216
+ "deleteUser",
217
+ this.db.prepare("DELETE FROM kyro_users WHERE id = ?")
218
+ );
219
+ this.preparedStatements.set(
220
+ "findUsersPaginated",
221
+ this.db.prepare(
222
+ "SELECT * FROM kyro_users ORDER BY created_at DESC LIMIT ? OFFSET ?"
223
+ )
224
+ );
225
+ this.preparedStatements.set(
226
+ "findUsersWithSearch",
227
+ this.db.prepare(
228
+ "SELECT * FROM kyro_users WHERE email LIKE ? ORDER BY created_at DESC LIMIT ? OFFSET ?"
229
+ )
230
+ );
231
+ this.preparedStatements.set(
232
+ "countUsersWithSearch",
233
+ this.db.prepare(
234
+ "SELECT COUNT(*) as count FROM kyro_users WHERE email LIKE ?"
235
+ )
236
+ );
237
+ this.preparedStatements.set(
238
+ "getPasswordHistory",
239
+ this.db.prepare(
240
+ "SELECT password_hash FROM kyro_password_history WHERE user_id = ? ORDER BY created_at DESC LIMIT ?"
241
+ )
242
+ );
243
+ this.preparedStatements.set(
244
+ "addPasswordHistory",
245
+ this.db.prepare(
246
+ "INSERT INTO kyro_password_history (user_id, password_hash, created_at) VALUES (?, ?, ?)"
247
+ )
248
+ );
249
+ this.preparedStatements.set(
250
+ "trimPasswordHistory",
251
+ this.db.prepare(
252
+ `DELETE FROM kyro_password_history WHERE id IN (
253
+ SELECT id FROM kyro_password_history WHERE user_id = ? ORDER BY created_at DESC LIMIT -1 OFFSET 5
254
+ )`
255
+ )
256
+ );
257
+ this.preparedStatements.set(
258
+ "deleteExpiredSessions",
259
+ this.db.prepare("DELETE FROM kyro_sessions WHERE expires_at < ?")
260
+ );
261
+ this.preparedStatements.set(
262
+ "cleanupOldAuditLogs",
263
+ this.db.prepare("DELETE FROM kyro_audit_logs WHERE timestamp < ?")
264
+ );
265
+ this.preparedStatements.set(
266
+ "cleanupExpiredLockouts",
267
+ this.db.prepare(
268
+ "UPDATE kyro_lockouts SET attempts = 0, locked_at = NULL, locked_until = NULL WHERE locked_until < ?"
269
+ )
270
+ );
271
+ this.preparedStatements.set(
272
+ "getLockout",
273
+ this.db.prepare("SELECT * FROM kyro_lockouts WHERE user_id = ?")
274
+ );
275
+ this.preparedStatements.set(
276
+ "upsertLockout",
277
+ this.db.prepare(`
278
+ INSERT INTO kyro_lockouts (user_id, attempts, last_attempt, locked_at, locked_until)
279
+ VALUES (?, ?, ?, ?, ?)
280
+ ON CONFLICT(user_id) DO UPDATE SET
281
+ attempts = excluded.attempts,
282
+ last_attempt = excluded.last_attempt,
283
+ locked_at = excluded.locked_at,
284
+ locked_until = excluded.locked_until
285
+ `)
286
+ );
287
+ this.preparedStatements.set(
288
+ "resetLockout",
289
+ this.db.prepare(
290
+ "UPDATE kyro_lockouts SET attempts = 0, locked_at = NULL, locked_until = NULL WHERE user_id = ?"
291
+ )
292
+ );
293
+ }
294
+ stmt(name) {
295
+ const stmt = this.preparedStatements.get(name);
296
+ if (!stmt) throw new Error(`Prepared statement not found: ${name}`);
297
+ return stmt;
298
+ }
299
+ async cleanupExpiredSessions() {
300
+ await this.ensureConnected();
301
+ const result = this.stmt("deleteExpiredSessions").run(
302
+ (/* @__PURE__ */ new Date()).toISOString()
303
+ );
304
+ return result.changes;
305
+ }
306
+ async cleanupOldAuditLogs(retentionDays = 30) {
307
+ await this.ensureConnected();
308
+ const cutoff = new Date(
309
+ Date.now() - retentionDays * 24 * 60 * 60 * 1e3
310
+ ).toISOString();
311
+ const result = this.stmt("cleanupOldAuditLogs").run(cutoff);
312
+ return result.changes;
313
+ }
314
+ async getStats() {
315
+ await this.ensureConnected();
316
+ const userCount = this.stmt("countUsers").get().count;
317
+ const activeSessionCount = this.db.prepare(
318
+ "SELECT COUNT(*) as count FROM kyro_sessions WHERE expires_at > ?"
319
+ ).get((/* @__PURE__ */ new Date()).toISOString()).count;
320
+ const auditLogCount = this.db.prepare(
321
+ "SELECT COUNT(*) as count FROM kyro_audit_logs"
322
+ ).get().count;
323
+ return { userCount, activeSessionCount, auditLogCount };
324
+ }
325
+ async createUser(data) {
326
+ await this.ensureConnected();
327
+ const id = randomBytes(16).toString("hex");
328
+ const now = (/* @__PURE__ */ new Date()).toISOString();
329
+ const passwordHash = await this.hashPassword(data.password);
330
+ const user = {
331
+ id,
332
+ name: data.name,
333
+ email: data.email.toLowerCase(),
334
+ passwordHash,
335
+ role: data.role || "customer",
336
+ tenantId: data.tenantId,
337
+ createdAt: now,
338
+ updatedAt: now
339
+ };
340
+ this.db.prepare(
341
+ `INSERT INTO kyro_users (id, name, email, password_hash, role, tenant_id, created_at, updated_at)
342
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)`
343
+ ).run(
344
+ id,
345
+ user.name || null,
346
+ user.email,
347
+ user.passwordHash,
348
+ user.role,
349
+ user.tenantId,
350
+ now,
351
+ now
352
+ );
353
+ return user;
354
+ }
355
+ async findUserByEmail(email) {
356
+ await this.ensureConnected();
357
+ const row = this.stmt("findUserByEmail").get(email.toLowerCase());
358
+ if (!row) return null;
359
+ return this.rowToUser(row);
360
+ }
361
+ async findUserById(userId) {
362
+ await this.ensureConnected();
363
+ const row = this.stmt("findUserById").get(userId);
364
+ if (!row) return null;
365
+ return this.rowToUser(row);
366
+ }
367
+ async updateUser(userId, data) {
368
+ await this.ensureConnected();
369
+ const existing = await this.findUserById(userId);
370
+ if (!existing) return null;
371
+ const updates = [];
372
+ const values = [];
373
+ if (data.email !== void 0) {
374
+ updates.push("email = ?");
375
+ values.push(data.email.toLowerCase());
376
+ }
377
+ if (data.name !== void 0) {
378
+ updates.push("name = ?");
379
+ values.push(data.name);
380
+ }
381
+ if (data.passwordHash !== void 0) {
382
+ updates.push("password_hash = ?");
383
+ values.push(data.passwordHash);
384
+ }
385
+ if (data.role !== void 0) {
386
+ updates.push("role = ?");
387
+ values.push(data.role);
388
+ }
389
+ if (data.tenantId !== void 0) {
390
+ updates.push("tenant_id = ?");
391
+ values.push(data.tenantId);
392
+ }
393
+ if (data.emailVerified !== void 0) {
394
+ updates.push("email_verified = ?");
395
+ values.push(data.emailVerified ? 1 : 0);
396
+ }
397
+ if (data.locked !== void 0) {
398
+ updates.push("locked = ?");
399
+ values.push(data.locked ? 1 : 0);
400
+ }
401
+ if (data.lastLogin !== void 0) {
402
+ updates.push("last_login = ?");
403
+ values.push(data.lastLogin);
404
+ }
405
+ if (data.failedLoginAttempts !== void 0) {
406
+ updates.push("failed_login_attempts = ?");
407
+ values.push(data.failedLoginAttempts);
408
+ }
409
+ updates.push("updated_at = ?");
410
+ values.push((/* @__PURE__ */ new Date()).toISOString());
411
+ values.push(userId);
412
+ this.db.prepare(
413
+ `UPDATE kyro_users SET ${updates.join(", ")} WHERE id = ?`
414
+ ).run(...values);
415
+ return this.findUserById(userId);
416
+ }
417
+ async deleteUser(userId) {
418
+ await this.ensureConnected();
419
+ const result = this.stmt("deleteUser").run(userId);
420
+ return result.changes > 0;
421
+ }
422
+ async hashPassword(password) {
423
+ return bcrypt.hash(password, this.saltRounds);
424
+ }
425
+ async verifyPassword(email, password) {
426
+ await this.ensureConnected();
427
+ const user = await this.findUserByEmail(email);
428
+ if (!user) return null;
429
+ const stored = this.db.prepare(
430
+ "SELECT password_hash FROM kyro_users WHERE id = ?"
431
+ ).get(user.id);
432
+ if (!stored?.password_hash) return null;
433
+ const valid = await bcrypt.compare(password, stored.password_hash);
434
+ return valid ? user : null;
435
+ }
436
+ async createSession(userId, data = {}) {
437
+ await this.ensureConnected();
438
+ const id = randomBytes(32).toString("hex");
439
+ const token = randomBytes(32).toString("base64url");
440
+ const refreshToken = randomBytes(32).toString("base64url");
441
+ const now = /* @__PURE__ */ new Date();
442
+ const expiresAt = new Date(now.getTime() + 864e5).toISOString();
443
+ const session = {
444
+ id,
445
+ userId,
446
+ token,
447
+ refreshToken,
448
+ expiresAt,
449
+ createdAt: now.toISOString(),
450
+ ipAddress: data.ipAddress,
451
+ userAgent: data.userAgent
452
+ };
453
+ this.db.prepare(
454
+ `INSERT INTO kyro_sessions (id, user_id, token, refresh_token, expires_at, created_at, ip_address, user_agent)
455
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)`
456
+ ).run(
457
+ session.id,
458
+ session.userId,
459
+ session.token,
460
+ session.refreshToken,
461
+ session.expiresAt,
462
+ session.createdAt,
463
+ session.ipAddress,
464
+ session.userAgent
465
+ );
466
+ return session;
467
+ }
468
+ async findSessionByToken(token) {
469
+ await this.ensureConnected();
470
+ const row = this.stmt("findSessionByToken").get(token);
471
+ if (!row) return null;
472
+ return this.rowToSession(row);
473
+ }
474
+ async findSessionByRefreshToken(refreshToken) {
475
+ await this.ensureConnected();
476
+ const row = this.stmt("findSessionByRefreshToken").get(refreshToken);
477
+ if (!row) return null;
478
+ return this.rowToSession(row);
479
+ }
480
+ async deleteSession(sessionId) {
481
+ await this.ensureConnected();
482
+ const result = this.stmt("deleteSession").run(sessionId, sessionId);
483
+ return result.changes > 0;
484
+ }
485
+ async deleteUserSessions(userId) {
486
+ await this.ensureConnected();
487
+ const result = this.stmt("deleteUserSessions").run(userId);
488
+ return result.changes;
489
+ }
490
+ async hasAnyUsers() {
491
+ await this.ensureConnected();
492
+ const row = this.stmt("countUsers").get();
493
+ return row.count > 0;
494
+ }
495
+ async findUsers(options = {}) {
496
+ await this.ensureConnected();
497
+ const page = options.page ?? 1;
498
+ const limit = options.limit ?? 10;
499
+ const offset = (page - 1) * limit;
500
+ const search = options.search;
501
+ let total;
502
+ let rows;
503
+ if (search) {
504
+ const searchPattern = `%${search}%`;
505
+ total = this.stmt("countUsersWithSearch").get(searchPattern).count;
506
+ rows = this.stmt("findUsersWithSearch").all(
507
+ searchPattern,
508
+ limit,
509
+ offset
510
+ );
511
+ } else {
512
+ total = this.stmt("countUsers").get().count;
513
+ rows = this.stmt("findUsersPaginated").all(limit, offset);
514
+ }
515
+ return {
516
+ users: rows.map((row) => this.rowToUser(row)),
517
+ total
518
+ };
519
+ }
520
+ async addPasswordToHistory(userId, passwordHash) {
521
+ await this.ensureConnected();
522
+ this.stmt("addPasswordHistory").run(
523
+ userId,
524
+ passwordHash,
525
+ (/* @__PURE__ */ new Date()).toISOString()
526
+ );
527
+ this.stmt("trimPasswordHistory").run(userId);
528
+ }
529
+ async getPasswordHistory(userId, count = 5) {
530
+ await this.ensureConnected();
531
+ const rows = this.stmt("getPasswordHistory").all(userId, count);
532
+ return rows.map((r) => r.password_hash);
533
+ }
534
+ async isPasswordInHistory(password, userId, historyCount = 5) {
535
+ const history = await this.getPasswordHistory(userId, historyCount);
536
+ for (const hash of history) {
537
+ if (await bcrypt.compare(password, hash)) {
538
+ return true;
539
+ }
540
+ }
541
+ return false;
542
+ }
543
+ async recordFailedAttempt(userId) {
544
+ await this.ensureConnected();
545
+ const now = Date.now();
546
+ const lockout = this.stmt("getLockout").get(userId);
547
+ const attempts = (lockout?.attempts || 0) + 1;
548
+ const lockedUntil = attempts >= 5 ? now + 15 * 60 * 1e3 : lockout?.locked_until || null;
549
+ this.stmt("upsertLockout").run(
550
+ userId,
551
+ attempts,
552
+ now,
553
+ lockedUntil !== null ? now : null,
554
+ lockedUntil
555
+ );
556
+ }
557
+ async resetAttempts(userId) {
558
+ await this.ensureConnected();
559
+ this.stmt("resetLockout").run(userId);
560
+ }
561
+ async checkLockout(userId) {
562
+ await this.ensureConnected();
563
+ this.stmt("cleanupExpiredLockouts").run(Date.now());
564
+ const lockout = this.stmt("getLockout").get(userId);
565
+ if (!lockout) {
566
+ return {
567
+ locked: false,
568
+ attemptsRemaining: 5,
569
+ totalAttempts: 0
570
+ };
571
+ }
572
+ if (lockout.locked_until !== null && lockout.locked_until > Date.now()) {
573
+ return {
574
+ locked: true,
575
+ attemptsRemaining: 0,
576
+ lockedUntil: new Date(lockout.locked_until),
577
+ totalAttempts: lockout.attempts
578
+ };
579
+ }
580
+ return {
581
+ locked: false,
582
+ attemptsRemaining: Math.max(0, 5 - lockout.attempts),
583
+ totalAttempts: lockout.attempts
584
+ };
585
+ }
586
+ async logAudit(data) {
587
+ await this.ensureConnected();
588
+ const id = randomBytes(16).toString("hex");
589
+ const timestamp = (/* @__PURE__ */ new Date()).toISOString();
590
+ this.db.prepare(
591
+ `INSERT INTO kyro_audit_logs (
592
+ id, timestamp, action, user_id, user_email, role, resource, resource_id,
593
+ ip_address, user_agent, success, error, metadata, created_at
594
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
595
+ ).run(
596
+ id,
597
+ timestamp,
598
+ data.action,
599
+ data.userId || null,
600
+ data.userEmail || null,
601
+ data.role || null,
602
+ data.resource,
603
+ data.resourceId || null,
604
+ data.ipAddress || null,
605
+ data.userAgent || null,
606
+ data.success ? 1 : 0,
607
+ data.error || null,
608
+ data.metadata ? JSON.stringify(data.metadata) : null,
609
+ (/* @__PURE__ */ new Date()).toISOString()
610
+ );
611
+ return id;
612
+ }
613
+ async queryAuditLogs(options = {}) {
614
+ await this.ensureConnected();
615
+ const conditions = [];
616
+ const params = [];
617
+ if (options.action) {
618
+ conditions.push("action = ?");
619
+ params.push(options.action);
620
+ }
621
+ if (options.userId) {
622
+ conditions.push("user_id = ?");
623
+ params.push(options.userId);
624
+ }
625
+ if (options.resource) {
626
+ conditions.push("resource = ?");
627
+ params.push(options.resource);
628
+ }
629
+ if (options.success !== void 0) {
630
+ conditions.push("success = ?");
631
+ params.push(options.success ? 1 : 0);
632
+ }
633
+ if (options.startDate) {
634
+ conditions.push("timestamp >= ?");
635
+ params.push(options.startDate.toISOString());
636
+ }
637
+ if (options.endDate) {
638
+ conditions.push("timestamp <= ?");
639
+ params.push(options.endDate.toISOString());
640
+ }
641
+ const where = conditions.length > 0 ? "WHERE " + conditions.join(" AND ") : "";
642
+ const limit = options.limit || 50;
643
+ const offset = options.offset || 0;
644
+ const totalResult = this.db.prepare(
645
+ `SELECT COUNT(*) as count FROM kyro_audit_logs ${where}`
646
+ ).get(...params);
647
+ const rows = this.db.prepare(
648
+ `SELECT * FROM kyro_audit_logs ${where} ORDER BY timestamp DESC LIMIT ? OFFSET ?`
649
+ ).all(...params, limit, offset);
650
+ return {
651
+ total: totalResult.count,
652
+ logs: rows.map((row) => ({
653
+ id: row.id,
654
+ timestamp: new Date(row.timestamp),
655
+ action: row.action,
656
+ userId: row.user_id || void 0,
657
+ userEmail: row.user_email || void 0,
658
+ resource: row.resource,
659
+ resourceId: row.resource_id || void 0,
660
+ ipAddress: row.ip_address || void 0,
661
+ userAgent: row.user_agent || void 0,
662
+ success: row.success === 1,
663
+ error: row.error || void 0,
664
+ metadata: row.metadata ? JSON.parse(row.metadata) : void 0
665
+ }))
666
+ };
667
+ }
668
+ rowToUser(row) {
669
+ return {
670
+ id: row.id,
671
+ name: row.name || void 0,
672
+ email: row.email,
673
+ passwordHash: row.password_hash,
674
+ role: row.role,
675
+ tenantId: row.tenant_id,
676
+ emailVerified: row.email_verified === 1,
677
+ locked: row.locked === 1,
678
+ lastLogin: row.last_login,
679
+ failedLoginAttempts: row.failed_login_attempts || 0,
680
+ createdAt: row.created_at,
681
+ updatedAt: row.updated_at
682
+ };
683
+ }
684
+ rowToSession(row) {
685
+ return {
686
+ id: row.id,
687
+ userId: row.user_id,
688
+ token: row.token,
689
+ refreshToken: row.refresh_token,
690
+ expiresAt: row.expires_at,
691
+ createdAt: row.created_at,
692
+ ipAddress: row.ip_address,
693
+ userAgent: row.user_agent
694
+ };
695
+ }
696
+ async findAuditLogs(filter) {
697
+ const result = await this.queryAuditLogs({
698
+ action: filter.action,
699
+ userId: filter.userId,
700
+ resource: filter.resource,
701
+ success: filter.success,
702
+ startDate: filter.startDate,
703
+ endDate: filter.endDate,
704
+ limit: filter.limit,
705
+ offset: filter.offset
706
+ });
707
+ return {
708
+ logs: result.logs.map((log) => ({
709
+ ...log,
710
+ action: log.action
711
+ })),
712
+ total: result.total
713
+ };
714
+ }
715
+ async createAuditLog(data) {
716
+ const id = await this.logAudit({
717
+ action: data.action,
718
+ userId: data.userId,
719
+ userEmail: data.userEmail,
720
+ role: data.role,
721
+ resource: data.resource,
722
+ resourceId: data.resourceId,
723
+ ipAddress: data.ipAddress,
724
+ userAgent: data.userAgent,
725
+ success: data.success,
726
+ error: data.error,
727
+ metadata: data.metadata
728
+ });
729
+ const row = this.db?.prepare("SELECT * FROM kyro_audit_logs WHERE id = ?").get(id);
730
+ return {
731
+ ...data,
732
+ id,
733
+ timestamp: row ? new Date(row.timestamp) : /* @__PURE__ */ new Date()
734
+ };
735
+ }
736
+ async createEmailVerificationToken(userId) {
737
+ await this.ensureConnected();
738
+ const id = randomBytes(16).toString("hex");
739
+ const token = randomBytes(32).toString("hex");
740
+ const expiresAt = new Date(Date.now() + 24 * 60 * 60 * 1e3);
741
+ this.db.prepare(
742
+ "INSERT INTO kyro_email_verifications (id, user_id, token, expires_at, created_at) VALUES (?, ?, ?, ?, ?)"
743
+ ).run(id, userId, token, expiresAt.toISOString(), (/* @__PURE__ */ new Date()).toISOString());
744
+ return { token, expiresAt };
745
+ }
746
+ async verifyEmailToken(token) {
747
+ await this.ensureConnected();
748
+ const row = this.db.prepare(
749
+ "SELECT * FROM kyro_email_verifications WHERE token = ?"
750
+ ).get(token);
751
+ if (!row) {
752
+ return { success: false, error: "Invalid verification token" };
753
+ }
754
+ if (new Date(row.expires_at) < /* @__PURE__ */ new Date()) {
755
+ return { success: false, error: "Verification token has expired" };
756
+ }
757
+ this.db.prepare(
758
+ "UPDATE kyro_users SET email_verified = 1 WHERE id = ?"
759
+ ).run(row.user_id);
760
+ this.db.prepare(
761
+ "DELETE FROM kyro_email_verifications WHERE id = ?"
762
+ ).run(row.id);
763
+ return { success: true, userId: row.user_id };
764
+ }
765
+ async createPasswordResetToken(email) {
766
+ await this.ensureConnected();
767
+ const user = await this.findUserByEmail(email);
768
+ if (!user) {
769
+ return { token: "", expiresAt: /* @__PURE__ */ new Date(), error: "User not found" };
770
+ }
771
+ const id = randomBytes(16).toString("hex");
772
+ const token = randomBytes(32).toString("hex");
773
+ const expiresAt = new Date(Date.now() + 60 * 60 * 1e3);
774
+ this.db.prepare(
775
+ "INSERT INTO kyro_password_resets (id, user_id, token, expires_at, created_at) VALUES (?, ?, ?, ?, ?)"
776
+ ).run(id, user.id, token, expiresAt.toISOString(), (/* @__PURE__ */ new Date()).toISOString());
777
+ return { token, expiresAt };
778
+ }
779
+ async resetPasswordWithToken(token, newPassword) {
780
+ await this.ensureConnected();
781
+ const row = this.db.prepare(
782
+ "SELECT * FROM kyro_password_resets WHERE token = ?"
783
+ ).get(token);
784
+ if (!row) {
785
+ return { success: false, error: "Invalid reset token" };
786
+ }
787
+ if (new Date(row.expires_at) < /* @__PURE__ */ new Date()) {
788
+ return { success: false, error: "Reset token has expired" };
789
+ }
790
+ if (row.used_at) {
791
+ return { success: false, error: "Reset token has already been used" };
792
+ }
793
+ const passwordHash = await this.hashPassword(newPassword);
794
+ this.db.prepare(
795
+ "UPDATE kyro_users SET password_hash = ?, updated_at = ? WHERE id = ?"
796
+ ).run(passwordHash, (/* @__PURE__ */ new Date()).toISOString(), row.user_id);
797
+ this.db.prepare(
798
+ "UPDATE kyro_password_resets SET used_at = ? WHERE id = ?"
799
+ ).run((/* @__PURE__ */ new Date()).toISOString(), row.id);
800
+ this.db.prepare(
801
+ "DELETE FROM kyro_sessions WHERE user_id = ?"
802
+ ).run(row.user_id);
803
+ return { success: true };
804
+ }
805
+ };
806
+
807
+ export { SQLiteAuthAdapter };
808
+ //# sourceMappingURL=chunk-H727JIG7.js.map
809
+ //# sourceMappingURL=chunk-H727JIG7.js.map