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