local-lite-server 0.1.0 → 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.
Files changed (54) hide show
  1. package/admin/dist/assets/{index-DMJ7Ri2R.js → index-6REgGhGR.js} +4 -4
  2. package/admin/dist/index.html +1 -1
  3. package/dist/admin/console.d.ts +19 -0
  4. package/dist/admin/index.d.ts +28 -0
  5. package/dist/admin/ops.d.ts +11 -0
  6. package/dist/admin/session.d.ts +14 -0
  7. package/dist/admin/session.js +2 -1
  8. package/dist/apiKeys.d.ts +36 -0
  9. package/dist/app.d.ts +1 -0
  10. package/dist/app.js +5 -1
  11. package/dist/auth.d.ts +16 -0
  12. package/dist/cli.d.ts +2 -0
  13. package/dist/codegen.d.ts +4 -0
  14. package/dist/config.d.ts +39 -0
  15. package/dist/core/broker.d.ts +12 -0
  16. package/dist/core/broker.js +2 -8
  17. package/dist/core/changes.d.ts +17 -0
  18. package/dist/core/changes.js +1 -5
  19. package/dist/core/http.d.ts +8 -0
  20. package/dist/core/http.js +1 -1
  21. package/dist/core/mailer.d.ts +3 -0
  22. package/dist/core/resolve.d.ts +2 -0
  23. package/dist/core/resolve.js +20 -0
  24. package/dist/cpanel.d.ts +1 -0
  25. package/dist/cpanel.js +24 -6
  26. package/dist/crons.d.ts +24 -0
  27. package/dist/db.d.ts +17 -0
  28. package/dist/db.js +12 -6
  29. package/dist/functions/index.d.ts +3 -0
  30. package/dist/functions/loader.d.ts +4 -0
  31. package/dist/functions/runtime.d.ts +21 -0
  32. package/dist/functions/types.d.ts +59 -0
  33. package/dist/index.d.ts +12 -0
  34. package/dist/index.js +1 -0
  35. package/dist/migrations.d.ts +16 -0
  36. package/dist/migrations.js +13 -0
  37. package/dist/oauth.d.ts +7 -0
  38. package/dist/oauth.js +149 -0
  39. package/dist/rateLimit.d.ts +12 -0
  40. package/dist/routes.d.ts +15 -0
  41. package/dist/routes.js +13 -0
  42. package/dist/rules.d.ts +23 -0
  43. package/dist/rules.js +3 -19
  44. package/dist/schema.d.ts +18 -0
  45. package/dist/schema.js +5 -19
  46. package/dist/server.d.ts +13 -0
  47. package/dist/server.js +47 -72
  48. package/dist/start.d.ts +8 -0
  49. package/dist/start.js +13 -13
  50. package/dist/storage.d.ts +4 -0
  51. package/dist/tableStorage.d.ts +63 -0
  52. package/dist/tableStorage.js +1 -6
  53. package/package.json +1 -1
  54. package/templates/.env.example +33 -0
package/dist/oauth.js ADDED
@@ -0,0 +1,149 @@
1
+ import { resolveUnifiedUserId } from 'local-lite/auth';
2
+ const CACHE_TTL_MS = 5 * 60 * 1000;
3
+ const tokenCache = new Map();
4
+ function parseBodyParams(rawText) {
5
+ if (rawText.trim().startsWith('{')) {
6
+ try {
7
+ const parsed = JSON.parse(rawText);
8
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed))
9
+ return null;
10
+ const out = {};
11
+ for (const [k, v] of Object.entries(parsed)) {
12
+ if (v != null)
13
+ out[k] = String(v);
14
+ }
15
+ return out;
16
+ }
17
+ catch {
18
+ return null;
19
+ }
20
+ }
21
+ return Object.fromEntries(new URLSearchParams(rawText).entries());
22
+ }
23
+ /** Handles `POST /auth/google-token` and `POST /auth/github-token` code exchanges. */
24
+ export async function handleOAuthTokenExchange(request) {
25
+ const url = new URL(request.url);
26
+ const rawText = await request.text().catch(() => '');
27
+ const params = parseBodyParams(rawText);
28
+ if (!params) {
29
+ return Response.json({ error: 'Invalid JSON payload' }, { status: 400 });
30
+ }
31
+ if (url.pathname.endsWith('/google-token')) {
32
+ const clientSecret = process.env.GOOGLE_CLIENT_SECRET?.trim();
33
+ if (!clientSecret) {
34
+ return Response.json({ error: 'Google OAuth client secret is not configured on the server' }, { status: 503 });
35
+ }
36
+ if (params.grant_type !== 'authorization_code' && params.grant_type !== 'refresh_token') {
37
+ return Response.json({ error: 'Unsupported grant_type. Expected authorization_code or refresh_token.' }, { status: 400 });
38
+ }
39
+ const forwarded = new URLSearchParams();
40
+ for (const f of ['grant_type', 'client_id', 'code', 'code_verifier', 'redirect_uri', 'refresh_token']) {
41
+ if (params[f])
42
+ forwarded.set(f, params[f]);
43
+ }
44
+ forwarded.set('client_secret', clientSecret);
45
+ const gRes = await fetch('https://oauth2.googleapis.com/token', {
46
+ method: 'POST',
47
+ signal: AbortSignal.timeout(10_000),
48
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
49
+ body: forwarded.toString(),
50
+ });
51
+ return new Response(await gRes.text(), {
52
+ status: gRes.status,
53
+ headers: { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' },
54
+ });
55
+ }
56
+ if (url.pathname.endsWith('/github-token')) {
57
+ const clientSecret = process.env.GITHUB_CLIENT_SECRET?.trim();
58
+ if (!clientSecret) {
59
+ return Response.json({ error: 'GITHUB_CLIENT_SECRET is not configured on server' }, { status: 503 });
60
+ }
61
+ const { client_id, code, redirect_uri, state } = params;
62
+ if (!code || !client_id) {
63
+ return Response.json({ error: 'client_id and code are required' }, { status: 400 });
64
+ }
65
+ const forwarded = new URLSearchParams({ client_id, client_secret: clientSecret, code });
66
+ if (redirect_uri)
67
+ forwarded.set('redirect_uri', redirect_uri);
68
+ if (state)
69
+ forwarded.set('state', state);
70
+ const ghRes = await fetch('https://github.com/login/oauth/access_token', {
71
+ method: 'POST',
72
+ signal: AbortSignal.timeout(10_000),
73
+ headers: { Accept: 'application/json', 'Content-Type': 'application/x-www-form-urlencoded' },
74
+ body: forwarded.toString(),
75
+ });
76
+ return new Response(await ghRes.text(), {
77
+ status: ghRes.status,
78
+ headers: { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' },
79
+ });
80
+ }
81
+ return Response.json({ error: 'Endpoint not found' }, { status: 404 });
82
+ }
83
+ function cacheUser(token, userId) {
84
+ if (tokenCache.size > 2000)
85
+ tokenCache.clear();
86
+ tokenCache.set(token, { userId, expiresAt: Date.now() + CACHE_TTL_MS });
87
+ return { id: userId };
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
+ }
98
+ /** Verifies a Google (ID/access) or GitHub OAuth token and maps it to a unified userId. */
99
+ export async function verifyOAuthToken(token) {
100
+ if (!token || token.length < 16)
101
+ return null;
102
+ const cached = tokenCache.get(token);
103
+ if (cached && cached.expiresAt > Date.now())
104
+ return { id: cached.userId };
105
+ try {
106
+ const isGitHubPrefix = token.startsWith('gho_') || token.startsWith('ghu_') || token.startsWith('ghp_');
107
+ if (!isGitHubPrefix && token.split('.').length === 3) {
108
+ const gRes = await fetch(`https://oauth2.googleapis.com/tokeninfo?id_token=${encodeURIComponent(token)}`, { signal: AbortSignal.timeout(8_000) });
109
+ if (gRes.ok) {
110
+ const id = toGoogleUserId(await gRes.json());
111
+ if (id)
112
+ return cacheUser(token, id);
113
+ }
114
+ }
115
+ if (!isGitHubPrefix) {
116
+ const uRes = await fetch('https://www.googleapis.com/oauth2/v3/userinfo', {
117
+ signal: AbortSignal.timeout(8_000),
118
+ headers: { Authorization: `Bearer ${token}` },
119
+ });
120
+ if (uRes.ok) {
121
+ const id = toGoogleUserId(await uRes.json());
122
+ if (id)
123
+ return cacheUser(token, id);
124
+ }
125
+ }
126
+ const ghRes = await fetch('https://api.github.com/user', {
127
+ signal: AbortSignal.timeout(8_000),
128
+ headers: {
129
+ Authorization: `Bearer ${token}`,
130
+ Accept: 'application/vnd.github+json',
131
+ 'User-Agent': 'local-lite-server',
132
+ },
133
+ });
134
+ if (ghRes.ok) {
135
+ const info = (await ghRes.json());
136
+ if (info?.id != null) {
137
+ const id = resolveUnifiedUserId({ id: String(info.id), email: info.email ?? undefined, emailVerified: Boolean(info.email) }, 'github');
138
+ return cacheUser(token, id);
139
+ }
140
+ }
141
+ }
142
+ catch {
143
+ // Ignore transient upstream OAuth errors
144
+ }
145
+ return null;
146
+ }
147
+ export function clearOAuthCacheForTests() {
148
+ tokenCache.clear();
149
+ }
@@ -0,0 +1,12 @@
1
+ import type { SqlExecutor } from 'local-lite/server';
2
+ export type RateLimitResult = {
3
+ ok: true;
4
+ } | {
5
+ ok: false;
6
+ retryAfter: number;
7
+ };
8
+ /** Fixed-window in-memory limiter, keyed per client IP. */
9
+ export declare function createRateLimiter(max: number, windowMs: number): (key: string, now?: number) => RateLimitResult;
10
+ /** DB-backed limiter for multi-instance deployments, with in-memory fallback. */
11
+ export declare function createDistributedRateLimiter(db: SqlExecutor, max: number, windowMs: number, enabled?: boolean): (key: string, now?: number) => Promise<RateLimitResult>;
12
+ export declare function clientIp(request: Request): string;
@@ -0,0 +1,15 @@
1
+ import type { SqlExecutor, SyncEventBroker } from 'local-lite/server';
2
+ import type { ServerSettings } from './config.js';
3
+ import type { FunctionAuth } from './functions/index.js';
4
+ import type { SchemaDictionary } from './schema.js';
5
+ export interface CustomRoutesContext {
6
+ db: SqlExecutor;
7
+ settings: ServerSettings;
8
+ schema: SchemaDictionary;
9
+ broker: SyncEventBroker;
10
+ resolveAuth: (request: Request, allowQuery?: boolean) => Promise<FunctionAuth | null>;
11
+ }
12
+ export type CustomRoutesMap = Record<string, Record<string, (ctx: any) => Promise<Response> | Response>>;
13
+ export type CustomRoutesFactory = (ctx: CustomRoutesContext) => CustomRoutesMap;
14
+ export declare function resolveRoutesFile(explicit?: string, cwd?: string): string | null;
15
+ export declare function loadRoutesFile(file: string): Promise<CustomRoutesMap | CustomRoutesFactory>;
package/dist/routes.js ADDED
@@ -0,0 +1,13 @@
1
+ import { pathToFileURL } from 'node:url';
2
+ import { resolveProjectFile } from './core/resolve.js';
3
+ export function resolveRoutesFile(explicit, cwd = process.cwd()) {
4
+ return resolveProjectFile(explicit, 'ROUTES_PATH', ['routes.mjs', 'src/routes.ts', 'routes.ts'], cwd);
5
+ }
6
+ export async function loadRoutesFile(file) {
7
+ const loaded = await import(pathToFileURL(file).href);
8
+ const mod = loaded.default;
9
+ if (!mod || (typeof mod !== 'object' && typeof mod !== 'function') || Array.isArray(mod)) {
10
+ throw new Error(`${file} must export default an endpoints object or factory function.`);
11
+ }
12
+ return mod;
13
+ }
@@ -0,0 +1,23 @@
1
+ export interface RuleContext {
2
+ isAdmin: boolean;
3
+ userId?: string;
4
+ }
5
+ export type RowPredicate = (ctx: RuleContext, row: Record<string, any>) => boolean | Promise<boolean>;
6
+ export type RulePreset = 'authenticated' | 'owner' | `owner:${string}` | 'admin' | 'none';
7
+ export type RuleExpression = RowPredicate | RulePreset;
8
+ export interface TableRuleInput {
9
+ read?: RuleExpression;
10
+ write?: RuleExpression;
11
+ delete?: RuleExpression;
12
+ }
13
+ export interface TableRule {
14
+ read?: RowPredicate;
15
+ write?: RowPredicate;
16
+ delete?: RowPredicate;
17
+ }
18
+ export type RulesInputDictionary = Record<string, TableRuleInput | RulePreset>;
19
+ export type RulesDictionary = Record<string, TableRule>;
20
+ export declare function normalizeRules(input: RulesInputDictionary): RulesDictionary;
21
+ export declare function defineRules(rules: RulesInputDictionary): RulesDictionary;
22
+ export declare function resolveRulesFile(explicit?: string, cwd?: string): string | null;
23
+ export declare function loadRulesFile(file: string): Promise<RulesDictionary>;
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
  }
@@ -0,0 +1,18 @@
1
+ import type { SqlExecutor } from 'local-lite/server';
2
+ import { type SchemaDictionary, type SchemaFieldType, type SqlSchemaState } from 'local-lite/schema/migrations';
3
+ export type { SchemaDictionary, SchemaFieldType };
4
+ /** Identity helper for typed `schema.ts` files. */
5
+ export declare function defineSchema<T extends SchemaDictionary>(schema: T): T;
6
+ /** Validates names, field types, and guarantees an `id` column on every table. */
7
+ export declare function normalizeSchema(input: SchemaDictionary): SchemaDictionary;
8
+ export declare function resolveSchemaFile(explicit?: string, cwd?: string): string;
9
+ export declare function loadSchemaFile(file: string): Promise<SchemaDictionary>;
10
+ export interface SchemaPlan {
11
+ up: string[];
12
+ warnings: string[];
13
+ next: SqlSchemaState;
14
+ first: boolean;
15
+ }
16
+ export declare function planSchema(db: SqlExecutor, dictionary: SchemaDictionary): Promise<SchemaPlan>;
17
+ /** Applies the schema diff and records the new state. Safe to call on every boot. */
18
+ export declare function applySchema(db: SqlExecutor, dictionary: SchemaDictionary): Promise<SchemaPlan>;
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
  }
@@ -0,0 +1,13 @@
1
+ import { type SqlExecutor, type SyncEventBroker } from 'local-lite/server';
2
+ import type { ServerSettings } from './config.js';
3
+ import type { SchemaDictionary } from './schema.js';
4
+ import type { RulesDictionary } from './rules.js';
5
+ import { createHttpServer } from './core/http.js';
6
+ import type { CustomRoutesFactory, CustomRoutesMap } from './routes.js';
7
+ import { type FunctionRegistry } from './functions/index.js';
8
+ export { createHttpServer };
9
+ export declare function createApp(settings: ServerSettings, executor: SqlExecutor, schema: SchemaDictionary, functions?: FunctionRegistry, rules?: RulesDictionary, brokerOverride?: SyncEventBroker, customRoutesInput?: CustomRoutesMap | CustomRoutesFactory): {
10
+ fetch: (req: Request) => Promise<Response>;
11
+ broker: SyncEventBroker;
12
+ fnRuntime: import("./functions/runtime.js").FunctionRuntime;
13
+ };
package/dist/server.js CHANGED
@@ -2,13 +2,14 @@ import { createServer, createSyncEventBroker, createSyncEventsHandler, } from 'l
2
2
  import { ClientError, ForbiddenError, TableSyncStorage } from './tableStorage.js';
3
3
  import { createAuthService } from './auth.js';
4
4
  import { createApiKeyService } from './apiKeys.js';
5
+ import { handleOAuthTokenExchange, verifyOAuthToken } from './oauth.js';
5
6
  import { createAdminConsole } from './admin/index.js';
6
7
  import { createStorageHandler } from './storage.js';
7
8
  import { corsHeaders, createHttpServer, safeEqual } from './core/http.js';
8
9
  import { clientIp, createDistributedRateLimiter } from './rateLimit.js';
9
10
  import { createFunctionRuntime, FunctionError, } from './functions/index.js';
10
11
  export { createHttpServer };
11
- export function createApp(settings, executor, schema, functions = new Map(), rules = {}, brokerOverride) {
12
+ export function createApp(settings, executor, schema, functions = new Map(), rules = {}, brokerOverride, customRoutesInput) {
12
13
  const broker = brokerOverride ?? createSyncEventBroker();
13
14
  const storage = new TableSyncStorage(executor, { schema, rules, broker });
14
15
  const auth = createAuthService(settings, executor);
@@ -39,6 +40,9 @@ export function createApp(settings, executor, schema, functions = new Map(), rul
39
40
  const user = await auth.verifyUser(token);
40
41
  if (user)
41
42
  return { isAdmin: false, userId: user.id };
43
+ const oauthUser = await verifyOAuthToken(token);
44
+ if (oauthUser)
45
+ return { isAdmin: false, userId: oauthUser.id };
42
46
  }
43
47
  if (settings.adminUi) {
44
48
  const adminSession = await consoleApi.authenticate(request);
@@ -72,10 +76,23 @@ export function createApp(settings, executor, schema, functions = new Map(), rul
72
76
  }
73
77
  };
74
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
+ };
75
89
  const events = createSyncEventsHandler({
76
90
  broker,
77
91
  authenticate: (req) => canSync(req, true),
78
92
  });
93
+ const customRoutes = typeof customRoutesInput === 'function'
94
+ ? customRoutesInput({ db: executor, settings, schema, broker, resolveAuth })
95
+ : (customRoutesInput ?? {});
79
96
  const api = createServer({
80
97
  config: {},
81
98
  middleware: [
@@ -93,25 +110,26 @@ export function createApp(settings, executor, schema, functions = new Map(), rul
93
110
  ],
94
111
  onError: (error) => console.error('[local-lite-server]', error),
95
112
  endpoints: {
113
+ ...customRoutes,
96
114
  '/health': {
97
115
  GET: async () => {
98
116
  try {
99
117
  await executor.query('SELECT 1');
100
- return Response.json({ ok: true, dialect: settings.dialect });
118
+ return Response.json({ ok: true, timestamp: new Date().toISOString() });
101
119
  }
102
120
  catch {
103
- return Response.json({ ok: false }, { status: 503 });
121
+ return Response.json({ ok: false, timestamp: new Date().toISOString() }, { status: 503 });
104
122
  }
105
123
  },
106
124
  },
125
+ '/auth/google-token': {
126
+ POST: async ({ request }) => (await rateLimited(request)) ?? handleOAuthTokenExchange(request),
127
+ },
128
+ '/auth/github-token': {
129
+ POST: async ({ request }) => (await rateLimited(request)) ?? handleOAuthTokenExchange(request),
130
+ },
107
131
  '/auth/*': {
108
- POST: async ({ request }) => {
109
- const limit = await authLimiter(clientIp(request));
110
- if (!limit.ok) {
111
- return Response.json({ error: 'Too many requests. Please try again shortly.' }, { status: 429, headers: { 'Retry-After': String(limit.retryAfter) } });
112
- }
113
- return auth.handler(request);
114
- },
132
+ POST: async ({ request }) => (await rateLimited(request)) ?? auth.handler(request),
115
133
  },
116
134
  '/sync/events': {
117
135
  GET: ({ request }) => events(request),
@@ -206,64 +224,27 @@ export function createApp(settings, executor, schema, functions = new Map(), rul
206
224
  '/admin': { GET: ({ request }) => consoleApi.serveStatic(new URL(request.url).pathname) },
207
225
  '/admin/login': {
208
226
  GET: ({ request }) => consoleApi.getLogin(request),
209
- POST: async ({ request }) => {
210
- const limit = await authLimiter(clientIp(request));
211
- if (!limit.ok) {
212
- return Response.json({ error: 'Too many requests. Please try again shortly.' }, { status: 429, headers: { 'Retry-After': String(limit.retryAfter) } });
213
- }
214
- return consoleApi.postLogin(request);
215
- },
227
+ POST: async ({ request }) => (await rateLimited(request)) ?? consoleApi.postLogin(request),
216
228
  },
217
229
  '/admin/logout': {
218
230
  POST: async ({ request }) => consoleApi.postLogout(request, await consoleApi.authenticate(request)),
219
231
  },
220
- '/admin/overview': {
221
- GET: async ({ request }) => {
222
- const s = await consoleApi.authenticate(request);
223
- return s ? consoleApi.overview(s) : unauthorized();
224
- },
225
- },
226
- '/admin/table': {
227
- ALL: async ({ request }) => (await consoleApi.authenticate(request)) ? consoleApi.handleTable(request) : unauthorized(),
228
- },
229
- '/admin/endpoints': {
230
- GET: async ({ request }) => (await consoleApi.authenticate(request)) ? consoleApi.listEndpoints() : unauthorized(),
231
- },
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()) },
232
235
  '/admin/users': {
233
- GET: async ({ request }) => (await consoleApi.authenticate(request)) ? consoleApi.listUsers() : unauthorized(),
234
- POST: async ({ request }) => (await consoleApi.authenticate(request)) ? consoleApi.manageUsers(request) : unauthorized(),
235
- },
236
- '/admin/logs': {
237
- GET: async ({ request }) => (await consoleApi.authenticate(request))
238
- ? consoleApi.handleLogs(new URL(request.url))
239
- : unauthorized(),
240
- },
241
- '/admin/env': {
242
- ALL: async ({ request }) => (await consoleApi.authenticate(request)) ? consoleApi.handleEnv(request) : unauthorized(),
243
- },
244
- '/admin/backups': {
245
- ALL: async ({ request }) => (await consoleApi.authenticate(request)) ? consoleApi.handleBackups(request) : unauthorized(),
246
- },
247
- '/admin/storage': {
248
- ALL: async ({ request }) => (await consoleApi.authenticate(request)) ? consoleApi.handleStorage(request) : unauthorized(),
249
- },
250
- '/admin/crons': {
251
- ALL: async ({ request }) => (await consoleApi.authenticate(request)) ? consoleApi.handleCrons(request) : unauthorized(),
252
- },
253
- '/admin/settings': {
254
- ALL: async ({ request }) => (await consoleApi.authenticate(request)) ? consoleApi.handleSettings(request) : unauthorized(),
236
+ GET: withAdmin(() => consoleApi.listUsers()),
237
+ POST: withAdmin((req) => consoleApi.manageUsers(req)),
255
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)) },
256
245
  '/admin/api-keys': {
257
- GET: async ({ request }) => {
258
- const s = await consoleApi.authenticate(request);
259
- if (!s)
260
- return unauthorized();
261
- return Response.json({ keys: await apiKeys.listKeys() });
262
- },
263
- POST: async ({ request }) => {
264
- const s = await consoleApi.authenticate(request);
265
- if (!s)
266
- return unauthorized();
246
+ GET: withAdmin(async () => Response.json({ keys: await apiKeys.listKeys() })),
247
+ POST: withAdmin(async (request, s) => {
267
248
  const body = (await request.json().catch(() => null));
268
249
  const days = Number(body?.expiresInDays ?? 0);
269
250
  const expiresAt = Number.isFinite(days) && days > 0 ? Date.now() + days * 86_400_000 : null;
@@ -280,28 +261,22 @@ export function createApp(settings, executor, schema, functions = new Map(), rul
280
261
  catch (err) {
281
262
  return Response.json({ error: err.message }, { status: 400 });
282
263
  }
283
- },
284
- PATCH: async ({ request }) => {
285
- const s = await consoleApi.authenticate(request);
286
- if (!s)
287
- return unauthorized();
264
+ }),
265
+ PATCH: withAdmin(async (request) => {
288
266
  const body = (await request.json().catch(() => null));
289
267
  if (!body?.id || body.action !== 'revoke') {
290
268
  return Response.json({ error: 'Provide id and action: "revoke".' }, { status: 400 });
291
269
  }
292
270
  const ok = await apiKeys.revokeKey(String(body.id));
293
271
  return ok ? Response.json({ ok: true }) : Response.json({ error: 'Key not found or already revoked.' }, { status: 404 });
294
- },
295
- DELETE: async ({ request }) => {
296
- const s = await consoleApi.authenticate(request);
297
- if (!s)
298
- return unauthorized();
272
+ }),
273
+ DELETE: withAdmin(async (request) => {
299
274
  const id = new URL(request.url).searchParams.get('id') ?? '';
300
275
  if (!id)
301
276
  return Response.json({ error: 'Missing id.' }, { status: 400 });
302
277
  const ok = await apiKeys.deleteKey(id);
303
278
  return ok ? Response.json({ ok: true }) : Response.json({ error: 'Key not found.' }, { status: 404 });
304
- },
279
+ }),
305
280
  },
306
281
  '/admin/*': {
307
282
  GET: ({ request }) => consoleApi.serveStatic(new URL(request.url).pathname),
@@ -0,0 +1,8 @@
1
+ import { type ServerSettings } from './config.js';
2
+ import { type Database } from './db.js';
3
+ import type { SchemaDictionary } from './schema.js';
4
+ export declare function loadSchema(s: ServerSettings): Promise<SchemaDictionary>;
5
+ /** Core + schema migrations. Returns a human-readable log. */
6
+ export declare function migrate(s: ServerSettings, db: Database, schema: SchemaDictionary): Promise<void>;
7
+ /** Shared boot used by the CLI and the cPanel entry point. */
8
+ export declare function start(): Promise<import("node:http").Server<typeof import("node:http").IncomingMessage, typeof import("node:http").ServerResponse>>;
package/dist/start.js CHANGED
@@ -1,8 +1,9 @@
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';
6
+ import { loadRoutesFile, resolveRoutesFile } from './routes.js';
6
7
  import { loadFunctionsDir, watchFunctionsDir } from './functions/index.js';
7
8
  import { createClusterBroker } from './core/broker.js';
8
9
  import { startCronScheduler } from './crons.js';
@@ -11,14 +12,7 @@ async function tryCreateDatabase(s) {
11
12
  try {
12
13
  if (s.dialect === 'postgres') {
13
14
  const pg = (await import('pg')).default;
14
- const client = new pg.Client({
15
- host: s.db.host,
16
- port: s.db.port,
17
- user: s.db.user,
18
- password: s.db.password,
19
- database: 'postgres',
20
- ssl: s.db.ssl ? { rejectUnauthorized: false } : undefined,
21
- });
15
+ const client = new pg.Client(pgClientConfig(s, 'postgres'));
22
16
  await client.connect();
23
17
  try {
24
18
  await client.query(`CREATE DATABASE "${s.db.database.replace(/"/g, '')}"`);
@@ -96,6 +90,8 @@ export async function start() {
96
90
  console.warn('[local-lite-server] APP_SECRET is set without src/rules.ts; authenticated users can sync all tables.');
97
91
  }
98
92
  const functions = await loadFunctionsDir(settings.functionsDir);
93
+ const routesFile = resolveRoutesFile();
94
+ const customRoutes = routesFile ? await loadRoutesFile(routesFile) : undefined;
99
95
  const database = await createDatabase(settings);
100
96
  try {
101
97
  if (settings.autoMigrate) {
@@ -113,17 +109,21 @@ export async function start() {
113
109
  throw friendlyDbError(err, settings);
114
110
  }
115
111
  const broker = await createClusterBroker(settings, database.executor);
116
- const app = createApp(settings, database.executor, schema, functions, rules, broker);
112
+ const app = createApp(settings, database.executor, schema, functions, rules, broker, customRoutes);
117
113
  const server = createHttpServer(app);
114
+ const host = process.env.SERVER_HOST || '127.0.0.1';
118
115
  let activePort = settings.port;
119
116
  let attempts = 0;
117
+ const listen = (onListening) => typeof activePort === 'number'
118
+ ? server.listen(activePort, host, onListening)
119
+ : server.listen(activePort, onListening);
120
120
  server.on('error', (err) => {
121
121
  if (err.code === 'EADDRINUSE' && typeof activePort === 'number' && !process.env.PORT && attempts < 20) {
122
122
  const nextPort = activePort + 1;
123
123
  console.warn(`[local-lite-server] port ${activePort} is in use, trying ${nextPort}...`);
124
124
  activePort = nextPort;
125
125
  attempts += 1;
126
- server.listen(activePort);
126
+ listen();
127
127
  return;
128
128
  }
129
129
  if (err.code === 'EADDRINUSE') {
@@ -134,8 +134,8 @@ export async function start() {
134
134
  }
135
135
  void database.close().finally(() => process.exit(1));
136
136
  });
137
- server.listen(activePort, () => {
138
- const addr = typeof activePort === 'number' ? `http://localhost:${activePort}` : activePort;
137
+ listen(() => {
138
+ const addr = typeof activePort === 'number' ? `http://${host === '0.0.0.0' ? '127.0.0.1' : host}:${activePort}` : activePort;
139
139
  console.log(`[local-lite-server] listening on ${addr} (${settings.dialect})`);
140
140
  if (settings.adminUi && typeof activePort === 'number') {
141
141
  console.log(`[local-lite-server] admin console: ${addr}/admin`);
@@ -0,0 +1,4 @@
1
+ import { type SqlExecutor, type StorageAuthContext, type StorageMetadataAdapter } from 'local-lite/server';
2
+ import type { ServerSettings } from './config.js';
3
+ export declare function createSqlStorageMetadata(db: SqlExecutor): StorageMetadataAdapter;
4
+ export declare function createStorageHandler(settings: ServerSettings, db: SqlExecutor, authenticate: (req: Request) => Promise<StorageAuthContext | null>): (request: Request) => Promise<Response>;