local-lite-server 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +103 -2
- package/admin/dist/assets/index-DMJ7Ri2R.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.js +166 -0
- package/dist/admin/index.js +13 -0
- package/dist/admin/ops.js +279 -0
- package/dist/admin/session.js +160 -0
- package/dist/apiKeys.js +91 -0
- package/dist/app.js +6 -0
- package/dist/auth.js +99 -0
- package/dist/cli.js +127 -0
- package/dist/codegen.js +74 -0
- package/dist/config.js +51 -0
- package/dist/core/broker.js +78 -0
- package/dist/core/changes.js +68 -0
- package/dist/core/http.js +72 -0
- package/dist/core/mailer.js +11 -0
- package/dist/cpanel.js +78 -0
- package/dist/crons.js +124 -0
- package/dist/db.js +37 -0
- package/dist/functions/index.js +3 -0
- package/dist/functions/loader.js +64 -0
- package/dist/functions/runtime.js +238 -0
- package/dist/functions/types.js +16 -0
- package/dist/index.js +6 -0
- package/dist/migrations.js +254 -0
- package/dist/rateLimit.js +54 -0
- package/dist/rules.js +73 -0
- package/dist/schema.js +89 -0
- package/dist/server.js +314 -0
- package/dist/start.js +161 -0
- package/dist/storage.js +82 -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 +16 -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
|
@@ -0,0 +1,238 @@
|
|
|
1
|
+
import { quoteIdent } from 'local-lite/server';
|
|
2
|
+
import { newRowId, patchTableRow, recordChange, setRowDeleted, upsertTableRow, } from '../core/changes.js';
|
|
3
|
+
import { fromDbRow, toDbValue } from '../tableStorage.js';
|
|
4
|
+
import { FunctionError, } from './types.js';
|
|
5
|
+
function createReader(db, schema, readTables) {
|
|
6
|
+
const q = (n) => quoteIdent(n, db.dialect);
|
|
7
|
+
const fieldsOf = (table) => {
|
|
8
|
+
const f = Object.hasOwn(schema, table) ? schema[table] : undefined;
|
|
9
|
+
if (!f)
|
|
10
|
+
throw new FunctionError(`Unknown table "${table}".`, 400);
|
|
11
|
+
return f;
|
|
12
|
+
};
|
|
13
|
+
const notDeleted = db.dialect === 'postgres' ? 'FALSE' : '0';
|
|
14
|
+
return {
|
|
15
|
+
async get(table, id) {
|
|
16
|
+
const fields = fieldsOf(table);
|
|
17
|
+
readTables.add(table);
|
|
18
|
+
const rows = await db.query(`SELECT * FROM ${q(table)} WHERE ${q('id')} = ? AND ${q('deleted')} = ${notDeleted} LIMIT 1`, [id]);
|
|
19
|
+
return rows[0] ? { id: String(rows[0].id), ...fromDbRow(fields, rows[0]) } : null;
|
|
20
|
+
},
|
|
21
|
+
async list(table, opts = {}) {
|
|
22
|
+
const fields = fieldsOf(table);
|
|
23
|
+
readTables.add(table);
|
|
24
|
+
const clauses = [];
|
|
25
|
+
const params = [];
|
|
26
|
+
if (!opts.includeDeleted)
|
|
27
|
+
clauses.push(`${q('deleted')} = ${notDeleted}`);
|
|
28
|
+
if (opts.where) {
|
|
29
|
+
for (const [col, val] of Object.entries(opts.where)) {
|
|
30
|
+
if (!Object.hasOwn(fields, col))
|
|
31
|
+
throw new FunctionError(`Unknown column "${table}.${col}".`, 400);
|
|
32
|
+
if (val === null)
|
|
33
|
+
clauses.push(`${q(col)} IS NULL`);
|
|
34
|
+
else {
|
|
35
|
+
clauses.push(`${q(col)} = ?`);
|
|
36
|
+
params.push(toDbValue(fields[col], val, db.dialect));
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
const whereSql = clauses.length ? `WHERE ${clauses.join(' AND ')}` : '';
|
|
41
|
+
const orderCol = opts.orderBy && Object.hasOwn(fields, opts.orderBy) ? opts.orderBy : 'updated_at';
|
|
42
|
+
const dir = opts.order === 'asc' ? 'ASC' : 'DESC';
|
|
43
|
+
const limit = Math.min(Math.max(Math.floor(opts.limit ?? 100), 1), 1000);
|
|
44
|
+
const offset = Math.max(Math.floor(opts.offset ?? 0), 0);
|
|
45
|
+
const rows = await db.query(`SELECT * FROM ${q(table)} ${whereSql} ORDER BY ${q(orderCol)} ${dir} LIMIT ${limit} OFFSET ${offset}`, params);
|
|
46
|
+
return rows.map((r) => ({ id: String(r.id), ...fromDbRow(fields, r) }));
|
|
47
|
+
},
|
|
48
|
+
async sql(query, params = [], touchesTables) {
|
|
49
|
+
if (touchesTables) {
|
|
50
|
+
for (const t of touchesTables)
|
|
51
|
+
readTables.add(t);
|
|
52
|
+
}
|
|
53
|
+
else {
|
|
54
|
+
for (const t of Object.keys(schema)) {
|
|
55
|
+
if (new RegExp(`\\b${t}\\b`).test(query))
|
|
56
|
+
readTables.add(t);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
return db.query(query, params);
|
|
60
|
+
},
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
export function createFunctionRuntime(opts) {
|
|
64
|
+
const { registry, db, schema, broker } = opts;
|
|
65
|
+
const scopeField = opts.scopeField ?? 'scope_id';
|
|
66
|
+
const getFn = (name) => {
|
|
67
|
+
const fn = registry.get(name);
|
|
68
|
+
if (!fn)
|
|
69
|
+
throw new FunctionError(`Function "${name}" not found.`, 404);
|
|
70
|
+
return fn;
|
|
71
|
+
};
|
|
72
|
+
const parseArgs = (fn, raw) => {
|
|
73
|
+
if (!fn.args)
|
|
74
|
+
return raw;
|
|
75
|
+
try {
|
|
76
|
+
return fn.args(raw);
|
|
77
|
+
}
|
|
78
|
+
catch (err) {
|
|
79
|
+
throw new FunctionError(err instanceof Error ? err.message : 'Invalid arguments.', 400);
|
|
80
|
+
}
|
|
81
|
+
};
|
|
82
|
+
const runQuery = async (name, rawArgs, auth) => {
|
|
83
|
+
const fn = getFn(name);
|
|
84
|
+
if (fn.__kind !== 'query')
|
|
85
|
+
throw new FunctionError(`"${name}" is a ${fn.__kind}, not a query.`, 400);
|
|
86
|
+
const readTables = new Set();
|
|
87
|
+
const result = await fn.handler({ db: createReader(db, schema, readTables), auth }, parseArgs(fn, rawArgs));
|
|
88
|
+
return { result, readTables };
|
|
89
|
+
};
|
|
90
|
+
const runMutation = async (name, rawArgs, auth) => {
|
|
91
|
+
const fn = getFn(name);
|
|
92
|
+
if (fn.__kind !== 'mutation')
|
|
93
|
+
throw new FunctionError(`"${name}" is a ${fn.__kind}, not a mutation.`, 400);
|
|
94
|
+
const args = parseArgs(fn, rawArgs);
|
|
95
|
+
const emitted = [];
|
|
96
|
+
const readTables = new Set();
|
|
97
|
+
const result = await db.withTransaction(async (tx) => {
|
|
98
|
+
const reader = createReader(tx, schema, readTables);
|
|
99
|
+
const track = async (table, id, scopeVal) => {
|
|
100
|
+
const ts = await recordChange(tx, table, id);
|
|
101
|
+
emitted.push({
|
|
102
|
+
scopeId: typeof scopeVal === 'string' && scopeVal ? scopeVal : 'default',
|
|
103
|
+
tableName: table,
|
|
104
|
+
checkpoint: ts,
|
|
105
|
+
});
|
|
106
|
+
return ts;
|
|
107
|
+
};
|
|
108
|
+
const writer = {
|
|
109
|
+
...reader,
|
|
110
|
+
async insert(table, data) {
|
|
111
|
+
const fields = Object.hasOwn(schema, table) ? schema[table] : undefined;
|
|
112
|
+
if (!fields)
|
|
113
|
+
throw new FunctionError(`Unknown table "${table}".`, 400);
|
|
114
|
+
const id = newRowId(data.id);
|
|
115
|
+
const ts = await track(table, id, data[scopeField]);
|
|
116
|
+
await upsertTableRow(tx, table, fields, id, data, ts);
|
|
117
|
+
return (await reader.get(table, id));
|
|
118
|
+
},
|
|
119
|
+
async patch(table, id, patch) {
|
|
120
|
+
const fields = Object.hasOwn(schema, table) ? schema[table] : undefined;
|
|
121
|
+
if (!fields)
|
|
122
|
+
throw new FunctionError(`Unknown table "${table}".`, 400);
|
|
123
|
+
const existing = await reader.get(table, id);
|
|
124
|
+
if (!existing)
|
|
125
|
+
return null;
|
|
126
|
+
const ts = await track(table, id, patch[scopeField] ?? existing[scopeField]);
|
|
127
|
+
await patchTableRow(tx, table, fields, id, patch, ts);
|
|
128
|
+
return reader.get(table, id);
|
|
129
|
+
},
|
|
130
|
+
async remove(table, id) {
|
|
131
|
+
if (!Object.hasOwn(schema, table))
|
|
132
|
+
throw new FunctionError(`Unknown table "${table}".`, 400);
|
|
133
|
+
const existing = await reader.get(table, id);
|
|
134
|
+
if (!existing)
|
|
135
|
+
return false;
|
|
136
|
+
const ts = await track(table, id, existing[scopeField]);
|
|
137
|
+
await setRowDeleted(tx, table, id, true, ts);
|
|
138
|
+
return true;
|
|
139
|
+
},
|
|
140
|
+
};
|
|
141
|
+
return fn.handler({ db: writer, auth }, args);
|
|
142
|
+
});
|
|
143
|
+
for (const e of emitted)
|
|
144
|
+
broker.publish(e);
|
|
145
|
+
return { result, readTables };
|
|
146
|
+
};
|
|
147
|
+
const run = async (name, rawArgs, auth) => {
|
|
148
|
+
const fn = getFn(name);
|
|
149
|
+
if (fn.__kind === 'query')
|
|
150
|
+
return runQuery(name, rawArgs, auth);
|
|
151
|
+
if (fn.__kind === 'mutation')
|
|
152
|
+
return runMutation(name, rawArgs, auth);
|
|
153
|
+
const ctx = {
|
|
154
|
+
auth,
|
|
155
|
+
runQuery: async (n, a = {}) => (await runQuery(n, a, auth)).result,
|
|
156
|
+
runMutation: async (n, a = {}) => (await runMutation(n, a, auth)).result,
|
|
157
|
+
};
|
|
158
|
+
return { result: await fn.handler(ctx, parseArgs(fn, rawArgs)), readTables: new Set() };
|
|
159
|
+
};
|
|
160
|
+
const subscribe = async (name, rawArgs, auth) => {
|
|
161
|
+
const initial = await runQuery(name, rawArgs, auth);
|
|
162
|
+
let tracked = initial.readTables;
|
|
163
|
+
let lastJson = JSON.stringify(initial.result);
|
|
164
|
+
const encoder = new TextEncoder();
|
|
165
|
+
let cleanup = null;
|
|
166
|
+
let running = false;
|
|
167
|
+
let queued = false;
|
|
168
|
+
const stream = new ReadableStream({
|
|
169
|
+
start(controller) {
|
|
170
|
+
const send = (chunk) => {
|
|
171
|
+
try {
|
|
172
|
+
controller.enqueue(encoder.encode(chunk));
|
|
173
|
+
}
|
|
174
|
+
catch {
|
|
175
|
+
cleanup?.();
|
|
176
|
+
}
|
|
177
|
+
};
|
|
178
|
+
send(`event: data\ndata: ${lastJson}\n\n`);
|
|
179
|
+
const refresh = async () => {
|
|
180
|
+
if (running) {
|
|
181
|
+
queued = true;
|
|
182
|
+
return;
|
|
183
|
+
}
|
|
184
|
+
running = true;
|
|
185
|
+
try {
|
|
186
|
+
const next = await runQuery(name, rawArgs, auth);
|
|
187
|
+
tracked = next.readTables;
|
|
188
|
+
const nextJson = JSON.stringify(next.result);
|
|
189
|
+
if (nextJson !== lastJson) {
|
|
190
|
+
lastJson = nextJson;
|
|
191
|
+
send(`event: data\ndata: ${nextJson}\n\n`);
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
catch (err) {
|
|
195
|
+
send(`event: error\ndata: ${JSON.stringify({ error: err instanceof Error ? err.message : 'Query failed.' })}\n\n`);
|
|
196
|
+
}
|
|
197
|
+
finally {
|
|
198
|
+
running = false;
|
|
199
|
+
if (queued) {
|
|
200
|
+
queued = false;
|
|
201
|
+
void refresh();
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
};
|
|
205
|
+
const unsub = broker.subscribe((ev) => {
|
|
206
|
+
if (tracked.size === 0 || tracked.has(ev.tableName))
|
|
207
|
+
void refresh();
|
|
208
|
+
});
|
|
209
|
+
const heartbeat = setInterval(() => send(': keep-alive\n\n'), 25_000);
|
|
210
|
+
cleanup = () => {
|
|
211
|
+
unsub();
|
|
212
|
+
clearInterval(heartbeat);
|
|
213
|
+
try {
|
|
214
|
+
controller.close();
|
|
215
|
+
}
|
|
216
|
+
catch { }
|
|
217
|
+
};
|
|
218
|
+
},
|
|
219
|
+
cancel() {
|
|
220
|
+
cleanup?.();
|
|
221
|
+
},
|
|
222
|
+
});
|
|
223
|
+
return new Response(stream, {
|
|
224
|
+
status: 200,
|
|
225
|
+
headers: {
|
|
226
|
+
'Content-Type': 'text/event-stream; charset=utf-8',
|
|
227
|
+
'Cache-Control': 'no-cache, no-transform',
|
|
228
|
+
Connection: 'keep-alive',
|
|
229
|
+
'X-Accel-Buffering': 'no',
|
|
230
|
+
},
|
|
231
|
+
});
|
|
232
|
+
};
|
|
233
|
+
return {
|
|
234
|
+
list: () => [...registry.entries()].map(([name, def]) => ({ name, kind: def.__kind })),
|
|
235
|
+
run,
|
|
236
|
+
subscribe,
|
|
237
|
+
};
|
|
238
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
export class FunctionError extends Error {
|
|
2
|
+
status;
|
|
3
|
+
constructor(message, status = 400) {
|
|
4
|
+
super(message);
|
|
5
|
+
this.status = status;
|
|
6
|
+
}
|
|
7
|
+
}
|
|
8
|
+
export function defineQuery(def) {
|
|
9
|
+
return { __kind: 'query', ...def };
|
|
10
|
+
}
|
|
11
|
+
export function defineMutation(def) {
|
|
12
|
+
return { __kind: 'mutation', ...def };
|
|
13
|
+
}
|
|
14
|
+
export function defineAction(def) {
|
|
15
|
+
return { __kind: 'action', ...def };
|
|
16
|
+
}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
export { defineSchema, normalizeSchema } from './schema.js';
|
|
2
|
+
export { defineRules } from './rules.js';
|
|
3
|
+
export { defineQuery, defineMutation, defineAction, FunctionError, } from './functions/index.js';
|
|
4
|
+
export { TableSyncStorage, ClientError, ForbiddenError } from './tableStorage.js';
|
|
5
|
+
export { createApp, createHttpServer } from './server.js';
|
|
6
|
+
export { loadSettings } from './config.js';
|
|
@@ -0,0 +1,254 @@
|
|
|
1
|
+
/** Framework tables. App tables come from schema.ts. */
|
|
2
|
+
export const MIGRATIONS = [
|
|
3
|
+
{
|
|
4
|
+
id: '0001_init',
|
|
5
|
+
mysql: [
|
|
6
|
+
`CREATE TABLE IF NOT EXISTS _server_sync_clock (
|
|
7
|
+
id INT PRIMARY KEY,
|
|
8
|
+
checkpoint BIGINT NOT NULL
|
|
9
|
+
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`,
|
|
10
|
+
`INSERT IGNORE INTO _server_sync_clock (id, checkpoint) VALUES (1, 0)`,
|
|
11
|
+
`CREATE TABLE IF NOT EXISTS _server_changes (
|
|
12
|
+
id BIGINT AUTO_INCREMENT PRIMARY KEY,
|
|
13
|
+
table_name VARCHAR(128) NOT NULL,
|
|
14
|
+
row_id VARCHAR(128) NOT NULL,
|
|
15
|
+
\`timestamp\` BIGINT NOT NULL,
|
|
16
|
+
INDEX idx_changes_ts (\`timestamp\`),
|
|
17
|
+
INDEX idx_changes_table_row (table_name, row_id)
|
|
18
|
+
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`,
|
|
19
|
+
`CREATE TABLE IF NOT EXISTS _lls_schema_state (
|
|
20
|
+
id INT PRIMARY KEY,
|
|
21
|
+
state LONGTEXT NOT NULL
|
|
22
|
+
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`,
|
|
23
|
+
`CREATE TABLE IF NOT EXISTS _local_auth_accounts (
|
|
24
|
+
id VARCHAR(64) NOT NULL PRIMARY KEY,
|
|
25
|
+
email VARCHAR(255) NOT NULL UNIQUE,
|
|
26
|
+
display_name VARCHAR(255) NULL,
|
|
27
|
+
password_hash VARCHAR(255) NOT NULL,
|
|
28
|
+
salt VARCHAR(128) NOT NULL,
|
|
29
|
+
iterations INT NOT NULL,
|
|
30
|
+
algorithm VARCHAR(64) NOT NULL,
|
|
31
|
+
failed_login_attempts INT NOT NULL DEFAULT 0,
|
|
32
|
+
locked_until BIGINT NULL,
|
|
33
|
+
token_version INT NOT NULL DEFAULT 1,
|
|
34
|
+
console_role VARCHAR(32) NULL,
|
|
35
|
+
console_active TINYINT(1) NOT NULL DEFAULT 0,
|
|
36
|
+
created_at BIGINT NOT NULL,
|
|
37
|
+
updated_at BIGINT NOT NULL
|
|
38
|
+
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`,
|
|
39
|
+
`CREATE TABLE IF NOT EXISTS _local_auth_reset_otps (
|
|
40
|
+
id VARCHAR(64) NOT NULL PRIMARY KEY,
|
|
41
|
+
user_id VARCHAR(64) NOT NULL,
|
|
42
|
+
email VARCHAR(255) NOT NULL,
|
|
43
|
+
otp_hash VARCHAR(128) NOT NULL,
|
|
44
|
+
attempts INT NOT NULL DEFAULT 0,
|
|
45
|
+
expires_at BIGINT NOT NULL,
|
|
46
|
+
used_at BIGINT NULL,
|
|
47
|
+
created_at BIGINT NOT NULL,
|
|
48
|
+
INDEX idx_otps_email (email)
|
|
49
|
+
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`,
|
|
50
|
+
`CREATE TABLE IF NOT EXISTS _lls_storage_buckets (
|
|
51
|
+
name VARCHAR(128) NOT NULL PRIMARY KEY,
|
|
52
|
+
visibility VARCHAR(16) NOT NULL DEFAULT 'private',
|
|
53
|
+
created_at BIGINT NOT NULL
|
|
54
|
+
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`,
|
|
55
|
+
`CREATE TABLE IF NOT EXISTS _lls_storage_files (
|
|
56
|
+
id VARCHAR(64) NOT NULL PRIMARY KEY,
|
|
57
|
+
storage_key VARCHAR(255) NOT NULL UNIQUE,
|
|
58
|
+
bucket VARCHAR(128) NOT NULL,
|
|
59
|
+
name VARCHAR(255) NOT NULL,
|
|
60
|
+
mime_type VARCHAR(128) NOT NULL,
|
|
61
|
+
size_bytes BIGINT NOT NULL,
|
|
62
|
+
created_at BIGINT NOT NULL,
|
|
63
|
+
INDEX idx_files_bucket (bucket)
|
|
64
|
+
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`,
|
|
65
|
+
`CREATE TABLE IF NOT EXISTS _lls_env_vars (
|
|
66
|
+
var_key VARCHAR(128) NOT NULL PRIMARY KEY,
|
|
67
|
+
var_value TEXT NOT NULL,
|
|
68
|
+
is_secret TINYINT(1) NOT NULL DEFAULT 0,
|
|
69
|
+
updated_at BIGINT NOT NULL
|
|
70
|
+
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`,
|
|
71
|
+
`CREATE TABLE IF NOT EXISTS _lls_backups (
|
|
72
|
+
id VARCHAR(64) NOT NULL PRIMARY KEY,
|
|
73
|
+
user_id VARCHAR(64) NOT NULL,
|
|
74
|
+
file_name VARCHAR(255) NOT NULL,
|
|
75
|
+
status VARCHAR(32) NOT NULL,
|
|
76
|
+
size_bytes BIGINT NOT NULL,
|
|
77
|
+
record_count INT NOT NULL,
|
|
78
|
+
created_at BIGINT NOT NULL
|
|
79
|
+
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`,
|
|
80
|
+
`CREATE TABLE IF NOT EXISTS _lls_crons (
|
|
81
|
+
job_key VARCHAR(128) NOT NULL PRIMARY KEY,
|
|
82
|
+
label VARCHAR(255) NOT NULL,
|
|
83
|
+
action_type VARCHAR(64) NOT NULL,
|
|
84
|
+
cron_expr VARCHAR(64) NOT NULL,
|
|
85
|
+
timezone VARCHAR(64) NOT NULL DEFAULT 'UTC',
|
|
86
|
+
enabled TINYINT(1) NOT NULL DEFAULT 1,
|
|
87
|
+
config_json TEXT NULL,
|
|
88
|
+
last_run_at BIGINT NULL,
|
|
89
|
+
last_status VARCHAR(32) NULL,
|
|
90
|
+
last_summary TEXT NULL
|
|
91
|
+
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`,
|
|
92
|
+
`CREATE TABLE IF NOT EXISTS _lls_rate_limits (
|
|
93
|
+
rate_key VARCHAR(128) NOT NULL PRIMARY KEY,
|
|
94
|
+
hits INT NOT NULL DEFAULT 0,
|
|
95
|
+
reset_at BIGINT NOT NULL
|
|
96
|
+
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`,
|
|
97
|
+
],
|
|
98
|
+
postgres: [
|
|
99
|
+
`CREATE TABLE IF NOT EXISTS _server_sync_clock (
|
|
100
|
+
id INT PRIMARY KEY,
|
|
101
|
+
checkpoint BIGINT NOT NULL
|
|
102
|
+
)`,
|
|
103
|
+
`INSERT INTO _server_sync_clock (id, checkpoint) VALUES (1, 0) ON CONFLICT (id) DO NOTHING`,
|
|
104
|
+
`CREATE TABLE IF NOT EXISTS _server_changes (
|
|
105
|
+
id BIGSERIAL PRIMARY KEY,
|
|
106
|
+
table_name VARCHAR(128) NOT NULL,
|
|
107
|
+
row_id VARCHAR(128) NOT NULL,
|
|
108
|
+
"timestamp" BIGINT NOT NULL
|
|
109
|
+
)`,
|
|
110
|
+
`CREATE INDEX IF NOT EXISTS idx_changes_ts ON _server_changes ("timestamp")`,
|
|
111
|
+
`CREATE INDEX IF NOT EXISTS idx_changes_table_row ON _server_changes (table_name, row_id)`,
|
|
112
|
+
`CREATE TABLE IF NOT EXISTS _lls_schema_state (
|
|
113
|
+
id INT PRIMARY KEY,
|
|
114
|
+
state TEXT NOT NULL
|
|
115
|
+
)`,
|
|
116
|
+
`CREATE TABLE IF NOT EXISTS _local_auth_accounts (
|
|
117
|
+
id VARCHAR(64) NOT NULL PRIMARY KEY,
|
|
118
|
+
email VARCHAR(255) NOT NULL UNIQUE,
|
|
119
|
+
display_name VARCHAR(255) NULL,
|
|
120
|
+
password_hash VARCHAR(255) NOT NULL,
|
|
121
|
+
salt VARCHAR(128) NOT NULL,
|
|
122
|
+
iterations INT NOT NULL,
|
|
123
|
+
algorithm VARCHAR(64) NOT NULL,
|
|
124
|
+
failed_login_attempts INT NOT NULL DEFAULT 0,
|
|
125
|
+
locked_until BIGINT NULL,
|
|
126
|
+
token_version INT NOT NULL DEFAULT 1,
|
|
127
|
+
console_role VARCHAR(32) NULL,
|
|
128
|
+
console_active BOOLEAN NOT NULL DEFAULT FALSE,
|
|
129
|
+
created_at BIGINT NOT NULL,
|
|
130
|
+
updated_at BIGINT NOT NULL
|
|
131
|
+
)`,
|
|
132
|
+
`CREATE TABLE IF NOT EXISTS _local_auth_reset_otps (
|
|
133
|
+
id VARCHAR(64) NOT NULL PRIMARY KEY,
|
|
134
|
+
user_id VARCHAR(64) NOT NULL,
|
|
135
|
+
email VARCHAR(255) NOT NULL,
|
|
136
|
+
otp_hash VARCHAR(128) NOT NULL,
|
|
137
|
+
attempts INT NOT NULL DEFAULT 0,
|
|
138
|
+
expires_at BIGINT NOT NULL,
|
|
139
|
+
used_at BIGINT NULL,
|
|
140
|
+
created_at BIGINT NOT NULL
|
|
141
|
+
)`,
|
|
142
|
+
`CREATE INDEX IF NOT EXISTS idx_otps_email ON _local_auth_reset_otps (email)`,
|
|
143
|
+
`CREATE TABLE IF NOT EXISTS _lls_storage_buckets (
|
|
144
|
+
name VARCHAR(128) NOT NULL PRIMARY KEY,
|
|
145
|
+
visibility VARCHAR(16) NOT NULL DEFAULT 'private',
|
|
146
|
+
created_at BIGINT NOT NULL
|
|
147
|
+
)`,
|
|
148
|
+
`CREATE TABLE IF NOT EXISTS _lls_storage_files (
|
|
149
|
+
id VARCHAR(64) NOT NULL PRIMARY KEY,
|
|
150
|
+
storage_key VARCHAR(255) NOT NULL UNIQUE,
|
|
151
|
+
bucket VARCHAR(128) NOT NULL,
|
|
152
|
+
name VARCHAR(255) NOT NULL,
|
|
153
|
+
mime_type VARCHAR(128) NOT NULL,
|
|
154
|
+
size_bytes BIGINT NOT NULL,
|
|
155
|
+
created_at BIGINT NOT NULL
|
|
156
|
+
)`,
|
|
157
|
+
`CREATE INDEX IF NOT EXISTS idx_files_bucket ON _lls_storage_files (bucket)`,
|
|
158
|
+
`CREATE TABLE IF NOT EXISTS _lls_env_vars (
|
|
159
|
+
var_key VARCHAR(128) NOT NULL PRIMARY KEY,
|
|
160
|
+
var_value TEXT NOT NULL,
|
|
161
|
+
is_secret BOOLEAN NOT NULL DEFAULT FALSE,
|
|
162
|
+
updated_at BIGINT NOT NULL
|
|
163
|
+
)`,
|
|
164
|
+
`CREATE TABLE IF NOT EXISTS _lls_backups (
|
|
165
|
+
id VARCHAR(64) NOT NULL PRIMARY KEY,
|
|
166
|
+
user_id VARCHAR(64) NOT NULL,
|
|
167
|
+
file_name VARCHAR(255) NOT NULL,
|
|
168
|
+
status VARCHAR(32) NOT NULL,
|
|
169
|
+
size_bytes BIGINT NOT NULL,
|
|
170
|
+
record_count INT NOT NULL,
|
|
171
|
+
created_at BIGINT NOT NULL
|
|
172
|
+
)`,
|
|
173
|
+
`CREATE TABLE IF NOT EXISTS _lls_crons (
|
|
174
|
+
job_key VARCHAR(128) NOT NULL PRIMARY KEY,
|
|
175
|
+
label VARCHAR(255) NOT NULL,
|
|
176
|
+
action_type VARCHAR(64) NOT NULL,
|
|
177
|
+
cron_expr VARCHAR(64) NOT NULL,
|
|
178
|
+
timezone VARCHAR(64) NOT NULL DEFAULT 'UTC',
|
|
179
|
+
enabled BOOLEAN NOT NULL DEFAULT TRUE,
|
|
180
|
+
config_json TEXT NULL,
|
|
181
|
+
last_run_at BIGINT NULL,
|
|
182
|
+
last_status VARCHAR(32) NULL,
|
|
183
|
+
last_summary TEXT NULL
|
|
184
|
+
)`,
|
|
185
|
+
`CREATE TABLE IF NOT EXISTS _lls_rate_limits (
|
|
186
|
+
rate_key VARCHAR(128) NOT NULL PRIMARY KEY,
|
|
187
|
+
hits INT NOT NULL DEFAULT 0,
|
|
188
|
+
reset_at BIGINT NOT NULL
|
|
189
|
+
)`,
|
|
190
|
+
],
|
|
191
|
+
},
|
|
192
|
+
{
|
|
193
|
+
id: '0002_api_keys',
|
|
194
|
+
mysql: [
|
|
195
|
+
`CREATE TABLE IF NOT EXISTS _lls_api_keys (
|
|
196
|
+
id VARCHAR(64) NOT NULL PRIMARY KEY,
|
|
197
|
+
name VARCHAR(128) NOT NULL,
|
|
198
|
+
key_prefix VARCHAR(24) NOT NULL,
|
|
199
|
+
key_hash VARCHAR(128) NOT NULL UNIQUE,
|
|
200
|
+
role VARCHAR(16) NOT NULL DEFAULT 'admin',
|
|
201
|
+
user_id VARCHAR(64) NULL,
|
|
202
|
+
created_by VARCHAR(64) NULL,
|
|
203
|
+
last_used_at BIGINT NULL,
|
|
204
|
+
expires_at BIGINT NULL,
|
|
205
|
+
revoked_at BIGINT NULL,
|
|
206
|
+
created_at BIGINT NOT NULL
|
|
207
|
+
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`,
|
|
208
|
+
],
|
|
209
|
+
postgres: [
|
|
210
|
+
`CREATE TABLE IF NOT EXISTS _lls_api_keys (
|
|
211
|
+
id VARCHAR(64) NOT NULL PRIMARY KEY,
|
|
212
|
+
name VARCHAR(128) NOT NULL,
|
|
213
|
+
key_prefix VARCHAR(24) NOT NULL,
|
|
214
|
+
key_hash VARCHAR(128) NOT NULL UNIQUE,
|
|
215
|
+
role VARCHAR(16) NOT NULL DEFAULT 'admin',
|
|
216
|
+
user_id VARCHAR(64) NULL,
|
|
217
|
+
created_by VARCHAR(64) NULL,
|
|
218
|
+
last_used_at BIGINT NULL,
|
|
219
|
+
expires_at BIGINT NULL,
|
|
220
|
+
revoked_at BIGINT NULL,
|
|
221
|
+
created_at BIGINT NOT NULL
|
|
222
|
+
)`,
|
|
223
|
+
],
|
|
224
|
+
},
|
|
225
|
+
];
|
|
226
|
+
export async function runMigrations(db) {
|
|
227
|
+
await db.execute(db.dialect === 'postgres'
|
|
228
|
+
? `CREATE TABLE IF NOT EXISTS _lls_migrations (id VARCHAR(128) PRIMARY KEY, applied_at BIGINT NOT NULL)`
|
|
229
|
+
: `CREATE TABLE IF NOT EXISTS _lls_migrations (id VARCHAR(128) PRIMARY KEY, applied_at BIGINT NOT NULL) ENGINE=InnoDB`);
|
|
230
|
+
const done = new Set((await db.query('SELECT id FROM _lls_migrations')).map((r) => r.id));
|
|
231
|
+
const applied = [];
|
|
232
|
+
for (const m of MIGRATIONS) {
|
|
233
|
+
if (done.has(m.id))
|
|
234
|
+
continue;
|
|
235
|
+
for (const stmt of m[db.dialect])
|
|
236
|
+
await db.execute(stmt);
|
|
237
|
+
await db.execute('INSERT INTO _lls_migrations (id, applied_at) VALUES (?, ?)', [m.id, Date.now()]);
|
|
238
|
+
applied.push(m.id);
|
|
239
|
+
}
|
|
240
|
+
return { applied };
|
|
241
|
+
}
|
|
242
|
+
export async function coreMigrationStatus(db) {
|
|
243
|
+
try {
|
|
244
|
+
const rows = await db.query('SELECT id FROM _lls_migrations');
|
|
245
|
+
const done = new Set(rows.map((r) => r.id));
|
|
246
|
+
return {
|
|
247
|
+
applied: MIGRATIONS.filter((m) => done.has(m.id)).map((m) => m.id),
|
|
248
|
+
pending: MIGRATIONS.filter((m) => !done.has(m.id)).map((m) => m.id),
|
|
249
|
+
};
|
|
250
|
+
}
|
|
251
|
+
catch {
|
|
252
|
+
return { applied: [], pending: MIGRATIONS.map((m) => m.id) };
|
|
253
|
+
}
|
|
254
|
+
}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
/** Fixed-window in-memory limiter, keyed per client IP. */
|
|
2
|
+
export function createRateLimiter(max, windowMs) {
|
|
3
|
+
const buckets = new Map();
|
|
4
|
+
return (key, now = Date.now()) => {
|
|
5
|
+
const b = buckets.get(key);
|
|
6
|
+
if (!b || b.resetAt <= now) {
|
|
7
|
+
if (buckets.size > 5000)
|
|
8
|
+
buckets.clear();
|
|
9
|
+
buckets.set(key, { count: 1, resetAt: now + windowMs });
|
|
10
|
+
return { ok: true };
|
|
11
|
+
}
|
|
12
|
+
b.count += 1;
|
|
13
|
+
if (b.count > max)
|
|
14
|
+
return { ok: false, retryAfter: Math.max(1, Math.ceil((b.resetAt - now) / 1000)) };
|
|
15
|
+
return { ok: true };
|
|
16
|
+
};
|
|
17
|
+
}
|
|
18
|
+
/** DB-backed limiter for multi-instance deployments, with in-memory fallback. */
|
|
19
|
+
export function createDistributedRateLimiter(db, max, windowMs, enabled = false) {
|
|
20
|
+
const memory = createRateLimiter(max, windowMs);
|
|
21
|
+
if (!enabled)
|
|
22
|
+
return async (key, now = Date.now()) => memory(key, now);
|
|
23
|
+
return async (key, now = Date.now()) => {
|
|
24
|
+
try {
|
|
25
|
+
return await db.withTransaction(async (tx) => {
|
|
26
|
+
const rows = await tx.query('SELECT hits, reset_at FROM _lls_rate_limits WHERE rate_key = ? LIMIT 1', [key]);
|
|
27
|
+
const existing = rows[0];
|
|
28
|
+
if (!existing || Number(existing.reset_at) <= now) {
|
|
29
|
+
const resetAt = now + windowMs;
|
|
30
|
+
await tx.execute(tx.dialect === 'postgres'
|
|
31
|
+
? 'INSERT INTO _lls_rate_limits (rate_key, hits, reset_at) VALUES (?, 1, ?) ON CONFLICT (rate_key) DO UPDATE SET hits = 1, reset_at = EXCLUDED.reset_at'
|
|
32
|
+
: 'INSERT INTO _lls_rate_limits (rate_key, hits, reset_at) VALUES (?, 1, ?) ON DUPLICATE KEY UPDATE hits = 1, reset_at = VALUES(reset_at)', [key, resetAt]);
|
|
33
|
+
return { ok: true };
|
|
34
|
+
}
|
|
35
|
+
const nextHits = Number(existing.hits) + 1;
|
|
36
|
+
await tx.execute('UPDATE _lls_rate_limits SET hits = ? WHERE rate_key = ?', [nextHits, key]);
|
|
37
|
+
if (nextHits > max) {
|
|
38
|
+
return {
|
|
39
|
+
ok: false,
|
|
40
|
+
retryAfter: Math.max(1, Math.ceil((Number(existing.reset_at) - now) / 1000)),
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
return { ok: true };
|
|
44
|
+
});
|
|
45
|
+
}
|
|
46
|
+
catch {
|
|
47
|
+
return memory(key, now);
|
|
48
|
+
}
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
export function clientIp(request) {
|
|
52
|
+
const fwd = request.headers.get('x-forwarded-for')?.split(',')[0]?.trim();
|
|
53
|
+
return fwd || request.headers.get('x-real-ip') || 'unknown';
|
|
54
|
+
}
|
package/dist/rules.js
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { pathToFileURL } from 'node:url';
|
|
4
|
+
function compileRule(expr) {
|
|
5
|
+
if (!expr)
|
|
6
|
+
return undefined;
|
|
7
|
+
if (typeof expr === 'function')
|
|
8
|
+
return expr;
|
|
9
|
+
if (expr === 'authenticated')
|
|
10
|
+
return (ctx) => ctx.isAdmin || Boolean(ctx.userId);
|
|
11
|
+
if (expr === 'admin')
|
|
12
|
+
return (ctx) => ctx.isAdmin;
|
|
13
|
+
if (expr === 'none')
|
|
14
|
+
return () => false;
|
|
15
|
+
if (expr === 'owner') {
|
|
16
|
+
return (ctx, row) => ctx.isAdmin ||
|
|
17
|
+
(Boolean(ctx.userId) &&
|
|
18
|
+
(row.owner_id != null ? row.owner_id === ctx.userId : row.user_id === ctx.userId));
|
|
19
|
+
}
|
|
20
|
+
if (expr.startsWith('owner:')) {
|
|
21
|
+
const col = expr.slice(6).trim();
|
|
22
|
+
return (ctx, row) => ctx.isAdmin || (Boolean(ctx.userId) && row[col] === ctx.userId);
|
|
23
|
+
}
|
|
24
|
+
throw new Error(`Unknown rule preset "${String(expr)}".`);
|
|
25
|
+
}
|
|
26
|
+
export function normalizeRules(input) {
|
|
27
|
+
const out = {};
|
|
28
|
+
for (const [table, entry] of Object.entries(input)) {
|
|
29
|
+
if (!entry)
|
|
30
|
+
continue;
|
|
31
|
+
if (typeof entry === 'string') {
|
|
32
|
+
const fn = compileRule(entry);
|
|
33
|
+
out[table] = { read: fn, write: fn, delete: fn };
|
|
34
|
+
}
|
|
35
|
+
else {
|
|
36
|
+
out[table] = {
|
|
37
|
+
read: compileRule(entry.read),
|
|
38
|
+
write: compileRule(entry.write),
|
|
39
|
+
delete: compileRule(entry.delete),
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
return out;
|
|
44
|
+
}
|
|
45
|
+
export function defineRules(rules) {
|
|
46
|
+
return normalizeRules(rules);
|
|
47
|
+
}
|
|
48
|
+
const CANDIDATES = ['src/rules.ts', 'rules.ts'];
|
|
49
|
+
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;
|
|
65
|
+
}
|
|
66
|
+
export async function loadRulesFile(file) {
|
|
67
|
+
const loaded = await import(pathToFileURL(file).href);
|
|
68
|
+
const mod = loaded.default ?? loaded.rules ?? loaded;
|
|
69
|
+
if (!mod || typeof mod !== 'object' || Array.isArray(mod)) {
|
|
70
|
+
throw new Error(`${file} must export default an object of { table: { read?, write?, delete? } }.`);
|
|
71
|
+
}
|
|
72
|
+
return normalizeRules(mod);
|
|
73
|
+
}
|