levix-bot 4.2.1 → 4.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/app.cjs +50 -4
- package/package.json +1 -1
- package/public/dashboard/assets/index-BCXZoPGP.js +446 -0
- package/public/dashboard/index.html +1 -1
- package/public/dashboard.css +71 -1
- package/public/gateway.js +41 -0
- package/src/bootstrap/core.js +4 -0
- package/src/bootstrap/panel.js +2 -0
- package/src/commands/autoschedule.cjs +10 -13
- package/src/commands/block.cjs +1 -1
- package/src/commands/restart.cjs +46 -17
- package/src/commands/schedule.cjs +8 -10
- package/src/commands/send.cjs +116 -0
- package/src/commands/stopbot.cjs +68 -0
- package/src/commands/unblock.cjs +1 -1
- package/src/config/defaults.cjs +2 -1
- package/src/config/settings.cjs +4 -2
- package/src/core/session-holder.cjs +23 -0
- package/src/handlers/command.handler.js +3 -5
- package/src/panel/password-reset.cjs +187 -0
- package/src/routes/dashboard.api.esm.js +48 -78
- package/src/services/settingsTransfer.cjs +246 -0
- package/views/login.ejs +209 -9
- package/views/setup.ejs +19 -5
- package/public/dashboard/assets/index-4AuqfnH5.js +0 -431
- package/src/commands/shutdown.cjs +0 -55
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
// Password reset over WhatsApp.
|
|
2
|
+
//
|
|
3
|
+
// The panel password is a one-way hash (src/config/secrets.cjs) — there is
|
|
4
|
+
// nothing to "recover". This is the recovery path that matches the product:
|
|
5
|
+
// the bot itself messages the operator's WhatsApp with a one-time code. It
|
|
6
|
+
// works because the paired account IS the operator's account, so "send the
|
|
7
|
+
// code over WhatsApp" means "drop it in your own chat" — reachable whenever
|
|
8
|
+
// the session is up, with no email server and nothing to configure.
|
|
9
|
+
//
|
|
10
|
+
// Why a WhatsApp code rather than passkeys / biometrics (WebAuthn)? WebAuthn
|
|
11
|
+
// only exists in a secure context: HTTPS or localhost. A Levix panel is very
|
|
12
|
+
// often opened at plain http://<lan-ip>:3001, where no browser will offer a
|
|
13
|
+
// passkey at all. The code works on every shape of install, and
|
|
14
|
+
// `levix reset-password` on the server stays the offline fallback for when
|
|
15
|
+
// WhatsApp itself is down.
|
|
16
|
+
//
|
|
17
|
+
// The code lives only in this process's memory — hashed, 10 minutes, five
|
|
18
|
+
// verification attempts, single use. A restart clears it, which is fine:
|
|
19
|
+
// requesting a new one costs nothing. Requests are throttled per TCP peer
|
|
20
|
+
// (never `req.ip`, same discipline as login-throttle) and globally, because
|
|
21
|
+
// every accepted request costs the operator one WhatsApp message.
|
|
22
|
+
|
|
23
|
+
const crypto = require("node:crypto");
|
|
24
|
+
|
|
25
|
+
const logger = require("../utils/logger.cjs");
|
|
26
|
+
const secrets = require("../config/secrets.cjs");
|
|
27
|
+
const brand = require("../config/brand.cjs");
|
|
28
|
+
const { sendBotMessage } = require("../utils/sendBotMessage.cjs");
|
|
29
|
+
const { withLang, detectLang, tr } = require("../utils/i18n.cjs");
|
|
30
|
+
const normalizeJid = require("../utils/normalizeJid.esm.js").default;
|
|
31
|
+
|
|
32
|
+
const CODE_TTL_MS = 10 * 60 * 1000;
|
|
33
|
+
const MAX_CODE_ATTEMPTS = 5;
|
|
34
|
+
const REQUEST_WINDOW_MS = 15 * 60 * 1000;
|
|
35
|
+
const MAX_REQUESTS_PER_WINDOW = 3;
|
|
36
|
+
// Any peer may not trigger two sends closer than this — the code goes to the
|
|
37
|
+
// operator's own WhatsApp, and nobody should be able to machine-gun it.
|
|
38
|
+
const GLOBAL_COOLDOWN_MS = 60 * 1000;
|
|
39
|
+
|
|
40
|
+
// The backend's WhatsApp session manager, handed over by bootstrapPanel()
|
|
41
|
+
// next to the dashboard API's setSession(). Re-read the socket every time —
|
|
42
|
+
// a reconnect replaces it.
|
|
43
|
+
let session = null;
|
|
44
|
+
let pending = null; // { salt, hash, expiresAt, attempts }
|
|
45
|
+
let lastRequestAt = 0;
|
|
46
|
+
const requests = new Map(); // peer -> { count, firstAt }
|
|
47
|
+
|
|
48
|
+
function setSession(manager) {
|
|
49
|
+
session = manager;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** Tests: drop the in-memory code and throttle state. */
|
|
53
|
+
function _resetForTests() {
|
|
54
|
+
pending = null;
|
|
55
|
+
lastRequestAt = 0;
|
|
56
|
+
requests.clear();
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function hashCode(code, salt) {
|
|
60
|
+
return crypto.createHash("sha256").update(`${salt}:${code}`).digest("hex");
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function codeMessage(code) {
|
|
64
|
+
return withLang(detectLang(""), () =>
|
|
65
|
+
tr(
|
|
66
|
+
`🔐 *${brand.name} — password reset code: ${code}*\n\n` +
|
|
67
|
+
`Enter it in the control panel within 10 minutes. ` +
|
|
68
|
+
`If you didn't request this, ignore this message — nobody else can use it.`,
|
|
69
|
+
`🔐 *${brand.name} — كود إعادة تعيين كلمة السر: ${code}*\n\n` +
|
|
70
|
+
`ادخل الكود في لوحة التحكم خلال ١٠ دقائق. ` +
|
|
71
|
+
`لو مش إنت اللي طلبته، اهمل الرسالة — مفيش حد تاني يقدر يستخدمه.`,
|
|
72
|
+
),
|
|
73
|
+
);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Generate a reset code and WhatsApp it to the linked account's own chat.
|
|
78
|
+
*
|
|
79
|
+
* @returns {Promise<object>} { ok: true } or { ok: false, reason, ... }
|
|
80
|
+
*/
|
|
81
|
+
async function requestResetCode(peer) {
|
|
82
|
+
const now = Date.now();
|
|
83
|
+
|
|
84
|
+
for (const [key, entry] of requests) {
|
|
85
|
+
if (now - entry.firstAt > REQUEST_WINDOW_MS) requests.delete(key);
|
|
86
|
+
}
|
|
87
|
+
const entry = requests.get(peer);
|
|
88
|
+
if (entry && entry.count >= MAX_REQUESTS_PER_WINDOW) {
|
|
89
|
+
return {
|
|
90
|
+
ok: false,
|
|
91
|
+
reason: "throttled",
|
|
92
|
+
retryAfter: Math.ceil((REQUEST_WINDOW_MS - (now - entry.firstAt)) / 1000),
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
const sinceLast = now - lastRequestAt;
|
|
96
|
+
if (lastRequestAt && sinceLast < GLOBAL_COOLDOWN_MS) {
|
|
97
|
+
return {
|
|
98
|
+
ok: false,
|
|
99
|
+
reason: "throttled",
|
|
100
|
+
retryAfter: Math.ceil((GLOBAL_COOLDOWN_MS - sinceLast) / 1000),
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
const sock = session?.socket ?? null;
|
|
105
|
+
if (!sock?.user?.id) {
|
|
106
|
+
return { ok: false, reason: "no_session" };
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
const code = String(crypto.randomInt(0, 1_000_000)).padStart(6, "0");
|
|
110
|
+
const salt = crypto.randomBytes(16).toString("hex");
|
|
111
|
+
pending = { salt, hash: hashCode(code, salt), expiresAt: now + CODE_TTL_MS, attempts: 0 };
|
|
112
|
+
|
|
113
|
+
try {
|
|
114
|
+
await sendBotMessage(
|
|
115
|
+
sock,
|
|
116
|
+
normalizeJid(sock.user.id),
|
|
117
|
+
{ text: codeMessage(code) },
|
|
118
|
+
{
|
|
119
|
+
typing: false,
|
|
120
|
+
delayMs: 0,
|
|
121
|
+
},
|
|
122
|
+
);
|
|
123
|
+
} catch (error) {
|
|
124
|
+
pending = null;
|
|
125
|
+
logger.error({ err: error }, "[reset] failed to send the reset code over WhatsApp");
|
|
126
|
+
return { ok: false, reason: "send_failed" };
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
lastRequestAt = now;
|
|
130
|
+
if (entry) entry.count += 1;
|
|
131
|
+
else requests.set(peer, { count: 1, firstAt: now });
|
|
132
|
+
|
|
133
|
+
logger.info({ ip: peer }, "[reset] Reset code sent over WhatsApp");
|
|
134
|
+
return { ok: true, expiresInMinutes: Math.round(CODE_TTL_MS / 60000) };
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* Verify the code and, when it matches, set the new password. A wrong code
|
|
139
|
+
* burns one of the five attempts; a mismatched confirmation or a too-short
|
|
140
|
+
* password does not.
|
|
141
|
+
*
|
|
142
|
+
* @returns {object} { ok: true } or { ok: false, reason, ... }
|
|
143
|
+
*/
|
|
144
|
+
function completeReset(code, password, confirm) {
|
|
145
|
+
if (!pending) return { ok: false, reason: "no_pending" };
|
|
146
|
+
if (Date.now() > pending.expiresAt) {
|
|
147
|
+
pending = null;
|
|
148
|
+
return { ok: false, reason: "expired" };
|
|
149
|
+
}
|
|
150
|
+
if (String(password ?? "") !== String(confirm ?? "")) {
|
|
151
|
+
return { ok: false, reason: "mismatch" };
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
pending.attempts += 1;
|
|
155
|
+
const expected = Buffer.from(pending.hash, "hex");
|
|
156
|
+
const actual = Buffer.from(hashCode(String(code ?? "").trim(), pending.salt), "hex");
|
|
157
|
+
if (expected.length !== actual.length || !crypto.timingSafeEqual(expected, actual)) {
|
|
158
|
+
const attemptsLeft = MAX_CODE_ATTEMPTS - pending.attempts;
|
|
159
|
+
if (attemptsLeft <= 0) {
|
|
160
|
+
pending = null;
|
|
161
|
+
return { ok: false, reason: "too_many_attempts" };
|
|
162
|
+
}
|
|
163
|
+
return { ok: false, reason: "wrong_code", attemptsLeft };
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
try {
|
|
167
|
+
// Bumps the password epoch, so every panel session stamped before this
|
|
168
|
+
// moment — including any an attacker might hold — stops being valid.
|
|
169
|
+
secrets.setDashboardPassword(password);
|
|
170
|
+
} catch (error) {
|
|
171
|
+
// The code is still good; the operator may fix the password and retry.
|
|
172
|
+
return { ok: false, reason: "invalid_password", message: error.message };
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
pending = null;
|
|
176
|
+
logger.info("[reset] Panel password reset via WhatsApp code");
|
|
177
|
+
return { ok: true };
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
module.exports = {
|
|
181
|
+
CODE_TTL_MS,
|
|
182
|
+
MAX_CODE_ATTEMPTS,
|
|
183
|
+
setSession,
|
|
184
|
+
requestResetCode,
|
|
185
|
+
completeReset,
|
|
186
|
+
_resetForTests,
|
|
187
|
+
};
|
|
@@ -26,13 +26,13 @@ import {
|
|
|
26
26
|
countSchedules,
|
|
27
27
|
countTodos,
|
|
28
28
|
countWarnings,
|
|
29
|
+
describePeer,
|
|
29
30
|
getAllGroupDirectory,
|
|
30
31
|
getAllGroupSettings,
|
|
31
32
|
getAllNotesFlat,
|
|
32
33
|
getAllTodos,
|
|
33
34
|
getAllUsers,
|
|
34
35
|
getAllWarnings,
|
|
35
|
-
describePeer,
|
|
36
36
|
getGroupDirectory,
|
|
37
37
|
getGroupSettings,
|
|
38
38
|
getRecentDebts,
|
|
@@ -68,11 +68,7 @@ const {
|
|
|
68
68
|
} = require("../../scheduler.cjs");
|
|
69
69
|
const { describeScheduledJob } = require("../utils/recurrence.cjs");
|
|
70
70
|
const { discoverProviderModels, DiscoveryError } = require("../services/llmDiscovery.cjs");
|
|
71
|
-
const
|
|
72
|
-
invalidateDiscoveryCache,
|
|
73
|
-
applyCapabilityGuards,
|
|
74
|
-
resolveCapabilities,
|
|
75
|
-
} = require("../services/modelRegistry.cjs");
|
|
71
|
+
const settingsTransfer = require("../services/settingsTransfer.cjs");
|
|
76
72
|
const cron = require("node-cron");
|
|
77
73
|
|
|
78
74
|
const router = Router();
|
|
@@ -301,76 +297,18 @@ router.get("/settings", (req, res) => {
|
|
|
301
297
|
|
|
302
298
|
router.patch("/settings", (req, res) => {
|
|
303
299
|
const { key } = req.body || {};
|
|
304
|
-
let { value } = req.body || {};
|
|
305
300
|
if (typeof key !== "string" || !key) return badRequest(res, "key is required");
|
|
306
301
|
|
|
307
302
|
try {
|
|
308
303
|
if (key === "prefix") {
|
|
309
|
-
const prefix = runtimeConfig.setPrefix(value);
|
|
304
|
+
const prefix = runtimeConfig.setPrefix(req.body?.value);
|
|
310
305
|
return res.json({ success: true, prefix });
|
|
311
306
|
}
|
|
312
307
|
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
? "gemini_model"
|
|
318
|
-
: provider === "anthropic"
|
|
319
|
-
? "anthropic_model"
|
|
320
|
-
: "openai_model";
|
|
321
|
-
const resolved = resolveCapabilities(provider, settings.get(modelKey));
|
|
322
|
-
const next = applyCapabilityGuards({
|
|
323
|
-
visionEnabled: key === "ai_vision_enabled" ? value : settings.get("ai_vision_enabled"),
|
|
324
|
-
sttEnabled: key === "ai_stt_enabled" ? value : settings.get("ai_stt_enabled"),
|
|
325
|
-
capabilities: resolved.capabilities,
|
|
326
|
-
capabilitySource: resolved.capabilitySource,
|
|
327
|
-
autoDetect: settings.get("ai_auto_detect_capabilities"),
|
|
328
|
-
});
|
|
329
|
-
if (key === "ai_vision_enabled") value = next.visionEnabled;
|
|
330
|
-
if (key === "ai_stt_enabled") value = next.sttEnabled;
|
|
331
|
-
}
|
|
332
|
-
|
|
333
|
-
settings.set(key, value);
|
|
334
|
-
if (typeof key === "string" && (key.includes("api_key") || key.includes("base_url"))) {
|
|
335
|
-
const prov = key.startsWith("gemini")
|
|
336
|
-
? "gemini"
|
|
337
|
-
: key.startsWith("anthropic")
|
|
338
|
-
? "anthropic"
|
|
339
|
-
: key.startsWith("openai")
|
|
340
|
-
? "openai"
|
|
341
|
-
: null;
|
|
342
|
-
if (prov) invalidateDiscoveryCache(prov);
|
|
343
|
-
else invalidateDiscoveryCache();
|
|
344
|
-
}
|
|
345
|
-
if (
|
|
346
|
-
key === "ai_provider" ||
|
|
347
|
-
key === "gemini_model" ||
|
|
348
|
-
key === "openai_model" ||
|
|
349
|
-
key === "anthropic_model"
|
|
350
|
-
) {
|
|
351
|
-
const provider = key === "ai_provider" ? String(value || "gemini") : key.split("_")[0];
|
|
352
|
-
const modelKey =
|
|
353
|
-
provider === "gemini"
|
|
354
|
-
? "gemini_model"
|
|
355
|
-
: provider === "anthropic"
|
|
356
|
-
? "anthropic_model"
|
|
357
|
-
: "openai_model";
|
|
358
|
-
const modelId = key.endsWith("_model") ? value : settings.get(modelKey);
|
|
359
|
-
const resolved = resolveCapabilities(provider, modelId);
|
|
360
|
-
const next = applyCapabilityGuards({
|
|
361
|
-
visionEnabled: settings.get("ai_vision_enabled"),
|
|
362
|
-
sttEnabled: settings.get("ai_stt_enabled"),
|
|
363
|
-
capabilities: resolved.capabilities,
|
|
364
|
-
capabilitySource: resolved.capabilitySource,
|
|
365
|
-
autoDetect: settings.get("ai_auto_detect_capabilities"),
|
|
366
|
-
});
|
|
367
|
-
if (Boolean(settings.get("ai_vision_enabled")) !== next.visionEnabled) {
|
|
368
|
-
settings.set("ai_vision_enabled", next.visionEnabled);
|
|
369
|
-
}
|
|
370
|
-
if (Boolean(settings.get("ai_stt_enabled")) !== next.sttEnabled) {
|
|
371
|
-
settings.set("ai_stt_enabled", next.sttEnabled);
|
|
372
|
-
}
|
|
373
|
-
}
|
|
308
|
+
// Capability guards, discovery-cache drops and the save itself live in one
|
|
309
|
+
// place the import route shares (settingsTransfer.applySettingChange), so
|
|
310
|
+
// a hand edit and a shared file can't drift apart.
|
|
311
|
+
settingsTransfer.applySettingChange(key, req.body?.value);
|
|
374
312
|
return res.json({
|
|
375
313
|
success: true,
|
|
376
314
|
// Never echo a value back: for a secret that would hand it to anyone who
|
|
@@ -382,6 +320,37 @@ router.patch("/settings", (req, res) => {
|
|
|
382
320
|
}
|
|
383
321
|
});
|
|
384
322
|
|
|
323
|
+
// --- Share settings --------------------------------------------------------
|
|
324
|
+
//
|
|
325
|
+
// The file a friend can load: every non-secret override (settingsTransfer
|
|
326
|
+
// owns what is in and what stays out). The import applies what it understands
|
|
327
|
+
// and reports the rest, so a file from a different version never half-kills
|
|
328
|
+
// an install in silence.
|
|
329
|
+
|
|
330
|
+
// (no per-route no-store needed: the /dashboard/api mount already sets it)
|
|
331
|
+
router.get("/settings/export", (req, res) => {
|
|
332
|
+
try {
|
|
333
|
+
const payload = settingsTransfer.exportSettings();
|
|
334
|
+
const date = payload.exportedAt.slice(0, 10);
|
|
335
|
+
res.set("Content-Type", "application/json; charset=utf-8");
|
|
336
|
+
res.set("Content-Disposition", `attachment; filename="levix-settings-${date}.json"`);
|
|
337
|
+
return res.json(payload);
|
|
338
|
+
} catch (error) {
|
|
339
|
+
return fail(res, error, "Error exporting settings");
|
|
340
|
+
}
|
|
341
|
+
});
|
|
342
|
+
|
|
343
|
+
router.post("/settings/import", (req, res) => {
|
|
344
|
+
try {
|
|
345
|
+
const report = settingsTransfer.applyImport(req.body || {});
|
|
346
|
+
// Aliases and disabled commands are cached in the dispatcher's index.
|
|
347
|
+
rebuildCommandIndex();
|
|
348
|
+
return res.json({ success: true, ...report });
|
|
349
|
+
} catch (error) {
|
|
350
|
+
return badRequest(res, error.message);
|
|
351
|
+
}
|
|
352
|
+
});
|
|
353
|
+
|
|
385
354
|
// ===========================================================================
|
|
386
355
|
// AI — the editable system prompt and the long-term memory files
|
|
387
356
|
// ===========================================================================
|
|
@@ -659,7 +628,12 @@ async function getChatConversationAsync(chatId) {
|
|
|
659
628
|
if (messages.length >= MAX_INSPECTOR_MESSAGES) break;
|
|
660
629
|
}
|
|
661
630
|
|
|
662
|
-
return {
|
|
631
|
+
return {
|
|
632
|
+
chatId,
|
|
633
|
+
updatedAt: meta.updatedAt ?? null,
|
|
634
|
+
truncated: messages.length >= MAX_INSPECTOR_MESSAGES,
|
|
635
|
+
messages,
|
|
636
|
+
};
|
|
663
637
|
}
|
|
664
638
|
|
|
665
639
|
// ===========================================================================
|
|
@@ -671,15 +645,10 @@ function groupView(groupId, stored) {
|
|
|
671
645
|
const directory = getGroupDirectory(groupId) || null;
|
|
672
646
|
const config = stored || {};
|
|
673
647
|
const subject = live?.subject || directory?.subject || null;
|
|
674
|
-
const memberCount =
|
|
675
|
-
live?.participants?.length ?? directory?.participant_count ?? null;
|
|
648
|
+
const memberCount = live?.participants?.length ?? directory?.participant_count ?? null;
|
|
676
649
|
const mediaEnabled = !!config.media_control?.enabled;
|
|
677
650
|
const blocked = config.media_control?.blocked_types || [];
|
|
678
|
-
const mediaRestriction = !mediaEnabled
|
|
679
|
-
? "none"
|
|
680
|
-
: blocked.length >= 4
|
|
681
|
-
? "block_all"
|
|
682
|
-
: "custom";
|
|
651
|
+
const mediaRestriction = !mediaEnabled ? "none" : blocked.length >= 4 ? "block_all" : "custom";
|
|
683
652
|
|
|
684
653
|
return {
|
|
685
654
|
id: groupId,
|
|
@@ -1185,7 +1154,8 @@ router.post("/security/password", (req, res) => {
|
|
|
1185
1154
|
clearAttempts(peer);
|
|
1186
1155
|
stampPanelSession(req.session);
|
|
1187
1156
|
req.session.save((err) => {
|
|
1188
|
-
if (err)
|
|
1157
|
+
if (err)
|
|
1158
|
+
return res.status(500).json({ success: false, error: "Could not refresh the session" });
|
|
1189
1159
|
try {
|
|
1190
1160
|
const { disconnectInvalidPanelSockets } = require("../../app.cjs");
|
|
1191
1161
|
disconnectInvalidPanelSockets();
|
|
@@ -0,0 +1,246 @@
|
|
|
1
|
+
// Share settings as a file: export what the operator changed, import it back
|
|
2
|
+
// on another install — the "my friend set their bot up like mine" flow.
|
|
3
|
+
//
|
|
4
|
+
// Two rules make the file safe to pass around:
|
|
5
|
+
//
|
|
6
|
+
// * Secrets never leave. API keys, the proxy password, the panel password —
|
|
7
|
+
// every `type: "secret"` setting is skipped on export AND refused on
|
|
8
|
+
// import, so a shared file can't carry a credential and can't overwrite
|
|
9
|
+
// the importer's own. Everyone fills their own keys in the panel.
|
|
10
|
+
// * Only overrides are exported. A setting the operator never touched stays
|
|
11
|
+
// out of the file, so the importer keeps following their own shipped
|
|
12
|
+
// defaults wherever the sharer also hadn't changed anything.
|
|
13
|
+
//
|
|
14
|
+
// What is covered: every non-secret `setting:*` row (AI provider and models,
|
|
15
|
+
// language, delays, thumbnails, port and proxy shape, …) plus the command
|
|
16
|
+
// table — prefix, permission overrides, alias overrides, disabled commands.
|
|
17
|
+
// Not covered on purpose: per-group config and the memory files (they are
|
|
18
|
+
// personal data, not settings) and the AI persona (a behaviour file the
|
|
19
|
+
// operator authors, shared by copy-paste if wanted).
|
|
20
|
+
|
|
21
|
+
const settings = require("../config/settings.cjs");
|
|
22
|
+
const runtimeConfig = require("../config/runtime-config.cjs");
|
|
23
|
+
const logger = require("../utils/logger.cjs");
|
|
24
|
+
const {
|
|
25
|
+
invalidateDiscoveryCache,
|
|
26
|
+
applyCapabilityGuards,
|
|
27
|
+
resolveCapabilities,
|
|
28
|
+
} = require("./modelRegistry.cjs");
|
|
29
|
+
|
|
30
|
+
const FORMAT = "levix-settings";
|
|
31
|
+
const VERSION = 1;
|
|
32
|
+
|
|
33
|
+
function isPlainObject(value) {
|
|
34
|
+
return !!value && typeof value === "object" && !Array.isArray(value);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* The file a friend shares. Hand the JSON straight to the importer UI.
|
|
39
|
+
*/
|
|
40
|
+
function exportSettings() {
|
|
41
|
+
const exported = {};
|
|
42
|
+
for (const key of settings.SETTING_KEYS) {
|
|
43
|
+
if (settings.SECRET_SETTING_KEYS.includes(key)) continue;
|
|
44
|
+
if (settings.sourceOf(key) !== "dashboard") continue;
|
|
45
|
+
exported[key] = settings.get(key);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
// Hand-edited rows can't happen through the panel, but a copy that passed
|
|
49
|
+
// through someone's editor might — export only the levels the code acts on.
|
|
50
|
+
const permissions = {};
|
|
51
|
+
for (const [command, level] of Object.entries(runtimeConfig.permissionOverrides())) {
|
|
52
|
+
if (runtimeConfig.PERMISSION_LEVELS.includes(level)) permissions[command] = level;
|
|
53
|
+
}
|
|
54
|
+
const aliases = {};
|
|
55
|
+
for (const [command, list] of Object.entries(runtimeConfig.aliasOverrides())) {
|
|
56
|
+
if (Array.isArray(list)) aliases[command] = list.map(String);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
return {
|
|
60
|
+
format: FORMAT,
|
|
61
|
+
version: VERSION,
|
|
62
|
+
exportedAt: new Date().toISOString(),
|
|
63
|
+
settings: exported,
|
|
64
|
+
commands: {
|
|
65
|
+
prefix: runtimeConfig.getPrefix(),
|
|
66
|
+
permissions,
|
|
67
|
+
aliases,
|
|
68
|
+
disabled: runtimeConfig.disabledCommands(),
|
|
69
|
+
},
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Apply one non-secret setting exactly the way PATCH /dashboard/api/settings
|
|
75
|
+
* does: model-capability guards around vision/STT, discovery-cache drops when
|
|
76
|
+
* a credential or endpoint moves. The PATCH route calls this too, so a hand
|
|
77
|
+
* edit and an import can't drift apart.
|
|
78
|
+
*
|
|
79
|
+
* @returns the value actually in force afterwards
|
|
80
|
+
*/
|
|
81
|
+
function applySettingChange(key, value) {
|
|
82
|
+
if (key === "ai_vision_enabled" || key === "ai_stt_enabled") {
|
|
83
|
+
const provider = String(settings.get("ai_provider") || "gemini");
|
|
84
|
+
const modelKey =
|
|
85
|
+
provider === "gemini"
|
|
86
|
+
? "gemini_model"
|
|
87
|
+
: provider === "anthropic"
|
|
88
|
+
? "anthropic_model"
|
|
89
|
+
: "openai_model";
|
|
90
|
+
const resolved = resolveCapabilities(provider, settings.get(modelKey));
|
|
91
|
+
const next = applyCapabilityGuards({
|
|
92
|
+
visionEnabled: key === "ai_vision_enabled" ? value : settings.get("ai_vision_enabled"),
|
|
93
|
+
sttEnabled: key === "ai_stt_enabled" ? value : settings.get("ai_stt_enabled"),
|
|
94
|
+
capabilities: resolved.capabilities,
|
|
95
|
+
capabilitySource: resolved.capabilitySource,
|
|
96
|
+
autoDetect: settings.get("ai_auto_detect_capabilities"),
|
|
97
|
+
});
|
|
98
|
+
if (key === "ai_vision_enabled") value = next.visionEnabled;
|
|
99
|
+
if (key === "ai_stt_enabled") value = next.sttEnabled;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
settings.set(key, value);
|
|
103
|
+
|
|
104
|
+
if (key.includes("api_key") || key.includes("base_url")) {
|
|
105
|
+
const prov = key.startsWith("gemini")
|
|
106
|
+
? "gemini"
|
|
107
|
+
: key.startsWith("anthropic")
|
|
108
|
+
? "anthropic"
|
|
109
|
+
: key.startsWith("openai")
|
|
110
|
+
? "openai"
|
|
111
|
+
: null;
|
|
112
|
+
if (prov) invalidateDiscoveryCache(prov);
|
|
113
|
+
else invalidateDiscoveryCache();
|
|
114
|
+
}
|
|
115
|
+
if (
|
|
116
|
+
key === "ai_provider" ||
|
|
117
|
+
key === "gemini_model" ||
|
|
118
|
+
key === "openai_model" ||
|
|
119
|
+
key === "anthropic_model"
|
|
120
|
+
) {
|
|
121
|
+
const provider = key === "ai_provider" ? String(value || "gemini") : key.split("_")[0];
|
|
122
|
+
const modelKey =
|
|
123
|
+
provider === "gemini"
|
|
124
|
+
? "gemini_model"
|
|
125
|
+
: provider === "anthropic"
|
|
126
|
+
? "anthropic_model"
|
|
127
|
+
: "openai_model";
|
|
128
|
+
const modelId = key.endsWith("_model") ? value : settings.get(modelKey);
|
|
129
|
+
const resolved = resolveCapabilities(provider, modelId);
|
|
130
|
+
const next = applyCapabilityGuards({
|
|
131
|
+
visionEnabled: settings.get("ai_vision_enabled"),
|
|
132
|
+
sttEnabled: settings.get("ai_stt_enabled"),
|
|
133
|
+
capabilities: resolved.capabilities,
|
|
134
|
+
capabilitySource: resolved.capabilitySource,
|
|
135
|
+
autoDetect: settings.get("ai_auto_detect_capabilities"),
|
|
136
|
+
});
|
|
137
|
+
if (Boolean(settings.get("ai_vision_enabled")) !== next.visionEnabled) {
|
|
138
|
+
settings.set("ai_vision_enabled", next.visionEnabled);
|
|
139
|
+
}
|
|
140
|
+
if (Boolean(settings.get("ai_stt_enabled")) !== next.sttEnabled) {
|
|
141
|
+
settings.set("ai_stt_enabled", next.sttEnabled);
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
return settings.get(key);
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/**
|
|
148
|
+
* Apply a shared file to this install. One bad value never stops the rest —
|
|
149
|
+
* it is reported and the import carries on.
|
|
150
|
+
*
|
|
151
|
+
* @returns {object} a report the panel shows: what landed, what didn't, and
|
|
152
|
+
* which keys wait for a restart.
|
|
153
|
+
*/
|
|
154
|
+
function applyImport(payload) {
|
|
155
|
+
if (!isPlainObject(payload) || payload.format !== FORMAT) {
|
|
156
|
+
throw new Error("That file isn't a Levix settings export");
|
|
157
|
+
}
|
|
158
|
+
if (payload.version !== VERSION) {
|
|
159
|
+
throw new Error(`Unsupported export version: ${String(payload.version)}`);
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
const report = { applied: [], skipped: [], restartNeeded: [], counts: {} };
|
|
163
|
+
|
|
164
|
+
for (const [key, value] of Object.entries(
|
|
165
|
+
isPlainObject(payload.settings) ? payload.settings : {},
|
|
166
|
+
)) {
|
|
167
|
+
if (!settings.SETTING_KEYS.includes(key)) {
|
|
168
|
+
report.skipped.push({ key, reason: "Unknown setting" });
|
|
169
|
+
continue;
|
|
170
|
+
}
|
|
171
|
+
if (settings.SECRET_SETTING_KEYS.includes(key)) {
|
|
172
|
+
// A hand-crafted file doesn't get to plant a credential.
|
|
173
|
+
report.skipped.push({ key, reason: "Secret — set it in the panel" });
|
|
174
|
+
continue;
|
|
175
|
+
}
|
|
176
|
+
try {
|
|
177
|
+
applySettingChange(key, value);
|
|
178
|
+
report.applied.push(key);
|
|
179
|
+
if (settings.RESTART_SETTING_KEYS.includes(key)) report.restartNeeded.push(key);
|
|
180
|
+
} catch (error) {
|
|
181
|
+
report.skipped.push({ key, reason: error.message });
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
const commands = isPlainObject(payload.commands) ? payload.commands : {};
|
|
186
|
+
const commandReport = { permissions: 0, aliases: 0, disabled: 0 };
|
|
187
|
+
|
|
188
|
+
if (typeof commands.prefix === "string" && commands.prefix.trim()) {
|
|
189
|
+
try {
|
|
190
|
+
runtimeConfig.setPrefix(commands.prefix);
|
|
191
|
+
report.applied.push("prefix");
|
|
192
|
+
} catch (error) {
|
|
193
|
+
report.skipped.push({ key: "prefix", reason: error.message });
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
for (const [command, level] of Object.entries(
|
|
198
|
+
isPlainObject(commands.permissions) ? commands.permissions : {},
|
|
199
|
+
)) {
|
|
200
|
+
try {
|
|
201
|
+
runtimeConfig.setPermission(command, level);
|
|
202
|
+
commandReport.permissions += 1;
|
|
203
|
+
} catch (error) {
|
|
204
|
+
report.skipped.push({ key: `permission:${command}`, reason: error.message });
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
for (const [command, list] of Object.entries(
|
|
209
|
+
isPlainObject(commands.aliases) ? commands.aliases : {},
|
|
210
|
+
)) {
|
|
211
|
+
try {
|
|
212
|
+
runtimeConfig.setAliases(command, Array.isArray(list) ? list : null);
|
|
213
|
+
commandReport.aliases += 1;
|
|
214
|
+
} catch (error) {
|
|
215
|
+
report.skipped.push({ key: `aliases:${command}`, reason: error.message });
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
// The disabled list replaces the local one, so the two installs actually end
|
|
220
|
+
// up alike: everything the file doesn't name runs again.
|
|
221
|
+
const disabledWanted = Array.isArray(commands.disabled) ? commands.disabled.map(String) : [];
|
|
222
|
+
const currentlyDisabled = runtimeConfig.disabledCommands();
|
|
223
|
+
for (const command of currentlyDisabled) {
|
|
224
|
+
if (!disabledWanted.includes(command)) runtimeConfig.setEnabled(command, true);
|
|
225
|
+
}
|
|
226
|
+
for (const command of disabledWanted) {
|
|
227
|
+
runtimeConfig.setEnabled(command, false);
|
|
228
|
+
commandReport.disabled += 1;
|
|
229
|
+
}
|
|
230
|
+
if (commands.disabled !== undefined) report.applied.push("disabled_commands");
|
|
231
|
+
|
|
232
|
+
report.counts = commandReport;
|
|
233
|
+
logger.info(
|
|
234
|
+
{ applied: report.applied.length, skipped: report.skipped.length },
|
|
235
|
+
"[settings] import applied",
|
|
236
|
+
);
|
|
237
|
+
return report;
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
module.exports = {
|
|
241
|
+
FORMAT,
|
|
242
|
+
VERSION,
|
|
243
|
+
exportSettings,
|
|
244
|
+
applyImport,
|
|
245
|
+
applySettingChange,
|
|
246
|
+
};
|