36 lines
1.4 KiB
JavaScript
36 lines
1.4 KiB
JavaScript
import { pbkdf2Sync, randomBytes } from 'node:crypto';
|
|
import { rm } from 'node:fs/promises';
|
|
import { isAbsolute, join, relative, resolve } from 'node:path';
|
|
import { createDatabase } from '../database.mjs';
|
|
import { createBaseDatabase } from '../src/data/base.mjs';
|
|
|
|
const root = resolve(process.cwd());
|
|
const databasePath = join(root, 'data', 'exam.sqlite');
|
|
const relativePath = relative(root, databasePath);
|
|
if (!relativePath || relativePath.startsWith('..') || isAbsolute(relativePath)) throw new Error('拒绝重建工作区以外的数据库');
|
|
|
|
for (const path of [databasePath, `${databasePath}-shm`, `${databasePath}-wal`]) await rm(path, { force: true });
|
|
|
|
function hashPassword(password, salt = randomBytes(16).toString('hex')) {
|
|
const hash = pbkdf2Sync(password, salt, 120000, 32, 'sha256').toString('hex');
|
|
return `${salt}:${hash}`;
|
|
}
|
|
|
|
process.env.DATABASE_CLIENT = 'sqlite';
|
|
process.env.SQLITE_PATH = databasePath;
|
|
const database = await createDatabase({
|
|
root,
|
|
seed: () => createBaseDatabase({
|
|
nowIso: () => new Date().toISOString(),
|
|
hashPassword,
|
|
initialAdmin: {
|
|
username: process.env.INITIAL_ADMIN_USERNAME,
|
|
password: process.env.INITIAL_ADMIN_PASSWORD,
|
|
displayName: process.env.INITIAL_ADMIN_DISPLAY_NAME
|
|
}
|
|
})
|
|
});
|
|
const state = await database.read();
|
|
await database.close();
|
|
console.log(`Rebuilt empty ${databasePath} (schema ${state.meta.version}, ${state.candidateProfiles.length} candidates)`);
|