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,2 @@
1
+ /*! tailwindcss v4.3.5 | MIT License | https://tailwindcss.com */
2
+ @layer properties{@supports (((-webkit-hyphens:none)) and (not (margin-trim:block))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))){*,:before,:after,::backdrop{--tw-rotate-x:initial;--tw-rotate-y:initial;--tw-rotate-z:initial;--tw-skew-x:initial;--tw-skew-y:initial;--tw-border-style:solid;--tw-blur:initial;--tw-brightness:initial;--tw-contrast:initial;--tw-grayscale:initial;--tw-hue-rotate:initial;--tw-invert:initial;--tw-opacity:initial;--tw-saturate:initial;--tw-sepia:initial;--tw-drop-shadow:initial;--tw-drop-shadow-color:initial;--tw-drop-shadow-alpha:100%;--tw-drop-shadow-size:initial}}}@layer theme{:root,:host{--font-sans:-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", "Noto Sans", Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";--font-mono:ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;--default-transition-duration:.15s;--default-transition-timing-function:cubic-bezier(.4, 0, .2, 1);--default-font-family:var(--font-sans);--default-mono-font-family:var(--font-mono)}}@layer base{*,:after,:before,::backdrop{box-sizing:border-box;border:0 solid;margin:0;padding:0}::file-selector-button{box-sizing:border-box;border:0 solid;margin:0;padding:0}html,:host{-webkit-text-size-adjust:100%;tab-size:4;line-height:1.5;font-family:var(--default-font-family,-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", "Noto Sans", Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji");font-feature-settings:var(--default-font-feature-settings,normal);font-variation-settings:var(--default-font-variation-settings,normal);-webkit-tap-highlight-color:transparent}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;-webkit-text-decoration:inherit;-webkit-text-decoration:inherit;-webkit-text-decoration:inherit;-webkit-text-decoration:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:var(--default-mono-font-family,ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace);font-feature-settings:var(--default-mono-font-feature-settings,normal);font-variation-settings:var(--default-mono-font-variation-settings,normal);font-size:1em}small{font-size:80%}sub,sup{vertical-align:baseline;font-size:75%;line-height:0;position:relative}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}:-moz-focusring:where(:not(iframe)){outline:auto}progress{vertical-align:baseline}summary{display:list-item}ol,ul,menu{list-style:none}img,svg,video,canvas,audio,iframe,embed,object{vertical-align:middle;display:block}img,video{max-width:100%;height:auto}button,input,select,optgroup,textarea{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}::file-selector-button{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}:where(select:is([multiple],[size])) optgroup{font-weight:bolder}:where(select:is([multiple],[size])) optgroup option{padding-inline-start:20px}::file-selector-button{margin-inline-end:4px}::placeholder{opacity:1}@supports (not ((-webkit-appearance:-apple-pay-button))) or (contain-intrinsic-size:1px){::placeholder{color:currentColor}@supports (color:color-mix(in lab, red, red)){::placeholder{color:color-mix(in oklab, currentcolor 50%, transparent)}}}textarea{resize:vertical}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-date-and-time-value{min-height:1lh;text-align:inherit}::-webkit-datetime-edit{display:inline-flex}::-webkit-datetime-edit-fields-wrapper{padding:0}::-webkit-datetime-edit{padding-block:0}::-webkit-datetime-edit-year-field{padding-block:0}::-webkit-datetime-edit-month-field{padding-block:0}::-webkit-datetime-edit-day-field{padding-block:0}::-webkit-datetime-edit-hour-field{padding-block:0}::-webkit-datetime-edit-minute-field{padding-block:0}::-webkit-datetime-edit-second-field{padding-block:0}::-webkit-datetime-edit-millisecond-field{padding-block:0}::-webkit-datetime-edit-meridiem-field{padding-block:0}::-webkit-calendar-picker-indicator{line-height:1}:-moz-ui-invalid{box-shadow:none}button,input:where([type=button],[type=reset],[type=submit]){appearance:button}::file-selector-button{appearance:button}::-webkit-inner-spin-button{height:auto}::-webkit-outer-spin-button{height:auto}[hidden]:where(:not([hidden=until-found])){display:none!important}}@layer components;@layer utilities{.collapse{visibility:collapse}.absolute{position:absolute}.fixed{position:fixed}.relative{position:relative}.block{display:block}.flex{display:flex}.grid{display:grid}.hidden{display:none}.inline-block{display:inline-block}.inline-flex{display:inline-flex}.table{display:table}.transform{transform:var(--tw-rotate-x, ) var(--tw-rotate-y, ) var(--tw-rotate-z, ) var(--tw-skew-x, ) var(--tw-skew-y, )}.resize{resize:both}.border{border-style:var(--tw-border-style);border-width:1px}.break-all{word-break:break-all}.uppercase{text-transform:uppercase}.underline{text-decoration-line:underline}.filter{filter:var(--tw-blur, ) var(--tw-brightness, ) var(--tw-contrast, ) var(--tw-grayscale, ) var(--tw-hue-rotate, ) var(--tw-invert, ) var(--tw-saturate, ) var(--tw-sepia, ) var(--tw-drop-shadow, )}.transition{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to,opacity,box-shadow,transform,translate,scale,rotate,filter,-webkit-backdrop-filter,backdrop-filter,display,content-visibility,overlay,pointer-events;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}}:root{--bg:#0c0d10;--sidebar:#111217;--surface:#16181f;--surface-alt:#1e2029;--surface-hover:#252834;--border:#272a36;--text:#f4f4f5;--muted:#9ca3af;--accent:#9e78dc;--accent-soft:#9e78dc24;--success:#4ade80;--success-soft:#4ade8024;--danger:#f87171;--danger-soft:#f8717124}*{box-sizing:border-box}html,body{overscroll-behavior-y:none;touch-action:manipulation;-webkit-font-smoothing:antialiased;margin:0;padding:0;font-family:-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica,Arial,sans-serif}.admin-theme{background:var(--bg);min-height:100vh;color:var(--text)}button,input,textarea,select{font-family:inherit}::-webkit-scrollbar{width:8px;height:8px}::-webkit-scrollbar-track{background:0 0}::-webkit-scrollbar-thumb{background:#2e313d;border-radius:4px}.app-shell{min-height:100vh;display:flex}.sidebar{background:var(--sidebar);border-right:1px solid var(--border);flex-direction:column;flex-shrink:0;justify-content:space-between;width:240px;height:100vh;padding:18px 12px;display:flex;position:sticky;top:0;overflow-y:auto}.nav-item{width:100%;color:var(--muted);cursor:pointer;text-align:left;background:0 0;border:none;border-radius:8px;align-items:center;gap:10px;padding:9px 12px;font-size:13.5px;font-weight:500;transition:background .15s,color .15s;display:flex}.nav-item:hover{background:var(--surface-alt);color:var(--text)}.nav-item.active{background:var(--accent-soft);color:var(--text);font-weight:600}.main-area{flex-direction:column;flex:1;min-width:0;display:flex}.topbar{border-bottom:1px solid var(--border);background:var(--sidebar);justify-content:space-between;align-items:center;gap:12px;height:58px;padding:0 24px;display:flex}.content-body{flex:1;min-width:0;padding:24px}@media (width<=820px){.app-shell{flex-direction:column}.sidebar{border-right:none;border-bottom:1px solid var(--border);width:100%;height:auto;padding:12px;position:static}}@property --tw-rotate-x{syntax:"*";inherits:false}@property --tw-rotate-y{syntax:"*";inherits:false}@property --tw-rotate-z{syntax:"*";inherits:false}@property --tw-skew-x{syntax:"*";inherits:false}@property --tw-skew-y{syntax:"*";inherits:false}@property --tw-border-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-blur{syntax:"*";inherits:false}@property --tw-brightness{syntax:"*";inherits:false}@property --tw-contrast{syntax:"*";inherits:false}@property --tw-grayscale{syntax:"*";inherits:false}@property --tw-hue-rotate{syntax:"*";inherits:false}@property --tw-invert{syntax:"*";inherits:false}@property --tw-opacity{syntax:"*";inherits:false}@property --tw-saturate{syntax:"*";inherits:false}@property --tw-sepia{syntax:"*";inherits:false}@property --tw-drop-shadow{syntax:"*";inherits:false}@property --tw-drop-shadow-color{syntax:"*";inherits:false}@property --tw-drop-shadow-alpha{syntax:"<percentage>";inherits:false;initial-value:100%}@property --tw-drop-shadow-size{syntax:"*";inherits:false}
@@ -0,0 +1,11 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" fill="none">
2
+ <defs>
3
+ <linearGradient id="bg" x1="8" y1="6" x2="56" y2="58" gradientUnits="userSpaceOnUse">
4
+ <stop offset="0%" stop-color="#9E78DC"/>
5
+ <stop offset="100%" stop-color="#5B3FA6"/>
6
+ </linearGradient>
7
+ </defs>
8
+ <rect width="64" height="64" rx="16" fill="url(#bg)"/>
9
+ <path d="M18 46V18H31C37.6 18 42 21.8 42 27.5C42 33.2 37.6 37 31 37H25V46H18ZM25 31H30.5C33.6 31 35.3 29.7 35.3 27.5C35.3 25.3 33.6 24 30.5 24H25V31Z" fill="#FFFFFF"/>
10
+ <circle cx="44" cy="43" r="5" fill="#4ADE80"/>
11
+ </svg>
@@ -0,0 +1,14 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8" />
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6
+ <link rel="icon" type="image/svg+xml" href="/admin/favicon.svg" />
7
+ <title>local-lite-server — Admin Console</title>
8
+ <script type="module" crossorigin src="/admin/assets/index-B2nX9Pef.js"></script>
9
+ <link rel="stylesheet" crossorigin href="/admin/assets/index-Dt3bXEks.css">
10
+ </head>
11
+ <body>
12
+ <div id="root"></div>
13
+ </body>
14
+ </html>
@@ -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,166 @@
1
+ import { quoteIdent } from 'local-lite/server';
2
+ import { fromDbRow } from '../tableStorage.js';
3
+ import { newRowId, patchTableRow, recordChange, setRowDeleted, upsertTableRow } from '../core/changes.js';
4
+ const int = (v, d, min, max) => Math.min(Math.max(Math.floor(Number(v ?? d)) || d, min), max);
5
+ export function createAdminData(opts) {
6
+ const { settings, db, schema, broker, fnRuntime } = opts;
7
+ const q = (n) => quoteIdent(n, db.dialect);
8
+ const notDeleted = db.dialect === 'postgres' ? 'FALSE' : '0';
9
+ return {
10
+ async overview(session) {
11
+ let dbConnected = true;
12
+ let dbError = null;
13
+ const tableCounts = [];
14
+ try {
15
+ for (const t of Object.keys(schema)) {
16
+ const r = await db.query(`SELECT COUNT(*) AS n FROM ${q(t)}`);
17
+ tableCounts.push({ table: t, count: Number(r[0]?.n ?? 0) });
18
+ }
19
+ }
20
+ catch {
21
+ dbConnected = false;
22
+ dbError = 'Database unavailable';
23
+ }
24
+ const acctRow = await db.query('SELECT COUNT(*) AS n FROM _local_auth_accounts');
25
+ const bkpRow = await db.query('SELECT COUNT(*) AS n FROM _lls_backups');
26
+ return Response.json({
27
+ health: { ok: dbConnected, dialect: settings.dialect },
28
+ dbConnected,
29
+ dbError,
30
+ tableCounts,
31
+ accountsCount: Number(acctRow[0]?.n ?? 0),
32
+ backupsCount: Number(bkpRow[0]?.n ?? 0),
33
+ consoleRole: session.consoleRole,
34
+ });
35
+ },
36
+ async listEndpoints() {
37
+ const fns = (fnRuntime?.list() ?? []).map((f) => ({
38
+ method: f.kind.toUpperCase(),
39
+ path: `/fn/${f.name}`,
40
+ }));
41
+ return Response.json({
42
+ endpoints: [
43
+ { method: 'GET', path: '/health' },
44
+ { method: 'GET', path: '/sync' },
45
+ { method: 'POST', path: '/sync' },
46
+ { method: 'GET', path: '/sync/events' },
47
+ ...fns,
48
+ ],
49
+ });
50
+ },
51
+ async listUsers() {
52
+ const accounts = await db.query('SELECT id, email, display_name, failed_login_attempts, locked_until, console_role, console_active, created_at FROM _local_auth_accounts ORDER BY created_at DESC LIMIT 200');
53
+ return Response.json({
54
+ localAccounts: accounts.map((a) => ({
55
+ id: String(a.id),
56
+ email: String(a.email),
57
+ displayName: a.display_name ?? null,
58
+ failedLoginAttempts: Number(a.failed_login_attempts ?? 0),
59
+ lockedUntil: a.locked_until != null ? Number(a.locked_until) : null,
60
+ tokenVersion: 1,
61
+ consoleRole: a.console_role ?? null,
62
+ consoleActive: Boolean(a.console_active),
63
+ createdAt: Number(a.created_at),
64
+ })),
65
+ });
66
+ },
67
+ async handleTable(request, tableOverride, idOverride) {
68
+ const url = new URL(request.url);
69
+ const method = request.method.toUpperCase();
70
+ if (method === 'GET') {
71
+ const table = tableOverride || url.searchParams.get('table') || '';
72
+ if (!Object.hasOwn(schema, table))
73
+ return Response.json({ error: 'Invalid table name.' }, { status: 400 });
74
+ const fields = schema[table];
75
+ const limit = int(url.searchParams.get('limit'), 30, 1, 500);
76
+ const offset = int(url.searchParams.get('offset'), 0, 0, 10_000_000);
77
+ const where = url.searchParams.get('includeDeleted') === '1' ? '' : `WHERE ${q('deleted')} = ${notDeleted}`;
78
+ const total = Number((await db.query(`SELECT COUNT(*) AS n FROM ${q(table)} ${where}`))[0]?.n ?? 0);
79
+ const raw = await db.query(`SELECT * FROM ${q(table)} ${where} ORDER BY ${q('updated_at')} DESC LIMIT ${limit} OFFSET ${offset}`);
80
+ return Response.json({
81
+ table,
82
+ columns: [...Object.keys(fields), 'deleted', 'updated_at'],
83
+ total,
84
+ limit,
85
+ offset,
86
+ rows: raw.map((r) => ({ id: String(r.id), ...fromDbRow(fields, r) })),
87
+ });
88
+ }
89
+ const body = (await request.json().catch(() => null));
90
+ const table = tableOverride || url.searchParams.get('table') || String(body?.table ?? '');
91
+ if (!Object.hasOwn(schema, table))
92
+ return Response.json({ error: 'Invalid table name.' }, { status: 400 });
93
+ const fields = schema[table];
94
+ const rowData = body?.row && typeof body.row === 'object' ? body.row : body || {};
95
+ if (method === 'POST' || method === 'PATCH') {
96
+ const id = idOverride || newRowId(rowData.id);
97
+ const ts = await db.withTransaction(async (tx) => {
98
+ const checkpoint = await recordChange(tx, table, id);
99
+ if (method === 'PATCH')
100
+ await patchTableRow(tx, table, fields, id, rowData, checkpoint);
101
+ else
102
+ await upsertTableRow(tx, table, fields, id, rowData, checkpoint);
103
+ return checkpoint;
104
+ });
105
+ broker?.publish({ scopeId: 'default', tableName: table, checkpoint: ts });
106
+ return Response.json({ success: true, id, cursor: ts }, { status: method === 'POST' ? 201 : 200 });
107
+ }
108
+ if (method === 'DELETE') {
109
+ const id = idOverride || url.searchParams.get('id') || String(body?.id ?? '');
110
+ const restore = url.searchParams.get('restore') === '1';
111
+ const ts = await db.withTransaction(async (tx) => {
112
+ const checkpoint = await recordChange(tx, table, id);
113
+ await setRowDeleted(tx, table, id, !restore, checkpoint);
114
+ return checkpoint;
115
+ });
116
+ broker?.publish({ scopeId: 'default', tableName: table, checkpoint: ts });
117
+ return Response.json({ success: true, id, deleted: !restore, cursor: ts });
118
+ }
119
+ return Response.json({ error: 'Method Not Allowed' }, { status: 405 });
120
+ },
121
+ async manageUsers(request) {
122
+ const body = (await request.json().catch(() => null));
123
+ const userId = String(body?.userId ?? '');
124
+ const action = String(body?.action ?? '');
125
+ if (!userId)
126
+ return Response.json({ error: 'userId is required.' }, { status: 400 });
127
+ if (action === 'unlock') {
128
+ await db.execute('UPDATE _local_auth_accounts SET failed_login_attempts = 0, locked_until = NULL, updated_at = ? WHERE id = ?', [Date.now(), userId]);
129
+ }
130
+ else if (action === 'revoke_sessions') {
131
+ await db.execute('UPDATE _local_auth_accounts SET token_version = COALESCE(token_version, 1) + 1, updated_at = ? WHERE id = ?', [Date.now(), userId]);
132
+ }
133
+ else if (action === 'set_console_role') {
134
+ const role = body?.consoleRole === 'super_admin' || body?.consoleRole === 'admin' ? body.consoleRole : null;
135
+ const active = role !== null;
136
+ await db.execute('UPDATE _local_auth_accounts SET console_role = ?, console_active = ?, updated_at = ? WHERE id = ?', [role, db.dialect === 'postgres' ? active : active ? 1 : 0, Date.now(), userId]);
137
+ }
138
+ else {
139
+ return Response.json({ error: 'Unsupported action.' }, { status: 400 });
140
+ }
141
+ return Response.json({ success: true });
142
+ },
143
+ async handleLogs(url) {
144
+ const table = url.searchParams.get('table') || 'ALL';
145
+ const limit = int(url.searchParams.get('limit'), 30, 1, 200);
146
+ const offset = int(url.searchParams.get('offset'), 0, 0, 10_000_000);
147
+ const hasTable = table !== 'ALL' && Object.hasOwn(schema, table);
148
+ const where = hasTable ? 'WHERE table_name = ?' : '';
149
+ const params = hasTable ? [table] : [];
150
+ const total = Number((await db.query(`SELECT COUNT(*) AS n FROM ${q('_server_changes')} ${where}`, params))[0]?.n ?? 0);
151
+ const raw = await db.query(`SELECT id, table_name, row_id, ${q('timestamp')} FROM ${q('_server_changes')} ${where} ORDER BY id DESC LIMIT ${limit} OFFSET ${offset}`, params);
152
+ return Response.json({
153
+ total,
154
+ limit,
155
+ offset,
156
+ rows: raw.map((r) => ({
157
+ tableName: r.table_name,
158
+ rowId: r.row_id,
159
+ operation: 'UPSERT',
160
+ businessId: '',
161
+ updatedAt: Number(r.timestamp),
162
+ })),
163
+ });
164
+ },
165
+ };
166
+ }
@@ -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,13 @@
1
+ import { createAdminData } from './console.js';
2
+ import { createAdminOps } from './ops.js';
3
+ import { createAdminSession } from './session.js';
4
+ export function createAdminConsole(opts) {
5
+ const session = createAdminSession(opts.settings, opts.db);
6
+ const data = createAdminData(opts);
7
+ const ops = createAdminOps(opts.settings, opts.db, opts.schema, opts.fnRuntime);
8
+ return {
9
+ ...session,
10
+ ...data,
11
+ ...ops,
12
+ };
13
+ }
@@ -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,279 @@
1
+ import crypto from 'node:crypto';
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import { buildUpsertSql, quoteIdent } from 'local-lite/server';
5
+ import { sendSmtpMail } from '../core/mailer.js';
6
+ import { runCronAction } from '../crons.js';
7
+ import { applySchema, planSchema } from '../schema.js';
8
+ import { fromDbRow } from '../tableStorage.js';
9
+ const int = (v, d, min, max) => Math.min(Math.max(Math.floor(Number(v ?? d)) || d, min), max);
10
+ export function createAdminOps(settings, db, schema, fnRuntime) {
11
+ const q = (n) => quoteIdent(n, db.dialect);
12
+ return {
13
+ async handleEnv(request) {
14
+ const method = request.method.toUpperCase();
15
+ if (method === 'GET') {
16
+ const rows = await db.query('SELECT var_key, var_value, is_secret, updated_at FROM _lls_env_vars ORDER BY var_key ASC');
17
+ return Response.json({
18
+ vars: rows.map((r) => ({
19
+ key: r.var_key,
20
+ value: r.is_secret ? '••••••••' : r.var_value,
21
+ masked: Boolean(r.is_secret),
22
+ revealable: Boolean(r.is_secret),
23
+ updatedAt: Number(r.updated_at),
24
+ source: 'db',
25
+ })),
26
+ });
27
+ }
28
+ if (method === 'POST') {
29
+ const body = (await request.json().catch(() => null));
30
+ if (body?.action === 'reveal') {
31
+ const rows = await db.query('SELECT var_value FROM _lls_env_vars WHERE var_key = ?', [String(body.key ?? '')]);
32
+ return Response.json({ value: rows[0]?.var_value ?? '' });
33
+ }
34
+ const key = String(body?.key ?? '').trim();
35
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key))
36
+ return Response.json({ error: 'Invalid key.' }, { status: 400 });
37
+ const val = String(body?.value ?? '');
38
+ const isSecret = Boolean(body?.isSecret ?? body?.secret);
39
+ await db.execute(buildUpsertSql({
40
+ table: '_lls_env_vars',
41
+ conflictCols: ['var_key'],
42
+ insertCols: ['var_key', 'var_value', 'is_secret', 'updated_at'],
43
+ updateCols: ['var_value', 'is_secret', 'updated_at'],
44
+ dialect: db.dialect,
45
+ }), [key, val, db.dialect === 'postgres' ? isSecret : isSecret ? 1 : 0, Date.now()]);
46
+ process.env[key] = val;
47
+ return Response.json({ success: true });
48
+ }
49
+ if (method === 'DELETE') {
50
+ const key = new URL(request.url).searchParams.get('key') || '';
51
+ await db.execute('DELETE FROM _lls_env_vars WHERE var_key = ?', [key]);
52
+ return Response.json({ success: true });
53
+ }
54
+ return Response.json({ error: 'Method Not Allowed' }, { status: 405 });
55
+ },
56
+ async handleBackups(request) {
57
+ const dir = path.resolve(settings.backupDir);
58
+ const url = new URL(request.url);
59
+ const method = request.method.toUpperCase();
60
+ if (method === 'GET') {
61
+ const file = url.searchParams.get('file');
62
+ if (!file) {
63
+ const rows = await db.query('SELECT id, user_id, file_name, status, size_bytes, record_count, created_at FROM _lls_backups ORDER BY created_at DESC LIMIT 50');
64
+ return Response.json({
65
+ backups: rows.map((b) => ({
66
+ id: String(b.id),
67
+ userId: String(b.user_id),
68
+ fileName: String(b.file_name),
69
+ status: String(b.status),
70
+ sizeBytes: Number(b.size_bytes),
71
+ recordCount: Number(b.record_count),
72
+ createdAt: Number(b.created_at),
73
+ })),
74
+ });
75
+ }
76
+ const target = path.resolve(dir, path.basename(file));
77
+ if (!fs.existsSync(target))
78
+ return Response.json({ error: 'Backup not found.' }, { status: 404 });
79
+ return new Response(fs.readFileSync(target), { headers: { 'content-type': 'application/json; charset=utf-8' } });
80
+ }
81
+ if (method === 'POST') {
82
+ fs.mkdirSync(dir, { recursive: true });
83
+ const data = {};
84
+ let recordCount = 0;
85
+ for (const [table, fields] of Object.entries(schema)) {
86
+ const rows = await db.query(`SELECT * FROM ${q(table)}`);
87
+ data[table] = rows.map((r) => ({ id: String(r.id), ...fromDbRow(fields, r) }));
88
+ recordCount += rows.length;
89
+ }
90
+ const now = Date.now();
91
+ const fileName = `backup-${settings.db.database}-${now}.json`;
92
+ const json = JSON.stringify({ version: 1, dialect: settings.dialect, exportedAt: now, tables: data }, null, 2);
93
+ fs.writeFileSync(path.join(dir, fileName), json);
94
+ const backup = {
95
+ id: crypto.randomUUID(),
96
+ userId: 'system',
97
+ fileName,
98
+ status: 'completed',
99
+ sizeBytes: Buffer.byteLength(json),
100
+ recordCount,
101
+ createdAt: now,
102
+ };
103
+ await db.execute('INSERT INTO _lls_backups (id, user_id, file_name, status, size_bytes, record_count, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)', [backup.id, backup.userId, backup.fileName, backup.status, backup.sizeBytes, backup.recordCount, backup.createdAt]);
104
+ return Response.json({ success: true, backup });
105
+ }
106
+ if (method === 'DELETE') {
107
+ const file = path.basename(url.searchParams.get('file') || '');
108
+ const target = path.resolve(dir, file);
109
+ if (fs.existsSync(target))
110
+ fs.unlinkSync(target);
111
+ await db.execute('DELETE FROM _lls_backups WHERE file_name = ?', [file]);
112
+ return Response.json({ success: true });
113
+ }
114
+ return Response.json({ error: 'Method Not Allowed' }, { status: 405 });
115
+ },
116
+ async handleStorage(request) {
117
+ const url = new URL(request.url);
118
+ const method = request.method.toUpperCase();
119
+ if (method === 'GET') {
120
+ const bucket = url.searchParams.get('bucket');
121
+ const limit = int(url.searchParams.get('limit'), 30, 1, 200);
122
+ const offset = int(url.searchParams.get('offset'), 0, 0, 10_000_000);
123
+ const buckets = await db.query('SELECT * FROM _lls_storage_buckets ORDER BY name ASC');
124
+ const where = bucket ? 'WHERE bucket = ?' : '';
125
+ const params = bucket ? [bucket] : [];
126
+ const files = await db.query(`SELECT * FROM _lls_storage_files ${where} ORDER BY created_at DESC LIMIT ${limit} OFFSET ${offset}`, params);
127
+ const totals = await db.query(`SELECT COUNT(*) AS n, COALESCE(SUM(size_bytes), 0) AS b FROM _lls_storage_files ${where}`, params);
128
+ return Response.json({
129
+ buckets,
130
+ files,
131
+ totalFiles: Number(totals[0]?.n ?? 0),
132
+ totalBytes: Number(totals[0]?.b ?? 0),
133
+ });
134
+ }
135
+ if (method === 'POST') {
136
+ const body = (await request.json().catch(() => null));
137
+ const name = String(body?.name ?? '').trim().toLowerCase();
138
+ if (!/^[a-z0-9][a-z0-9_-]{0,63}$/.test(name))
139
+ return Response.json({ error: 'Invalid bucket name.' }, { status: 400 });
140
+ const vis = body?.visibility === 'public' ? 'public' : 'private';
141
+ await db.execute(buildUpsertSql({
142
+ table: '_lls_storage_buckets',
143
+ conflictCols: ['name'],
144
+ insertCols: ['name', 'visibility', 'created_at'],
145
+ updateCols: ['visibility'],
146
+ dialect: db.dialect,
147
+ }), [name, vis, Date.now()]);
148
+ return Response.json({ success: true, name, visibility: vis }, { status: 201 });
149
+ }
150
+ if (method === 'DELETE') {
151
+ const bucket = url.searchParams.get('bucket');
152
+ const key = url.searchParams.get('key');
153
+ if (bucket) {
154
+ await db.execute('DELETE FROM _lls_storage_buckets WHERE name = ?', [bucket]);
155
+ return Response.json({ success: true });
156
+ }
157
+ if (key) {
158
+ const target = path.resolve(settings.uploadDir, key);
159
+ if (fs.existsSync(target))
160
+ fs.unlinkSync(target);
161
+ await db.execute('DELETE FROM _lls_storage_files WHERE storage_key = ?', [key]);
162
+ return Response.json({ success: true });
163
+ }
164
+ return Response.json({ error: 'bucket or key required.' }, { status: 400 });
165
+ }
166
+ return Response.json({ error: 'Method Not Allowed' }, { status: 405 });
167
+ },
168
+ async handleCrons(request) {
169
+ const method = request.method.toUpperCase();
170
+ if (method === 'GET') {
171
+ const jobs = await db.query('SELECT * FROM _lls_crons ORDER BY job_key ASC');
172
+ return Response.json({ jobs });
173
+ }
174
+ if (method === 'POST') {
175
+ const jobParam = new URL(request.url).searchParams.get('job');
176
+ if (jobParam === 'storage_orphan_prune') {
177
+ const summary = await runCronAction('storage_orphan_prune', null, { settings, db, fnRuntime });
178
+ return Response.json({ success: true, summary });
179
+ }
180
+ const body = (await request.json().catch(() => null));
181
+ const jobKey = String(body?.job_key ?? '').trim();
182
+ if (body?.action === 'save') {
183
+ await db.execute(buildUpsertSql({
184
+ table: '_lls_crons',
185
+ conflictCols: ['job_key'],
186
+ insertCols: ['job_key', 'label', 'action_type', 'cron_expr', 'timezone', 'enabled', 'config_json'],
187
+ updateCols: ['label', 'action_type', 'cron_expr', 'timezone', 'enabled', 'config_json'],
188
+ dialect: db.dialect,
189
+ }), [
190
+ jobKey,
191
+ String(body.label || jobKey),
192
+ String(body.action_type || 'http_webhook'),
193
+ String(body.cron_expr || '0 * * * *'),
194
+ String(body.timezone || 'UTC'),
195
+ db.dialect === 'postgres' ? body.enabled !== false : body.enabled !== false ? 1 : 0,
196
+ body.config_json ? JSON.stringify(body.config_json) : null,
197
+ ]);
198
+ return Response.json({ success: true });
199
+ }
200
+ const rows = await db.query('SELECT * FROM _lls_crons WHERE job_key = ?', [jobKey]);
201
+ const job = rows[0];
202
+ if (!job)
203
+ return Response.json({ error: 'Schedule not found.' }, { status: 404 });
204
+ try {
205
+ const summary = await runCronAction(job.action_type, job.config_json, { settings, db, fnRuntime });
206
+ await db.execute('UPDATE _lls_crons SET last_run_at = ?, last_status = ?, last_summary = ? WHERE job_key = ?', [
207
+ Date.now(), 'ok', summary, jobKey,
208
+ ]);
209
+ return Response.json({ success: true, summary });
210
+ }
211
+ catch (err) {
212
+ const msg = err instanceof Error ? err.message : 'Execution failed.';
213
+ await db.execute('UPDATE _lls_crons SET last_run_at = ?, last_status = ?, last_summary = ? WHERE job_key = ?', [
214
+ Date.now(), 'error', msg, jobKey,
215
+ ]);
216
+ return Response.json({ error: msg }, { status: 500 });
217
+ }
218
+ }
219
+ if (method === 'DELETE') {
220
+ const jobKey = new URL(request.url).searchParams.get('job_key') || '';
221
+ await db.execute('DELETE FROM _lls_crons WHERE job_key = ?', [jobKey]);
222
+ return Response.json({ success: true });
223
+ }
224
+ return Response.json({ error: 'Method Not Allowed' }, { status: 405 });
225
+ },
226
+ async handleSettings(request) {
227
+ if (request.method.toUpperCase() === 'POST') {
228
+ const body = (await request.json().catch(() => ({})));
229
+ if (body.action === 'apply_schema') {
230
+ const plan = await applySchema(db, schema);
231
+ return Response.json({ ok: true, applied: plan.up.length, warnings: plan.warnings });
232
+ }
233
+ if (body.action === 'test_email') {
234
+ if (!settings.smtp)
235
+ return Response.json({ ok: false, error: 'SMTP is not configured.' }, { status: 400 });
236
+ const to = String(body.to ?? '').trim();
237
+ if (!to || !to.includes('@'))
238
+ return Response.json({ ok: false, error: 'Valid recipient email is required.' }, { status: 400 });
239
+ await sendSmtpMail(settings.smtp, to, `${settings.appName} SMTP Test`, `SMTP is working on ${settings.appName} (${new Date().toISOString()}).`);
240
+ return Response.json({ ok: true });
241
+ }
242
+ const t0 = Date.now();
243
+ try {
244
+ await db.query('SELECT 1');
245
+ return Response.json({ ok: true, status: 200, latencyMs: Date.now() - t0 });
246
+ }
247
+ catch (err) {
248
+ return Response.json({ ok: false, status: 503, latencyMs: Date.now() - t0, error: String(err) });
249
+ }
250
+ }
251
+ const plan = await planSchema(db, schema).catch(() => null);
252
+ return Response.json({
253
+ mode: 'self-hosted',
254
+ dialect: settings.dialect,
255
+ dbHost: settings.db.host,
256
+ dbPort: String(settings.db.port),
257
+ dbName: settings.db.database,
258
+ poolSize: settings.db.poolSize,
259
+ corsOrigins: settings.corsOrigins,
260
+ uploadDir: settings.uploadDir,
261
+ backupDir: settings.backupDir,
262
+ nodeVersion: process.version,
263
+ uptimeSeconds: Math.floor(process.uptime()),
264
+ memoryMb: Math.round(process.memoryUsage().rss / 1024 / 1024),
265
+ pendingSql: plan?.up ?? [],
266
+ schemaWarnings: plan?.warnings ?? [],
267
+ integrations: {
268
+ appSecret: Boolean(settings.appSecret),
269
+ smtp: Boolean(settings.smtp),
270
+ autoMigrate: settings.autoMigrate,
271
+ internalCrons: settings.internalCrons,
272
+ multiInstance: settings.multiInstance,
273
+ googleOAuth: Boolean(process.env.GOOGLE_CLIENT_SECRET),
274
+ githubOAuth: Boolean(process.env.GITHUB_CLIENT_SECRET),
275
+ },
276
+ });
277
+ },
278
+ };
279
+ }
@@ -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
+ };