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.
Files changed (90) hide show
  1. package/README.md +103 -2
  2. package/admin/dist/assets/index-B2nX9Pef.js +18 -0
  3. package/admin/dist/assets/index-Dt3bXEks.css +2 -0
  4. package/admin/dist/favicon.svg +11 -0
  5. package/admin/dist/index.html +14 -0
  6. package/dist/admin/console.d.ts +19 -0
  7. package/dist/admin/console.js +166 -0
  8. package/dist/admin/index.d.ts +28 -0
  9. package/dist/admin/index.js +13 -0
  10. package/dist/admin/ops.d.ts +11 -0
  11. package/dist/admin/ops.js +279 -0
  12. package/dist/admin/session.d.ts +14 -0
  13. package/dist/admin/session.js +160 -0
  14. package/dist/apiKeys.d.ts +36 -0
  15. package/dist/apiKeys.js +91 -0
  16. package/dist/app.d.ts +1 -0
  17. package/dist/app.js +10 -0
  18. package/dist/auth.d.ts +16 -0
  19. package/dist/auth.js +99 -0
  20. package/dist/cli.d.ts +2 -0
  21. package/dist/cli.js +127 -0
  22. package/dist/codegen.d.ts +4 -0
  23. package/dist/codegen.js +74 -0
  24. package/dist/config.d.ts +39 -0
  25. package/dist/config.js +51 -0
  26. package/dist/core/broker.d.ts +12 -0
  27. package/dist/core/broker.js +78 -0
  28. package/dist/core/changes.d.ts +17 -0
  29. package/dist/core/changes.js +68 -0
  30. package/dist/core/http.d.ts +8 -0
  31. package/dist/core/http.js +72 -0
  32. package/dist/core/mailer.d.ts +3 -0
  33. package/dist/core/mailer.js +11 -0
  34. package/dist/cpanel.d.ts +1 -0
  35. package/dist/cpanel.js +96 -0
  36. package/dist/crons.d.ts +24 -0
  37. package/dist/crons.js +124 -0
  38. package/dist/db.d.ts +7 -0
  39. package/dist/db.js +37 -0
  40. package/dist/functions/index.d.ts +3 -0
  41. package/dist/functions/index.js +3 -0
  42. package/dist/functions/loader.d.ts +4 -0
  43. package/dist/functions/loader.js +64 -0
  44. package/dist/functions/runtime.d.ts +21 -0
  45. package/dist/functions/runtime.js +238 -0
  46. package/dist/functions/types.d.ts +59 -0
  47. package/dist/functions/types.js +16 -0
  48. package/dist/index.d.ts +12 -0
  49. package/dist/index.js +7 -0
  50. package/dist/migrations.d.ts +16 -0
  51. package/dist/migrations.js +254 -0
  52. package/dist/oauth.d.ts +7 -0
  53. package/dist/oauth.js +152 -0
  54. package/dist/rateLimit.d.ts +12 -0
  55. package/dist/rateLimit.js +54 -0
  56. package/dist/routes.d.ts +15 -0
  57. package/dist/routes.js +29 -0
  58. package/dist/rules.d.ts +23 -0
  59. package/dist/rules.js +73 -0
  60. package/dist/schema.d.ts +18 -0
  61. package/dist/schema.js +89 -0
  62. package/dist/server.d.ts +13 -0
  63. package/dist/server.js +340 -0
  64. package/dist/start.d.ts +8 -0
  65. package/dist/start.js +168 -0
  66. package/dist/storage.d.ts +4 -0
  67. package/dist/storage.js +82 -0
  68. package/dist/tableStorage.d.ts +63 -0
  69. package/dist/tableStorage.js +261 -0
  70. package/docs/api.md +181 -0
  71. package/docs/client-usage.md +104 -0
  72. package/docs/cpanel.md +63 -0
  73. package/docs/functions.md +78 -0
  74. package/docs/schema-and-migrations.md +54 -0
  75. package/docs/vps.md +67 -0
  76. package/package.json +54 -4
  77. package/templates/.env +16 -0
  78. package/templates/.env.example +49 -0
  79. package/templates/README.md +23 -0
  80. package/templates/data/backups/.gitkeep +1 -0
  81. package/templates/data/uploads/.gitkeep +1 -0
  82. package/templates/gitignore +29 -0
  83. package/templates/package.json +14 -0
  84. package/templates/src/functions/notes.ts +47 -0
  85. package/templates/src/lib/validators.ts +9 -0
  86. package/templates/src/rules.ts +12 -0
  87. package/templates/src/schema.ts +9 -0
  88. package/templates/src/types.ts +9 -0
  89. package/templates/tests/notes.test.ts +26 -0
  90. package/templates/tsconfig.json +13 -0
@@ -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,7 @@
1
+ /** Handles `POST /auth/google-token` and `POST /auth/github-token` code exchanges. */
2
+ export declare function handleOAuthTokenExchange(request: Request): Promise<Response>;
3
+ /** Verifies a Google (ID/access) or GitHub OAuth token and maps it to a unified userId. */
4
+ export declare function verifyOAuthToken(token: string): Promise<{
5
+ id: string;
6
+ } | null>;
7
+ export declare function clearOAuthCacheForTests(): void;
package/dist/oauth.js ADDED
@@ -0,0 +1,152 @@
1
+ import { resolveUnifiedUserId } from 'local-lite/auth';
2
+ const CACHE_TTL_MS = 5 * 60 * 1000;
3
+ const tokenCache = new Map();
4
+ function parseBodyParams(rawText) {
5
+ if (rawText.trim().startsWith('{')) {
6
+ try {
7
+ const parsed = JSON.parse(rawText);
8
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed))
9
+ return null;
10
+ const out = {};
11
+ for (const [k, v] of Object.entries(parsed)) {
12
+ if (v != null)
13
+ out[k] = String(v);
14
+ }
15
+ return out;
16
+ }
17
+ catch {
18
+ return null;
19
+ }
20
+ }
21
+ return Object.fromEntries(new URLSearchParams(rawText).entries());
22
+ }
23
+ /** Handles `POST /auth/google-token` and `POST /auth/github-token` code exchanges. */
24
+ export async function handleOAuthTokenExchange(request) {
25
+ const url = new URL(request.url);
26
+ const rawText = await request.text().catch(() => '');
27
+ const params = parseBodyParams(rawText);
28
+ if (!params) {
29
+ return Response.json({ error: 'Invalid JSON payload' }, { status: 400 });
30
+ }
31
+ if (url.pathname.endsWith('/google-token')) {
32
+ const clientSecret = process.env.GOOGLE_CLIENT_SECRET?.trim();
33
+ if (!clientSecret) {
34
+ return Response.json({ error: 'Google OAuth client secret is not configured on the server' }, { status: 503 });
35
+ }
36
+ if (params.grant_type !== 'authorization_code' && params.grant_type !== 'refresh_token') {
37
+ return Response.json({ error: 'Unsupported grant_type. Expected authorization_code or refresh_token.' }, { status: 400 });
38
+ }
39
+ const forwarded = new URLSearchParams();
40
+ for (const f of ['grant_type', 'client_id', 'code', 'code_verifier', 'redirect_uri', 'refresh_token']) {
41
+ if (params[f])
42
+ forwarded.set(f, params[f]);
43
+ }
44
+ forwarded.set('client_secret', clientSecret);
45
+ const gRes = await fetch('https://oauth2.googleapis.com/token', {
46
+ method: 'POST',
47
+ signal: AbortSignal.timeout(10_000),
48
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
49
+ body: forwarded.toString(),
50
+ });
51
+ return new Response(await gRes.text(), {
52
+ status: gRes.status,
53
+ headers: { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' },
54
+ });
55
+ }
56
+ if (url.pathname.endsWith('/github-token')) {
57
+ const clientSecret = process.env.GITHUB_CLIENT_SECRET?.trim();
58
+ if (!clientSecret) {
59
+ return Response.json({ error: 'GITHUB_CLIENT_SECRET is not configured on server' }, { status: 503 });
60
+ }
61
+ const { client_id, code, redirect_uri, state } = params;
62
+ if (!code || !client_id) {
63
+ return Response.json({ error: 'client_id and code are required' }, { status: 400 });
64
+ }
65
+ const forwarded = new URLSearchParams({ client_id, client_secret: clientSecret, code });
66
+ if (redirect_uri)
67
+ forwarded.set('redirect_uri', redirect_uri);
68
+ if (state)
69
+ forwarded.set('state', state);
70
+ const ghRes = await fetch('https://github.com/login/oauth/access_token', {
71
+ method: 'POST',
72
+ signal: AbortSignal.timeout(10_000),
73
+ headers: { Accept: 'application/json', 'Content-Type': 'application/x-www-form-urlencoded' },
74
+ body: forwarded.toString(),
75
+ });
76
+ return new Response(await ghRes.text(), {
77
+ status: ghRes.status,
78
+ headers: { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' },
79
+ });
80
+ }
81
+ return Response.json({ error: 'Endpoint not found' }, { status: 404 });
82
+ }
83
+ function cacheUser(token, userId) {
84
+ if (tokenCache.size > 2000)
85
+ tokenCache.clear();
86
+ tokenCache.set(token, { userId, expiresAt: Date.now() + CACHE_TTL_MS });
87
+ return { id: userId };
88
+ }
89
+ /** Verifies a Google (ID/access) or GitHub OAuth token and maps it to a unified userId. */
90
+ export async function verifyOAuthToken(token) {
91
+ if (!token || token.length < 16)
92
+ return null;
93
+ const cached = tokenCache.get(token);
94
+ if (cached && cached.expiresAt > Date.now())
95
+ return { id: cached.userId };
96
+ try {
97
+ const isGitHubPrefix = token.startsWith('gho_') || token.startsWith('ghu_') || token.startsWith('ghp_');
98
+ if (!isGitHubPrefix && token.split('.').length === 3) {
99
+ const gRes = await fetch(`https://oauth2.googleapis.com/tokeninfo?id_token=${encodeURIComponent(token)}`, { signal: AbortSignal.timeout(8_000) });
100
+ if (gRes.ok) {
101
+ const info = (await gRes.json());
102
+ if (typeof info?.sub === 'string' && info.sub) {
103
+ const id = resolveUnifiedUserId({
104
+ id: info.sub,
105
+ email: info.email,
106
+ emailVerified: info.email_verified === true || info.email_verified === 'true',
107
+ }, 'google');
108
+ return cacheUser(token, id);
109
+ }
110
+ }
111
+ }
112
+ if (!isGitHubPrefix) {
113
+ const uRes = await fetch('https://www.googleapis.com/oauth2/v3/userinfo', {
114
+ signal: AbortSignal.timeout(8_000),
115
+ headers: { Authorization: `Bearer ${token}` },
116
+ });
117
+ if (uRes.ok) {
118
+ const info = (await uRes.json());
119
+ if (typeof info?.sub === 'string' && info.sub) {
120
+ const id = resolveUnifiedUserId({
121
+ id: info.sub,
122
+ email: info.email,
123
+ emailVerified: info.email_verified === true || info.email_verified === 'true',
124
+ }, 'google');
125
+ return cacheUser(token, id);
126
+ }
127
+ }
128
+ }
129
+ const ghRes = await fetch('https://api.github.com/user', {
130
+ signal: AbortSignal.timeout(8_000),
131
+ headers: {
132
+ Authorization: `Bearer ${token}`,
133
+ Accept: 'application/vnd.github+json',
134
+ 'User-Agent': 'local-lite-server',
135
+ },
136
+ });
137
+ if (ghRes.ok) {
138
+ const info = (await ghRes.json());
139
+ if (info?.id != null) {
140
+ const id = resolveUnifiedUserId({ id: String(info.id), email: info.email ?? undefined, emailVerified: Boolean(info.email) }, 'github');
141
+ return cacheUser(token, id);
142
+ }
143
+ }
144
+ }
145
+ catch {
146
+ // Ignore transient upstream OAuth errors
147
+ }
148
+ return null;
149
+ }
150
+ export function clearOAuthCacheForTests() {
151
+ tokenCache.clear();
152
+ }
@@ -0,0 +1,12 @@
1
+ import type { SqlExecutor } from 'local-lite/server';
2
+ export type RateLimitResult = {
3
+ ok: true;
4
+ } | {
5
+ ok: false;
6
+ retryAfter: number;
7
+ };
8
+ /** Fixed-window in-memory limiter, keyed per client IP. */
9
+ export declare function createRateLimiter(max: number, windowMs: number): (key: string, now?: number) => RateLimitResult;
10
+ /** DB-backed limiter for multi-instance deployments, with in-memory fallback. */
11
+ export declare function createDistributedRateLimiter(db: SqlExecutor, max: number, windowMs: number, enabled?: boolean): (key: string, now?: number) => Promise<RateLimitResult>;
12
+ export declare function clientIp(request: Request): string;
@@ -0,0 +1,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
+ }
@@ -0,0 +1,15 @@
1
+ import type { SqlExecutor, SyncEventBroker } from 'local-lite/server';
2
+ import type { ServerSettings } from './config.js';
3
+ import type { FunctionAuth } from './functions/index.js';
4
+ import type { SchemaDictionary } from './schema.js';
5
+ export interface CustomRoutesContext {
6
+ db: SqlExecutor;
7
+ settings: ServerSettings;
8
+ schema: SchemaDictionary;
9
+ broker: SyncEventBroker;
10
+ resolveAuth: (request: Request, allowQuery?: boolean) => Promise<FunctionAuth | null>;
11
+ }
12
+ export type CustomRoutesMap = Record<string, Record<string, (ctx: any) => Promise<Response> | Response>>;
13
+ export type CustomRoutesFactory = (ctx: CustomRoutesContext) => CustomRoutesMap;
14
+ export declare function resolveRoutesFile(explicit?: string, cwd?: string): string | null;
15
+ export declare function loadRoutesFile(file: string): Promise<CustomRoutesMap | CustomRoutesFactory>;
package/dist/routes.js ADDED
@@ -0,0 +1,29 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { pathToFileURL } from 'node:url';
4
+ const CANDIDATES = ['routes.mjs', 'src/routes.ts', 'routes.ts'];
5
+ export function resolveRoutesFile(explicit, cwd = process.cwd()) {
6
+ if (explicit) {
7
+ const abs = path.resolve(cwd, explicit);
8
+ if (!fs.existsSync(abs))
9
+ throw new Error(`ROUTES_PATH not found: ${abs}`);
10
+ return abs;
11
+ }
12
+ const isOwnRepo = fs.existsSync(path.resolve(cwd, 'src/cli.ts'));
13
+ for (const name of CANDIDATES) {
14
+ if (isOwnRepo && name === 'src/routes.ts')
15
+ continue;
16
+ const abs = path.resolve(cwd, name);
17
+ if (fs.existsSync(abs))
18
+ return abs;
19
+ }
20
+ return null;
21
+ }
22
+ export async function loadRoutesFile(file) {
23
+ const loaded = await import(pathToFileURL(file).href);
24
+ const mod = loaded.default ?? loaded.routes;
25
+ if (!mod || (typeof mod !== 'object' && typeof mod !== 'function') || Array.isArray(mod)) {
26
+ throw new Error(`${file} must export default an endpoints object or factory function.`);
27
+ }
28
+ return mod;
29
+ }
@@ -0,0 +1,23 @@
1
+ export interface RuleContext {
2
+ isAdmin: boolean;
3
+ userId?: string;
4
+ }
5
+ export type RowPredicate = (ctx: RuleContext, row: Record<string, any>) => boolean | Promise<boolean>;
6
+ export type RulePreset = 'authenticated' | 'owner' | `owner:${string}` | 'admin' | 'none';
7
+ export type RuleExpression = RowPredicate | RulePreset;
8
+ export interface TableRuleInput {
9
+ read?: RuleExpression;
10
+ write?: RuleExpression;
11
+ delete?: RuleExpression;
12
+ }
13
+ export interface TableRule {
14
+ read?: RowPredicate;
15
+ write?: RowPredicate;
16
+ delete?: RowPredicate;
17
+ }
18
+ export type RulesInputDictionary = Record<string, TableRuleInput | RulePreset>;
19
+ export type RulesDictionary = Record<string, TableRule>;
20
+ export declare function normalizeRules(input: RulesInputDictionary): RulesDictionary;
21
+ export declare function defineRules(rules: RulesInputDictionary): RulesDictionary;
22
+ export declare function resolveRulesFile(explicit?: string, cwd?: string): string | null;
23
+ export declare function loadRulesFile(file: string): Promise<RulesDictionary>;
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
+ }
@@ -0,0 +1,18 @@
1
+ import type { SqlExecutor } from 'local-lite/server';
2
+ import { type SchemaDictionary, type SchemaFieldType, type SqlSchemaState } from 'local-lite/schema/migrations';
3
+ export type { SchemaDictionary, SchemaFieldType };
4
+ /** Identity helper for typed `schema.ts` files. */
5
+ export declare function defineSchema<T extends SchemaDictionary>(schema: T): T;
6
+ /** Validates names, field types, and guarantees an `id` column on every table. */
7
+ export declare function normalizeSchema(input: SchemaDictionary): SchemaDictionary;
8
+ export declare function resolveSchemaFile(explicit?: string, cwd?: string): string;
9
+ export declare function loadSchemaFile(file: string): Promise<SchemaDictionary>;
10
+ export interface SchemaPlan {
11
+ up: string[];
12
+ warnings: string[];
13
+ next: SqlSchemaState;
14
+ first: boolean;
15
+ }
16
+ export declare function planSchema(db: SqlExecutor, dictionary: SchemaDictionary): Promise<SchemaPlan>;
17
+ /** Applies the schema diff and records the new state. Safe to call on every boot. */
18
+ export declare function applySchema(db: SqlExecutor, dictionary: SchemaDictionary): Promise<SchemaPlan>;