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,160 @@
|
|
|
1
|
+
import crypto from 'node:crypto';
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { hashPassword, verifyPassword } from 'local-lite/auth/local';
|
|
5
|
+
import { createSignedToken, verifySignedToken } from 'local-lite/keys';
|
|
6
|
+
import { safeEqual } from '../core/http.js';
|
|
7
|
+
const COOKIE_NAME = 'lls_admin_session';
|
|
8
|
+
const SESSION_TTL_MS = 12 * 60 * 60 * 1000;
|
|
9
|
+
const MIME = {
|
|
10
|
+
'.html': 'text/html; charset=utf-8',
|
|
11
|
+
'.js': 'application/javascript; charset=utf-8',
|
|
12
|
+
'.css': 'text/css; charset=utf-8',
|
|
13
|
+
'.svg': 'image/svg+xml',
|
|
14
|
+
'.png': 'image/png',
|
|
15
|
+
'.json': 'application/json; charset=utf-8',
|
|
16
|
+
};
|
|
17
|
+
function readCookie(req, name) {
|
|
18
|
+
const raw = req.headers.get('cookie') ?? '';
|
|
19
|
+
for (const part of raw.split(';')) {
|
|
20
|
+
const idx = part.indexOf('=');
|
|
21
|
+
if (idx !== -1 && part.slice(0, idx).trim() === name) {
|
|
22
|
+
return decodeURIComponent(part.slice(idx + 1).trim());
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
return null;
|
|
26
|
+
}
|
|
27
|
+
function makeCookie(req, val, maxAgeSec) {
|
|
28
|
+
const secure = req.url.startsWith('https://') || req.headers.get('x-forwarded-proto') === 'https';
|
|
29
|
+
return `${COOKIE_NAME}=${encodeURIComponent(val)}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${maxAgeSec}${secure ? '; Secure' : ''}`;
|
|
30
|
+
}
|
|
31
|
+
export function createAdminSession(settings, db) {
|
|
32
|
+
const sessionSecret = crypto
|
|
33
|
+
.createHmac('sha256', settings.appSecret || settings.apiKey)
|
|
34
|
+
.update('lls-admin-session-v1')
|
|
35
|
+
.digest('hex');
|
|
36
|
+
const resolveAdminDist = () => {
|
|
37
|
+
for (const dir of [
|
|
38
|
+
path.resolve(process.cwd(), 'admin/dist'),
|
|
39
|
+
path.resolve(process.cwd(), 'admin-ui'),
|
|
40
|
+
...(import.meta.dirname ? [path.resolve(import.meta.dirname, '../../admin/dist')] : []),
|
|
41
|
+
]) {
|
|
42
|
+
if (fs.existsSync(path.join(dir, 'index.html')))
|
|
43
|
+
return dir;
|
|
44
|
+
}
|
|
45
|
+
return null;
|
|
46
|
+
};
|
|
47
|
+
async function authenticate(req) {
|
|
48
|
+
const auth = req.headers.get('authorization') ?? '';
|
|
49
|
+
const bearer = auth.startsWith('Bearer ') ? auth.slice(7).trim() : '';
|
|
50
|
+
if (bearer && safeEqual(bearer, settings.apiKey))
|
|
51
|
+
return { consoleRole: 'super_admin' };
|
|
52
|
+
const token = readCookie(req, COOKIE_NAME);
|
|
53
|
+
if (!token)
|
|
54
|
+
return null;
|
|
55
|
+
const verified = verifySignedToken(token, sessionSecret);
|
|
56
|
+
const payload = verified.valid ? verified.payload : null;
|
|
57
|
+
if (!payload?.sub || !payload.consoleRole)
|
|
58
|
+
return null;
|
|
59
|
+
const rows = await db.query('SELECT id, email, console_role, console_active, token_version FROM _local_auth_accounts WHERE id = ? LIMIT 1', [payload.sub]);
|
|
60
|
+
const u = rows[0];
|
|
61
|
+
if (!u || !u.console_active || !u.console_role)
|
|
62
|
+
return null;
|
|
63
|
+
if (Number(u.token_version ?? 1) !== Number(payload.tv ?? 1))
|
|
64
|
+
return null;
|
|
65
|
+
return {
|
|
66
|
+
userId: String(u.id),
|
|
67
|
+
email: String(u.email),
|
|
68
|
+
consoleRole: u.console_role === 'super_admin' ? 'super_admin' : 'admin',
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
return {
|
|
72
|
+
authenticate,
|
|
73
|
+
serveStatic(pathname) {
|
|
74
|
+
const dist = resolveAdminDist();
|
|
75
|
+
if (!dist) {
|
|
76
|
+
return new Response('Admin UI not built. Run `cd admin && npm run build`.', { status: 404 });
|
|
77
|
+
}
|
|
78
|
+
const rel = pathname.replace(/^\/admin\/?/, '') || 'index.html';
|
|
79
|
+
const target = path.resolve(dist, rel);
|
|
80
|
+
const file = target.startsWith(dist) && fs.existsSync(target) && fs.statSync(target).isFile()
|
|
81
|
+
? target
|
|
82
|
+
: path.join(dist, 'index.html');
|
|
83
|
+
const ext = path.extname(file);
|
|
84
|
+
return new Response(fs.readFileSync(file), {
|
|
85
|
+
headers: {
|
|
86
|
+
'content-type': MIME[ext] || 'application/octet-stream',
|
|
87
|
+
'cache-control': ext === '.html' ? 'no-store' : 'public, max-age=31536000, immutable',
|
|
88
|
+
},
|
|
89
|
+
});
|
|
90
|
+
},
|
|
91
|
+
async getLogin(request) {
|
|
92
|
+
const rows = await db.query('SELECT COUNT(*) AS n FROM _local_auth_accounts WHERE console_role IS NOT NULL AND console_active != 0');
|
|
93
|
+
const session = await authenticate(request).catch(() => null);
|
|
94
|
+
return Response.json({
|
|
95
|
+
hasConsoleAdmins: Number(rows[0]?.n ?? 0) > 0,
|
|
96
|
+
authenticated: Boolean(session),
|
|
97
|
+
consoleRole: session?.consoleRole ?? null,
|
|
98
|
+
});
|
|
99
|
+
},
|
|
100
|
+
async postLogin(request) {
|
|
101
|
+
const body = (await request.json().catch(() => null));
|
|
102
|
+
const email = String(body?.email ?? '').trim().toLowerCase();
|
|
103
|
+
const password = String(body?.password ?? '');
|
|
104
|
+
if (!email || !password) {
|
|
105
|
+
return Response.json({ error: 'Email and password are required.' }, { status: 400 });
|
|
106
|
+
}
|
|
107
|
+
if (body?.action === 'bootstrap') {
|
|
108
|
+
const sec = String(body.secret ?? '').trim();
|
|
109
|
+
const validSecret = (settings.appSecret && safeEqual(sec, settings.appSecret)) || safeEqual(sec, settings.apiKey);
|
|
110
|
+
if (!validSecret)
|
|
111
|
+
return Response.json({ error: 'Invalid APP_SECRET / SERVER_API_KEY.' }, { status: 403 });
|
|
112
|
+
if (password.length < 8)
|
|
113
|
+
return Response.json({ error: 'Password must be at least 8 characters.' }, { status: 400 });
|
|
114
|
+
const existing = await db.query('SELECT id FROM _local_auth_accounts WHERE email = ? LIMIT 1', [email]);
|
|
115
|
+
const now = Date.now();
|
|
116
|
+
let userId;
|
|
117
|
+
if (existing[0]) {
|
|
118
|
+
userId = String(existing[0].id);
|
|
119
|
+
await db.execute('UPDATE _local_auth_accounts SET console_role = ?, console_active = ?, updated_at = ? WHERE id = ?', ['super_admin', db.dialect === 'postgres' ? true : 1, now, userId]);
|
|
120
|
+
}
|
|
121
|
+
else {
|
|
122
|
+
userId = crypto.randomUUID();
|
|
123
|
+
const hashed = await hashPassword(password, { iterations: 100_000 });
|
|
124
|
+
await db.execute(`INSERT INTO _local_auth_accounts (id, email, display_name, password_hash, salt, iterations, algorithm, failed_login_attempts, locked_until, token_version, console_role, console_active, created_at, updated_at)
|
|
125
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, 0, NULL, 1, ?, ?, ?, ?)`, [
|
|
126
|
+
userId, email, email.split('@')[0], hashed.hash, hashed.salt, hashed.iterations,
|
|
127
|
+
hashed.algorithm, 'super_admin', db.dialect === 'postgres' ? true : 1, now, now,
|
|
128
|
+
]);
|
|
129
|
+
}
|
|
130
|
+
const token = createSignedToken({
|
|
131
|
+
secret: sessionSecret,
|
|
132
|
+
expiresInMs: SESSION_TTL_MS,
|
|
133
|
+
payload: { sub: userId, email, consoleRole: 'super_admin', tv: 1 },
|
|
134
|
+
});
|
|
135
|
+
return Response.json({ ok: true, success: true, consoleRole: 'super_admin' }, { headers: { 'Set-Cookie': makeCookie(request, token, SESSION_TTL_MS / 1000) } });
|
|
136
|
+
}
|
|
137
|
+
const rows = await db.query('SELECT * FROM _local_auth_accounts WHERE email = ? LIMIT 1', [email]);
|
|
138
|
+
const user = rows[0];
|
|
139
|
+
if (!user || !user.console_active || !user.console_role) {
|
|
140
|
+
return Response.json({ error: 'Invalid console credentials.' }, { status: 401 });
|
|
141
|
+
}
|
|
142
|
+
const ok = await verifyPassword(password, user.password_hash, user.salt, Number(user.iterations), user.algorithm);
|
|
143
|
+
if (!ok)
|
|
144
|
+
return Response.json({ error: 'Invalid console credentials.' }, { status: 401 });
|
|
145
|
+
const role = user.console_role === 'super_admin' ? 'super_admin' : 'admin';
|
|
146
|
+
const token = createSignedToken({
|
|
147
|
+
secret: sessionSecret,
|
|
148
|
+
expiresInMs: SESSION_TTL_MS,
|
|
149
|
+
payload: { sub: String(user.id), email, consoleRole: role, tv: Number(user.token_version ?? 1) },
|
|
150
|
+
});
|
|
151
|
+
return Response.json({ ok: true, success: true, consoleRole: role }, { headers: { 'Set-Cookie': makeCookie(request, token, SESSION_TTL_MS / 1000) } });
|
|
152
|
+
},
|
|
153
|
+
async postLogout(request, session) {
|
|
154
|
+
if (new URL(request.url).searchParams.get('all') === '1' && session?.userId) {
|
|
155
|
+
await db.execute('UPDATE _local_auth_accounts SET token_version = COALESCE(token_version, 1) + 1 WHERE id = ?', [session.userId]);
|
|
156
|
+
}
|
|
157
|
+
return Response.json({ ok: true, success: true }, { headers: { 'Set-Cookie': makeCookie(request, '', 0) } });
|
|
158
|
+
},
|
|
159
|
+
};
|
|
160
|
+
}
|
package/dist/apiKeys.js
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import crypto from 'node:crypto';
|
|
2
|
+
import { generateApiKey, hashApiKey, verifyApiKeyFormat } from 'local-lite/keys';
|
|
3
|
+
const numOrNull = (v) => (v == null ? null : Number(v));
|
|
4
|
+
function toRecord(r) {
|
|
5
|
+
return {
|
|
6
|
+
id: String(r.id),
|
|
7
|
+
name: String(r.name),
|
|
8
|
+
keyPrefix: String(r.key_prefix),
|
|
9
|
+
role: r.role === 'user' ? 'user' : 'admin',
|
|
10
|
+
userId: r.user_id ?? null,
|
|
11
|
+
createdBy: r.created_by ?? null,
|
|
12
|
+
lastUsedAt: numOrNull(r.last_used_at),
|
|
13
|
+
expiresAt: numOrNull(r.expires_at),
|
|
14
|
+
revokedAt: numOrNull(r.revoked_at),
|
|
15
|
+
createdAt: Number(r.created_at),
|
|
16
|
+
};
|
|
17
|
+
}
|
|
18
|
+
export function createApiKeyService(db) {
|
|
19
|
+
return {
|
|
20
|
+
async listKeys() {
|
|
21
|
+
const rows = await db.query(`SELECT id, name, key_prefix, role, user_id, created_by, last_used_at, expires_at, revoked_at, created_at
|
|
22
|
+
FROM _lls_api_keys
|
|
23
|
+
ORDER BY created_at DESC`);
|
|
24
|
+
return rows.map(toRecord);
|
|
25
|
+
},
|
|
26
|
+
async createKey(input) {
|
|
27
|
+
const name = input.name.trim();
|
|
28
|
+
if (!name || name.length > 128) {
|
|
29
|
+
throw new Error('API key name is required (max 128 chars).');
|
|
30
|
+
}
|
|
31
|
+
const role = input.role === 'user' ? 'user' : 'admin';
|
|
32
|
+
const id = `key_${crypto.randomUUID().replace(/-/g, '').slice(0, 20)}`;
|
|
33
|
+
const generated = generateApiKey({ prefix: 'lls', name });
|
|
34
|
+
const rawKey = generated.key;
|
|
35
|
+
const keyPrefix = generated.display;
|
|
36
|
+
const keyHash = generated.keyHash;
|
|
37
|
+
const now = Date.now();
|
|
38
|
+
const userId = role === 'user' ? (input.userId?.trim() || `api_key:${id}`) : null;
|
|
39
|
+
const expiresAt = input.expiresAt && input.expiresAt > now ? Math.floor(input.expiresAt) : null;
|
|
40
|
+
await db.execute(`INSERT INTO _lls_api_keys
|
|
41
|
+
(id, name, key_prefix, key_hash, role, user_id, created_by, last_used_at, expires_at, revoked_at, created_at)
|
|
42
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, NULL, ?, NULL, ?)`, [id, name, keyPrefix, keyHash, role, userId, input.createdBy ?? null, expiresAt, now]);
|
|
43
|
+
return {
|
|
44
|
+
key: rawKey,
|
|
45
|
+
record: {
|
|
46
|
+
id,
|
|
47
|
+
name,
|
|
48
|
+
keyPrefix,
|
|
49
|
+
role,
|
|
50
|
+
userId,
|
|
51
|
+
createdBy: input.createdBy ?? null,
|
|
52
|
+
lastUsedAt: null,
|
|
53
|
+
expiresAt,
|
|
54
|
+
revokedAt: null,
|
|
55
|
+
createdAt: now,
|
|
56
|
+
},
|
|
57
|
+
};
|
|
58
|
+
},
|
|
59
|
+
async revokeKey(id) {
|
|
60
|
+
const res = await db.execute('UPDATE _lls_api_keys SET revoked_at = ? WHERE id = ? AND revoked_at IS NULL', [Date.now(), id]);
|
|
61
|
+
return (res?.affectedRows ?? 0) > 0;
|
|
62
|
+
},
|
|
63
|
+
async deleteKey(id) {
|
|
64
|
+
const res = await db.execute('DELETE FROM _lls_api_keys WHERE id = ?', [id]);
|
|
65
|
+
return (res?.affectedRows ?? 0) > 0;
|
|
66
|
+
},
|
|
67
|
+
async verifyKey(rawKey) {
|
|
68
|
+
if (!verifyApiKeyFormat(rawKey, 'lls'))
|
|
69
|
+
return null;
|
|
70
|
+
const keyHash = hashApiKey(rawKey);
|
|
71
|
+
const [row] = await db.query('SELECT id, role, user_id, last_used_at, expires_at, revoked_at FROM _lls_api_keys WHERE key_hash = ? LIMIT 1', [keyHash]);
|
|
72
|
+
if (!row || row.revoked_at != null)
|
|
73
|
+
return null;
|
|
74
|
+
const now = Date.now();
|
|
75
|
+
if (row.expires_at != null && Number(row.expires_at) <= now)
|
|
76
|
+
return null;
|
|
77
|
+
// Throttle last_used_at writes to at most once per minute per key.
|
|
78
|
+
if (row.last_used_at == null || now - Number(row.last_used_at) > 60_000) {
|
|
79
|
+
void db
|
|
80
|
+
.execute('UPDATE _lls_api_keys SET last_used_at = ? WHERE id = ?', [now, row.id])
|
|
81
|
+
.catch(() => { });
|
|
82
|
+
}
|
|
83
|
+
const isAdmin = row.role !== 'user';
|
|
84
|
+
return {
|
|
85
|
+
id: String(row.id),
|
|
86
|
+
isAdmin,
|
|
87
|
+
userId: row.user_id ? String(row.user_id) : undefined,
|
|
88
|
+
};
|
|
89
|
+
},
|
|
90
|
+
};
|
|
91
|
+
}
|
package/dist/app.js
ADDED
package/dist/auth.js
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import { createAuthEndpoint, verifyAuthTokenWithStorage, } from 'local-lite/server';
|
|
2
|
+
import { sendSmtpMail } from './core/mailer.js';
|
|
3
|
+
const num = (v) => (v == null ? null : Number(v));
|
|
4
|
+
/** SQL-backed accounts + reset OTPs (tables created by migration 0002_auth). */
|
|
5
|
+
export function createAuthStorage(db) {
|
|
6
|
+
return {
|
|
7
|
+
async findUserByEmail(email) {
|
|
8
|
+
const [r] = await db.query('SELECT * FROM _local_auth_accounts WHERE email = ? LIMIT 1', [email]);
|
|
9
|
+
if (!r)
|
|
10
|
+
return null;
|
|
11
|
+
return {
|
|
12
|
+
id: String(r.id),
|
|
13
|
+
email: String(r.email),
|
|
14
|
+
displayName: r.display_name ?? null,
|
|
15
|
+
passwordHash: String(r.password_hash),
|
|
16
|
+
salt: String(r.salt),
|
|
17
|
+
iterations: Number(r.iterations),
|
|
18
|
+
algorithm: String(r.algorithm),
|
|
19
|
+
failedLoginAttempts: Number(r.failed_login_attempts ?? 0),
|
|
20
|
+
lockedUntil: num(r.locked_until),
|
|
21
|
+
tokenVersion: r.token_version != null ? Number(r.token_version) : 1,
|
|
22
|
+
createdAt: Number(r.created_at),
|
|
23
|
+
updatedAt: Number(r.updated_at),
|
|
24
|
+
};
|
|
25
|
+
},
|
|
26
|
+
async createUser(u) {
|
|
27
|
+
await db.execute(`INSERT INTO _local_auth_accounts (id, email, display_name, password_hash, salt, iterations, algorithm, failed_login_attempts, locked_until, token_version, created_at, updated_at)
|
|
28
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, [u.id, u.email, u.displayName ?? null, u.passwordHash, u.salt, u.iterations, u.algorithm,
|
|
29
|
+
u.failedLoginAttempts, u.lockedUntil ?? null, u.tokenVersion ?? 1, u.createdAt, u.updatedAt]);
|
|
30
|
+
},
|
|
31
|
+
async recordFailedAttempt(userId, attempts, lockedUntil, updatedAt) {
|
|
32
|
+
await db.execute('UPDATE _local_auth_accounts SET failed_login_attempts = ?, locked_until = ?, updated_at = ? WHERE id = ?', [attempts, lockedUntil, updatedAt, userId]);
|
|
33
|
+
},
|
|
34
|
+
async updatePasswordAndResetLockout(userId, p) {
|
|
35
|
+
await db.execute('UPDATE _local_auth_accounts SET password_hash = ?, salt = ?, iterations = ?, algorithm = ?, failed_login_attempts = 0, locked_until = NULL, token_version = COALESCE(token_version, 1) + 1, updated_at = ? WHERE id = ?', [p.passwordHash, p.salt, p.iterations, p.algorithm, p.updatedAt, userId]);
|
|
36
|
+
},
|
|
37
|
+
async invalidateActiveOtps(email, usedAt) {
|
|
38
|
+
await db.execute('UPDATE _local_auth_reset_otps SET used_at = ? WHERE email = ? AND used_at IS NULL', [usedAt, email]);
|
|
39
|
+
},
|
|
40
|
+
async createResetOtp(o) {
|
|
41
|
+
await db.execute('INSERT INTO _local_auth_reset_otps (id, user_id, email, otp_hash, attempts, expires_at, used_at, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)', [o.id, o.userId, o.email, o.otpHash, o.attempts, o.expiresAt, o.usedAt ?? null, o.createdAt]);
|
|
42
|
+
},
|
|
43
|
+
async findLatestActiveOtp(email) {
|
|
44
|
+
const [r] = await db.query('SELECT * FROM _local_auth_reset_otps WHERE email = ? AND used_at IS NULL ORDER BY created_at DESC LIMIT 1', [email]);
|
|
45
|
+
if (!r)
|
|
46
|
+
return null;
|
|
47
|
+
return {
|
|
48
|
+
id: String(r.id),
|
|
49
|
+
userId: String(r.user_id),
|
|
50
|
+
email: String(r.email),
|
|
51
|
+
otpHash: String(r.otp_hash),
|
|
52
|
+
attempts: Number(r.attempts ?? 0),
|
|
53
|
+
expiresAt: Number(r.expires_at),
|
|
54
|
+
usedAt: num(r.used_at),
|
|
55
|
+
createdAt: Number(r.created_at),
|
|
56
|
+
};
|
|
57
|
+
},
|
|
58
|
+
async incrementOtpAttempts(id, attempts, usedAt) {
|
|
59
|
+
await db.execute('UPDATE _local_auth_reset_otps SET attempts = ?, used_at = ? WHERE id = ?', [attempts, usedAt, id]);
|
|
60
|
+
},
|
|
61
|
+
async markOtpUsed(id, usedAt) {
|
|
62
|
+
await db.execute('UPDATE _local_auth_reset_otps SET used_at = ? WHERE id = ?', [usedAt, id]);
|
|
63
|
+
},
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
export function createAuthService(s, db) {
|
|
67
|
+
const storage = createAuthStorage(db);
|
|
68
|
+
const userCount = async () => Number((await db.query('SELECT COUNT(*) AS n FROM _local_auth_accounts'))[0]?.n ?? 0);
|
|
69
|
+
if (!s.appSecret) {
|
|
70
|
+
return {
|
|
71
|
+
enabled: false,
|
|
72
|
+
handler: async () => Response.json({ error: 'Accounts are disabled: set APP_SECRET to enable /auth.' }, { status: 503 }),
|
|
73
|
+
verifyToken: async () => false,
|
|
74
|
+
verifyUser: async () => null,
|
|
75
|
+
userCount,
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
const secret = s.appSecret;
|
|
79
|
+
const handler = createAuthEndpoint({
|
|
80
|
+
storage,
|
|
81
|
+
secret,
|
|
82
|
+
sendResetOtpEmail: async ({ to, otp, expiresMinutes }) => {
|
|
83
|
+
if (!s.smtp)
|
|
84
|
+
throw new Error('SMTP is not configured (set SMTP_HOST etc.).');
|
|
85
|
+
await sendSmtpMail(s.smtp, to, `${s.appName} password reset code`, `Your verification code is: ${otp}\n\nIt expires in ${expiresMinutes} minutes.\nIf you did not request this, ignore this email.`);
|
|
86
|
+
},
|
|
87
|
+
});
|
|
88
|
+
const verifyUser = async (token) => {
|
|
89
|
+
const user = await verifyAuthTokenWithStorage(token, secret, storage);
|
|
90
|
+
return user ? { id: user.id, email: user.email } : null;
|
|
91
|
+
};
|
|
92
|
+
return {
|
|
93
|
+
enabled: true,
|
|
94
|
+
handler,
|
|
95
|
+
verifyToken: async (token) => Boolean(await verifyUser(token)),
|
|
96
|
+
verifyUser,
|
|
97
|
+
userCount,
|
|
98
|
+
};
|
|
99
|
+
}
|
package/dist/cli.js
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import crypto from 'node:crypto';
|
|
3
|
+
import fs from 'node:fs';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import { loadSettings } from './config.js';
|
|
6
|
+
import { createDatabase } from './db.js';
|
|
7
|
+
import { coreMigrationStatus } from './migrations.js';
|
|
8
|
+
import { planSchema } from './schema.js';
|
|
9
|
+
import { loadSchema, migrate, start } from './start.js';
|
|
10
|
+
import { loadFunctionsDir } from './functions/index.js';
|
|
11
|
+
import { writeClientCode } from './codegen.js';
|
|
12
|
+
import { buildCpanelBundle } from './cpanel.js';
|
|
13
|
+
if (fs.existsSync('.env')) {
|
|
14
|
+
process.loadEnvFile?.('.env');
|
|
15
|
+
}
|
|
16
|
+
const cmd = process.argv[2] ?? 'start';
|
|
17
|
+
const sub = process.argv[3];
|
|
18
|
+
function resolveInitDir(targetDir, force) {
|
|
19
|
+
if (targetDir) {
|
|
20
|
+
return { cwd: path.resolve(process.cwd(), targetDir), relLabel: targetDir };
|
|
21
|
+
}
|
|
22
|
+
const here = process.cwd();
|
|
23
|
+
const hasFiles = fs.readdirSync(here).some((f) => !f.startsWith('.'));
|
|
24
|
+
if (!hasFiles || force)
|
|
25
|
+
return { cwd: here };
|
|
26
|
+
let name = 'local-lite-server';
|
|
27
|
+
let n = 2;
|
|
28
|
+
while (fs.existsSync(path.join(here, name)))
|
|
29
|
+
name = `local-lite-server-${n++}`;
|
|
30
|
+
console.log(`Current directory is not empty; creating ./${name}/`);
|
|
31
|
+
return { cwd: path.join(here, name), relLabel: name };
|
|
32
|
+
}
|
|
33
|
+
function collectTemplates(dir, root = dir) {
|
|
34
|
+
const out = [];
|
|
35
|
+
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
|
36
|
+
const abs = path.join(dir, entry.name);
|
|
37
|
+
if (entry.isDirectory())
|
|
38
|
+
out.push(...collectTemplates(abs, root));
|
|
39
|
+
else
|
|
40
|
+
out.push(path.relative(root, abs));
|
|
41
|
+
}
|
|
42
|
+
return out;
|
|
43
|
+
}
|
|
44
|
+
function runInit(targetDir, force) {
|
|
45
|
+
const { cwd, relLabel } = resolveInitDir(targetDir, force);
|
|
46
|
+
fs.mkdirSync(cwd, { recursive: true });
|
|
47
|
+
const tplRoot = path.resolve(import.meta.dirname, '../templates');
|
|
48
|
+
const vars = {
|
|
49
|
+
PKG_NAME: path.basename(cwd).toLowerCase().replace(/[^a-z0-9-_]/g, '-') || 'my-local-lite-server',
|
|
50
|
+
API_KEY: crypto.randomBytes(24).toString('hex'),
|
|
51
|
+
APP_SECRET: crypto.randomBytes(32).toString('hex'),
|
|
52
|
+
};
|
|
53
|
+
for (const rel of collectTemplates(tplRoot)) {
|
|
54
|
+
const outRel = rel === 'gitignore' ? '.gitignore' : rel;
|
|
55
|
+
const dest = path.join(cwd, outRel);
|
|
56
|
+
if (fs.existsSync(dest) && !force) {
|
|
57
|
+
console.log(`skip ${relLabel ? path.join(relLabel, outRel) : outRel} (already exists)`);
|
|
58
|
+
continue;
|
|
59
|
+
}
|
|
60
|
+
let content = fs.readFileSync(path.join(tplRoot, rel), 'utf8');
|
|
61
|
+
for (const [k, v] of Object.entries(vars))
|
|
62
|
+
content = content.replaceAll(`{{${k}}}`, v);
|
|
63
|
+
fs.mkdirSync(path.dirname(dest), { recursive: true });
|
|
64
|
+
fs.writeFileSync(dest, content);
|
|
65
|
+
console.log(`write ${relLabel ? path.join(relLabel, outRel) : outRel}`);
|
|
66
|
+
}
|
|
67
|
+
const cdStep = relLabel ? ` 1. cd ${relLabel}\n` : '';
|
|
68
|
+
const n = relLabel ? 2 : 1;
|
|
69
|
+
console.log(`\nNext:\n${cdStep} ${n}. Edit .env with your MySQL/Postgres credentials\n ${n + 1}. Run: npm run start (or npx local-lite-server start)`);
|
|
70
|
+
}
|
|
71
|
+
if (cmd === 'init') {
|
|
72
|
+
const dirArg = process.argv.slice(3).find((a) => !a.startsWith('-'));
|
|
73
|
+
runInit(dirArg, process.argv.includes('--force'));
|
|
74
|
+
}
|
|
75
|
+
else if (cmd === 'start') {
|
|
76
|
+
await start();
|
|
77
|
+
}
|
|
78
|
+
else if (cmd === 'migrate') {
|
|
79
|
+
const settings = loadSettings();
|
|
80
|
+
const schema = await loadSchema(settings);
|
|
81
|
+
const db = await createDatabase(settings);
|
|
82
|
+
try {
|
|
83
|
+
if (sub === 'status' || sub === 'diff') {
|
|
84
|
+
console.log('core:', await coreMigrationStatus(db.executor));
|
|
85
|
+
const plan = await planSchema(db.executor, schema).catch(() => null);
|
|
86
|
+
if (!plan)
|
|
87
|
+
console.log('schema: not initialised (run `migrate`)');
|
|
88
|
+
else {
|
|
89
|
+
console.log(`schema: ${plan.up.length} pending change(s)`);
|
|
90
|
+
if (sub === 'diff')
|
|
91
|
+
for (const s of plan.up)
|
|
92
|
+
console.log(`\n${s}`);
|
|
93
|
+
for (const w of plan.warnings)
|
|
94
|
+
console.log('warning:', w);
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
else {
|
|
98
|
+
await migrate(settings, db, schema);
|
|
99
|
+
console.log('Migrations up to date.');
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
finally {
|
|
103
|
+
await db.close();
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
else if (cmd === 'codegen') {
|
|
107
|
+
const outIdx = process.argv.indexOf('--out');
|
|
108
|
+
const outFile = outIdx !== -1 && process.argv[outIdx + 1] ? process.argv[outIdx + 1] : 'src/client.ts';
|
|
109
|
+
const settings = loadSettings();
|
|
110
|
+
const schema = await loadSchema(settings);
|
|
111
|
+
const functions = await loadFunctionsDir(settings.functionsDir);
|
|
112
|
+
const abs = writeClientCode(outFile, schema, functions);
|
|
113
|
+
console.log(`Generated typed client SDK: ${abs}`);
|
|
114
|
+
}
|
|
115
|
+
else if (cmd === 'build:cpanel') {
|
|
116
|
+
const outIdx = process.argv.indexOf('--out');
|
|
117
|
+
const outDir = outIdx !== -1 && process.argv[outIdx + 1] ? process.argv[outIdx + 1] : 'dist/cpanel';
|
|
118
|
+
await buildCpanelBundle(process.cwd(), outDir);
|
|
119
|
+
}
|
|
120
|
+
else if (cmd === '-v' || cmd === '--version') {
|
|
121
|
+
const pkg = JSON.parse(fs.readFileSync(path.resolve(import.meta.dirname, '../package.json'), 'utf8'));
|
|
122
|
+
console.log(pkg.version);
|
|
123
|
+
}
|
|
124
|
+
else {
|
|
125
|
+
console.log('Usage: local-lite-server <init [dir] [--force] | start | migrate [status|diff] | codegen [--out file] | build:cpanel [--out dir] | --version>');
|
|
126
|
+
process.exit(cmd === '-h' || cmd === '--help' || cmd === 'help' ? 0 : 1);
|
|
127
|
+
}
|
package/dist/codegen.js
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
function tsType(field) {
|
|
4
|
+
const nullable = field.endsWith(' | null');
|
|
5
|
+
const base = nullable ? field.slice(0, -' | null'.length) : field;
|
|
6
|
+
const mapped = base === 'string'
|
|
7
|
+
? 'string'
|
|
8
|
+
: base === 'number'
|
|
9
|
+
? 'number'
|
|
10
|
+
: base === 'boolean'
|
|
11
|
+
? 'boolean'
|
|
12
|
+
: base === 'string[]'
|
|
13
|
+
? 'string[]'
|
|
14
|
+
: 'Record<string, unknown>';
|
|
15
|
+
return nullable ? `${mapped} | null` : mapped;
|
|
16
|
+
}
|
|
17
|
+
function pascal(name) {
|
|
18
|
+
return name
|
|
19
|
+
.split(/[^A-Za-z0-9]+/)
|
|
20
|
+
.filter(Boolean)
|
|
21
|
+
.map((p) => p[0].toUpperCase() + p.slice(1))
|
|
22
|
+
.join('');
|
|
23
|
+
}
|
|
24
|
+
export function generateClientCode(schema, functions) {
|
|
25
|
+
const lines = [
|
|
26
|
+
'// Auto-generated by `local-lite-server codegen`. Do not edit by hand.',
|
|
27
|
+
'',
|
|
28
|
+
'export interface ClientOptions {',
|
|
29
|
+
' url: string;',
|
|
30
|
+
' getToken?: () => string | null | undefined | Promise<string | null | undefined>;',
|
|
31
|
+
' fetch?: typeof fetch;',
|
|
32
|
+
'}',
|
|
33
|
+
'',
|
|
34
|
+
];
|
|
35
|
+
for (const [table, fields] of Object.entries(schema)) {
|
|
36
|
+
lines.push(`export interface ${pascal(table)}Row {`);
|
|
37
|
+
for (const [col, t] of Object.entries(fields)) {
|
|
38
|
+
lines.push(` ${col}: ${tsType(t)};`);
|
|
39
|
+
}
|
|
40
|
+
if (!fields.updated_at)
|
|
41
|
+
lines.push(' updated_at: number;');
|
|
42
|
+
if (!fields.deleted)
|
|
43
|
+
lines.push(' deleted: boolean;');
|
|
44
|
+
lines.push('}', '');
|
|
45
|
+
}
|
|
46
|
+
const byMod = new Map();
|
|
47
|
+
for (const [full, def] of functions.entries()) {
|
|
48
|
+
const [mod, fn] = full.split('/');
|
|
49
|
+
if (!mod || !fn)
|
|
50
|
+
continue;
|
|
51
|
+
const list = byMod.get(mod) ?? [];
|
|
52
|
+
list.push({ name: fn, kind: def.__kind });
|
|
53
|
+
byMod.set(mod, list);
|
|
54
|
+
}
|
|
55
|
+
lines.push('export function createClient(opts: ClientOptions) {', ' const baseUrl = opts.url.replace(/\\/+$/, "");', ' const doFetch = opts.fetch ?? globalThis.fetch;', '', ' async function call<T = unknown>(fn: string, args: Record<string, unknown> = {}): Promise<T> {', ' const token = await opts.getToken?.();', ' const headers: Record<string, string> = { "Content-Type": "application/json" };', ' if (token) headers.Authorization = `Bearer ${token}`;', ' const res = await doFetch(`${baseUrl}/fn/${fn}`, {', ' method: "POST",', ' headers,', ' body: JSON.stringify({ args }),', ' });', ' const data = (await res.json().catch(() => ({}))) as { result?: T; error?: string };', ' if (!res.ok) throw new Error(data.error || `Request failed (${res.status})`);', ' return data.result as T;', ' }', '', ' function subscribe<T = unknown>(', ' fn: string,', ' args: Record<string, unknown>,', ' onData: (data: T) => void,', ' onError?: (err: unknown) => void,', ' ): () => void {', ' let es: EventSource | null = null;', ' let closed = false;', ' void Promise.resolve(opts.getToken?.()).then((token) => {', ' if (closed) return;', ' const q = new URLSearchParams({ args: JSON.stringify(args) });', ' if (token) q.set("token", token);', ' es = new EventSource(`${baseUrl}/subscribe/${fn}?${q.toString()}`);', ' es.addEventListener("data", (ev) => {', ' try { onData(JSON.parse((ev as MessageEvent).data) as T); } catch (e) { onError?.(e); }', ' });', ' if (onError) es.addEventListener("error", onError);', ' });', ' return () => { closed = true; es?.close(); };', ' }', '', ' return {', ' call,', ' subscribe,');
|
|
56
|
+
for (const [mod, fns] of byMod) {
|
|
57
|
+
lines.push(` ${mod}: {`);
|
|
58
|
+
for (const f of fns) {
|
|
59
|
+
lines.push(` ${f.name}: <T = unknown>(args: Record<string, unknown> = {}) => call<T>("${mod}/${f.name}", args),`);
|
|
60
|
+
if (f.kind === 'query') {
|
|
61
|
+
lines.push(` subscribe${pascal(f.name)}: <T = unknown>(args: Record<string, unknown>, onData: (data: T) => void, onError?: (err: unknown) => void) => subscribe<T>("${mod}/${f.name}", args, onData, onError),`);
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
lines.push(' },');
|
|
65
|
+
}
|
|
66
|
+
lines.push(' };', '}', '');
|
|
67
|
+
return lines.join('\n');
|
|
68
|
+
}
|
|
69
|
+
export function writeClientCode(outFile, schema, functions) {
|
|
70
|
+
const abs = path.resolve(process.cwd(), outFile);
|
|
71
|
+
fs.mkdirSync(path.dirname(abs), { recursive: true });
|
|
72
|
+
fs.writeFileSync(abs, generateClientCode(schema, functions));
|
|
73
|
+
return abs;
|
|
74
|
+
}
|
package/dist/config.js
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
export function loadSettings(env = process.env) {
|
|
2
|
+
const dialect = (env.DB_DIALECT ?? 'mysql').toLowerCase();
|
|
3
|
+
if (dialect !== 'mysql' && dialect !== 'postgres') {
|
|
4
|
+
throw new Error(`DB_DIALECT must be "mysql" or "postgres", got "${dialect}".`);
|
|
5
|
+
}
|
|
6
|
+
const missing = ['DB_HOST', 'DB_USER', 'DB_NAME', 'SERVER_API_KEY'].filter((k) => !env[k]);
|
|
7
|
+
if (missing.length) {
|
|
8
|
+
throw new Error(`Missing required environment variables: ${missing.join(', ')}`);
|
|
9
|
+
}
|
|
10
|
+
const rawPort = env.PORT || env.SERVER_PORT || '3000';
|
|
11
|
+
const smtpPort = Number(env.SMTP_PORT || 465);
|
|
12
|
+
return {
|
|
13
|
+
port: /^\d+$/.test(rawPort) ? Number(rawPort) : rawPort,
|
|
14
|
+
dialect,
|
|
15
|
+
db: {
|
|
16
|
+
host: env.DB_HOST,
|
|
17
|
+
port: Number(env.DB_PORT || (dialect === 'postgres' ? 5432 : 3306)),
|
|
18
|
+
user: env.DB_USER,
|
|
19
|
+
password: env.DB_PASSWORD ?? '',
|
|
20
|
+
database: env.DB_NAME,
|
|
21
|
+
ssl: env.DB_SSL === 'true',
|
|
22
|
+
poolSize: Number(env.DB_POOL_SIZE || 5),
|
|
23
|
+
},
|
|
24
|
+
autoMigrate: env.AUTO_MIGRATE !== 'false',
|
|
25
|
+
schemaPath: env.SCHEMA_PATH || undefined,
|
|
26
|
+
rulesPath: env.RULES_PATH || undefined,
|
|
27
|
+
functionsDir: env.FUNCTIONS_DIR || undefined,
|
|
28
|
+
uploadDir: env.UPLOAD_DIR || './uploads',
|
|
29
|
+
backupDir: env.BACKUP_DIR || './backups',
|
|
30
|
+
internalCrons: env.ENABLE_INTERNAL_CRONS === 'true',
|
|
31
|
+
multiInstance: env.MULTI_INSTANCE === 'true',
|
|
32
|
+
apiKey: env.SERVER_API_KEY,
|
|
33
|
+
appSecret: env.APP_SECRET?.trim() || undefined,
|
|
34
|
+
appName: env.APP_NAME || 'local-lite-server',
|
|
35
|
+
adminUi: env.ADMIN_UI !== 'false',
|
|
36
|
+
smtp: env.SMTP_HOST
|
|
37
|
+
? {
|
|
38
|
+
host: env.SMTP_HOST,
|
|
39
|
+
port: smtpPort,
|
|
40
|
+
secure: env.SMTP_SECURE ? env.SMTP_SECURE === 'true' : smtpPort === 465,
|
|
41
|
+
user: env.SMTP_USER || undefined,
|
|
42
|
+
pass: env.SMTP_PASS || undefined,
|
|
43
|
+
from: env.SMTP_FROM || env.SMTP_USER || 'no-reply@localhost',
|
|
44
|
+
}
|
|
45
|
+
: undefined,
|
|
46
|
+
corsOrigins: (env.CORS_ORIGINS ?? '*')
|
|
47
|
+
.split(',')
|
|
48
|
+
.map((s) => s.trim())
|
|
49
|
+
.filter(Boolean),
|
|
50
|
+
};
|
|
51
|
+
}
|