import { Global, Injectable, Module, OnModuleDestroy } from '@nestjs/common'; import { DatabaseSync } from 'node:sqlite'; import { mkdirSync, existsSync, readFileSync, writeFileSync } from 'node:fs'; import { resolve, join } from 'node:path'; import { randomBytes } from 'node:crypto'; export const dataDir = () => resolve(process.env.DATA_DIR || './data'); export function secret(name: string): Buffer { const configured = process.env[name]; if (configured) { const value = Buffer.from(configured, 'hex'); if (value.length !== 32 || !/^[a-f\d]{64}$/i.test(configured)) throw new Error(`${name} must contain 64 hexadecimal characters`); return value; } mkdirSync(dataDir(), { recursive: true }); const file = join(dataDir(), `${name.toLowerCase()}.key`); if (!existsSync(file)) { if ( process.env.NODE_ENV === 'production' && process.env.REQUIRE_STATIC_SECRETS === 'true' ) throw new Error(`${name} is required in production`); writeFileSync(file, randomBytes(32), { flag: 'wx', mode: 0o600 }); } const value = readFileSync(file); if (value.length !== 32) throw new Error(`Invalid key file: ${name}`); return value; } @Injectable() export class Store implements OnModuleDestroy { readonly db: DatabaseSync; constructor() { mkdirSync(dataDir(), { recursive: true }); this.db = new DatabaseSync(join(dataDir(), 'stillwave.sqlite')); this.db .exec(`PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL; PRAGMA busy_timeout=5000; CREATE TABLE IF NOT EXISTS documents ( collection TEXT NOT NULL, id TEXT NOT NULL, owner TEXT NOT NULL DEFAULT '', data TEXT NOT NULL, updated INTEGER NOT NULL, PRIMARY KEY(collection,id)); CREATE INDEX IF NOT EXISTS documents_owner ON documents(collection,owner,updated DESC); CREATE UNIQUE INDEX IF NOT EXISTS users_email ON documents(json_extract(data,'$.email')) WHERE collection='users'; CREATE UNIQUE INDEX IF NOT EXISTS users_username ON documents(json_extract(data,'$.username')) WHERE collection='users';`); } get(collection: string, id: string): T | undefined { const row = this.db .prepare('SELECT data FROM documents WHERE collection=? AND id=?') .get(collection, id); return row ? JSON.parse(row.data as string) : undefined; } list(collection: string, owner?: string, limit = -1): T[] { const rows = owner === undefined ? this.db .prepare( 'SELECT data FROM documents WHERE collection=? ORDER BY updated DESC LIMIT ?', ) .all(collection, limit) : this.db .prepare( 'SELECT data FROM documents WHERE collection=? AND owner=? ORDER BY updated DESC LIMIT ?', ) .all(collection, owner, limit); return rows.map((row) => JSON.parse(row.data as string)); } put(collection: string, value: T, owner = ''): T { this.db .prepare( `INSERT INTO documents VALUES(?,?,?,?,?) ON CONFLICT(collection,id) DO UPDATE SET owner=excluded.owner,data=excluded.data,updated=excluded.updated`, ) .run(collection, value.id, owner, JSON.stringify(value), Date.now()); return value; } remove(collection: string, id: string) { this.db .prepare('DELETE FROM documents WHERE collection=? AND id=?') .run(collection, id); } transaction(fn: () => T): T { this.db.exec('BEGIN IMMEDIATE'); try { const value = fn(); this.db.exec('COMMIT'); return value; } catch (error) { this.db.exec('ROLLBACK'); throw error; } } onModuleDestroy() { this.db.close(); } } @Global() @Module({ providers: [Store], exports: [Store] }) export class StoreModule {}