local-lite-server 0.1.0 → 0.1.1

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 (44) hide show
  1. package/admin/dist/assets/{index-DMJ7Ri2R.js → index-B2nX9Pef.js} +3 -3
  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/apiKeys.d.ts +36 -0
  8. package/dist/app.d.ts +1 -0
  9. package/dist/app.js +5 -1
  10. package/dist/auth.d.ts +16 -0
  11. package/dist/cli.d.ts +2 -0
  12. package/dist/codegen.d.ts +4 -0
  13. package/dist/config.d.ts +39 -0
  14. package/dist/core/broker.d.ts +12 -0
  15. package/dist/core/changes.d.ts +17 -0
  16. package/dist/core/http.d.ts +8 -0
  17. package/dist/core/http.js +1 -1
  18. package/dist/core/mailer.d.ts +3 -0
  19. package/dist/cpanel.d.ts +1 -0
  20. package/dist/cpanel.js +24 -6
  21. package/dist/crons.d.ts +24 -0
  22. package/dist/db.d.ts +7 -0
  23. package/dist/functions/index.d.ts +3 -0
  24. package/dist/functions/loader.d.ts +4 -0
  25. package/dist/functions/runtime.d.ts +21 -0
  26. package/dist/functions/types.d.ts +59 -0
  27. package/dist/index.d.ts +12 -0
  28. package/dist/index.js +1 -0
  29. package/dist/migrations.d.ts +16 -0
  30. package/dist/oauth.d.ts +7 -0
  31. package/dist/oauth.js +152 -0
  32. package/dist/rateLimit.d.ts +12 -0
  33. package/dist/routes.d.ts +15 -0
  34. package/dist/routes.js +29 -0
  35. package/dist/rules.d.ts +23 -0
  36. package/dist/schema.d.ts +18 -0
  37. package/dist/server.d.ts +13 -0
  38. package/dist/server.js +27 -1
  39. package/dist/start.d.ts +8 -0
  40. package/dist/start.js +11 -4
  41. package/dist/storage.d.ts +4 -0
  42. package/dist/tableStorage.d.ts +63 -0
  43. package/package.json +1 -1
  44. package/templates/.env.example +33 -0
@@ -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,29 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { pathToFileURL } from 'node:url';
4
+ const CANDIDATES = ['routes.mjs', 'src/routes.ts', 'routes.ts'];
5
+ 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;
21
+ }
22
+ export async function loadRoutesFile(file) {
23
+ const loaded = await import(pathToFileURL(file).href);
24
+ const mod = loaded.default ?? loaded.routes;
25
+ if (!mod || (typeof mod !== 'object' && typeof mod !== 'function') || Array.isArray(mod)) {
26
+ throw new Error(`${file} must export default an endpoints object or factory function.`);
27
+ }
28
+ return mod;
29
+ }
@@ -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>;
@@ -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>;
@@ -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);
@@ -76,6 +80,9 @@ export function createApp(settings, executor, schema, functions = new Map(), rul
76
80
  broker,
77
81
  authenticate: (req) => canSync(req, true),
78
82
  });
83
+ const customRoutes = typeof customRoutesInput === 'function'
84
+ ? customRoutesInput({ db: executor, settings, schema, broker, resolveAuth })
85
+ : (customRoutesInput ?? {});
79
86
  const api = createServer({
80
87
  config: {},
81
88
  middleware: [
@@ -93,6 +100,7 @@ export function createApp(settings, executor, schema, functions = new Map(), rul
93
100
  ],
94
101
  onError: (error) => console.error('[local-lite-server]', error),
95
102
  endpoints: {
103
+ ...customRoutes,
96
104
  '/health': {
97
105
  GET: async () => {
98
106
  try {
@@ -104,6 +112,24 @@ export function createApp(settings, executor, schema, functions = new Map(), rul
104
112
  }
105
113
  },
106
114
  },
115
+ '/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
+ },
123
+ },
124
+ '/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
+ },
132
+ },
107
133
  '/auth/*': {
108
134
  POST: async ({ request }) => {
109
135
  const limit = await authLimiter(clientIp(request));
@@ -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
@@ -3,6 +3,7 @@ import { createDatabase } 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';
@@ -96,6 +97,8 @@ export async function start() {
96
97
  console.warn('[local-lite-server] APP_SECRET is set without src/rules.ts; authenticated users can sync all tables.');
97
98
  }
98
99
  const functions = await loadFunctionsDir(settings.functionsDir);
100
+ const routesFile = resolveRoutesFile();
101
+ const customRoutes = routesFile ? await loadRoutesFile(routesFile) : undefined;
99
102
  const database = await createDatabase(settings);
100
103
  try {
101
104
  if (settings.autoMigrate) {
@@ -113,17 +116,21 @@ export async function start() {
113
116
  throw friendlyDbError(err, settings);
114
117
  }
115
118
  const broker = await createClusterBroker(settings, database.executor);
116
- const app = createApp(settings, database.executor, schema, functions, rules, broker);
119
+ const app = createApp(settings, database.executor, schema, functions, rules, broker, customRoutes);
117
120
  const server = createHttpServer(app);
121
+ const host = process.env.SERVER_HOST || '127.0.0.1';
118
122
  let activePort = settings.port;
119
123
  let attempts = 0;
124
+ const listen = (onListening) => typeof activePort === 'number'
125
+ ? server.listen(activePort, host, onListening)
126
+ : server.listen(activePort, onListening);
120
127
  server.on('error', (err) => {
121
128
  if (err.code === 'EADDRINUSE' && typeof activePort === 'number' && !process.env.PORT && attempts < 20) {
122
129
  const nextPort = activePort + 1;
123
130
  console.warn(`[local-lite-server] port ${activePort} is in use, trying ${nextPort}...`);
124
131
  activePort = nextPort;
125
132
  attempts += 1;
126
- server.listen(activePort);
133
+ listen();
127
134
  return;
128
135
  }
129
136
  if (err.code === 'EADDRINUSE') {
@@ -134,8 +141,8 @@ export async function start() {
134
141
  }
135
142
  void database.close().finally(() => process.exit(1));
136
143
  });
137
- server.listen(activePort, () => {
138
- const addr = typeof activePort === 'number' ? `http://localhost:${activePort}` : activePort;
144
+ listen(() => {
145
+ const addr = typeof activePort === 'number' ? `http://${host === '0.0.0.0' ? '127.0.0.1' : host}:${activePort}` : activePort;
139
146
  console.log(`[local-lite-server] listening on ${addr} (${settings.dialect})`);
140
147
  if (settings.adminUi && typeof activePort === 'number') {
141
148
  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>;
@@ -0,0 +1,63 @@
1
+ import { type ServerSyncStorage, type SqlExecutor, type SyncEventBroker } from 'local-lite/server';
2
+ import type { RuleContext, RulesDictionary } from './rules.js';
3
+ import type { SchemaDictionary, SchemaFieldType } from './schema.js';
4
+ type Op = {
5
+ id: string;
6
+ tableName: string;
7
+ rowId: string;
8
+ operation: 'INSERT' | 'UPDATE' | 'DELETE';
9
+ payload?: Record<string, any> | null;
10
+ timestamp: number;
11
+ };
12
+ /** Thrown for bad client input; the HTTP layer maps it to 400. */
13
+ export declare class ClientError extends Error {
14
+ }
15
+ /** Thrown when a row-level access rule rejects the operation; mapped to 403. */
16
+ export declare class ForbiddenError extends Error {
17
+ }
18
+ /** Client value -> DB parameter. */
19
+ export declare function toDbValue(type: SchemaFieldType, value: unknown, dialect: string): unknown;
20
+ /** DB row -> client payload. */
21
+ export declare function fromDbRow(fields: Record<string, SchemaFieldType>, row: Record<string, any>): Record<string, any>;
22
+ export interface TableSyncStorageOptions {
23
+ schema: SchemaDictionary;
24
+ rules?: RulesDictionary;
25
+ broker?: SyncEventBroker;
26
+ changesTable?: string;
27
+ clockTable?: string;
28
+ /** Column used as the realtime event scope when a payload has it. */
29
+ scopeField?: string;
30
+ }
31
+ /**
32
+ * Stores every synced table as a real SQL table. `_server_changes` keeps only
33
+ * (table_name, row_id, timestamp) as a monotonic cursor/event log.
34
+ */
35
+ export declare class TableSyncStorage implements ServerSyncStorage {
36
+ private db;
37
+ private schema;
38
+ private rules;
39
+ private broker?;
40
+ private changes;
41
+ private clock;
42
+ private scopeField;
43
+ constructor(db: SqlExecutor, opts: TableSyncStorageOptions);
44
+ get tables(): string[];
45
+ private q;
46
+ private fields;
47
+ applyOperations(operations: Op[] | any[], _serverTime?: number, auth?: RuleContext): Promise<{
48
+ applied: number;
49
+ successfulIds: string[];
50
+ serverTime: number;
51
+ cursor: number;
52
+ }>;
53
+ getDeltas(tables: string[], since: number, limit?: number, auth?: RuleContext): Promise<{
54
+ changes: {
55
+ timestamp: number;
56
+ changes: any[];
57
+ };
58
+ cursor: number;
59
+ hasMore: boolean;
60
+ serverTime: number;
61
+ }>;
62
+ }
63
+ export {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "local-lite-server",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
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",
@@ -1,16 +1,49 @@
1
+ # Server bind host and port. Use 0.0.0.0 for LAN / physical mobile device connections.
2
+ SERVER_HOST=127.0.0.1
1
3
  SERVER_PORT=3000
4
+
5
+ # Database: mysql | postgres
2
6
  DB_DIALECT=mysql
3
7
  DB_HOST=127.0.0.1
4
8
  DB_PORT=3306
5
9
  DB_USER=root
6
10
  DB_PASSWORD=
7
11
  DB_NAME=local_lite
12
+ # DB_SSL=true
8
13
  DB_POOL_SIZE=5
14
+
15
+ # Migrations & custom paths
9
16
  AUTO_MIGRATE=true
17
+ # SCHEMA_PATH=./src/schema.ts
18
+ # RULES_PATH=./src/rules.ts
19
+ # FUNCTIONS_DIR=./src/functions
20
+ # ROUTES_PATH=./src/routes.ts
21
+
22
+ # Storage & backups
10
23
  UPLOAD_DIR=./data/uploads
11
24
  BACKUP_DIR=./data/backups
25
+
26
+ # Auth & Admin Console
12
27
  SERVER_API_KEY=change-me
13
28
  APP_SECRET=change-me
14
29
  APP_NAME={{PKG_NAME}}
15
30
  ADMIN_UI=true
31
+
32
+ # OAuth code exchange (optional: POST /auth/google-token & /auth/github-token)
33
+ # GOOGLE_CLIENT_SECRET=
34
+ # GITHUB_CLIENT_SECRET=
35
+
36
+ # SMTP for password-reset emails (optional)
37
+ # SMTP_HOST=mail.yourdomain.com
38
+ # SMTP_PORT=465
39
+ # SMTP_SECURE=true
40
+ # SMTP_USER=no-reply@yourdomain.com
41
+ # SMTP_PASS=
42
+ # SMTP_FROM={{PKG_NAME}} <no-reply@yourdomain.com>
43
+
44
+ # Background crons & multi-instance sync (optional)
45
+ # ENABLE_INTERNAL_CRONS=true
46
+ # MULTI_INSTANCE=true
47
+
48
+ # CORS
16
49
  CORS_ORIGINS=*