dsh-config-manager 0.8.1 → 0.9.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/lib/adapters/mcp.js +42 -13
- package/lib/adapters/messages.d.ts +1 -0
- package/lib/adapters/messages.js +2 -0
- package/lib/adapters/patch-key-guard.d.ts +23 -0
- package/lib/adapters/patch-key-guard.js +13 -0
- package/lib/adapters/plugin-data.d.ts +19 -5
- package/lib/adapters/plugin-data.js +76 -22
- package/lib/adapters/plugins.d.ts +14 -1
- package/lib/adapters/plugins.js +147 -4
- package/lib/cli/actions.d.ts +7 -105
- package/lib/cli/actions.js +16 -172
- package/lib/cli/control-state.d.ts +54 -0
- package/lib/cli/control-state.js +107 -0
- package/lib/cli/index.js +14 -0
- package/lib/cli/write-gates.d.ts +61 -0
- package/lib/cli/write-gates.js +110 -0
- package/lib/client.d.ts +122 -50
- package/lib/client.js +12676 -12091
- package/lib/core/backup.d.ts +0 -4
- package/lib/core/backup.js +21 -4
- package/lib/core/boot-rescue.d.ts +1 -1
- package/lib/core/boot-rescue.js +12 -1
- package/lib/core/boot-safety.js +37 -2
- package/lib/core/conflict-decisions.js +2 -1
- package/lib/core/exporter.js +22 -1
- package/lib/core/journal.d.ts +54 -4
- package/lib/core/journal.js +158 -35
- package/lib/core/local-plugin-host.d.ts +29 -0
- package/lib/core/local-plugin-host.js +55 -48
- package/lib/core/messages.d.ts +7 -0
- package/lib/core/messages.js +14 -0
- package/lib/core/migration-history.js +16 -9
- package/lib/core/model-tools.d.ts +2 -2
- package/lib/core/model-tools.js +14 -2
- package/lib/core/patch-secret-guard.d.ts +49 -0
- package/lib/core/patch-secret-guard.js +164 -0
- package/lib/core/reconcile.d.ts +8 -0
- package/lib/core/reconcile.js +18 -3
- package/lib/core/reinstall.d.ts +2 -0
- package/lib/core/reinstall.js +6 -2
- package/lib/core/restore.js +31 -6
- package/lib/core/section-sanitize.d.ts +32 -0
- package/lib/core/section-sanitize.js +13 -0
- package/lib/core/snapshot-diff.d.ts +30 -0
- package/lib/core/snapshot-diff.js +56 -20
- package/lib/core/startup-barrier.js +8 -2
- package/lib/core/types.d.ts +22 -0
- package/lib/core/update-check.js +51 -2
- package/lib/foreign/kernel.js +9 -2
- package/lib/foreign/read-claude-plugins.js +29 -11
- package/lib/foreign/read-dsh.js +31 -2
- package/lib/foreign/read-trae.d.ts +11 -0
- package/lib/foreign/read-trae.js +124 -4
- package/lib/foreign/session-ir.js +50 -9
- package/lib/foreign/session-read.d.ts +8 -0
- package/lib/foreign/session-read.js +26 -0
- package/lib/foreign/session-source.d.ts +12 -4
- package/lib/foreign/session-source.js +5 -3
- package/lib/foreign/trae-sqlcipher.d.ts +127 -0
- package/lib/foreign/trae-sqlcipher.js +519 -0
- package/lib/foreign/trae.js +3 -1
- package/lib/foreign/truth-table.js +3 -2
- package/lib/foreign/types.d.ts +9 -1
- package/lib/index.d.ts +1 -1
- package/lib/index.js +1 -1
- package/lib/profiles/dsh-profile-io.d.ts +20 -0
- package/lib/profiles/dsh-profile-io.js +27 -0
- package/lib/profiles/dsh-profile-manager.d.ts +27 -0
- package/lib/profiles/dsh-profile-manager.js +45 -4
- package/lib/profiles/dsh-profile-runtime.d.ts +5 -1
- package/lib/profiles/dsh-profile-runtime.js +16 -3
- package/lib/profiles/process-control.d.ts +18 -1
- package/lib/profiles/process-control.js +25 -1
- package/lib/routes/profiles.js +2 -1
- package/lib/routes/sync.js +13 -1
- package/lib/schema/types.d.ts +11 -0
- package/lib/security/redaction.js +22 -6
- package/lib/sync/autosync-repeat.d.ts +27 -0
- package/lib/sync/autosync-repeat.js +23 -0
- package/lib/sync/autosync-scheduler.d.ts +34 -1
- package/lib/sync/autosync-scheduler.js +151 -43
- package/lib/sync/baseline-heal.js +7 -0
- package/lib/sync/baseline-record.d.ts +67 -0
- package/lib/sync/baseline-record.js +74 -0
- package/lib/sync/blob-store.js +13 -0
- package/lib/sync/content-diff.d.ts +39 -0
- package/lib/sync/content-diff.js +46 -0
- package/lib/sync/git/git-transport.d.ts +32 -1
- package/lib/sync/git/git-transport.js +146 -26
- package/lib/sync/github-auth.d.ts +17 -1
- package/lib/sync/github-auth.js +37 -1
- package/lib/sync/merge-apply-plan.d.ts +38 -0
- package/lib/sync/merge-apply-plan.js +76 -0
- package/lib/sync/messages.d.ts +1 -0
- package/lib/sync/messages.js +2 -0
- package/lib/sync/pending-merge.d.ts +34 -0
- package/lib/sync/pending-merge.js +53 -0
- package/lib/sync/s3/s3-transport.d.ts +14 -2
- package/lib/sync/s3/s3-transport.js +72 -48
- package/lib/sync/sync-engine.d.ts +23 -40
- package/lib/sync/sync-engine.js +115 -132
- package/lib/sync/sync-history.d.ts +7 -0
- package/lib/sync/sync-state.d.ts +28 -0
- package/lib/sync/sync-state.js +20 -0
- package/lib/sync/transport.d.ts +12 -3
- package/lib/sync/transport.js +13 -4
- package/lib/sync/webdav/webdav-transport.d.ts +19 -2
- package/lib/sync/webdav/webdav-transport.js +81 -40
- package/lib/ui/commands.js +5 -11
- package/lib/ui/dsh-profiles-view.d.ts +8 -3
- package/lib/ui/dsh-profiles-view.js +9 -5
- package/lib/ui/foreign-view.d.ts +19 -0
- package/lib/ui/foreign-view.js +24 -0
- package/lib/ui/i18n.d.ts +7 -1
- package/lib/ui/i18n.js +17 -2
- package/lib/ui/menu-placement.js +1 -1
- package/lib/ui/migration-consult-view.d.ts +11 -0
- package/lib/ui/migration-consult-view.js +15 -0
- package/lib/ui/overview-view.d.ts +7 -0
- package/lib/ui/overview-view.js +3 -0
- package/lib/ui/report.d.ts +9 -0
- package/lib/ui/report.js +17 -4
- package/lib/ui/selection-model.d.ts +8 -0
- package/lib/ui/selection-model.js +16 -0
- package/lib/utils/patch-yaml.d.ts +39 -1
- package/lib/utils/patch-yaml.js +82 -2
- package/lib/utils/paths.d.ts +13 -0
- package/lib/utils/paths.js +35 -0
- package/lib/utils/workdir-lock.js +18 -3
- package/package.json +2 -1
- package/src/adapters/mcp.test.ts +29 -0
- package/src/adapters/mcp.ts +43 -12
- package/src/adapters/messages.ts +2 -0
- package/src/adapters/patch-key-guard.ts +29 -0
- package/src/adapters/plugin-data.test.ts +126 -0
- package/src/adapters/plugin-data.ts +97 -26
- package/src/adapters/plugins.test.ts +288 -0
- package/src/adapters/plugins.ts +141 -4
- package/src/cli/actions.test.ts +74 -1
- package/src/cli/actions.ts +27 -246
- package/src/cli/control-state.ts +143 -0
- package/src/cli/index.ts +18 -0
- package/src/cli/web/web.test.ts +27 -0
- package/src/cli/write-gates.ts +149 -0
- package/src/client/about/AboutPanel.tsx +7 -6
- package/src/client/about/release-notes-view.test.ts +17 -0
- package/src/client/about/release-notes-view.ts +49 -24
- package/src/client/chat/ChatEntryView.tsx +2 -2
- package/src/client/chat/rollback-entry-view.ts +6 -1
- package/src/client/common/CommandPalette.tsx +6 -3
- package/src/client/common/ConfirmDialog.tsx +29 -12
- package/src/client/common/ContentPicker.tsx +13 -12
- package/src/client/common/Modal.tsx +12 -5
- package/src/client/common/MoreMenu.tsx +4 -1
- package/src/client/common/RunsCenter.tsx +103 -32
- package/src/client/common/Select.tsx +2 -2
- package/src/client/common/floating-bounds.ts +1 -1
- package/src/client/common/floating-units.test.ts +1 -2
- package/src/client/common/plan-text-redaction.test.ts +188 -3
- package/src/client/common/runs-center-guard.test.ts +60 -0
- package/src/client/common/runs-center-view.test.ts +128 -0
- package/src/client/common/runs-center-view.ts +96 -0
- package/src/client/common/section-title-action.test.ts +66 -0
- package/src/client/common/ui.tsx +93 -30
- package/src/client/config-manager.module.css +1507 -272
- package/src/client/consult/ConsultCard.tsx +7 -6
- package/src/client/environment/EnvironmentPanel.tsx +20 -21
- package/src/client/environment/maintenance/DiskUsageCard.tsx +65 -91
- package/src/client/environment/profiles-incomplete-ui.test.ts +8 -8
- package/src/client/export/ExportView.tsx +7 -16
- package/src/client/history/HistoryPanel.tsx +88 -28
- package/src/client/history/history-locales.ts +3 -3
- package/src/client/home/BackupScheduleCard.tsx +35 -30
- package/src/client/home/HomePanel.tsx +45 -10
- package/src/client/import/ConflictList.tsx +13 -13
- package/src/client/import/ForeignImportView.tsx +32 -13
- package/src/client/import/ImportWizardView.tsx +2 -3
- package/src/client/import/PathMappingForm.tsx +4 -4
- package/src/client/import/PathPickerDialog.tsx +2 -1
- package/src/client/import/foreign-import-view-guard.test.ts +1 -1
- package/src/client/import/import-wizard-steps.tsx +51 -39
- package/src/client/import/use-import-wizard-controller.test.ts +129 -0
- package/src/client/import/use-import-wizard-controller.ts +116 -22
- package/src/client/library/ArtifactRow.tsx +2 -2
- package/src/client/library/BackupInspectView.tsx +19 -15
- package/src/client/library/LibraryActions.tsx +56 -16
- package/src/client/library/LibraryPanel.tsx +7 -7
- package/src/client/library/RestorePlanView.tsx +13 -8
- package/src/client/locales/about.ts +0 -2
- package/src/client/locales/backup.ts +10 -12
- package/src/client/locales/common.ts +2 -0
- package/src/client/locales/export.ts +5 -12
- package/src/client/locales/foreign.ts +11 -2
- package/src/client/locales/import.ts +3 -2
- package/src/client/locales/overview.ts +4 -0
- package/src/client/locales/profiles.ts +32 -4
- package/src/client/locales/restore.ts +0 -2
- package/src/client/locales/sessions.ts +0 -2
- package/src/client/locales/shell.ts +2 -2
- package/src/client/market/MarketPanel.tsx +38 -20
- package/src/client/market/MyConfigsList.tsx +34 -32
- package/src/client/market/MyConfigsLoginCard.tsx +12 -15
- package/src/client/market/MyConfigsView.tsx +5 -5
- package/src/client/market/MyConfigsWizard.tsx +7 -12
- package/src/client/market/market-locales.ts +0 -6
- package/src/client/market/my-configs-split.test.ts +2 -1
- package/src/client/nav-menu-clip-guard.test.ts +52 -0
- package/src/client/recovery/IncompleteCopiesSection.tsx +1 -3
- package/src/client/recovery/RecoveryPanel.tsx +31 -16
- package/src/client/recovery/RollbackCard.tsx +58 -16
- package/src/client/recovery/RollbackFileChanges.tsx +40 -27
- package/src/client/recovery/SessionHealthCard.tsx +2 -2
- package/src/client/recovery/SessionHealthDialog.tsx +5 -7
- package/src/client/recovery/SessionLayoutSection.tsx +3 -5
- package/src/client/recovery/recovery-locales.ts +12 -8
- package/src/client/run-store.test.ts +30 -0
- package/src/client/run-store.ts +21 -1
- package/src/client/sync/AddChannelCard.tsx +65 -0
- package/src/client/sync/AutosyncCard.tsx +182 -108
- package/src/client/sync/ChannelClearConfirmDialog.tsx +5 -1
- package/src/client/sync/ChannelConfigDialog.tsx +27 -48
- package/src/client/sync/MergePreviewView.tsx +3 -5
- package/src/client/sync/PushReportSections.tsx +35 -0
- package/src/client/sync/SyncChannelEntryCard.tsx +33 -24
- package/src/client/sync/SyncConfirmView.tsx +3 -3
- package/src/client/sync/SyncLogList.tsx +16 -5
- package/src/client/sync/SyncPanel.tsx +153 -159
- package/src/client/sync/SyncProbeRow.tsx +5 -7
- package/src/client/sync/SyncRepositoryPicker.tsx +17 -4
- package/src/client/sync/SyncSecuritySection.tsx +157 -0
- package/src/client/sync/SyncSettingsDialog.tsx +304 -0
- package/src/client/sync/SyncSettingsView.test.ts +26 -8
- package/src/client/sync/WorkDirCard.tsx +2 -4
- package/src/client/sync/config-clear-guard.test.ts +94 -0
- package/src/client/sync/config-clear-guard.ts +98 -0
- package/src/client/sync/config-dirty.test.ts +91 -0
- package/src/client/sync/config-dirty.ts +88 -0
- package/src/client/sync/history-model.test.ts +2 -0
- package/src/client/sync/history-model.ts +3 -0
- package/src/client/sync/merge-request.ts +20 -0
- package/src/client/sync/sync-api.ts +12 -0
- package/src/client/sync/sync-locales.ts +87 -47
- package/src/client/sync/sync-panel-clear.test.ts +44 -0
- package/src/client/sync/sync-view.test.ts +20 -0
- package/src/client/sync/sync-view.ts +42 -4
- package/src/core/backup.test.ts +61 -1
- package/src/core/backup.ts +21 -4
- package/src/core/boot-rescue.test.ts +35 -0
- package/src/core/boot-rescue.ts +13 -2
- package/src/core/boot-safety.test.ts +25 -0
- package/src/core/boot-safety.ts +37 -2
- package/src/core/conflict-decisions.ts +2 -1
- package/src/core/exporter.ts +21 -1
- package/src/core/journal.test.ts +183 -0
- package/src/core/journal.ts +163 -25
- package/src/core/local-plugin-host.test.ts +68 -2
- package/src/core/local-plugin-host.ts +31 -4
- package/src/core/messages.ts +14 -0
- package/src/core/migration-history.test.ts +27 -0
- package/src/core/migration-history.ts +12 -4
- package/src/core/model-tools.test.ts +67 -0
- package/src/core/model-tools.ts +16 -4
- package/src/core/patch-secret-guard.test.ts +110 -0
- package/src/core/patch-secret-guard.ts +176 -0
- package/src/core/reconcile.ts +32 -4
- package/src/core/reinstall.ts +8 -2
- package/src/core/restore.ts +32 -7
- package/src/core/section-sanitize.ts +37 -0
- package/src/core/snapshot-diff.test.ts +73 -1
- package/src/core/snapshot-diff.ts +66 -21
- package/src/core/startup-barrier.test.ts +64 -0
- package/src/core/startup-barrier.ts +8 -2
- package/src/core/types.ts +27 -1
- package/src/core/update-check.test.ts +40 -0
- package/src/core/update-check.ts +53 -2
- package/src/foreign/claude-code.test.ts +5 -0
- package/src/foreign/claude-plugins.test.ts +57 -0
- package/src/foreign/claude-sessions-bytes.test.ts +7 -1
- package/src/foreign/dsh.test.ts +23 -0
- package/src/foreign/file-budget.test.ts +7 -1
- package/src/foreign/kernel.ts +9 -2
- package/src/foreign/read-claude-plugins.ts +32 -11
- package/src/foreign/read-dsh.ts +33 -2
- package/src/foreign/read-trae.ts +117 -5
- package/src/foreign/session-ir.test.ts +67 -0
- package/src/foreign/session-ir.ts +54 -14
- package/src/foreign/session-read.ts +23 -0
- package/src/foreign/session-source.ts +15 -5
- package/src/foreign/trae-sqlcipher.test.ts +360 -0
- package/src/foreign/trae-sqlcipher.ts +564 -0
- package/src/foreign/trae.test.ts +188 -0
- package/src/foreign/trae.ts +3 -1
- package/src/foreign/truth-table.ts +4 -2
- package/src/foreign/types.ts +10 -1
- package/src/index.ts +1 -1
- package/src/profiles/dsh-profile-copy-rollback.test.ts +58 -4
- package/src/profiles/dsh-profile-io.ts +29 -0
- package/src/profiles/dsh-profile-manager.test.ts +30 -0
- package/src/profiles/dsh-profile-manager.ts +53 -5
- package/src/profiles/dsh-profile-runtime.test.ts +29 -7
- package/src/profiles/dsh-profile-runtime.ts +17 -3
- package/src/profiles/process-control.test.ts +97 -0
- package/src/profiles/process-control.ts +28 -1
- package/src/routes/profiles.ts +2 -1
- package/src/routes/sync.ts +13 -1
- package/src/schema/types.ts +16 -1
- package/src/security/redaction.test.ts +31 -0
- package/src/security/redaction.ts +23 -6
- package/src/sync/autosync-repeat.test.ts +58 -0
- package/src/sync/autosync-repeat.ts +55 -0
- package/src/sync/autosync-scheduler.test.ts +417 -0
- package/src/sync/autosync-scheduler.ts +154 -41
- package/src/sync/baseline-heal.ts +6 -0
- package/src/sync/baseline-record.ts +135 -0
- package/src/sync/blob-store.test.ts +16 -0
- package/src/sync/blob-store.ts +13 -0
- package/src/sync/content-diff.test.ts +95 -0
- package/src/sync/content-diff.ts +79 -0
- package/src/sync/git/git-transport.test.ts +151 -4
- package/src/sync/git/git-transport.ts +143 -27
- package/src/sync/github-auth.test.ts +26 -1
- package/src/sync/github-auth.ts +37 -1
- package/src/sync/merge-apply-plan.ts +117 -0
- package/src/sync/messages.ts +2 -0
- package/src/sync/pending-merge.ts +77 -0
- package/src/sync/s3/s3-delete-and-blob-index.test.ts +249 -0
- package/src/sync/s3/s3-transport.ts +76 -42
- package/src/sync/sync-config.test.ts +39 -12
- package/src/sync/sync-device-identity.test.ts +3 -0
- package/src/sync/sync-engine.test.ts +465 -12
- package/src/sync/sync-engine.ts +130 -135
- package/src/sync/sync-history.ts +7 -0
- package/src/sync/sync-state.ts +48 -0
- package/src/sync/transport.test.ts +13 -1
- package/src/sync/transport.ts +12 -4
- package/src/sync/webdav/webdav-delete-and-blob-index.test.ts +249 -0
- package/src/sync/webdav/webdav-transport.ts +86 -34
- package/src/ui/commands.test.ts +11 -0
- package/src/ui/commands.ts +5 -14
- package/src/ui/dsh-profiles-view.test.ts +16 -0
- package/src/ui/dsh-profiles-view.ts +11 -5
- package/src/ui/foreign-view.test.ts +36 -0
- package/src/ui/foreign-view.ts +46 -0
- package/src/ui/i18n.ts +17 -2
- package/src/ui/menu-placement.ts +1 -1
- package/src/ui/migration-consult-view.test.ts +20 -1
- package/src/ui/migration-consult-view.ts +17 -0
- package/src/ui/overview-view.ts +10 -0
- package/src/ui/report.test.ts +25 -1
- package/src/ui/report.ts +15 -4
- package/src/ui/selection-model.test.ts +15 -1
- package/src/ui/selection-model.ts +18 -0
- package/src/utils/js-yaml4.d.ts +35 -0
- package/src/utils/patch-yaml.test.ts +207 -1
- package/src/utils/patch-yaml.ts +98 -2
- package/src/utils/paths.test.ts +14 -1
- package/src/utils/paths.ts +35 -0
- package/src/utils/workdir-lock.test.ts +69 -0
- package/src/utils/workdir-lock.ts +17 -3
- package/lib/ui/path-mapping.d.ts +0 -38
- package/lib/ui/path-mapping.js +0 -75
- package/src/client/common/InfoHint.tsx +0 -289
- package/src/client/common/info-hint-guard.test.ts +0 -1119
- package/src/client/sync/DecryptPasswordCard.tsx +0 -48
- package/src/client/sync/SecurityOptionsCard.tsx +0 -97
- package/src/client/sync/SyncSectionPickerDialog.tsx +0 -213
- package/src/ui/path-mapping.test.ts +0 -67
- package/src/ui/path-mapping.ts +0 -103
|
@@ -0,0 +1,564 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Trae 2.3.x 的**加密会话库**通道(SQLCipher 4.x 页面布局)—— issue #134。
|
|
3
|
+
*
|
|
4
|
+
* 为什么需要它:Trae 系四个发行版(Trae / Trae CN / TRAE SOLO CN / TRAE SOLO)从 2.3 起把会话从
|
|
5
|
+
* `<User>/globalStorage/state.vscdb` 迁到 `<User>/ModularData/ai-agent/database.db`,**整库
|
|
6
|
+
* SQLCipher 加密**(真机量级约 1.4 GB)。旧通道(read-trae.ts 的 ItemTable)在新版上恒为空 ⇒
|
|
7
|
+
* 用户只看到「nothing to import」,没有任何解释。本模块负责「识别加密库 → 逐页解密出明文库 →
|
|
8
|
+
* 只读读表 → 交出**中性**会话行」;ID/角色/正文的语义映射仍留在 read-trae.ts(口径一处不改)。
|
|
9
|
+
*
|
|
10
|
+
* 页面布局(SQLCipher 4.x,page 4096,每页尾 reserve 80 B = IV(16) + HMAC-SHA512(64)):
|
|
11
|
+
* 第 1 页 [salt 16][cipher 4000][IV 16][HMAC 64] ← 前 16 B 是 salt,不是密文
|
|
12
|
+
* 其余页 [cipher 4016][IV 16][HMAC 64]
|
|
13
|
+
* 解密用 `aes-256-cbc` + `setAutoPadding(false)`(CBC 每块独立,页内无需分组边界对齐);
|
|
14
|
+
* 明文每页可用 4016 B = 4096 − 80,第 1 页明文 `[0,16)` 必须改写成 SQLite 头
|
|
15
|
+
* `SQLite format 3\0`,否则 `node:sqlite` 直接拒开(它只认明文头)。
|
|
16
|
+
*
|
|
17
|
+
* 密钥:raw AES-256(**不是**口令 ⇒ 不做 PBKDF2)。缺省值取参考实现
|
|
18
|
+
* xitula/trae-session-export 公开的常量;环境变量 `DCM_TRAE_DB_KEY`(64 位十六进制)可覆盖。
|
|
19
|
+
* 密钥错/换版必须**可判定**:不校验 HMAC(参考实现同样不校验),而是解密第 1 页后校验明文页头
|
|
20
|
+
* (页大小 / payload 分数 / 保留字节 / 声明页数)—— 错密钥撞过全部判据的概率在 2^-32 量级,
|
|
21
|
+
* 一旦不符即报 `trae-db-key-invalid`,**绝不静默 0 会话**。
|
|
22
|
+
*
|
|
23
|
+
* 三点刻意的取舍(都在 #134 的汇报里写明):
|
|
24
|
+
* ① **不额外复制原库**:按页流式解密、直接写出明文库(原库全程只读)。1.4 GB 复制会让磁盘
|
|
25
|
+
* 峰值翻倍,而解密本身已经是逐页 O(1) 内存。
|
|
26
|
+
* ② 明文只活在本次导入的私有临时目录(`os.tmpdir()/dcm-trae-db-*`),读完即 `rm -rf`;
|
|
27
|
+
* 不落用户可见目录、不进快照、不进日志(本模块**不写日志**,错误只带稳定码与 detail)。
|
|
28
|
+
* ③ 体积上限**按来源独立**(`TRAE_DB_MAX_BYTES`),**不动** sqlite.ts 的全局
|
|
29
|
+
* `DEFAULT_MAX_COPY_BYTES`(1 GiB):那是所有来源共用的兜底,改它会连带放宽别处。
|
|
30
|
+
*
|
|
31
|
+
* 诚实边界:
|
|
32
|
+
* · 表/列名只有 `chat_session` / `history_v2` / `history_v2.messages.raw_messages[]` 有调研
|
|
33
|
+
* 证据;其余元数据列(会话 id 的关联列、cwd、标题、时间)**没有真机样本** ⇒ 一律按候选列名
|
|
34
|
+
* 逐个自证,命中才用,找不到就交给下游落 `session-missing-cwd`(绝不猜语义)。
|
|
35
|
+
* · 加密库的 `-wal` 分帧同样是密文且带独立 salt,本版**不合并 WAL**:实时复制可能漏掉最新
|
|
36
|
+
* 尾部,读不到目标表按 `trae-db-schema-mismatch` 可判定失败,绝不假装读到。
|
|
37
|
+
*/
|
|
38
|
+
import { createDecipheriv } from 'node:crypto';
|
|
39
|
+
import fs from 'node:fs/promises';
|
|
40
|
+
import os from 'node:os';
|
|
41
|
+
import path from 'node:path';
|
|
42
|
+
|
|
43
|
+
import { isAbsoluteFor, joinFor } from './platform-paths.ts';
|
|
44
|
+
import type { ForeignPlatform } from './platform-paths.ts';
|
|
45
|
+
import { statOrNull } from './session-read.ts';
|
|
46
|
+
import { cellBytes, cellText, cellTime, openSqliteReadOnlyEx } from './sqlite.ts';
|
|
47
|
+
import type { SqliteHandle, SqliteRow } from './sqlite.ts';
|
|
48
|
+
import { isRecord } from '../utils/guards.ts';
|
|
49
|
+
import type { ForeignSkip } from './types.ts';
|
|
50
|
+
|
|
51
|
+
/** 加密库相对 `<User>` 的路径段(4 个发行版共用同一命名) */
|
|
52
|
+
export const TRAE_DB_REL_SEGMENTS: readonly string[] = ['ModularData', 'ai-agent', 'database.db'];
|
|
53
|
+
/** SQLCipher 4.x 的页大小(该库固定 4096) */
|
|
54
|
+
export const TRAE_DB_PAGE_SIZE = 4096;
|
|
55
|
+
/** 每页尾保留字节:IV(16) + HMAC-SHA512(64) */
|
|
56
|
+
export const TRAE_DB_RESERVE_BYTES = 80;
|
|
57
|
+
/** IV 长度(AES 块大小) */
|
|
58
|
+
export const TRAE_DB_IV_BYTES = 16;
|
|
59
|
+
/** 第 1 页开头的 salt 长度(不是密文,也不参与解密) */
|
|
60
|
+
export const TRAE_DB_SALT_BYTES = 16;
|
|
61
|
+
/** raw AES-256 密钥长度 */
|
|
62
|
+
export const TRAE_DB_KEY_BYTES = 32;
|
|
63
|
+
/**
|
|
64
|
+
* 缺省密钥:参考实现 xitula/trae-session-export 公开的 raw key 常量。
|
|
65
|
+
*
|
|
66
|
+
* **为什么可以内置**:它是产品级的固定 key(不是用户口令),参考实现公开分发;本插件只读、
|
|
67
|
+
* 且不写回任何 Trae 数据。换版后 key 变化 ⇒ 页头校验失败 ⇒ `trae-db-key-invalid`(可判定)。
|
|
68
|
+
*/
|
|
69
|
+
export const TRAE_DB_DEFAULT_KEY = '3605f6691095a993f03d5009c918352ef5be31ae31e8f000212b81ff058da773';
|
|
70
|
+
/** 覆盖密钥的环境变量名(只报键名,绝不回显值) */
|
|
71
|
+
export const TRAE_DB_KEY_ENV = 'DCM_TRAE_DB_KEY';
|
|
72
|
+
/**
|
|
73
|
+
* 加密库的体积上限(**按来源独立**,2 GiB 覆盖 1.4 GB 量级;超限走既有 copy-too-large 语义)。
|
|
74
|
+
* 刻意不碰 sqlite.ts 的 `DEFAULT_MAX_COPY_BYTES`(1 GiB,全局兜底)。
|
|
75
|
+
*/
|
|
76
|
+
export const TRAE_DB_MAX_BYTES = 2 * 1024 * 1024 * 1024;
|
|
77
|
+
/** 会话表(调研确证) */
|
|
78
|
+
export const TRAE_DB_TABLE_SESSION = 'chat_session';
|
|
79
|
+
/** 正文表(调研确证:消息在 `messages` 的 `raw_messages[]`) */
|
|
80
|
+
export const TRAE_DB_TABLE_HISTORY = 'history_v2';
|
|
81
|
+
/** 表结构**最小**签名:只钉确证过的表与列,其余列按候选自证 */
|
|
82
|
+
export const TRAE_DB_REQUIRED_SCHEMA: Readonly<Record<string, readonly string[]>> = {
|
|
83
|
+
[TRAE_DB_TABLE_SESSION]: ['id'],
|
|
84
|
+
[TRAE_DB_TABLE_HISTORY]: ['messages'],
|
|
85
|
+
};
|
|
86
|
+
/** 会话上限(与 read-trae 的 MAX_SESSIONS 同量级;由调用方再收窄) */
|
|
87
|
+
export const TRAE_DB_MAX_SESSIONS = 5000;
|
|
88
|
+
|
|
89
|
+
/** 真机样本缺失:会话→正文的关联列候选(命中即用) */
|
|
90
|
+
const SESSION_JOIN_COLUMNS: readonly string[] = [
|
|
91
|
+
'session_id', 'sessionId', 'chat_session_id', 'chatSessionId', 'conversation_id', 'conversationId',
|
|
92
|
+
];
|
|
93
|
+
/** cwd 候选(与 read-trae 的 CWD_KEYS 同口径:只认语义明确的键,且必须是绝对路径) */
|
|
94
|
+
const SESSION_CWD_COLUMNS: readonly string[] = ['cwd', 'workspace', 'workspace_path', 'workspacePath', 'root_path', 'project_path'];
|
|
95
|
+
/** 标题候选 */
|
|
96
|
+
const SESSION_TITLE_COLUMNS: readonly string[] = ['title', 'name', 'session_name', 'sessionName'];
|
|
97
|
+
/** 时间候选 */
|
|
98
|
+
const SESSION_TIME_COLUMNS: readonly string[] = ['created_at', 'createdAt', 'create_time', 'createTime', 'updated_at', 'updatedAt', 'update_time'];
|
|
99
|
+
/** 正文容器的候选键(`raw_messages` 是调研确证的第一顺位) */
|
|
100
|
+
const MESSAGE_ARRAY_KEYS: readonly string[] = ['raw_messages', 'rawMessages', 'messages'];
|
|
101
|
+
|
|
102
|
+
/** 明文库头的魔数(16 字节 ASCII,含结尾 NUL) */
|
|
103
|
+
const SQLITE_MAGIC = 'SQLite format 3';
|
|
104
|
+
/** 页大小字段的「1 表示 65536」约定 */
|
|
105
|
+
const PAGE_SIZE_ESCAPE = 1;
|
|
106
|
+
/** 明文页里 payload 分数三连(max / min / leaf),SQLite 恒定 64 / 32 / 32 */
|
|
107
|
+
const PAYLOAD_FRACTION_MAX = 64;
|
|
108
|
+
const PAYLOAD_FRACTION_MIN = 32;
|
|
109
|
+
const PAYLOAD_FRACTION_LEAF = 32;
|
|
110
|
+
|
|
111
|
+
/** 解密/读表失败的**稳定码**(与 types.ts 的 ForeignSkipCode 一一对应) */
|
|
112
|
+
export type TraeDbProblemCode =
|
|
113
|
+
| 'trae-db-key-invalid'
|
|
114
|
+
| 'trae-db-too-large'
|
|
115
|
+
| 'trae-db-decrypt-failed'
|
|
116
|
+
| 'trae-db-schema-mismatch';
|
|
117
|
+
|
|
118
|
+
/** 失败原因(`detail` 只放可枚举的短标签,绝不放密钥/明文片段) */
|
|
119
|
+
export interface TraeDbProblem {
|
|
120
|
+
readonly code: TraeDbProblemCode;
|
|
121
|
+
readonly detail: string;
|
|
122
|
+
readonly count?: number | undefined;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** 读表交出的**中性**会话行(ID 校验与角色映射在 read-trae 里做,口径一处不改) */
|
|
126
|
+
export interface TraeDbSession {
|
|
127
|
+
readonly id: string;
|
|
128
|
+
readonly cwd?: string | undefined;
|
|
129
|
+
readonly title?: string | undefined;
|
|
130
|
+
readonly createdAt?: number | undefined;
|
|
131
|
+
readonly items: readonly unknown[];
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/** 一次加密库读取的结果 */
|
|
135
|
+
export interface TraeDbReadOutcome {
|
|
136
|
+
readonly sessions: readonly TraeDbSession[];
|
|
137
|
+
readonly problem?: TraeDbProblem | undefined;
|
|
138
|
+
/** 解密出的页数(明文直读时为 undefined) */
|
|
139
|
+
readonly pages?: number | undefined;
|
|
140
|
+
/** `decrypted` = 走解密;`plaintext` = 库本身已是明文(旧版/已被解密的形态) */
|
|
141
|
+
readonly mode?: 'decrypted' | 'plaintext' | undefined;
|
|
142
|
+
/** 消息单元格解析不出的行数(如实计入,绝不伪造正文) */
|
|
143
|
+
readonly dropped?: number | undefined;
|
|
144
|
+
/** 缺 id 而无法建会话的行数 */
|
|
145
|
+
readonly skipped?: number | undefined;
|
|
146
|
+
/** 会话数触顶(调用方的 maxSessions) */
|
|
147
|
+
readonly truncated?: boolean | undefined;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/** 读表选项 */
|
|
151
|
+
export interface TraeDbReadOptions {
|
|
152
|
+
readonly env: Readonly<Record<string, string | undefined>>;
|
|
153
|
+
readonly platform: ForeignPlatform;
|
|
154
|
+
/** 体积上限(缺省 `TRAE_DB_MAX_BYTES`;单测用它造超限,不必造 2 GiB 文件) */
|
|
155
|
+
readonly maxBytes?: number | undefined;
|
|
156
|
+
/** 会话数上限(缺省 `TRAE_DB_MAX_SESSIONS`) */
|
|
157
|
+
readonly maxSessions?: number | undefined;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/** 密钥解析结果:要么给出 32 字节 raw key,要么给出可判定失败 */
|
|
161
|
+
export type TraeDbKeyResolution =
|
|
162
|
+
| { readonly key: Buffer; readonly source: 'default' | 'env' }
|
|
163
|
+
| { readonly problem: TraeDbProblem };
|
|
164
|
+
|
|
165
|
+
/** 一个 `<User>` 根下的加密库位置(**绝不硬编码分隔符**) */
|
|
166
|
+
export function traeDbPathFor(userDir: string, platform: ForeignPlatform): string {
|
|
167
|
+
return joinFor(platform, userDir, ...TRAE_DB_REL_SEGMENTS);
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/**
|
|
171
|
+
* 解析密钥:环境变量优先,缺省内置常量。
|
|
172
|
+
*
|
|
173
|
+
* 环境变量**设了但不合法**时直接报 `trae-db-key-invalid`(detail=key-format),
|
|
174
|
+
* 绝不悄悄回落到内置 key —— 那会让「我换了密钥但没生效」变成静默 0 会话。
|
|
175
|
+
*/
|
|
176
|
+
export function resolveTraeDbKey(env: Readonly<Record<string, string | undefined>>): TraeDbKeyResolution {
|
|
177
|
+
const raw = env[TRAE_DB_KEY_ENV];
|
|
178
|
+
const trimmed = typeof raw === 'string' ? raw.trim() : '';
|
|
179
|
+
if (trimmed === '') return { key: Buffer.from(TRAE_DB_DEFAULT_KEY, 'hex'), source: 'default' };
|
|
180
|
+
if (!/^[0-9a-fA-F]{64}$/.test(trimmed)) {
|
|
181
|
+
return { problem: { code: 'trae-db-key-invalid', detail: 'key-format' } };
|
|
182
|
+
}
|
|
183
|
+
return { key: Buffer.from(trimmed, 'hex'), source: 'env' };
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/** 一个页的密文区间(第 1 页跳过 salt;其余页从头开始) */
|
|
187
|
+
function cipherRange(index: number): { start: number; end: number } {
|
|
188
|
+
return { start: index === 0 ? TRAE_DB_SALT_BYTES : 0, end: TRAE_DB_PAGE_SIZE - TRAE_DB_RESERVE_BYTES };
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/** 页尾 IV 的区间(两种页都一样:倒数 80 B 的前 16 B) */
|
|
192
|
+
function ivRange(): { start: number; end: number } {
|
|
193
|
+
const start = TRAE_DB_PAGE_SIZE - TRAE_DB_RESERVE_BYTES;
|
|
194
|
+
return { start, end: start + TRAE_DB_IV_BYTES };
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/** 一页的 CBC 解密(关闭填充;异常一律 null —— 调用方转成稳定码,绝不抛出) */
|
|
198
|
+
function decryptBlock(key: Buffer, iv: Buffer, block: Buffer): Buffer | null {
|
|
199
|
+
if (block.length === 0 || block.length % TRAE_DB_IV_BYTES !== 0) return null;
|
|
200
|
+
try {
|
|
201
|
+
const decipher = createDecipheriv('aes-256-cbc', key, iv);
|
|
202
|
+
decipher.setAutoPadding(false);
|
|
203
|
+
return Buffer.concat([decipher.update(block), decipher.final()]);
|
|
204
|
+
} catch {
|
|
205
|
+
return null;
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/**
|
|
210
|
+
* 校验解密出的第 1 页明文(`plain` = 明文页的 `[16, 4016)`,即文件 offset 16 起的 4000 B)。
|
|
211
|
+
*
|
|
212
|
+
* 返回 null = 通过;返回字符串 = 可判定的失败 detail(一律映射成 `trae-db-key-invalid`)。
|
|
213
|
+
*/
|
|
214
|
+
export function validateTraePageOne(plain: Buffer, pages: number | null): string | null {
|
|
215
|
+
if (plain.length < 16) return 'short-first-page';
|
|
216
|
+
const rawPageSize = plain.readUInt16BE(0);
|
|
217
|
+
const pageSize = rawPageSize === PAGE_SIZE_ESCAPE ? 65536 : rawPageSize;
|
|
218
|
+
if (pageSize !== TRAE_DB_PAGE_SIZE) return 'page-size-mismatch';
|
|
219
|
+
// 保留字节写在 SQLite 头的 offset 20(明文里的 [4]):SQLCipher 4 为 80;0 也接受(个别库不写)
|
|
220
|
+
const reserve = plain[4] ?? 0;
|
|
221
|
+
if (reserve !== 0 && reserve !== TRAE_DB_RESERVE_BYTES) return 'reserve-mismatch';
|
|
222
|
+
if (plain[5] !== PAYLOAD_FRACTION_MAX || plain[6] !== PAYLOAD_FRACTION_MIN || plain[7] !== PAYLOAD_FRACTION_LEAF) {
|
|
223
|
+
return 'payload-fraction-mismatch';
|
|
224
|
+
}
|
|
225
|
+
if (pages !== null) {
|
|
226
|
+
const declared = plain.readUInt32BE(12);
|
|
227
|
+
if (declared !== 0 && declared !== pages) return 'page-count-mismatch';
|
|
228
|
+
}
|
|
229
|
+
return null;
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
/** 读满一页(short read 一律 null,调用方按截断处理) */
|
|
233
|
+
async function readExact(handle: Awaited<ReturnType<typeof fs.open>>, buf: Buffer, position: number): Promise<boolean> {
|
|
234
|
+
let offset = 0;
|
|
235
|
+
while (offset < buf.length) {
|
|
236
|
+
const { bytesRead } = await handle.read(buf, offset, buf.length - offset, position + offset);
|
|
237
|
+
if (bytesRead <= 0) return false;
|
|
238
|
+
offset += bytesRead;
|
|
239
|
+
}
|
|
240
|
+
return true;
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
/** 读文件开头(用于明文魔数探测与单页探测) */
|
|
244
|
+
async function readHead(file: string, length: number): Promise<Buffer | null> {
|
|
245
|
+
let handle: Awaited<ReturnType<typeof fs.open>> | null = null;
|
|
246
|
+
try {
|
|
247
|
+
handle = await fs.open(file, 'r');
|
|
248
|
+
const buf = Buffer.alloc(length);
|
|
249
|
+
const ok = await readExact(handle, buf, 0);
|
|
250
|
+
return ok ? buf : null;
|
|
251
|
+
} catch {
|
|
252
|
+
return null;
|
|
253
|
+
} finally {
|
|
254
|
+
if (handle !== null) await handle.close().catch(() => undefined);
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
/** 库本身是否已经是明文 SQLite(旧版 / 已被第三方解密的形态) */
|
|
259
|
+
async function isPlaintextSqlite(file: string): Promise<boolean> {
|
|
260
|
+
const head = await readHead(file, 16);
|
|
261
|
+
return head !== null && head.length === 16 && head.toString('latin1').startsWith(SQLITE_MAGIC);
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
/**
|
|
265
|
+
* 把一个加密库逐页解密成明文库(**覆盖写 `destPath`**,目标不存在才写)。
|
|
266
|
+
*
|
|
267
|
+
* 只读源库;内存占用恒为一页;失败时返回稳定码,**不留半截明文**(由调用方的临时目录统一清理)。
|
|
268
|
+
*/
|
|
269
|
+
export async function decryptTraeDatabase(
|
|
270
|
+
sourcePath: string,
|
|
271
|
+
destPath: string,
|
|
272
|
+
key: Buffer,
|
|
273
|
+
): Promise<{ ok: true; pages: number } | { ok: false; problem: TraeDbProblem }> {
|
|
274
|
+
const stat = await statOrNull(sourcePath);
|
|
275
|
+
if (stat === null || !stat.isFile()) {
|
|
276
|
+
return { ok: false, problem: { code: 'trae-db-decrypt-failed', detail: 'unreadable' } };
|
|
277
|
+
}
|
|
278
|
+
if (stat.size === 0) return { ok: false, problem: { code: 'trae-db-decrypt-failed', detail: 'empty-file' } };
|
|
279
|
+
// 对齐检查优先于解密:截断的库按「可判定失败」处理,不拿补 0 的明文去骗 node:sqlite
|
|
280
|
+
if (stat.size % TRAE_DB_PAGE_SIZE !== 0) {
|
|
281
|
+
return { ok: false, problem: { code: 'trae-db-decrypt-failed', detail: 'truncated-database', count: stat.size } };
|
|
282
|
+
}
|
|
283
|
+
const pages = stat.size / TRAE_DB_PAGE_SIZE;
|
|
284
|
+
const reserve = Buffer.alloc(TRAE_DB_RESERVE_BYTES); // 明文页尾不再承载 IV/HMAC ⇒ 全 0
|
|
285
|
+
const page = Buffer.alloc(TRAE_DB_PAGE_SIZE);
|
|
286
|
+
let source: Awaited<ReturnType<typeof fs.open>> | null = null;
|
|
287
|
+
let dest: Awaited<ReturnType<typeof fs.open>> | null = null;
|
|
288
|
+
try {
|
|
289
|
+
source = await fs.open(sourcePath, 'r');
|
|
290
|
+
dest = await fs.open(destPath, 'wx');
|
|
291
|
+
let firstPlain: Buffer | null = null;
|
|
292
|
+
for (let index = 0; index < pages; index += 1) {
|
|
293
|
+
if (!await readExact(source, page, index * TRAE_DB_PAGE_SIZE)) {
|
|
294
|
+
return { ok: false, problem: { code: 'trae-db-decrypt-failed', detail: 'short-read', count: index } };
|
|
295
|
+
}
|
|
296
|
+
const iv = ivRange();
|
|
297
|
+
const range = cipherRange(index);
|
|
298
|
+
const plain = decryptBlock(key, page.subarray(iv.start, iv.end), page.subarray(range.start, range.end));
|
|
299
|
+
if (plain === null) {
|
|
300
|
+
return { ok: false, problem: { code: 'trae-db-decrypt-failed', detail: 'cipher-rejected', count: index } };
|
|
301
|
+
}
|
|
302
|
+
if (index === 0) {
|
|
303
|
+
firstPlain = plain;
|
|
304
|
+
// 明文页 [0,16) 必须是 SQLite 头(salt 已被丢弃),否则 node:sqlite 拒开
|
|
305
|
+
const first = Buffer.concat([Buffer.from(SQLITE_MAGIC + '\0', 'latin1'), plain]);
|
|
306
|
+
// 我们每页恒留 80 B 保留区 ⇒ 头里的「每页保留字节数」必须声明 80(真实 SQLCipher 明文本就是 80;
|
|
307
|
+
// 个别库不写这个字段,若不归一化,node:sqlite 会把页尾 80 B 当成有效内容而判库损坏)
|
|
308
|
+
first[20] = TRAE_DB_RESERVE_BYTES;
|
|
309
|
+
await dest.write(first);
|
|
310
|
+
} else {
|
|
311
|
+
await dest.write(plain);
|
|
312
|
+
}
|
|
313
|
+
await dest.write(reserve);
|
|
314
|
+
}
|
|
315
|
+
const mismatch = firstPlain === null ? 'missing-first-page' : validateTraePageOne(firstPlain, pages);
|
|
316
|
+
if (mismatch !== null) {
|
|
317
|
+
return { ok: false, problem: { code: 'trae-db-key-invalid', detail: mismatch } };
|
|
318
|
+
}
|
|
319
|
+
return { ok: true, pages };
|
|
320
|
+
} catch (err) {
|
|
321
|
+
return {
|
|
322
|
+
ok: false,
|
|
323
|
+
problem: { code: 'trae-db-decrypt-failed', detail: err instanceof Error ? 'io-error' : 'io-error' },
|
|
324
|
+
};
|
|
325
|
+
} finally {
|
|
326
|
+
if (dest !== null) await dest.close().catch(() => undefined);
|
|
327
|
+
if (source !== null) await source.close().catch(() => undefined);
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
/**
|
|
332
|
+
* 探测期的**单页**校验(detect 用):只解密第 1 页、只读 4 KB,用来抢在 build 之前把
|
|
333
|
+
* 「密钥错 / 截断 / 超限」这三类可判定失败摆到界面上(#134 的第二半)。
|
|
334
|
+
*
|
|
335
|
+
* 返回 null = 没发现问题(或库不存在 / 已是明文)。
|
|
336
|
+
*/
|
|
337
|
+
export async function probeTraeEncryptedDatabase(
|
|
338
|
+
sourcePath: string,
|
|
339
|
+
options: Pick<TraeDbReadOptions, 'env' | 'maxBytes'>,
|
|
340
|
+
): Promise<TraeDbProblem | null> {
|
|
341
|
+
const stat = await statOrNull(sourcePath);
|
|
342
|
+
if (stat === null || !stat.isFile()) return null;
|
|
343
|
+
const maxBytes = options.maxBytes ?? TRAE_DB_MAX_BYTES;
|
|
344
|
+
if (stat.size > maxBytes) {
|
|
345
|
+
return { code: 'trae-db-too-large', detail: 'copy-too-large', count: stat.size };
|
|
346
|
+
}
|
|
347
|
+
const resolution = resolveTraeDbKey(options.env);
|
|
348
|
+
if ('problem' in resolution) return resolution.problem;
|
|
349
|
+
if (await isPlaintextSqlite(sourcePath)) return null;
|
|
350
|
+
if (stat.size === 0) return { code: 'trae-db-decrypt-failed', detail: 'empty-file' };
|
|
351
|
+
if (stat.size % TRAE_DB_PAGE_SIZE !== 0) {
|
|
352
|
+
return { code: 'trae-db-decrypt-failed', detail: 'truncated-database', count: stat.size };
|
|
353
|
+
}
|
|
354
|
+
const head = await readHead(sourcePath, TRAE_DB_PAGE_SIZE);
|
|
355
|
+
if (head === null) return { code: 'trae-db-decrypt-failed', detail: 'unreadable' };
|
|
356
|
+
const iv = ivRange();
|
|
357
|
+
const range = cipherRange(0);
|
|
358
|
+
const plain = decryptBlock(resolution.key, head.subarray(iv.start, iv.end), head.subarray(range.start, range.end));
|
|
359
|
+
if (plain === null) return { code: 'trae-db-decrypt-failed', detail: 'cipher-rejected' };
|
|
360
|
+
const mismatch = validateTraePageOne(plain, stat.size / TRAE_DB_PAGE_SIZE);
|
|
361
|
+
return mismatch === null ? null : { code: 'trae-db-key-invalid', detail: mismatch };
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
/** 标识符引用(表/列名来自本模块的常量与库自报的列清单,仍按 SQLite 规则转义) */
|
|
365
|
+
function quoteIdent(name: string): string {
|
|
366
|
+
return '"' + name.split('"').join('""') + '"';
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
/** 选中列清单(显式列名 ⇒ 缺列不会被动变成 `*`) */
|
|
370
|
+
function selectList(columns: readonly string[]): string {
|
|
371
|
+
return columns.map(quoteIdent).join(', ');
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
/** 候选列里第一个真实存在的列 */
|
|
375
|
+
function firstPresent(actual: readonly string[], candidates: readonly string[]): string | null {
|
|
376
|
+
for (const candidate of candidates) {
|
|
377
|
+
if (actual.includes(candidate)) return candidate;
|
|
378
|
+
}
|
|
379
|
+
return null;
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
/** 单元格 → JSON(TEXT 与 BLOB 都试;解析不出 → undefined,绝不伪造) */
|
|
383
|
+
function jsonCell(row: SqliteRow, key: string): unknown {
|
|
384
|
+
const text = cellText(row, key);
|
|
385
|
+
if (text !== undefined && text !== '') {
|
|
386
|
+
try {
|
|
387
|
+
return JSON.parse(text);
|
|
388
|
+
} catch {
|
|
389
|
+
// 落到 BLOB 分支再试一次
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
const bytes = cellBytes(row, key);
|
|
393
|
+
if (bytes === undefined) return undefined;
|
|
394
|
+
try {
|
|
395
|
+
return JSON.parse(new TextDecoder().decode(bytes));
|
|
396
|
+
} catch {
|
|
397
|
+
return undefined;
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
/** 正文容器 → 消息数组(`raw_messages` 第一顺位;数组本身也接受) */
|
|
402
|
+
export function messageItemsOf(value: unknown): unknown[] | null {
|
|
403
|
+
if (Array.isArray(value)) return value;
|
|
404
|
+
if (!isRecord(value)) return null;
|
|
405
|
+
for (const key of MESSAGE_ARRAY_KEYS) {
|
|
406
|
+
const candidate = value[key];
|
|
407
|
+
if (Array.isArray(candidate)) return candidate;
|
|
408
|
+
}
|
|
409
|
+
return null;
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
/** 在一行上取「第一个有内容且是绝对路径」的候选列 */
|
|
413
|
+
function absoluteCellOf(row: SqliteRow, column: string | null, platform: ForeignPlatform): string | undefined {
|
|
414
|
+
if (column === null) return undefined;
|
|
415
|
+
const value = (cellText(row, column) ?? '').trim();
|
|
416
|
+
if (value === '' || !isAbsoluteFor(platform, value)) return undefined;
|
|
417
|
+
return value;
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
/** 在一行上取第一个有内容的候选列(标题/时间用) */
|
|
421
|
+
function firstCellOf(row: SqliteRow, column: string | null): string | undefined {
|
|
422
|
+
if (column === null) return undefined;
|
|
423
|
+
const value = (cellText(row, column) ?? '').trim();
|
|
424
|
+
return value === '' ? undefined : value;
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
/** 读表并把「会话行 + 正文行」拼成中性会话列表(失败一律稳定码,绝不抛出) */
|
|
428
|
+
function readSchema(
|
|
429
|
+
db: SqliteHandle,
|
|
430
|
+
options: TraeDbReadOptions,
|
|
431
|
+
): Pick<TraeDbReadOutcome, 'sessions' | 'problem' | 'dropped' | 'skipped' | 'truncated'> {
|
|
432
|
+
const tables = db.tables();
|
|
433
|
+
if (tables === null) return { sessions: [], problem: { code: 'trae-db-schema-mismatch', detail: 'table-list-failed' } };
|
|
434
|
+
for (const [table, columns] of Object.entries(TRAE_DB_REQUIRED_SCHEMA)) {
|
|
435
|
+
if (!tables.includes(table)) {
|
|
436
|
+
return { sessions: [], problem: { code: 'trae-db-schema-mismatch', detail: 'missing-table-' + table } };
|
|
437
|
+
}
|
|
438
|
+
const actual = db.columns(table);
|
|
439
|
+
if (actual === null) return { sessions: [], problem: { code: 'trae-db-schema-mismatch', detail: 'column-list-failed-' + table } };
|
|
440
|
+
for (const column of columns) {
|
|
441
|
+
if (!actual.includes(column)) {
|
|
442
|
+
return { sessions: [], problem: { code: 'trae-db-schema-mismatch', detail: 'missing-column-' + table + '.' + column } };
|
|
443
|
+
}
|
|
444
|
+
}
|
|
445
|
+
}
|
|
446
|
+
const sessionCols = db.columns(TRAE_DB_TABLE_SESSION) ?? [];
|
|
447
|
+
const historyCols = db.columns(TRAE_DB_TABLE_HISTORY) ?? [];
|
|
448
|
+
const sessionRows = db.all('SELECT ' + selectList(sessionCols) + ' FROM ' + quoteIdent(TRAE_DB_TABLE_SESSION));
|
|
449
|
+
if (sessionRows === null) return { sessions: [], problem: { code: 'trae-db-schema-mismatch', detail: 'session-read-failed' } };
|
|
450
|
+
const historyRows = db.all('SELECT ' + selectList(historyCols) + ' FROM ' + quoteIdent(TRAE_DB_TABLE_HISTORY));
|
|
451
|
+
if (historyRows === null) return { sessions: [], problem: { code: 'trae-db-schema-mismatch', detail: 'history-read-failed' } };
|
|
452
|
+
|
|
453
|
+
const joinColumn = firstPresent(historyCols, SESSION_JOIN_COLUMNS);
|
|
454
|
+
const itemsByKey = new Map<string, unknown[]>();
|
|
455
|
+
const orderedKeys: string[] = [];
|
|
456
|
+
let dropped = 0;
|
|
457
|
+
for (const row of historyRows) {
|
|
458
|
+
const items = messageItemsOf(jsonCell(row, 'messages'));
|
|
459
|
+
if (items === null) { dropped += 1; continue; }
|
|
460
|
+
const key = joinColumn === null ? '' : (cellText(row, joinColumn) ?? '');
|
|
461
|
+
const existing = itemsByKey.get(key);
|
|
462
|
+
if (existing === undefined) {
|
|
463
|
+
itemsByKey.set(key, [...items]);
|
|
464
|
+
orderedKeys.push(key);
|
|
465
|
+
} else {
|
|
466
|
+
existing.push(...items);
|
|
467
|
+
}
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
// 没有关联列时**不猜**:只有唯一一个会话行才敢把全部正文归给它(否则=可判定失败)
|
|
471
|
+
let fallbackItems: unknown[] | null = null;
|
|
472
|
+
if (joinColumn === null) {
|
|
473
|
+
if (sessionRows.length > 1) {
|
|
474
|
+
return { sessions: [], problem: { code: 'trae-db-schema-mismatch', detail: 'session-join-column-missing' }, dropped };
|
|
475
|
+
}
|
|
476
|
+
fallbackItems = orderedKeys.flatMap((key) => itemsByKey.get(key) ?? []);
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
const cwdColumn = firstPresent(sessionCols, SESSION_CWD_COLUMNS);
|
|
480
|
+
const titleColumn = firstPresent(sessionCols, SESSION_TITLE_COLUMNS);
|
|
481
|
+
const timeColumn = firstPresent(sessionCols, SESSION_TIME_COLUMNS);
|
|
482
|
+
const maxSessions = options.maxSessions ?? TRAE_DB_MAX_SESSIONS;
|
|
483
|
+
const sessions: TraeDbSession[] = [];
|
|
484
|
+
let skipped = 0;
|
|
485
|
+
let truncated = false;
|
|
486
|
+
for (const row of sessionRows) {
|
|
487
|
+
if (sessions.length >= maxSessions) { truncated = true; break; }
|
|
488
|
+
const id = (cellText(row, 'id') ?? '').trim();
|
|
489
|
+
if (id === '') { skipped += 1; continue; }
|
|
490
|
+
const cwd = absoluteCellOf(row, cwdColumn, options.platform);
|
|
491
|
+
const title = firstCellOf(row, titleColumn);
|
|
492
|
+
const createdAt = timeColumn === null ? undefined : cellTime(row, timeColumn);
|
|
493
|
+
const items = fallbackItems ?? itemsByKey.get(id) ?? [];
|
|
494
|
+
sessions.push({
|
|
495
|
+
id,
|
|
496
|
+
...(cwd !== undefined ? { cwd } : {}),
|
|
497
|
+
...(title !== undefined ? { title: title.slice(0, 200) } : {}),
|
|
498
|
+
...(createdAt !== undefined ? { createdAt } : {}),
|
|
499
|
+
items,
|
|
500
|
+
});
|
|
501
|
+
}
|
|
502
|
+
return { sessions, dropped, skipped, truncated };
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
/**
|
|
506
|
+
* 读一个加密库:体积上限 → 密钥 → 解密(或明文直读)→ 只读读表 → 删临时明文。
|
|
507
|
+
*
|
|
508
|
+
* **绝不抛出**:所有失败都收成 `problem`(稳定码 + detail),调用方据此推 skip。
|
|
509
|
+
*/
|
|
510
|
+
export async function readTraeEncryptedDatabase(
|
|
511
|
+
sourcePath: string,
|
|
512
|
+
options: TraeDbReadOptions,
|
|
513
|
+
): Promise<TraeDbReadOutcome> {
|
|
514
|
+
const stat = await statOrNull(sourcePath);
|
|
515
|
+
if (stat === null || !stat.isFile()) {
|
|
516
|
+
return { sessions: [], problem: { code: 'trae-db-decrypt-failed', detail: 'missing' } };
|
|
517
|
+
}
|
|
518
|
+
const maxBytes = options.maxBytes ?? TRAE_DB_MAX_BYTES;
|
|
519
|
+
if (stat.size > maxBytes) {
|
|
520
|
+
return { sessions: [], problem: { code: 'trae-db-too-large', detail: 'copy-too-large', count: stat.size } };
|
|
521
|
+
}
|
|
522
|
+
const resolution = resolveTraeDbKey(options.env);
|
|
523
|
+
if ('problem' in resolution) return { sessions: [], problem: resolution.problem };
|
|
524
|
+
|
|
525
|
+
const plaintextSource = await isPlaintextSqlite(sourcePath);
|
|
526
|
+
const dir = plaintextSource ? null : await fs.mkdtemp(path.join(os.tmpdir(), 'dcm-trae-db-'));
|
|
527
|
+
try {
|
|
528
|
+
let target = sourcePath;
|
|
529
|
+
let pages: number | undefined;
|
|
530
|
+
let mode: 'decrypted' | 'plaintext' = 'plaintext';
|
|
531
|
+
if (dir !== null) {
|
|
532
|
+
target = path.join(dir, 'database.plain.db');
|
|
533
|
+
const decrypted = await decryptTraeDatabase(sourcePath, target, resolution.key);
|
|
534
|
+
if (!decrypted.ok) return { sessions: [], problem: decrypted.problem };
|
|
535
|
+
pages = decrypted.pages;
|
|
536
|
+
mode = 'decrypted';
|
|
537
|
+
}
|
|
538
|
+
// 明文库是我们自己的临时副本(无 -wal/-shm):上限与加密库同档,避免第二次复制撞全局 1 GiB
|
|
539
|
+
const opened = await openSqliteReadOnlyEx(target, { maxCopyBytes: maxBytes });
|
|
540
|
+
if (opened.db === null) {
|
|
541
|
+
return { sessions: [], problem: { code: 'trae-db-schema-mismatch', detail: 'open-' + String(opened.problem ?? 'failed') } };
|
|
542
|
+
}
|
|
543
|
+
try {
|
|
544
|
+
return { ...readSchema(opened.db, options), pages, mode };
|
|
545
|
+
} finally {
|
|
546
|
+
opened.db.close();
|
|
547
|
+
}
|
|
548
|
+
} catch {
|
|
549
|
+
return { sessions: [], problem: { code: 'trae-db-decrypt-failed', detail: 'io-error' } };
|
|
550
|
+
} finally {
|
|
551
|
+
// 明文只在本次导入内存在:无论成败都删(失败也不留半截)
|
|
552
|
+
if (dir !== null) await fs.rm(dir, { recursive: true, force: true }).catch(() => undefined);
|
|
553
|
+
}
|
|
554
|
+
}
|
|
555
|
+
|
|
556
|
+
/** problem → skip(origin 固定 'trae';count 只在有意义时带上) */
|
|
557
|
+
export function traeDbSkipOf(problem: TraeDbProblem): ForeignSkip {
|
|
558
|
+
return {
|
|
559
|
+
code: problem.code,
|
|
560
|
+
origin: 'trae',
|
|
561
|
+
detail: problem.detail,
|
|
562
|
+
...(problem.count !== undefined ? { count: problem.count } : {}),
|
|
563
|
+
};
|
|
564
|
+
}
|