|
|
@@ -13,8 +13,7 @@ const DB_DIR = path.dirname(DB_PATH);
|
|
|
|
|
|
let db = null;
|
|
|
|
|
|
-async function initializeSchema() {
|
|
|
- // Create users table
|
|
|
+async function seedInfo() {
|
|
|
db.exec(`
|
|
|
CREATE TABLE IF NOT EXISTS users (
|
|
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
|
@@ -24,28 +23,33 @@ async function initializeSchema() {
|
|
|
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
|
|
);
|
|
|
`);
|
|
|
-}
|
|
|
+ db.prepare('INSERT INTO users (email, password) VALUES (?, ?)').run('admin@delete.me', await hashPassword('deleteme'));
|
|
|
|
|
|
-async function seedAdminUser() {
|
|
|
- const stmt = db.prepare('SELECT COUNT(*) as count FROM users');
|
|
|
- const result = stmt.get();
|
|
|
+ db.exec(`
|
|
|
+ CREATE TABLE IF NOT EXISTS scopes (
|
|
|
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
|
+ name TEXT UNIQUE NOT NULL
|
|
|
+ );
|
|
|
+ `);
|
|
|
+ for (const name of [ 'admin', 'llm', 'mcp', 'user' ]) db.prepare('INSERT INTO scopes (name) VALUES (?)').run(name);
|
|
|
|
|
|
- // Only seed if no users exist
|
|
|
- if (result.count === 0) {
|
|
|
- const hashedPassword = await hashPassword('deleteme');
|
|
|
- const insertStmt = db.prepare(
|
|
|
- 'INSERT INTO users (email, password) VALUES (?, ?)'
|
|
|
+ db.exec(`
|
|
|
+ CREATE TABLE IF NOT EXISTS user_scopes (
|
|
|
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
|
+ user_id INTEGER NOT NULL,
|
|
|
+ scope_id INTEGER NOT NULL,
|
|
|
+ UNIQUE(user_id, scope_id),
|
|
|
+ FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
|
|
|
+ FOREIGN KEY (scope_id) REFERENCES scopes(id) ON DELETE CASCADE
|
|
|
);
|
|
|
- insertStmt.run('admin@delete.me', hashedPassword);
|
|
|
- }
|
|
|
+ `);
|
|
|
+ db.prepare('INSERT INTO user_scopes (user_id, scope_id) VALUES (1, 1)').run();
|
|
|
}
|
|
|
|
|
|
export async function getSqlite3() {
|
|
|
- if (db) return db;
|
|
|
+ if (config.database.type !== "sqlite3" || db) return db;
|
|
|
|
|
|
- if (!fs.existsSync(DB_DIR)) {
|
|
|
- fs.mkdirSync(DB_DIR, { recursive: true });
|
|
|
- }
|
|
|
+ if (!fs.existsSync(DB_DIR)) fs.mkdirSync(DB_DIR, { recursive: true });
|
|
|
|
|
|
const isNewDb = !fs.existsSync(DB_PATH);
|
|
|
|
|
|
@@ -62,8 +66,13 @@ export async function getSqlite3() {
|
|
|
db.pragma(`temp_store = ${dbConfig.performance.tempStore}`);
|
|
|
|
|
|
if (isNewDb) {
|
|
|
- await initializeSchema();
|
|
|
- await seedAdminUser();
|
|
|
+ try {
|
|
|
+ await seedInfo();
|
|
|
+ } catch (error) {
|
|
|
+ db.close();
|
|
|
+ db = null;
|
|
|
+ throw error;
|
|
|
+ }
|
|
|
}
|
|
|
|
|
|
return db;
|
|
|
@@ -73,9 +82,10 @@ export function closeSqlite3() {
|
|
|
if (db) {
|
|
|
try {
|
|
|
db.close();
|
|
|
+ } catch (error) {
|
|
|
+ throw error;
|
|
|
+ } finally {
|
|
|
db = null;
|
|
|
- } catch (err) {
|
|
|
- throw err;
|
|
|
}
|
|
|
}
|
|
|
}
|