local-lite 2.0.6 → 3.0.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.
Files changed (82) hide show
  1. package/README.md +0 -30
  2. package/dist/adapters/local/index.d.ts +1 -0
  3. package/dist/adapters/local/index.js +1 -0
  4. package/dist/adapters/local/sqlite-wasm.d.ts +25 -0
  5. package/dist/adapters/local/sqlite-wasm.js +55 -0
  6. package/dist/adapters/remote/convex.d.ts +1 -1
  7. package/dist/adapters/remote/convex.js +25 -3
  8. package/dist/adapters/remote/demo.d.ts +3 -3
  9. package/dist/adapters/remote/demo.js +11 -3
  10. package/dist/adapters/remote/firestore.d.ts +1 -1
  11. package/dist/adapters/remote/firestore.js +57 -91
  12. package/dist/adapters/remote/index.d.ts +2 -1
  13. package/dist/adapters/remote/index.js +1 -0
  14. package/dist/adapters/remote/postgres.d.ts +37 -0
  15. package/dist/adapters/remote/postgres.js +119 -0
  16. package/dist/adapters/remote/self-hosted.d.ts +12 -0
  17. package/dist/adapters/remote/self-hosted.js +55 -4
  18. package/dist/adapters/remote/supabase.d.ts +1 -1
  19. package/dist/adapters/remote/supabase.js +22 -5
  20. package/dist/auth/apple.js +0 -6
  21. package/dist/auth/github.js +0 -3
  22. package/dist/auth/google.js +0 -3
  23. package/dist/auth/identity.d.ts +0 -5
  24. package/dist/auth/identity.js +0 -3
  25. package/dist/auth/microsoft.js +0 -3
  26. package/dist/auth/unified.d.ts +5 -5
  27. package/dist/auth/unified.js +1 -1
  28. package/dist/config/index.d.ts +0 -12
  29. package/dist/config/index.js +3 -26
  30. package/dist/config/types.d.ts +3 -2
  31. package/dist/core/audit.d.ts +52 -0
  32. package/dist/core/audit.js +153 -0
  33. package/dist/core/client.d.ts +4 -0
  34. package/dist/core/client.js +7 -0
  35. package/dist/core/conflict.d.ts +24 -0
  36. package/dist/core/conflict.js +77 -0
  37. package/dist/core/field-encryption.d.ts +25 -0
  38. package/dist/core/field-encryption.js +128 -0
  39. package/dist/core/index.d.ts +2 -0
  40. package/dist/core/index.js +2 -0
  41. package/dist/core/query-builder.d.ts +51 -0
  42. package/dist/core/query-builder.js +278 -35
  43. package/dist/core/query.js +6 -1
  44. package/dist/core/types.d.ts +2 -1
  45. package/dist/devtools/BenchmarkModal.js +285 -1
  46. package/dist/email/index.d.ts +1 -1
  47. package/dist/email/index.js +2 -2
  48. package/dist/index.d.ts +2 -27
  49. package/dist/index.js +2 -27
  50. package/dist/presence/index.d.ts +45 -0
  51. package/dist/presence/index.js +142 -0
  52. package/dist/reactive/event-emitter.d.ts +10 -1
  53. package/dist/reactive/event-emitter.js +44 -1
  54. package/dist/reactive/live-query.d.ts +18 -0
  55. package/dist/reactive/live-query.js +71 -0
  56. package/dist/schema/index.d.ts +1 -0
  57. package/dist/schema/index.js +1 -0
  58. package/dist/schema/typed.d.ts +38 -0
  59. package/dist/schema/typed.js +33 -0
  60. package/dist/server/dashboard.d.ts +2 -0
  61. package/dist/server/dashboard.js +1272 -1044
  62. package/dist/solid/index.d.ts +24 -0
  63. package/dist/solid/index.js +35 -0
  64. package/dist/storage/firebase.d.ts +3 -3
  65. package/dist/storage/firebase.js +40 -94
  66. package/dist/svelte/index.d.ts +15 -0
  67. package/dist/svelte/index.js +27 -0
  68. package/dist/testing/index.d.ts +22 -0
  69. package/dist/testing/index.js +74 -0
  70. package/dist/vue/index.d.ts +27 -0
  71. package/dist/vue/index.js +37 -0
  72. package/package.json +46 -9
  73. package/dist/kv/index.d.ts +0 -3
  74. package/dist/kv/index.js +0 -19
  75. package/dist/kv/manager.d.ts +0 -52
  76. package/dist/kv/manager.js +0 -167
  77. package/dist/kv/store.d.ts +0 -13
  78. package/dist/kv/store.js +0 -85
  79. package/dist/kv/types.d.ts +0 -27
  80. package/dist/kv/types.js +0 -2
  81. package/dist/react/kv.d.ts +0 -9
  82. package/dist/react/kv.js +0 -53
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.createDashboardHandler = createDashboardHandler;
4
+ const local_js_1 = require("../auth/local.js");
4
5
  const encryption_js_1 = require("../backups/encryption.js");
5
6
  const store_js_1 = require("../kv-store/store.js");
6
7
  const sql_js_1 = require("../utils/sql.js");
@@ -26,6 +27,30 @@ function isAuthorized(request, url, authToken) {
26
27
  return true;
27
28
  return false;
28
29
  }
30
+ function extractSessionToken(request, url) {
31
+ const header = request.headers.get('authorization');
32
+ if (header && header.startsWith('Bearer ')) {
33
+ const token = header.slice(7).trim();
34
+ if (token)
35
+ return token;
36
+ }
37
+ const queryToken = url.searchParams.get('token');
38
+ if (queryToken)
39
+ return queryToken;
40
+ const cookieHeader = request.headers.get('cookie');
41
+ if (cookieHeader) {
42
+ for (const part of cookieHeader.split(';')) {
43
+ const eq = part.indexOf('=');
44
+ if (eq === -1)
45
+ continue;
46
+ const k = part.slice(0, eq).trim();
47
+ if (k === 'local_lite_session') {
48
+ return decodeURIComponent(part.slice(eq + 1).trim());
49
+ }
50
+ }
51
+ }
52
+ return null;
53
+ }
29
54
  async function listTables(db) {
30
55
  const tablesRows = await db.execute(`SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name ASC;`);
31
56
  const summaries = [];
@@ -113,7 +138,45 @@ function toCsv(columns, rows) {
113
138
  function createDashboardHandler(db, options = {}) {
114
139
  const title = options.title ?? 'local-lite Dashboard';
115
140
  const readOnly = Boolean(options.readOnly);
141
+ const requireAuth = options.requireAuth !== false;
116
142
  const basePath = (options.basePath ?? '').replace(/\/+$/, '');
143
+ const authEngine = new local_js_1.LocalAuthEngine(db);
144
+ let authInitPromise = null;
145
+ const ensureAuth = () => (authInitPromise ??= authEngine.initialize());
146
+ const countUsers = async () => {
147
+ await ensureAuth();
148
+ const rows = (await db.execute(`SELECT COUNT(*) AS cnt FROM _local_users;`)) ?? [];
149
+ return Number(rows[0]?.cnt ?? 0);
150
+ };
151
+ const verifyLocalSession = async (request, url) => {
152
+ const token = extractSessionToken(request, url);
153
+ if (!token)
154
+ return null;
155
+ await ensureAuth();
156
+ const rows = (await db.execute(`SELECT s.id AS session_id, s.user_id, s.expires_at, u.email, u.username, u.display_name, u.role
157
+ FROM _local_sessions s
158
+ INNER JOIN _local_users u ON u.id = s.user_id
159
+ WHERE s.token = ?
160
+ LIMIT 1;`, [token])) ?? [];
161
+ const row = rows[0];
162
+ if (!row)
163
+ return null;
164
+ if (row.expires_at !== null && row.expires_at !== undefined && Number(row.expires_at) <= Date.now()) {
165
+ return null;
166
+ }
167
+ return {
168
+ id: String(row.user_id),
169
+ email: row.email ? String(row.email) : undefined,
170
+ username: row.username ? String(row.username) : undefined,
171
+ name: row.display_name ? String(row.display_name) : undefined,
172
+ role: row.role ? String(row.role) : undefined,
173
+ };
174
+ };
175
+ const withSessionCookie = (res, token, maxAgeSeconds = 60 * 60 * 24 * 7) => {
176
+ const headers = new Headers(res.headers);
177
+ headers.append('Set-Cookie', `local_lite_session=${encodeURIComponent(token)}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${maxAgeSeconds}`);
178
+ return new Response(res.body, { status: res.status, headers });
179
+ };
117
180
  const logs = [];
118
181
  let nextLogId = 1;
119
182
  const recordLog = (method, path, status, startedAt, detail) => {
@@ -132,988 +195,1088 @@ function createDashboardHandler(db, options = {}) {
132
195
  logs.length = 200;
133
196
  };
134
197
  return async (request) => {
198
+ const origin = request.headers.get('origin');
199
+ const applyCors = (response) => {
200
+ if (!origin)
201
+ return response;
202
+ const headers = new Headers(response.headers);
203
+ headers.set('Access-Control-Allow-Origin', origin);
204
+ headers.set('Access-Control-Allow-Credentials', 'true');
205
+ headers.set('Access-Control-Allow-Headers', 'Content-Type, Authorization');
206
+ headers.set('Access-Control-Allow-Methods', 'GET, POST, PATCH, PUT, DELETE, OPTIONS');
207
+ headers.set('Vary', 'Origin');
208
+ return new Response(response.body, {
209
+ status: response.status,
210
+ statusText: response.statusText,
211
+ headers,
212
+ });
213
+ };
214
+ if (request.method === 'OPTIONS') {
215
+ return applyCors(new Response(null, { status: 204 }));
216
+ }
135
217
  const startedAt = performance.now();
136
218
  const url = new URL(request.url);
137
219
  let pathname = url.pathname;
138
220
  if (basePath && pathname.startsWith(basePath)) {
139
221
  pathname = pathname.slice(basePath.length) || '/';
140
222
  }
141
- if (!isAuthorized(request, url, options.authToken)) {
223
+ if (options.authToken && !isAuthorized(request, url, options.authToken)) {
142
224
  recordLog(request.method, pathname, 401, startedAt, 'Unauthorized');
143
225
  return errorResponse('Unauthorized.', 401);
144
226
  }
145
- const reply = (res, detail) => {
146
- if (pathname.startsWith('/api/')) {
147
- recordLog(request.method, pathname, res.status, startedAt, detail);
148
- }
149
- return res;
150
- };
151
- try {
152
- if (request.method === 'GET' &&
153
- (pathname === '/' || pathname === '/index.html' || pathname.startsWith('/assets/'))) {
154
- const staticRes = await tryServeDashboardAsset(pathname, title);
155
- if (staticRes)
156
- return staticRes;
157
- return new Response(`<!DOCTYPE html><html><head><meta charset="utf-8"/><title>${escapeHtml(title)}</title></head><body style="font-family:sans-serif;background:#0b0d12;color:#e6ebf5;padding:32px;"><h2>${escapeHtml(title)}</h2><p>Dashboard UI not built. Run <code>npm --prefix dashboard run build</code> or launch via <code>npx local-lite dashboard</code>.</p></body></html>`, {
158
- status: 200,
159
- headers: {
160
- 'Content-Type': 'text/html; charset=utf-8',
161
- 'Cache-Control': 'no-store',
162
- },
163
- });
164
- }
165
- if (request.method === 'GET' && pathname === '/api/overview') {
166
- const [tables, versionRows, journalRows, pageSizeRows, pageCountRows] = await Promise.all([
167
- listTables(db),
168
- db.execute('SELECT sqlite_version() AS version;'),
169
- db.execute('PRAGMA journal_mode;').catch(() => []),
170
- db.execute('PRAGMA page_size;').catch(() => []),
171
- db.execute('PRAGMA page_count;').catch(() => []),
172
- ]);
173
- const dataTables = tables.filter((t) => !t.internal);
174
- const systemTables = tables.filter((t) => t.internal);
175
- const totalRows = dataTables.reduce((acc, t) => acc + t.rowCount, 0);
176
- const totalIndexes = tables.reduce((acc, t) => acc + t.indexes.length, 0);
177
- const pageSize = Number(pageSizeRows?.[0]?.page_size ?? 0);
178
- const pageCount = Number(pageCountRows?.[0]?.page_count ?? 0);
227
+ // ── Local Auth endpoints (accessible before login) ──────────────────
228
+ if (pathname === '/api/dashboard-auth/status' && request.method === 'GET') {
229
+ try {
230
+ const userCount = await countUsers();
231
+ const sessionUser = requireAuth ? await verifyLocalSession(request, url) : null;
179
232
  return jsonResponse({
180
- title,
181
- readOnly,
182
- sqliteVersion: String(versionRows?.[0]?.version ?? 'unknown'),
183
- journalMode: String(journalRows?.[0]?.journal_mode ?? 'unknown'),
184
- databaseSizeBytes: pageSize * pageCount,
185
- dataTableCount: dataTables.length,
186
- systemTableCount: systemTables.length,
187
- totalDataRows: totalRows,
188
- totalIndexes,
189
- topTables: [...dataTables]
190
- .sort((a, b) => b.rowCount - a.rowCount)
191
- .slice(0, 8)
192
- .map((t) => ({ name: t.name, rowCount: t.rowCount })),
233
+ requireAuth,
234
+ authenticated: !requireAuth || Boolean(options.authToken && isAuthorized(request, url, options.authToken)) || Boolean(sessionUser),
235
+ userCount,
236
+ user: sessionUser,
193
237
  });
194
238
  }
195
- if (request.method === 'GET' && pathname === '/api/tables') {
196
- const tables = await listTables(db);
197
- return jsonResponse({ tables });
239
+ catch (err) {
240
+ return errorResponse(err?.message ?? 'Auth status failed.', 500);
198
241
  }
199
- if (request.method === 'GET' && pathname === '/api/schema/sql') {
200
- const dialectRaw = (url.searchParams.get('dialect') ?? 'sqlite').toLowerCase();
201
- const dialect = ['sqlite', 'postgres', 'mysql'].includes(dialectRaw)
202
- ? dialectRaw
203
- : 'sqlite';
204
- const includeSystem = url.searchParams.get('includeSystem') === '1';
205
- const onlyTable = url.searchParams.get('table');
206
- const allTables = await listTables(db);
207
- const selected = allTables.filter((t) => {
208
- if (onlyTable && t.name !== onlyTable)
209
- return false;
210
- if (!onlyTable && !includeSystem && t.internal)
211
- return false;
212
- return true;
213
- });
214
- const quoteId = (id) => dialect === 'mysql'
215
- ? `\`${id.replace(/`/g, '``')}\``
216
- : (0, sql_js_1.escapeIdentifier)(id);
217
- const mapColType = (rawType, isPk) => {
218
- const upper = (rawType || 'TEXT').toUpperCase();
219
- if (dialect === 'sqlite')
220
- return upper;
221
- if (dialect === 'postgres') {
222
- if (upper.includes('INT'))
223
- return 'BIGINT';
224
- if (upper.includes('REAL') || upper.includes('FLOA') || upper.includes('DOUB'))
225
- return 'DOUBLE PRECISION';
226
- if (upper.includes('BLOB'))
227
- return 'BYTEA';
228
- if (upper.includes('NUM') || upper.includes('DEC'))
229
- return 'NUMERIC';
230
- return 'TEXT';
231
- }
232
- // mysql
233
- if (upper.includes('INT'))
234
- return 'BIGINT';
235
- if (upper.includes('REAL') || upper.includes('FLOA') || upper.includes('DOUB'))
236
- return 'DOUBLE';
237
- if (upper.includes('BLOB'))
238
- return 'LONGBLOB';
239
- if (upper.includes('NUM') || upper.includes('DEC'))
240
- return 'DECIMAL(18, 4)';
241
- return isPk ? 'VARCHAR(255)' : 'TEXT';
242
- };
243
- const statements = [];
244
- for (const t of selected) {
245
- const pkCols = t.columns.filter((c) => c.pk > 0).sort((a, b) => a.pk - b.pk);
246
- const singlePk = pkCols.length === 1;
247
- const lines = t.columns.map((c) => {
248
- const parts = [quoteId(c.name), mapColType(c.type, c.pk > 0)];
249
- if (singlePk && c.pk > 0)
250
- parts.push('PRIMARY KEY');
251
- if (c.notnull > 0 && !(singlePk && c.pk > 0))
252
- parts.push('NOT NULL');
253
- if (c.dflt_value != null)
254
- parts.push(`DEFAULT ${String(c.dflt_value)}`);
255
- return ` ${parts.join(' ')}`;
256
- });
257
- if (pkCols.length > 1) {
258
- lines.push(` PRIMARY KEY (${pkCols.map((c) => quoteId(c.name)).join(', ')})`);
259
- }
260
- statements.push(`CREATE TABLE IF NOT EXISTS ${quoteId(t.name)} (\n${lines.join(',\n')}\n);`);
261
- for (const idx of t.indexes) {
262
- if (idx.name.startsWith('sqlite_autoindex_') || idx.columns.length === 0) {
263
- continue;
264
- }
265
- const uniqueSql = idx.unique ? 'UNIQUE ' : '';
266
- const ifNotExists = dialect === 'mysql' ? '' : 'IF NOT EXISTS ';
267
- statements.push(`CREATE ${uniqueSql}INDEX ${ifNotExists}${quoteId(idx.name)} ON ${quoteId(t.name)} (${idx.columns.map(quoteId).join(', ')});`);
268
- }
269
- }
270
- const sql = statements.join('\n\n');
271
- if (url.searchParams.get('download') === '1') {
272
- return new Response(sql, {
273
- status: 200,
274
- headers: {
275
- 'Content-Type': 'application/sql; charset=utf-8',
276
- 'Content-Disposition': `attachment; filename="schema-${dialect}.sql"`,
277
- },
278
- });
279
- }
280
- return jsonResponse({ dialect, tableCount: selected.length, sql });
281
- }
282
- if (request.method === 'POST' && pathname === '/api/tables') {
283
- if (readOnly) {
284
- return errorResponse('Dashboard is running in read-only mode.', 403);
242
+ }
243
+ if (pathname === '/api/dashboard-auth/setup' && request.method === 'POST') {
244
+ try {
245
+ const userCount = await countUsers();
246
+ if (userCount > 0) {
247
+ return errorResponse('Admin account already exists. Please sign in.', 403);
285
248
  }
286
249
  const body = (await request.json().catch(() => null));
287
- const name = String(body?.name ?? '').trim();
288
- if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(name)) {
289
- return errorResponse('Invalid table name. Use letters, numbers, and underscores.', 400);
290
- }
291
- if ((0, sql_js_1.isInternalTable)(name)) {
292
- return errorResponse('Cannot create an internal system table.', 400);
293
- }
294
- const cols = Array.isArray(body?.columns) ? body.columns : [];
295
- if (cols.length === 0) {
296
- return errorResponse('At least one column is required.', 400);
297
- }
298
- const allowedTypes = new Set(['TEXT', 'INTEGER', 'REAL', 'BLOB', 'NUMERIC']);
299
- const colDefs = cols.map((c) => {
300
- const colName = String(c.name ?? '').trim();
301
- if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(colName)) {
302
- throw new Error(`Invalid column name: ${colName}`);
303
- }
304
- const colType = allowedTypes.has(String(c.type ?? 'TEXT').toUpperCase())
305
- ? String(c.type ?? 'TEXT').toUpperCase()
306
- : 'TEXT';
307
- const parts = [(0, sql_js_1.escapeIdentifier)(colName), colType];
308
- if (c.pk)
309
- parts.push('PRIMARY KEY');
310
- if (c.notnull && !c.pk)
311
- parts.push('NOT NULL');
312
- return parts.join(' ');
250
+ const result = await authEngine.signUp({
251
+ email: String(body?.email ?? ''),
252
+ username: body?.username ? String(body.username) : undefined,
253
+ password: String(body?.password ?? ''),
254
+ displayName: body?.name ? String(body.name) : undefined,
255
+ role: 'admin',
313
256
  });
314
- await db.execute(`CREATE TABLE ${(0, sql_js_1.escapeIdentifier)(name)} (${colDefs.join(', ')});`);
315
- return jsonResponse({ ok: true, name }, 201);
316
- }
317
- const tableTargetMatch = pathname.match(/^\/api\/tables\/([^/]+)$/);
318
- if (tableTargetMatch && request.method === 'PATCH') {
319
- if (readOnly) {
320
- return errorResponse('Dashboard is running in read-only mode.', 403);
321
- }
322
- const tableName = decodeURIComponent(tableTargetMatch[1]);
323
- if ((0, sql_js_1.isInternalTable)(tableName)) {
324
- return errorResponse('Cannot modify internal system tables.', 403);
257
+ let token = result.session?.token ?? '';
258
+ if (!token && result.session?.id) {
259
+ token = (0, local_js_1.generateCryptoToken)(32).token;
260
+ await db.execute(`UPDATE _local_sessions SET token = ? WHERE id = ?;`, [
261
+ token,
262
+ result.session.id,
263
+ ]);
325
264
  }
265
+ const res = jsonResponse({
266
+ user: result.user,
267
+ token,
268
+ expiresAt: result.session?.expiresAt ?? null,
269
+ }, 201);
270
+ return token ? withSessionCookie(res, token) : res;
271
+ }
272
+ catch (err) {
273
+ return errorResponse(err?.message ?? 'Setup failed.', 400);
274
+ }
275
+ }
276
+ if (pathname === '/api/dashboard-auth/login' && request.method === 'POST') {
277
+ try {
278
+ await ensureAuth();
326
279
  const body = (await request.json().catch(() => null));
327
- if (body?.newName) {
328
- const nextName = String(body.newName).trim();
329
- if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(nextName) || (0, sql_js_1.isInternalTable)(nextName)) {
330
- return errorResponse('Invalid target table name.', 400);
331
- }
332
- await db.execute(`ALTER TABLE ${(0, sql_js_1.escapeIdentifier)(tableName)} RENAME TO ${(0, sql_js_1.escapeIdentifier)(nextName)};`);
333
- return jsonResponse({ ok: true, name: nextName });
334
- }
335
- if (body?.addColumn) {
336
- const colName = String(body.addColumn.name ?? '').trim();
337
- if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(colName)) {
338
- return errorResponse('Invalid column name.', 400);
339
- }
340
- const allowedTypes = new Set(['TEXT', 'INTEGER', 'REAL', 'BLOB', 'NUMERIC']);
341
- const colType = allowedTypes.has(String(body.addColumn.type ?? 'TEXT').toUpperCase())
342
- ? String(body.addColumn.type ?? 'TEXT').toUpperCase()
343
- : 'TEXT';
344
- const parts = [(0, sql_js_1.escapeIdentifier)(colName), colType];
345
- const dflt = body.addColumn.defaultValue;
346
- if (dflt !== undefined && dflt !== '') {
347
- const escapedDflt = `'${String(dflt).replace(/'/g, "''")}'`;
348
- if (body.addColumn.notnull)
349
- parts.push('NOT NULL');
350
- parts.push(`DEFAULT ${escapedDflt}`);
351
- }
352
- else if (body.addColumn.notnull) {
353
- parts.push("NOT NULL DEFAULT ''");
354
- }
355
- await db.execute(`ALTER TABLE ${(0, sql_js_1.escapeIdentifier)(tableName)} ADD COLUMN ${parts.join(' ')};`);
356
- return jsonResponse({ ok: true });
357
- }
358
- if (body?.dropColumn) {
359
- const colName = String(body.dropColumn).trim();
360
- if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(colName)) {
361
- return errorResponse('Invalid column name.', 400);
362
- }
363
- await db.execute(`ALTER TABLE ${(0, sql_js_1.escapeIdentifier)(tableName)} DROP COLUMN ${(0, sql_js_1.escapeIdentifier)(colName)};`);
364
- return jsonResponse({ ok: true });
280
+ const result = await authEngine.signIn({
281
+ identifier: String(body?.identifier ?? ''),
282
+ password: String(body?.password ?? ''),
283
+ });
284
+ let token = result.session?.token ?? '';
285
+ if (!token && result.session?.id) {
286
+ token = (0, local_js_1.generateCryptoToken)(32).token;
287
+ await db.execute(`UPDATE _local_sessions SET token = ? WHERE id = ?;`, [
288
+ token,
289
+ result.session.id,
290
+ ]);
365
291
  }
366
- return errorResponse('Provide newName, addColumn, or dropColumn.', 400);
292
+ const res = jsonResponse({
293
+ user: result.user,
294
+ token,
295
+ expiresAt: result.session?.expiresAt ?? null,
296
+ });
297
+ return token ? withSessionCookie(res, token) : res;
367
298
  }
368
- if (tableTargetMatch && request.method === 'DELETE') {
369
- if (readOnly) {
370
- return errorResponse('Dashboard is running in read-only mode.', 403);
371
- }
372
- const tableName = decodeURIComponent(tableTargetMatch[1]);
373
- if ((0, sql_js_1.isInternalTable)(tableName)) {
374
- return errorResponse('Cannot drop internal system tables.', 403);
375
- }
376
- await db.execute(`DROP TABLE IF EXISTS ${(0, sql_js_1.escapeIdentifier)(tableName)};`);
377
- return jsonResponse({ ok: true });
299
+ catch (err) {
300
+ return errorResponse(err?.message ?? 'Invalid credentials.', 401);
378
301
  }
379
- const clearTableMatch = pathname.match(/^\/api\/tables\/([^/]+)\/clear$/);
380
- if (clearTableMatch && request.method === 'POST') {
381
- if (readOnly) {
382
- return errorResponse('Dashboard is running in read-only mode.', 403);
383
- }
384
- const tableName = decodeURIComponent(clearTableMatch[1]);
385
- if ((0, sql_js_1.isInternalTable)(tableName)) {
386
- return errorResponse('Cannot clear internal system tables from here.', 403);
387
- }
388
- await db.execute(`DELETE FROM ${(0, sql_js_1.escapeIdentifier)(tableName)};`);
389
- return jsonResponse({ ok: true });
302
+ }
303
+ if (pathname === '/api/dashboard-auth/logout' && request.method === 'POST') {
304
+ try {
305
+ const token = extractSessionToken(request, url);
306
+ if (token) {
307
+ await ensureAuth();
308
+ await db.execute(`DELETE FROM _local_sessions WHERE token = ?;`, [token]);
309
+ }
310
+ return withSessionCookie(jsonResponse({ ok: true }), '', 0);
390
311
  }
391
- const importTableMatch = pathname.match(/^\/api\/tables\/([^/]+)\/import$/);
392
- if (importTableMatch && request.method === 'POST') {
393
- if (readOnly) {
394
- return errorResponse('Dashboard is running in read-only mode.', 403);
395
- }
396
- const tableName = decodeURIComponent(importTableMatch[1]);
397
- const tables = await listTables(db);
398
- const tableMeta = tables.find((t) => t.name === tableName);
399
- if (!tableMeta) {
400
- return errorResponse(`Table "${tableName}" not found.`, 404);
401
- }
402
- const body = (await request.json().catch(() => null));
403
- const rows = Array.isArray(body?.rows) ? body.rows : [];
404
- if (rows.length === 0) {
405
- return errorResponse('rows array is required.', 400);
406
- }
407
- const validCols = new Set(tableMeta.columns.map((c) => c.name));
408
- let imported = 0;
409
- for (const row of rows) {
410
- if (!row || typeof row !== 'object')
411
- continue;
412
- const entries = Object.entries(row).filter(([k]) => validCols.has(k));
413
- if (entries.length === 0)
414
- continue;
415
- const cols = entries.map(([k]) => (0, sql_js_1.escapeIdentifier)(k)).join(', ');
416
- const placeholders = entries.map(() => '?').join(', ');
417
- await db.execute(`INSERT OR REPLACE INTO ${(0, sql_js_1.escapeIdentifier)(tableName)} (${cols}) VALUES (${placeholders});`, entries.map(([, v]) => v));
418
- imported += 1;
419
- }
420
- return jsonResponse({ ok: true, imported });
312
+ catch (err) {
313
+ return errorResponse(err?.message ?? 'Logout failed.', 500);
421
314
  }
422
- const indexCreateMatch = pathname.match(/^\/api\/tables\/([^/]+)\/indexes$/);
423
- if (indexCreateMatch && request.method === 'POST') {
424
- if (readOnly) {
425
- return errorResponse('Dashboard is running in read-only mode.', 403);
426
- }
427
- const tableName = decodeURIComponent(indexCreateMatch[1]);
428
- const body = (await request.json().catch(() => null));
429
- const idxName = String(body?.name ?? '').trim();
430
- const cols = Array.isArray(body?.columns) ? body.columns.filter(Boolean) : [];
431
- if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(idxName) || cols.length === 0) {
432
- return errorResponse('Valid index name and at least one column are required.', 400);
433
- }
434
- const uniqueSql = body?.unique ? 'UNIQUE ' : '';
435
- const colSql = cols.map((c) => (0, sql_js_1.escapeIdentifier)(c)).join(', ');
436
- await db.execute(`CREATE ${uniqueSql}INDEX IF NOT EXISTS ${(0, sql_js_1.escapeIdentifier)(idxName)} ON ${(0, sql_js_1.escapeIdentifier)(tableName)} (${colSql});`);
437
- return jsonResponse({ ok: true }, 201);
315
+ }
316
+ // Gate all other /api/* requests behind local-lite session auth when requireAuth is enabled
317
+ if (requireAuth && pathname.startsWith('/api/')) {
318
+ const staticTokenOk = Boolean(options.authToken && isAuthorized(request, url, options.authToken));
319
+ const sessionUser = staticTokenOk ? { id: 'token' } : await verifyLocalSession(request, url);
320
+ if (!sessionUser) {
321
+ recordLog(request.method, pathname, 401, startedAt, 'Unauthorized');
322
+ return errorResponse('Authentication required.', 401);
438
323
  }
439
- const indexDropMatch = pathname.match(/^\/api\/tables\/([^/]+)\/indexes\/([^/]+)$/);
440
- if (indexDropMatch && request.method === 'DELETE') {
441
- if (readOnly) {
442
- return errorResponse('Dashboard is running in read-only mode.', 403);
443
- }
444
- const idxName = decodeURIComponent(indexDropMatch[2]);
445
- await db.execute(`DROP INDEX IF EXISTS ${(0, sql_js_1.escapeIdentifier)(idxName)};`);
446
- return jsonResponse({ ok: true });
324
+ }
325
+ let loggedThisRequest = false;
326
+ const reply = (res, detail) => {
327
+ if (pathname.startsWith('/api/')) {
328
+ loggedThisRequest = true;
329
+ recordLog(request.method, pathname, res.status, startedAt, detail);
447
330
  }
448
- const exportMatch = pathname.match(/^\/api\/tables\/([^/]+)\/export$/);
449
- if (exportMatch && request.method === 'GET') {
450
- const tableName = decodeURIComponent(exportMatch[1]);
451
- const tables = await listTables(db);
452
- const tableMeta = tables.find((t) => t.name === tableName);
453
- if (!tableMeta) {
454
- return errorResponse(`Table "${tableName}" not found.`, 404);
455
- }
456
- const format = url.searchParams.get('format') === 'csv' ? 'csv' : 'json';
457
- const rows = (await db.execute(`SELECT * FROM ${(0, sql_js_1.escapeIdentifier)(tableName)} LIMIT 10000;`)) ?? [];
458
- if (format === 'csv') {
459
- const cols = tableMeta.columns.map((c) => c.name);
460
- return new Response(toCsv(cols, rows), {
331
+ return res;
332
+ };
333
+ const res = await (async () => {
334
+ try {
335
+ if (request.method === 'GET' &&
336
+ (pathname === '/' || pathname === '/index.html' || pathname.startsWith('/assets/'))) {
337
+ const staticRes = await tryServeDashboardAsset(pathname, title);
338
+ if (staticRes)
339
+ return staticRes;
340
+ return new Response(`<!DOCTYPE html><html><head><meta charset="utf-8"/><title>${escapeHtml(title)}</title></head><body style="font-family:sans-serif;background:#0b0d12;color:#e6ebf5;padding:32px;"><h2>${escapeHtml(title)}</h2><p>Dashboard UI not built. Run <code>npm --prefix dashboard run build</code> or launch via <code>npx local-lite dashboard</code>.</p></body></html>`, {
461
341
  status: 200,
462
342
  headers: {
463
- 'Content-Type': 'text/csv; charset=utf-8',
464
- 'Content-Disposition': `attachment; filename="${tableName}.csv"`,
343
+ 'Content-Type': 'text/html; charset=utf-8',
344
+ 'Cache-Control': 'no-store',
465
345
  },
466
346
  });
467
347
  }
468
- return new Response(JSON.stringify(rows, null, 2), {
469
- status: 200,
470
- headers: {
471
- 'Content-Type': 'application/json; charset=utf-8',
472
- 'Content-Disposition': `attachment; filename="${tableName}.json"`,
473
- },
474
- });
475
- }
476
- const tableRowsMatch = pathname.match(/^\/api\/tables\/([^/]+)\/rows$/);
477
- if (tableRowsMatch) {
478
- const tableName = decodeURIComponent(tableRowsMatch[1]);
479
- const tables = await listTables(db);
480
- const tableMeta = tables.find((t) => t.name === tableName);
481
- if (!tableMeta) {
482
- return errorResponse(`Table "${tableName}" not found.`, 404);
483
- }
484
- const quotedTable = (0, sql_js_1.escapeIdentifier)(tableName);
485
- if (request.method === 'GET') {
486
- const limit = Math.min(500, Math.max(1, Number(url.searchParams.get('limit') ?? 50)));
487
- const offset = Math.max(0, Number(url.searchParams.get('offset') ?? 0));
488
- const search = (url.searchParams.get('search') ?? '').trim();
489
- const filterCol = (url.searchParams.get('filterCol') ?? '').trim();
490
- const filterVal = url.searchParams.get('filterVal') ?? '';
491
- const orderBy = url.searchParams.get('orderBy') ?? '';
492
- const orderDir = url.searchParams.get('orderDir')?.toUpperCase() === 'DESC'
493
- ? 'DESC'
494
- : 'ASC';
495
- const validColNames = new Set(tableMeta.columns.map((c) => c.name));
496
- const params = [];
497
- const conditions = [];
498
- if (search && tableMeta.columns.length > 0) {
499
- const likeTerm = `%${search.replace(/[%_\\]/g, '\\$&')}%`;
500
- const predicates = tableMeta.columns.map((col) => {
501
- params.push(likeTerm);
502
- return `CAST(${(0, sql_js_1.escapeIdentifier)(col.name)} AS TEXT) LIKE ? ESCAPE '\\'`;
503
- });
504
- conditions.push(`(${predicates.join(' OR ')})`);
505
- }
506
- if (filterCol && validColNames.has(filterCol) && filterVal !== '') {
507
- params.push(filterVal);
508
- conditions.push(`CAST(${(0, sql_js_1.escapeIdentifier)(filterCol)} AS TEXT) = ?`);
509
- }
510
- const whereClause = conditions.length > 0 ? ` WHERE ${conditions.join(' AND ')}` : '';
511
- let orderClause = '';
512
- if (orderBy && validColNames.has(orderBy)) {
513
- orderClause = ` ORDER BY ${(0, sql_js_1.escapeIdentifier)(orderBy)} ${orderDir}`;
514
- }
515
- const countRows = await db.execute(`SELECT COUNT(*) AS cnt FROM ${quotedTable}${whereClause};`, params);
516
- const total = Number(countRows?.[0]?.cnt ?? 0);
517
- const rows = await db.execute(`SELECT * FROM ${quotedTable}${whereClause}${orderClause} LIMIT ? OFFSET ?;`, [...params, limit, offset]);
348
+ if (request.method === 'GET' && pathname === '/api/overview') {
349
+ const [tables, versionRows, journalRows, pageSizeRows, pageCountRows] = await Promise.all([
350
+ listTables(db),
351
+ db.execute('SELECT sqlite_version() AS version;'),
352
+ db.execute('PRAGMA journal_mode;').catch(() => []),
353
+ db.execute('PRAGMA page_size;').catch(() => []),
354
+ db.execute('PRAGMA page_count;').catch(() => []),
355
+ ]);
356
+ const dataTables = tables.filter((t) => !t.internal);
357
+ const systemTables = tables.filter((t) => t.internal);
358
+ const totalRows = dataTables.reduce((acc, t) => acc + t.rowCount, 0);
359
+ const totalIndexes = tables.reduce((acc, t) => acc + t.indexes.length, 0);
360
+ const pageSize = Number(pageSizeRows?.[0]?.page_size ?? 0);
361
+ const pageCount = Number(pageCountRows?.[0]?.page_count ?? 0);
518
362
  return jsonResponse({
519
- table: tableMeta,
520
- rows: rows ?? [],
521
- total,
522
- limit,
523
- offset,
524
- });
525
- }
526
- if (readOnly) {
527
- return errorResponse('Dashboard is running in read-only mode.', 403);
528
- }
529
- const body = (await request.json().catch(() => null));
530
- if (!body || typeof body !== 'object') {
531
- return errorResponse('JSON object body is required.', 400);
532
- }
533
- const validColNames = new Set(tableMeta.columns.map((c) => c.name));
534
- const pkColumns = tableMeta.columns
535
- .filter((c) => c.pk > 0)
536
- .sort((a, b) => a.pk - b.pk);
537
- if (request.method === 'POST') {
538
- const entries = Object.entries(body).filter(([key]) => validColNames.has(key));
539
- if (entries.length === 0) {
540
- return errorResponse('At least one valid column is required.', 400);
541
- }
542
- const cols = entries.map(([k]) => (0, sql_js_1.escapeIdentifier)(k)).join(', ');
543
- const placeholders = entries.map(() => '?').join(', ');
544
- const values = entries.map(([, v]) => v);
545
- await db.execute(`INSERT INTO ${quotedTable} (${cols}) VALUES (${placeholders});`, values);
546
- return jsonResponse({ ok: true }, 201);
547
- }
548
- if (request.method === 'PATCH') {
549
- if (pkColumns.length === 0) {
550
- return errorResponse(`Table "${tableName}" has no primary key for row updates.`, 400);
551
- }
552
- const updates = body.updates;
553
- const key = body.key;
554
- if (!updates || !key) {
555
- return errorResponse('Both "key" and "updates" objects are required.', 400);
556
- }
557
- const setEntries = Object.entries(updates).filter(([col]) => validColNames.has(col));
558
- if (setEntries.length === 0) {
559
- return errorResponse('No valid update columns provided.', 400);
560
- }
561
- const setClause = setEntries
562
- .map(([col]) => `${(0, sql_js_1.escapeIdentifier)(col)} = ?`)
563
- .join(', ');
564
- const whereClause = pkColumns
565
- .map((pk) => `${(0, sql_js_1.escapeIdentifier)(pk.name)} = ?`)
566
- .join(' AND ');
567
- const params = [
568
- ...setEntries.map(([, val]) => val),
569
- ...pkColumns.map((pk) => key[pk.name]),
570
- ];
571
- await db.execute(`UPDATE ${quotedTable} SET ${setClause} WHERE ${whereClause};`, params);
572
- return jsonResponse({ ok: true });
573
- }
574
- if (request.method === 'DELETE') {
575
- if (pkColumns.length === 0) {
576
- return errorResponse(`Table "${tableName}" has no primary key for row deletion.`, 400);
577
- }
578
- const key = (body.key ?? body);
579
- const whereClause = pkColumns
580
- .map((pk) => `${(0, sql_js_1.escapeIdentifier)(pk.name)} = ?`)
581
- .join(' AND ');
582
- const params = pkColumns.map((pk) => key[pk.name]);
583
- await db.execute(`DELETE FROM ${quotedTable} WHERE ${whereClause};`, params);
584
- return jsonResponse({ ok: true });
585
- }
586
- }
587
- if (request.method === 'POST' && pathname === '/api/query') {
588
- const body = (await request.json().catch(() => null));
589
- const sql = String(body?.sql ?? '').trim();
590
- if (!sql) {
591
- return errorResponse('SQL query is required.', 400);
592
- }
593
- if (readOnly && !(0, sql_js_1.isReadQuery)(sql)) {
594
- return errorResponse('Only read-only SELECT / WITH / EXPLAIN / PRAGMA queries are allowed in read-only mode.', 403);
595
- }
596
- const started = performance.now();
597
- const rows = (await db.execute(sql, Array.isArray(body?.params) ? body.params : [])) ?? [];
598
- const durationMs = Math.round((performance.now() - started) * 100) / 100;
599
- const columns = rows.length > 0 && typeof rows[0] === 'object' && rows[0] !== null
600
- ? Object.keys(rows[0])
601
- : [];
602
- return reply(jsonResponse({
603
- columns,
604
- rows,
605
- rowsAffected: 0,
606
- durationMs,
607
- }), sql.slice(0, 160));
608
- }
609
- if (request.method === 'GET' && pathname === '/api/system') {
610
- const [outbox, kvStore, scheduler, actions, users, sessions, migrations] = await Promise.all([
611
- readRowsIfTableExists(db, 'sync_outbox', 200),
612
- readRowsIfTableExists(db, store_js_1.DEFAULT_KV_STORE_TABLE, 200),
613
- readRowsIfTableExists(db, '_local_scheduler', 100),
614
- readRowsIfTableExists(db, '_local_actions', 100),
615
- readRowsIfTableExists(db, '_local_users', 100),
616
- readRowsIfTableExists(db, '_local_sessions', 100),
617
- readRowsIfTableExists(db, 'schema_migrations', 100),
618
- ]);
619
- return jsonResponse({
620
- outbox,
621
- kvStore,
622
- scheduler,
623
- actions,
624
- users,
625
- sessions,
626
- migrations,
627
- });
628
- }
629
- if (request.method === 'GET' && pathname === '/api/settings') {
630
- const [journalRows, syncRows, busyRows, cacheRows, fkRows, pageSizeRows, pageCountRows, freelistRows, kvRows, outboxRows, scheduledJobsRows, schedulerRows,] = await Promise.all([
631
- db.execute('PRAGMA journal_mode;').catch(() => []),
632
- db.execute('PRAGMA synchronous;').catch(() => []),
633
- db.execute('PRAGMA busy_timeout;').catch(() => []),
634
- db.execute('PRAGMA cache_size;').catch(() => []),
635
- db.execute('PRAGMA foreign_keys;').catch(() => []),
636
- db.execute('PRAGMA page_size;').catch(() => []),
637
- db.execute('PRAGMA page_count;').catch(() => []),
638
- db.execute('PRAGMA freelist_count;').catch(() => []),
639
- readRowsIfTableExists(db, store_js_1.DEFAULT_KV_STORE_TABLE, 500),
640
- readRowsIfTableExists(db, 'sync_outbox', 1000),
641
- readRowsIfTableExists(db, '_local_scheduled_jobs', 100),
642
- readRowsIfTableExists(db, '_local_scheduler', 100),
643
- ]);
644
- const outboxList = outboxRows ?? [];
645
- return jsonResponse({
646
- dashboard: {
647
363
  title,
648
364
  readOnly,
649
- authEnabled: Boolean(options.authToken),
650
- basePath,
651
- },
652
- pragmas: {
365
+ sqliteVersion: String(versionRows?.[0]?.version ?? 'unknown'),
653
366
  journalMode: String(journalRows?.[0]?.journal_mode ?? 'unknown'),
654
- synchronous: Number(syncRows?.[0]?.synchronous ?? 0),
655
- busyTimeout: Number(busyRows?.[0]?.timeout ?? busyRows?.[0]?.busy_timeout ?? 0),
656
- cacheSize: Number(cacheRows?.[0]?.cache_size ?? 0),
657
- foreignKeys: Boolean(Number(fkRows?.[0]?.foreign_keys ?? 0)),
658
- pageSize: Number(pageSizeRows?.[0]?.page_size ?? 0),
659
- pageCount: Number(pageCountRows?.[0]?.page_count ?? 0),
660
- freelistCount: Number(freelistRows?.[0]?.freelist_count ?? 0),
661
- },
662
- kvStore: {
663
- exists: kvRows !== null,
664
- entries: kvRows ?? [],
665
- },
666
- sync: {
667
- outboxExists: outboxRows !== null,
668
- outboxTotal: outboxList.length,
669
- outboxPending: outboxList.filter((r) => r.status === 'pending' || !r.status).length,
670
- outboxFailed: outboxList.filter((r) => r.status === 'failed').length,
671
- schedulerJobs: scheduledJobsRows ?? schedulerRows ?? null,
672
- },
673
- });
674
- }
675
- if (request.method === 'POST' && pathname === '/api/settings/pragma') {
676
- if (readOnly) {
677
- return errorResponse('Dashboard is running in read-only mode.', 403);
678
- }
679
- const body = (await request.json().catch(() => null));
680
- const pragma = String(body?.pragma ?? '');
681
- const val = body?.value;
682
- if (pragma === 'journal_mode') {
683
- const allowed = new Set(['DELETE', 'TRUNCATE', 'PERSIST', 'MEMORY', 'WAL', 'OFF']);
684
- const mode = String(val ?? '').toUpperCase();
685
- if (!allowed.has(mode)) {
686
- return errorResponse(`Unsupported journal_mode: ${mode}`, 400);
687
- }
688
- const rows = await db.execute(`PRAGMA journal_mode = ${mode};`);
689
- return jsonResponse({ ok: true, pragma, value: rows?.[0]?.journal_mode ?? mode });
367
+ databaseSizeBytes: pageSize * pageCount,
368
+ dataTableCount: dataTables.length,
369
+ systemTableCount: systemTables.length,
370
+ totalDataRows: totalRows,
371
+ totalIndexes,
372
+ topTables: [...dataTables]
373
+ .sort((a, b) => b.rowCount - a.rowCount)
374
+ .slice(0, 8)
375
+ .map((t) => ({ name: t.name, rowCount: t.rowCount })),
376
+ });
690
377
  }
691
- if (pragma === 'synchronous') {
692
- const num = Number(val);
693
- if (!Number.isInteger(num) || num < 0 || num > 3) {
694
- return errorResponse('synchronous must be 0 (OFF), 1 (NORMAL), 2 (FULL), or 3 (EXTRA).', 400);
378
+ if (request.method === 'GET' && pathname === '/api/tables') {
379
+ const tables = await listTables(db);
380
+ return jsonResponse({ tables });
381
+ }
382
+ if (request.method === 'GET' && pathname === '/api/schema/sql') {
383
+ const dialectRaw = (url.searchParams.get('dialect') ?? 'sqlite').toLowerCase();
384
+ const dialect = ['sqlite', 'postgres', 'mysql'].includes(dialectRaw)
385
+ ? dialectRaw
386
+ : 'sqlite';
387
+ const includeSystem = url.searchParams.get('includeSystem') === '1';
388
+ const onlyTable = url.searchParams.get('table');
389
+ const allTables = await listTables(db);
390
+ const selected = allTables.filter((t) => {
391
+ if (onlyTable && t.name !== onlyTable)
392
+ return false;
393
+ if (!onlyTable && !includeSystem && t.internal)
394
+ return false;
395
+ return true;
396
+ });
397
+ const quoteId = (id) => dialect === 'mysql'
398
+ ? `\`${id.replace(/`/g, '``')}\``
399
+ : (0, sql_js_1.escapeIdentifier)(id);
400
+ const mapColType = (rawType, isPk) => {
401
+ const upper = (rawType || 'TEXT').toUpperCase();
402
+ if (dialect === 'sqlite')
403
+ return upper;
404
+ if (dialect === 'postgres') {
405
+ if (upper.includes('INT'))
406
+ return 'BIGINT';
407
+ if (upper.includes('REAL') || upper.includes('FLOA') || upper.includes('DOUB'))
408
+ return 'DOUBLE PRECISION';
409
+ if (upper.includes('BLOB'))
410
+ return 'BYTEA';
411
+ if (upper.includes('NUM') || upper.includes('DEC'))
412
+ return 'NUMERIC';
413
+ return 'TEXT';
414
+ }
415
+ // mysql
416
+ if (upper.includes('INT'))
417
+ return 'BIGINT';
418
+ if (upper.includes('REAL') || upper.includes('FLOA') || upper.includes('DOUB'))
419
+ return 'DOUBLE';
420
+ if (upper.includes('BLOB'))
421
+ return 'LONGBLOB';
422
+ if (upper.includes('NUM') || upper.includes('DEC'))
423
+ return 'DECIMAL(18, 4)';
424
+ return isPk ? 'VARCHAR(255)' : 'TEXT';
425
+ };
426
+ const statements = [];
427
+ for (const t of selected) {
428
+ const pkCols = t.columns.filter((c) => c.pk > 0).sort((a, b) => a.pk - b.pk);
429
+ const singlePk = pkCols.length === 1;
430
+ const lines = t.columns.map((c) => {
431
+ const parts = [quoteId(c.name), mapColType(c.type, c.pk > 0)];
432
+ if (singlePk && c.pk > 0)
433
+ parts.push('PRIMARY KEY');
434
+ if (c.notnull > 0 && !(singlePk && c.pk > 0))
435
+ parts.push('NOT NULL');
436
+ if (c.dflt_value != null)
437
+ parts.push(`DEFAULT ${String(c.dflt_value)}`);
438
+ return ` ${parts.join(' ')}`;
439
+ });
440
+ if (pkCols.length > 1) {
441
+ lines.push(` PRIMARY KEY (${pkCols.map((c) => quoteId(c.name)).join(', ')})`);
442
+ }
443
+ statements.push(`CREATE TABLE IF NOT EXISTS ${quoteId(t.name)} (\n${lines.join(',\n')}\n);`);
444
+ for (const idx of t.indexes) {
445
+ if (idx.name.startsWith('sqlite_autoindex_') || idx.columns.length === 0) {
446
+ continue;
447
+ }
448
+ const uniqueSql = idx.unique ? 'UNIQUE ' : '';
449
+ const ifNotExists = dialect === 'mysql' ? '' : 'IF NOT EXISTS ';
450
+ statements.push(`CREATE ${uniqueSql}INDEX ${ifNotExists}${quoteId(idx.name)} ON ${quoteId(t.name)} (${idx.columns.map(quoteId).join(', ')});`);
451
+ }
695
452
  }
696
- await db.execute(`PRAGMA synchronous = ${num};`);
697
- return jsonResponse({ ok: true, pragma, value: num });
698
- }
699
- if (pragma === 'busy_timeout') {
700
- const ms = Number(val);
701
- if (!Number.isInteger(ms) || ms < 0 || ms > 600000) {
702
- return errorResponse('busy_timeout must be an integer between 0 and 600000 ms.', 400);
453
+ const sql = statements.join('\n\n');
454
+ if (url.searchParams.get('download') === '1') {
455
+ return new Response(sql, {
456
+ status: 200,
457
+ headers: {
458
+ 'Content-Type': 'application/sql; charset=utf-8',
459
+ 'Content-Disposition': `attachment; filename="schema-${dialect}.sql"`,
460
+ },
461
+ });
703
462
  }
704
- await db.execute(`PRAGMA busy_timeout = ${ms};`);
705
- return jsonResponse({ ok: true, pragma, value: ms });
463
+ return jsonResponse({ dialect, tableCount: selected.length, sql });
706
464
  }
707
- if (pragma === 'cache_size') {
708
- const size = Number(val);
709
- if (!Number.isInteger(size) || size < -1048576 || size > 1048576) {
710
- return errorResponse('cache_size must be an integer between -1048576 and 1048576.', 400);
465
+ if (request.method === 'POST' && pathname === '/api/tables') {
466
+ if (readOnly) {
467
+ return errorResponse('Dashboard is running in read-only mode.', 403);
711
468
  }
712
- await db.execute(`PRAGMA cache_size = ${size};`);
713
- return jsonResponse({ ok: true, pragma, value: size });
714
- }
715
- if (pragma === 'foreign_keys') {
716
- const enabled = val === true || val === 1 || val === '1' || String(val).toUpperCase() === 'ON';
717
- await db.execute(`PRAGMA foreign_keys = ${enabled ? 'ON' : 'OFF'};`);
718
- return jsonResponse({ ok: true, pragma, value: enabled });
719
- }
720
- return errorResponse(`Unsupported pragma "${pragma}".`, 400);
721
- }
722
- if (request.method === 'POST' && pathname === '/api/settings/maintenance') {
723
- const body = (await request.json().catch(() => null));
724
- const action = String(body?.action ?? '');
725
- if (action === 'integrity_check') {
726
- const rows = await db.execute('PRAGMA integrity_check;');
727
- const result = (rows ?? []).map((r) => Object.values(r)[0]).join(', ') || 'ok';
728
- return jsonResponse({ ok: true, action, message: `Integrity check: ${result}` });
729
- }
730
- if (readOnly) {
731
- return errorResponse('Dashboard is running in read-only mode.', 403);
732
- }
733
- if (action === 'vacuum') {
734
- await db.execute('VACUUM;');
735
- return jsonResponse({ ok: true, action, message: 'VACUUM completed.' });
736
- }
737
- if (action === 'checkpoint') {
738
- const rows = await db.execute('PRAGMA wal_checkpoint(TRUNCATE);');
739
- return jsonResponse({ ok: true, action, message: 'WAL checkpoint completed.', detail: rows?.[0] ?? null });
740
- }
741
- if (action === 'prune_kv_expired') {
742
- const exists = await db.execute(`SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?;`, [store_js_1.DEFAULT_KV_STORE_TABLE]);
743
- if (exists?.length) {
744
- await store_js_1.KVStore.pruneExpired(db, store_js_1.DEFAULT_KV_STORE_TABLE);
469
+ const body = (await request.json().catch(() => null));
470
+ const name = String(body?.name ?? '').trim();
471
+ if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(name)) {
472
+ return errorResponse('Invalid table name. Use letters, numbers, and underscores.', 400);
745
473
  }
746
- return jsonResponse({ ok: true, action, message: 'Expired KV Store entries pruned.' });
747
- }
748
- if (action === 'prune_outbox') {
749
- const exists = await db.execute(`SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'sync_outbox';`);
750
- if (exists?.length) {
751
- await db.execute(`DELETE FROM sync_outbox WHERE status = 'synced';`);
474
+ if ((0, sql_js_1.isInternalTable)(name)) {
475
+ return errorResponse('Cannot create an internal system table.', 400);
752
476
  }
753
- return jsonResponse({ ok: true, action, message: 'Synced outbox entries pruned.' });
754
- }
755
- if (action === 'clear_failed_outbox') {
756
- const exists = await db.execute(`SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'sync_outbox';`);
757
- if (exists?.length) {
758
- await db.execute(`DELETE FROM sync_outbox WHERE status = 'failed';`);
477
+ const cols = Array.isArray(body?.columns) ? body.columns : [];
478
+ if (cols.length === 0) {
479
+ return errorResponse('At least one column is required.', 400);
759
480
  }
760
- return jsonResponse({ ok: true, action, message: 'Failed outbox mutations cleared.' });
761
- }
762
- return errorResponse(`Unsupported maintenance action "${action}".`, 400);
763
- }
764
- if (request.method === 'GET' && pathname === '/api/settings/export') {
765
- const includeInternal = url.searchParams.get('includeInternal') === '1';
766
- const tables = await listTables(db);
767
- const selected = includeInternal ? tables : tables.filter((t) => !t.internal);
768
- const data = {};
769
- for (const t of selected) {
770
- data[t.name] =
771
- (await db.execute(`SELECT * FROM ${(0, sql_js_1.escapeIdentifier)(t.name)} LIMIT 50000;`)) ?? [];
772
- }
773
- return new Response(JSON.stringify({ exportedAt: new Date().toISOString(), tables: data }, null, 2), {
774
- status: 200,
775
- headers: {
776
- 'Content-Type': 'application/json; charset=utf-8',
777
- 'Content-Disposition': 'attachment; filename="local-lite-export.json"',
778
- },
779
- });
780
- }
781
- if (pathname === '/api/kv-store') {
782
- if (readOnly) {
783
- return errorResponse('Dashboard is running in read-only mode.', 403);
481
+ const allowedTypes = new Set(['TEXT', 'INTEGER', 'REAL', 'BLOB', 'NUMERIC']);
482
+ const colDefs = cols.map((c) => {
483
+ const colName = String(c.name ?? '').trim();
484
+ if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(colName)) {
485
+ throw new Error(`Invalid column name: ${colName}`);
486
+ }
487
+ const colType = allowedTypes.has(String(c.type ?? 'TEXT').toUpperCase())
488
+ ? String(c.type ?? 'TEXT').toUpperCase()
489
+ : 'TEXT';
490
+ const parts = [(0, sql_js_1.escapeIdentifier)(colName), colType];
491
+ if (c.pk)
492
+ parts.push('PRIMARY KEY');
493
+ if (c.notnull && !c.pk)
494
+ parts.push('NOT NULL');
495
+ return parts.join(' ');
496
+ });
497
+ await db.execute(`CREATE TABLE ${(0, sql_js_1.escapeIdentifier)(name)} (${colDefs.join(', ')});`);
498
+ return jsonResponse({ ok: true, name }, 201);
784
499
  }
785
- const body = (await request.json().catch(() => null));
786
- if (request.method === 'POST') {
787
- const key = String(body?.key ?? '').trim();
788
- if (!key) {
789
- return errorResponse('Key is required.', 400);
790
- }
791
- await store_js_1.KVStore.ensureSchema(db, store_js_1.DEFAULT_KV_STORE_TABLE);
792
- const type = ['string', 'number', 'boolean', 'json'].includes(String(body?.type))
793
- ? String(body?.type)
794
- : 'string';
795
- let valueStr;
796
- if (type === 'number') {
797
- const n = Number(body?.value);
798
- if (Number.isNaN(n))
799
- return errorResponse('Invalid number value.', 400);
800
- valueStr = String(n);
801
- }
802
- else if (type === 'boolean') {
803
- const b = body?.value === true || body?.value === 'true' || body?.value === '1' || body?.value === 1;
804
- valueStr = b ? '1' : '0';
805
- }
806
- else if (type === 'json') {
807
- try {
808
- const parsed = typeof body?.value === 'string' ? JSON.parse(body.value) : body?.value;
809
- valueStr = JSON.stringify(parsed ?? null);
500
+ const tableTargetMatch = pathname.match(/^\/api\/tables\/([^/]+)$/);
501
+ if (tableTargetMatch && request.method === 'PATCH') {
502
+ if (readOnly) {
503
+ return errorResponse('Dashboard is running in read-only mode.', 403);
504
+ }
505
+ const tableName = decodeURIComponent(tableTargetMatch[1]);
506
+ if ((0, sql_js_1.isInternalTable)(tableName)) {
507
+ return errorResponse('Cannot modify internal system tables.', 403);
508
+ }
509
+ const body = (await request.json().catch(() => null));
510
+ if (body?.newName) {
511
+ const nextName = String(body.newName).trim();
512
+ if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(nextName) || (0, sql_js_1.isInternalTable)(nextName)) {
513
+ return errorResponse('Invalid target table name.', 400);
810
514
  }
811
- catch {
812
- return errorResponse('Invalid JSON value.', 400);
515
+ await db.execute(`ALTER TABLE ${(0, sql_js_1.escapeIdentifier)(tableName)} RENAME TO ${(0, sql_js_1.escapeIdentifier)(nextName)};`);
516
+ return jsonResponse({ ok: true, name: nextName });
517
+ }
518
+ if (body?.addColumn) {
519
+ const colName = String(body.addColumn.name ?? '').trim();
520
+ if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(colName)) {
521
+ return errorResponse('Invalid column name.', 400);
522
+ }
523
+ const allowedTypes = new Set(['TEXT', 'INTEGER', 'REAL', 'BLOB', 'NUMERIC']);
524
+ const colType = allowedTypes.has(String(body.addColumn.type ?? 'TEXT').toUpperCase())
525
+ ? String(body.addColumn.type ?? 'TEXT').toUpperCase()
526
+ : 'TEXT';
527
+ const parts = [(0, sql_js_1.escapeIdentifier)(colName), colType];
528
+ const dflt = body.addColumn.defaultValue;
529
+ if (dflt !== undefined && dflt !== '') {
530
+ const escapedDflt = `'${String(dflt).replace(/'/g, "''")}'`;
531
+ if (body.addColumn.notnull)
532
+ parts.push('NOT NULL');
533
+ parts.push(`DEFAULT ${escapedDflt}`);
534
+ }
535
+ else if (body.addColumn.notnull) {
536
+ parts.push("NOT NULL DEFAULT ''");
813
537
  }
538
+ await db.execute(`ALTER TABLE ${(0, sql_js_1.escapeIdentifier)(tableName)} ADD COLUMN ${parts.join(' ')};`);
539
+ return jsonResponse({ ok: true });
814
540
  }
815
- else {
816
- valueStr = String(body?.value ?? '');
541
+ if (body?.dropColumn) {
542
+ const colName = String(body.dropColumn).trim();
543
+ if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(colName)) {
544
+ return errorResponse('Invalid column name.', 400);
545
+ }
546
+ await db.execute(`ALTER TABLE ${(0, sql_js_1.escapeIdentifier)(tableName)} DROP COLUMN ${(0, sql_js_1.escapeIdentifier)(colName)};`);
547
+ return jsonResponse({ ok: true });
817
548
  }
818
- const now = Date.now();
819
- const expiresAt = body?.ttlMs != null && Number(body.ttlMs) > 0 ? now + Number(body.ttlMs) : null;
820
- await store_js_1.KVStore.set(db, store_js_1.DEFAULT_KV_STORE_TABLE, key, valueStr, type, now, expiresAt);
549
+ return errorResponse('Provide newName, addColumn, or dropColumn.', 400);
550
+ }
551
+ if (tableTargetMatch && request.method === 'DELETE') {
552
+ if (readOnly) {
553
+ return errorResponse('Dashboard is running in read-only mode.', 403);
554
+ }
555
+ const tableName = decodeURIComponent(tableTargetMatch[1]);
556
+ if ((0, sql_js_1.isInternalTable)(tableName)) {
557
+ return errorResponse('Cannot drop internal system tables.', 403);
558
+ }
559
+ await db.execute(`DROP TABLE IF EXISTS ${(0, sql_js_1.escapeIdentifier)(tableName)};`);
821
560
  return jsonResponse({ ok: true });
822
561
  }
823
- if (request.method === 'DELETE') {
824
- const key = String(body?.key ?? '').trim();
825
- if (!key) {
826
- return errorResponse('Key is required.', 400);
562
+ const clearTableMatch = pathname.match(/^\/api\/tables\/([^/]+)\/clear$/);
563
+ if (clearTableMatch && request.method === 'POST') {
564
+ if (readOnly) {
565
+ return errorResponse('Dashboard is running in read-only mode.', 403);
566
+ }
567
+ const tableName = decodeURIComponent(clearTableMatch[1]);
568
+ if ((0, sql_js_1.isInternalTable)(tableName)) {
569
+ return errorResponse('Cannot clear internal system tables from here.', 403);
827
570
  }
828
- await store_js_1.KVStore.ensureSchema(db, store_js_1.DEFAULT_KV_STORE_TABLE);
829
- await store_js_1.KVStore.delete(db, store_js_1.DEFAULT_KV_STORE_TABLE, key);
571
+ await db.execute(`DELETE FROM ${(0, sql_js_1.escapeIdentifier)(tableName)};`);
830
572
  return jsonResponse({ ok: true });
831
573
  }
832
- }
833
- if (request.method === 'GET' && pathname === '/api/files') {
834
- const blobs = await readRowsIfTableExists(db, '_local_blobs', 500);
835
- return jsonResponse({ exists: blobs !== null, files: blobs ?? [] });
836
- }
837
- const fileDeleteMatch = pathname.match(/^\/api\/files\/([^/]+)$/);
838
- if (fileDeleteMatch && request.method === 'DELETE') {
839
- if (readOnly) {
840
- return errorResponse('Dashboard is running in read-only mode.', 403);
574
+ const importTableMatch = pathname.match(/^\/api\/tables\/([^/]+)\/import$/);
575
+ if (importTableMatch && request.method === 'POST') {
576
+ if (readOnly) {
577
+ return errorResponse('Dashboard is running in read-only mode.', 403);
578
+ }
579
+ const tableName = decodeURIComponent(importTableMatch[1]);
580
+ const tables = await listTables(db);
581
+ const tableMeta = tables.find((t) => t.name === tableName);
582
+ if (!tableMeta) {
583
+ return errorResponse(`Table "${tableName}" not found.`, 404);
584
+ }
585
+ const body = (await request.json().catch(() => null));
586
+ const rows = Array.isArray(body?.rows) ? body.rows : [];
587
+ if (rows.length === 0) {
588
+ return errorResponse('rows array is required.', 400);
589
+ }
590
+ const validCols = new Set(tableMeta.columns.map((c) => c.name));
591
+ let imported = 0;
592
+ for (const row of rows) {
593
+ if (!row || typeof row !== 'object')
594
+ continue;
595
+ const entries = Object.entries(row).filter(([k]) => validCols.has(k));
596
+ if (entries.length === 0)
597
+ continue;
598
+ const cols = entries.map(([k]) => (0, sql_js_1.escapeIdentifier)(k)).join(', ');
599
+ const placeholders = entries.map(() => '?').join(', ');
600
+ await db.execute(`INSERT OR REPLACE INTO ${(0, sql_js_1.escapeIdentifier)(tableName)} (${cols}) VALUES (${placeholders});`, entries.map(([, v]) => v));
601
+ imported += 1;
602
+ }
603
+ return jsonResponse({ ok: true, imported });
841
604
  }
842
- const fileId = decodeURIComponent(fileDeleteMatch[1]);
843
- const exists = await db.execute(`SELECT name FROM sqlite_master WHERE type = 'table' AND name = '_local_blobs';`);
844
- if (exists?.length) {
845
- await db.execute(`DELETE FROM _local_blobs WHERE id = ?;`, [fileId]);
605
+ const indexCreateMatch = pathname.match(/^\/api\/tables\/([^/]+)\/indexes$/);
606
+ if (indexCreateMatch && request.method === 'POST') {
607
+ if (readOnly) {
608
+ return errorResponse('Dashboard is running in read-only mode.', 403);
609
+ }
610
+ const tableName = decodeURIComponent(indexCreateMatch[1]);
611
+ const body = (await request.json().catch(() => null));
612
+ const idxName = String(body?.name ?? '').trim();
613
+ const cols = Array.isArray(body?.columns) ? body.columns.filter(Boolean) : [];
614
+ if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(idxName) || cols.length === 0) {
615
+ return errorResponse('Valid index name and at least one column are required.', 400);
616
+ }
617
+ const uniqueSql = body?.unique ? 'UNIQUE ' : '';
618
+ const colSql = cols.map((c) => (0, sql_js_1.escapeIdentifier)(c)).join(', ');
619
+ await db.execute(`CREATE ${uniqueSql}INDEX IF NOT EXISTS ${(0, sql_js_1.escapeIdentifier)(idxName)} ON ${(0, sql_js_1.escapeIdentifier)(tableName)} (${colSql});`);
620
+ return jsonResponse({ ok: true }, 201);
846
621
  }
847
- return jsonResponse({ ok: true });
848
- }
849
- if (pathname === '/api/auth-admin') {
850
- if (request.method === 'GET') {
851
- const [users, sessions, apiKeys] = await Promise.all([
852
- readRowsIfTableExists(db, '_local_users', 500),
853
- readRowsIfTableExists(db, '_local_sessions', 500),
854
- readRowsIfTableExists(db, '_local_api_keys', 500),
855
- ]);
856
- return jsonResponse({ users, sessions, apiKeys });
622
+ const indexDropMatch = pathname.match(/^\/api\/tables\/([^/]+)\/indexes\/([^/]+)$/);
623
+ if (indexDropMatch && request.method === 'DELETE') {
624
+ if (readOnly) {
625
+ return errorResponse('Dashboard is running in read-only mode.', 403);
626
+ }
627
+ const idxName = decodeURIComponent(indexDropMatch[2]);
628
+ await db.execute(`DROP INDEX IF EXISTS ${(0, sql_js_1.escapeIdentifier)(idxName)};`);
629
+ return jsonResponse({ ok: true });
630
+ }
631
+ const exportMatch = pathname.match(/^\/api\/tables\/([^/]+)\/export$/);
632
+ if (exportMatch && request.method === 'GET') {
633
+ const tableName = decodeURIComponent(exportMatch[1]);
634
+ const tables = await listTables(db);
635
+ const tableMeta = tables.find((t) => t.name === tableName);
636
+ if (!tableMeta) {
637
+ return errorResponse(`Table "${tableName}" not found.`, 404);
638
+ }
639
+ const format = url.searchParams.get('format') === 'csv' ? 'csv' : 'json';
640
+ const rows = (await db.execute(`SELECT * FROM ${(0, sql_js_1.escapeIdentifier)(tableName)} LIMIT 10000;`)) ?? [];
641
+ if (format === 'csv') {
642
+ const cols = tableMeta.columns.map((c) => c.name);
643
+ return new Response(toCsv(cols, rows), {
644
+ status: 200,
645
+ headers: {
646
+ 'Content-Type': 'text/csv; charset=utf-8',
647
+ 'Content-Disposition': `attachment; filename="${tableName}.csv"`,
648
+ },
649
+ });
650
+ }
651
+ return new Response(JSON.stringify(rows, null, 2), {
652
+ status: 200,
653
+ headers: {
654
+ 'Content-Type': 'application/json; charset=utf-8',
655
+ 'Content-Disposition': `attachment; filename="${tableName}.json"`,
656
+ },
657
+ });
857
658
  }
858
- if (request.method === 'POST') {
659
+ const tableRowsMatch = pathname.match(/^\/api\/tables\/([^/]+)\/rows$/);
660
+ if (tableRowsMatch) {
661
+ const tableName = decodeURIComponent(tableRowsMatch[1]);
662
+ const tables = await listTables(db);
663
+ const tableMeta = tables.find((t) => t.name === tableName);
664
+ if (!tableMeta) {
665
+ return errorResponse(`Table "${tableName}" not found.`, 404);
666
+ }
667
+ const quotedTable = (0, sql_js_1.escapeIdentifier)(tableName);
668
+ if (request.method === 'GET') {
669
+ const limit = Math.min(500, Math.max(1, Number(url.searchParams.get('limit') ?? 50)));
670
+ const offset = Math.max(0, Number(url.searchParams.get('offset') ?? 0));
671
+ const search = (url.searchParams.get('search') ?? '').trim();
672
+ const filterCol = (url.searchParams.get('filterCol') ?? '').trim();
673
+ const filterVal = url.searchParams.get('filterVal') ?? '';
674
+ const orderBy = url.searchParams.get('orderBy') ?? '';
675
+ const orderDir = url.searchParams.get('orderDir')?.toUpperCase() === 'DESC'
676
+ ? 'DESC'
677
+ : 'ASC';
678
+ const validColNames = new Set(tableMeta.columns.map((c) => c.name));
679
+ const params = [];
680
+ const conditions = [];
681
+ if (search && tableMeta.columns.length > 0) {
682
+ const likeTerm = `%${search.replace(/[%_\\]/g, '\\$&')}%`;
683
+ const predicates = tableMeta.columns.map((col) => {
684
+ params.push(likeTerm);
685
+ return `CAST(${(0, sql_js_1.escapeIdentifier)(col.name)} AS TEXT) LIKE ? ESCAPE '\\'`;
686
+ });
687
+ conditions.push(`(${predicates.join(' OR ')})`);
688
+ }
689
+ if (filterCol && validColNames.has(filterCol) && filterVal !== '') {
690
+ params.push(filterVal);
691
+ conditions.push(`CAST(${(0, sql_js_1.escapeIdentifier)(filterCol)} AS TEXT) = ?`);
692
+ }
693
+ const whereClause = conditions.length > 0 ? ` WHERE ${conditions.join(' AND ')}` : '';
694
+ let orderClause = '';
695
+ if (orderBy && validColNames.has(orderBy)) {
696
+ orderClause = ` ORDER BY ${(0, sql_js_1.escapeIdentifier)(orderBy)} ${orderDir}`;
697
+ }
698
+ const countRows = await db.execute(`SELECT COUNT(*) AS cnt FROM ${quotedTable}${whereClause};`, params);
699
+ const total = Number(countRows?.[0]?.cnt ?? 0);
700
+ const rows = await db.execute(`SELECT * FROM ${quotedTable}${whereClause}${orderClause} LIMIT ? OFFSET ?;`, [...params, limit, offset]);
701
+ return jsonResponse({
702
+ table: tableMeta,
703
+ rows: rows ?? [],
704
+ total,
705
+ limit,
706
+ offset,
707
+ });
708
+ }
859
709
  if (readOnly) {
860
710
  return errorResponse('Dashboard is running in read-only mode.', 403);
861
711
  }
862
712
  const body = (await request.json().catch(() => null));
863
- const action = String(body?.action ?? '');
864
- const id = String(body?.id ?? '');
865
- if (!id)
866
- return errorResponse('id is required.', 400);
867
- if (action === 'revoke_session') {
868
- await db.execute(`DELETE FROM _local_sessions WHERE id = ?;`, [id]);
869
- return jsonResponse({ ok: true });
713
+ if (!body || typeof body !== 'object') {
714
+ return errorResponse('JSON object body is required.', 400);
715
+ }
716
+ const validColNames = new Set(tableMeta.columns.map((c) => c.name));
717
+ const pkColumns = tableMeta.columns
718
+ .filter((c) => c.pk > 0)
719
+ .sort((a, b) => a.pk - b.pk);
720
+ if (request.method === 'POST') {
721
+ const entries = Object.entries(body).filter(([key]) => validColNames.has(key));
722
+ if (entries.length === 0) {
723
+ return errorResponse('At least one valid column is required.', 400);
724
+ }
725
+ const cols = entries.map(([k]) => (0, sql_js_1.escapeIdentifier)(k)).join(', ');
726
+ const placeholders = entries.map(() => '?').join(', ');
727
+ const values = entries.map(([, v]) => v);
728
+ await db.execute(`INSERT INTO ${quotedTable} (${cols}) VALUES (${placeholders});`, values);
729
+ return jsonResponse({ ok: true }, 201);
870
730
  }
871
- if (action === 'unlock_user') {
872
- await db.execute(`UPDATE _local_users SET failed_attempts = 0, locked_until = NULL WHERE id = ?;`, [id]);
731
+ if (request.method === 'PATCH') {
732
+ if (pkColumns.length === 0) {
733
+ return errorResponse(`Table "${tableName}" has no primary key for row updates.`, 400);
734
+ }
735
+ const updates = body.updates;
736
+ const key = body.key;
737
+ if (!updates || !key) {
738
+ return errorResponse('Both "key" and "updates" objects are required.', 400);
739
+ }
740
+ const setEntries = Object.entries(updates).filter(([col]) => validColNames.has(col));
741
+ if (setEntries.length === 0) {
742
+ return errorResponse('No valid update columns provided.', 400);
743
+ }
744
+ const setClause = setEntries
745
+ .map(([col]) => `${(0, sql_js_1.escapeIdentifier)(col)} = ?`)
746
+ .join(', ');
747
+ const whereClause = pkColumns
748
+ .map((pk) => `${(0, sql_js_1.escapeIdentifier)(pk.name)} = ?`)
749
+ .join(' AND ');
750
+ const params = [
751
+ ...setEntries.map(([, val]) => val),
752
+ ...pkColumns.map((pk) => key[pk.name]),
753
+ ];
754
+ await db.execute(`UPDATE ${quotedTable} SET ${setClause} WHERE ${whereClause};`, params);
873
755
  return jsonResponse({ ok: true });
874
756
  }
875
- if (action === 'revoke_api_key') {
876
- await db.execute(`UPDATE _local_api_keys SET revoked_at = ? WHERE id = ?;`, [Date.now(), id]).catch(async () => {
877
- await db.execute(`DELETE FROM _local_api_keys WHERE id = ?;`, [id]);
878
- });
757
+ if (request.method === 'DELETE') {
758
+ if (pkColumns.length === 0) {
759
+ return errorResponse(`Table "${tableName}" has no primary key for row deletion.`, 400);
760
+ }
761
+ const key = (body.key ?? body);
762
+ const whereClause = pkColumns
763
+ .map((pk) => `${(0, sql_js_1.escapeIdentifier)(pk.name)} = ?`)
764
+ .join(' AND ');
765
+ const params = pkColumns.map((pk) => key[pk.name]);
766
+ await db.execute(`DELETE FROM ${quotedTable} WHERE ${whereClause};`, params);
879
767
  return jsonResponse({ ok: true });
880
768
  }
881
- return errorResponse(`Unsupported auth action "${action}".`, 400);
882
769
  }
883
- }
884
- if (pathname === '/api/jobs') {
885
- if (request.method === 'GET') {
886
- const [actions, scheduledJobs, jobRuns, outbox] = await Promise.all([
887
- readRowsIfTableExists(db, '_local_actions', 500),
888
- readRowsIfTableExists(db, '_local_scheduled_jobs', 200),
889
- readRowsIfTableExists(db, '_local_job_runs', 200),
890
- readRowsIfTableExists(db, 'sync_outbox', 500),
770
+ if (request.method === 'POST' && pathname === '/api/query') {
771
+ const body = (await request.json().catch(() => null));
772
+ const sql = String(body?.sql ?? '').trim();
773
+ if (!sql) {
774
+ return errorResponse('SQL query is required.', 400);
775
+ }
776
+ if (readOnly && !(0, sql_js_1.isReadQuery)(sql)) {
777
+ return errorResponse('Only read-only SELECT / WITH / EXPLAIN / PRAGMA queries are allowed in read-only mode.', 403);
778
+ }
779
+ const started = performance.now();
780
+ const rows = (await db.execute(sql, Array.isArray(body?.params) ? body.params : [])) ?? [];
781
+ const durationMs = Math.round((performance.now() - started) * 100) / 100;
782
+ const columns = rows.length > 0 && typeof rows[0] === 'object' && rows[0] !== null
783
+ ? Object.keys(rows[0])
784
+ : [];
785
+ return reply(jsonResponse({
786
+ columns,
787
+ rows,
788
+ rowsAffected: 0,
789
+ durationMs,
790
+ }), sql.slice(0, 160));
791
+ }
792
+ if (request.method === 'GET' && pathname === '/api/system') {
793
+ const [outbox, kvStore, scheduler, actions, users, sessions, migrations] = await Promise.all([
794
+ readRowsIfTableExists(db, 'sync_outbox', 200),
795
+ readRowsIfTableExists(db, store_js_1.DEFAULT_KV_STORE_TABLE, 200),
796
+ readRowsIfTableExists(db, '_local_scheduler', 100),
797
+ readRowsIfTableExists(db, '_local_actions', 100),
798
+ readRowsIfTableExists(db, '_local_users', 100),
799
+ readRowsIfTableExists(db, '_local_sessions', 100),
800
+ readRowsIfTableExists(db, 'schema_migrations', 100),
891
801
  ]);
892
- return jsonResponse({ actions, scheduledJobs, jobRuns, outbox });
802
+ return jsonResponse({
803
+ outbox,
804
+ kvStore,
805
+ scheduler,
806
+ actions,
807
+ users,
808
+ sessions,
809
+ migrations,
810
+ });
893
811
  }
894
- if (request.method === 'POST') {
812
+ if (request.method === 'GET' && pathname === '/api/settings') {
813
+ const [journalRows, syncRows, busyRows, cacheRows, fkRows, pageSizeRows, pageCountRows, freelistRows, kvRows, outboxRows, scheduledJobsRows, schedulerRows,] = await Promise.all([
814
+ db.execute('PRAGMA journal_mode;').catch(() => []),
815
+ db.execute('PRAGMA synchronous;').catch(() => []),
816
+ db.execute('PRAGMA busy_timeout;').catch(() => []),
817
+ db.execute('PRAGMA cache_size;').catch(() => []),
818
+ db.execute('PRAGMA foreign_keys;').catch(() => []),
819
+ db.execute('PRAGMA page_size;').catch(() => []),
820
+ db.execute('PRAGMA page_count;').catch(() => []),
821
+ db.execute('PRAGMA freelist_count;').catch(() => []),
822
+ readRowsIfTableExists(db, store_js_1.DEFAULT_KV_STORE_TABLE, 500),
823
+ readRowsIfTableExists(db, 'sync_outbox', 1000),
824
+ readRowsIfTableExists(db, '_local_scheduled_jobs', 100),
825
+ readRowsIfTableExists(db, '_local_scheduler', 100),
826
+ ]);
827
+ const outboxList = outboxRows ?? [];
828
+ return jsonResponse({
829
+ dashboard: {
830
+ title,
831
+ readOnly,
832
+ authEnabled: Boolean(options.authToken),
833
+ basePath,
834
+ },
835
+ pragmas: {
836
+ journalMode: String(journalRows?.[0]?.journal_mode ?? 'unknown'),
837
+ synchronous: Number(syncRows?.[0]?.synchronous ?? 0),
838
+ busyTimeout: Number(busyRows?.[0]?.timeout ?? busyRows?.[0]?.busy_timeout ?? 0),
839
+ cacheSize: Number(cacheRows?.[0]?.cache_size ?? 0),
840
+ foreignKeys: Boolean(Number(fkRows?.[0]?.foreign_keys ?? 0)),
841
+ pageSize: Number(pageSizeRows?.[0]?.page_size ?? 0),
842
+ pageCount: Number(pageCountRows?.[0]?.page_count ?? 0),
843
+ freelistCount: Number(freelistRows?.[0]?.freelist_count ?? 0),
844
+ },
845
+ kvStore: {
846
+ exists: kvRows !== null,
847
+ entries: kvRows ?? [],
848
+ },
849
+ sync: {
850
+ outboxExists: outboxRows !== null,
851
+ outboxTotal: outboxList.length,
852
+ outboxPending: outboxList.filter((r) => r.status === 'pending' || !r.status).length,
853
+ outboxFailed: outboxList.filter((r) => r.status === 'failed').length,
854
+ schedulerJobs: scheduledJobsRows ?? schedulerRows ?? null,
855
+ },
856
+ });
857
+ }
858
+ if (request.method === 'POST' && pathname === '/api/settings/pragma') {
895
859
  if (readOnly) {
896
860
  return errorResponse('Dashboard is running in read-only mode.', 403);
897
861
  }
862
+ const body = (await request.json().catch(() => null));
863
+ const pragma = String(body?.pragma ?? '');
864
+ const val = body?.value;
865
+ if (pragma === 'journal_mode') {
866
+ const allowed = new Set(['DELETE', 'TRUNCATE', 'PERSIST', 'MEMORY', 'WAL', 'OFF']);
867
+ const mode = String(val ?? '').toUpperCase();
868
+ if (!allowed.has(mode)) {
869
+ return errorResponse(`Unsupported journal_mode: ${mode}`, 400);
870
+ }
871
+ const rows = await db.execute(`PRAGMA journal_mode = ${mode};`);
872
+ return jsonResponse({ ok: true, pragma, value: rows?.[0]?.journal_mode ?? mode });
873
+ }
874
+ if (pragma === 'synchronous') {
875
+ const num = Number(val);
876
+ if (!Number.isInteger(num) || num < 0 || num > 3) {
877
+ return errorResponse('synchronous must be 0 (OFF), 1 (NORMAL), 2 (FULL), or 3 (EXTRA).', 400);
878
+ }
879
+ await db.execute(`PRAGMA synchronous = ${num};`);
880
+ return jsonResponse({ ok: true, pragma, value: num });
881
+ }
882
+ if (pragma === 'busy_timeout') {
883
+ const ms = Number(val);
884
+ if (!Number.isInteger(ms) || ms < 0 || ms > 600000) {
885
+ return errorResponse('busy_timeout must be an integer between 0 and 600000 ms.', 400);
886
+ }
887
+ await db.execute(`PRAGMA busy_timeout = ${ms};`);
888
+ return jsonResponse({ ok: true, pragma, value: ms });
889
+ }
890
+ if (pragma === 'cache_size') {
891
+ const size = Number(val);
892
+ if (!Number.isInteger(size) || size < -1048576 || size > 1048576) {
893
+ return errorResponse('cache_size must be an integer between -1048576 and 1048576.', 400);
894
+ }
895
+ await db.execute(`PRAGMA cache_size = ${size};`);
896
+ return jsonResponse({ ok: true, pragma, value: size });
897
+ }
898
+ if (pragma === 'foreign_keys') {
899
+ const enabled = val === true || val === 1 || val === '1' || String(val).toUpperCase() === 'ON';
900
+ await db.execute(`PRAGMA foreign_keys = ${enabled ? 'ON' : 'OFF'};`);
901
+ return jsonResponse({ ok: true, pragma, value: enabled });
902
+ }
903
+ return errorResponse(`Unsupported pragma "${pragma}".`, 400);
904
+ }
905
+ if (request.method === 'POST' && pathname === '/api/settings/maintenance') {
898
906
  const body = (await request.json().catch(() => null));
899
907
  const action = String(body?.action ?? '');
900
- const id = String(body?.id ?? '');
901
- if (action === 'retry_action' && id) {
902
- await db.execute(`UPDATE _local_actions SET status = 'pending', attempts = 0, last_error = NULL WHERE id = ?;`, [id]);
903
- return jsonResponse({ ok: true });
908
+ if (action === 'integrity_check') {
909
+ const rows = await db.execute('PRAGMA integrity_check;');
910
+ const result = (rows ?? []).map((r) => Object.values(r)[0]).join(', ') || 'ok';
911
+ return jsonResponse({ ok: true, action, message: `Integrity check: ${result}` });
904
912
  }
905
- if (action === 'delete_action' && id) {
906
- await db.execute(`DELETE FROM _local_actions WHERE id = ?;`, [id]);
907
- return jsonResponse({ ok: true });
913
+ if (readOnly) {
914
+ return errorResponse('Dashboard is running in read-only mode.', 403);
915
+ }
916
+ if (action === 'vacuum') {
917
+ await db.execute('VACUUM;');
918
+ return jsonResponse({ ok: true, action, message: 'VACUUM completed.' });
908
919
  }
909
- if (action === 'clear_completed_actions') {
910
- const exists = await db.execute(`SELECT name FROM sqlite_master WHERE type = 'table' AND name = '_local_actions';`);
920
+ if (action === 'checkpoint') {
921
+ const rows = await db.execute('PRAGMA wal_checkpoint(TRUNCATE);');
922
+ return jsonResponse({ ok: true, action, message: 'WAL checkpoint completed.', detail: rows?.[0] ?? null });
923
+ }
924
+ if (action === 'prune_kv_expired') {
925
+ const exists = await db.execute(`SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?;`, [store_js_1.DEFAULT_KV_STORE_TABLE]);
911
926
  if (exists?.length) {
912
- await db.execute(`DELETE FROM _local_actions WHERE status = 'completed';`);
927
+ await store_js_1.KVStore.pruneExpired(db, store_js_1.DEFAULT_KV_STORE_TABLE);
913
928
  }
914
- return jsonResponse({ ok: true });
929
+ return jsonResponse({ ok: true, action, message: 'Expired KV Store entries pruned.' });
915
930
  }
916
- if (action === 'retry_outbox' && id) {
917
- await db.execute(`UPDATE sync_outbox SET status = 'pending', retry_count = 0, last_error = NULL WHERE id = ?;`, [id]);
918
- return jsonResponse({ ok: true });
931
+ if (action === 'prune_outbox') {
932
+ const exists = await db.execute(`SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'sync_outbox';`);
933
+ if (exists?.length) {
934
+ await db.execute(`DELETE FROM sync_outbox WHERE status = 'synced';`);
935
+ }
936
+ return jsonResponse({ ok: true, action, message: 'Synced outbox entries pruned.' });
919
937
  }
920
- if (action === 'delete_outbox' && id) {
921
- await db.execute(`DELETE FROM sync_outbox WHERE id = ?;`, [id]);
922
- return jsonResponse({ ok: true });
938
+ if (action === 'clear_failed_outbox') {
939
+ const exists = await db.execute(`SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'sync_outbox';`);
940
+ if (exists?.length) {
941
+ await db.execute(`DELETE FROM sync_outbox WHERE status = 'failed';`);
942
+ }
943
+ return jsonResponse({ ok: true, action, message: 'Failed outbox mutations cleared.' });
923
944
  }
924
- if (action === 'toggle_job' && id) {
925
- await db.execute(`UPDATE _local_scheduled_jobs SET enabled = ? WHERE id = ?;`, [body?.enabled ? 1 : 0, id]);
926
- return jsonResponse({ ok: true });
945
+ return errorResponse(`Unsupported maintenance action "${action}".`, 400);
946
+ }
947
+ if (request.method === 'GET' && pathname === '/api/settings/export') {
948
+ const includeInternal = url.searchParams.get('includeInternal') === '1';
949
+ const tables = await listTables(db);
950
+ const selected = includeInternal ? tables : tables.filter((t) => !t.internal);
951
+ const data = {};
952
+ for (const t of selected) {
953
+ data[t.name] =
954
+ (await db.execute(`SELECT * FROM ${(0, sql_js_1.escapeIdentifier)(t.name)} LIMIT 50000;`)) ?? [];
927
955
  }
928
- if (action === 'delete_job' && id) {
929
- await db.execute(`DELETE FROM _local_scheduled_jobs WHERE id = ?;`, [id]);
956
+ return new Response(JSON.stringify({ exportedAt: new Date().toISOString(), tables: data }, null, 2), {
957
+ status: 200,
958
+ headers: {
959
+ 'Content-Type': 'application/json; charset=utf-8',
960
+ 'Content-Disposition': 'attachment; filename="local-lite-export.json"',
961
+ },
962
+ });
963
+ }
964
+ if (pathname === '/api/kv-store') {
965
+ if (readOnly) {
966
+ return errorResponse('Dashboard is running in read-only mode.', 403);
967
+ }
968
+ const body = (await request.json().catch(() => null));
969
+ if (request.method === 'POST') {
970
+ const key = String(body?.key ?? '').trim();
971
+ if (!key) {
972
+ return errorResponse('Key is required.', 400);
973
+ }
974
+ await store_js_1.KVStore.ensureSchema(db, store_js_1.DEFAULT_KV_STORE_TABLE);
975
+ const type = ['string', 'number', 'boolean', 'json'].includes(String(body?.type))
976
+ ? String(body?.type)
977
+ : 'string';
978
+ let valueStr;
979
+ if (type === 'number') {
980
+ const n = Number(body?.value);
981
+ if (Number.isNaN(n))
982
+ return errorResponse('Invalid number value.', 400);
983
+ valueStr = String(n);
984
+ }
985
+ else if (type === 'boolean') {
986
+ const b = body?.value === true || body?.value === 'true' || body?.value === '1' || body?.value === 1;
987
+ valueStr = b ? '1' : '0';
988
+ }
989
+ else if (type === 'json') {
990
+ try {
991
+ const parsed = typeof body?.value === 'string' ? JSON.parse(body.value) : body?.value;
992
+ valueStr = JSON.stringify(parsed ?? null);
993
+ }
994
+ catch {
995
+ return errorResponse('Invalid JSON value.', 400);
996
+ }
997
+ }
998
+ else {
999
+ valueStr = String(body?.value ?? '');
1000
+ }
1001
+ const now = Date.now();
1002
+ const expiresAt = body?.ttlMs != null && Number(body.ttlMs) > 0 ? now + Number(body.ttlMs) : null;
1003
+ await store_js_1.KVStore.set(db, store_js_1.DEFAULT_KV_STORE_TABLE, key, valueStr, type, now, expiresAt);
930
1004
  return jsonResponse({ ok: true });
931
1005
  }
932
- return errorResponse(`Unsupported job action "${action}".`, 400);
933
- }
934
- }
935
- // ── Live Logs & Query Telemetry ────────────────────────────────────
936
- if (pathname === '/api/logs') {
937
- if (request.method === 'GET') {
938
- const level = url.searchParams.get('level')?.trim() || '';
939
- const search = url.searchParams.get('q')?.trim().toLowerCase() || '';
940
- const filtered = logs.filter((entry) => {
941
- if (level === 'error' && entry.status < 400)
942
- return false;
943
- if (level === 'ok' && entry.status >= 400)
944
- return false;
945
- if (search) {
946
- const hay = `${entry.method} ${entry.path} ${entry.detail ?? ''}`.toLowerCase();
947
- if (!hay.includes(search))
948
- return false;
1006
+ if (request.method === 'DELETE') {
1007
+ const key = String(body?.key ?? '').trim();
1008
+ if (!key) {
1009
+ return errorResponse('Key is required.', 400);
949
1010
  }
950
- return true;
951
- });
952
- return jsonResponse({ logs: filtered });
1011
+ await store_js_1.KVStore.ensureSchema(db, store_js_1.DEFAULT_KV_STORE_TABLE);
1012
+ await store_js_1.KVStore.delete(db, store_js_1.DEFAULT_KV_STORE_TABLE, key);
1013
+ return jsonResponse({ ok: true });
1014
+ }
953
1015
  }
954
- if (request.method === 'DELETE') {
955
- logs.length = 0;
956
- return jsonResponse({ ok: true });
1016
+ if (request.method === 'GET' && pathname === '/api/files') {
1017
+ const blobs = await readRowsIfTableExists(db, '_local_blobs', 500);
1018
+ return jsonResponse({ exists: blobs !== null, files: blobs ?? [] });
957
1019
  }
958
- }
959
- // ── Sample Row Seeder ──────────────────────────────────────────────
960
- const seedMatch = pathname.match(/^\/api\/tables\/([^/]+)\/seed$/);
961
- if (seedMatch && request.method === 'POST') {
962
- if (readOnly)
963
- return reply(errorResponse('Dashboard is in read-only mode.', 403));
964
- const tableName = decodeURIComponent(seedMatch[1]);
965
- const quoted = (0, sql_js_1.escapeIdentifier)(tableName);
966
- const colRows = (await db.execute(`PRAGMA table_info(${quoted});`)) ?? [];
967
- if (colRows.length === 0) {
968
- return reply(errorResponse(`Table "${tableName}" not found.`, 404));
969
- }
970
- const body = (await request.json().catch(() => null));
971
- const count = Math.min(100, Math.max(1, Number(body?.count ?? 10) || 10));
972
- const cols = colRows.map((r) => ({
973
- name: String(r.name),
974
- type: String(r.type ?? 'TEXT').toUpperCase(),
975
- notnull: Boolean(r.notnull),
976
- pk: Number(r.pk) > 0,
977
- }));
978
- const fkRows = (await db.execute(`PRAGMA foreign_key_list(${quoted});`)) ?? [];
979
- const fkValues = new Map();
980
- for (const fk of fkRows) {
981
- const fromCol = String(fk.from ?? '');
982
- const refTable = String(fk.table ?? '');
983
- const refCol = String(fk.to ?? '');
984
- if (!fromCol || !refTable || !refCol)
985
- continue;
986
- try {
987
- const refRows = (await db.execute(`SELECT ${(0, sql_js_1.escapeIdentifier)(refCol)} AS val FROM ${(0, sql_js_1.escapeIdentifier)(refTable)} LIMIT 20;`)) ?? [];
988
- fkValues.set(fromCol.toLowerCase(), refRows.map((r) => r.val));
1020
+ const fileDeleteMatch = pathname.match(/^\/api\/files\/([^/]+)$/);
1021
+ if (fileDeleteMatch && request.method === 'DELETE') {
1022
+ if (readOnly) {
1023
+ return errorResponse('Dashboard is running in read-only mode.', 403);
989
1024
  }
990
- catch {
991
- // ignore
1025
+ const fileId = decodeURIComponent(fileDeleteMatch[1]);
1026
+ const exists = await db.execute(`SELECT name FROM sqlite_master WHERE type = 'table' AND name = '_local_blobs';`);
1027
+ if (exists?.length) {
1028
+ await db.execute(`DELETE FROM _local_blobs WHERE id = ?;`, [fileId]);
992
1029
  }
1030
+ return jsonResponse({ ok: true });
993
1031
  }
994
- const now = Date.now();
995
- let inserted = 0;
996
- for (let i = 0; i < count; i++) {
997
- const insertCols = [];
998
- const placeholders = [];
999
- const params = [];
1000
- for (const col of cols) {
1001
- const lower = col.name.toLowerCase();
1002
- if (col.pk && col.type.includes('INT')) {
1003
- continue;
1032
+ if (pathname === '/api/auth-admin') {
1033
+ if (request.method === 'GET') {
1034
+ const [users, sessions, apiKeys] = await Promise.all([
1035
+ readRowsIfTableExists(db, '_local_users', 500),
1036
+ readRowsIfTableExists(db, '_local_sessions', 500),
1037
+ readRowsIfTableExists(db, '_local_api_keys', 500),
1038
+ ]);
1039
+ return jsonResponse({ users, sessions, apiKeys });
1040
+ }
1041
+ if (request.method === 'POST') {
1042
+ if (readOnly) {
1043
+ return errorResponse('Dashboard is running in read-only mode.', 403);
1004
1044
  }
1005
- insertCols.push((0, sql_js_1.escapeIdentifier)(col.name));
1006
- placeholders.push('?');
1007
- const n = i + 1;
1008
- const suffix = `${now.toString(36)}_${n}`;
1009
- const fkCandidates = fkValues.get(lower);
1010
- if (fkCandidates !== undefined) {
1011
- params.push(fkCandidates.length > 0
1012
- ? fkCandidates[i % fkCandidates.length]
1013
- : col.notnull
1014
- ? `${tableName.slice(0, 4)}_${suffix}`
1015
- : null);
1045
+ const body = (await request.json().catch(() => null));
1046
+ const action = String(body?.action ?? '');
1047
+ const id = String(body?.id ?? '');
1048
+ if (!id)
1049
+ return errorResponse('id is required.', 400);
1050
+ if (action === 'revoke_session') {
1051
+ await db.execute(`DELETE FROM _local_sessions WHERE id = ?;`, [id]);
1052
+ return jsonResponse({ ok: true });
1016
1053
  }
1017
- else if (col.pk || lower === 'id' || lower.endsWith('_id')) {
1018
- params.push(`${tableName.slice(0, 4)}_${suffix}`);
1054
+ if (action === 'unlock_user') {
1055
+ await db.execute(`UPDATE _local_users SET failed_attempts = 0, locked_until = NULL WHERE id = ?;`, [id]);
1056
+ return jsonResponse({ ok: true });
1019
1057
  }
1020
- else if (lower.includes('email')) {
1021
- params.push(`user${n}_${now.toString(36)}@example.com`);
1058
+ if (action === 'revoke_api_key') {
1059
+ await db.execute(`UPDATE _local_api_keys SET revoked_at = ? WHERE id = ?;`, [Date.now(), id]).catch(async () => {
1060
+ await db.execute(`DELETE FROM _local_api_keys WHERE id = ?;`, [id]);
1061
+ });
1062
+ return jsonResponse({ ok: true });
1022
1063
  }
1023
- else if (lower.includes('name') || lower.includes('title')) {
1024
- params.push(`Sample ${col.name} ${n}`);
1064
+ return errorResponse(`Unsupported auth action "${action}".`, 400);
1065
+ }
1066
+ }
1067
+ if (pathname === '/api/jobs') {
1068
+ if (request.method === 'GET') {
1069
+ const [actions, scheduledJobs, jobRuns, outbox] = await Promise.all([
1070
+ readRowsIfTableExists(db, '_local_actions', 500),
1071
+ readRowsIfTableExists(db, '_local_scheduled_jobs', 200),
1072
+ readRowsIfTableExists(db, '_local_job_runs', 200),
1073
+ readRowsIfTableExists(db, 'sync_outbox', 500),
1074
+ ]);
1075
+ return jsonResponse({ actions, scheduledJobs, jobRuns, outbox });
1076
+ }
1077
+ if (request.method === 'POST') {
1078
+ if (readOnly) {
1079
+ return errorResponse('Dashboard is running in read-only mode.', 403);
1080
+ }
1081
+ const body = (await request.json().catch(() => null));
1082
+ const action = String(body?.action ?? '');
1083
+ const id = String(body?.id ?? '');
1084
+ if (action === 'retry_action' && id) {
1085
+ await db.execute(`UPDATE _local_actions SET status = 'pending', attempts = 0, last_error = NULL WHERE id = ?;`, [id]);
1086
+ return jsonResponse({ ok: true });
1025
1087
  }
1026
- else if (lower.includes('created') || lower.includes('updated') || lower.includes('date') || lower.includes('time')) {
1027
- params.push(col.type.includes('INT') ? now + i : new Date(now + i * 1000).toISOString());
1088
+ if (action === 'delete_action' && id) {
1089
+ await db.execute(`DELETE FROM _local_actions WHERE id = ?;`, [id]);
1090
+ return jsonResponse({ ok: true });
1028
1091
  }
1029
- else if (lower.includes('active') || lower.includes('enabled') || lower.startsWith('is_') || col.type.includes('BOOL')) {
1030
- params.push(i % 2 === 0 ? 1 : 0);
1092
+ if (action === 'clear_completed_actions') {
1093
+ const exists = await db.execute(`SELECT name FROM sqlite_master WHERE type = 'table' AND name = '_local_actions';`);
1094
+ if (exists?.length) {
1095
+ await db.execute(`DELETE FROM _local_actions WHERE status = 'completed';`);
1096
+ }
1097
+ return jsonResponse({ ok: true });
1031
1098
  }
1032
- else if (col.type.includes('INT')) {
1033
- params.push(n * 10);
1099
+ if (action === 'retry_outbox' && id) {
1100
+ await db.execute(`UPDATE sync_outbox SET status = 'pending', retry_count = 0, last_error = NULL WHERE id = ?;`, [id]);
1101
+ return jsonResponse({ ok: true });
1034
1102
  }
1035
- else if (col.type.includes('REAL') || col.type.includes('FLOAT') || col.type.includes('NUM') || col.type.includes('DEC')) {
1036
- params.push(Number((n * 12.5).toFixed(2)));
1103
+ if (action === 'delete_outbox' && id) {
1104
+ await db.execute(`DELETE FROM sync_outbox WHERE id = ?;`, [id]);
1105
+ return jsonResponse({ ok: true });
1037
1106
  }
1038
- else {
1039
- params.push(`${col.name}_${n}`);
1107
+ if (action === 'toggle_job' && id) {
1108
+ await db.execute(`UPDATE _local_scheduled_jobs SET enabled = ? WHERE id = ?;`, [body?.enabled ? 1 : 0, id]);
1109
+ return jsonResponse({ ok: true });
1040
1110
  }
1111
+ if (action === 'delete_job' && id) {
1112
+ await db.execute(`DELETE FROM _local_scheduled_jobs WHERE id = ?;`, [id]);
1113
+ return jsonResponse({ ok: true });
1114
+ }
1115
+ return errorResponse(`Unsupported job action "${action}".`, 400);
1041
1116
  }
1042
- if (insertCols.length === 0) {
1043
- await db.execute(`INSERT INTO ${quoted} DEFAULT VALUES;`);
1117
+ }
1118
+ // ── Live Logs & Query Telemetry ────────────────────────────────────
1119
+ if (pathname === '/api/logs') {
1120
+ if (request.method === 'GET') {
1121
+ const level = url.searchParams.get('level')?.trim() || '';
1122
+ const search = url.searchParams.get('q')?.trim().toLowerCase() || '';
1123
+ const filtered = logs.filter((entry) => {
1124
+ if (level === 'error' && entry.status < 400)
1125
+ return false;
1126
+ if (level === 'ok' && entry.status >= 400)
1127
+ return false;
1128
+ if (search) {
1129
+ const hay = `${entry.method} ${entry.path} ${entry.detail ?? ''}`.toLowerCase();
1130
+ if (!hay.includes(search))
1131
+ return false;
1132
+ }
1133
+ return true;
1134
+ });
1135
+ return jsonResponse({ logs: filtered });
1044
1136
  }
1045
- else {
1046
- await db.execute(`INSERT INTO ${quoted} (${insertCols.join(', ')}) VALUES (${placeholders.join(', ')});`, params);
1137
+ if (request.method === 'DELETE') {
1138
+ logs.length = 0;
1139
+ return jsonResponse({ ok: true });
1047
1140
  }
1048
- inserted++;
1049
1141
  }
1050
- return reply(jsonResponse({ ok: true, inserted }), `Seeded ${inserted} rows into ${tableName}`);
1051
- }
1052
- // ── Migration & Schema Diff Generator ──────────────────────────────
1053
- if (pathname === '/api/schema/diff' && request.method === 'POST') {
1054
- const body = (await request.json().catch(() => null));
1055
- const targetSql = typeof body?.targetSql === 'string' ? body.targetSql : '';
1056
- const targetTablesInput = Array.isArray(body?.tables) ? body.tables : null;
1057
- const liveTables = (await listTables(db)).filter((t) => !(0, sql_js_1.isInternalTable)(t.name));
1058
- const parseTargetSql = (sqlText) => {
1059
- const parsed = [];
1060
- const regex = /CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?["`[]?([A-Za-z_][A-Za-z0-9_]*)["`\]]?\s*\(([\s\S]*?)\)\s*;/gi;
1061
- let match;
1062
- while ((match = regex.exec(sqlText)) !== null) {
1063
- const tName = match[1];
1064
- const bodyStr = match[2];
1065
- const cols = [];
1066
- for (const rawLine of bodyStr.split(',')) {
1067
- const line = rawLine.trim();
1068
- if (!line || /^(PRIMARY\s+KEY|FOREIGN\s+KEY|UNIQUE|CHECK|CONSTRAINT)\b/i.test(line))
1069
- continue;
1070
- const colMatch = line.match(/^["`[]?([A-Za-z_][A-Za-z0-9_]*)["`\]]?\s+([A-Za-z0-9_()]+)?([\s\S]*)$/i);
1071
- if (!colMatch)
1142
+ // ── Sample Row Seeder ──────────────────────────────────────────────
1143
+ const seedMatch = pathname.match(/^\/api\/tables\/([^/]+)\/seed$/);
1144
+ if (seedMatch && request.method === 'POST') {
1145
+ if (readOnly)
1146
+ return reply(errorResponse('Dashboard is in read-only mode.', 403));
1147
+ const tableName = decodeURIComponent(seedMatch[1]);
1148
+ const quoted = (0, sql_js_1.escapeIdentifier)(tableName);
1149
+ const colRows = (await db.execute(`PRAGMA table_info(${quoted});`)) ?? [];
1150
+ if (colRows.length === 0) {
1151
+ return reply(errorResponse(`Table "${tableName}" not found.`, 404));
1152
+ }
1153
+ const body = (await request.json().catch(() => null));
1154
+ const count = Math.min(100, Math.max(1, Number(body?.count ?? 10) || 10));
1155
+ const cols = colRows.map((r) => ({
1156
+ name: String(r.name),
1157
+ type: String(r.type ?? 'TEXT').toUpperCase(),
1158
+ notnull: Boolean(r.notnull),
1159
+ pk: Number(r.pk) > 0,
1160
+ }));
1161
+ const fkRows = (await db.execute(`PRAGMA foreign_key_list(${quoted});`)) ?? [];
1162
+ const fkValues = new Map();
1163
+ for (const fk of fkRows) {
1164
+ const fromCol = String(fk.from ?? '');
1165
+ const refTable = String(fk.table ?? '');
1166
+ const refCol = String(fk.to ?? '');
1167
+ if (!fromCol || !refTable || !refCol)
1168
+ continue;
1169
+ try {
1170
+ const refRows = (await db.execute(`SELECT ${(0, sql_js_1.escapeIdentifier)(refCol)} AS val FROM ${(0, sql_js_1.escapeIdentifier)(refTable)} LIMIT 20;`)) ?? [];
1171
+ fkValues.set(fromCol.toLowerCase(), refRows.map((r) => r.val));
1172
+ }
1173
+ catch {
1174
+ // ignore
1175
+ }
1176
+ }
1177
+ const now = Date.now();
1178
+ let inserted = 0;
1179
+ for (let i = 0; i < count; i++) {
1180
+ const insertCols = [];
1181
+ const placeholders = [];
1182
+ const params = [];
1183
+ for (const col of cols) {
1184
+ const lower = col.name.toLowerCase();
1185
+ if (col.pk && col.type.includes('INT')) {
1072
1186
  continue;
1073
- const colName = colMatch[1];
1074
- const colType = (colMatch[2] || 'TEXT').toUpperCase();
1075
- const rest = (colMatch[3] || '').toUpperCase();
1076
- cols.push({
1077
- name: colName,
1078
- type: colType,
1079
- notnull: rest.includes('NOT NULL'),
1080
- pk: rest.includes('PRIMARY KEY'),
1081
- });
1187
+ }
1188
+ insertCols.push((0, sql_js_1.escapeIdentifier)(col.name));
1189
+ placeholders.push('?');
1190
+ const n = i + 1;
1191
+ const suffix = `${now.toString(36)}_${n}`;
1192
+ const fkCandidates = fkValues.get(lower);
1193
+ if (fkCandidates !== undefined) {
1194
+ params.push(fkCandidates.length > 0
1195
+ ? fkCandidates[i % fkCandidates.length]
1196
+ : col.notnull
1197
+ ? `${tableName.slice(0, 4)}_${suffix}`
1198
+ : null);
1199
+ }
1200
+ else if (col.pk || lower === 'id' || lower.endsWith('_id')) {
1201
+ params.push(`${tableName.slice(0, 4)}_${suffix}`);
1202
+ }
1203
+ else if (lower.includes('email')) {
1204
+ params.push(`user${n}_${now.toString(36)}@example.com`);
1205
+ }
1206
+ else if (lower.includes('name') || lower.includes('title')) {
1207
+ params.push(`Sample ${col.name} ${n}`);
1208
+ }
1209
+ else if (lower.includes('created') || lower.includes('updated') || lower.includes('date') || lower.includes('time')) {
1210
+ params.push(col.type.includes('INT') ? now + i : new Date(now + i * 1000).toISOString());
1211
+ }
1212
+ else if (lower.includes('active') || lower.includes('enabled') || lower.startsWith('is_') || col.type.includes('BOOL')) {
1213
+ params.push(i % 2 === 0 ? 1 : 0);
1214
+ }
1215
+ else if (col.type.includes('INT')) {
1216
+ params.push(n * 10);
1217
+ }
1218
+ else if (col.type.includes('REAL') || col.type.includes('FLOAT') || col.type.includes('NUM') || col.type.includes('DEC')) {
1219
+ params.push(Number((n * 12.5).toFixed(2)));
1220
+ }
1221
+ else {
1222
+ params.push(`${col.name}_${n}`);
1223
+ }
1082
1224
  }
1083
- parsed.push({ name: tName, columns: cols });
1084
- }
1085
- return parsed;
1086
- };
1087
- const targetTables = targetTablesInput
1088
- ? targetTablesInput
1089
- : targetSql.trim()
1090
- ? parseTargetSql(targetSql)
1091
- : [];
1092
- const statements = [];
1093
- const summary = [];
1094
- if (targetTables.length === 0) {
1095
- for (const t of liveTables) {
1096
- const colDefs = t.columns.map((c) => {
1097
- const parts = [(0, sql_js_1.escapeIdentifier)(c.name), c.type || 'TEXT'];
1098
- if (c.pk)
1099
- parts.push('PRIMARY KEY');
1100
- if (c.notnull && !c.pk)
1101
- parts.push('NOT NULL');
1102
- if (c.dflt_value !== null && c.dflt_value !== undefined)
1103
- parts.push(`DEFAULT ${c.dflt_value}`);
1104
- return ` ${parts.join(' ')}`;
1105
- });
1106
- statements.push(`CREATE TABLE IF NOT EXISTS ${(0, sql_js_1.escapeIdentifier)(t.name)} (\n${colDefs.join(',\n')}\n);`);
1107
- summary.push({ type: 'baseline', table: t.name, detail: `${t.columns.length} columns` });
1225
+ if (insertCols.length === 0) {
1226
+ await db.execute(`INSERT INTO ${quoted} DEFAULT VALUES;`);
1227
+ }
1228
+ else {
1229
+ await db.execute(`INSERT INTO ${quoted} (${insertCols.join(', ')}) VALUES (${placeholders.join(', ')});`, params);
1230
+ }
1231
+ inserted++;
1108
1232
  }
1233
+ return reply(jsonResponse({ ok: true, inserted }), `Seeded ${inserted} rows into ${tableName}`);
1109
1234
  }
1110
- else {
1111
- const liveMap = new Map(liveTables.map((t) => [t.name.toLowerCase(), t]));
1112
- const targetMap = new Map(targetTables.map((t) => [t.name.toLowerCase(), t]));
1113
- for (const target of targetTables) {
1114
- const live = liveMap.get(target.name.toLowerCase());
1115
- if (!live) {
1116
- const colDefs = target.columns.map((c) => {
1235
+ // ── Migration & Schema Diff Generator ──────────────────────────────
1236
+ if (pathname === '/api/schema/diff' && request.method === 'POST') {
1237
+ const body = (await request.json().catch(() => null));
1238
+ const targetSql = typeof body?.targetSql === 'string' ? body.targetSql : '';
1239
+ const targetTablesInput = Array.isArray(body?.tables) ? body.tables : null;
1240
+ const liveTables = (await listTables(db)).filter((t) => !(0, sql_js_1.isInternalTable)(t.name));
1241
+ const parseTargetSql = (sqlText) => {
1242
+ const parsed = [];
1243
+ const regex = /CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?["`[]?([A-Za-z_][A-Za-z0-9_]*)["`\]]?\s*\(([\s\S]*?)\)\s*;/gi;
1244
+ let match;
1245
+ while ((match = regex.exec(sqlText)) !== null) {
1246
+ const tName = match[1];
1247
+ const bodyStr = match[2];
1248
+ const cols = [];
1249
+ for (const rawLine of bodyStr.split(',')) {
1250
+ const line = rawLine.trim();
1251
+ if (!line || /^(PRIMARY\s+KEY|FOREIGN\s+KEY|UNIQUE|CHECK|CONSTRAINT)\b/i.test(line))
1252
+ continue;
1253
+ const colMatch = line.match(/^["`[]?([A-Za-z_][A-Za-z0-9_]*)["`\]]?\s+([A-Za-z0-9_()]+)?([\s\S]*)$/i);
1254
+ if (!colMatch)
1255
+ continue;
1256
+ const colName = colMatch[1];
1257
+ const colType = (colMatch[2] || 'TEXT').toUpperCase();
1258
+ const rest = (colMatch[3] || '').toUpperCase();
1259
+ cols.push({
1260
+ name: colName,
1261
+ type: colType,
1262
+ notnull: rest.includes('NOT NULL'),
1263
+ pk: rest.includes('PRIMARY KEY'),
1264
+ });
1265
+ }
1266
+ parsed.push({ name: tName, columns: cols });
1267
+ }
1268
+ return parsed;
1269
+ };
1270
+ const targetTables = targetTablesInput
1271
+ ? targetTablesInput
1272
+ : targetSql.trim()
1273
+ ? parseTargetSql(targetSql)
1274
+ : [];
1275
+ const statements = [];
1276
+ const summary = [];
1277
+ if (targetTables.length === 0) {
1278
+ for (const t of liveTables) {
1279
+ const colDefs = t.columns.map((c) => {
1117
1280
  const parts = [(0, sql_js_1.escapeIdentifier)(c.name), c.type || 'TEXT'];
1118
1281
  if (c.pk)
1119
1282
  parts.push('PRIMARY KEY');
@@ -1123,191 +1286,256 @@ function createDashboardHandler(db, options = {}) {
1123
1286
  parts.push(`DEFAULT ${c.dflt_value}`);
1124
1287
  return ` ${parts.join(' ')}`;
1125
1288
  });
1126
- statements.push(`CREATE TABLE IF NOT EXISTS ${(0, sql_js_1.escapeIdentifier)(target.name)} (\n${colDefs.join(',\n')}\n);`);
1127
- summary.push({ type: 'create_table', table: target.name, detail: `New table (${target.columns.length} columns)` });
1289
+ statements.push(`CREATE TABLE IF NOT EXISTS ${(0, sql_js_1.escapeIdentifier)(t.name)} (\n${colDefs.join(',\n')}\n);`);
1290
+ summary.push({ type: 'baseline', table: t.name, detail: `${t.columns.length} columns` });
1128
1291
  }
1129
- else {
1130
- const liveCols = new Set(live.columns.map((c) => c.name.toLowerCase()));
1131
- for (const tc of target.columns) {
1132
- if (!liveCols.has(tc.name.toLowerCase())) {
1133
- const def = `${(0, sql_js_1.escapeIdentifier)(tc.name)} ${tc.type || 'TEXT'}${tc.notnull ? " NOT NULL DEFAULT ''" : ''}`;
1134
- statements.push(`ALTER TABLE ${(0, sql_js_1.escapeIdentifier)(target.name)} ADD COLUMN ${def};`);
1135
- summary.push({ type: 'add_column', table: target.name, detail: `Add column ${tc.name} (${tc.type || 'TEXT'})` });
1292
+ }
1293
+ else {
1294
+ const liveMap = new Map(liveTables.map((t) => [t.name.toLowerCase(), t]));
1295
+ const targetMap = new Map(targetTables.map((t) => [t.name.toLowerCase(), t]));
1296
+ for (const target of targetTables) {
1297
+ const live = liveMap.get(target.name.toLowerCase());
1298
+ if (!live) {
1299
+ const colDefs = target.columns.map((c) => {
1300
+ const parts = [(0, sql_js_1.escapeIdentifier)(c.name), c.type || 'TEXT'];
1301
+ if (c.pk)
1302
+ parts.push('PRIMARY KEY');
1303
+ if (c.notnull && !c.pk)
1304
+ parts.push('NOT NULL');
1305
+ if (c.dflt_value !== null && c.dflt_value !== undefined)
1306
+ parts.push(`DEFAULT ${c.dflt_value}`);
1307
+ return ` ${parts.join(' ')}`;
1308
+ });
1309
+ statements.push(`CREATE TABLE IF NOT EXISTS ${(0, sql_js_1.escapeIdentifier)(target.name)} (\n${colDefs.join(',\n')}\n);`);
1310
+ summary.push({ type: 'create_table', table: target.name, detail: `New table (${target.columns.length} columns)` });
1311
+ }
1312
+ else {
1313
+ const liveCols = new Set(live.columns.map((c) => c.name.toLowerCase()));
1314
+ for (const tc of target.columns) {
1315
+ if (!liveCols.has(tc.name.toLowerCase())) {
1316
+ const def = `${(0, sql_js_1.escapeIdentifier)(tc.name)} ${tc.type || 'TEXT'}${tc.notnull ? " NOT NULL DEFAULT ''" : ''}`;
1317
+ statements.push(`ALTER TABLE ${(0, sql_js_1.escapeIdentifier)(target.name)} ADD COLUMN ${def};`);
1318
+ summary.push({ type: 'add_column', table: target.name, detail: `Add column ${tc.name} (${tc.type || 'TEXT'})` });
1319
+ }
1136
1320
  }
1137
1321
  }
1138
1322
  }
1323
+ for (const live of liveTables) {
1324
+ if (!targetMap.has(live.name.toLowerCase())) {
1325
+ statements.push(`-- Table "${live.name}" exists in DB but not in target schema`);
1326
+ statements.push(`-- DROP TABLE IF EXISTS ${(0, sql_js_1.escapeIdentifier)(live.name)};`);
1327
+ summary.push({ type: 'extra_table', table: live.name, detail: 'Exists in DB only (commented DROP)' });
1328
+ }
1329
+ }
1139
1330
  }
1140
- for (const live of liveTables) {
1141
- if (!targetMap.has(live.name.toLowerCase())) {
1142
- statements.push(`-- Table "${live.name}" exists in DB but not in target schema`);
1143
- statements.push(`-- DROP TABLE IF EXISTS ${(0, sql_js_1.escapeIdentifier)(live.name)};`);
1144
- summary.push({ type: 'extra_table', table: live.name, detail: 'Exists in DB only (commented DROP)' });
1331
+ return reply(jsonResponse({
1332
+ sql: statements.join('\n\n'),
1333
+ changes: summary,
1334
+ }));
1335
+ }
1336
+ // ── FTS5 Full-Text Search Explorer ─────────────────────────────────
1337
+ if (pathname === '/api/search/indexes' && request.method === 'GET') {
1338
+ const ftsRows = (await db.execute(`SELECT name, sql FROM sqlite_master WHERE type = 'table' AND name LIKE '_fts_%' AND sql LIKE 'CREATE VIRTUAL TABLE%' ORDER BY name;`)) ?? [];
1339
+ const indexes = [];
1340
+ for (const row of ftsRows) {
1341
+ const ftsName = String(row.name);
1342
+ const sourceTable = ftsName.replace(/^_fts_/, '');
1343
+ let count = 0;
1344
+ try {
1345
+ const cnt = (await db.execute(`SELECT COUNT(*) AS count FROM ${(0, sql_js_1.escapeIdentifier)(ftsName)};`)) ?? [];
1346
+ count = Number(cnt[0]?.count ?? 0);
1347
+ }
1348
+ catch {
1349
+ // ignore
1145
1350
  }
1351
+ indexes.push({
1352
+ ftsTable: ftsName,
1353
+ sourceTable,
1354
+ rowCount: count,
1355
+ sql: row.sql ? String(row.sql) : null,
1356
+ });
1146
1357
  }
1358
+ return reply(jsonResponse({ indexes }));
1147
1359
  }
1148
- return reply(jsonResponse({
1149
- sql: statements.join('\n\n'),
1150
- changes: summary,
1151
- }));
1152
- }
1153
- // ── FTS5 Full-Text Search Explorer ─────────────────────────────────
1154
- if (pathname === '/api/search/indexes' && request.method === 'GET') {
1155
- const ftsRows = (await db.execute(`SELECT name, sql FROM sqlite_master WHERE type = 'table' AND name LIKE '_fts_%' AND sql LIKE 'CREATE VIRTUAL TABLE%' ORDER BY name;`)) ?? [];
1156
- const indexes = [];
1157
- for (const row of ftsRows) {
1158
- const ftsName = String(row.name);
1159
- const sourceTable = ftsName.replace(/^_fts_/, '');
1160
- let count = 0;
1161
- try {
1162
- const cnt = (await db.execute(`SELECT COUNT(*) AS count FROM ${(0, sql_js_1.escapeIdentifier)(ftsName)};`)) ?? [];
1163
- count = Number(cnt[0]?.count ?? 0);
1164
- }
1165
- catch {
1166
- // ignore
1360
+ if (pathname === '/api/search/index' && request.method === 'POST') {
1361
+ if (readOnly)
1362
+ return reply(errorResponse('Dashboard is in read-only mode.', 403));
1363
+ const body = (await request.json().catch(() => null));
1364
+ const tableName = typeof body?.table === 'string' ? body.table.trim() : '';
1365
+ if (!tableName)
1366
+ return reply(errorResponse('Table name is required.', 400));
1367
+ const quotedSource = (0, sql_js_1.escapeIdentifier)(tableName);
1368
+ const info = (await db.execute(`PRAGMA table_info(${quotedSource});`)) ?? [];
1369
+ if (info.length === 0)
1370
+ return reply(errorResponse(`Table "${tableName}" not found.`, 404));
1371
+ const requestedCols = Array.isArray(body?.columns)
1372
+ ? body.columns.map(String).filter(Boolean)
1373
+ : info
1374
+ .filter((r) => !String(r.type ?? '').toUpperCase().includes('BLOB'))
1375
+ .map((r) => String(r.name));
1376
+ if (requestedCols.length === 0) {
1377
+ return reply(errorResponse('No searchable columns found.', 400));
1167
1378
  }
1168
- indexes.push({
1379
+ const ftsName = `_fts_${tableName}`;
1380
+ const quotedFts = (0, sql_js_1.escapeIdentifier)(ftsName);
1381
+ const colList = requestedCols.map((c) => (0, sql_js_1.escapeIdentifier)(c)).join(', ');
1382
+ const newColList = requestedCols.map((c) => `new.${(0, sql_js_1.escapeIdentifier)(c)}`).join(', ');
1383
+ await db.execute(`DROP TABLE IF EXISTS ${quotedFts};`);
1384
+ await db.execute(`CREATE VIRTUAL TABLE ${quotedFts} USING fts5(${colList});`);
1385
+ await db.execute(`INSERT INTO ${quotedFts}(rowid, ${colList}) SELECT rowid, ${colList} FROM ${quotedSource};`);
1386
+ const aiTrig = (0, sql_js_1.escapeIdentifier)(`_fts_${tableName}_ai`);
1387
+ const auTrig = (0, sql_js_1.escapeIdentifier)(`_fts_${tableName}_au`);
1388
+ const adTrig = (0, sql_js_1.escapeIdentifier)(`_fts_${tableName}_ad`);
1389
+ await db.execute(`DROP TRIGGER IF EXISTS ${aiTrig};`);
1390
+ await db.execute(`DROP TRIGGER IF EXISTS ${auTrig};`);
1391
+ await db.execute(`DROP TRIGGER IF EXISTS ${adTrig};`);
1392
+ await db.execute(`CREATE TRIGGER ${aiTrig} AFTER INSERT ON ${quotedSource} BEGIN
1393
+ INSERT INTO ${quotedFts}(rowid, ${colList}) VALUES (new.rowid, ${newColList});
1394
+ END;`);
1395
+ await db.execute(`CREATE TRIGGER ${adTrig} AFTER DELETE ON ${quotedSource} BEGIN
1396
+ DELETE FROM ${quotedFts} WHERE rowid = old.rowid;
1397
+ END;`);
1398
+ await db.execute(`CREATE TRIGGER ${auTrig} AFTER UPDATE ON ${quotedSource} BEGIN
1399
+ DELETE FROM ${quotedFts} WHERE rowid = old.rowid;
1400
+ INSERT INTO ${quotedFts}(rowid, ${colList}) VALUES (new.rowid, ${newColList});
1401
+ END;`);
1402
+ const cnt = (await db.execute(`SELECT COUNT(*) AS count FROM ${quotedFts};`)) ?? [];
1403
+ return reply(jsonResponse({
1404
+ ok: true,
1169
1405
  ftsTable: ftsName,
1170
- sourceTable,
1171
- rowCount: count,
1172
- sql: row.sql ? String(row.sql) : null,
1173
- });
1174
- }
1175
- return reply(jsonResponse({ indexes }));
1176
- }
1177
- if (pathname === '/api/search/index' && request.method === 'POST') {
1178
- if (readOnly)
1179
- return reply(errorResponse('Dashboard is in read-only mode.', 403));
1180
- const body = (await request.json().catch(() => null));
1181
- const tableName = typeof body?.table === 'string' ? body.table.trim() : '';
1182
- if (!tableName)
1183
- return reply(errorResponse('Table name is required.', 400));
1184
- const quotedSource = (0, sql_js_1.escapeIdentifier)(tableName);
1185
- const info = (await db.execute(`PRAGMA table_info(${quotedSource});`)) ?? [];
1186
- if (info.length === 0)
1187
- return reply(errorResponse(`Table "${tableName}" not found.`, 404));
1188
- const requestedCols = Array.isArray(body?.columns)
1189
- ? body.columns.map(String).filter(Boolean)
1190
- : info
1191
- .filter((r) => !String(r.type ?? '').toUpperCase().includes('BLOB'))
1192
- .map((r) => String(r.name));
1193
- if (requestedCols.length === 0) {
1194
- return reply(errorResponse('No searchable columns found.', 400));
1195
- }
1196
- const ftsName = `_fts_${tableName}`;
1197
- const quotedFts = (0, sql_js_1.escapeIdentifier)(ftsName);
1198
- const colList = requestedCols.map((c) => (0, sql_js_1.escapeIdentifier)(c)).join(', ');
1199
- await db.execute(`DROP TABLE IF EXISTS ${quotedFts};`);
1200
- await db.execute(`CREATE VIRTUAL TABLE ${quotedFts} USING fts5(${colList});`);
1201
- await db.execute(`INSERT INTO ${quotedFts}(${colList}) SELECT ${colList} FROM ${quotedSource};`);
1202
- const cnt = (await db.execute(`SELECT COUNT(*) AS count FROM ${quotedFts};`)) ?? [];
1203
- return reply(jsonResponse({
1204
- ok: true,
1205
- ftsTable: ftsName,
1206
- sourceTable: tableName,
1207
- columns: requestedCols,
1208
- rowCount: Number(cnt[0]?.count ?? 0),
1209
- }, 201), `Indexed ${tableName} into ${ftsName}`);
1210
- }
1211
- if (pathname === '/api/search' && request.method === 'GET') {
1212
- const tableName = url.searchParams.get('table')?.trim() || '';
1213
- const q = url.searchParams.get('q')?.trim() || '';
1214
- const limit = Math.min(100, Math.max(1, Number(url.searchParams.get('limit') ?? 25) || 25));
1215
- if (!tableName)
1216
- return reply(errorResponse('Query parameter "table" is required.', 400));
1217
- const ftsName = tableName.startsWith('_fts_') ? tableName : `_fts_${tableName}`;
1218
- const quotedFts = (0, sql_js_1.escapeIdentifier)(ftsName);
1219
- if (!q) {
1220
- const rows = (await db.execute(`SELECT rowid, * FROM ${quotedFts} LIMIT ?;`, [limit])) ?? [];
1406
+ sourceTable: tableName,
1407
+ columns: requestedCols,
1408
+ rowCount: Number(cnt[0]?.count ?? 0),
1409
+ }, 201), `Indexed ${tableName} into ${ftsName}`);
1410
+ }
1411
+ if (pathname === '/api/search' && request.method === 'GET') {
1412
+ const tableName = url.searchParams.get('table')?.trim() || '';
1413
+ const q = url.searchParams.get('q')?.trim() || '';
1414
+ const limit = Math.min(100, Math.max(1, Number(url.searchParams.get('limit') ?? 25) || 25));
1415
+ if (!tableName)
1416
+ return reply(errorResponse('Query parameter "table" is required.', 400));
1417
+ const ftsName = tableName.startsWith('_fts_') ? tableName : `_fts_${tableName}`;
1418
+ const quotedFts = (0, sql_js_1.escapeIdentifier)(ftsName);
1419
+ if (!q) {
1420
+ const rows = (await db.execute(`SELECT rowid, * FROM ${quotedFts} LIMIT ?;`, [limit])) ?? [];
1421
+ const columns = rows.length > 0 ? Object.keys(rows[0]) : [];
1422
+ return reply(jsonResponse({ rows, columns }));
1423
+ }
1424
+ const safeQuery = q.includes('"') ? q : `"${q.replace(/"/g, '""')}"*`;
1425
+ const info = (await db.execute(`PRAGMA table_info(${quotedFts});`)) ?? [];
1426
+ const snippetExpr = info.length > 0
1427
+ ? `snippet(${quotedFts}, 0, '<mark>', '</mark>', '...', 24) AS _snippet,`
1428
+ : '';
1429
+ const rows = (await db.execute(`SELECT rowid, bm25(${quotedFts}) AS _rank, ${snippetExpr} * FROM ${quotedFts} WHERE ${quotedFts} MATCH ? ORDER BY _rank LIMIT ?;`, [safeQuery, limit])) ?? [];
1221
1430
  const columns = rows.length > 0 ? Object.keys(rows[0]) : [];
1222
- return reply(jsonResponse({ rows, columns }));
1223
- }
1224
- const safeQuery = q.includes('"') ? q : `"${q.replace(/"/g, '""')}"*`;
1225
- const info = (await db.execute(`PRAGMA table_info(${quotedFts});`)) ?? [];
1226
- const snippetExpr = info.length > 0
1227
- ? `snippet(${quotedFts}, 0, '<mark>', '</mark>', '...', 24) AS _snippet,`
1228
- : '';
1229
- const rows = (await db.execute(`SELECT rowid, bm25(${quotedFts}) AS _rank, ${snippetExpr} * FROM ${quotedFts} WHERE ${quotedFts} MATCH ? ORDER BY _rank LIMIT ?;`, [safeQuery, limit])) ?? [];
1230
- const columns = rows.length > 0 ? Object.keys(rows[0]) : [];
1231
- return reply(jsonResponse({ rows, columns }), `FTS5 "${q}" on ${ftsName}`);
1232
- }
1233
- // ── Encrypted Backup & Restore ─────────────────────────────────────
1234
- if (pathname === '/api/backups/export' && request.method === 'POST') {
1235
- const body = (await request.json().catch(() => null));
1236
- const passphrase = typeof body?.passphrase === 'string' ? body.passphrase : '';
1237
- if (passphrase.length < 4) {
1238
- return reply(errorResponse('Passphrase must be at least 4 characters.', 400));
1239
- }
1240
- const allTables = (await listTables(db)).filter((t) => !t.name.startsWith('_fts_') && !t.name.startsWith('sqlite_'));
1241
- const tablesData = {};
1242
- for (const t of allTables) {
1243
- const dataRows = (await db.execute(`SELECT * FROM ${(0, sql_js_1.escapeIdentifier)(t.name)};`)) ?? [];
1244
- const sqlRow = (await db.execute(`SELECT sql FROM sqlite_master WHERE type = 'table' AND name = ?;`, [t.name])) ?? [];
1245
- tablesData[t.name] = {
1246
- sql: sqlRow[0]?.sql ? String(sqlRow[0].sql) : null,
1247
- rows: dataRows,
1248
- };
1249
- }
1250
- const payload = JSON.stringify({
1251
- version: 1,
1252
- exportedAt: new Date().toISOString(),
1253
- tables: tablesData,
1254
- });
1255
- const encrypted = await (0, encryption_js_1.encryptBackupData)(new TextEncoder().encode(payload), passphrase);
1256
- return reply(jsonResponse({
1257
- filename: `local-lite-backup-${new Date().toISOString().slice(0, 10)}.localbackup`,
1258
- sizeBytes: encrypted.byteLength,
1259
- tableCount: Object.keys(tablesData).length,
1260
- dataBase64: Buffer.from(encrypted).toString('base64'),
1261
- }), `Exported ${Object.keys(tablesData).length} tables`);
1262
- }
1263
- if (pathname === '/api/backups/restore' && request.method === 'POST') {
1264
- if (readOnly)
1265
- return reply(errorResponse('Dashboard is in read-only mode.', 403));
1266
- const body = (await request.json().catch(() => null));
1267
- const passphrase = typeof body?.passphrase === 'string' ? body.passphrase : '';
1268
- const dataBase64 = typeof body?.dataBase64 === 'string' ? body.dataBase64 : '';
1269
- if (!passphrase || !dataBase64) {
1270
- return reply(errorResponse('Passphrase and backup data are required.', 400));
1271
- }
1272
- const encryptedBytes = new Uint8Array(Buffer.from(dataBase64, 'base64'));
1273
- let decryptedBytes;
1274
- try {
1275
- decryptedBytes = await (0, encryption_js_1.decryptBackupData)(encryptedBytes, passphrase);
1276
- }
1277
- catch {
1278
- return reply(errorResponse('Failed to decrypt backup. Check passphrase or file integrity.', 400));
1431
+ return reply(jsonResponse({ rows, columns }), `FTS5 "${q}" on ${ftsName}`);
1279
1432
  }
1280
- const snapshot = JSON.parse(new TextDecoder().decode(decryptedBytes));
1281
- if (!snapshot?.tables || typeof snapshot.tables !== 'object') {
1282
- return reply(errorResponse('Invalid backup payload.', 400));
1283
- }
1284
- let restoredTables = 0;
1285
- let restoredRows = 0;
1286
- for (const [tableName, tableEntry] of Object.entries(snapshot.tables)) {
1287
- if (tableEntry.sql) {
1288
- const createSql = tableEntry.sql.replace(/^CREATE\s+TABLE\s+/i, 'CREATE TABLE IF NOT EXISTS ');
1289
- await db.execute(createSql);
1433
+ // ── Encrypted Backup & Restore ─────────────────────────────────────
1434
+ if (pathname === '/api/backups/export' && request.method === 'POST') {
1435
+ const body = (await request.json().catch(() => null));
1436
+ const passphrase = typeof body?.passphrase === 'string' ? body.passphrase : '';
1437
+ if (passphrase.length < 4) {
1438
+ return reply(errorResponse('Passphrase must be at least 4 characters.', 400));
1290
1439
  }
1291
- const quoted = (0, sql_js_1.escapeIdentifier)(tableName);
1292
- await db.execute(`DELETE FROM ${quoted};`);
1293
- for (const row of tableEntry.rows ?? []) {
1294
- const keys = Object.keys(row);
1295
- if (keys.length === 0)
1296
- continue;
1297
- const colsSql = keys.map((k) => (0, sql_js_1.escapeIdentifier)(k)).join(', ');
1298
- const placeholders = keys.map(() => '?').join(', ');
1299
- await db.execute(`INSERT INTO ${quoted} (${colsSql}) VALUES (${placeholders});`, keys.map((k) => row[k]));
1300
- restoredRows++;
1440
+ const allTables = (await listTables(db)).filter((t) => !t.name.startsWith('_fts_') && !t.name.startsWith('sqlite_'));
1441
+ const tablesData = {};
1442
+ for (const t of allTables) {
1443
+ const dataRows = (await db.execute(`SELECT * FROM ${(0, sql_js_1.escapeIdentifier)(t.name)};`)) ?? [];
1444
+ const sqlRow = (await db.execute(`SELECT sql FROM sqlite_master WHERE type = 'table' AND name = ?;`, [t.name])) ?? [];
1445
+ tablesData[t.name] = {
1446
+ sql: sqlRow[0]?.sql ? String(sqlRow[0].sql) : null,
1447
+ rows: dataRows,
1448
+ };
1449
+ }
1450
+ const payload = JSON.stringify({
1451
+ version: 1,
1452
+ exportedAt: new Date().toISOString(),
1453
+ tables: tablesData,
1454
+ });
1455
+ const encrypted = await (0, encryption_js_1.encryptBackupData)(new TextEncoder().encode(payload), passphrase);
1456
+ return reply(jsonResponse({
1457
+ filename: `local-lite-backup-${new Date().toISOString().slice(0, 10)}.localbackup`,
1458
+ sizeBytes: encrypted.byteLength,
1459
+ tableCount: Object.keys(tablesData).length,
1460
+ dataBase64: Buffer.from(encrypted).toString('base64'),
1461
+ }), `Exported ${Object.keys(tablesData).length} tables`);
1462
+ }
1463
+ if (pathname === '/api/backups/restore' && request.method === 'POST') {
1464
+ if (readOnly)
1465
+ return reply(errorResponse('Dashboard is in read-only mode.', 403));
1466
+ const body = (await request.json().catch(() => null));
1467
+ const passphrase = typeof body?.passphrase === 'string' ? body.passphrase : '';
1468
+ const dataBase64 = typeof body?.dataBase64 === 'string' ? body.dataBase64 : '';
1469
+ if (!passphrase || !dataBase64) {
1470
+ return reply(errorResponse('Passphrase and backup data are required.', 400));
1301
1471
  }
1302
- restoredTables++;
1472
+ const encryptedBytes = new Uint8Array(Buffer.from(dataBase64, 'base64'));
1473
+ let decryptedBytes;
1474
+ try {
1475
+ decryptedBytes = await (0, encryption_js_1.decryptBackupData)(encryptedBytes, passphrase);
1476
+ }
1477
+ catch {
1478
+ return reply(errorResponse('Failed to decrypt backup. Check passphrase or file integrity.', 400));
1479
+ }
1480
+ const snapshot = JSON.parse(new TextDecoder().decode(decryptedBytes));
1481
+ if (!snapshot?.tables || typeof snapshot.tables !== 'object') {
1482
+ return reply(errorResponse('Invalid backup payload.', 400));
1483
+ }
1484
+ let restoredTables = 0;
1485
+ let restoredRows = 0;
1486
+ const fkRes = (await db.execute(`PRAGMA foreign_keys;`)) ?? [];
1487
+ const prevFk = Number(fkRes[0]?.foreign_keys ?? 0) === 1;
1488
+ if (prevFk) {
1489
+ await db.execute(`PRAGMA foreign_keys = OFF;`);
1490
+ }
1491
+ await db.execute(`BEGIN IMMEDIATE;`);
1492
+ try {
1493
+ for (const [tableName, tableEntry] of Object.entries(snapshot.tables)) {
1494
+ if (tableEntry.sql) {
1495
+ const createSql = tableEntry.sql.replace(/^CREATE\s+TABLE\s+/i, 'CREATE TABLE IF NOT EXISTS ');
1496
+ await db.execute(createSql);
1497
+ }
1498
+ const quoted = (0, sql_js_1.escapeIdentifier)(tableName);
1499
+ await db.execute(`DELETE FROM ${quoted};`);
1500
+ for (const row of tableEntry.rows ?? []) {
1501
+ const keys = Object.keys(row);
1502
+ if (keys.length === 0)
1503
+ continue;
1504
+ const colsSql = keys.map((k) => (0, sql_js_1.escapeIdentifier)(k)).join(', ');
1505
+ const placeholders = keys.map(() => '?').join(', ');
1506
+ await db.execute(`INSERT INTO ${quoted} (${colsSql}) VALUES (${placeholders});`, keys.map((k) => row[k]));
1507
+ restoredRows++;
1508
+ }
1509
+ restoredTables++;
1510
+ }
1511
+ await db.execute(`COMMIT;`);
1512
+ }
1513
+ catch (restoreErr) {
1514
+ try {
1515
+ await db.execute(`ROLLBACK;`);
1516
+ }
1517
+ catch {
1518
+ // ignore rollback error
1519
+ }
1520
+ throw restoreErr;
1521
+ }
1522
+ finally {
1523
+ if (prevFk) {
1524
+ await db.execute(`PRAGMA foreign_keys = ON;`);
1525
+ }
1526
+ }
1527
+ return reply(jsonResponse({ ok: true, restoredTables, restoredRows }), `Restored ${restoredTables} tables (${restoredRows} rows)`);
1303
1528
  }
1304
- return reply(jsonResponse({ ok: true, restoredTables, restoredRows }), `Restored ${restoredTables} tables (${restoredRows} rows)`);
1529
+ return reply(errorResponse('Not found.', 404));
1305
1530
  }
1306
- return reply(errorResponse('Not found.', 404));
1307
- }
1308
- catch (err) {
1309
- return reply(errorResponse(err?.message ?? 'Internal server error.', 500), err?.message);
1531
+ catch (err) {
1532
+ return reply(errorResponse(err?.message ?? 'Internal server error.', 500), err?.message);
1533
+ }
1534
+ })();
1535
+ if (!loggedThisRequest && pathname.startsWith('/api/')) {
1536
+ recordLog(request.method, pathname, res.status, startedAt);
1310
1537
  }
1538
+ return applyCors(res);
1311
1539
  };
1312
1540
  }
1313
1541
  function escapeHtml(text) {