luckytri 1.0.6 → 1.0.7
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/LICENSE +21 -21
- package/docs/en/CHANGELOG.md +25 -16
- package/docs/en/chat-style.md +28 -9
- package/docs/en/guide.md +5 -5
- package/docs/en/her-life.md +2 -2
- package/docs/en/webui.md +1 -1
- package/docs/zh/CHANGELOG.md +25 -16
- package/docs/zh/chat-style.md +30 -9
- package/docs/zh/guide.md +5 -5
- package/docs/zh/her-life.md +2 -2
- package/docs/zh/webui.md +1 -1
- package/package.json +1 -1
- package/public/app/assets/{ChatsPage-DCYMkJ91.js → ChatsPage-CshdtTzV.js} +2 -2
- package/public/app/assets/ChatsPage-DfyPCS9N.css +1 -0
- package/public/app/assets/{Empty-CLyZkxR5.js → Empty-C7yzOBzy.js} +1 -1
- package/public/app/assets/{Empty-DIobYG3x.css → Empty-DmUB2-Bk.css} +1 -1
- package/public/app/assets/{Field-BpaRwLI_.js → Field-BjFv4Rfn.js} +1 -1
- package/public/app/assets/HeartPage-Bft9wZp5.css +1 -0
- package/public/app/assets/{HeartPage-BIOMTiwr.js → HeartPage-eqo6ru16.js} +1 -1
- package/public/app/assets/LifePage-BUi5euBF.css +1 -0
- package/public/app/assets/{LifePage-BCgM4JkR.js → LifePage-CN8GE5NK.js} +1 -1
- package/public/app/assets/{MemoryPage-vShvRqMt.js → MemoryPage-CCpMN4Wg.js} +1 -1
- package/public/app/assets/MemoryPage-cZvXfkXb.css +1 -0
- package/public/app/assets/{NaturePage-Cy9ptr4G.js → NaturePage-C0JqdBTR.js} +2 -2
- package/public/app/assets/NaturePage-CHkpb5NK.css +1 -0
- package/public/app/assets/PeoplePage-BTU0H1pM.css +1 -0
- package/public/app/assets/{PeoplePage-CUZekB2E.js → PeoplePage-BXGBbO4u.js} +1 -1
- package/public/app/assets/{PluginsPage-1RM4rmJP.js → PluginsPage-Dksp5AV5.js} +1 -1
- package/public/app/assets/{SystemPage-BI2CB5Ig.css → SystemPage-BenIyTvk.css} +1 -1
- package/public/app/assets/{SystemPage-BeT5TmIV.js → SystemPage-Cd7aa8eE.js} +1 -1
- package/public/app/assets/TimePage-BOms_n4I.css +1 -0
- package/public/app/assets/{TimePage-taTmPMM8.js → TimePage-Bs_zImb4.js} +2 -2
- package/public/app/assets/{index-DY5AM0Hz.css → index-BHZcHUMh.css} +1 -1
- package/public/app/assets/{index-DdYwC5ZU.js → index-CyRtYxP3.js} +3 -3
- package/public/app/assets/{knowledge-DJmfu2KN.js → knowledge-BJOIyuJo.js} +1 -1
- package/public/app/assets/{media-BEtnE0Gv.js → media-Bwtx8blz.js} +1 -1
- package/public/app/assets/{mind-Dtiw0-QK.js → mind-DtTVrW6Z.js} +1 -1
- package/public/app/index.html +5 -6
- package/public/guide.en.html +3 -3
- package/public/guide.html +3 -3
- package/scripts/import-data.js +128 -128
- package/scripts/proxy-config.js +167 -167
- package/scripts/update-instance.js +201 -201
- package/server/channels/adapters.js +27 -27
- package/server/channels/onebot/adapter.js +288 -288
- package/server/channels/qqbot/adapter.js +253 -253
- package/server/channels/qqbot/api.js +199 -199
- package/server/channels/qqbot/credentials.js +11 -11
- package/server/channels/qqbot/gateway.js +274 -274
- package/server/channels/qqbot/index.js +389 -389
- package/server/channels/segments.js +40 -40
- package/server/channels/session-key.js +153 -153
- package/server/channels/state.js +42 -42
- package/server/core/api.js +564 -564
- package/server/core/context-builder.js +288 -288
- package/server/core/context-compactor.js +454 -454
- package/server/core/conversation-cues.js +365 -325
- package/server/core/conversation-grounding.js +178 -0
- package/server/core/conversation-manager.js +87 -87
- package/server/core/dialogue-context.js +52 -0
- package/server/core/feedback.js +8 -8
- package/server/core/group-style.js +72 -72
- package/server/core/initiative-context.js +66 -66
- package/server/core/input-budget.js +32 -32
- package/server/core/local-demo.js +98 -98
- package/server/core/message-manager.js +118 -118
- package/server/core/message-scheduler.js +78 -78
- package/server/core/model-json.js +190 -190
- package/server/core/model-presets.js +900 -900
- package/server/core/name-call.js +29 -29
- package/server/core/network.js +157 -157
- package/server/core/person-name.js +22 -22
- package/server/core/persona-manager.js +324 -269
- package/server/core/reply-delivery.js +472 -404
- package/server/core/reply-target-resolver.js +50 -50
- package/server/core/response-generator.js +58 -50
- package/server/core/response-validator.js +30 -27
- package/server/core/retired-prompts.js +51 -51
- package/server/core/sessions.js +109 -109
- package/server/core/speaker-names.js +92 -92
- package/server/core/topic-tracker.js +65 -65
- package/server/core/turn.js +42 -8
- package/server/http.js +18 -18
- package/server/i18n/decisions.js +209 -209
- package/server/i18n/index.js +144 -144
- package/server/i18n/labels.js +0 -5
- package/server/i18n/models.js +111 -111
- package/server/knowledge/api.js +342 -342
- package/server/knowledge/embedding-profile.js +114 -114
- package/server/knowledge/index.js +13 -13
- package/server/knowledge/retrieval.js +93 -93
- package/server/knowledge/schema.js +158 -158
- package/server/knowledge/vector-index.js +90 -90
- package/server/mind/affect.js +265 -265
- package/server/mind/attention.js +200 -200
- package/server/mind/bonds.js +565 -565
- package/server/mind/clock.js +83 -83
- package/server/mind/context-selection.js +16 -4
- package/server/mind/continuity.js +562 -562
- package/server/mind/conversation-origin.js +175 -175
- package/server/mind/days.js +210 -210
- package/server/mind/evidence-read.js +45 -45
- package/server/mind/faces.js +373 -373
- package/server/mind/guard.js +68 -60
- package/server/mind/initiative.js +338 -338
- package/server/mind/life/activities.js +21 -21
- package/server/mind/life/context.js +330 -330
- package/server/mind/life/growth.js +261 -261
- package/server/mind/life/presence.js +305 -305
- package/server/mind/meetings.js +1069 -1069
- package/server/mind/memory-policy.js +48 -48
- package/server/mind/memory.js +888 -888
- package/server/mind/nature.js +358 -358
- package/server/mind/novelty.js +19 -19
- package/server/mind/periods.js +118 -118
- package/server/mind/reading.js +120 -120
- package/server/mind/relationship-context.js +71 -71
- package/server/mind/relationships.js +390 -390
- package/server/mind/salience.js +201 -201
- package/server/mind/schema.js +567 -567
- package/server/mind/self.js +496 -484
- package/server/mind/thoughts.js +274 -274
- package/server/mind/time/agenda.js +242 -242
- package/server/mind/time/api.js +200 -200
- package/server/mind/time/attention.js +34 -34
- package/server/mind/time/delivery-links.js +130 -130
- package/server/mind/time/games.js +7 -3
- package/server/mind/time/index.js +3 -0
- package/server/mind/time/model-material.js +77 -77
- package/server/mind/time/presentation.js +35 -51
- package/server/mind/time/schedule.js +83 -83
- package/server/mind/time/schema.js +84 -84
- package/server/mind/time/search.js +383 -383
- package/server/mind/time/sharing.js +472 -472
- package/server/mind/time/task-links.js +311 -311
- package/server/mind/time/works.js +438 -432
- package/server/mind/traits.js +191 -191
- package/server/mind/view.js +43 -6
- package/server/runtime/installation.js +116 -116
- package/server/runtime/update-manager.js +140 -140
- package/server/storage/data-package.js +298 -298
- package/server/storage/data-transfer-api.js +50 -50
- package/server/storage/data-transfer-worker.js +18 -18
- package/server/storage/data-transfer.js +416 -416
- package/server/studio/display-names.js +139 -139
- package/server/studio/management.js +102 -102
- package/server/studio/updates.js +144 -144
- package/server/version.js +10 -10
- package/public/app/assets/ChatsPage-CFMVozoG.css +0 -1
- package/public/app/assets/HeartPage-C-2jvgzF.css +0 -1
- package/public/app/assets/LifePage-CG1OHbRK.css +0 -1
- package/public/app/assets/MemoryPage-C_Bu4rfb.css +0 -1
- package/public/app/assets/NaturePage-CPZlImT0.css +0 -1
- package/public/app/assets/PeoplePage-3RRUITDz.css +0 -1
- package/public/app/assets/TimePage-C-guwPk2.css +0 -1
|
@@ -1,298 +1,298 @@
|
|
|
1
|
-
import { DatabaseSync } from "node:sqlite";
|
|
2
|
-
import { randomUUID } from "node:crypto";
|
|
3
|
-
import {
|
|
4
|
-
createReadStream,
|
|
5
|
-
createWriteStream,
|
|
6
|
-
writeFileSync,
|
|
7
|
-
openSync,
|
|
8
|
-
readSync,
|
|
9
|
-
closeSync,
|
|
10
|
-
existsSync,
|
|
11
|
-
statSync,
|
|
12
|
-
renameSync,
|
|
13
|
-
mkdirSync,
|
|
14
|
-
rmSync,
|
|
15
|
-
} from "node:fs";
|
|
16
|
-
import { join, dirname, basename } from "node:path";
|
|
17
|
-
import { pipeline } from "node:stream/promises";
|
|
18
|
-
import {
|
|
19
|
-
copyDatabaseFile,
|
|
20
|
-
inspectDatabase,
|
|
21
|
-
writeArchiveManifest,
|
|
22
|
-
verifyArchive,
|
|
23
|
-
DATABASE_VERSION,
|
|
24
|
-
} from "./archive.js";
|
|
25
|
-
import { withBackupLock } from "./backup-lock.js";
|
|
26
|
-
import { createStore } from "./store.js";
|
|
27
|
-
import { Repository } from "../core/repository.js";
|
|
28
|
-
import { KNOWLEDGE_TRIGGERS } from "../knowledge/schema.js";
|
|
29
|
-
|
|
30
|
-
export const PACKAGE_MAGIC = Buffer.from("LUCKYTRI-DATA\n");
|
|
31
|
-
const SQLITE_MAGIC = Buffer.from("SQLite format 3\0");
|
|
32
|
-
export function packageHeader(manifest) {
|
|
33
|
-
const json = Buffer.from(JSON.stringify(manifest));
|
|
34
|
-
if (json.length > 262144) throw Error("数据清单过大");
|
|
35
|
-
const length = Buffer.alloc(4);
|
|
36
|
-
length.writeUInt32BE(json.length);
|
|
37
|
-
return Buffer.concat([PACKAGE_MAGIC, length, json]);
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
export function validateData(file) {
|
|
41
|
-
const result = inspectDatabase(file);
|
|
42
|
-
const db = new DatabaseSync(file, { readOnly: true });
|
|
43
|
-
try {
|
|
44
|
-
const canonical = (sql) =>
|
|
45
|
-
String(sql)
|
|
46
|
-
.replace(/\bIF\s+NOT\s+EXISTS\b/gi, "")
|
|
47
|
-
.replace(/\s+/g, "")
|
|
48
|
-
.replace(/;$/, "")
|
|
49
|
-
.toLowerCase();
|
|
50
|
-
const allowed = new Set(KNOWLEDGE_TRIGGERS.map(canonical));
|
|
51
|
-
if (
|
|
52
|
-
db
|
|
53
|
-
.prepare(
|
|
54
|
-
"SELECT type,sql FROM sqlite_master WHERE type IN ('trigger','view')",
|
|
55
|
-
)
|
|
56
|
-
.all()
|
|
57
|
-
.some(
|
|
58
|
-
(row) => row.type !== "trigger" || !allowed.has(canonical(row.sql)),
|
|
59
|
-
)
|
|
60
|
-
)
|
|
61
|
-
throw Error("数据文件包含不支持的数据库结构");
|
|
62
|
-
const settings = JSON.parse(
|
|
63
|
-
db.prepare("SELECT value FROM settings WHERE id=1").get()?.value ||
|
|
64
|
-
"null",
|
|
65
|
-
);
|
|
66
|
-
if (
|
|
67
|
-
!settings ||
|
|
68
|
-
typeof settings !== "object" ||
|
|
69
|
-
Array.isArray(settings) ||
|
|
70
|
-
typeof settings.name !== "string"
|
|
71
|
-
)
|
|
72
|
-
throw Error("不是有效的 LuckyTri 数据文件");
|
|
73
|
-
return { ...result, name: settings.name.slice(0, 100) };
|
|
74
|
-
} finally {
|
|
75
|
-
db.close();
|
|
76
|
-
}
|
|
77
|
-
}
|
|
78
|
-
|
|
79
|
-
export function makeDataExport(source, target, backups) {
|
|
80
|
-
return withBackupLock(backups, () => {
|
|
81
|
-
copyDatabaseFile(source, target);
|
|
82
|
-
const db = new DatabaseSync(target);
|
|
83
|
-
try {
|
|
84
|
-
for (const table of ["management_sessions", "management_auth"])
|
|
85
|
-
if (
|
|
86
|
-
db
|
|
87
|
-
.prepare(
|
|
88
|
-
"SELECT 1 FROM sqlite_master WHERE type='table' AND name=?",
|
|
89
|
-
)
|
|
90
|
-
.get(table)
|
|
91
|
-
)
|
|
92
|
-
db.exec(`DELETE FROM ${table}`);
|
|
93
|
-
db.exec("PRAGMA wal_checkpoint(TRUNCATE)");
|
|
94
|
-
} finally {
|
|
95
|
-
db.close();
|
|
96
|
-
}
|
|
97
|
-
const manifest = writeArchiveManifest(target, {
|
|
98
|
-
kind: "export",
|
|
99
|
-
filename: "data.db",
|
|
100
|
-
});
|
|
101
|
-
const summary = validateData(target);
|
|
102
|
-
return { manifest, summary, bytes: statSync(target).size };
|
|
103
|
-
});
|
|
104
|
-
}
|
|
105
|
-
|
|
106
|
-
export async function prepareDataImport(upload, target) {
|
|
107
|
-
const fd = openSync(upload, "r");
|
|
108
|
-
let offset = 0,
|
|
109
|
-
manifest = null;
|
|
110
|
-
try {
|
|
111
|
-
const start = Buffer.alloc(16);
|
|
112
|
-
const read = readSync(fd, start, 0, 16, 0);
|
|
113
|
-
if (read !== 16) throw Error("不是有效的 LuckyTri 数据文件");
|
|
114
|
-
if (!start.equals(SQLITE_MAGIC)) {
|
|
115
|
-
if (!start.subarray(0, PACKAGE_MAGIC.length).equals(PACKAGE_MAGIC))
|
|
116
|
-
throw Error("不是有效的 LuckyTri 数据文件");
|
|
117
|
-
const lengthBytes = Buffer.alloc(4);
|
|
118
|
-
if (readSync(fd, lengthBytes, 0, 4, PACKAGE_MAGIC.length) !== 4)
|
|
119
|
-
throw Error("数据包已损坏");
|
|
120
|
-
const length = lengthBytes.readUInt32BE();
|
|
121
|
-
if (length < 2 || length > 262144) throw Error("数据包已损坏");
|
|
122
|
-
const json = Buffer.alloc(length);
|
|
123
|
-
if (readSync(fd, json, 0, length, PACKAGE_MAGIC.length + 4) !== length)
|
|
124
|
-
throw Error("数据包已损坏");
|
|
125
|
-
manifest = JSON.parse(json.toString("utf8"));
|
|
126
|
-
if (
|
|
127
|
-
manifest.app !== "luckytri" ||
|
|
128
|
-
manifest.format !== 1 ||
|
|
129
|
-
!/^[a-f0-9]{64}$/.test(manifest.sha256)
|
|
130
|
-
)
|
|
131
|
-
throw Error("数据包已损坏");
|
|
132
|
-
offset = PACKAGE_MAGIC.length + 4 + length;
|
|
133
|
-
}
|
|
134
|
-
} finally {
|
|
135
|
-
closeSync(fd);
|
|
136
|
-
}
|
|
137
|
-
if (statSync(upload).size <= offset) throw Error("数据包已损坏");
|
|
138
|
-
await pipeline(
|
|
139
|
-
createReadStream(upload, { start: offset }),
|
|
140
|
-
createWriteStream(target, { flags: "wx", mode: 0o600 }),
|
|
141
|
-
);
|
|
142
|
-
if (manifest) {
|
|
143
|
-
writeFileSync(`${target}.json`, JSON.stringify(manifest), { mode: 0o600 });
|
|
144
|
-
verifyArchive(target);
|
|
145
|
-
}
|
|
146
|
-
const original = validateData(target);
|
|
147
|
-
// Upgrade only the staged copy; the running database is never opened here.
|
|
148
|
-
const store = createStore(target, { quietMigration: true });
|
|
149
|
-
try {
|
|
150
|
-
new Repository(store);
|
|
151
|
-
} finally {
|
|
152
|
-
store.db.close();
|
|
153
|
-
}
|
|
154
|
-
const migrated = validateData(target);
|
|
155
|
-
const checked = writeArchiveManifest(target, {
|
|
156
|
-
kind: "import",
|
|
157
|
-
filename: "data.db",
|
|
158
|
-
});
|
|
159
|
-
return {
|
|
160
|
-
summary: migrated,
|
|
161
|
-
originalVersion: original.schemaVersion,
|
|
162
|
-
manifest: checked,
|
|
163
|
-
bytes: statSync(target).size,
|
|
164
|
-
};
|
|
165
|
-
}
|
|
166
|
-
|
|
167
|
-
export function applyDataImport(
|
|
168
|
-
candidate,
|
|
169
|
-
source,
|
|
170
|
-
backups,
|
|
171
|
-
{ id = randomUUID(), move = renameSync, beforeSwap = () => {} } = {},
|
|
172
|
-
) {
|
|
173
|
-
if (source === ":memory:" || !existsSync(source))
|
|
174
|
-
throw Error("当前实例不支持文件导入");
|
|
175
|
-
return withBackupLock(backups, () => {
|
|
176
|
-
verifyArchive(candidate);
|
|
177
|
-
validateData(candidate);
|
|
178
|
-
const old = new DatabaseSync(source);
|
|
179
|
-
let auth, sessions, settings;
|
|
180
|
-
try {
|
|
181
|
-
settings = JSON.parse(
|
|
182
|
-
old.prepare("SELECT value FROM settings WHERE id=1").get().value,
|
|
183
|
-
);
|
|
184
|
-
auth = old
|
|
185
|
-
.prepare("SELECT salt,hash FROM management_auth WHERE id=1")
|
|
186
|
-
.get();
|
|
187
|
-
sessions = old
|
|
188
|
-
.prepare("SELECT id,expires FROM management_sessions")
|
|
189
|
-
.all();
|
|
190
|
-
const checkpoint = old.prepare("PRAGMA wal_checkpoint(TRUNCATE)").get();
|
|
191
|
-
if (checkpoint.busy) throw Error("当前数据库仍在使用,请稍后导入");
|
|
192
|
-
} finally {
|
|
193
|
-
old.close();
|
|
194
|
-
}
|
|
195
|
-
if (existsSync(`${source}-wal`) || existsSync(`${source}-shm`))
|
|
196
|
-
throw Error("当前数据库仍在使用,请稍后导入");
|
|
197
|
-
const imported = new DatabaseSync(candidate);
|
|
198
|
-
try {
|
|
199
|
-
imported.exec("BEGIN IMMEDIATE");
|
|
200
|
-
imported.exec(
|
|
201
|
-
"DROP TABLE IF EXISTS management_sessions; DROP TABLE IF EXISTS management_auth; CREATE TABLE management_auth(id INTEGER PRIMARY KEY CHECK(id=1),salt TEXT NOT NULL,hash TEXT NOT NULL); CREATE TABLE management_sessions(id TEXT PRIMARY KEY,expires INTEGER NOT NULL);",
|
|
202
|
-
);
|
|
203
|
-
if (auth)
|
|
204
|
-
imported
|
|
205
|
-
.prepare("INSERT INTO management_auth VALUES (1,?,?)")
|
|
206
|
-
.run(auth.salt, auth.hash);
|
|
207
|
-
for (const row of sessions)
|
|
208
|
-
imported
|
|
209
|
-
.prepare("INSERT INTO management_sessions VALUES (?,?)")
|
|
210
|
-
.run(row.id, row.expires);
|
|
211
|
-
const incoming = JSON.parse(
|
|
212
|
-
imported.prepare("SELECT value FROM settings WHERE id=1").get().value,
|
|
213
|
-
);
|
|
214
|
-
for (const field of [
|
|
215
|
-
"onebotToken",
|
|
216
|
-
"qqbotAppId",
|
|
217
|
-
"qqbotSecret",
|
|
218
|
-
"channel",
|
|
219
|
-
"backupCleanup",
|
|
220
|
-
"backupCleanupLast",
|
|
221
|
-
]) {
|
|
222
|
-
delete incoming[field];
|
|
223
|
-
if (settings[field] !== undefined) incoming[field] = settings[field];
|
|
224
|
-
}
|
|
225
|
-
incoming.enabled = false;
|
|
226
|
-
incoming.dataImportId = id;
|
|
227
|
-
imported
|
|
228
|
-
.prepare("UPDATE settings SET value=? WHERE id=1")
|
|
229
|
-
.run(JSON.stringify(incoming));
|
|
230
|
-
imported.exec(
|
|
231
|
-
"UPDATE plugin_installs SET enabled=0,granted='[]',path=''; COMMIT; PRAGMA wal_checkpoint(TRUNCATE);",
|
|
232
|
-
);
|
|
233
|
-
} catch (error) {
|
|
234
|
-
if (imported.isTransaction) imported.exec("ROLLBACK");
|
|
235
|
-
throw error;
|
|
236
|
-
} finally {
|
|
237
|
-
imported.close();
|
|
238
|
-
}
|
|
239
|
-
validateData(candidate);
|
|
240
|
-
mkdirSync(backups, { recursive: true });
|
|
241
|
-
const rollback = join(
|
|
242
|
-
backups,
|
|
243
|
-
`luckytri-before-import-${Date.now()}-${randomUUID().slice(0, 8)}.db`,
|
|
244
|
-
);
|
|
245
|
-
// Move the checkpointed original instead of creating another multi-GiB
|
|
246
|
-
// duplicate. The snapshot and its manifest remain available to restore.
|
|
247
|
-
writeArchiveManifest(source, {
|
|
248
|
-
kind: "before-import",
|
|
249
|
-
filename: basename(rollback),
|
|
250
|
-
});
|
|
251
|
-
beforeSwap(basename(rollback));
|
|
252
|
-
let original = rollback;
|
|
253
|
-
try {
|
|
254
|
-
move(source, rollback);
|
|
255
|
-
} catch (error) {
|
|
256
|
-
if (error.code !== "EXDEV") throw error;
|
|
257
|
-
// Custom backup folders may be on another disk. Retain one verified
|
|
258
|
-
// snapshot there, and keep the swap on the database's own filesystem.
|
|
259
|
-
copyDatabaseFile(source, rollback);
|
|
260
|
-
writeArchiveManifest(rollback, {
|
|
261
|
-
kind: "before-import",
|
|
262
|
-
filename: basename(rollback),
|
|
263
|
-
});
|
|
264
|
-
original = `${source}.import-swap-${randomUUID()}`;
|
|
265
|
-
move(source, original);
|
|
266
|
-
}
|
|
267
|
-
try {
|
|
268
|
-
if (original === rollback) move(`${source}.json`, `${rollback}.json`);
|
|
269
|
-
try {
|
|
270
|
-
move(candidate, source);
|
|
271
|
-
} catch (error) {
|
|
272
|
-
if (error.code !== "EXDEV") throw error;
|
|
273
|
-
const local = join(
|
|
274
|
-
dirname(source),
|
|
275
|
-
`.luckytri-import-${randomUUID()}.partial.db`,
|
|
276
|
-
);
|
|
277
|
-
try {
|
|
278
|
-
copyDatabaseFile(candidate, local);
|
|
279
|
-
validateData(local);
|
|
280
|
-
move(local, source);
|
|
281
|
-
rmSync(candidate, { force: true });
|
|
282
|
-
} finally {
|
|
283
|
-
rmSync(local, { force: true });
|
|
284
|
-
}
|
|
285
|
-
}
|
|
286
|
-
} catch (error) {
|
|
287
|
-
if (!existsSync(source)) renameSync(original, source);
|
|
288
|
-
if (existsSync(`${rollback}.json`))
|
|
289
|
-
renameSync(`${rollback}.json`, `${source}.json`);
|
|
290
|
-
throw error;
|
|
291
|
-
}
|
|
292
|
-
if (original !== rollback) {
|
|
293
|
-
rmSync(original, { force: true });
|
|
294
|
-
rmSync(`${source}.json`, { force: true });
|
|
295
|
-
}
|
|
296
|
-
return { backup: basename(rollback), schemaVersion: DATABASE_VERSION };
|
|
297
|
-
});
|
|
298
|
-
}
|
|
1
|
+
import { DatabaseSync } from "node:sqlite";
|
|
2
|
+
import { randomUUID } from "node:crypto";
|
|
3
|
+
import {
|
|
4
|
+
createReadStream,
|
|
5
|
+
createWriteStream,
|
|
6
|
+
writeFileSync,
|
|
7
|
+
openSync,
|
|
8
|
+
readSync,
|
|
9
|
+
closeSync,
|
|
10
|
+
existsSync,
|
|
11
|
+
statSync,
|
|
12
|
+
renameSync,
|
|
13
|
+
mkdirSync,
|
|
14
|
+
rmSync,
|
|
15
|
+
} from "node:fs";
|
|
16
|
+
import { join, dirname, basename } from "node:path";
|
|
17
|
+
import { pipeline } from "node:stream/promises";
|
|
18
|
+
import {
|
|
19
|
+
copyDatabaseFile,
|
|
20
|
+
inspectDatabase,
|
|
21
|
+
writeArchiveManifest,
|
|
22
|
+
verifyArchive,
|
|
23
|
+
DATABASE_VERSION,
|
|
24
|
+
} from "./archive.js";
|
|
25
|
+
import { withBackupLock } from "./backup-lock.js";
|
|
26
|
+
import { createStore } from "./store.js";
|
|
27
|
+
import { Repository } from "../core/repository.js";
|
|
28
|
+
import { KNOWLEDGE_TRIGGERS } from "../knowledge/schema.js";
|
|
29
|
+
|
|
30
|
+
export const PACKAGE_MAGIC = Buffer.from("LUCKYTRI-DATA\n");
|
|
31
|
+
const SQLITE_MAGIC = Buffer.from("SQLite format 3\0");
|
|
32
|
+
export function packageHeader(manifest) {
|
|
33
|
+
const json = Buffer.from(JSON.stringify(manifest));
|
|
34
|
+
if (json.length > 262144) throw Error("数据清单过大");
|
|
35
|
+
const length = Buffer.alloc(4);
|
|
36
|
+
length.writeUInt32BE(json.length);
|
|
37
|
+
return Buffer.concat([PACKAGE_MAGIC, length, json]);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export function validateData(file) {
|
|
41
|
+
const result = inspectDatabase(file);
|
|
42
|
+
const db = new DatabaseSync(file, { readOnly: true });
|
|
43
|
+
try {
|
|
44
|
+
const canonical = (sql) =>
|
|
45
|
+
String(sql)
|
|
46
|
+
.replace(/\bIF\s+NOT\s+EXISTS\b/gi, "")
|
|
47
|
+
.replace(/\s+/g, "")
|
|
48
|
+
.replace(/;$/, "")
|
|
49
|
+
.toLowerCase();
|
|
50
|
+
const allowed = new Set(KNOWLEDGE_TRIGGERS.map(canonical));
|
|
51
|
+
if (
|
|
52
|
+
db
|
|
53
|
+
.prepare(
|
|
54
|
+
"SELECT type,sql FROM sqlite_master WHERE type IN ('trigger','view')",
|
|
55
|
+
)
|
|
56
|
+
.all()
|
|
57
|
+
.some(
|
|
58
|
+
(row) => row.type !== "trigger" || !allowed.has(canonical(row.sql)),
|
|
59
|
+
)
|
|
60
|
+
)
|
|
61
|
+
throw Error("数据文件包含不支持的数据库结构");
|
|
62
|
+
const settings = JSON.parse(
|
|
63
|
+
db.prepare("SELECT value FROM settings WHERE id=1").get()?.value ||
|
|
64
|
+
"null",
|
|
65
|
+
);
|
|
66
|
+
if (
|
|
67
|
+
!settings ||
|
|
68
|
+
typeof settings !== "object" ||
|
|
69
|
+
Array.isArray(settings) ||
|
|
70
|
+
typeof settings.name !== "string"
|
|
71
|
+
)
|
|
72
|
+
throw Error("不是有效的 LuckyTri 数据文件");
|
|
73
|
+
return { ...result, name: settings.name.slice(0, 100) };
|
|
74
|
+
} finally {
|
|
75
|
+
db.close();
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export function makeDataExport(source, target, backups) {
|
|
80
|
+
return withBackupLock(backups, () => {
|
|
81
|
+
copyDatabaseFile(source, target);
|
|
82
|
+
const db = new DatabaseSync(target);
|
|
83
|
+
try {
|
|
84
|
+
for (const table of ["management_sessions", "management_auth"])
|
|
85
|
+
if (
|
|
86
|
+
db
|
|
87
|
+
.prepare(
|
|
88
|
+
"SELECT 1 FROM sqlite_master WHERE type='table' AND name=?",
|
|
89
|
+
)
|
|
90
|
+
.get(table)
|
|
91
|
+
)
|
|
92
|
+
db.exec(`DELETE FROM ${table}`);
|
|
93
|
+
db.exec("PRAGMA wal_checkpoint(TRUNCATE)");
|
|
94
|
+
} finally {
|
|
95
|
+
db.close();
|
|
96
|
+
}
|
|
97
|
+
const manifest = writeArchiveManifest(target, {
|
|
98
|
+
kind: "export",
|
|
99
|
+
filename: "data.db",
|
|
100
|
+
});
|
|
101
|
+
const summary = validateData(target);
|
|
102
|
+
return { manifest, summary, bytes: statSync(target).size };
|
|
103
|
+
});
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
export async function prepareDataImport(upload, target) {
|
|
107
|
+
const fd = openSync(upload, "r");
|
|
108
|
+
let offset = 0,
|
|
109
|
+
manifest = null;
|
|
110
|
+
try {
|
|
111
|
+
const start = Buffer.alloc(16);
|
|
112
|
+
const read = readSync(fd, start, 0, 16, 0);
|
|
113
|
+
if (read !== 16) throw Error("不是有效的 LuckyTri 数据文件");
|
|
114
|
+
if (!start.equals(SQLITE_MAGIC)) {
|
|
115
|
+
if (!start.subarray(0, PACKAGE_MAGIC.length).equals(PACKAGE_MAGIC))
|
|
116
|
+
throw Error("不是有效的 LuckyTri 数据文件");
|
|
117
|
+
const lengthBytes = Buffer.alloc(4);
|
|
118
|
+
if (readSync(fd, lengthBytes, 0, 4, PACKAGE_MAGIC.length) !== 4)
|
|
119
|
+
throw Error("数据包已损坏");
|
|
120
|
+
const length = lengthBytes.readUInt32BE();
|
|
121
|
+
if (length < 2 || length > 262144) throw Error("数据包已损坏");
|
|
122
|
+
const json = Buffer.alloc(length);
|
|
123
|
+
if (readSync(fd, json, 0, length, PACKAGE_MAGIC.length + 4) !== length)
|
|
124
|
+
throw Error("数据包已损坏");
|
|
125
|
+
manifest = JSON.parse(json.toString("utf8"));
|
|
126
|
+
if (
|
|
127
|
+
manifest.app !== "luckytri" ||
|
|
128
|
+
manifest.format !== 1 ||
|
|
129
|
+
!/^[a-f0-9]{64}$/.test(manifest.sha256)
|
|
130
|
+
)
|
|
131
|
+
throw Error("数据包已损坏");
|
|
132
|
+
offset = PACKAGE_MAGIC.length + 4 + length;
|
|
133
|
+
}
|
|
134
|
+
} finally {
|
|
135
|
+
closeSync(fd);
|
|
136
|
+
}
|
|
137
|
+
if (statSync(upload).size <= offset) throw Error("数据包已损坏");
|
|
138
|
+
await pipeline(
|
|
139
|
+
createReadStream(upload, { start: offset }),
|
|
140
|
+
createWriteStream(target, { flags: "wx", mode: 0o600 }),
|
|
141
|
+
);
|
|
142
|
+
if (manifest) {
|
|
143
|
+
writeFileSync(`${target}.json`, JSON.stringify(manifest), { mode: 0o600 });
|
|
144
|
+
verifyArchive(target);
|
|
145
|
+
}
|
|
146
|
+
const original = validateData(target);
|
|
147
|
+
// Upgrade only the staged copy; the running database is never opened here.
|
|
148
|
+
const store = createStore(target, { quietMigration: true });
|
|
149
|
+
try {
|
|
150
|
+
new Repository(store);
|
|
151
|
+
} finally {
|
|
152
|
+
store.db.close();
|
|
153
|
+
}
|
|
154
|
+
const migrated = validateData(target);
|
|
155
|
+
const checked = writeArchiveManifest(target, {
|
|
156
|
+
kind: "import",
|
|
157
|
+
filename: "data.db",
|
|
158
|
+
});
|
|
159
|
+
return {
|
|
160
|
+
summary: migrated,
|
|
161
|
+
originalVersion: original.schemaVersion,
|
|
162
|
+
manifest: checked,
|
|
163
|
+
bytes: statSync(target).size,
|
|
164
|
+
};
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
export function applyDataImport(
|
|
168
|
+
candidate,
|
|
169
|
+
source,
|
|
170
|
+
backups,
|
|
171
|
+
{ id = randomUUID(), move = renameSync, beforeSwap = () => {} } = {},
|
|
172
|
+
) {
|
|
173
|
+
if (source === ":memory:" || !existsSync(source))
|
|
174
|
+
throw Error("当前实例不支持文件导入");
|
|
175
|
+
return withBackupLock(backups, () => {
|
|
176
|
+
verifyArchive(candidate);
|
|
177
|
+
validateData(candidate);
|
|
178
|
+
const old = new DatabaseSync(source);
|
|
179
|
+
let auth, sessions, settings;
|
|
180
|
+
try {
|
|
181
|
+
settings = JSON.parse(
|
|
182
|
+
old.prepare("SELECT value FROM settings WHERE id=1").get().value,
|
|
183
|
+
);
|
|
184
|
+
auth = old
|
|
185
|
+
.prepare("SELECT salt,hash FROM management_auth WHERE id=1")
|
|
186
|
+
.get();
|
|
187
|
+
sessions = old
|
|
188
|
+
.prepare("SELECT id,expires FROM management_sessions")
|
|
189
|
+
.all();
|
|
190
|
+
const checkpoint = old.prepare("PRAGMA wal_checkpoint(TRUNCATE)").get();
|
|
191
|
+
if (checkpoint.busy) throw Error("当前数据库仍在使用,请稍后导入");
|
|
192
|
+
} finally {
|
|
193
|
+
old.close();
|
|
194
|
+
}
|
|
195
|
+
if (existsSync(`${source}-wal`) || existsSync(`${source}-shm`))
|
|
196
|
+
throw Error("当前数据库仍在使用,请稍后导入");
|
|
197
|
+
const imported = new DatabaseSync(candidate);
|
|
198
|
+
try {
|
|
199
|
+
imported.exec("BEGIN IMMEDIATE");
|
|
200
|
+
imported.exec(
|
|
201
|
+
"DROP TABLE IF EXISTS management_sessions; DROP TABLE IF EXISTS management_auth; CREATE TABLE management_auth(id INTEGER PRIMARY KEY CHECK(id=1),salt TEXT NOT NULL,hash TEXT NOT NULL); CREATE TABLE management_sessions(id TEXT PRIMARY KEY,expires INTEGER NOT NULL);",
|
|
202
|
+
);
|
|
203
|
+
if (auth)
|
|
204
|
+
imported
|
|
205
|
+
.prepare("INSERT INTO management_auth VALUES (1,?,?)")
|
|
206
|
+
.run(auth.salt, auth.hash);
|
|
207
|
+
for (const row of sessions)
|
|
208
|
+
imported
|
|
209
|
+
.prepare("INSERT INTO management_sessions VALUES (?,?)")
|
|
210
|
+
.run(row.id, row.expires);
|
|
211
|
+
const incoming = JSON.parse(
|
|
212
|
+
imported.prepare("SELECT value FROM settings WHERE id=1").get().value,
|
|
213
|
+
);
|
|
214
|
+
for (const field of [
|
|
215
|
+
"onebotToken",
|
|
216
|
+
"qqbotAppId",
|
|
217
|
+
"qqbotSecret",
|
|
218
|
+
"channel",
|
|
219
|
+
"backupCleanup",
|
|
220
|
+
"backupCleanupLast",
|
|
221
|
+
]) {
|
|
222
|
+
delete incoming[field];
|
|
223
|
+
if (settings[field] !== undefined) incoming[field] = settings[field];
|
|
224
|
+
}
|
|
225
|
+
incoming.enabled = false;
|
|
226
|
+
incoming.dataImportId = id;
|
|
227
|
+
imported
|
|
228
|
+
.prepare("UPDATE settings SET value=? WHERE id=1")
|
|
229
|
+
.run(JSON.stringify(incoming));
|
|
230
|
+
imported.exec(
|
|
231
|
+
"UPDATE plugin_installs SET enabled=0,granted='[]',path=''; COMMIT; PRAGMA wal_checkpoint(TRUNCATE);",
|
|
232
|
+
);
|
|
233
|
+
} catch (error) {
|
|
234
|
+
if (imported.isTransaction) imported.exec("ROLLBACK");
|
|
235
|
+
throw error;
|
|
236
|
+
} finally {
|
|
237
|
+
imported.close();
|
|
238
|
+
}
|
|
239
|
+
validateData(candidate);
|
|
240
|
+
mkdirSync(backups, { recursive: true });
|
|
241
|
+
const rollback = join(
|
|
242
|
+
backups,
|
|
243
|
+
`luckytri-before-import-${Date.now()}-${randomUUID().slice(0, 8)}.db`,
|
|
244
|
+
);
|
|
245
|
+
// Move the checkpointed original instead of creating another multi-GiB
|
|
246
|
+
// duplicate. The snapshot and its manifest remain available to restore.
|
|
247
|
+
writeArchiveManifest(source, {
|
|
248
|
+
kind: "before-import",
|
|
249
|
+
filename: basename(rollback),
|
|
250
|
+
});
|
|
251
|
+
beforeSwap(basename(rollback));
|
|
252
|
+
let original = rollback;
|
|
253
|
+
try {
|
|
254
|
+
move(source, rollback);
|
|
255
|
+
} catch (error) {
|
|
256
|
+
if (error.code !== "EXDEV") throw error;
|
|
257
|
+
// Custom backup folders may be on another disk. Retain one verified
|
|
258
|
+
// snapshot there, and keep the swap on the database's own filesystem.
|
|
259
|
+
copyDatabaseFile(source, rollback);
|
|
260
|
+
writeArchiveManifest(rollback, {
|
|
261
|
+
kind: "before-import",
|
|
262
|
+
filename: basename(rollback),
|
|
263
|
+
});
|
|
264
|
+
original = `${source}.import-swap-${randomUUID()}`;
|
|
265
|
+
move(source, original);
|
|
266
|
+
}
|
|
267
|
+
try {
|
|
268
|
+
if (original === rollback) move(`${source}.json`, `${rollback}.json`);
|
|
269
|
+
try {
|
|
270
|
+
move(candidate, source);
|
|
271
|
+
} catch (error) {
|
|
272
|
+
if (error.code !== "EXDEV") throw error;
|
|
273
|
+
const local = join(
|
|
274
|
+
dirname(source),
|
|
275
|
+
`.luckytri-import-${randomUUID()}.partial.db`,
|
|
276
|
+
);
|
|
277
|
+
try {
|
|
278
|
+
copyDatabaseFile(candidate, local);
|
|
279
|
+
validateData(local);
|
|
280
|
+
move(local, source);
|
|
281
|
+
rmSync(candidate, { force: true });
|
|
282
|
+
} finally {
|
|
283
|
+
rmSync(local, { force: true });
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
} catch (error) {
|
|
287
|
+
if (!existsSync(source)) renameSync(original, source);
|
|
288
|
+
if (existsSync(`${rollback}.json`))
|
|
289
|
+
renameSync(`${rollback}.json`, `${source}.json`);
|
|
290
|
+
throw error;
|
|
291
|
+
}
|
|
292
|
+
if (original !== rollback) {
|
|
293
|
+
rmSync(original, { force: true });
|
|
294
|
+
rmSync(`${source}.json`, { force: true });
|
|
295
|
+
}
|
|
296
|
+
return { backup: basename(rollback), schemaVersion: DATABASE_VERSION };
|
|
297
|
+
});
|
|
298
|
+
}
|