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/storage.js
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import { buildUpsertSql, createStorageEndpoint, } from 'local-lite/server';
|
|
2
|
+
export function createSqlStorageMetadata(db) {
|
|
3
|
+
return {
|
|
4
|
+
async getBucket(name) {
|
|
5
|
+
const rows = await db.query('SELECT * FROM _lls_storage_buckets WHERE name = ? LIMIT 1', [name]);
|
|
6
|
+
if (!rows[0])
|
|
7
|
+
return null;
|
|
8
|
+
return {
|
|
9
|
+
id: String(rows[0].name),
|
|
10
|
+
name: String(rows[0].name),
|
|
11
|
+
visibility: rows[0].visibility === 'public' ? 'public' : 'private',
|
|
12
|
+
createdAt: Number(rows[0].created_at),
|
|
13
|
+
};
|
|
14
|
+
},
|
|
15
|
+
async listBuckets() {
|
|
16
|
+
const rows = await db.query('SELECT * FROM _lls_storage_buckets ORDER BY name ASC');
|
|
17
|
+
return rows.map((r) => ({
|
|
18
|
+
id: String(r.name),
|
|
19
|
+
name: String(r.name),
|
|
20
|
+
visibility: r.visibility === 'public' ? 'public' : 'private',
|
|
21
|
+
createdAt: Number(r.created_at),
|
|
22
|
+
}));
|
|
23
|
+
},
|
|
24
|
+
async createBucket(bucket) {
|
|
25
|
+
await db.execute(buildUpsertSql({
|
|
26
|
+
table: '_lls_storage_buckets',
|
|
27
|
+
conflictCols: ['name'],
|
|
28
|
+
insertCols: ['name', 'visibility', 'created_at'],
|
|
29
|
+
updateCols: ['visibility'],
|
|
30
|
+
dialect: db.dialect,
|
|
31
|
+
}), [bucket.name, bucket.visibility, bucket.createdAt ?? Date.now()]);
|
|
32
|
+
},
|
|
33
|
+
async deleteBucket(name) {
|
|
34
|
+
await db.execute('DELETE FROM _lls_storage_buckets WHERE name = ?', [name]);
|
|
35
|
+
},
|
|
36
|
+
async countFilesInBucket(bucket) {
|
|
37
|
+
const rows = await db.query('SELECT COUNT(*) AS n FROM _lls_storage_files WHERE bucket = ?', [bucket]);
|
|
38
|
+
return Number(rows[0]?.n ?? 0);
|
|
39
|
+
},
|
|
40
|
+
async upsertFile(file) {
|
|
41
|
+
await db.execute(buildUpsertSql({
|
|
42
|
+
table: '_lls_storage_files',
|
|
43
|
+
conflictCols: ['storage_key'],
|
|
44
|
+
insertCols: ['id', 'storage_key', 'bucket', 'name', 'mime_type', 'size_bytes', 'created_at'],
|
|
45
|
+
updateCols: ['bucket', 'name', 'mime_type', 'size_bytes'],
|
|
46
|
+
dialect: db.dialect,
|
|
47
|
+
}), [file.id, file.storageKey, file.bucket, file.name, file.mimeType, file.sizeBytes, file.createdAt]);
|
|
48
|
+
},
|
|
49
|
+
async getFile(storageKey, bucket) {
|
|
50
|
+
const rows = bucket
|
|
51
|
+
? await db.query('SELECT * FROM _lls_storage_files WHERE storage_key = ? AND bucket = ? LIMIT 1', [storageKey, bucket])
|
|
52
|
+
: await db.query('SELECT * FROM _lls_storage_files WHERE storage_key = ? LIMIT 1', [storageKey]);
|
|
53
|
+
const r = rows[0];
|
|
54
|
+
if (!r)
|
|
55
|
+
return null;
|
|
56
|
+
return {
|
|
57
|
+
id: String(r.id),
|
|
58
|
+
storageKey: String(r.storage_key),
|
|
59
|
+
bucket: String(r.bucket),
|
|
60
|
+
name: String(r.name),
|
|
61
|
+
mimeType: String(r.mime_type),
|
|
62
|
+
sizeBytes: Number(r.size_bytes),
|
|
63
|
+
createdAt: Number(r.created_at),
|
|
64
|
+
};
|
|
65
|
+
},
|
|
66
|
+
async updateFileBucket(storageKey, toBucket) {
|
|
67
|
+
await db.execute('UPDATE _lls_storage_files SET bucket = ? WHERE storage_key = ?', [toBucket, storageKey]);
|
|
68
|
+
},
|
|
69
|
+
async deleteFile(storageKey) {
|
|
70
|
+
await db.execute('DELETE FROM _lls_storage_files WHERE storage_key = ?', [storageKey]);
|
|
71
|
+
},
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
export function createStorageHandler(settings, db, authenticate) {
|
|
75
|
+
return createStorageEndpoint({
|
|
76
|
+
uploadDir: settings.uploadDir,
|
|
77
|
+
signingSecret: settings.appSecret || settings.apiKey,
|
|
78
|
+
metadata: createSqlStorageMetadata(db),
|
|
79
|
+
authenticate,
|
|
80
|
+
basePath: '/storage',
|
|
81
|
+
});
|
|
82
|
+
}
|
|
@@ -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 {};
|
|
@@ -0,0 +1,261 @@
|
|
|
1
|
+
import { quoteIdent, } from 'local-lite/server';
|
|
2
|
+
import { appendChangeLog, commitClock, lockClock, setRowDeleted, upsertTableRow, } from './core/changes.js';
|
|
3
|
+
/** Thrown for bad client input; the HTTP layer maps it to 400. */
|
|
4
|
+
export class ClientError extends Error {
|
|
5
|
+
}
|
|
6
|
+
/** Thrown when a row-level access rule rejects the operation; mapped to 403. */
|
|
7
|
+
export class ForbiddenError extends Error {
|
|
8
|
+
}
|
|
9
|
+
const MAX_BATCH = 1000;
|
|
10
|
+
const baseType = (t) => t.replace(' | null', '');
|
|
11
|
+
/** Client value -> DB parameter. */
|
|
12
|
+
export function toDbValue(type, value, dialect) {
|
|
13
|
+
if (value === undefined || value === null)
|
|
14
|
+
return null;
|
|
15
|
+
switch (baseType(type)) {
|
|
16
|
+
case 'boolean':
|
|
17
|
+
return dialect === 'postgres' ? Boolean(value) : value ? 1 : 0;
|
|
18
|
+
case 'number':
|
|
19
|
+
return Number(value);
|
|
20
|
+
case 'json':
|
|
21
|
+
case 'string[]':
|
|
22
|
+
return typeof value === 'string' ? value : JSON.stringify(value);
|
|
23
|
+
default:
|
|
24
|
+
return typeof value === 'string' ? value : String(value);
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
/** DB row -> client payload. */
|
|
28
|
+
export function fromDbRow(fields, row) {
|
|
29
|
+
const out = {};
|
|
30
|
+
for (const [col, type] of Object.entries(fields)) {
|
|
31
|
+
const v = row[col];
|
|
32
|
+
if (v === undefined)
|
|
33
|
+
continue;
|
|
34
|
+
if (v === null) {
|
|
35
|
+
out[col] = null;
|
|
36
|
+
continue;
|
|
37
|
+
}
|
|
38
|
+
switch (baseType(type)) {
|
|
39
|
+
case 'boolean':
|
|
40
|
+
out[col] = Boolean(v);
|
|
41
|
+
break;
|
|
42
|
+
case 'number':
|
|
43
|
+
out[col] = Number(v);
|
|
44
|
+
break;
|
|
45
|
+
case 'json':
|
|
46
|
+
case 'string[]':
|
|
47
|
+
if (typeof v === 'string') {
|
|
48
|
+
try {
|
|
49
|
+
out[col] = JSON.parse(v);
|
|
50
|
+
}
|
|
51
|
+
catch {
|
|
52
|
+
out[col] = v;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
else
|
|
56
|
+
out[col] = v;
|
|
57
|
+
break;
|
|
58
|
+
default:
|
|
59
|
+
out[col] = v;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
out.deleted = Boolean(row.deleted);
|
|
63
|
+
out.updated_at = Number(row.updated_at ?? 0);
|
|
64
|
+
return out;
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* Stores every synced table as a real SQL table. `_server_changes` keeps only
|
|
68
|
+
* (table_name, row_id, timestamp) as a monotonic cursor/event log.
|
|
69
|
+
*/
|
|
70
|
+
export class TableSyncStorage {
|
|
71
|
+
db;
|
|
72
|
+
schema;
|
|
73
|
+
rules;
|
|
74
|
+
broker;
|
|
75
|
+
changes;
|
|
76
|
+
clock;
|
|
77
|
+
scopeField;
|
|
78
|
+
constructor(db, opts) {
|
|
79
|
+
this.db = db;
|
|
80
|
+
this.schema = opts.schema;
|
|
81
|
+
this.rules = opts.rules ?? {};
|
|
82
|
+
this.broker = opts.broker;
|
|
83
|
+
this.changes = opts.changesTable ?? '_server_changes';
|
|
84
|
+
this.clock = opts.clockTable ?? '_server_sync_clock';
|
|
85
|
+
this.scopeField = opts.scopeField ?? 'scope_id';
|
|
86
|
+
}
|
|
87
|
+
get tables() {
|
|
88
|
+
return Object.keys(this.schema);
|
|
89
|
+
}
|
|
90
|
+
q = (name) => quoteIdent(name, this.db.dialect);
|
|
91
|
+
fields(table) {
|
|
92
|
+
const f = Object.hasOwn(this.schema, table) ? this.schema[table] : undefined;
|
|
93
|
+
if (!f)
|
|
94
|
+
throw new ClientError(`Unknown table "${table}".`);
|
|
95
|
+
return f;
|
|
96
|
+
}
|
|
97
|
+
async applyOperations(operations, _serverTime, auth = { isAdmin: true }) {
|
|
98
|
+
if (operations.length > MAX_BATCH)
|
|
99
|
+
throw new ClientError('Batch is too large.');
|
|
100
|
+
const emitted = [];
|
|
101
|
+
const successfulIds = [];
|
|
102
|
+
let cursor = 0;
|
|
103
|
+
await this.db.withTransaction(async (tx) => {
|
|
104
|
+
cursor = await lockClock(tx, this.clock);
|
|
105
|
+
// Prefetch existing rows in batches for any table with a write RLS rule.
|
|
106
|
+
const existingByKey = new Map();
|
|
107
|
+
if (!auth.isAdmin) {
|
|
108
|
+
const idsByTable = new Map();
|
|
109
|
+
for (const op of operations) {
|
|
110
|
+
if (!op || typeof op.rowId !== 'string' || !op.rowId || op.rowId.length > 128) {
|
|
111
|
+
throw new ClientError('Each operation needs a rowId string (max 128 chars).');
|
|
112
|
+
}
|
|
113
|
+
this.fields(op.tableName);
|
|
114
|
+
const tableRule = this.rules[op.tableName];
|
|
115
|
+
const needsCheck = op.operation === 'DELETE' ? (tableRule?.delete ?? tableRule?.write) : tableRule?.write;
|
|
116
|
+
if (needsCheck) {
|
|
117
|
+
const set = idsByTable.get(op.tableName) ?? new Set();
|
|
118
|
+
set.add(op.rowId);
|
|
119
|
+
idsByTable.set(op.tableName, set);
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
for (const [table, idSet] of idsByTable) {
|
|
123
|
+
const fields = this.fields(table);
|
|
124
|
+
const ids = [...idSet];
|
|
125
|
+
for (let i = 0; i < ids.length; i += 400) {
|
|
126
|
+
const chunk = ids.slice(i, i + 400);
|
|
127
|
+
const found = await tx.query(`SELECT * FROM ${this.q(table)} WHERE ${this.q('id')} IN (${chunk.map(() => '?').join(', ')})`, chunk);
|
|
128
|
+
for (const r of found) {
|
|
129
|
+
existingByKey.set(`${table}\u0000${r.id}`, {
|
|
130
|
+
id: String(r.id),
|
|
131
|
+
...fromDbRow(fields, r),
|
|
132
|
+
});
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
for (const op of operations) {
|
|
138
|
+
if (!op || typeof op.rowId !== 'string' || !op.rowId || op.rowId.length > 128) {
|
|
139
|
+
throw new ClientError('Each operation needs a rowId string (max 128 chars).');
|
|
140
|
+
}
|
|
141
|
+
const fields = this.fields(op.tableName);
|
|
142
|
+
const payload = op.payload && typeof op.payload === 'object' ? op.payload : {};
|
|
143
|
+
const tableRule = !auth.isAdmin ? this.rules[op.tableName] : undefined;
|
|
144
|
+
const writeRule = op.operation === 'DELETE' ? (tableRule?.delete ?? tableRule?.write) : tableRule?.write;
|
|
145
|
+
if (writeRule) {
|
|
146
|
+
const existing = existingByKey.get(`${op.tableName}\u0000${op.rowId}`);
|
|
147
|
+
if (existing) {
|
|
148
|
+
if (!(await writeRule(auth, existing))) {
|
|
149
|
+
throw new ForbiddenError(`Write denied on ${op.tableName}/${op.rowId}.`);
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
else if (op.operation === 'DELETE') {
|
|
153
|
+
if (!(await writeRule(auth, { id: op.rowId, ...payload }))) {
|
|
154
|
+
throw new ForbiddenError(`Delete denied on ${op.tableName}/${op.rowId}.`);
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
if (op.operation !== 'DELETE') {
|
|
158
|
+
if (!(await writeRule(auth, { id: op.rowId, ...payload }))) {
|
|
159
|
+
throw new ForbiddenError(`Write denied on ${op.tableName}/${op.rowId}.`);
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
cursor = Math.max(Date.now(), cursor + 1);
|
|
164
|
+
if (op.operation === 'DELETE') {
|
|
165
|
+
await setRowDeleted(tx, op.tableName, op.rowId, true, cursor);
|
|
166
|
+
}
|
|
167
|
+
else {
|
|
168
|
+
await upsertTableRow(tx, op.tableName, fields, op.rowId, payload, cursor);
|
|
169
|
+
existingByKey.set(`${op.tableName}\u0000${op.rowId}`, { id: op.rowId, ...payload });
|
|
170
|
+
}
|
|
171
|
+
await appendChangeLog(tx, op.tableName, op.rowId, cursor, this.changes);
|
|
172
|
+
const scope = payload[this.scopeField];
|
|
173
|
+
emitted.push({
|
|
174
|
+
scopeId: typeof scope === 'string' && scope ? scope : 'default',
|
|
175
|
+
tableName: op.tableName,
|
|
176
|
+
checkpoint: cursor,
|
|
177
|
+
});
|
|
178
|
+
successfulIds.push(op.id);
|
|
179
|
+
}
|
|
180
|
+
if (operations.length > 0) {
|
|
181
|
+
await commitClock(tx, cursor, this.clock);
|
|
182
|
+
}
|
|
183
|
+
});
|
|
184
|
+
for (const e of emitted)
|
|
185
|
+
this.broker?.publish(e);
|
|
186
|
+
return { applied: successfulIds.length, successfulIds, serverTime: Date.now(), cursor };
|
|
187
|
+
}
|
|
188
|
+
async getDeltas(tables, since, limit = 500, auth = { isAdmin: true }) {
|
|
189
|
+
const names = tables.length ? tables : this.tables;
|
|
190
|
+
for (const t of names)
|
|
191
|
+
this.fields(t);
|
|
192
|
+
const checkpoint = Number.isFinite(since) && since >= 0 ? Math.floor(since) : 0;
|
|
193
|
+
const safeLimit = Math.max(1, Math.min(2000, Math.floor(Number(limit) || 500)));
|
|
194
|
+
const empty = {
|
|
195
|
+
changes: { timestamp: checkpoint, changes: [] },
|
|
196
|
+
cursor: checkpoint,
|
|
197
|
+
hasMore: false,
|
|
198
|
+
serverTime: Date.now(),
|
|
199
|
+
};
|
|
200
|
+
if (!names.length)
|
|
201
|
+
return empty;
|
|
202
|
+
const raw = await this.db.query(`SELECT table_name, row_id, ${this.q('timestamp')} AS ts FROM ${this.q(this.changes)} ` +
|
|
203
|
+
`WHERE ${this.q('timestamp')} > ? AND table_name IN (${names.map(() => '?').join(', ')}) ` +
|
|
204
|
+
`ORDER BY ${this.q('timestamp')} ASC LIMIT ${safeLimit + 1}`, [checkpoint, ...names]);
|
|
205
|
+
const hasMore = raw.length > safeLimit;
|
|
206
|
+
const page = hasMore ? raw.slice(0, safeLimit) : raw;
|
|
207
|
+
if (!page.length)
|
|
208
|
+
return empty;
|
|
209
|
+
// Collapse repeated edits of one row to its latest change.
|
|
210
|
+
const latest = new Map();
|
|
211
|
+
for (const c of page) {
|
|
212
|
+
const key = `${c.table_name}\u0000${c.row_id}`;
|
|
213
|
+
latest.delete(key);
|
|
214
|
+
latest.set(key, { table: c.table_name, id: String(c.row_id), ts: Number(c.ts) });
|
|
215
|
+
}
|
|
216
|
+
const byTable = new Map();
|
|
217
|
+
for (const e of latest.values()) {
|
|
218
|
+
const ids = byTable.get(e.table) ?? [];
|
|
219
|
+
ids.push(e.id);
|
|
220
|
+
byTable.set(e.table, ids);
|
|
221
|
+
}
|
|
222
|
+
const rows = new Map();
|
|
223
|
+
for (const [table, ids] of byTable) {
|
|
224
|
+
for (let i = 0; i < ids.length; i += 400) {
|
|
225
|
+
const chunk = ids.slice(i, i + 400);
|
|
226
|
+
const found = await this.db.query(`SELECT * FROM ${this.q(table)} WHERE ${this.q('id')} IN (${chunk.map(() => '?').join(', ')})`, chunk);
|
|
227
|
+
for (const r of found)
|
|
228
|
+
rows.set(`${table}\u0000${r.id}`, r);
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
const allChanges = [...latest.values()].map((e) => {
|
|
232
|
+
const row = rows.get(`${e.table}\u0000${e.id}`);
|
|
233
|
+
const gone = !row || Boolean(row.deleted);
|
|
234
|
+
return {
|
|
235
|
+
tableName: e.table,
|
|
236
|
+
rowId: e.id,
|
|
237
|
+
operation: gone ? 'DELETE' : 'UPDATE',
|
|
238
|
+
payload: row ? fromDbRow(this.fields(e.table), row) : null,
|
|
239
|
+
timestamp: e.ts,
|
|
240
|
+
};
|
|
241
|
+
});
|
|
242
|
+
const changes = [];
|
|
243
|
+
for (const c of allChanges) {
|
|
244
|
+
const readRule = !auth.isAdmin ? this.rules[c.tableName]?.read : undefined;
|
|
245
|
+
if (!readRule) {
|
|
246
|
+
changes.push(c);
|
|
247
|
+
continue;
|
|
248
|
+
}
|
|
249
|
+
const subject = { id: c.rowId, ...(c.payload ?? { deleted: true }) };
|
|
250
|
+
if (await readRule(auth, subject))
|
|
251
|
+
changes.push(c);
|
|
252
|
+
}
|
|
253
|
+
const cursor = Number(page[page.length - 1].ts);
|
|
254
|
+
return {
|
|
255
|
+
changes: { timestamp: cursor, changes },
|
|
256
|
+
cursor,
|
|
257
|
+
hasMore,
|
|
258
|
+
serverTime: Date.now(),
|
|
259
|
+
};
|
|
260
|
+
}
|
|
261
|
+
}
|
package/docs/api.md
ADDED
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
# HTTP & SSE API Reference
|
|
2
|
+
|
|
3
|
+
All JSON endpoints accept and return `application/json` (max body size: `6 MB`).
|
|
4
|
+
|
|
5
|
+
## Authentication
|
|
6
|
+
|
|
7
|
+
Endpoints use one of three credentials:
|
|
8
|
+
- **Admin API Key:** `Authorization: Bearer <SERVER_API_KEY>` (full access, bypasses RLS).
|
|
9
|
+
- **User JWT** *(when `APP_SECRET` is set)*: `Authorization: Bearer <jwt>` (or `?token=<jwt>` for `EventSource` SSE routes). Subject to `src/rules.ts` RLS on `/sync`.
|
|
10
|
+
- **Admin Session Cookie:** `lls_admin_session` (HTTP-only cookie set by `POST /admin/login`).
|
|
11
|
+
|
|
12
|
+
---
|
|
13
|
+
|
|
14
|
+
## Health
|
|
15
|
+
|
|
16
|
+
### `GET /health`
|
|
17
|
+
Public health check (no auth required).
|
|
18
|
+
|
|
19
|
+
**Response `200`:**
|
|
20
|
+
```json
|
|
21
|
+
{ "ok": true, "dialect": "mysql" }
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
---
|
|
25
|
+
|
|
26
|
+
## Sync
|
|
27
|
+
|
|
28
|
+
### `GET /sync?tables=notes&since=0&limit=500`
|
|
29
|
+
Pull delta changes after `since` (monotonic cursor). `limit` is clamped to `1..2000`.
|
|
30
|
+
**Auth:** Admin key or User JWT.
|
|
31
|
+
|
|
32
|
+
**Response `200`:**
|
|
33
|
+
```json
|
|
34
|
+
{
|
|
35
|
+
"success": true,
|
|
36
|
+
"changes": {
|
|
37
|
+
"timestamp": 1732541000123,
|
|
38
|
+
"changes": [
|
|
39
|
+
{
|
|
40
|
+
"tableName": "notes",
|
|
41
|
+
"rowId": "n1",
|
|
42
|
+
"operation": "UPDATE",
|
|
43
|
+
"payload": { "title": "Hello", "deleted": false, "updated_at": 1732541000123 },
|
|
44
|
+
"timestamp": 1732541000123
|
|
45
|
+
}
|
|
46
|
+
]
|
|
47
|
+
},
|
|
48
|
+
"cursor": 1732541000123,
|
|
49
|
+
"hasMore": false,
|
|
50
|
+
"serverTime": 1732541000500
|
|
51
|
+
}
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
### `POST /sync`
|
|
55
|
+
Push up to `1000` operations atomically.
|
|
56
|
+
**Auth:** Admin key or User JWT.
|
|
57
|
+
|
|
58
|
+
**Body:**
|
|
59
|
+
```json
|
|
60
|
+
{
|
|
61
|
+
"operations": [
|
|
62
|
+
{
|
|
63
|
+
"id": "op-1",
|
|
64
|
+
"tableName": "notes",
|
|
65
|
+
"rowId": "n1",
|
|
66
|
+
"operation": "INSERT",
|
|
67
|
+
"payload": { "title": "Hello", "pinned": true },
|
|
68
|
+
"timestamp": 1732541000000
|
|
69
|
+
}
|
|
70
|
+
]
|
|
71
|
+
}
|
|
72
|
+
```
|
|
73
|
+
`operation` is `"INSERT" | "UPDATE" | "DELETE"`.
|
|
74
|
+
|
|
75
|
+
**Response `200`:**
|
|
76
|
+
```json
|
|
77
|
+
{
|
|
78
|
+
"success": true,
|
|
79
|
+
"processed": 1,
|
|
80
|
+
"applied": 1,
|
|
81
|
+
"successfulIds": ["op-1"],
|
|
82
|
+
"serverTime": 1732541000500,
|
|
83
|
+
"cursor": 1732541000123
|
|
84
|
+
}
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
### `GET /sync/events?token=<key_or_jwt>&scopeId=<scope>`
|
|
88
|
+
Server-Sent Events (SSE) stream emitting change notifications whenever tables are modified.
|
|
89
|
+
**Auth:** Admin key or User JWT (header or `?token=`).
|
|
90
|
+
|
|
91
|
+
---
|
|
92
|
+
|
|
93
|
+
## Server Functions
|
|
94
|
+
|
|
95
|
+
### `GET /fn`
|
|
96
|
+
List all loaded functions from `src/functions/` (or `functions/`).
|
|
97
|
+
**Auth:** Admin key, User JWT, or Admin cookie.
|
|
98
|
+
|
|
99
|
+
**Response `200`:**
|
|
100
|
+
```json
|
|
101
|
+
{
|
|
102
|
+
"functions": [
|
|
103
|
+
{ "name": "notes/list", "kind": "query" },
|
|
104
|
+
{ "name": "notes/create", "kind": "mutation" }
|
|
105
|
+
]
|
|
106
|
+
}
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
### `POST /fn/:module/:name`
|
|
110
|
+
Invoke a `query`, `mutation`, or `action`.
|
|
111
|
+
**Auth:** Admin key, User JWT, or Admin cookie.
|
|
112
|
+
|
|
113
|
+
**Body:** `{ "args": { ... } }` (or pass args at the top level).
|
|
114
|
+
**Response `200`:**
|
|
115
|
+
```json
|
|
116
|
+
{ "success": true, "result": ... }
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
### `GET /subscribe/:module/:name?args={}&token=<key_or_jwt>`
|
|
120
|
+
Reactive SSE stream for a `query` function. Sends an initial `event: data` frame, then re-runs and pushes updated `event: data` frames whenever any table read by the query changes.
|
|
121
|
+
**Auth:** Admin key, User JWT, or Admin cookie (`?token=` supported for `EventSource`).
|
|
122
|
+
|
|
123
|
+
---
|
|
124
|
+
|
|
125
|
+
## User Authentication (`/auth/*`)
|
|
126
|
+
|
|
127
|
+
Requires `APP_SECRET` to be set (otherwise returns `503`). Rate-limited to **20 requests / minute per IP**.
|
|
128
|
+
|
|
129
|
+
- **`POST /auth/signup`**: `{ "mode": "signup", "email", "password", "displayName"? }` → `200 { token, user }`
|
|
130
|
+
- **`POST /auth/signin`**: `{ "mode": "signin", "email", "password" }` → `200 { token, user }`
|
|
131
|
+
- **`POST /auth/refresh`**: `Authorization: Bearer <token>` → `200 { token }`
|
|
132
|
+
- **`POST /auth/forgot-password`**: `{ "email" }` → `200 { ok: true }` (sends 6-digit OTP via SMTP)
|
|
133
|
+
- **`POST /auth/reset-password`**: `{ "email", "otp", "newPassword" }` → `200 { success: true }`
|
|
134
|
+
|
|
135
|
+
---
|
|
136
|
+
|
|
137
|
+
## File Storage (`/storage/*` & `/public/files/*`)
|
|
138
|
+
|
|
139
|
+
Backed by `UPLOAD_DIR`, `_lls_storage_buckets`, and `_lls_storage_files`.
|
|
140
|
+
|
|
141
|
+
- **`POST /storage/upload`**: `multipart/form-data` with `bucket` and `file` → `200 { key, bucket, visibility, remoteUrl }`
|
|
142
|
+
- **`GET /storage/files/:bucket/:key`**: Download file (requires auth or valid signed `?token=` for private buckets)
|
|
143
|
+
- **`GET /public/files/:bucket/:key`**: Direct read for `public` buckets (no auth required)
|
|
144
|
+
- **`POST /storage/sign`**: `{ "key", "bucket"?, "expiresInMs"? }` → `200 { url, expiresAt }`
|
|
145
|
+
- **`DELETE /storage/files/:bucket/:key`**: Delete file
|
|
146
|
+
- **`GET / POST / DELETE /storage/buckets`**: List, create (`{ "name", "visibility": "public" | "private" }`), or delete empty buckets
|
|
147
|
+
|
|
148
|
+
---
|
|
149
|
+
|
|
150
|
+
## Admin Console API (`/admin/*`)
|
|
151
|
+
|
|
152
|
+
Protected by Admin session cookie (`lls_admin_session`) or `Authorization: Bearer <SERVER_API_KEY>` (except `/admin/login` and static UI assets).
|
|
153
|
+
|
|
154
|
+
| Endpoint | Methods | Purpose |
|
|
155
|
+
|---|---|---|
|
|
156
|
+
| `/admin/login` | `GET`, `POST` | Check session/bootstrap status; sign in or bootstrap first `super_admin` |
|
|
157
|
+
| `/admin/logout` | `POST` | Clear session cookie (`?all=1` revokes all sessions) |
|
|
158
|
+
| `/admin/overview` | `GET` | Health, table counts, account/backup counts, console role |
|
|
159
|
+
| `/admin/endpoints` | `GET` | Registered HTTP & function routes |
|
|
160
|
+
| `/admin/table` | `GET`, `POST`, `PATCH`, `DELETE` | Paginated row browser & CRUD |
|
|
161
|
+
| `/admin/users` | `GET`, `POST` | List accounts; unlock, revoke sessions, or set console role |
|
|
162
|
+
| `/admin/logs` | `GET` | Paginated `_server_changes` log |
|
|
163
|
+
| `/admin/env` | `GET`, `POST`, `DELETE` | DB-backed environment variables (including `action: "reveal"`) |
|
|
164
|
+
| `/admin/backups` | `GET`, `POST`, `DELETE` | List, download (`?file=`), create, or delete JSON backups |
|
|
165
|
+
| `/admin/storage` | `GET`, `POST`, `DELETE` | Admin storage browser & bucket management |
|
|
166
|
+
| `/admin/crons` | `GET`, `POST`, `DELETE` | Manage schedules, run jobs (`{ job_key }`), or prune orphans |
|
|
167
|
+
| `/admin/settings` | `GET`, `POST` | Runtime info, `test_health`, `apply_schema`, `test_email` |
|
|
168
|
+
|
|
169
|
+
---
|
|
170
|
+
|
|
171
|
+
## Standard Error Codes
|
|
172
|
+
|
|
173
|
+
| Status | Meaning |
|
|
174
|
+
|---|---|
|
|
175
|
+
| `400` | Invalid JSON, unknown table/column, or validation error |
|
|
176
|
+
| `401` | Missing or invalid token / session |
|
|
177
|
+
| `403` | Rejected by `src/rules.ts` RLS policy or invalid bootstrap secret |
|
|
178
|
+
| `404` | Unknown function, bucket, or file |
|
|
179
|
+
| `413` | Request body exceeds `6 MB` |
|
|
180
|
+
| `429` | Rate limit exceeded (`Retry-After` header included) |
|
|
181
|
+
| `503` | Database unavailable or `/auth` disabled (`APP_SECRET` unset) |
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
# Client Usage & Authentication
|
|
2
|
+
|
|
3
|
+
## 1. Local-First Sync (`local-lite/self-hosted`)
|
|
4
|
+
|
|
5
|
+
Point `SelfHostedRemoteAdapter` at your server's `/sync` endpoint:
|
|
6
|
+
|
|
7
|
+
```ts
|
|
8
|
+
import { LocalFirstClient } from 'local-lite/core';
|
|
9
|
+
import { SelfHostedRemoteAdapter } from 'local-lite/self-hosted';
|
|
10
|
+
|
|
11
|
+
const remote = new SelfHostedRemoteAdapter({
|
|
12
|
+
url: 'https://api.yourdomain.com/sync',
|
|
13
|
+
token: userJwtOrApiKey,
|
|
14
|
+
tables: ['notes'],
|
|
15
|
+
pollIntervalMs: 5000,
|
|
16
|
+
});
|
|
17
|
+
|
|
18
|
+
const client = new LocalFirstClient({
|
|
19
|
+
local: mySqliteAdapter,
|
|
20
|
+
remote,
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
await client.initialize();
|
|
24
|
+
client.syncWorker.start();
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
### Realtime Sync Events (SSE)
|
|
28
|
+
|
|
29
|
+
Listen for change notifications on `/sync/events`:
|
|
30
|
+
|
|
31
|
+
```ts
|
|
32
|
+
const es = new EventSource(
|
|
33
|
+
`https://api.yourdomain.com/sync/events?token=${encodeURIComponent(token)}`
|
|
34
|
+
);
|
|
35
|
+
es.onmessage = () => {
|
|
36
|
+
void client.syncWorker.pullRemoteChanges();
|
|
37
|
+
};
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
## 2. User Accounts (`/auth/*`)
|
|
41
|
+
|
|
42
|
+
Set `APP_SECRET` in `.env` to enable user accounts (rate-limited to 20 requests/min per IP):
|
|
43
|
+
|
|
44
|
+
- **Sign Up:**
|
|
45
|
+
```http
|
|
46
|
+
POST /auth/signup
|
|
47
|
+
Content-Type: application/json
|
|
48
|
+
|
|
49
|
+
{ "mode": "signup", "email": "user@example.com", "password": "strongpassword", "displayName": "Alex" }
|
|
50
|
+
```
|
|
51
|
+
Returns `{ token, user }`.
|
|
52
|
+
- **Sign In:**
|
|
53
|
+
```http
|
|
54
|
+
POST /auth/signin
|
|
55
|
+
Content-Type: application/json
|
|
56
|
+
|
|
57
|
+
{ "mode": "signin", "email": "user@example.com", "password": "strongpassword" }
|
|
58
|
+
```
|
|
59
|
+
- **Refresh Token:** `POST /auth/refresh` with `Authorization: Bearer <token>`
|
|
60
|
+
- **Password Reset (6-digit Email OTP, requires `SMTP_*`):**
|
|
61
|
+
1. `POST /auth/forgot-password` with `{ "email": "user@example.com" }`
|
|
62
|
+
2. `POST /auth/reset-password` with `{ "email": "user@example.com", "otp": "123456", "newPassword": "newpassword" }`
|
|
63
|
+
|
|
64
|
+
## 3. Typed Client SDK (`codegen`)
|
|
65
|
+
|
|
66
|
+
Generate a zero-dependency TypeScript client from your `schema.ts` and `functions/` directly into your frontend or mobile app:
|
|
67
|
+
|
|
68
|
+
```bash
|
|
69
|
+
npx local-lite-server codegen --out ../my-frontend/src/api.ts
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
Then import and use `createClient`:
|
|
73
|
+
|
|
74
|
+
```ts
|
|
75
|
+
import { createClient, type NotesRow } from './api';
|
|
76
|
+
|
|
77
|
+
const api = createClient({
|
|
78
|
+
url: 'https://api.yourdomain.com',
|
|
79
|
+
getToken: () => localStorage.getItem('token'),
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
// Query & mutation
|
|
83
|
+
const notes = await api.notes.list<NotesRow[]>();
|
|
84
|
+
await api.notes.create({ title: 'My Note', pinned: true });
|
|
85
|
+
|
|
86
|
+
// Live SSE subscription
|
|
87
|
+
const unsubscribe = api.notes.subscribeList<NotesRow[]>({}, (liveNotes) => {
|
|
88
|
+
console.log('Notes updated:', liveNotes);
|
|
89
|
+
});
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
Or call `/fn/:module/:name` directly with `fetch`:
|
|
93
|
+
|
|
94
|
+
```ts
|
|
95
|
+
const res = await fetch('https://api.yourdomain.com/fn/notes/create', {
|
|
96
|
+
method: 'POST',
|
|
97
|
+
headers: {
|
|
98
|
+
'Content-Type': 'application/json',
|
|
99
|
+
Authorization: `Bearer ${token}`,
|
|
100
|
+
},
|
|
101
|
+
body: JSON.stringify({ args: { title: 'My Note', pinned: true } }),
|
|
102
|
+
});
|
|
103
|
+
const { result } = await res.json();
|
|
104
|
+
```
|