Skip to content

WorkBuddy、CodeBuddy 桌面端增强助手:签到猫猫旅行成长计划查询、多账号独立备份、点切即用;免打扰模式让 AI 无人值守跑长任务;跨账号会话迁移、异常中断自动续接;暂存/快捷提示词;毛玻璃主题与更多实用功能。

fix(db): bind session queries across SQLite backends

Jinhui Zheng536055e4aad0
diff --git a/scripts/build-mac-dmg.sh b/scripts/build-mac-dmg.sh
index 5583a30..e987f83 100644
--- a/scripts/build-mac-dmg.sh
+++ b/scripts/build-mac-dmg.sh
@@ -43,7 +43,7 @@ chmod 755 "$APP/Contents/MacOS/launcher"
echo "==> launcher 可执行位已保证: $(stat -f '%Sp' "$APP/Contents/MacOS/launcher")"
# 2) 只覆盖前端代码(保留壳的其余一切:launcher/Info.plist/builtin/node_modules/theme-audit.js)
-for f in daemon.js inject.js theme-patches.js credit-segments.js credit-resource-queries.js lib.js profiles.js cdp-targets.js sentry-report.js install.sh relaunch-with-cdp.sh uninstall.sh apply-update.sh; do
+for f in daemon.js session-db.js inject.js theme-patches.js credit-segments.js credit-resource-queries.js lib.js profiles.js cdp-targets.js sentry-report.js install.sh relaunch-with-cdp.sh uninstall.sh apply-update.sh; do
[ -f "scripts/$f" ] && cp "scripts/$f" "$APP/Contents/Resources/scripts/$f"
done
# 恢复这些文件的壳权限(与 1.0.3 壳内一致:sh/lib/daemon 755,inject/theme-patches 644)
@@ -54,7 +54,8 @@ chmod 755 "$APP/Contents/Resources/scripts/daemon.js" \
"$APP/Contents/Resources/scripts/relaunch-with-cdp.sh" \
"$APP/Contents/Resources/scripts/uninstall.sh" \
"$APP/Contents/Resources/scripts/apply-update.sh"
-chmod 644 "$APP/Contents/Resources/scripts/inject.js" \
+chmod 644 "$APP/Contents/Resources/scripts/session-db.js" \
+ "$APP/Contents/Resources/scripts/inject.js" \
"$APP/Contents/Resources/scripts/theme-patches.js"
echo "==> 前端代码已覆盖(权限按壳原样)"
diff --git a/scripts/daemon.js b/scripts/daemon.js
index 60de504..cd8e539 100644
--- a/scripts/daemon.js
+++ b/scripts/daemon.js
@@ -100,6 +100,8 @@ const { buildCreditResourceBody } = require('./credit-resource-queries.js');
const { captureException, captureMessage } = require('./sentry-report.js');
const { getProfile, profileDataDir, listInstalledModelSources } = require('./profiles.js');
const { classifyTarget, looksLikeWbFamilyTarget, isTargetForProfile } = require('./cdp-targets.js');
+const { createSessionDb, normalizeSessionIdBatch, parameterCount } = require('./session-db.js');
+
const PROFILE = getProfile();
const DATA_DIR = defaultDataDir();
// 版本号:改动 daemon/inject/theme-patches/builtin 资产后递增,launcher 检测到运行中版本不一致会强制用 app 内置代码重启
@@ -169,8 +171,9 @@ const DATA_DIR = defaultDataDir();
// 1.0.13:下载使用唯一临时文件并在校验通过后原子替换,防止并发更新造成 ENOENT。
// 1.0.25:会话删除仅作用于数据库匹配记录,并在清理失败时保留可重试的数据库记录。
// 1.0.26:Windows launcher/logout 取消脚本提权与镜像名结束,只操作同安装目录的已验证 PID。
-const DAEMON_VERSION = '1.0.26';
-const DAEMON_BUILD_ID = 'release-1.0.26-20260824-least-privilege';
+// 1.0.27:会话数据库查询在原生 SQLite 与 CLI fallback 上统一使用绑定参数。
+const DAEMON_VERSION = '1.0.27';
+const DAEMON_BUILD_ID = 'release-1.0.27-20260824-session-db';
const HOST = '127.0.0.1';
const IS_WIN = process.platform === 'win32'; // Windows 移植:平台分支开关(macOS 行为保持不变)
// Windows 安装目录(install.ps1 铺、launcher 用、更新替换目标),对应 macOS 的 /Applications/WorkDaddy.app
@@ -2349,78 +2352,17 @@ async function writeDiagnosticsSnapshot(reason) {
// ===== SESSIONS_API_MARK:会话管理(读 WorkBuddy workbuddy.db)=====
const SESSIONS_DB = PROFILE.sessionDb;
-// Windows:无系统 sqlite3 CLI,优先用 Node 内置 node:sqlite(需 --experimental-sqlite 启动,launcher/install 已统一加)
-let NodeSqlite = null;
-if (IS_WIN) { try { NodeSqlite = require('node:sqlite'); } catch (_) { NodeSqlite = null; } }
-// 输出统一为 "header|header2\nval|val2" 格式,sqliteQuery 的解析两种后端通用
-function sqliteIsWrite(sql) {
- // 复制/迁移/删除/恢复会执行写 SQL;其余当前调用均为查询。
- return /^\s*(?:INSERT|UPDATE|DELETE|REPLACE|CREATE|DROP|ALTER|VACUUM|REINDEX|ANALYZE|BEGIN|COMMIT|ROLLBACK|ATTACH|DETACH)\b/i.test(String(sql || ''));
-}
-function sqliteRun(sql) {
+const SESSION_DB = createSessionDb({ dbPath: SESSIONS_DB });
+
+function sqliteRun(sql, params = []) {
if (PROFILE.kind === 'codebuddy') {
return Promise.reject(new Error(`${PROFILE.name} 会话库暂只支持读取`));
}
- if (IS_WIN && NodeSqlite) {
- return new Promise((resolve, reject) => {
- let db = null;
- try {
- const write = sqliteIsWrite(sql);
- db = new NodeSqlite.DatabaseSync(SESSIONS_DB, { readOnly: !write });
- if (write) {
- db.exec(sql);
- db.close(); db = null;
- return resolve('');
- }
- const rows = db.prepare(sql).all();
- db.close(); db = null;
- if (!rows.length) return resolve('');
- const header = Object.keys(rows[0]).join('|');
- const lines = rows.map((r) =>
- Object.values(r).map((v) => (v === null || v === undefined ? '' : String(v))).join('|')
- );
- resolve([header].concat(lines).join('\n'));
- } catch (e) {
- if (db) { try { db.close(); } catch (_) {} }
- reject(new Error('sqlite 查询失败: ' + e.message));
- }
- });
- }
- return new Promise((resolve, reject) => {
- const p = spawn('sqlite3', ['-header', SESSIONS_DB], { stdio: ['pipe', 'pipe', 'pipe'] });
- let out = '', err = '';
- p.stdout.on('data', (d) => (out += d));
- p.stderr.on('data', (d) => (err += d));
- p.on('error', (e) => reject(new Error('sqlite3 不可用: ' + e.message)));
- p.on('close', (code) => {
- if (code !== 0) reject(new Error('sqlite 失败(' + code + '): ' + err.slice(0, 200)));
- else resolve(out);
- });
- p.stdin.end(sql);
- });
+ return SESSION_DB.run(sql, params);
}
function codeBuddySessionRows() {
- if (NodeSqlite) {
- try {
- const db = new NodeSqlite.DatabaseSync(SESSIONS_DB, { readOnly: true });
- const items = db.prepare("SELECT key, value FROM ItemTable WHERE key LIKE 'session:%'").all();
- db.close();
- return Promise.resolve(items.map((item) => ({ key: item.key, value: item.value })));
- } catch (e) {
- return Promise.reject(new Error('CodeBuddy 会话库读取失败: ' + e.message));
- }
- }
- return new Promise((resolve, reject) => {
- const p = spawn('sqlite3', ['-json', SESSIONS_DB, 'SELECT key, value FROM ItemTable WHERE key LIKE \'session:%\';'], { stdio: ['ignore', 'pipe', 'pipe'] });
- let out = '', err = '';
- p.stdout.on('data', (d) => { out += d; });
- p.stderr.on('data', (d) => { err += d; });
- p.on('error', (e) => reject(new Error('sqlite3 不可用: ' + e.message)));
- p.on('close', (code) => {
- if (code !== 0) return reject(new Error('CodeBuddy 会话库读取失败: ' + err.slice(0, 200)));
- let items = [];
- try { items = JSON.parse(out || '[]'); } catch (e) { return reject(new Error('CodeBuddy 会话记录解析失败: ' + e.message)); }
- resolve(items.map((item) => {
+ return SESSION_DB.all("SELECT key, value FROM ItemTable WHERE key LIKE 'session:%'")
+ .then((items) => items.map((item) => {
let value = {};
try { value = typeof item.value === 'string' ? JSON.parse(item.value) : (item.value || {}); } catch (_) {}
const id = String(value.conversationId || String(item.key || '').replace(/^session:/, ''));
@@ -2430,36 +2372,51 @@ function codeBuddySessionRows() {
last_activity_at: value.updatedAt || null, is_playground: value.isPlayground ? 1 : 0,
deleted_at: null, source_mode: value.mode || 'agents', mode: value.mode || 'agents', model: value.model || '',
};
- }));
- });
- });
+ }))
+ .catch((e) => { throw new Error('CodeBuddy 会话库读取失败: ' + e.message); });
+}
+function sqlParamAt(textSql, params, questionIndex) {
+ return params[parameterCount(textSql.slice(0, questionIndex + 1)) - 1];
}
-async function sqliteQuery(sql) {
+async function sqliteQuery(sql, params = []) {
+ const expectedParams = parameterCount(sql);
+ if (expectedParams !== params.length) {
+ throw new Error(`sqlite 参数数量不匹配: SQL 需要 ${expectedParams} 个,实际收到 ${params.length} 个`);
+ }
if (PROFILE.kind === 'codebuddy') {
const rows = await codeBuddySessionRows();
const textSql = String(sql || '');
- const uidMatch = textSql.match(/user_id\s*=\s*'([^']*)'/i);
- const idMatch = textSql.match(/id\s+IN\s*\(([^)]*)\)/i);
+ const uidMatch = /user_id\s*=\s*\?/i.exec(textSql);
+ const idMatch = /id\s+IN\s*\(([^)]*)\)/i.exec(textSql);
+ const singleIdMatch = /\bid\s*=\s*\?/i.exec(textSql);
let filtered = rows;
- if (uidMatch) filtered = filtered.filter((r) => String(r.user_id) === uidMatch[1]);
+ if (uidMatch) {
+ const questionIndex = textSql.indexOf('?', uidMatch.index);
+ const uid = sqlParamAt(textSql, params, questionIndex);
+ filtered = filtered.filter((r) => String(r.user_id) === String(uid));
+ }
if (idMatch) {
- const ids = new Set(Array.from(idMatch[1].matchAll(/'([^']*)'/g)).map((m) => m[1]));
+ const questionIndex = textSql.indexOf('?', idMatch.index);
+ const start = parameterCount(textSql.slice(0, questionIndex + 1)) - 1;
+ const ids = new Set(params.slice(start, start + parameterCount(idMatch[1])).map(String));
filtered = filtered.filter((r) => ids.has(String(r.id)));
}
+ if (singleIdMatch) {
+ const questionIndex = textSql.indexOf('?', singleIdMatch.index);
+ const id = sqlParamAt(textSql, params, questionIndex);
+ filtered = filtered.filter((r) => String(r.id) === String(id));
+ }
if (/SELECT\s+DISTINCT\s+cwd/i.test(textSql)) return Array.from(new Set(filtered.map((r) => r.cwd).filter(Boolean))).map((cwd) => ({ cwd }));
if (/SELECT\s+user_id/i.test(textSql) && /LIMIT\s+1/i.test(textSql)) return filtered.slice(0, 1).map((r) => ({ user_id: r.user_id }));
return filtered;
}
- const out = await sqliteRun(sql);
- if (!out.trim()) return [];
- const lines = out.trim().split('\n');
- const header = lines[0].split('|');
- return lines.slice(1).map((ln) => {
- const parts = ln.split('|');
- const o = {};
- header.forEach((h, i) => (o[h.trim()] = parts[i] === undefined ? null : parts[i].trim()));
- return o;
- });
+ const rows = await SESSION_DB.all(sql, params);
+ // Keep the existing API contract (SQLite cells were strings, NULL was empty)
+ // while avoiding the delimiter/newline corruption of the former text parser.
+ return rows.map((row) => Object.fromEntries(Object.entries(row).map(([key, value]) => [
+ key,
+ value === null || value === undefined ? '' : String(value).trim(),
+ ])));
}
function sessionRangeMs(range) {
const now = Date.now();
@@ -2532,39 +2489,38 @@ function isTaskSessionRecord(cwd) {
return false;
}
-function sqlQuote(value) {
- return "'" + String(value == null ? '' : value).replace(/'/g, "''") + "'";
-}
-
-function sqlNullable(value) {
- return value === null || value === undefined || value === '' ? 'NULL' : sqlQuote(value);
+function sqlPlaceholders(values) {
+ return values.map(() => '?').join(',');
}
async function insertCopiedSession(src, targetUid, newId) {
const vals = [
- sqlQuote(newId),
- sqlQuote(src.cwd || ''),
- sqlQuote(targetUid),
- sqlQuote(src.title || ''),
- sqlQuote(src.custom_title || ''),
- sqlQuote(src.status || 'Pending'),
- String(src.created_at || Date.now()),
- String(Date.now()),
- String(src.last_activity_at || src.updated_at || Date.now()),
- String(src.is_playground || 0),
- sqlNullable(src.source_mode),
- src.is_background_automation === null || src.is_background_automation === undefined || src.is_background_automation === '' ? 'NULL' : String(src.is_background_automation),
- sqlNullable(src.mode),
- sqlNullable(src.model),
- sqlNullable(src.expert_id),
- sqlNullable(src.expert_locale),
- sqlNullable(src.expert_runtime_identity),
- sqlNullable(src.expert_marketplace),
- sqlNullable(src.permission_mode),
- src.use_sandbox_cli === null || src.use_sandbox_cli === undefined || src.use_sandbox_cli === '' ? 'NULL' : String(src.use_sandbox_cli),
- sqlNullable(src.project_id),
+ newId,
+ src.cwd || '',
+ targetUid,
+ src.title || '',
+ src.custom_title || '',
+ src.status || 'Pending',
+ Number(src.created_at || Date.now()),
+ Date.now(),
+ Number(src.last_activity_at || src.updated_at || Date.now()),
+ Number(src.is_playground || 0),
+ src.source_mode || null,
+ src.is_background_automation === null || src.is_background_automation === undefined || src.is_background_automation === '' ? null : Number(src.is_background_automation),
+ src.mode || null,
+ src.model || null,
+ src.expert_id || null,
+ src.expert_locale || null,
+ src.expert_runtime_identity || null,
+ src.expert_marketplace || null,
+ src.permission_mode || null,
+ src.use_sandbox_cli === null || src.use_sandbox_cli === undefined || src.use_sandbox_cli === '' ? null : Number(src.use_sandbox_cli),
+ src.project_id || null,
];
- await sqliteRun('INSERT INTO sessions (' + SESSION_COPY_COLUMNS.join(',') + ') VALUES (' + vals.join(',') + ');');
+ await sqliteRun(
+ 'INSERT INTO sessions (' + SESSION_COPY_COLUMNS.join(',') + ') VALUES (' + sqlPlaceholders(vals) + ');',
+ vals
+ );
}
async function copySessionRecord(src, targetUid, options = {}) {
@@ -2579,7 +2535,10 @@ async function copySessionRecord(src, targetUid, options = {}) {
if (sourceUid && lineageId) {
const mapping = getAutoCopyMapping(DATA_DIR, lineageId, targetUid);
if (mapping && mapping.targetId) {
- const existing = await sqliteQuery('SELECT id, user_id FROM sessions WHERE id = ' + sqlQuote(mapping.targetId) + ' AND deleted_at IS NULL LIMIT 1;');
+ const existing = await sqliteQuery(
+ 'SELECT id, user_id FROM sessions WHERE id = ? AND deleted_at IS NULL LIMIT 1;',
+ [mapping.targetId]
+ );
if (existing.length && String(existing[0].user_id || '') === String(targetUid)) {
const files = copySessionFiles(wbHome, src.id, mapping.targetId);
addAutoCopySessionMember(DATA_DIR, lineageId, targetUid, mapping.targetId);
@@ -2627,7 +2586,8 @@ async function buildAutoCopyPlan(sourceUid, targetUid) {
if (!rules.sessionIds.length && !rules.workspaces.length) return [];
const rows = await sqliteQuery(
'SELECT id, cwd, user_id, title, custom_title, status, created_at, updated_at, last_activity_at, is_playground, source_mode, is_background_automation, mode, model, expert_id, expert_locale, expert_runtime_identity, expert_marketplace, permission_mode, use_sandbox_cli, project_id ' +
- 'FROM sessions WHERE deleted_at IS NULL AND user_id = ' + sqlQuote(source) + ' ORDER BY created_at DESC;'
+ 'FROM sessions WHERE deleted_at IS NULL AND user_id = ? ORDER BY created_at DESC;',
+ [source]
);
const sessionSet = new Set(rules.sessionIds);
const workspaceSet = new Set(rules.workspaces.map(canonicalWorkspace));
@@ -4758,10 +4718,11 @@ function handleApi(req, res) {
const range = url.searchParams.get('range') || '7d';
const rangeMs = sessionRangeMs(range);
const clauses = ["deleted_at IS NULL"];
- if (uid) clauses.push("user_id = '" + uid.replace(/'/g, "''") + "'");
- if (rangeMs) clauses.push('COALESCE(last_activity_at, updated_at, created_at) >= ' + rangeMs);
+ const params = [];
+ if (uid) { clauses.push('user_id = ?'); params.push(uid); }
+ if (rangeMs) { clauses.push('COALESCE(last_activity_at, updated_at, created_at) >= ?'); params.push(rangeMs); }
// 时间筛选和排序按最近活动/修改时间;旧记录缺字段时回退到创建时间。
- return sqliteQuery("SELECT id, cwd, user_id, title, custom_title, status, created_at, updated_at, last_activity_at, is_playground, project_id FROM sessions WHERE " + clauses.join(' AND ') + " ORDER BY COALESCE(last_activity_at, updated_at, created_at) DESC, created_at DESC;")
+ return sqliteQuery("SELECT id, cwd, user_id, title, custom_title, status, created_at, updated_at, last_activity_at, is_playground, project_id FROM sessions WHERE " + clauses.join(' AND ') + " ORDER BY COALESCE(last_activity_at, updated_at, created_at) DESC, created_at DESC;", params)
.then((rows) => {
const rulesByUid = {};
rows.forEach((row) => {
@@ -4965,7 +4926,10 @@ function handleApi(req, res) {
const key = String(body.key || '').trim();
if (!uid || !key) return json(res, 400, { ok: false, error: '缺少自动复制规则参数' });
if (kind === 'session') {
- const rows = await sqliteQuery('SELECT user_id FROM sessions WHERE id = ' + sqlQuote(key) + ' AND deleted_at IS NULL LIMIT 1;');
+ const rows = await sqliteQuery(
+ 'SELECT user_id FROM sessions WHERE id = ? AND deleted_at IS NULL LIMIT 1;',
+ [key]
+ );
if (!rows.length || String(rows[0].user_id || '') !== uid) return json(res, 404, { ok: false, error: '会话不存在或不属于该账号' });
}
const rules = setAutoCopyRule(DATA_DIR, { uid, kind, key, enabled: body.enabled !== false });
@@ -4983,14 +4947,18 @@ function handleApi(req, res) {
// 复制会话:POST /api/sessions/copy { ids, targetUid }(保留原会话,复制记录+消息文件到目标账号)
if (req.method === 'POST' && p === '/api/sessions/copy') {
return readBody(req).then(async (body) => {
- const ids = Array.isArray(body.ids) ? body.ids.filter((x) => typeof x === 'string') : [];
+ let ids;
+ try { ids = normalizeSessionIdBatch(body && body.ids); }
+ catch (e) { return json(res, 400, { ok: false, error: e.message }); }
const targetUid = (body.targetUid || '').trim();
if (!ids.length) return json(res, 400, { ok: false, error: '未选择会话' });
if (!targetUid) return json(res, 400, { ok: false, error: '未指定目标账号' });
try {
- const esc = ids.map((i) => "'" + String(i).replace(/'/g, "''") + "'").join(',');
// 1) 取出源会话(含 cwd 用于定位消息文件)
- const srcRows = await sqliteQuery("SELECT id, cwd, user_id, title, custom_title, status, created_at, updated_at, last_activity_at, is_playground, source_mode, is_background_automation, mode, model, expert_id, expert_locale, expert_runtime_identity, expert_marketplace, permission_mode, use_sandbox_cli, project_id FROM sessions WHERE id IN (" + esc + ") AND deleted_at IS NULL;");
+ const srcRows = await sqliteQuery(
+ "SELECT id, cwd, user_id, title, custom_title, status, created_at, updated_at, last_activity_at, is_playground, source_mode, is_background_automation, mode, model, expert_id, expert_locale, expert_runtime_identity, expert_marketplace, permission_mode, use_sandbox_cli, project_id FROM sessions WHERE id IN (" + sqlPlaceholders(ids) + ") AND deleted_at IS NULL;",
+ ids
+ );
if (!srcRows.length) return json(res, 404, { ok: false, error: '源会话不存在' });
let copied = 0;
for (const src of srcRows) {
@@ -5006,14 +4974,22 @@ function handleApi(req, res) {
// 迁移会话:POST /api/sessions/migrate { ids, targetUid }
if (req.method === 'POST' && p === '/api/sessions/migrate') {
return readBody(req).then(async (body) => {
- const ids = Array.isArray(body.ids) ? body.ids.filter((x) => typeof x === 'string') : [];
+ let ids;
+ try { ids = normalizeSessionIdBatch(body && body.ids); }
+ catch (e) { return json(res, 400, { ok: false, error: e.message }); }
const targetUid = (body.targetUid || '').trim();
if (!ids.length) return json(res, 400, { ok: false, error: '未选择会话' });
if (!targetUid) return json(res, 400, { ok: false, error: '未指定目标账号' });
try {
- const esc = ids.map((i) => sqlQuote(i)).join(',');
- const before = await sqliteQuery('SELECT id, user_id FROM sessions WHERE id IN (' + esc + ') AND deleted_at IS NULL;');
- await sqliteRun("UPDATE sessions SET user_id = " + sqlQuote(targetUid) + ", updated_at = " + Date.now() + " WHERE id IN (" + esc + ");");
+ const placeholders = sqlPlaceholders(ids);
+ const before = await sqliteQuery(
+ 'SELECT id, user_id FROM sessions WHERE id IN (' + placeholders + ') AND deleted_at IS NULL;',
+ ids
+ );
+ await sqliteRun(
+ "UPDATE sessions SET user_id = ?, updated_at = ? WHERE id IN (" + placeholders + ");",
+ [targetUid, Date.now(), ...ids]
+ );
let rulesMoved = 0;
for (const row of before) {
if (String(row.user_id || '') === targetUid) continue;
@@ -5033,12 +5009,14 @@ function handleApi(req, res) {
// 删除会话(真实删除):POST /api/sessions/delete { ids }——删除 DB 记录 + 该账号下全部会话文件(不可恢复)
if (req.method === 'POST' && p === '/api/sessions/delete') {
return readBody(req).then(async (body) => {
- const ids = Array.isArray(body.ids) ? body.ids : [];
+ let ids;
+ try { ids = normalizeSessionIdBatch(body && body.ids); }
+ catch (e) { return json(res, 400, { ok: false, error: e.message }); }
if (!ids.length) return json(res, 400, { ok: false, error: '未选择会话' });
if (!ids.every(isValidSessionId)) return json(res, 400, { ok: false, error: '包含无效的会话 ID' });
try {
- const esc = ids.map((i) => sqlQuote(i)).join(',');
- const before = await sqliteQuery('SELECT id, user_id FROM sessions WHERE id IN (' + esc + ');');
+ const placeholders = sqlPlaceholders(ids);
+ const before = await sqliteQuery('SELECT id, user_id FROM sessions WHERE id IN (' + placeholders + ');', ids);
const matchedIds = matchedSessionIds(ids, before);
const matchedSet = new Set(matchedIds);
const matchedRows = before.filter((row) => matchedSet.has(String(row.id || '')));
@@ -5057,8 +5035,10 @@ function handleApi(req, res) {
}
// 2) 最后真实删除 DB 记录(非软删)。若此步失败,重复请求可安全重试。
if (matchedIds.length) {
- const matchedEsc = matchedIds.map((i) => sqlQuote(i)).join(',');
- await sqliteRun("DELETE FROM sessions WHERE id IN (" + matchedEsc + ");");
+ await sqliteRun(
+ "DELETE FROM sessions WHERE id IN (" + sqlPlaceholders(matchedIds) + ");",
+ matchedIds
+ );
}
log(`[sessions-delete] 已真实删除 ${matchedIds.length} 个会话(DB + ${filesRemoved} 项文件)`);
return json(res, 200, { ok: true, deleted: matchedIds.length, requested: ids.length, filesRemoved, rulesRemoved });
@@ -5070,10 +5050,14 @@ function handleApi(req, res) {
// 恢复会话:POST /api/sessions/restore { ids }
if (req.method === 'POST' && p === '/api/sessions/restore') {
return readBody(req).then((body) => {
- const ids = Array.isArray(body.ids) ? body.ids.filter((x) => typeof x === 'string') : [];
+ let ids;
+ try { ids = normalizeSessionIdBatch(body && body.ids); }
+ catch (e) { return json(res, 400, { ok: false, error: e.message }); }
if (!ids.length) return json(res, 400, { ok: false, error: '未选择会话' });
- const esc = ids.map((i) => "'" + String(i).replace(/'/g, "''") + "'").join(',');
- return sqliteRun("UPDATE sessions SET deleted_at = NULL, updated_at = " + Date.now() + " WHERE id IN (" + esc + ");")
+ return sqliteRun(
+ "UPDATE sessions SET deleted_at = NULL, updated_at = ? WHERE id IN (" + sqlPlaceholders(ids) + ");",
+ [Date.now(), ...ids]
+ )
.then(() => json(res, 200, { ok: true, restored: ids.length }))
.catch((e) => json(res, 500, { ok: false, error: e.message }));
});
diff --git a/scripts/session-db.js b/scripts/session-db.js
new file mode 100644
index 0000000..9ed06b6
--- /dev/null
+++ b/scripts/session-db.js
@@ -0,0 +1,483 @@
+'use strict';
+
+const { spawn } = require('node:child_process');
+
+const JS_SAFE_INTEGER_MIN = BigInt(Number.MIN_SAFE_INTEGER);
+const JS_SAFE_INTEGER_MAX = BigInt(Number.MAX_SAFE_INTEGER);
+const MAX_SESSION_ID_BATCH = 100;
+const MAX_SESSION_ID_LENGTH = 200;
+
+function loadNodeSqlite() {
+ try {
+ return require('node:sqlite');
+ } catch (_) {
+ return null;
+ }
+}
+
+function parameterCount(sql) {
+ const text = String(sql || '');
+ let count = 0;
+ let state = 'plain';
+ for (let i = 0; i < text.length; i++) {
+ const ch = text[i];
+ const next = text[i + 1];
+ if (state === 'single') {
+ if (ch === "'" && next === "'") i++;
+ else if (ch === "'") state = 'plain';
+ continue;
+ }
+ if (state === 'double') {
+ if (ch === '"' && next === '"') i++;
+ else if (ch === '"') state = 'plain';
+ continue;
+ }
+ if (state === 'backtick') {
+ if (ch === '`' && next === '`') i++;
+ else if (ch === '`') state = 'plain';
+ continue;
+ }
+ if (state === 'bracket') {
+ if (ch === ']') state = 'plain';
+ continue;
+ }
+ if (state === 'line-comment') {
+ if (ch === '\n' || ch === '\r') state = 'plain';
+ continue;
+ }
+ if (state === 'block-comment') {
+ if (ch === '*' && next === '/') { state = 'plain'; i++; }
+ continue;
+ }
+ if (ch === "'") state = 'single';
+ else if (ch === '"') state = 'double';
+ else if (ch === '`') state = 'backtick';
+ else if (ch === '[') state = 'bracket';
+ else if (ch === '-' && next === '-') { state = 'line-comment'; i++; }
+ else if (ch === '/' && next === '*') { state = 'block-comment'; i++; }
+ else if (ch === '?') count++;
+ }
+ return count;
+}
+
+function assertParameterCount(sql, params) {
+ if (!Array.isArray(params)) throw new TypeError('sqlite 参数必须是数组');
+ const expected = parameterCount(sql);
+ if (expected !== params.length) {
+ throw new Error(`sqlite 参数数量不匹配: SQL 需要 ${expected} 个,实际收到 ${params.length} 个`);
+ }
+}
+
+function assertNoSqliteMetaCommands(sql) {
+ const text = String(sql || '');
+ let state = 'plain';
+ let lineOnlyWhitespace = true;
+ for (let i = 0; i < text.length; i++) {
+ const ch = text[i];
+ const next = text[i + 1];
+ if (ch === '\r' || ch === '\n') {
+ if (state === 'line-comment') state = 'plain';
+ lineOnlyWhitespace = true;
+ continue;
+ }
+ if (state === 'single') {
+ if (ch === "'" && next === "'") { lineOnlyWhitespace = false; i++; }
+ else if (ch === "'") state = 'plain';
+ if (ch !== ' ' && ch !== '\t') lineOnlyWhitespace = false;
+ continue;
+ }
+ if (state === 'double') {
+ if (ch === '"' && next === '"') { lineOnlyWhitespace = false; i++; }
+ else if (ch === '"') state = 'plain';
+ if (ch !== ' ' && ch !== '\t') lineOnlyWhitespace = false;
+ continue;
+ }
+ if (state === 'backtick') {
+ if (ch === '`' && next === '`') { lineOnlyWhitespace = false; i++; }
+ else if (ch === '`') state = 'plain';
+ if (ch !== ' ' && ch !== '\t') lineOnlyWhitespace = false;
+ continue;
+ }
+ if (state === 'bracket') {
+ if (ch === ']') state = 'plain';
+ if (ch !== ' ' && ch !== '\t') lineOnlyWhitespace = false;
+ continue;
+ }
+ if (state === 'line-comment') {
+ if (ch !== ' ' && ch !== '\t') lineOnlyWhitespace = false;
+ continue;
+ }
+ if (state === 'block-comment') {
+ if (ch === '*' && next === '/') { lineOnlyWhitespace = false; state = 'plain'; i++; }
+ else if (ch !== ' ' && ch !== '\t') lineOnlyWhitespace = false;
+ continue;
+ }
+ if (lineOnlyWhitespace && ch === '.') {
+ throw new Error('sqlite SQL 不允许 CLI 点命令 (dot command)');
+ }
+ if (ch !== ' ' && ch !== '\t' && ch !== '\ufeff') lineOnlyWhitespace = false;
+ if (ch === "'") state = 'single';
+ else if (ch === '"') state = 'double';
+ else if (ch === '`') state = 'backtick';
+ else if (ch === '[') state = 'bracket';
+ else if (ch === '-' && next === '-') { state = 'line-comment'; i++; }
+ else if (ch === '/' && next === '*') { state = 'block-comment'; i++; }
+ }
+}
+
+function leadingSqlKeyword(sql) {
+ const text = String(sql || '');
+ let index = 0;
+ while (index < text.length) {
+ while (index < text.length && /\s/.test(text[index])) index++;
+ if (text[index] === '-' && text[index + 1] === '-') {
+ index += 2;
+ while (index < text.length && text[index] !== '\r' && text[index] !== '\n') index++;
+ continue;
+ }
+ if (text[index] === '/' && text[index + 1] === '*') {
+ const end = text.indexOf('*/', index + 2);
+ if (end < 0) return '';
+ index = end + 2;
+ continue;
+ }
+ break;
+ }
+ const match = /^[A-Za-z]+/.exec(text.slice(index));
+ return match ? match[0].toUpperCase() : '';
+}
+
+function assertNoTransactionControl(sql) {
+ const keyword = leadingSqlKeyword(sql);
+ if (new Set(['BEGIN', 'COMMIT', 'END', 'ROLLBACK', 'SAVEPOINT', 'RELEASE']).has(keyword)) {
+ throw new Error(`sqlite 事务 item 不允许事务控制语句: ${keyword}`);
+ }
+}
+
+function assertSingleStatement(sql) {
+ if (typeof sql !== 'string') throw new TypeError('sqlite 事务 SQL 必须是字符串');
+ let state = 'plain';
+ let hasContent = false;
+ let hasTrailingSemicolon = false;
+ for (let i = 0; i < sql.length; i++) {
+ const ch = sql[i];
+ const next = sql[i + 1];
+ if (state === 'single') {
+ if (ch === "'" && next === "'") i++;
+ else if (ch === "'") state = 'plain';
+ continue;
+ }
+ if (state === 'double') {
+ if (ch === '"' && next === '"') i++;
+ else if (ch === '"') state = 'plain';
+ continue;
+ }
+ if (state === 'backtick') {
+ if (ch === '`' && next === '`') i++;
+ else if (ch === '`') state = 'plain';
+ continue;
+ }
+ if (state === 'bracket') {
+ if (ch === ']') state = 'plain';
+ continue;
+ }
+ if (state === 'line-comment') {
+ if (ch === '\n' || ch === '\r') state = 'plain';
+ continue;
+ }
+ if (state === 'block-comment') {
+ if (ch === '*' && next === '/') { state = 'plain'; i++; }
+ continue;
+ }
+ if (/\s/.test(ch)) continue;
+ if (ch === '-' && next === '-') { state = 'line-comment'; i++; continue; }
+ if (ch === '/' && next === '*') { state = 'block-comment'; i++; continue; }
+ if (ch === ';') {
+ if (hasTrailingSemicolon) throw new Error('sqlite 事务的每个 item 只能包含单条 SQL 语句');
+ hasTrailingSemicolon = true;
+ continue;
+ }
+ if (hasTrailingSemicolon) throw new Error('sqlite 事务的每个 item 只能包含单条 SQL 语句');
+ hasContent = true;
+ if (ch === "'") state = 'single';
+ else if (ch === '"') state = 'double';
+ else if (ch === '`') state = 'backtick';
+ else if (ch === '[') state = 'bracket';
+ }
+ if (state === 'single' || state === 'double' || state === 'backtick' || state === 'bracket' || state === 'block-comment') {
+ throw new Error('sqlite 事务 SQL 包含未闭合的引号、标识符或注释');
+ }
+ if (!hasContent) throw new Error('sqlite 事务的每个 item 必须包含单条 SQL 语句');
+ return { hasTrailingSemicolon };
+}
+
+function normalizeParameters(sql, params) {
+ assertNoSqliteMetaCommands(sql);
+ assertParameterCount(sql, params);
+ return params.map((value) => {
+ if (value === null) return value;
+ if (typeof value === 'string') {
+ if (value.includes('\0')) throw new TypeError('sqlite 文本参数不能包含 NUL 字符');
+ return value;
+ }
+ if (typeof value === 'bigint') {
+ if (value < JS_SAFE_INTEGER_MIN || value > JS_SAFE_INTEGER_MAX) {
+ throw new RangeError('sqlite bigint 参数必须在 JavaScript 安全整数范围内');
+ }
+ return value;
+ }
+ if (typeof value === 'boolean') return value ? 1 : 0;
+ if (typeof value === 'number' && Number.isFinite(value)) {
+ if (Number.isInteger(value) && !Number.isSafeInteger(value)) {
+ throw new RangeError('sqlite number 整数参数必须在 JavaScript 安全整数范围内');
+ }
+ return value;
+ }
+ throw new TypeError(`sqlite 不支持参数类型: ${value === undefined ? 'undefined' : typeof value}`);
+ });
+}
+
+function normalizeTransactionStatements(statements) {
+ if (!Array.isArray(statements) || !statements.length) throw new Error('sqlite 事务至少需要一条语句');
+ return statements.map((statement) => {
+ if (!statement || typeof statement.sql !== 'string') throw new TypeError('sqlite 事务语句无效');
+ const statementInfo = assertSingleStatement(statement.sql);
+ assertNoTransactionControl(statement.sql);
+ return {
+ sql: statement.sql,
+ params: normalizeParameters(statement.sql, statement.params || []),
+ hasTrailingSemicolon: statementInfo.hasTrailingSemicolon,
+ };
+ });
+}
+
+function normalizeSessionIdBatch(value) {
+ if (!Array.isArray(value)) throw new TypeError('会话 ID 批次必须是数组');
+ if (value.length > MAX_SESSION_ID_BATCH) {
+ throw new RangeError(`单次最多接收 ${MAX_SESSION_ID_BATCH} 个会话 ID`);
+ }
+ const ids = [];
+ const seen = new Set();
+ for (const item of value) {
+ if (typeof item !== 'string' || !item) throw new TypeError('会话 ID 必须是非空字符串');
+ if (item.length > MAX_SESSION_ID_LENGTH) {
+ throw new RangeError(`会话 ID 长度不能超过 ${MAX_SESSION_ID_LENGTH} 个字符`);
+ }
+ if (seen.has(item)) continue;
+ seen.add(item);
+ ids.push(item);
+ }
+ return ids;
+}
+
+function cliLiteral(value) {
+ if (value === null) return 'NULL';
+ if (typeof value === 'number') {
+ if (!Number.isFinite(value)) throw new TypeError('sqlite 数值参数必须是有限数值');
+ return String(value);
+ }
+ if (typeof value === 'bigint') return String(value);
+ if (typeof value !== 'string') throw new TypeError(`sqlite CLI 不支持参数类型: ${typeof value}`);
+ return `CAST(X'${Buffer.from(value, 'utf8').toString('hex')}' AS TEXT)`;
+}
+
+function bindCliSql(sql, params = []) {
+ const values = normalizeParameters(sql, params);
+ const text = String(sql || '');
+ let output = '';
+ let index = 0;
+ let state = 'plain';
+ for (let i = 0; i < text.length; i++) {
+ const ch = text[i];
+ const next = text[i + 1];
+ output += ch;
+ if (state === 'single') {
+ if (ch === "'" && next === "'") { output += next; i++; }
+ else if (ch === "'") state = 'plain';
+ continue;
+ }
+ if (state === 'double') {
+ if (ch === '"' && next === '"') { output += next; i++; }
+ else if (ch === '"') state = 'plain';
+ continue;
+ }
+ if (state === 'backtick') {
+ if (ch === '`' && next === '`') { output += next; i++; }
+ else if (ch === '`') state = 'plain';
+ continue;
+ }
+ if (state === 'bracket') {
+ if (ch === ']') state = 'plain';
+ continue;
+ }
+ if (state === 'line-comment') {
+ if (ch === '\n' || ch === '\r') state = 'plain';
+ continue;
+ }
+ if (state === 'block-comment') {
+ if (ch === '*' && next === '/') { output += next; i++; state = 'plain'; }
+ continue;
+ }
+ if (ch === "'") state = 'single';
+ else if (ch === '"') state = 'double';
+ else if (ch === '`') state = 'backtick';
+ else if (ch === '[') state = 'bracket';
+ else if (ch === '-' && next === '-') { output += next; i++; state = 'line-comment'; }
+ else if (ch === '/' && next === '*') { output += next; i++; state = 'block-comment'; }
+ else if (ch === '?') {
+ output = output.slice(0, -1) + cliLiteral(values[index++]);
+ }
+ }
+ return output;
+}
+
+function runCli(command, args, input) {
+ return new Promise((resolve, reject) => {
+ let child;
+ try {
+ child = spawn(command, args, { stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true });
+ } catch (error) {
+ reject(new Error(`sqlite3 CLI 不可用: ${error.message}`));
+ return;
+ }
+ let stdout = '';
+ let stderr = '';
+ let stdinError = null;
+ let settled = false;
+ const settle = (error, value) => {
+ if (settled) return;
+ settled = true;
+ if (error) reject(error);
+ else resolve(value);
+ };
+ child.stdout.setEncoding('utf8');
+ child.stderr.setEncoding('utf8');
+ child.stdout.on('data', (data) => { stdout += data; });
+ child.stderr.on('data', (data) => { stderr += data; });
+ child.once('error', (error) => {
+ settle(new Error(`sqlite3 CLI 不可用: ${error.message}`));
+ });
+ child.stdin.once('error', (error) => {
+ stdinError = error;
+ });
+ child.once('close', (code) => {
+ if (settled) return;
+ if (code !== 0) {
+ const detail = String(stderr || stdout).trim().slice(0, 500);
+ if (/(?:unknown|unrecognized|bad) option.*json|unknown command.*json/i.test(detail)) {
+ settle(new Error('sqlite3 CLI 不支持 -json,无法安全解析结构化结果'));
+ return;
+ }
+ settle(new Error(`sqlite3 CLI 执行失败(${code}): ${detail || (stdinError && stdinError.message) || '未知错误'}`));
+ return;
+ }
+ if (stdinError) {
+ settle(new Error(`sqlite3 CLI stdin 写入失败: ${stdinError.message}`));
+ return;
+ }
+ settle(null, stdout);
+ });
+ try {
+ child.stdin.end(String(input || ''), 'utf8');
+ } catch (error) {
+ try { child.kill(); } catch (_) {}
+ settle(new Error(`sqlite3 CLI stdin 写入失败: ${error.message}`));
+ }
+ });
+}
+
+function createSessionDb(options = {}) {
+ const dbPath = String(options.dbPath || '');
+ if (!dbPath) throw new Error('缺少 sqlite 数据库路径');
+ const sqliteModule = options.disableNodeSqlite
+ ? null
+ : (Object.prototype.hasOwnProperty.call(options, 'nodeSqlite') ? options.nodeSqlite : loadNodeSqlite());
+ const sqliteCommand = options.sqliteCommand || process.env.WORKDADDY_SQLITE3 || 'sqlite3';
+
+ if (sqliteModule && typeof sqliteModule.DatabaseSync === 'function') {
+ return {
+ backend: 'node:sqlite',
+ async all(sql, params = []) {
+ const values = normalizeParameters(sql, params);
+ let db;
+ try {
+ db = new sqliteModule.DatabaseSync(dbPath, { readOnly: true });
+ return db.prepare(sql).all(...values).map((row) => Object.fromEntries(Object.entries(row)));
+ } catch (error) {
+ throw new Error(`sqlite 查询失败: ${error.message}`);
+ } finally {
+ if (db) { try { db.close(); } catch (_) {} }
+ }
+ },
+ async run(sql, params = []) {
+ const values = normalizeParameters(sql, params);
+ let db;
+ try {
+ db = new sqliteModule.DatabaseSync(dbPath);
+ const result = db.prepare(sql).run(...values);
+ return { changes: Number(result.changes), lastInsertRowid: result.lastInsertRowid };
+ } catch (error) {
+ throw new Error(`sqlite 写入失败: ${error.message}`);
+ } finally {
+ if (db) { try { db.close(); } catch (_) {} }
+ }
+ },
+ async transaction(statements) {
+ const preparedStatements = normalizeTransactionStatements(statements);
+ let db;
+ try {
+ db = new sqliteModule.DatabaseSync(dbPath);
+ db.exec('BEGIN IMMEDIATE');
+ const results = preparedStatements.map((statement) => {
+ const result = db.prepare(statement.sql).run(...statement.params);
+ return { changes: Number(result.changes), lastInsertRowid: result.lastInsertRowid };
+ });
+ db.exec('COMMIT');
+ return results;
+ } catch (error) {
+ if (db) { try { db.exec('ROLLBACK'); } catch (_) {} }
+ throw new Error(`sqlite 事务失败: ${error.message}`);
+ } finally {
+ if (db) { try { db.close(); } catch (_) {} }
+ }
+ },
+ };
+ }
+
+ return {
+ backend: 'sqlite3-cli',
+ async all(sql, params = []) {
+ const compiled = bindCliSql(sql, params);
+ const stdout = await runCli(sqliteCommand, ['-readonly', '-json', dbPath], `${compiled}\n`);
+ if (!stdout.trim()) return [];
+ try {
+ const rows = JSON.parse(stdout);
+ if (!Array.isArray(rows)) throw new Error('结果不是数组');
+ return rows;
+ } catch (error) {
+ throw new Error(`sqlite3 CLI 不支持可靠的 -json 结构化输出: ${error.message}`);
+ }
+ },
+ async run(sql, params = []) {
+ const compiled = bindCliSql(sql, params);
+ await runCli(sqliteCommand, [dbPath], `${compiled}\n`);
+ return { changes: null, lastInsertRowid: null };
+ },
+ async transaction(statements) {
+ const preparedStatements = normalizeTransactionStatements(statements);
+ const sql = preparedStatements.map((statement) => {
+ const compiled = bindCliSql(statement.sql, statement.params);
+ return statement.hasTrailingSemicolon ? compiled : compiled + '\n;';
+ }).join('\n');
+ await runCli(sqliteCommand, ['-bail', dbPath], `BEGIN IMMEDIATE;\n${sql}\nCOMMIT;\n`);
+ return preparedStatements.map(() => ({ changes: null, lastInsertRowid: null }));
+ },
+ };
+}
+
+module.exports = {
+ bindCliSql,
+ createSessionDb,
+ normalizeSessionIdBatch,
+ parameterCount,
+};
diff --git a/scripts/verify-win.cmd b/scripts/verify-win.cmd
index 1f09898..1c0fc0a 100644
--- a/scripts/verify-win.cmd
+++ b/scripts/verify-win.cmd
@@ -18,7 +18,7 @@ set "FAIL=0"
rem ---- 1) 关键文件齐全 ----
echo.
echo [1/6] 检查关键文件...
-for %%F in (daemon.js lib.js watchdog.js win-launcher.js windows-process-boundary.js windows-process-boundary.ps1 inject.js theme-patches.js launcher.cmd launcher-hidden.vbs install-win.cmd install-win.ps1 uninstall-win.ps1 apply-update.ps1 win\setup.sed) do (
+for %%F in (daemon.js session-db.js lib.js watchdog.js win-launcher.js windows-process-boundary.js windows-process-boundary.ps1 inject.js theme-patches.js launcher.cmd launcher-hidden.vbs install-win.cmd install-win.ps1 uninstall-win.ps1 apply-update.ps1 win\setup.sed) do (
if not exist "%SCRIPT_DIR%%%F" (
echo 缺失: %%~F
set /a FAIL+=1
@@ -55,7 +55,7 @@ if errorlevel 1 (
rem ---- 3) 脚本语法静态检查(node --check,不执行)----
echo.
echo [3/6] 校验 JS 语法...
-for %%F in (daemon.js lib.js watchdog.js win-launcher.js windows-process-boundary.js inject.js theme-patches.js) do (
+for %%F in (daemon.js session-db.js lib.js watchdog.js win-launcher.js windows-process-boundary.js inject.js theme-patches.js) do (
"%NODE%" --check "%SCRIPT_DIR%%%F" >nul 2>&1
if errorlevel 1 (
echo 语法错误: %%~F
diff --git a/test/session-db.test.js b/test/session-db.test.js
new file mode 100644
index 0000000..d2cad1d
--- /dev/null
+++ b/test/session-db.test.js
@@ -0,0 +1,257 @@
+'use strict';
+
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const os = require('node:os');
+const path = require('node:path');
+const { spawnSync } = require('node:child_process');
+const test = require('node:test');
+
+const repoRoot = path.resolve(__dirname, '..');
+const {
+ bindCliSql,
+ createSessionDb,
+ normalizeSessionIdBatch,
+} = require('../scripts/session-db.js');
+
+function tempDb() {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'workdaddy-session-db-'));
+ return { dir, file: path.join(dir, 'sessions.db') };
+}
+
+function generatedTextCorpus() {
+ const alphabet = ['a', 'Z', '0', "'", '"', '`', '[', ']', '?', '-', '/', '*', '|', '\n', '\r', '\t', '雪', '🙂'];
+ const values = ['', "'", '??', '-- comment', '/* block */', '雪🙂tail'];
+ let state = 0x5eed1234;
+ const next = () => {
+ state = (Math.imul(state, 1664525) + 1013904223) >>> 0;
+ return state;
+ };
+ for (let sample = 0; sample < 128; sample++) {
+ const length = next() % 65;
+ let value = '';
+ for (let i = 0; i < length; i++) value += alphabet[next() % alphabet.length];
+ values.push(value);
+ }
+ return values;
+}
+
+async function exerciseRoundTrip(adapter) {
+ await adapter.run('CREATE TABLE sessions (id TEXT PRIMARY KEY, title TEXT NOT NULL, owner TEXT, enabled INTEGER)');
+ const title = "left|right\n'); DELETE FROM sessions; --";
+ await adapter.run('INSERT INTO sessions (id, title, owner, enabled) VALUES (?, ?, ?, ?)', ['session-1', title, null, true]);
+
+ const rows = await adapter.all('SELECT id, title, owner, enabled FROM sessions WHERE id = ?', ['session-1']);
+ assert.deepEqual(rows, [{ id: 'session-1', title, owner: null, enabled: 1 }]);
+ assert.equal((await adapter.all('SELECT COUNT(*) AS count FROM sessions'))[0].count, 1);
+
+ await assert.rejects(adapter.all('DELETE FROM sessions'), /sqlite|readonly|只读|write/i);
+ assert.equal((await adapter.all('SELECT COUNT(*) AS count FROM sessions'))[0].count, 1);
+ await assert.rejects(adapter.run('INSERT INTO sessions (id, title) VALUES (?, ?)', ['bad-undefined', undefined]), /参数类型|undefined/);
+ await assert.rejects(adapter.run('INSERT INTO sessions (id, title) VALUES (?, ?)', ['bad-nan', Number.NaN]), /参数类型|number/);
+ await assert.rejects(adapter.run('INSERT INTO sessions (id, title) VALUES (?, ?)', ['bad-bigint', 2n ** 100n]), /安全整数|safe integer/i);
+ await assert.rejects(adapter.run('INSERT INTO sessions (id, title) VALUES (?, ?)', ['bad-nul', 'left\0right']), /NUL/);
+
+ await assert.rejects(
+ adapter.all('SELECT id FROM sessions WHERE id = ? AND title = ?', ['session-1']),
+ /参数数量不匹配/
+ );
+
+ const corpus = generatedTextCorpus();
+ await adapter.run('CREATE TABLE text_corpus (id TEXT PRIMARY KEY, value TEXT NOT NULL)');
+ await adapter.transaction(corpus.map((value, index) => ({
+ sql: 'INSERT INTO text_corpus (id, value) VALUES (?, ?)',
+ params: [`sample-${String(index).padStart(3, '0')}`, value],
+ })));
+ assert.deepEqual(
+ await adapter.all('SELECT id, value FROM text_corpus ORDER BY id'),
+ corpus.map((value, index) => ({ id: `sample-${String(index).padStart(3, '0')}`, value }))
+ );
+}
+
+async function exerciseRollback(adapter) {
+ await adapter.run('CREATE TABLE tx_items (id TEXT PRIMARY KEY, value TEXT NOT NULL)');
+ await assert.rejects(
+ adapter.transaction([
+ { sql: 'INSERT INTO tx_items (id, value) VALUES (?, ?)', params: ['same-id', 'first'] },
+ { sql: 'INSERT INTO tx_items (id, value) VALUES (?, ?)', params: ['same-id', 'second'] },
+ ]),
+ /sqlite/i
+ );
+ assert.deepEqual(await adapter.all('SELECT id, value FROM tx_items'), []);
+}
+
+async function exerciseSingleStatementTransaction(adapter) {
+ await adapter.run('CREATE TABLE tx_escape (id TEXT PRIMARY KEY, value TEXT NOT NULL)');
+ await adapter.transaction([
+ { sql: "INSERT INTO tx_escape (id, value) VALUES (?, 'quoted;value'); /* trailing; comment */", params: ['allowed'] },
+ { sql: 'INSERT INTO tx_escape (id, value) VALUES (?, ?) -- line; comment\n', params: ['allowed-line', 'line'] },
+ { sql: 'INSERT INTO tx_escape (id, value) VALUES (?, ?) -- trailing comment without newline', params: ['allowed-line-eof', 'line-eof'] },
+ { sql: "INSERT INTO tx_escape (id, value) VALUES (?, 'line one\n.print is literal')", params: ['allowed-dot-literal'] },
+ ]);
+ assert.deepEqual(await adapter.all('SELECT id, value FROM tx_escape ORDER BY id'), [
+ { id: 'allowed', value: 'quoted;value' },
+ { id: 'allowed-dot-literal', value: 'line one\n.print is literal' },
+ { id: 'allowed-line', value: 'line' },
+ { id: 'allowed-line-eof', value: 'line-eof' },
+ ]);
+ await adapter.run('DELETE FROM tx_escape');
+
+ await assert.rejects(
+ adapter.transaction([
+ { sql: 'INSERT INTO tx_escape (id, value) VALUES (?, ?); COMMIT; -- escape rollback', params: ['escaped', 'first'] },
+ { sql: 'INSERT INTO tx_escape (id, value) VALUES (?, ?)', params: ['escaped', 'duplicate'] },
+ ]),
+ /单条|single statement/i
+ );
+ assert.deepEqual(await adapter.all('SELECT id, value FROM tx_escape'), []);
+
+ await assert.rejects(
+ adapter.transaction([
+ { sql: 'INSERT INTO tx_escape (id, value) VALUES (?, ?)', params: ['before-commit', 'first'] },
+ { sql: ' /* leading comment */ CoMmIt ; -- transaction escape' },
+ { sql: 'INSERT INTO missing_table (id) VALUES (?)', params: ['boom'] },
+ ]),
+ /事务控制|transaction control/i
+ );
+ assert.deepEqual(await adapter.all('SELECT id, value FROM tx_escape'), []);
+
+ await assert.rejects(
+ adapter.transaction([
+ { sql: 'INSERT INTO tx_escape (id, value) VALUES (?, ?)', params: ['before-rollback', 'first'] },
+ { sql: '\n-- leading comment\nRoLlBaCk;' },
+ { sql: 'INSERT INTO tx_escape (id, value) VALUES (?, ?)', params: ['after-rollback', 'autocommit'] },
+ ]),
+ /事务控制|transaction control/i
+ );
+ assert.deepEqual(await adapter.all('SELECT id, value FROM tx_escape'), []);
+
+ await assert.rejects(
+ adapter.transaction([{ sql: '.print sqlite-cli-meta-command-must-not-run' }]),
+ /meta|点命令|dot command/i
+ );
+ await assert.rejects(adapter.run('.print sqlite-cli-meta-command-must-not-run'), /meta|点命令|dot command/i);
+ await assert.rejects(adapter.all('.print sqlite-cli-meta-command-must-not-run'), /meta|点命令|dot command/i);
+ await assert.rejects(adapter.run('\ufeff .print sqlite-cli-meta-command-must-not-run'), /meta|点命令|dot command/i);
+}
+
+async function exerciseNumericBoundaries(adapter) {
+ await adapter.run('CREATE TABLE numeric_values (id TEXT PRIMARY KEY, value)');
+ await adapter.transaction([
+ { sql: 'INSERT INTO numeric_values (id, value) VALUES (?, ?)', params: ['max-number', Number.MAX_SAFE_INTEGER] },
+ { sql: 'INSERT INTO numeric_values (id, value) VALUES (?, ?)', params: ['min-bigint', BigInt(Number.MIN_SAFE_INTEGER)] },
+ { sql: 'INSERT INTO numeric_values (id, value) VALUES (?, ?)', params: ['float', 1.25] },
+ { sql: 'INSERT INTO numeric_values (id, value) VALUES (?, ?)', params: ['null', null] },
+ { sql: 'INSERT INTO numeric_values (id, value) VALUES (?, ?)', params: ['text', '42'] },
+ { sql: 'INSERT INTO numeric_values (id, value) VALUES (?, ?)', params: ['bool', true] },
+ ]);
+ assert.deepEqual(await adapter.all('SELECT id, value FROM numeric_values ORDER BY id'), [
+ { id: 'bool', value: 1 },
+ { id: 'float', value: 1.25 },
+ { id: 'max-number', value: Number.MAX_SAFE_INTEGER },
+ { id: 'min-bigint', value: Number.MIN_SAFE_INTEGER },
+ { id: 'null', value: null },
+ { id: 'text', value: '42' },
+ ]);
+ for (const value of [
+ Number.MAX_SAFE_INTEGER + 1,
+ Number.MIN_SAFE_INTEGER - 1,
+ BigInt(Number.MAX_SAFE_INTEGER) + 1n,
+ BigInt(Number.MIN_SAFE_INTEGER) - 1n,
+ ]) {
+ await assert.rejects(
+ adapter.run('INSERT INTO numeric_values (id, value) VALUES (?, ?)', [`unsafe-${String(value)}`, value]),
+ /安全整数|safe integer/i
+ );
+ }
+}
+
+test('node:sqlite adapter preserves structured values and rolls back a failed transaction', async () => {
+ const tmp = tempDb();
+ try {
+ const adapter = createSessionDb({ dbPath: tmp.file });
+ assert.equal(adapter.backend, 'node:sqlite');
+ await exerciseRoundTrip(adapter);
+ await exerciseRollback(adapter);
+ await exerciseSingleStatementTransaction(adapter);
+ await exerciseNumericBoundaries(adapter);
+ } finally {
+ fs.rmSync(tmp.dir, { recursive: true, force: true });
+ }
+});
+
+test('sqlite3 CLI fallback preserves structured values and rolls back a failed transaction', async (t) => {
+ const sqliteCommand = process.env.WORKDADDY_SQLITE3 || 'sqlite3';
+ const probe = spawnSync(sqliteCommand, ['--version'], { encoding: 'utf8', windowsHide: true });
+ if (probe.error || probe.status !== 0) {
+ if (process.env.WORKDADDY_SQLITE3) {
+ assert.fail(`WORKDADDY_SQLITE3 is unavailable: ${probe.error ? probe.error.message : probe.stderr}`);
+ }
+ t.skip('sqlite3 CLI not found on PATH');
+ return;
+ }
+
+ const tmp = tempDb();
+ try {
+ const adapter = createSessionDb({ dbPath: tmp.file, disableNodeSqlite: true, sqliteCommand });
+ assert.equal(adapter.backend, 'sqlite3-cli');
+ await exerciseRoundTrip(adapter);
+ await exerciseRollback(adapter);
+ await exerciseSingleStatementTransaction(adapter);
+ await exerciseNumericBoundaries(adapter);
+
+ const longText = "雪|'\n".repeat(12000);
+ assert.ok(bindCliSql('INSERT INTO long_values (id, value) VALUES (?, ?)', ['long-1', longText]).length > 32767);
+ await adapter.run('CREATE TABLE long_values (id TEXT PRIMARY KEY, value TEXT NOT NULL)');
+ await adapter.run('INSERT INTO long_values (id, value) VALUES (?, ?)', ['long-1', longText]);
+ assert.deepEqual(await adapter.all('SELECT value FROM long_values WHERE id = ?', ['long-1']), [{ value: longText }]);
+ } finally {
+ fs.rmSync(tmp.dir, { recursive: true, force: true });
+ }
+});
+
+test('CLI fallback encodes text as UTF-8 hex and fails clearly without -json support', async () => {
+ const compiled = bindCliSql("SELECT ?, ?, ?, '?' /* ? */", ['雪|\nquote\'', 42, null]);
+ assert.match(compiled, /CAST\(X'[0-9a-f]+' AS TEXT\)/i);
+ assert.doesNotMatch(compiled, /雪|quote/);
+ assert.match(compiled, /SELECT CAST\(X'/);
+ assert.match(compiled, /, 42, NULL, '\?' \/\* \? \*\//);
+
+ const adapter = createSessionDb({
+ dbPath: path.join(os.tmpdir(), 'unused-workdaddy-session.db'),
+ disableNodeSqlite: true,
+ sqliteCommand: process.execPath,
+ });
+ await assert.rejects(adapter.all('SELECT 1'), /不支持 -json/);
+});
+
+test('session ID batches validate raw input, cap work, and deduplicate in order', () => {
+ assert.deepEqual(normalizeSessionIdBatch(['a', 'a', 'b', 'a', 'c']), ['a', 'b', 'c']);
+ assert.throws(() => normalizeSessionIdBatch(null), /数组/);
+ assert.throws(() => normalizeSessionIdBatch(['valid', 7]), /非空字符串/);
+ assert.throws(() => normalizeSessionIdBatch(['']), /非空字符串/);
+ assert.throws(() => normalizeSessionIdBatch(['x'.repeat(201)]), /200|过长/);
+ assert.throws(() => normalizeSessionIdBatch(Array(500).fill('same')), /100|上限|过多/);
+ assert.throws(
+ () => normalizeSessionIdBatch(Array.from({ length: 101 }, (_, index) => `session-${index}`)),
+ /100|上限|过多/
+ );
+});
+
+test('daemon session SQL uses bound parameters without delimiter serialization', () => {
+ const daemon = fs.readFileSync(path.join(repoRoot, 'scripts', 'daemon.js'), 'utf8');
+ const verifyWin = fs.readFileSync(path.join(repoRoot, 'scripts', 'verify-win.cmd'), 'utf8');
+ const macBuild = fs.readFileSync(path.join(repoRoot, 'scripts', 'build-mac-dmg.sh'), 'utf8');
+ assert.doesNotMatch(daemon, /Object\.values\([^\n]+join\(['"]\|['"]\)/);
+ assert.doesNotMatch(daemon, /function sqlQuote\(/);
+ assert.doesNotMatch(daemon, /id IN \(['"]?\s*\+\s*esc/);
+ assert.match(daemon, /createSessionDb/);
+ assert.equal((daemon.match(/normalizeSessionIdBatch\(body\s*&&\s*body\.ids\)/g) || []).length, 4);
+ assert.ok((daemon.match(/catch \(e\) \{ return json\(res, 400, \{ ok: false, error: e\.message \}\); \}/g) || []).length >= 4);
+ assert.doesNotMatch(daemon, /body\.ids\.filter\(/);
+ assert.match(daemon, /sqliteQuery\([^,]+,\s*\[[^\]]/s);
+ assert.match(verifyWin, /daemon\.js session-db\.js lib\.js/);
+ const copyList = (macBuild.match(/for f in ([^;]+); do/) || [])[1] || '';
+ assert.match(copyList, /(?:^|\s)session-db\.js(?:\s|$)/);
+ assert.match(macBuild, /chmod 644[\s\S]*session-db\.js/);
+});
diff --git a/test/session-delete-confinement.test.js b/test/session-delete-confinement.test.js
index db4a254..04bd803 100644
--- a/test/session-delete-confinement.test.js
+++ b/test/session-delete-confinement.test.js
@@ -169,11 +169,14 @@ test('delete route validates before SQL and deletes the matched set only', () =>
const routeStart = source.indexOf("p === '/api/sessions/delete'");
const routeEnd = source.indexOf("p === '/api/sessions/restore'", routeStart);
const route = source.slice(routeStart, routeEnd);
+ const normalizeAt = route.indexOf('normalizeSessionIdBatch');
const validateAt = route.indexOf('isValidSessionId');
const selectAt = route.indexOf("SELECT id, user_id FROM sessions");
- assert.ok(validateAt >= 0 && validateAt < selectAt, 'all IDs must be validated before SELECT or DELETE');
+ assert.ok(normalizeAt >= 0 && normalizeAt < validateAt, 'the raw batch must be bounded before path validation');
+ assert.ok(validateAt < selectAt, 'all IDs must be validated before SELECT or DELETE');
+ assert.match(route, /SELECT id, user_id FROM sessions WHERE id IN \(' \+ placeholders \+ '\);', ids/);
assert.match(route, /const matchedIds = matchedSessionIds\(ids, before\)/);
- assert.match(route, /DELETE FROM sessions WHERE id IN \(" \+ matchedEsc \+ "\)/);
+ assert.match(route, /DELETE FROM sessions WHERE id IN \(" \+ sqlPlaceholders\(matchedIds\) \+ "\);",\s+matchedIds/s);
assert.match(route, /for \(const id of matchedIds\) filesRemoved \+= deleteSessionFiles\(wbHome, id\)/);
assert.doesNotMatch(route, /for \(const id of ids\) filesRemoved/);
const filesAt = route.indexOf('for (const id of matchedIds) filesRemoved += deleteSessionFiles');