local-lite-server 0.1.0 → 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/admin/dist/assets/{index-DMJ7Ri2R.js → index-B2nX9Pef.js} +3 -3
- package/admin/dist/index.html +1 -1
- package/dist/admin/console.d.ts +19 -0
- package/dist/admin/index.d.ts +28 -0
- package/dist/admin/ops.d.ts +11 -0
- package/dist/admin/session.d.ts +14 -0
- package/dist/apiKeys.d.ts +36 -0
- package/dist/app.d.ts +1 -0
- package/dist/app.js +5 -1
- package/dist/auth.d.ts +16 -0
- package/dist/cli.d.ts +2 -0
- package/dist/codegen.d.ts +4 -0
- package/dist/config.d.ts +39 -0
- package/dist/core/broker.d.ts +12 -0
- package/dist/core/changes.d.ts +17 -0
- package/dist/core/http.d.ts +8 -0
- package/dist/core/http.js +1 -1
- package/dist/core/mailer.d.ts +3 -0
- package/dist/cpanel.d.ts +1 -0
- package/dist/cpanel.js +24 -6
- package/dist/crons.d.ts +24 -0
- package/dist/db.d.ts +7 -0
- package/dist/functions/index.d.ts +3 -0
- package/dist/functions/loader.d.ts +4 -0
- package/dist/functions/runtime.d.ts +21 -0
- package/dist/functions/types.d.ts +59 -0
- package/dist/index.d.ts +12 -0
- package/dist/index.js +1 -0
- package/dist/migrations.d.ts +16 -0
- package/dist/oauth.d.ts +7 -0
- package/dist/oauth.js +152 -0
- package/dist/rateLimit.d.ts +12 -0
- package/dist/routes.d.ts +15 -0
- package/dist/routes.js +29 -0
- package/dist/rules.d.ts +23 -0
- package/dist/schema.d.ts +18 -0
- package/dist/server.d.ts +13 -0
- package/dist/server.js +27 -1
- package/dist/start.d.ts +8 -0
- package/dist/start.js +11 -4
- package/dist/storage.d.ts +4 -0
- package/dist/tableStorage.d.ts +63 -0
- package/package.json +1 -1
- package/templates/.env.example +33 -0
package/admin/dist/index.html
CHANGED
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
|
6
6
|
<link rel="icon" type="image/svg+xml" href="/admin/favicon.svg" />
|
|
7
7
|
<title>local-lite-server — Admin Console</title>
|
|
8
|
-
<script type="module" crossorigin src="/admin/assets/index-
|
|
8
|
+
<script type="module" crossorigin src="/admin/assets/index-B2nX9Pef.js"></script>
|
|
9
9
|
<link rel="stylesheet" crossorigin href="/admin/assets/index-Dt3bXEks.css">
|
|
10
10
|
</head>
|
|
11
11
|
<body>
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { type SqlExecutor, type SyncEventBroker } from 'local-lite/server';
|
|
2
|
+
import type { ServerSettings } from '../config.js';
|
|
3
|
+
import type { FunctionRuntime } from '../functions/index.js';
|
|
4
|
+
import type { SchemaDictionary } from '../schema.js';
|
|
5
|
+
import type { AdminSession } from './session.js';
|
|
6
|
+
export declare function createAdminData(opts: {
|
|
7
|
+
settings: ServerSettings;
|
|
8
|
+
db: SqlExecutor;
|
|
9
|
+
schema: SchemaDictionary;
|
|
10
|
+
broker?: SyncEventBroker;
|
|
11
|
+
fnRuntime?: FunctionRuntime;
|
|
12
|
+
}): {
|
|
13
|
+
overview(session: AdminSession): Promise<Response>;
|
|
14
|
+
listEndpoints(): Promise<Response>;
|
|
15
|
+
listUsers(): Promise<Response>;
|
|
16
|
+
handleTable(request: Request, tableOverride?: string, idOverride?: string): Promise<Response>;
|
|
17
|
+
manageUsers(request: Request): Promise<Response>;
|
|
18
|
+
handleLogs(url: URL): Promise<Response>;
|
|
19
|
+
};
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import type { SqlExecutor, SyncEventBroker } from 'local-lite/server';
|
|
2
|
+
import type { ServerSettings } from '../config.js';
|
|
3
|
+
import type { FunctionRuntime } from '../functions/index.js';
|
|
4
|
+
import type { SchemaDictionary } from '../schema.js';
|
|
5
|
+
export declare function createAdminConsole(opts: {
|
|
6
|
+
settings: ServerSettings;
|
|
7
|
+
db: SqlExecutor;
|
|
8
|
+
schema: SchemaDictionary;
|
|
9
|
+
broker?: SyncEventBroker;
|
|
10
|
+
fnRuntime?: FunctionRuntime;
|
|
11
|
+
}): {
|
|
12
|
+
authenticate: (req: Request) => Promise<import("./session.js").AdminSession | null>;
|
|
13
|
+
serveStatic(pathname: string): Response;
|
|
14
|
+
getLogin(request: Request): Promise<Response>;
|
|
15
|
+
postLogin(request: Request): Promise<Response>;
|
|
16
|
+
postLogout(request: Request, session: import("./session.js").AdminSession | null): Promise<Response>;
|
|
17
|
+
overview(session: import("./session.js").AdminSession): Promise<Response>;
|
|
18
|
+
listEndpoints(): Promise<Response>;
|
|
19
|
+
listUsers(): Promise<Response>;
|
|
20
|
+
handleTable(request: Request, tableOverride?: string, idOverride?: string): Promise<Response>;
|
|
21
|
+
manageUsers(request: Request): Promise<Response>;
|
|
22
|
+
handleLogs(url: URL): Promise<Response>;
|
|
23
|
+
handleEnv(request: Request): Promise<Response>;
|
|
24
|
+
handleBackups(request: Request): Promise<Response>;
|
|
25
|
+
handleStorage(request: Request): Promise<Response>;
|
|
26
|
+
handleCrons(request: Request): Promise<Response>;
|
|
27
|
+
handleSettings(request: Request): Promise<Response>;
|
|
28
|
+
};
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { type SqlExecutor } from 'local-lite/server';
|
|
2
|
+
import type { ServerSettings } from '../config.js';
|
|
3
|
+
import type { FunctionRuntime } from '../functions/index.js';
|
|
4
|
+
import { type SchemaDictionary } from '../schema.js';
|
|
5
|
+
export declare function createAdminOps(settings: ServerSettings, db: SqlExecutor, schema: SchemaDictionary, fnRuntime?: FunctionRuntime): {
|
|
6
|
+
handleEnv(request: Request): Promise<Response>;
|
|
7
|
+
handleBackups(request: Request): Promise<Response>;
|
|
8
|
+
handleStorage(request: Request): Promise<Response>;
|
|
9
|
+
handleCrons(request: Request): Promise<Response>;
|
|
10
|
+
handleSettings(request: Request): Promise<Response>;
|
|
11
|
+
};
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { SqlExecutor } from 'local-lite/server';
|
|
2
|
+
import type { ServerSettings } from '../config.js';
|
|
3
|
+
export interface AdminSession {
|
|
4
|
+
userId?: string;
|
|
5
|
+
email?: string;
|
|
6
|
+
consoleRole: 'super_admin' | 'admin';
|
|
7
|
+
}
|
|
8
|
+
export declare function createAdminSession(settings: ServerSettings, db: SqlExecutor): {
|
|
9
|
+
authenticate: (req: Request) => Promise<AdminSession | null>;
|
|
10
|
+
serveStatic(pathname: string): Response;
|
|
11
|
+
getLogin(request: Request): Promise<Response>;
|
|
12
|
+
postLogin(request: Request): Promise<Response>;
|
|
13
|
+
postLogout(request: Request, session: AdminSession | null): Promise<Response>;
|
|
14
|
+
};
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import type { SqlExecutor } from 'local-lite/server';
|
|
2
|
+
export type ApiKeyRole = 'admin' | 'user';
|
|
3
|
+
export interface ApiKeyRecord {
|
|
4
|
+
id: string;
|
|
5
|
+
name: string;
|
|
6
|
+
keyPrefix: string;
|
|
7
|
+
role: ApiKeyRole;
|
|
8
|
+
userId: string | null;
|
|
9
|
+
createdBy: string | null;
|
|
10
|
+
lastUsedAt: number | null;
|
|
11
|
+
expiresAt: number | null;
|
|
12
|
+
revokedAt: number | null;
|
|
13
|
+
createdAt: number;
|
|
14
|
+
}
|
|
15
|
+
export interface VerifiedApiKey {
|
|
16
|
+
id: string;
|
|
17
|
+
isAdmin: boolean;
|
|
18
|
+
userId?: string;
|
|
19
|
+
}
|
|
20
|
+
export declare function createApiKeyService(db: SqlExecutor): {
|
|
21
|
+
listKeys(): Promise<ApiKeyRecord[]>;
|
|
22
|
+
createKey(input: {
|
|
23
|
+
name: string;
|
|
24
|
+
role?: ApiKeyRole;
|
|
25
|
+
userId?: string | null;
|
|
26
|
+
createdBy?: string | null;
|
|
27
|
+
expiresAt?: number | null;
|
|
28
|
+
}): Promise<{
|
|
29
|
+
key: string;
|
|
30
|
+
record: ApiKeyRecord;
|
|
31
|
+
}>;
|
|
32
|
+
revokeKey(id: string): Promise<boolean>;
|
|
33
|
+
deleteKey(id: string): Promise<boolean>;
|
|
34
|
+
verifyKey(rawKey: string): Promise<VerifiedApiKey | null>;
|
|
35
|
+
};
|
|
36
|
+
export type ApiKeyService = ReturnType<typeof createApiKeyService>;
|
package/dist/app.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
package/dist/app.js
CHANGED
|
@@ -1,5 +1,9 @@
|
|
|
1
|
-
// cPanel / Passenger entry point (bundled to dist/cpanel/app.
|
|
1
|
+
// cPanel / Passenger entry point (bundled to dist/cpanel/app.mjs).
|
|
2
|
+
import fs from 'node:fs';
|
|
2
3
|
import { start } from './start.js';
|
|
4
|
+
if (fs.existsSync('.env')) {
|
|
5
|
+
process.loadEnvFile?.('.env');
|
|
6
|
+
}
|
|
3
7
|
start().catch((err) => {
|
|
4
8
|
console.error('[local-lite-server] failed to start:', err);
|
|
5
9
|
process.exit(1);
|
package/dist/auth.d.ts
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { type ServerAuthStorage, type SqlExecutor } from 'local-lite/server';
|
|
2
|
+
import type { ServerSettings } from './config.js';
|
|
3
|
+
/** SQL-backed accounts + reset OTPs (tables created by migration 0002_auth). */
|
|
4
|
+
export declare function createAuthStorage(db: SqlExecutor): ServerAuthStorage;
|
|
5
|
+
export interface AuthService {
|
|
6
|
+
enabled: boolean;
|
|
7
|
+
handler: (request: Request) => Promise<Response>;
|
|
8
|
+
/** True when the bearer/query token is a valid, non-revoked user token. */
|
|
9
|
+
verifyToken: (token: string) => Promise<boolean>;
|
|
10
|
+
verifyUser: (token: string) => Promise<{
|
|
11
|
+
id: string;
|
|
12
|
+
email: string;
|
|
13
|
+
} | null>;
|
|
14
|
+
userCount: () => Promise<number>;
|
|
15
|
+
}
|
|
16
|
+
export declare function createAuthService(s: ServerSettings, db: SqlExecutor): AuthService;
|
package/dist/cli.d.ts
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import type { FunctionRegistry } from './functions/index.js';
|
|
2
|
+
import type { SchemaDictionary } from './schema.js';
|
|
3
|
+
export declare function generateClientCode(schema: SchemaDictionary, functions: FunctionRegistry): string;
|
|
4
|
+
export declare function writeClientCode(outFile: string, schema: SchemaDictionary, functions: FunctionRegistry): string;
|
package/dist/config.d.ts
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import type { SqlDialect } from 'local-lite/server';
|
|
2
|
+
export interface SmtpSettings {
|
|
3
|
+
host: string;
|
|
4
|
+
port: number;
|
|
5
|
+
secure: boolean;
|
|
6
|
+
user?: string;
|
|
7
|
+
pass?: string;
|
|
8
|
+
from: string;
|
|
9
|
+
}
|
|
10
|
+
export interface ServerSettings {
|
|
11
|
+
/** Number, or a socket path when the host (Passenger/lsnode) provides one. */
|
|
12
|
+
port: number | string;
|
|
13
|
+
dialect: SqlDialect;
|
|
14
|
+
db: {
|
|
15
|
+
host: string;
|
|
16
|
+
port: number;
|
|
17
|
+
user: string;
|
|
18
|
+
password: string;
|
|
19
|
+
database: string;
|
|
20
|
+
ssl: boolean;
|
|
21
|
+
poolSize: number;
|
|
22
|
+
};
|
|
23
|
+
autoMigrate: boolean;
|
|
24
|
+
schemaPath?: string;
|
|
25
|
+
rulesPath?: string;
|
|
26
|
+
functionsDir?: string;
|
|
27
|
+
uploadDir: string;
|
|
28
|
+
backupDir: string;
|
|
29
|
+
internalCrons: boolean;
|
|
30
|
+
multiInstance: boolean;
|
|
31
|
+
apiKey: string;
|
|
32
|
+
/** Signs user tokens. Enables /auth when set. */
|
|
33
|
+
appSecret?: string;
|
|
34
|
+
appName: string;
|
|
35
|
+
adminUi: boolean;
|
|
36
|
+
smtp?: SmtpSettings;
|
|
37
|
+
corsOrigins: string[];
|
|
38
|
+
}
|
|
39
|
+
export declare function loadSettings(env?: NodeJS.ProcessEnv): ServerSettings;
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { type SqlExecutor, type SyncEventBroker } from 'local-lite/server';
|
|
2
|
+
import type { ServerSettings } from '../config.js';
|
|
3
|
+
export interface ManagedBroker extends SyncEventBroker {
|
|
4
|
+
close(): Promise<void>;
|
|
5
|
+
}
|
|
6
|
+
/**
|
|
7
|
+
* Single-node in-memory broker by default.
|
|
8
|
+
* When `MULTI_INSTANCE=true`:
|
|
9
|
+
* - Postgres: uses native LISTEN/NOTIFY on `lls_sync_events` (zero extra deps).
|
|
10
|
+
* - MySQL: polls `_server_changes` every 1s for changes from sibling instances.
|
|
11
|
+
*/
|
|
12
|
+
export declare function createClusterBroker(settings: ServerSettings, db: SqlExecutor): Promise<ManagedBroker>;
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { type SqlExecutor } from 'local-lite/server';
|
|
2
|
+
import type { SchemaFieldType } from '../schema.js';
|
|
3
|
+
/** Locks and reads `_server_sync_clock` inside an active transaction. */
|
|
4
|
+
export declare function lockClock(tx: SqlExecutor, clockTable?: string): Promise<number>;
|
|
5
|
+
/** Appends a row entry to `_server_changes` with an already-computed timestamp. */
|
|
6
|
+
export declare function appendChangeLog(tx: SqlExecutor, table: string, rowId: string, timestamp: number, changesTable?: string): Promise<void>;
|
|
7
|
+
/** Updates `_server_sync_clock` to `timestamp`. */
|
|
8
|
+
export declare function commitClock(tx: SqlExecutor, timestamp: number, clockTable?: string): Promise<void>;
|
|
9
|
+
/** Advances `_server_sync_clock` inside an active transaction and logs to `_server_changes`. */
|
|
10
|
+
export declare function recordChange(tx: SqlExecutor, table: string, rowId: string, changesTable?: string, clockTable?: string): Promise<number>;
|
|
11
|
+
/** Upserts a row into a schema-defined table using dialect-safe column conversion. */
|
|
12
|
+
export declare function upsertTableRow(tx: SqlExecutor, table: string, fields: Record<string, SchemaFieldType>, rowId: string, data: Record<string, any>, timestamp: number): Promise<void>;
|
|
13
|
+
/** Updates specified schema columns on an existing row. */
|
|
14
|
+
export declare function patchTableRow(tx: SqlExecutor, table: string, fields: Record<string, SchemaFieldType>, rowId: string, patch: Record<string, any>, timestamp: number): Promise<void>;
|
|
15
|
+
/** Soft-deletes or restores a row in a schema-defined table. */
|
|
16
|
+
export declare function setRowDeleted(tx: SqlExecutor, table: string, rowId: string, deleted: boolean, timestamp: number): Promise<void>;
|
|
17
|
+
export declare function newRowId(raw?: unknown): string;
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import http from 'node:http';
|
|
2
|
+
import type { ServerSettings } from '../config.js';
|
|
3
|
+
export declare function safeEqual(a: string, b: string): boolean;
|
|
4
|
+
export declare function corsHeaders(request: Request, s: ServerSettings): Record<string, string>;
|
|
5
|
+
/** Node `http.Server` -> Web `Request`/`Response` bridge with streaming SSE support. */
|
|
6
|
+
export declare function createHttpServer(app: {
|
|
7
|
+
fetch(req: Request): Promise<Response>;
|
|
8
|
+
}): http.Server<typeof http.IncomingMessage, typeof http.ServerResponse>;
|
package/dist/core/http.js
CHANGED
|
@@ -12,7 +12,7 @@ export function corsHeaders(request, s) {
|
|
|
12
12
|
const allowed = allowAll ? '*' : origin && s.corsOrigins.includes(origin) ? origin : '';
|
|
13
13
|
const h = {
|
|
14
14
|
'Access-Control-Allow-Methods': 'GET,POST,PATCH,DELETE,OPTIONS',
|
|
15
|
-
'Access-Control-Allow-Headers': 'Authorization,Content-Type,X-API-Key',
|
|
15
|
+
'Access-Control-Allow-Headers': 'Authorization,Content-Type,X-API-Key,X-Captcha-Token',
|
|
16
16
|
'Access-Control-Max-Age': '600',
|
|
17
17
|
};
|
|
18
18
|
if (allowed)
|
package/dist/cpanel.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function buildCpanelBundle(cwd?: string, outDir?: string): Promise<void>;
|
package/dist/cpanel.js
CHANGED
|
@@ -2,9 +2,16 @@ import fs from 'node:fs';
|
|
|
2
2
|
import { createRequire } from 'node:module';
|
|
3
3
|
import path from 'node:path';
|
|
4
4
|
import { build } from 'esbuild';
|
|
5
|
+
import { resolveRoutesFile } from './routes.js';
|
|
5
6
|
import { resolveRulesFile } from './rules.js';
|
|
6
7
|
import { resolveSchemaFile } from './schema.js';
|
|
7
8
|
const require = createRequire(import.meta.url);
|
|
9
|
+
const EXTERNAL_PEERS = [
|
|
10
|
+
'react-native', 'react-native/*', '@react-native/*', '@react-native-community/*',
|
|
11
|
+
'expo', 'expo-*', 'expo-modules-core', 'react', 'react/*',
|
|
12
|
+
'better-sqlite3', '@libsql/*', 'op-sqlite', '@op-engineering/*',
|
|
13
|
+
'pg-native',
|
|
14
|
+
];
|
|
8
15
|
export async function buildCpanelBundle(cwd = process.cwd(), outDir = 'dist/cpanel') {
|
|
9
16
|
const pkgRoot = path.resolve(import.meta.dirname, '..');
|
|
10
17
|
const isOwnRepo = fs.existsSync(path.resolve(cwd, 'src/cli.ts'));
|
|
@@ -36,12 +43,7 @@ export async function buildCpanelBundle(cwd = process.cwd(), outDir = 'dist/cpan
|
|
|
36
43
|
},
|
|
37
44
|
minify: true,
|
|
38
45
|
logLevel: 'info',
|
|
39
|
-
external:
|
|
40
|
-
'react-native', 'react-native/*', '@react-native/*', '@react-native-community/*',
|
|
41
|
-
'expo', 'expo-*', 'expo-modules-core', 'react', 'react/*',
|
|
42
|
-
'better-sqlite3', '@libsql/*', 'op-sqlite', '@op-engineering/*',
|
|
43
|
-
'pg-native',
|
|
44
|
-
],
|
|
46
|
+
external: EXTERNAL_PEERS,
|
|
45
47
|
});
|
|
46
48
|
try {
|
|
47
49
|
const schemaFile = resolveSchemaFile(undefined, cwd);
|
|
@@ -54,6 +56,22 @@ export async function buildCpanelBundle(cwd = process.cwd(), outDir = 'dist/cpan
|
|
|
54
56
|
if (rulesFile) {
|
|
55
57
|
fs.copyFileSync(rulesFile, path.join(absOut, 'rules.ts'));
|
|
56
58
|
}
|
|
59
|
+
const routesFile = resolveRoutesFile(undefined, cwd);
|
|
60
|
+
if (routesFile) {
|
|
61
|
+
await build({
|
|
62
|
+
entryPoints: [routesFile],
|
|
63
|
+
bundle: true,
|
|
64
|
+
platform: 'node',
|
|
65
|
+
target: 'node24',
|
|
66
|
+
format: 'esm',
|
|
67
|
+
treeShaking: true,
|
|
68
|
+
legalComments: 'none',
|
|
69
|
+
outfile: path.join(absOut, 'routes.mjs'),
|
|
70
|
+
minify: true,
|
|
71
|
+
logLevel: 'info',
|
|
72
|
+
external: EXTERNAL_PEERS,
|
|
73
|
+
});
|
|
74
|
+
}
|
|
57
75
|
const envExample = fs.existsSync(path.resolve(cwd, '.env.example'))
|
|
58
76
|
? path.resolve(cwd, '.env.example')
|
|
59
77
|
: path.resolve(pkgRoot, 'templates/.env.example');
|
package/dist/crons.d.ts
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { type SqlExecutor } from 'local-lite/server';
|
|
2
|
+
import type { ServerSettings } from './config.js';
|
|
3
|
+
import type { FunctionRuntime } from './functions/index.js';
|
|
4
|
+
export interface CronJobRecord {
|
|
5
|
+
job_key: string;
|
|
6
|
+
label: string;
|
|
7
|
+
action_type: string;
|
|
8
|
+
cron_expr: string;
|
|
9
|
+
timezone: string;
|
|
10
|
+
enabled: boolean | number;
|
|
11
|
+
config_json?: string | null;
|
|
12
|
+
last_run_at?: number | null;
|
|
13
|
+
}
|
|
14
|
+
export declare function matchesCron(expr: string, date: Date, timeZone?: string): boolean;
|
|
15
|
+
export declare function runCronAction(actionType: string, configJson: string | null | undefined, deps: {
|
|
16
|
+
settings: ServerSettings;
|
|
17
|
+
db: SqlExecutor;
|
|
18
|
+
fnRuntime?: FunctionRuntime;
|
|
19
|
+
}): Promise<string>;
|
|
20
|
+
export declare function startCronScheduler(deps: {
|
|
21
|
+
settings: ServerSettings;
|
|
22
|
+
db: SqlExecutor;
|
|
23
|
+
fnRuntime?: FunctionRuntime;
|
|
24
|
+
}): () => void;
|
package/dist/db.d.ts
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { type SqlExecutor } from 'local-lite/server';
|
|
2
|
+
import type { ServerSettings } from './config.js';
|
|
3
|
+
export interface Database {
|
|
4
|
+
executor: SqlExecutor;
|
|
5
|
+
close(): Promise<void>;
|
|
6
|
+
}
|
|
7
|
+
export declare function createDatabase(settings: ServerSettings): Promise<Database>;
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import type { FunctionRegistry } from './types.js';
|
|
2
|
+
export declare function loadFunctionsDir(dir?: string, cwd?: string, bustCache?: boolean): Promise<FunctionRegistry>;
|
|
3
|
+
/** Hot-reloads `functions/` in place on file edits without dropping SSE connections. */
|
|
4
|
+
export declare function watchFunctionsDir(dir: string | undefined, registry: FunctionRegistry, cwd?: string): () => void;
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { type SqlExecutor, type SyncEventBroker } from 'local-lite/server';
|
|
2
|
+
import type { SchemaDictionary } from '../schema.js';
|
|
3
|
+
import { type FunctionAuth, type FunctionKind, type FunctionRegistry } from './types.js';
|
|
4
|
+
export interface FunctionRuntime {
|
|
5
|
+
list(): Array<{
|
|
6
|
+
name: string;
|
|
7
|
+
kind: FunctionKind;
|
|
8
|
+
}>;
|
|
9
|
+
run(name: string, rawArgs: Record<string, unknown>, auth: FunctionAuth): Promise<{
|
|
10
|
+
result: unknown;
|
|
11
|
+
readTables: Set<string>;
|
|
12
|
+
}>;
|
|
13
|
+
subscribe(name: string, rawArgs: Record<string, unknown>, auth: FunctionAuth): Promise<Response>;
|
|
14
|
+
}
|
|
15
|
+
export declare function createFunctionRuntime(opts: {
|
|
16
|
+
registry: FunctionRegistry;
|
|
17
|
+
db: SqlExecutor;
|
|
18
|
+
schema: SchemaDictionary;
|
|
19
|
+
broker: SyncEventBroker;
|
|
20
|
+
scopeField?: string;
|
|
21
|
+
}): FunctionRuntime;
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
export type FunctionKind = 'query' | 'mutation' | 'action';
|
|
2
|
+
export declare class FunctionError extends Error {
|
|
3
|
+
status: number;
|
|
4
|
+
constructor(message: string, status?: number);
|
|
5
|
+
}
|
|
6
|
+
export interface FunctionAuth {
|
|
7
|
+
isAdmin: boolean;
|
|
8
|
+
userId?: string;
|
|
9
|
+
}
|
|
10
|
+
export interface ListOptions {
|
|
11
|
+
where?: Record<string, unknown>;
|
|
12
|
+
orderBy?: string;
|
|
13
|
+
order?: 'asc' | 'desc';
|
|
14
|
+
limit?: number;
|
|
15
|
+
offset?: number;
|
|
16
|
+
includeDeleted?: boolean;
|
|
17
|
+
}
|
|
18
|
+
export interface DbReader {
|
|
19
|
+
get(table: string, id: string): Promise<Record<string, any> | null>;
|
|
20
|
+
list(table: string, opts?: ListOptions): Promise<Record<string, any>[]>;
|
|
21
|
+
sql<T = Record<string, any>>(query: string, params?: unknown[], touchesTables?: string[]): Promise<T[]>;
|
|
22
|
+
}
|
|
23
|
+
export interface DbWriter extends DbReader {
|
|
24
|
+
insert(table: string, data: Record<string, unknown>): Promise<Record<string, any>>;
|
|
25
|
+
patch(table: string, id: string, patch: Record<string, unknown>): Promise<Record<string, any> | null>;
|
|
26
|
+
remove(table: string, id: string): Promise<boolean>;
|
|
27
|
+
}
|
|
28
|
+
export interface QueryContext {
|
|
29
|
+
db: DbReader;
|
|
30
|
+
auth: FunctionAuth;
|
|
31
|
+
}
|
|
32
|
+
export interface MutationContext {
|
|
33
|
+
db: DbWriter;
|
|
34
|
+
auth: FunctionAuth;
|
|
35
|
+
}
|
|
36
|
+
export interface ActionContext {
|
|
37
|
+
auth: FunctionAuth;
|
|
38
|
+
runQuery<T = unknown>(name: string, args?: Record<string, unknown>): Promise<T>;
|
|
39
|
+
runMutation<T = unknown>(name: string, args?: Record<string, unknown>): Promise<T>;
|
|
40
|
+
}
|
|
41
|
+
export type ArgValidator<TArgs> = (raw: Record<string, unknown>) => TArgs;
|
|
42
|
+
export interface FunctionDef<TCtx, TArgs, TRes> {
|
|
43
|
+
__kind: FunctionKind;
|
|
44
|
+
args?: ArgValidator<TArgs>;
|
|
45
|
+
handler: (ctx: TCtx, args: TArgs) => Promise<TRes> | TRes;
|
|
46
|
+
}
|
|
47
|
+
export type FunctionRegistry = Map<string, FunctionDef<any, any, any>>;
|
|
48
|
+
export declare function defineQuery<TArgs = Record<string, unknown>, TRes = unknown>(def: {
|
|
49
|
+
args?: ArgValidator<TArgs>;
|
|
50
|
+
handler: (ctx: QueryContext, args: TArgs) => Promise<TRes> | TRes;
|
|
51
|
+
}): FunctionDef<QueryContext, TArgs, TRes>;
|
|
52
|
+
export declare function defineMutation<TArgs = Record<string, unknown>, TRes = unknown>(def: {
|
|
53
|
+
args?: ArgValidator<TArgs>;
|
|
54
|
+
handler: (ctx: MutationContext, args: TArgs) => Promise<TRes> | TRes;
|
|
55
|
+
}): FunctionDef<MutationContext, TArgs, TRes>;
|
|
56
|
+
export declare function defineAction<TArgs = Record<string, unknown>, TRes = unknown>(def: {
|
|
57
|
+
args?: ArgValidator<TArgs>;
|
|
58
|
+
handler: (ctx: ActionContext, args: TArgs) => Promise<TRes> | TRes;
|
|
59
|
+
}): FunctionDef<ActionContext, TArgs, TRes>;
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
export { defineSchema, normalizeSchema } from './schema.js';
|
|
2
|
+
export type { SchemaDictionary, SchemaFieldType } from './schema.js';
|
|
3
|
+
export { defineRules } from './rules.js';
|
|
4
|
+
export type { RuleContext, RowPredicate, TableRule, RulesDictionary } from './rules.js';
|
|
5
|
+
export { defineQuery, defineMutation, defineAction, FunctionError, } from './functions/index.js';
|
|
6
|
+
export type { QueryContext, MutationContext, ActionContext, DbReader, DbWriter, FunctionAuth, FunctionKind, ListOptions, } from './functions/index.js';
|
|
7
|
+
export { TableSyncStorage, ClientError, ForbiddenError } from './tableStorage.js';
|
|
8
|
+
export { createApp, createHttpServer } from './server.js';
|
|
9
|
+
export { loadRoutesFile, resolveRoutesFile } from './routes.js';
|
|
10
|
+
export type { CustomRoutesContext, CustomRoutesFactory, CustomRoutesMap } from './routes.js';
|
|
11
|
+
export { loadSettings } from './config.js';
|
|
12
|
+
export type { ServerSettings } from './config.js';
|
package/dist/index.js
CHANGED
|
@@ -3,4 +3,5 @@ export { defineRules } from './rules.js';
|
|
|
3
3
|
export { defineQuery, defineMutation, defineAction, FunctionError, } from './functions/index.js';
|
|
4
4
|
export { TableSyncStorage, ClientError, ForbiddenError } from './tableStorage.js';
|
|
5
5
|
export { createApp, createHttpServer } from './server.js';
|
|
6
|
+
export { loadRoutesFile, resolveRoutesFile } from './routes.js';
|
|
6
7
|
export { loadSettings } from './config.js';
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import type { SqlExecutor } from 'local-lite/server';
|
|
2
|
+
interface Migration {
|
|
3
|
+
id: string;
|
|
4
|
+
mysql: string[];
|
|
5
|
+
postgres: string[];
|
|
6
|
+
}
|
|
7
|
+
/** Framework tables. App tables come from schema.ts. */
|
|
8
|
+
export declare const MIGRATIONS: Migration[];
|
|
9
|
+
export declare function runMigrations(db: SqlExecutor): Promise<{
|
|
10
|
+
applied: string[];
|
|
11
|
+
}>;
|
|
12
|
+
export declare function coreMigrationStatus(db: SqlExecutor): Promise<{
|
|
13
|
+
applied: string[];
|
|
14
|
+
pending: string[];
|
|
15
|
+
}>;
|
|
16
|
+
export {};
|
package/dist/oauth.d.ts
ADDED
|
@@ -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
|
+
}
|