local-lite-server 0.1.1 → 0.1.2

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.
@@ -5,7 +5,7 @@
5
5
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6
6
  <link rel="icon" type="image/svg+xml" href="/admin/favicon.svg" />
7
7
  <title>local-lite-server — Admin Console</title>
8
- <script type="module" crossorigin src="/admin/assets/index-B2nX9Pef.js"></script>
8
+ <script type="module" crossorigin src="/admin/assets/index-6REgGhGR.js"></script>
9
9
  <link rel="stylesheet" crossorigin href="/admin/assets/index-Dt3bXEks.css">
10
10
  </head>
11
11
  <body>
@@ -89,7 +89,8 @@ export function createAdminSession(settings, db) {
89
89
  });
90
90
  },
91
91
  async getLogin(request) {
92
- const rows = await db.query('SELECT COUNT(*) AS n FROM _local_auth_accounts WHERE console_role IS NOT NULL AND console_active != 0');
92
+ const activeCond = db.dialect === 'postgres' ? 'console_active IS TRUE' : 'console_active != 0';
93
+ const rows = await db.query(`SELECT COUNT(*) AS n FROM _local_auth_accounts WHERE console_role IS NOT NULL AND ${activeCond}`);
93
94
  const session = await authenticate(request).catch(() => null);
94
95
  return Response.json({
95
96
  hasConsoleAdmins: Number(rows[0]?.n ?? 0) > 0,
@@ -1,4 +1,5 @@
1
1
  import { createSyncEventBroker, quoteIdent, } from 'local-lite/server';
2
+ import { pgClientConfig } from '../db.js';
2
3
  /**
3
4
  * Single-node in-memory broker by default.
4
5
  * When `MULTI_INSTANCE=true`:
@@ -12,14 +13,7 @@ export async function createClusterBroker(settings, db) {
12
13
  }
13
14
  if (settings.dialect === 'postgres') {
14
15
  const pg = (await import('pg')).default;
15
- const sub = new pg.Client({
16
- host: settings.db.host,
17
- port: settings.db.port,
18
- user: settings.db.user,
19
- password: settings.db.password,
20
- database: settings.db.database,
21
- ssl: settings.db.ssl ? { rejectUnauthorized: false } : undefined,
22
- });
16
+ const sub = new pg.Client(pgClientConfig(settings));
23
17
  await sub.connect();
24
18
  sub.on('notification', (msg) => {
25
19
  if (msg.channel !== 'lls_sync_events' || !msg.payload)
@@ -29,7 +29,7 @@ export async function recordChange(tx, table, rowId, changesTable = '_server_cha
29
29
  /** Upserts a row into a schema-defined table using dialect-safe column conversion. */
30
30
  export async function upsertTableRow(tx, table, fields, rowId, data, timestamp) {
31
31
  const dialect = tx.dialect;
32
- const cols = Object.keys(fields).filter((c) => !SYSTEM_COLS.has(c) && c !== 'created_at' && Object.hasOwn(data, c));
32
+ const cols = Object.keys(fields).filter((c) => !SYSTEM_COLS.has(c) && Object.hasOwn(data, c));
33
33
  const insertCols = ['id', ...cols, 'updated_at', 'deleted'];
34
34
  const params = [
35
35
  rowId,
@@ -37,10 +37,6 @@ export async function upsertTableRow(tx, table, fields, rowId, data, timestamp)
37
37
  timestamp,
38
38
  dialect === 'postgres' ? Boolean(data.deleted) : data.deleted ? 1 : 0,
39
39
  ];
40
- if (fields.created_at) {
41
- insertCols.push('created_at');
42
- params.push(data.created_at != null ? toDbValue(fields.created_at, data.created_at, dialect) : timestamp);
43
- }
44
40
  await tx.execute(buildUpsertSql({
45
41
  table,
46
42
  conflictCols: ['id'],
@@ -0,0 +1,2 @@
1
+ /** Resolves a project config file (`src/<name>` or `<name>`), skipping this repo's own `src/` internals. */
2
+ export declare function resolveProjectFile(explicit: string | undefined, envKey: string, candidates: readonly string[], cwd?: string): string | null;
@@ -0,0 +1,20 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ /** Resolves a project config file (`src/<name>` or `<name>`), skipping this repo's own `src/` internals. */
4
+ export function resolveProjectFile(explicit, envKey, candidates, cwd = process.cwd()) {
5
+ if (explicit) {
6
+ const abs = path.resolve(cwd, explicit);
7
+ if (!fs.existsSync(abs))
8
+ throw new Error(`${envKey} not found: ${abs}`);
9
+ return abs;
10
+ }
11
+ const isOwnRepo = fs.existsSync(path.resolve(cwd, 'src/cli.ts'));
12
+ for (const name of candidates) {
13
+ if (isOwnRepo && name.startsWith('src/'))
14
+ continue;
15
+ const abs = path.resolve(cwd, name);
16
+ if (fs.existsSync(abs))
17
+ return abs;
18
+ }
19
+ return null;
20
+ }
package/dist/db.d.ts CHANGED
@@ -4,4 +4,14 @@ export interface Database {
4
4
  executor: SqlExecutor;
5
5
  close(): Promise<void>;
6
6
  }
7
+ export declare function pgClientConfig(settings: ServerSettings, database?: string): {
8
+ host: string;
9
+ port: number;
10
+ user: string;
11
+ password: string;
12
+ database: string;
13
+ ssl: {
14
+ rejectUnauthorized: boolean;
15
+ } | undefined;
16
+ };
7
17
  export declare function createDatabase(settings: ServerSettings): Promise<Database>;
package/dist/db.js CHANGED
@@ -1,4 +1,15 @@
1
1
  import { createSqlExecutor } from 'local-lite/server';
2
+ export function pgClientConfig(settings, database = settings.db.database) {
3
+ const { db } = settings;
4
+ return {
5
+ host: db.host,
6
+ port: db.port,
7
+ user: db.user,
8
+ password: db.password,
9
+ database,
10
+ ssl: db.ssl ? { rejectUnauthorized: false } : undefined,
11
+ };
12
+ }
2
13
  export async function createDatabase(settings) {
3
14
  const { db, dialect } = settings;
4
15
  if (dialect === 'postgres') {
@@ -6,12 +17,7 @@ export async function createDatabase(settings) {
6
17
  // Parse Postgres BIGINT as number to match mysql2 (epoch-ms timestamps).
7
18
  pg.types.setTypeParser(20, (v) => Number(v));
8
19
  const pool = new pg.Pool({
9
- host: db.host,
10
- port: db.port,
11
- user: db.user,
12
- password: db.password,
13
- database: db.database,
14
- ssl: db.ssl ? { rejectUnauthorized: false } : undefined,
20
+ ...pgClientConfig(settings),
15
21
  max: db.poolSize,
16
22
  });
17
23
  return {
@@ -237,8 +237,21 @@ export async function runMigrations(db) {
237
237
  await db.execute('INSERT INTO _lls_migrations (id, applied_at) VALUES (?, ?)', [m.id, Date.now()]);
238
238
  applied.push(m.id);
239
239
  }
240
+ await ensureColumn(db, '_local_auth_accounts', 'console_role', 'VARCHAR(32) NULL');
241
+ await ensureColumn(db, '_local_auth_accounts', 'console_active', db.dialect === 'postgres' ? 'BOOLEAN NOT NULL DEFAULT FALSE' : 'TINYINT(1) NOT NULL DEFAULT 0');
240
242
  return { applied };
241
243
  }
244
+ async function ensureColumn(db, table, col, def) {
245
+ try {
246
+ await db.execute(`ALTER TABLE ${table} ADD COLUMN ${col} ${def}`);
247
+ }
248
+ catch (err) {
249
+ // Ignore "duplicate column" (MySQL ER_DUP_FIELDNAME=1060, Postgres 42701).
250
+ if (err?.errno === 1060 || err?.code === 'ER_DUP_FIELDNAME' || err?.code === '42701')
251
+ return;
252
+ throw err;
253
+ }
254
+ }
242
255
  export async function coreMigrationStatus(db) {
243
256
  try {
244
257
  const rows = await db.query('SELECT id FROM _lls_migrations');
package/dist/oauth.js CHANGED
@@ -86,6 +86,15 @@ function cacheUser(token, userId) {
86
86
  tokenCache.set(token, { userId, expiresAt: Date.now() + CACHE_TTL_MS });
87
87
  return { id: userId };
88
88
  }
89
+ function toGoogleUserId(info) {
90
+ if (typeof info?.sub !== 'string' || !info.sub)
91
+ return null;
92
+ return resolveUnifiedUserId({
93
+ id: info.sub,
94
+ email: info.email,
95
+ emailVerified: info.email_verified === true || info.email_verified === 'true',
96
+ }, 'google');
97
+ }
89
98
  /** Verifies a Google (ID/access) or GitHub OAuth token and maps it to a unified userId. */
90
99
  export async function verifyOAuthToken(token) {
91
100
  if (!token || token.length < 16)
@@ -98,15 +107,9 @@ export async function verifyOAuthToken(token) {
98
107
  if (!isGitHubPrefix && token.split('.').length === 3) {
99
108
  const gRes = await fetch(`https://oauth2.googleapis.com/tokeninfo?id_token=${encodeURIComponent(token)}`, { signal: AbortSignal.timeout(8_000) });
100
109
  if (gRes.ok) {
101
- const info = (await gRes.json());
102
- if (typeof info?.sub === 'string' && info.sub) {
103
- const id = resolveUnifiedUserId({
104
- id: info.sub,
105
- email: info.email,
106
- emailVerified: info.email_verified === true || info.email_verified === 'true',
107
- }, 'google');
110
+ const id = toGoogleUserId(await gRes.json());
111
+ if (id)
108
112
  return cacheUser(token, id);
109
- }
110
113
  }
111
114
  }
112
115
  if (!isGitHubPrefix) {
@@ -115,15 +118,9 @@ export async function verifyOAuthToken(token) {
115
118
  headers: { Authorization: `Bearer ${token}` },
116
119
  });
117
120
  if (uRes.ok) {
118
- const info = (await uRes.json());
119
- if (typeof info?.sub === 'string' && info.sub) {
120
- const id = resolveUnifiedUserId({
121
- id: info.sub,
122
- email: info.email,
123
- emailVerified: info.email_verified === true || info.email_verified === 'true',
124
- }, 'google');
121
+ const id = toGoogleUserId(await uRes.json());
122
+ if (id)
125
123
  return cacheUser(token, id);
126
- }
127
124
  }
128
125
  }
129
126
  const ghRes = await fetch('https://api.github.com/user', {
package/dist/routes.js CHANGED
@@ -1,27 +1,11 @@
1
- import fs from 'node:fs';
2
- import path from 'node:path';
3
1
  import { pathToFileURL } from 'node:url';
4
- const CANDIDATES = ['routes.mjs', 'src/routes.ts', 'routes.ts'];
2
+ import { resolveProjectFile } from './core/resolve.js';
5
3
  export function resolveRoutesFile(explicit, cwd = process.cwd()) {
6
- if (explicit) {
7
- const abs = path.resolve(cwd, explicit);
8
- if (!fs.existsSync(abs))
9
- throw new Error(`ROUTES_PATH not found: ${abs}`);
10
- return abs;
11
- }
12
- const isOwnRepo = fs.existsSync(path.resolve(cwd, 'src/cli.ts'));
13
- for (const name of CANDIDATES) {
14
- if (isOwnRepo && name === 'src/routes.ts')
15
- continue;
16
- const abs = path.resolve(cwd, name);
17
- if (fs.existsSync(abs))
18
- return abs;
19
- }
20
- return null;
4
+ return resolveProjectFile(explicit, 'ROUTES_PATH', ['routes.mjs', 'src/routes.ts', 'routes.ts'], cwd);
21
5
  }
22
6
  export async function loadRoutesFile(file) {
23
7
  const loaded = await import(pathToFileURL(file).href);
24
- const mod = loaded.default ?? loaded.routes;
8
+ const mod = loaded.default;
25
9
  if (!mod || (typeof mod !== 'object' && typeof mod !== 'function') || Array.isArray(mod)) {
26
10
  throw new Error(`${file} must export default an endpoints object or factory function.`);
27
11
  }
package/dist/rules.js CHANGED
@@ -1,6 +1,5 @@
1
- import fs from 'node:fs';
2
- import path from 'node:path';
3
1
  import { pathToFileURL } from 'node:url';
2
+ import { resolveProjectFile } from './core/resolve.js';
4
3
  function compileRule(expr) {
5
4
  if (!expr)
6
5
  return undefined;
@@ -45,27 +44,12 @@ export function normalizeRules(input) {
45
44
  export function defineRules(rules) {
46
45
  return normalizeRules(rules);
47
46
  }
48
- const CANDIDATES = ['src/rules.ts', 'rules.ts'];
49
47
  export function resolveRulesFile(explicit, cwd = process.cwd()) {
50
- if (explicit) {
51
- const abs = path.resolve(cwd, explicit);
52
- if (!fs.existsSync(abs))
53
- throw new Error(`RULES_PATH not found: ${abs}`);
54
- return abs;
55
- }
56
- const isOwnRepo = fs.existsSync(path.resolve(cwd, 'src/cli.ts'));
57
- for (const name of CANDIDATES) {
58
- if (isOwnRepo && name === 'src/rules.ts')
59
- continue;
60
- const abs = path.resolve(cwd, name);
61
- if (fs.existsSync(abs))
62
- return abs;
63
- }
64
- return null;
48
+ return resolveProjectFile(explicit, 'RULES_PATH', ['src/rules.ts', 'rules.ts'], cwd);
65
49
  }
66
50
  export async function loadRulesFile(file) {
67
51
  const loaded = await import(pathToFileURL(file).href);
68
- const mod = loaded.default ?? loaded.rules ?? loaded;
52
+ const mod = loaded.default;
69
53
  if (!mod || typeof mod !== 'object' || Array.isArray(mod)) {
70
54
  throw new Error(`${file} must export default an object of { table: { read?, write?, delete? } }.`);
71
55
  }
package/dist/schema.js CHANGED
@@ -1,7 +1,6 @@
1
- import fs from 'node:fs';
2
- import path from 'node:path';
3
1
  import { pathToFileURL } from 'node:url';
4
2
  import { buildSqlTargetSchema, generateSqlDiff, } from 'local-lite/schema/migrations';
3
+ import { resolveProjectFile } from './core/resolve.js';
5
4
  /** Identity helper for typed `schema.ts` files. */
6
5
  export function defineSchema(schema) {
7
6
  return schema;
@@ -38,29 +37,16 @@ export function normalizeSchema(input) {
38
37
  }
39
38
  return out;
40
39
  }
41
- const CANDIDATES = ['src/schema.ts', 'schema.ts'];
42
40
  export function resolveSchemaFile(explicit, cwd = process.cwd()) {
43
- if (explicit) {
44
- const abs = path.resolve(cwd, explicit);
45
- if (!fs.existsSync(abs))
46
- throw new Error(`SCHEMA_PATH not found: ${abs}`);
47
- return abs;
48
- }
49
- // Inside the local-lite-server repo itself, src/schema.ts is the package's own loader.
50
- const isOwnRepo = fs.existsSync(path.resolve(cwd, 'src/cli.ts'));
51
- for (const name of CANDIDATES) {
52
- if (isOwnRepo && name === 'src/schema.ts')
53
- continue;
54
- const abs = path.resolve(cwd, name);
55
- if (fs.existsSync(abs))
56
- return abs;
57
- }
41
+ const found = resolveProjectFile(explicit, 'SCHEMA_PATH', ['src/schema.ts', 'schema.ts'], cwd);
42
+ if (found)
43
+ return found;
58
44
  throw new Error(`No schema file found. Create src/schema.ts (or set SCHEMA_PATH):\n` +
59
45
  ` export default { notes: { id: 'string', title: 'string', body: 'string | null' } };`);
60
46
  }
61
47
  export async function loadSchemaFile(file) {
62
48
  const loaded = await import(pathToFileURL(file).href);
63
- const mod = loaded.default ?? loaded.schema;
49
+ const mod = loaded.default;
64
50
  if (!mod || typeof mod !== 'object' || Array.isArray(mod)) {
65
51
  throw new Error(`${file} must export default an object of { table: { column: type } }.`);
66
52
  }
package/dist/server.js CHANGED
@@ -76,6 +76,16 @@ export function createApp(settings, executor, schema, functions = new Map(), rul
76
76
  }
77
77
  };
78
78
  const unauthorized = () => Response.json({ error: 'Unauthorized' }, { status: 401 });
79
+ const withAdmin = (run) => async ({ request }) => {
80
+ const s = await consoleApi.authenticate(request);
81
+ return s ? run(request, s) : unauthorized();
82
+ };
83
+ const rateLimited = async (request) => {
84
+ const limit = await authLimiter(clientIp(request));
85
+ if (limit.ok)
86
+ return null;
87
+ return Response.json({ error: 'Too many requests. Please try again shortly.' }, { status: 429, headers: { 'Retry-After': String(limit.retryAfter) } });
88
+ };
79
89
  const events = createSyncEventsHandler({
80
90
  broker,
81
91
  authenticate: (req) => canSync(req, true),
@@ -105,39 +115,21 @@ export function createApp(settings, executor, schema, functions = new Map(), rul
105
115
  GET: async () => {
106
116
  try {
107
117
  await executor.query('SELECT 1');
108
- return Response.json({ ok: true, dialect: settings.dialect });
118
+ return Response.json({ ok: true, timestamp: new Date().toISOString() });
109
119
  }
110
120
  catch {
111
- return Response.json({ ok: false }, { status: 503 });
121
+ return Response.json({ ok: false, timestamp: new Date().toISOString() }, { status: 503 });
112
122
  }
113
123
  },
114
124
  },
115
125
  '/auth/google-token': {
116
- POST: async ({ request }) => {
117
- const limit = await authLimiter(clientIp(request));
118
- if (!limit.ok) {
119
- return Response.json({ error: 'Too many requests. Please try again shortly.' }, { status: 429, headers: { 'Retry-After': String(limit.retryAfter) } });
120
- }
121
- return handleOAuthTokenExchange(request);
122
- },
126
+ POST: async ({ request }) => (await rateLimited(request)) ?? handleOAuthTokenExchange(request),
123
127
  },
124
128
  '/auth/github-token': {
125
- POST: async ({ request }) => {
126
- const limit = await authLimiter(clientIp(request));
127
- if (!limit.ok) {
128
- return Response.json({ error: 'Too many requests. Please try again shortly.' }, { status: 429, headers: { 'Retry-After': String(limit.retryAfter) } });
129
- }
130
- return handleOAuthTokenExchange(request);
131
- },
129
+ POST: async ({ request }) => (await rateLimited(request)) ?? handleOAuthTokenExchange(request),
132
130
  },
133
131
  '/auth/*': {
134
- POST: async ({ request }) => {
135
- const limit = await authLimiter(clientIp(request));
136
- if (!limit.ok) {
137
- return Response.json({ error: 'Too many requests. Please try again shortly.' }, { status: 429, headers: { 'Retry-After': String(limit.retryAfter) } });
138
- }
139
- return auth.handler(request);
140
- },
132
+ POST: async ({ request }) => (await rateLimited(request)) ?? auth.handler(request),
141
133
  },
142
134
  '/sync/events': {
143
135
  GET: ({ request }) => events(request),
@@ -232,64 +224,27 @@ export function createApp(settings, executor, schema, functions = new Map(), rul
232
224
  '/admin': { GET: ({ request }) => consoleApi.serveStatic(new URL(request.url).pathname) },
233
225
  '/admin/login': {
234
226
  GET: ({ request }) => consoleApi.getLogin(request),
235
- POST: async ({ request }) => {
236
- const limit = await authLimiter(clientIp(request));
237
- if (!limit.ok) {
238
- return Response.json({ error: 'Too many requests. Please try again shortly.' }, { status: 429, headers: { 'Retry-After': String(limit.retryAfter) } });
239
- }
240
- return consoleApi.postLogin(request);
241
- },
227
+ POST: async ({ request }) => (await rateLimited(request)) ?? consoleApi.postLogin(request),
242
228
  },
243
229
  '/admin/logout': {
244
230
  POST: async ({ request }) => consoleApi.postLogout(request, await consoleApi.authenticate(request)),
245
231
  },
246
- '/admin/overview': {
247
- GET: async ({ request }) => {
248
- const s = await consoleApi.authenticate(request);
249
- return s ? consoleApi.overview(s) : unauthorized();
250
- },
251
- },
252
- '/admin/table': {
253
- ALL: async ({ request }) => (await consoleApi.authenticate(request)) ? consoleApi.handleTable(request) : unauthorized(),
254
- },
255
- '/admin/endpoints': {
256
- GET: async ({ request }) => (await consoleApi.authenticate(request)) ? consoleApi.listEndpoints() : unauthorized(),
257
- },
232
+ '/admin/overview': { GET: withAdmin((_req, s) => consoleApi.overview(s)) },
233
+ '/admin/table': { ALL: withAdmin((req) => consoleApi.handleTable(req)) },
234
+ '/admin/endpoints': { GET: withAdmin(() => consoleApi.listEndpoints()) },
258
235
  '/admin/users': {
259
- GET: async ({ request }) => (await consoleApi.authenticate(request)) ? consoleApi.listUsers() : unauthorized(),
260
- POST: async ({ request }) => (await consoleApi.authenticate(request)) ? consoleApi.manageUsers(request) : unauthorized(),
261
- },
262
- '/admin/logs': {
263
- GET: async ({ request }) => (await consoleApi.authenticate(request))
264
- ? consoleApi.handleLogs(new URL(request.url))
265
- : unauthorized(),
266
- },
267
- '/admin/env': {
268
- ALL: async ({ request }) => (await consoleApi.authenticate(request)) ? consoleApi.handleEnv(request) : unauthorized(),
269
- },
270
- '/admin/backups': {
271
- ALL: async ({ request }) => (await consoleApi.authenticate(request)) ? consoleApi.handleBackups(request) : unauthorized(),
272
- },
273
- '/admin/storage': {
274
- ALL: async ({ request }) => (await consoleApi.authenticate(request)) ? consoleApi.handleStorage(request) : unauthorized(),
275
- },
276
- '/admin/crons': {
277
- ALL: async ({ request }) => (await consoleApi.authenticate(request)) ? consoleApi.handleCrons(request) : unauthorized(),
278
- },
279
- '/admin/settings': {
280
- ALL: async ({ request }) => (await consoleApi.authenticate(request)) ? consoleApi.handleSettings(request) : unauthorized(),
236
+ GET: withAdmin(() => consoleApi.listUsers()),
237
+ POST: withAdmin((req) => consoleApi.manageUsers(req)),
281
238
  },
239
+ '/admin/logs': { GET: withAdmin((req) => consoleApi.handleLogs(new URL(req.url))) },
240
+ '/admin/env': { ALL: withAdmin((req) => consoleApi.handleEnv(req)) },
241
+ '/admin/backups': { ALL: withAdmin((req) => consoleApi.handleBackups(req)) },
242
+ '/admin/storage': { ALL: withAdmin((req) => consoleApi.handleStorage(req)) },
243
+ '/admin/crons': { ALL: withAdmin((req) => consoleApi.handleCrons(req)) },
244
+ '/admin/settings': { ALL: withAdmin((req) => consoleApi.handleSettings(req)) },
282
245
  '/admin/api-keys': {
283
- GET: async ({ request }) => {
284
- const s = await consoleApi.authenticate(request);
285
- if (!s)
286
- return unauthorized();
287
- return Response.json({ keys: await apiKeys.listKeys() });
288
- },
289
- POST: async ({ request }) => {
290
- const s = await consoleApi.authenticate(request);
291
- if (!s)
292
- return unauthorized();
246
+ GET: withAdmin(async () => Response.json({ keys: await apiKeys.listKeys() })),
247
+ POST: withAdmin(async (request, s) => {
293
248
  const body = (await request.json().catch(() => null));
294
249
  const days = Number(body?.expiresInDays ?? 0);
295
250
  const expiresAt = Number.isFinite(days) && days > 0 ? Date.now() + days * 86_400_000 : null;
@@ -306,28 +261,22 @@ export function createApp(settings, executor, schema, functions = new Map(), rul
306
261
  catch (err) {
307
262
  return Response.json({ error: err.message }, { status: 400 });
308
263
  }
309
- },
310
- PATCH: async ({ request }) => {
311
- const s = await consoleApi.authenticate(request);
312
- if (!s)
313
- return unauthorized();
264
+ }),
265
+ PATCH: withAdmin(async (request) => {
314
266
  const body = (await request.json().catch(() => null));
315
267
  if (!body?.id || body.action !== 'revoke') {
316
268
  return Response.json({ error: 'Provide id and action: "revoke".' }, { status: 400 });
317
269
  }
318
270
  const ok = await apiKeys.revokeKey(String(body.id));
319
271
  return ok ? Response.json({ ok: true }) : Response.json({ error: 'Key not found or already revoked.' }, { status: 404 });
320
- },
321
- DELETE: async ({ request }) => {
322
- const s = await consoleApi.authenticate(request);
323
- if (!s)
324
- return unauthorized();
272
+ }),
273
+ DELETE: withAdmin(async (request) => {
325
274
  const id = new URL(request.url).searchParams.get('id') ?? '';
326
275
  if (!id)
327
276
  return Response.json({ error: 'Missing id.' }, { status: 400 });
328
277
  const ok = await apiKeys.deleteKey(id);
329
278
  return ok ? Response.json({ ok: true }) : Response.json({ error: 'Key not found.' }, { status: 404 });
330
- },
279
+ }),
331
280
  },
332
281
  '/admin/*': {
333
282
  GET: ({ request }) => consoleApi.serveStatic(new URL(request.url).pathname),
package/dist/start.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { loadSettings } from './config.js';
2
- import { createDatabase } from './db.js';
2
+ import { createDatabase, pgClientConfig } from './db.js';
3
3
  import { runMigrations } from './migrations.js';
4
4
  import { applySchema, loadSchemaFile, planSchema, resolveSchemaFile } from './schema.js';
5
5
  import { loadRulesFile, resolveRulesFile } from './rules.js';
@@ -12,14 +12,7 @@ async function tryCreateDatabase(s) {
12
12
  try {
13
13
  if (s.dialect === 'postgres') {
14
14
  const pg = (await import('pg')).default;
15
- const client = new pg.Client({
16
- host: s.db.host,
17
- port: s.db.port,
18
- user: s.db.user,
19
- password: s.db.password,
20
- database: 'postgres',
21
- ssl: s.db.ssl ? { rejectUnauthorized: false } : undefined,
22
- });
15
+ const client = new pg.Client(pgClientConfig(s, 'postgres'));
23
16
  await client.connect();
24
17
  try {
25
18
  await client.query(`CREATE DATABASE "${s.db.database.replace(/"/g, '')}"`);
@@ -149,12 +149,7 @@ export class TableSyncStorage {
149
149
  throw new ForbiddenError(`Write denied on ${op.tableName}/${op.rowId}.`);
150
150
  }
151
151
  }
152
- else if (op.operation === 'DELETE') {
153
- if (!(await writeRule(auth, { id: op.rowId, ...payload }))) {
154
- throw new ForbiddenError(`Delete denied on ${op.tableName}/${op.rowId}.`);
155
- }
156
- }
157
- if (op.operation !== 'DELETE') {
152
+ if (!existing || op.operation !== 'DELETE') {
158
153
  if (!(await writeRule(auth, { id: op.rowId, ...payload }))) {
159
154
  throw new ForbiddenError(`Write denied on ${op.tableName}/${op.rowId}.`);
160
155
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "local-lite-server",
3
- "version": "0.1.1",
3
+ "version": "0.1.2",
4
4
  "description": "Self-hostable local-lite sync server for MySQL or Postgres. Runs on cPanel Node.js apps or any VPS, no Docker.",
5
5
  "license": "MIT",
6
6
  "type": "module",