local-lite-server 0.0.0-stage → 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.
- package/README.md +103 -2
- package/admin/dist/assets/index-B2nX9Pef.js +18 -0
- package/admin/dist/assets/index-Dt3bXEks.css +2 -0
- package/admin/dist/favicon.svg +11 -0
- package/admin/dist/index.html +14 -0
- package/dist/admin/console.d.ts +19 -0
- package/dist/admin/console.js +166 -0
- package/dist/admin/index.d.ts +28 -0
- package/dist/admin/index.js +13 -0
- package/dist/admin/ops.d.ts +11 -0
- package/dist/admin/ops.js +279 -0
- package/dist/admin/session.d.ts +14 -0
- package/dist/admin/session.js +160 -0
- package/dist/apiKeys.d.ts +36 -0
- package/dist/apiKeys.js +91 -0
- package/dist/app.d.ts +1 -0
- package/dist/app.js +10 -0
- package/dist/auth.d.ts +16 -0
- package/dist/auth.js +99 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +127 -0
- package/dist/codegen.d.ts +4 -0
- package/dist/codegen.js +74 -0
- package/dist/config.d.ts +39 -0
- package/dist/config.js +51 -0
- package/dist/core/broker.d.ts +12 -0
- package/dist/core/broker.js +78 -0
- package/dist/core/changes.d.ts +17 -0
- package/dist/core/changes.js +68 -0
- package/dist/core/http.d.ts +8 -0
- package/dist/core/http.js +72 -0
- package/dist/core/mailer.d.ts +3 -0
- package/dist/core/mailer.js +11 -0
- package/dist/cpanel.d.ts +1 -0
- package/dist/cpanel.js +96 -0
- package/dist/crons.d.ts +24 -0
- package/dist/crons.js +124 -0
- package/dist/db.d.ts +7 -0
- package/dist/db.js +37 -0
- package/dist/functions/index.d.ts +3 -0
- package/dist/functions/index.js +3 -0
- package/dist/functions/loader.d.ts +4 -0
- package/dist/functions/loader.js +64 -0
- package/dist/functions/runtime.d.ts +21 -0
- package/dist/functions/runtime.js +238 -0
- package/dist/functions/types.d.ts +59 -0
- package/dist/functions/types.js +16 -0
- package/dist/index.d.ts +12 -0
- package/dist/index.js +7 -0
- package/dist/migrations.d.ts +16 -0
- package/dist/migrations.js +254 -0
- package/dist/oauth.d.ts +7 -0
- package/dist/oauth.js +152 -0
- package/dist/rateLimit.d.ts +12 -0
- package/dist/rateLimit.js +54 -0
- package/dist/routes.d.ts +15 -0
- package/dist/routes.js +29 -0
- package/dist/rules.d.ts +23 -0
- package/dist/rules.js +73 -0
- package/dist/schema.d.ts +18 -0
- package/dist/schema.js +89 -0
- package/dist/server.d.ts +13 -0
- package/dist/server.js +340 -0
- package/dist/start.d.ts +8 -0
- package/dist/start.js +168 -0
- package/dist/storage.d.ts +4 -0
- package/dist/storage.js +82 -0
- package/dist/tableStorage.d.ts +63 -0
- package/dist/tableStorage.js +261 -0
- package/docs/api.md +181 -0
- package/docs/client-usage.md +104 -0
- package/docs/cpanel.md +63 -0
- package/docs/functions.md +78 -0
- package/docs/schema-and-migrations.md +54 -0
- package/docs/vps.md +67 -0
- package/package.json +54 -4
- package/templates/.env +16 -0
- package/templates/.env.example +49 -0
- package/templates/README.md +23 -0
- package/templates/data/backups/.gitkeep +1 -0
- package/templates/data/uploads/.gitkeep +1 -0
- package/templates/gitignore +29 -0
- package/templates/package.json +14 -0
- package/templates/src/functions/notes.ts +47 -0
- package/templates/src/lib/validators.ts +9 -0
- package/templates/src/rules.ts +12 -0
- package/templates/src/schema.ts +9 -0
- package/templates/src/types.ts +9 -0
- package/templates/tests/notes.test.ts +26 -0
- package/templates/tsconfig.json +13 -0
package/dist/schema.js
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { pathToFileURL } from 'node:url';
|
|
4
|
+
import { buildSqlTargetSchema, generateSqlDiff, } from 'local-lite/schema/migrations';
|
|
5
|
+
/** Identity helper for typed `schema.ts` files. */
|
|
6
|
+
export function defineSchema(schema) {
|
|
7
|
+
return schema;
|
|
8
|
+
}
|
|
9
|
+
const NAME_RE = /^[A-Za-z_][A-Za-z0-9_]{0,63}$/;
|
|
10
|
+
const VALID_TYPES = new Set([
|
|
11
|
+
'string', 'string | null',
|
|
12
|
+
'number', 'number | null',
|
|
13
|
+
'boolean', 'boolean | null',
|
|
14
|
+
'json', 'json | null',
|
|
15
|
+
'string[]', 'string[] | null',
|
|
16
|
+
]);
|
|
17
|
+
/** Validates names, field types, and guarantees an `id` column on every table. */
|
|
18
|
+
export function normalizeSchema(input) {
|
|
19
|
+
const out = {};
|
|
20
|
+
for (const [table, fields] of Object.entries(input)) {
|
|
21
|
+
if (!NAME_RE.test(table) || table.startsWith('_')) {
|
|
22
|
+
throw new Error(`Invalid table name "${table}" in schema (letters, digits, _; must not start with _).`);
|
|
23
|
+
}
|
|
24
|
+
if (!fields || typeof fields !== 'object' || Array.isArray(fields)) {
|
|
25
|
+
throw new Error(`Table "${table}" in schema must be an object of { column: type }.`);
|
|
26
|
+
}
|
|
27
|
+
const cols = { id: 'string' };
|
|
28
|
+
for (const [col, type] of Object.entries(fields)) {
|
|
29
|
+
if (!NAME_RE.test(col))
|
|
30
|
+
throw new Error(`Invalid column name "${table}.${col}" in schema.`);
|
|
31
|
+
if (typeof type !== 'string' || !VALID_TYPES.has(type)) {
|
|
32
|
+
throw new Error(`Invalid field type for "${table}.${col}": "${String(type)}".`);
|
|
33
|
+
}
|
|
34
|
+
cols[col] = type;
|
|
35
|
+
}
|
|
36
|
+
cols.id = 'string';
|
|
37
|
+
out[table] = cols;
|
|
38
|
+
}
|
|
39
|
+
return out;
|
|
40
|
+
}
|
|
41
|
+
const CANDIDATES = ['src/schema.ts', 'schema.ts'];
|
|
42
|
+
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
|
+
}
|
|
58
|
+
throw new Error(`No schema file found. Create src/schema.ts (or set SCHEMA_PATH):\n` +
|
|
59
|
+
` export default { notes: { id: 'string', title: 'string', body: 'string | null' } };`);
|
|
60
|
+
}
|
|
61
|
+
export async function loadSchemaFile(file) {
|
|
62
|
+
const loaded = await import(pathToFileURL(file).href);
|
|
63
|
+
const mod = loaded.default ?? loaded.schema;
|
|
64
|
+
if (!mod || typeof mod !== 'object' || Array.isArray(mod)) {
|
|
65
|
+
throw new Error(`${file} must export default an object of { table: { column: type } }.`);
|
|
66
|
+
}
|
|
67
|
+
return normalizeSchema(mod);
|
|
68
|
+
}
|
|
69
|
+
export async function planSchema(db, dictionary) {
|
|
70
|
+
const dialect = db.dialect;
|
|
71
|
+
const rows = await db.query('SELECT state FROM _lls_schema_state WHERE id = 1');
|
|
72
|
+
const prev = rows[0]?.state ? JSON.parse(rows[0].state) : null;
|
|
73
|
+
const next = buildSqlTargetSchema(dictionary, [], { dialect });
|
|
74
|
+
const diff = generateSqlDiff(prev, next, dialect);
|
|
75
|
+
return { up: diff.up, warnings: diff.warnings, next, first: prev === null };
|
|
76
|
+
}
|
|
77
|
+
/** Applies the schema diff and records the new state. Safe to call on every boot. */
|
|
78
|
+
export async function applySchema(db, dictionary) {
|
|
79
|
+
const plan = await planSchema(db, dictionary);
|
|
80
|
+
for (const stmt of plan.up)
|
|
81
|
+
await db.execute(stmt);
|
|
82
|
+
if (plan.up.length > 0 || plan.first) {
|
|
83
|
+
await db.execute('DELETE FROM _lls_schema_state WHERE id = 1');
|
|
84
|
+
await db.execute('INSERT INTO _lls_schema_state (id, state) VALUES (1, ?)', [
|
|
85
|
+
JSON.stringify(plan.next),
|
|
86
|
+
]);
|
|
87
|
+
}
|
|
88
|
+
return plan;
|
|
89
|
+
}
|
package/dist/server.d.ts
ADDED
|
@@ -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
ADDED
|
@@ -0,0 +1,340 @@
|
|
|
1
|
+
import { createServer, createSyncEventBroker, createSyncEventsHandler, } from 'local-lite/server';
|
|
2
|
+
import { ClientError, ForbiddenError, TableSyncStorage } from './tableStorage.js';
|
|
3
|
+
import { createAuthService } from './auth.js';
|
|
4
|
+
import { createApiKeyService } from './apiKeys.js';
|
|
5
|
+
import { handleOAuthTokenExchange, verifyOAuthToken } from './oauth.js';
|
|
6
|
+
import { createAdminConsole } from './admin/index.js';
|
|
7
|
+
import { createStorageHandler } from './storage.js';
|
|
8
|
+
import { corsHeaders, createHttpServer, safeEqual } from './core/http.js';
|
|
9
|
+
import { clientIp, createDistributedRateLimiter } from './rateLimit.js';
|
|
10
|
+
import { createFunctionRuntime, FunctionError, } from './functions/index.js';
|
|
11
|
+
export { createHttpServer };
|
|
12
|
+
export function createApp(settings, executor, schema, functions = new Map(), rules = {}, brokerOverride, customRoutesInput) {
|
|
13
|
+
const broker = brokerOverride ?? createSyncEventBroker();
|
|
14
|
+
const storage = new TableSyncStorage(executor, { schema, rules, broker });
|
|
15
|
+
const auth = createAuthService(settings, executor);
|
|
16
|
+
const apiKeys = createApiKeyService(executor);
|
|
17
|
+
const fnRuntime = createFunctionRuntime({ registry: functions, db: executor, schema, broker });
|
|
18
|
+
const consoleApi = createAdminConsole({ settings, db: executor, schema, broker, fnRuntime });
|
|
19
|
+
const storageHandler = createStorageHandler(settings, executor, async (req) => {
|
|
20
|
+
const a = await resolveAuth(req, true);
|
|
21
|
+
return a ? { userId: a.userId ?? 'admin', isAdmin: a.isAdmin } : null;
|
|
22
|
+
});
|
|
23
|
+
const authLimiter = createDistributedRateLimiter(executor, 20, 60_000, settings.multiInstance);
|
|
24
|
+
const bearer = (request) => {
|
|
25
|
+
const header = request.headers.get('authorization') ?? '';
|
|
26
|
+
return header.startsWith('Bearer ') ? header.slice(7).trim() : '';
|
|
27
|
+
};
|
|
28
|
+
const apiKeyHeader = (request) => request.headers.get('x-api-key')?.trim() ?? '';
|
|
29
|
+
/** Admin key, API key, console cookie session, or a valid user token. */
|
|
30
|
+
const resolveAuth = async (request, allowQuery = false) => {
|
|
31
|
+
const token = bearer(request) ||
|
|
32
|
+
apiKeyHeader(request) ||
|
|
33
|
+
(allowQuery ? (new URL(request.url).searchParams.get('token') ?? '') : '');
|
|
34
|
+
if (token) {
|
|
35
|
+
if (safeEqual(token, settings.apiKey))
|
|
36
|
+
return { isAdmin: true };
|
|
37
|
+
const keyAuth = await apiKeys.verifyKey(token);
|
|
38
|
+
if (keyAuth)
|
|
39
|
+
return { isAdmin: keyAuth.isAdmin, userId: keyAuth.userId };
|
|
40
|
+
const user = await auth.verifyUser(token);
|
|
41
|
+
if (user)
|
|
42
|
+
return { isAdmin: false, userId: user.id };
|
|
43
|
+
const oauthUser = await verifyOAuthToken(token);
|
|
44
|
+
if (oauthUser)
|
|
45
|
+
return { isAdmin: false, userId: oauthUser.id };
|
|
46
|
+
}
|
|
47
|
+
if (settings.adminUi) {
|
|
48
|
+
const adminSession = await consoleApi.authenticate(request);
|
|
49
|
+
if (adminSession)
|
|
50
|
+
return { isAdmin: true, userId: adminSession.userId };
|
|
51
|
+
}
|
|
52
|
+
return null;
|
|
53
|
+
};
|
|
54
|
+
const canSync = async (request, allowQuery = false) => Boolean(await resolveAuth(request, allowQuery));
|
|
55
|
+
const guard = async (run) => {
|
|
56
|
+
try {
|
|
57
|
+
return await run();
|
|
58
|
+
}
|
|
59
|
+
catch (err) {
|
|
60
|
+
if (err instanceof ClientError) {
|
|
61
|
+
return Response.json({ error: err.message }, { status: 400 });
|
|
62
|
+
}
|
|
63
|
+
if (err instanceof ForbiddenError) {
|
|
64
|
+
return Response.json({ error: err.message }, { status: 403 });
|
|
65
|
+
}
|
|
66
|
+
if (err instanceof FunctionError) {
|
|
67
|
+
return Response.json({ error: err.message }, { status: err.status });
|
|
68
|
+
}
|
|
69
|
+
if (err instanceof Error && typeof err.status === 'number') {
|
|
70
|
+
const status = err.status;
|
|
71
|
+
if (status >= 400 && status < 500) {
|
|
72
|
+
return Response.json({ error: err.message }, { status });
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
throw err;
|
|
76
|
+
}
|
|
77
|
+
};
|
|
78
|
+
const unauthorized = () => Response.json({ error: 'Unauthorized' }, { status: 401 });
|
|
79
|
+
const events = createSyncEventsHandler({
|
|
80
|
+
broker,
|
|
81
|
+
authenticate: (req) => canSync(req, true),
|
|
82
|
+
});
|
|
83
|
+
const customRoutes = typeof customRoutesInput === 'function'
|
|
84
|
+
? customRoutesInput({ db: executor, settings, schema, broker, resolveAuth })
|
|
85
|
+
: (customRoutesInput ?? {});
|
|
86
|
+
const api = createServer({
|
|
87
|
+
config: {},
|
|
88
|
+
middleware: [
|
|
89
|
+
async ({ request }, next) => {
|
|
90
|
+
const cors = corsHeaders(request, settings);
|
|
91
|
+
if (request.method === 'OPTIONS') {
|
|
92
|
+
return new Response(null, { status: 204, headers: cors });
|
|
93
|
+
}
|
|
94
|
+
const res = await next();
|
|
95
|
+
const out = new Response(res.body, res);
|
|
96
|
+
for (const [k, v] of Object.entries(cors))
|
|
97
|
+
out.headers.set(k, v);
|
|
98
|
+
return out;
|
|
99
|
+
},
|
|
100
|
+
],
|
|
101
|
+
onError: (error) => console.error('[local-lite-server]', error),
|
|
102
|
+
endpoints: {
|
|
103
|
+
...customRoutes,
|
|
104
|
+
'/health': {
|
|
105
|
+
GET: async () => {
|
|
106
|
+
try {
|
|
107
|
+
await executor.query('SELECT 1');
|
|
108
|
+
return Response.json({ ok: true, dialect: settings.dialect });
|
|
109
|
+
}
|
|
110
|
+
catch {
|
|
111
|
+
return Response.json({ ok: false }, { status: 503 });
|
|
112
|
+
}
|
|
113
|
+
},
|
|
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
|
+
},
|
|
133
|
+
'/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
|
+
},
|
|
141
|
+
},
|
|
142
|
+
'/sync/events': {
|
|
143
|
+
GET: ({ request }) => events(request),
|
|
144
|
+
},
|
|
145
|
+
'/storage/*': {
|
|
146
|
+
ALL: ({ request }) => storageHandler(request),
|
|
147
|
+
},
|
|
148
|
+
'/public/files/*': {
|
|
149
|
+
GET: ({ request }) => {
|
|
150
|
+
const url = new URL(request.url);
|
|
151
|
+
url.pathname = url.pathname.replace(/^\/public\/files/, '/storage/files');
|
|
152
|
+
return storageHandler(new Request(url, request));
|
|
153
|
+
},
|
|
154
|
+
},
|
|
155
|
+
'/fn': {
|
|
156
|
+
GET: async ({ request }) => {
|
|
157
|
+
if (!(await canSync(request)))
|
|
158
|
+
return unauthorized();
|
|
159
|
+
return Response.json({ functions: fnRuntime.list() });
|
|
160
|
+
},
|
|
161
|
+
},
|
|
162
|
+
'/fn/:module/:name': {
|
|
163
|
+
POST: async ({ request, params }) => {
|
|
164
|
+
const userAuth = await resolveAuth(request);
|
|
165
|
+
if (!userAuth)
|
|
166
|
+
return unauthorized();
|
|
167
|
+
const raw = (await request.json().catch(() => ({})));
|
|
168
|
+
const args = raw && typeof raw === 'object' && raw.args && typeof raw.args === 'object'
|
|
169
|
+
? raw.args
|
|
170
|
+
: raw && typeof raw === 'object'
|
|
171
|
+
? raw
|
|
172
|
+
: {};
|
|
173
|
+
return guard(async () => {
|
|
174
|
+
const { result } = await fnRuntime.run(`${params.module}/${params.name}`, args, userAuth);
|
|
175
|
+
return Response.json({ success: true, result });
|
|
176
|
+
});
|
|
177
|
+
},
|
|
178
|
+
},
|
|
179
|
+
'/subscribe/:module/:name': {
|
|
180
|
+
GET: async ({ request, params }) => {
|
|
181
|
+
const userAuth = await resolveAuth(request, true);
|
|
182
|
+
if (!userAuth)
|
|
183
|
+
return unauthorized();
|
|
184
|
+
const rawArgs = new URL(request.url).searchParams.get('args');
|
|
185
|
+
let args = {};
|
|
186
|
+
if (rawArgs) {
|
|
187
|
+
try {
|
|
188
|
+
const parsed = JSON.parse(rawArgs);
|
|
189
|
+
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
|
|
190
|
+
args = parsed;
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
catch {
|
|
194
|
+
return Response.json({ error: 'Invalid args JSON.' }, { status: 400 });
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
return guard(() => fnRuntime.subscribe(`${params.module}/${params.name}`, args, userAuth));
|
|
198
|
+
},
|
|
199
|
+
},
|
|
200
|
+
'/sync': {
|
|
201
|
+
GET: async ({ request }) => {
|
|
202
|
+
const userAuth = await resolveAuth(request);
|
|
203
|
+
if (!userAuth)
|
|
204
|
+
return unauthorized();
|
|
205
|
+
const url = new URL(request.url);
|
|
206
|
+
const tables = (url.searchParams.get('tables') ?? '')
|
|
207
|
+
.split(',')
|
|
208
|
+
.map((t) => t.trim())
|
|
209
|
+
.filter(Boolean);
|
|
210
|
+
const limit = Math.min(Math.max(Number(url.searchParams.get('limit') || 500), 1), 2000);
|
|
211
|
+
return guard(async () => {
|
|
212
|
+
const result = await storage.getDeltas(tables, Number(url.searchParams.get('since') || 0), limit, userAuth);
|
|
213
|
+
return Response.json({ success: true, ...result });
|
|
214
|
+
});
|
|
215
|
+
},
|
|
216
|
+
POST: async ({ request }) => {
|
|
217
|
+
const userAuth = await resolveAuth(request);
|
|
218
|
+
if (!userAuth)
|
|
219
|
+
return unauthorized();
|
|
220
|
+
const body = (await request.json().catch(() => null));
|
|
221
|
+
if (!body || !Array.isArray(body.operations)) {
|
|
222
|
+
return Response.json({ error: 'Operations must be an array.' }, { status: 400 });
|
|
223
|
+
}
|
|
224
|
+
return guard(async () => {
|
|
225
|
+
const result = await storage.applyOperations(body.operations, undefined, userAuth);
|
|
226
|
+
return Response.json({ success: true, processed: result.applied, ...result });
|
|
227
|
+
});
|
|
228
|
+
},
|
|
229
|
+
},
|
|
230
|
+
...(settings.adminUi
|
|
231
|
+
? {
|
|
232
|
+
'/admin': { GET: ({ request }) => consoleApi.serveStatic(new URL(request.url).pathname) },
|
|
233
|
+
'/admin/login': {
|
|
234
|
+
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
|
+
},
|
|
242
|
+
},
|
|
243
|
+
'/admin/logout': {
|
|
244
|
+
POST: async ({ request }) => consoleApi.postLogout(request, await consoleApi.authenticate(request)),
|
|
245
|
+
},
|
|
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
|
+
},
|
|
258
|
+
'/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(),
|
|
281
|
+
},
|
|
282
|
+
'/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();
|
|
293
|
+
const body = (await request.json().catch(() => null));
|
|
294
|
+
const days = Number(body?.expiresInDays ?? 0);
|
|
295
|
+
const expiresAt = Number.isFinite(days) && days > 0 ? Date.now() + days * 86_400_000 : null;
|
|
296
|
+
try {
|
|
297
|
+
const created = await apiKeys.createKey({
|
|
298
|
+
name: String(body?.name ?? ''),
|
|
299
|
+
role: body?.role === 'user' ? 'user' : 'admin',
|
|
300
|
+
userId: body?.userId ?? null,
|
|
301
|
+
createdBy: s.userId,
|
|
302
|
+
expiresAt,
|
|
303
|
+
});
|
|
304
|
+
return Response.json(created, { status: 201 });
|
|
305
|
+
}
|
|
306
|
+
catch (err) {
|
|
307
|
+
return Response.json({ error: err.message }, { status: 400 });
|
|
308
|
+
}
|
|
309
|
+
},
|
|
310
|
+
PATCH: async ({ request }) => {
|
|
311
|
+
const s = await consoleApi.authenticate(request);
|
|
312
|
+
if (!s)
|
|
313
|
+
return unauthorized();
|
|
314
|
+
const body = (await request.json().catch(() => null));
|
|
315
|
+
if (!body?.id || body.action !== 'revoke') {
|
|
316
|
+
return Response.json({ error: 'Provide id and action: "revoke".' }, { status: 400 });
|
|
317
|
+
}
|
|
318
|
+
const ok = await apiKeys.revokeKey(String(body.id));
|
|
319
|
+
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();
|
|
325
|
+
const id = new URL(request.url).searchParams.get('id') ?? '';
|
|
326
|
+
if (!id)
|
|
327
|
+
return Response.json({ error: 'Missing id.' }, { status: 400 });
|
|
328
|
+
const ok = await apiKeys.deleteKey(id);
|
|
329
|
+
return ok ? Response.json({ ok: true }) : Response.json({ error: 'Key not found.' }, { status: 404 });
|
|
330
|
+
},
|
|
331
|
+
},
|
|
332
|
+
'/admin/*': {
|
|
333
|
+
GET: ({ request }) => consoleApi.serveStatic(new URL(request.url).pathname),
|
|
334
|
+
},
|
|
335
|
+
}
|
|
336
|
+
: {}),
|
|
337
|
+
},
|
|
338
|
+
});
|
|
339
|
+
return { fetch: (req) => api.fetch(req), broker, fnRuntime };
|
|
340
|
+
}
|
package/dist/start.d.ts
ADDED
|
@@ -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
ADDED
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
import { loadSettings } from './config.js';
|
|
2
|
+
import { createDatabase } from './db.js';
|
|
3
|
+
import { runMigrations } from './migrations.js';
|
|
4
|
+
import { applySchema, loadSchemaFile, planSchema, resolveSchemaFile } from './schema.js';
|
|
5
|
+
import { loadRulesFile, resolveRulesFile } from './rules.js';
|
|
6
|
+
import { loadRoutesFile, resolveRoutesFile } from './routes.js';
|
|
7
|
+
import { loadFunctionsDir, watchFunctionsDir } from './functions/index.js';
|
|
8
|
+
import { createClusterBroker } from './core/broker.js';
|
|
9
|
+
import { startCronScheduler } from './crons.js';
|
|
10
|
+
import { createApp, createHttpServer } from './server.js';
|
|
11
|
+
async function tryCreateDatabase(s) {
|
|
12
|
+
try {
|
|
13
|
+
if (s.dialect === 'postgres') {
|
|
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
|
+
});
|
|
23
|
+
await client.connect();
|
|
24
|
+
try {
|
|
25
|
+
await client.query(`CREATE DATABASE "${s.db.database.replace(/"/g, '')}"`);
|
|
26
|
+
}
|
|
27
|
+
finally {
|
|
28
|
+
await client.end();
|
|
29
|
+
}
|
|
30
|
+
return true;
|
|
31
|
+
}
|
|
32
|
+
const mysql = (await import('mysql2/promise')).default;
|
|
33
|
+
const conn = await mysql.createConnection({
|
|
34
|
+
host: s.db.host,
|
|
35
|
+
port: s.db.port,
|
|
36
|
+
user: s.db.user,
|
|
37
|
+
password: s.db.password,
|
|
38
|
+
});
|
|
39
|
+
try {
|
|
40
|
+
await conn.query(`CREATE DATABASE IF NOT EXISTS \`${s.db.database.replace(/`/g, '')}\` CHARACTER SET utf8mb4`);
|
|
41
|
+
}
|
|
42
|
+
finally {
|
|
43
|
+
await conn.end();
|
|
44
|
+
}
|
|
45
|
+
return true;
|
|
46
|
+
}
|
|
47
|
+
catch {
|
|
48
|
+
return false;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
function friendlyDbError(err, s) {
|
|
52
|
+
const code = err.code;
|
|
53
|
+
if (code === 'ER_BAD_DB_ERROR' || code === '3D000') {
|
|
54
|
+
return new Error(`Database "${s.db.database}" does not exist. Create it first ` +
|
|
55
|
+
(s.dialect === 'mysql'
|
|
56
|
+
? `(CREATE DATABASE \`${s.db.database}\` CHARACTER SET utf8mb4;)`
|
|
57
|
+
: `(CREATE DATABASE "${s.db.database}";)`) +
|
|
58
|
+
', or on cPanel create it in "MySQL Databases" and grant your user access.');
|
|
59
|
+
}
|
|
60
|
+
return err;
|
|
61
|
+
}
|
|
62
|
+
export async function loadSchema(s) {
|
|
63
|
+
return loadSchemaFile(resolveSchemaFile(s.schemaPath));
|
|
64
|
+
}
|
|
65
|
+
/** Core + schema migrations. Returns a human-readable log. */
|
|
66
|
+
export async function migrate(s, db, schema) {
|
|
67
|
+
const applyAll = async () => {
|
|
68
|
+
const core = await runMigrations(db.executor);
|
|
69
|
+
if (core.applied.length)
|
|
70
|
+
console.log('[local-lite-server] core migrations:', core.applied.join(', '));
|
|
71
|
+
const plan = await applySchema(db.executor, schema);
|
|
72
|
+
if (plan.up.length)
|
|
73
|
+
console.log(`[local-lite-server] schema: applied ${plan.up.length} change(s)`);
|
|
74
|
+
for (const w of plan.warnings)
|
|
75
|
+
console.warn('[local-lite-server] schema warning:', w);
|
|
76
|
+
};
|
|
77
|
+
try {
|
|
78
|
+
await applyAll();
|
|
79
|
+
}
|
|
80
|
+
catch (err) {
|
|
81
|
+
const code = err.code;
|
|
82
|
+
if ((code === 'ER_BAD_DB_ERROR' || code === '3D000') && (await tryCreateDatabase(s))) {
|
|
83
|
+
console.log(`[local-lite-server] created database "${s.db.database}"`);
|
|
84
|
+
await applyAll();
|
|
85
|
+
return;
|
|
86
|
+
}
|
|
87
|
+
throw friendlyDbError(err, s);
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
/** Shared boot used by the CLI and the cPanel entry point. */
|
|
91
|
+
export async function start() {
|
|
92
|
+
const settings = loadSettings();
|
|
93
|
+
const schema = await loadSchema(settings);
|
|
94
|
+
const rulesFile = resolveRulesFile(settings.rulesPath);
|
|
95
|
+
const rules = rulesFile ? await loadRulesFile(rulesFile) : {};
|
|
96
|
+
if (settings.appSecret && !rulesFile) {
|
|
97
|
+
console.warn('[local-lite-server] APP_SECRET is set without src/rules.ts; authenticated users can sync all tables.');
|
|
98
|
+
}
|
|
99
|
+
const functions = await loadFunctionsDir(settings.functionsDir);
|
|
100
|
+
const routesFile = resolveRoutesFile();
|
|
101
|
+
const customRoutes = routesFile ? await loadRoutesFile(routesFile) : undefined;
|
|
102
|
+
const database = await createDatabase(settings);
|
|
103
|
+
try {
|
|
104
|
+
if (settings.autoMigrate) {
|
|
105
|
+
await migrate(settings, database, schema);
|
|
106
|
+
}
|
|
107
|
+
else {
|
|
108
|
+
const plan = await planSchema(database.executor, schema).catch(() => null);
|
|
109
|
+
if (!plan || plan.up.length) {
|
|
110
|
+
console.warn('[local-lite-server] AUTO_MIGRATE=false and migrations are pending. Run: npm run migrate');
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
catch (err) {
|
|
115
|
+
await database.close().catch(() => { });
|
|
116
|
+
throw friendlyDbError(err, settings);
|
|
117
|
+
}
|
|
118
|
+
const broker = await createClusterBroker(settings, database.executor);
|
|
119
|
+
const app = createApp(settings, database.executor, schema, functions, rules, broker, customRoutes);
|
|
120
|
+
const server = createHttpServer(app);
|
|
121
|
+
const host = process.env.SERVER_HOST || '127.0.0.1';
|
|
122
|
+
let activePort = settings.port;
|
|
123
|
+
let attempts = 0;
|
|
124
|
+
const listen = (onListening) => typeof activePort === 'number'
|
|
125
|
+
? server.listen(activePort, host, onListening)
|
|
126
|
+
: server.listen(activePort, onListening);
|
|
127
|
+
server.on('error', (err) => {
|
|
128
|
+
if (err.code === 'EADDRINUSE' && typeof activePort === 'number' && !process.env.PORT && attempts < 20) {
|
|
129
|
+
const nextPort = activePort + 1;
|
|
130
|
+
console.warn(`[local-lite-server] port ${activePort} is in use, trying ${nextPort}...`);
|
|
131
|
+
activePort = nextPort;
|
|
132
|
+
attempts += 1;
|
|
133
|
+
listen();
|
|
134
|
+
return;
|
|
135
|
+
}
|
|
136
|
+
if (err.code === 'EADDRINUSE') {
|
|
137
|
+
console.error(`[local-lite-server] port ${activePort} is already in use. Stop the other process or change SERVER_PORT in .env.`);
|
|
138
|
+
}
|
|
139
|
+
else {
|
|
140
|
+
console.error('[local-lite-server] server error:', err);
|
|
141
|
+
}
|
|
142
|
+
void database.close().finally(() => process.exit(1));
|
|
143
|
+
});
|
|
144
|
+
listen(() => {
|
|
145
|
+
const addr = typeof activePort === 'number' ? `http://${host === '0.0.0.0' ? '127.0.0.1' : host}:${activePort}` : activePort;
|
|
146
|
+
console.log(`[local-lite-server] listening on ${addr} (${settings.dialect})`);
|
|
147
|
+
if (settings.adminUi && typeof activePort === 'number') {
|
|
148
|
+
console.log(`[local-lite-server] admin console: ${addr}/admin`);
|
|
149
|
+
}
|
|
150
|
+
});
|
|
151
|
+
const stopWatch = process.env.NODE_ENV === 'production'
|
|
152
|
+
? () => { }
|
|
153
|
+
: watchFunctionsDir(settings.functionsDir, functions);
|
|
154
|
+
const stopCrons = startCronScheduler({
|
|
155
|
+
settings,
|
|
156
|
+
db: database.executor,
|
|
157
|
+
fnRuntime: app.fnRuntime,
|
|
158
|
+
});
|
|
159
|
+
const shutdown = () => {
|
|
160
|
+
stopWatch();
|
|
161
|
+
stopCrons();
|
|
162
|
+
server.close();
|
|
163
|
+
void broker.close().finally(() => void database.close().finally(() => process.exit(0)));
|
|
164
|
+
};
|
|
165
|
+
process.on('SIGTERM', shutdown);
|
|
166
|
+
process.on('SIGINT', shutdown);
|
|
167
|
+
return server;
|
|
168
|
+
}
|
|
@@ -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>;
|