187 lines
8.9 KiB
TypeScript
187 lines
8.9 KiB
TypeScript
import { mkdirSync, chmodSync } from 'node:fs';
|
||
import { resolve, join } from 'node:path';
|
||
import { randomUUID } from 'node:crypto';
|
||
import { DatabaseSync, type SQLInputValue } from 'node:sqlite';
|
||
import { hashPasswordSync } from './password.ts';
|
||
|
||
export type AccountRole = 'admin' | 'user';
|
||
export type AccountRow = {
|
||
id: string; username: string; display_name: string; password_hash: string;
|
||
role: AccountRole; disabled: number; must_change_password: number;
|
||
created_at: string; updated_at: string; last_login_at: string | null;
|
||
};
|
||
|
||
export function normalizeUsername(value: unknown): string {
|
||
if (typeof value !== 'string' || !/^[a-zA-Z0-9][a-zA-Z0-9._@-]{2,63}$/.test(value.trim())) {
|
||
throw new Error('账号须为 3–64 位字母、数字或 . _ @ -,并以字母或数字开头。');
|
||
}
|
||
return value.trim().toLowerCase();
|
||
}
|
||
|
||
export function normalizeDisplayName(value: unknown): string {
|
||
if (typeof value !== 'string' || !value.trim() || value.trim().length > 80 || /[\u0000-\u001f\u007f]/.test(value)) {
|
||
throw new Error('姓名须为 1–80 个字符。');
|
||
}
|
||
return value.trim();
|
||
}
|
||
|
||
export function applicationOrigin(request?: Request): string {
|
||
const configured = process.env.APP_URL;
|
||
if (!configured) {
|
||
if (process.env.NODE_ENV === 'production') throw new Error('生产环境必须设置 APP_URL,例如 https://demand.example.com。');
|
||
return request ? new URL(request.url).origin : 'http://localhost:3000';
|
||
}
|
||
const url = new URL(configured);
|
||
if (!['https:', 'http:'].includes(url.protocol) || url.username || url.password || (url.pathname !== '/' && url.pathname !== '') || url.search || url.hash) {
|
||
throw new Error('APP_URL 必须为系统的完整访问域名,例如 https://demand.example.com,不含路径。');
|
||
}
|
||
return url.origin;
|
||
}
|
||
|
||
class PreparedQuery {
|
||
private database: DatabaseSync;
|
||
private sql: string;
|
||
private values: SQLInputValue[];
|
||
constructor(database: DatabaseSync, sql: string, values: SQLInputValue[] = []) {
|
||
this.database = database; this.sql = sql; this.values = values;
|
||
}
|
||
bind(...values: SQLInputValue[]): PreparedQuery { return new PreparedQuery(this.database, this.sql, values); }
|
||
all<T = Record<string, unknown>>(): { results: T[] } {
|
||
return { results: this.database.prepare(this.sql).all(...this.values) as T[] };
|
||
}
|
||
first<T = Record<string, unknown>>(): T | null {
|
||
return (this.database.prepare(this.sql).get(...this.values) as T | undefined) ?? null;
|
||
}
|
||
run(): { meta: { changes: number; last_row_id: number | bigint } } {
|
||
const result = this.database.prepare(this.sql).run(...this.values);
|
||
return { meta: { changes: Number(result.changes), last_row_id: result.lastInsertRowid } };
|
||
}
|
||
}
|
||
|
||
export class AppDatabase {
|
||
private database: DatabaseSync;
|
||
constructor(database: DatabaseSync) { this.database = database; }
|
||
prepare(sql: string): PreparedQuery { return new PreparedQuery(this.database, sql); }
|
||
transaction<T>(action: () => T): T {
|
||
this.database.exec('BEGIN IMMEDIATE');
|
||
try { const result = action(); this.database.exec('COMMIT'); return result; }
|
||
catch (error) { this.database.exec('ROLLBACK'); throw error; }
|
||
}
|
||
close(): void { this.database.close(); }
|
||
}
|
||
|
||
const databases = new Map<string, AppDatabase>();
|
||
|
||
function migrate(database: DatabaseSync): void {
|
||
database.exec('BEGIN IMMEDIATE');
|
||
try {
|
||
const version = Number((database.prepare('PRAGMA user_version').get() as { user_version: number }).user_version);
|
||
if (version > 3) throw new Error('数据库版本比当前应用更新,请使用匹配的应用版本。');
|
||
if (version < 1) {
|
||
database.exec(`
|
||
CREATE TABLE IF NOT EXISTS demands (
|
||
id TEXT PRIMARY KEY, owner_id TEXT NOT NULL, payload TEXT NOT NULL,
|
||
revision INTEGER NOT NULL DEFAULT 1, updated_at TEXT NOT NULL
|
||
);
|
||
CREATE INDEX IF NOT EXISTS demands_owner_updated ON demands(owner_id, updated_at DESC);
|
||
CREATE TABLE IF NOT EXISTS accounts (
|
||
id TEXT PRIMARY KEY, username TEXT NOT NULL COLLATE NOCASE UNIQUE,
|
||
display_name TEXT NOT NULL, password_hash TEXT NOT NULL,
|
||
role TEXT NOT NULL CHECK(role IN ('admin', 'user')),
|
||
disabled INTEGER NOT NULL DEFAULT 0 CHECK(disabled IN (0, 1)),
|
||
must_change_password INTEGER NOT NULL DEFAULT 1 CHECK(must_change_password IN (0, 1)),
|
||
created_at TEXT NOT NULL, updated_at TEXT NOT NULL, last_login_at TEXT
|
||
);
|
||
CREATE TABLE IF NOT EXISTS sessions (
|
||
token_hash TEXT PRIMARY KEY, account_id TEXT NOT NULL REFERENCES accounts(id) ON DELETE CASCADE,
|
||
expires_at INTEGER NOT NULL, created_at INTEGER NOT NULL
|
||
);
|
||
CREATE INDEX IF NOT EXISTS sessions_account ON sessions(account_id);
|
||
CREATE INDEX IF NOT EXISTS sessions_expiry ON sessions(expires_at);
|
||
CREATE TABLE IF NOT EXISTS login_limits (
|
||
key TEXT PRIMARY KEY, window_start INTEGER NOT NULL, attempts INTEGER NOT NULL
|
||
);
|
||
PRAGMA user_version = 1;
|
||
`);
|
||
}
|
||
if (version < 2) {
|
||
database.exec(`
|
||
CREATE TABLE IF NOT EXISTS attachments (
|
||
id TEXT PRIMARY KEY,
|
||
owner_id TEXT NOT NULL REFERENCES accounts(id),
|
||
demand_id TEXT REFERENCES demands(id),
|
||
name TEXT NOT NULL,
|
||
size INTEGER NOT NULL CHECK(size > 0 AND size <= 20971520),
|
||
content BLOB NOT NULL,
|
||
created_at TEXT NOT NULL
|
||
);
|
||
CREATE INDEX IF NOT EXISTS attachments_demand ON attachments(demand_id);
|
||
CREATE INDEX IF NOT EXISTS attachments_owner_staged ON attachments(owner_id, demand_id, created_at);
|
||
PRAGMA user_version = 2;
|
||
`);
|
||
}
|
||
if (version < 3) {
|
||
database.exec(`
|
||
CREATE TABLE feishu_identities (
|
||
account_id TEXT PRIMARY KEY REFERENCES accounts(id) ON DELETE CASCADE,
|
||
app_id TEXT NOT NULL, tenant_key TEXT NOT NULL, open_id TEXT NOT NULL,
|
||
name TEXT NOT NULL, bound_at TEXT NOT NULL,
|
||
UNIQUE(app_id, tenant_key, open_id)
|
||
);
|
||
CREATE TABLE feishu_oauth_states (
|
||
state_hash TEXT PRIMARY KEY, browser_hash TEXT NOT NULL,
|
||
account_id TEXT REFERENCES accounts(id) ON DELETE CASCADE,
|
||
session_hash TEXT, app_id TEXT NOT NULL, verifier TEXT NOT NULL,
|
||
return_to TEXT NOT NULL, expires_at INTEGER NOT NULL
|
||
);
|
||
CREATE INDEX feishu_oauth_expiry ON feishu_oauth_states(expires_at);
|
||
CREATE TABLE feishu_notifications (
|
||
id TEXT PRIMARY KEY, demand_id TEXT NOT NULL REFERENCES demands(id),
|
||
revision INTEGER NOT NULL, target_key TEXT NOT NULL, content TEXT NOT NULL,
|
||
status TEXT NOT NULL DEFAULT 'pending' CHECK(status IN ('pending','sending','sent','failed')),
|
||
attempts INTEGER NOT NULL DEFAULT 0, next_attempt_at INTEGER NOT NULL,
|
||
lease_token TEXT, last_error TEXT, created_at TEXT NOT NULL, sent_at TEXT,
|
||
UNIQUE(demand_id, revision, target_key)
|
||
);
|
||
CREATE INDEX feishu_notifications_due ON feishu_notifications(status, next_attempt_at);
|
||
PRAGMA user_version = 3;
|
||
`);
|
||
}
|
||
const count = Number((database.prepare('SELECT COUNT(*) AS count FROM accounts').get() as { count: number }).count);
|
||
if (count === 0) {
|
||
const username = process.env.INITIAL_ADMIN_USERNAME;
|
||
const password = process.env.INITIAL_ADMIN_PASSWORD;
|
||
if (!username || !password) throw new Error('首次启动请设置 INITIAL_ADMIN_USERNAME 和 INITIAL_ADMIN_PASSWORD(至少 12 位)。');
|
||
const now = new Date().toISOString();
|
||
database.prepare(`INSERT INTO accounts (id, username, display_name, password_hash, role, must_change_password, created_at, updated_at)
|
||
VALUES (?, ?, ?, ?, 'admin', 1, ?, ?)`).run(randomUUID(), normalizeUsername(username), normalizeDisplayName(process.env.INITIAL_ADMIN_DISPLAY_NAME || '系统管理员'), hashPasswordSync(password), now, now);
|
||
}
|
||
database.exec('COMMIT');
|
||
} catch (error) { database.exec('ROLLBACK'); throw error; }
|
||
}
|
||
|
||
// Lazy initialization is intentional: Next.js builds never open or bootstrap a database.
|
||
export function getDatabase(): AppDatabase {
|
||
applicationOrigin();
|
||
const directory = resolve(process.env.DATA_DIR || './data');
|
||
const filename = join(directory, 'demand-center.sqlite');
|
||
const existing = databases.get(filename);
|
||
if (existing) return existing;
|
||
mkdirSync(directory, { recursive: true, mode: 0o700 });
|
||
const native = new DatabaseSync(filename);
|
||
try {
|
||
chmodSync(filename, 0o600);
|
||
native.exec('PRAGMA busy_timeout = 5000; PRAGMA foreign_keys = ON; PRAGMA journal_mode = WAL; PRAGMA synchronous = FULL;');
|
||
migrate(native);
|
||
const adapter = new AppDatabase(native);
|
||
databases.set(filename, adapter);
|
||
return adapter;
|
||
} catch (error) { native.close(); throw error; }
|
||
}
|
||
|
||
/** Close connections for isolated test processes and graceful maintenance tooling. */
|
||
export function closeDatabases(): void {
|
||
for (const database of databases.values()) database.close();
|
||
databases.clear();
|
||
}
|