diff --git a/apps/desktop/src/components/connection/ConnectionDialog.vue b/apps/desktop/src/components/connection/ConnectionDialog.vue index 05d93b0eda..d3a5c68764 100644 --- a/apps/desktop/src/components/connection/ConnectionDialog.vue +++ b/apps/desktop/src/components/connection/ConnectionDialog.vue @@ -44,6 +44,7 @@ import type { NacosAdminConfig, NacosApiPlane, NacosAuthConfig, NacosImplementat import { CONNECTION_ATTEMPT_CANCELLED_MESSAGE, useConnectionStore } from "@/stores/connectionStore"; import { useTunnelProfileStore } from "@/stores/tunnelProfileStore"; import { detachTunnelProfileLayer, tunnelProfileReferenceLayer, tunnelProfileSummary } from "@/lib/connection/tunnelProfiles"; +import { insertSqliteRemoteTransportLayer, isSqliteRemoteTransportLayerType, sqliteRemoteTransportError } from "@/lib/connection/sqliteRemoteTransport"; import { sanitizeConnectionCredentials } from "@/lib/connection/credentialSanitizer"; import { applySshAuthMethod, inferSshAuthMethod } from "@/lib/connection/sshAuthMethod"; import { applySshConfigHostAliasPrefill as prefillSshConfigHostAlias } from "@/lib/connection/sshConfigHosts"; @@ -3301,8 +3302,8 @@ const selectedHttpTunnelLayer = computed(() => (selectedTransportLayer.value?.ty const tunnelProfiles = computed(() => { const profiles = tunnelProfileStore.profiles; - if (!sqliteSshOnlyTransport.value) return profiles; - return profiles.filter((profile) => profile.type === "ssh"); + if (!sqliteRemoteTransportRestricted.value) return profiles; + return profiles.filter((profile) => isSqliteRemoteTransportLayerType(profile.type)); }); const selectedLayerProfileId = computed(() => selectedTransportLayer.value?.profile_id || ""); const selectedLayerProfile = computed(() => tunnelProfileStore.profileById(selectedLayerProfileId.value)); @@ -3792,7 +3793,7 @@ const canUseTransportLayers = computed(() => { } return true; }); -const sqliteSshOnlyTransport = computed(() => form.value.db_type === "sqlite"); +const sqliteRemoteTransportRestricted = computed(() => form.value.db_type === "sqlite"); const sqliteUsesSsh = computed(() => form.value.db_type === "sqlite" && connectionUsesSsh(form.value)); const sqliteWorkerPlacement = computed({ get: () => getUrlParam(form.value.url_params, "dbx_sqlite_worker") || "session", @@ -6149,10 +6150,10 @@ watch(canUseTransportLayers, (value) => { } }); -watch(sqliteSshOnlyTransport, (sshOnly) => { - if (!sshOnly) return; +watch(sqliteRemoteTransportRestricted, (restricted) => { + if (!restricted) return; const layers = form.value.transport_layers || []; - const next = layers.filter((layer) => layer.type === "ssh"); + const next = layers.filter((layer) => isSqliteRemoteTransportLayerType(layer.type)); if (next.length === layers.length) return; form.value.transport_layers = next; selectedTransportLayerId.value = next[0]?.id || null; @@ -6179,16 +6180,15 @@ function addSshTunnel() { } function addProxyTunnel() { - if (sqliteSshOnlyTransport.value) return; const next: TransportLayerConfig = { type: "proxy", ...defaultProxyTunnel() }; next.name = `Proxy ${transportLayers.value.length + 1}`; - form.value.transport_layers = [...transportLayers.value, next]; + form.value.transport_layers = sqliteRemoteTransportRestricted.value ? insertSqliteRemoteTransportLayer(transportLayers.value, next) : [...transportLayers.value, next]; selectedTransportLayerId.value = next.id; resetTestState(); } function addHttpTunnel() { - if (sqliteSshOnlyTransport.value) return; + if (sqliteRemoteTransportRestricted.value) return; const next: TransportLayerConfig = { type: "http_tunnel", ...defaultHttpTunnel() }; next.name = t("connection.httpTunnelDefaultName", { index: 1 }); form.value.transport_layers = [next, ...transportLayers.value]; @@ -6197,9 +6197,9 @@ function addHttpTunnel() { } function duplicateTransportLayer(layer: TransportLayerConfig) { - if (sqliteSshOnlyTransport.value && layer.type !== "ssh") return; + if (sqliteRemoteTransportRestricted.value && !isSqliteRemoteTransportLayerType(layer.type)) return; const next = normalizeTransportLayer({ ...layer, id: uuid(), name: layer.name ? `${layer.name} copy` : "" }); - form.value.transport_layers = [...transportLayers.value, next]; + form.value.transport_layers = sqliteRemoteTransportRestricted.value ? insertSqliteRemoteTransportLayer(transportLayers.value, next) : [...transportLayers.value, next]; selectedTransportLayerId.value = next.id; resetTestState(); } @@ -6237,7 +6237,7 @@ function dropTransportLayer(targetId: string) { function changeSelectedTransportLayerType(type: "ssh" | "proxy" | "http_tunnel") { const selected = selectedTransportLayer.value; if (!selected || selected.type === type) return; - if (sqliteSshOnlyTransport.value && type !== "ssh") return; + if (sqliteRemoteTransportRestricted.value && !isSqliteRemoteTransportLayerType(type)) return; const replacement: TransportLayerConfig = type === "proxy" ? { type: "proxy", ...defaultProxyTunnel(), id: selected.id, name: selected.name } : type === "http_tunnel" ? { type: "http_tunnel", ...defaultHttpTunnel(), id: selected.id, name: selected.name } : { type: "ssh", ...defaultSshTunnel(), id: selected.id, name: selected.name }; form.value.transport_layers = transportLayers.value.map((layer) => (layer.id === selected.id ? replacement : layer)); @@ -6260,7 +6260,7 @@ function updateSelectedSshAuthMethod(value: unknown) { function validateTransportLayers(config: LegacyConnectionConfig) { const layers = config.transport_layers || []; - if (config.db_type === "sqlite" && layers.some((layer) => layer.enabled !== false && layer.type !== "ssh")) { + if (config.db_type === "sqlite" && sqliteRemoteTransportError(layers)) { throw new Error(t("connection.sqliteTransportSshOnly")); } layers.forEach((layer, index) => { @@ -9994,11 +9994,11 @@ function openExternalUrl(url: string) { {{ t("connection.sshHopAdd") }} - - @@ -10047,7 +10047,7 @@ function openExternalUrl(url: string) { {{ t("connection.tunnelProfileMissing") }} -
+
diff --git a/apps/desktop/src/i18n/locales/az.ts b/apps/desktop/src/i18n/locales/az.ts index 01418d8fc4..03087ddc76 100644 --- a/apps/desktop/src/i18n/locales/az.ts +++ b/apps/desktop/src/i18n/locales/az.ts @@ -1275,7 +1275,7 @@ export default withEnglishFallback({ sshHostKeyNoticeRejected: "{host}:{port} üçün host açarını rədd etdiniz; əlaqə dayandırıldı və kimlik məlumatları göndərilmədi.", sshHostKeyNoticeLearnFailed: "{host}:{port} üçün host açarını yadda saxlamaq mümkün olmadı — hosta yalnız bu sessiya üçün etibar edilir və növbəti dəfə onu yenidən yoxlamağınız istəniləcək.", sshHostKeyNoticeGeneric: "{host}:{port} üçün SSH host açarının yoxlanması uğursuz oldu.", - sqliteTransportSshOnly: "Uzaq SQLite yalnız SSH keçidlərini dəstəkləyir. Proksi və HTTP tuneli qatlarından istifadə etmək mümkün deyil.", + sqliteTransportSshOnly: "Uzaq SQLite son SSH keçidindən əvvəl HTTP CONNECT və ya SOCKS5 proksi qatlarını dəstəkləyir. HTTP tuneli qatları dəstəklənmir.", sqliteRemotePathPlaceholder: "/var/lib/app/data.db", sqliteRemotePathHint: "Son SSH keçidində mütləq yol daxil edin.", sqliteSshCipherUnsupportedHint: "Şifrələnmiş (SQLCipher) SQLite verilənlər bazaları SSH üzərindən hələ dəstəklənmir.", diff --git a/apps/desktop/src/i18n/locales/en.ts b/apps/desktop/src/i18n/locales/en.ts index 3ab8248152..c3f9b6c0c8 100644 --- a/apps/desktop/src/i18n/locales/en.ts +++ b/apps/desktop/src/i18n/locales/en.ts @@ -1579,7 +1579,7 @@ export default { sshHostKeyNoticeRejected: "You rejected the host key for {host}:{port}; the connection was aborted and no credentials were sent.", sshHostKeyNoticeLearnFailed: "Could not save the host key for {host}:{port} — the host is trusted for this session only and you will be asked to verify it again next time.", sshHostKeyNoticeGeneric: "SSH host key verification failed for {host}:{port}.", - sqliteTransportSshOnly: "Remote SQLite only supports SSH hops. Proxy and HTTP tunnel layers cannot be used.", + sqliteTransportSshOnly: "Remote SQLite supports HTTP CONNECT or SOCKS5 proxy layers only before a final SSH hop. HTTP tunnel layers are not supported.", sqliteRemotePathPlaceholder: "/var/lib/app/data.db", sqliteRemotePathHint: "Enter an absolute path on the final SSH hop.", sqliteSshCipherUnsupportedHint: "Encrypted (SQLCipher) SQLite databases are not supported over SSH yet.", diff --git a/apps/desktop/src/i18n/locales/es.ts b/apps/desktop/src/i18n/locales/es.ts index 36883d674f..01f7687886 100644 --- a/apps/desktop/src/i18n/locales/es.ts +++ b/apps/desktop/src/i18n/locales/es.ts @@ -1540,7 +1540,7 @@ export default withEnglishFallback({ sshHostKeyNoticeChanged: "La clave del host {host}:{port} ha cambiado, puede haber un ataque de intermediario. Si es esperado, elimine el registro antiguo y vuelva a conectar.", sshHostKeyNoticeRejected: "Ha rechazado la verificación de la clave del host {host}:{port}. La conexión se ha abortado, no se enviaron credenciales.", sshHostKeyNoticeGeneric: "Falló la verificación de la clave del host SSH {host}:{port}.", - sqliteTransportSshOnly: "SQLite remoto solo admite saltos SSH. No se pueden usar capas de proxy ni túnel HTTP.", + sqliteTransportSshOnly: "SQLite remoto admite capas de proxy HTTP CONNECT o SOCKS5 solo antes de un salto SSH final. No se admiten capas de túnel HTTP.", sqliteRemotePathPlaceholder: "/var/lib/app/data.db", sqliteRemotePathHint: "Introduce una ruta absoluta en el último salto SSH.", sqliteSshCipherUnsupportedHint: "Las bases de datos SQLite cifradas (SQLCipher) aún no son compatibles a través de SSH.", diff --git a/apps/desktop/src/i18n/locales/it.ts b/apps/desktop/src/i18n/locales/it.ts index e22af5a84a..566586b849 100644 --- a/apps/desktop/src/i18n/locales/it.ts +++ b/apps/desktop/src/i18n/locales/it.ts @@ -1475,7 +1475,7 @@ export default withEnglishFallback({ sshHostKeyNoticeChanged: "La chiave dell'host {host}:{port} è cambiata, potrebbe esserci un attacco man-in-the-middle. Se il cambiamento è previsto, elimina il vecchio record e riconnettiti.", sshHostKeyNoticeRejected: "Hai rifiutato la verifica della chiave host di {host}:{port}, la connessione è stata interrotta e le credenziali non sono state inviate.", sshHostKeyNoticeGeneric: "Verifica della chiave host SSH {host}:{port} fallita.", - sqliteTransportSshOnly: "SQLite remoto supporta solo salti SSH. Impossibile usare livelli proxy o tunnel HTTP.", + sqliteTransportSshOnly: "SQLite remoto supporta livelli proxy HTTP CONNECT o SOCKS5 solo prima di un salto SSH finale. I livelli tunnel HTTP non sono supportati.", sqliteRemotePathPlaceholder: "/var/lib/app/data.db", sqliteRemotePathHint: "Inserisci un percorso assoluto sull'ultimo salto SSH.", sqliteSshCipherUnsupportedHint: "I database SQLite cifrati (SQLCipher) non sono ancora supportati tramite SSH.", diff --git a/apps/desktop/src/i18n/locales/ja.ts b/apps/desktop/src/i18n/locales/ja.ts index 1a9b157d5b..139ea7c296 100644 --- a/apps/desktop/src/i18n/locales/ja.ts +++ b/apps/desktop/src/i18n/locales/ja.ts @@ -1474,7 +1474,7 @@ export default withEnglishFallback({ sshHostKeyNoticeChanged: "ホスト {host}:{port} のキーが変更されました。中間者攻撃の可能性があります。予期された変更である場合は、古いレコードを削除して再接続してください。", sshHostKeyNoticeRejected: "ホスト {host}:{port} のホストキー検証を拒否しました。接続は中止され、資格情報は送信されませんでした。", sshHostKeyNoticeGeneric: "SSHホスト {host}:{port} のキー検証に失敗しました。", - sqliteTransportSshOnly: "リモート SQLite は SSH ホップのみ対応です。プロキシ層や HTTP トンネルは使用できません。", + sqliteTransportSshOnly: "リモート SQLite では、最後の SSH ホップの前に HTTP CONNECT または SOCKS5 プロキシを配置できます。HTTP トンネルレイヤーはサポートされません。", sqliteRemotePathPlaceholder: "/var/lib/app/data.db", sqliteRemotePathHint: "最終 SSH ホップ上の絶対パスを入力してください。", sqliteSshCipherUnsupportedHint: "SSH 経由での暗号化(SQLCipher)SQLite データベースの接続にはまだ対応していません。", diff --git a/apps/desktop/src/i18n/locales/ko.ts b/apps/desktop/src/i18n/locales/ko.ts index c8689e3991..a9f43e5f58 100644 --- a/apps/desktop/src/i18n/locales/ko.ts +++ b/apps/desktop/src/i18n/locales/ko.ts @@ -1390,7 +1390,7 @@ export default withEnglishFallback({ sshHostKeyNoticeRejected: "{host}:{port}의 호스트 키를 거부했습니다. 연결이 중단되고 자격 증명이 전송되지 않았습니다.", sshHostKeyNoticeLearnFailed: "{host}:{port}의 호스트 키를 저장할 수 없습니다 — 이 호스트는 이 세션에만 신뢰되며 다음에 다시 확인을 요청받습니다.", sshHostKeyNoticeGeneric: "{host}:{port}의 SSH 호스트 키 검증에 실패했습니다.", - sqliteTransportSshOnly: "원격 SQLite는 SSH 홉만 지원합니다. 프록시 및 HTTP 터널 계층은 사용할 수 없습니다.", + sqliteTransportSshOnly: "원격 SQLite는 최종 SSH 홉 앞에 HTTP CONNECT 또는 SOCKS5 프록시 계층을 지원합니다. HTTP 터널 계층은 지원되지 않습니다.", sqliteRemotePathPlaceholder: "/var/lib/app/data.db", sqliteRemotePathHint: "마지막 SSH 홉의 절대 경로를 입력하세요.", sqliteSshCipherUnsupportedHint: "SSH를 통한 암호화(SQLCipher)된 SQLite 데이터베이스 연결은 아직 지원되지 않습니다.", diff --git a/apps/desktop/src/i18n/locales/pt-BR.ts b/apps/desktop/src/i18n/locales/pt-BR.ts index 14bfc9e9d5..9ed0b537d9 100644 --- a/apps/desktop/src/i18n/locales/pt-BR.ts +++ b/apps/desktop/src/i18n/locales/pt-BR.ts @@ -1475,7 +1475,7 @@ export default withEnglishFallback({ sshHostKeyNoticeChanged: "A chave do host {host}:{port} foi alterada, pode haver um ataque man-in-the-middle. Se esta alteração era esperada, exclua o registro antigo e reconecte.", sshHostKeyNoticeRejected: "Você rejeitou a verificação da chave do host {host}:{port}. A conexão foi abortada e as credenciais não foram enviadas.", sshHostKeyNoticeGeneric: "Falha na verificação da chave do host SSH {host}:{port}.", - sqliteTransportSshOnly: "O SQLite remoto suporta apenas saltos SSH. Camadas de proxy e túnel HTTP não podem ser usadas.", + sqliteTransportSshOnly: "O SQLite remoto aceita camadas de proxy HTTP CONNECT ou SOCKS5 apenas antes de um salto SSH final. Camadas de túnel HTTP não são compatíveis.", sqliteRemotePathPlaceholder: "/var/lib/app/data.db", sqliteRemotePathHint: "Informe um caminho absoluto no último salto SSH.", sqliteSshCipherUnsupportedHint: "Bancos de dados SQLite criptografados (SQLCipher) ainda não são suportados via SSH.", diff --git a/apps/desktop/src/i18n/locales/ru.ts b/apps/desktop/src/i18n/locales/ru.ts index 58a267f513..c2ba30358a 100644 --- a/apps/desktop/src/i18n/locales/ru.ts +++ b/apps/desktop/src/i18n/locales/ru.ts @@ -1464,7 +1464,7 @@ export default withEnglishFallback({ sshHostKeyNoticeRejected: "Вы отклонили ключ хоста {host}:{port}; подключение прервано, учётные данные не отправлены.", sshHostKeyNoticeLearnFailed: "Не удалось сохранить ключ хоста {host}:{port} — хост считается доверенным только для этого сеанса, и при следующем подключении потребуется повторная проверка.", sshHostKeyNoticeGeneric: "Не удалось проверить ключ хоста SSH для {host}:{port}.", - sqliteTransportSshOnly: "Удалённый SQLite поддерживает только переходы SSH. Слои прокси и HTTP-туннеля использовать нельзя.", + sqliteTransportSshOnly: "Удалённый SQLite поддерживает слои прокси HTTP CONNECT или SOCKS5 только перед конечным переходом SSH. Слои HTTP-туннеля не поддерживаются.", sqliteRemotePathPlaceholder: "/var/lib/app/data.db", sqliteRemotePathHint: "Введите абсолютный путь на последнем переходе SSH.", sqliteSshCipherUnsupportedHint: "Зашифрованные базы данных SQLite (SQLCipher) пока не поддерживаются через SSH.", diff --git a/apps/desktop/src/i18n/locales/tr.ts b/apps/desktop/src/i18n/locales/tr.ts index a9ee9626bc..c68cd23cd5 100644 --- a/apps/desktop/src/i18n/locales/tr.ts +++ b/apps/desktop/src/i18n/locales/tr.ts @@ -1277,7 +1277,7 @@ export default withEnglishFallback({ sshHostKeyNoticeRejected: "{host}:{port} için sunucu anahtarını reddettiniz; bağlantı iptal edildi ve hiçbir kimlik bilgisi gönderilmedi.", sshHostKeyNoticeLearnFailed: "{host}:{port} için sunucu anahtarı kaydedilemedi — sunucuya yalnızca bu oturum için güvenilecek ve bir sonraki seferde yeniden doğrulamanız istenecek.", sshHostKeyNoticeGeneric: "{host}:{port} için SSH sunucu anahtarı doğrulaması başarısız oldu.", - sqliteTransportSshOnly: "Uzak SQLite yalnızca SSH atlamalarını destekler. Proxy ve HTTP tünel katmanları kullanılamaz.", + sqliteTransportSshOnly: "Uzak SQLite, yalnızca son SSH atlamasından önce HTTP CONNECT veya SOCKS5 proxy katmanlarını destekler. HTTP tünel katmanları desteklenmez.", sqliteRemotePathPlaceholder: "/var/lib/app/data.db", sqliteRemotePathHint: "Son SSH atlamasındaki mutlak bir yol girin.", sqliteSshCipherUnsupportedHint: "Şifrelenmiş (SQLCipher) SQLite veritabanları henüz SSH üzerinden desteklenmiyor.", diff --git a/apps/desktop/src/i18n/locales/zh-CN.ts b/apps/desktop/src/i18n/locales/zh-CN.ts index 8530fc5339..00e6392512 100644 --- a/apps/desktop/src/i18n/locales/zh-CN.ts +++ b/apps/desktop/src/i18n/locales/zh-CN.ts @@ -1496,7 +1496,7 @@ export default withEnglishFallback({ sshHostKeyNoticeRejected: "你已拒绝 {host}:{port} 的主机密钥验证,连接已中止,凭据未发送。", sshHostKeyNoticeLearnFailed: "无法保存 {host}:{port} 的主机密钥 — 该主机仅在本次会话内受信任,下次连接仍需重新确认。", sshHostKeyNoticeGeneric: "SSH 主机 {host}:{port} 的密钥验证失败。", - sqliteTransportSshOnly: "远程 SQLite 只支持 SSH 跳板,不能使用代理或 HTTP 隧道。", + sqliteTransportSshOnly: "远程 SQLite 支持在最终 SSH 跳板前配置 HTTP CONNECT 或 SOCKS5 代理,但不支持 HTTP 隧道层。", sqliteRemotePathPlaceholder: "/var/lib/app/data.db", sqliteRemotePathHint: "请填写最后一跳 SSH 主机上的绝对路径。", sqliteSshCipherUnsupportedHint: "暂不支持通过 SSH 打开加密(SQLCipher)的 SQLite 数据库。", diff --git a/apps/desktop/src/i18n/locales/zh-TW.ts b/apps/desktop/src/i18n/locales/zh-TW.ts index 0dc6142941..b0427fc378 100644 --- a/apps/desktop/src/i18n/locales/zh-TW.ts +++ b/apps/desktop/src/i18n/locales/zh-TW.ts @@ -1485,7 +1485,7 @@ export default withEnglishFallback({ sshHostKeyNoticeChanged: "主機 {host}:{port} 的金鑰已變更,可能存在中間人攻擊。如確屬預期,請刪除舊記錄後重新連線。", sshHostKeyNoticeRejected: "您已拒絕 {host}:{port} 的主機金鑰驗證,連線已中止,憑證未發送。", sshHostKeyNoticeGeneric: "SSH 主機 {host}:{port} 的金鑰驗證失敗。", - sqliteTransportSshOnly: "遠端 SQLite 僅支援 SSH 跳板,無法使用代理或 HTTP 通道。", + sqliteTransportSshOnly: "遠端 SQLite 支援在最終 SSH 跳板前設定 HTTP CONNECT 或 SOCKS5 代理,但不支援 HTTP 通道層。", sqliteRemotePathPlaceholder: "/var/lib/app/data.db", sqliteRemotePathHint: "請填寫最後一跳 SSH 主機上的絕對路徑。", sqliteSshCipherUnsupportedHint: "暫不支援透過 SSH 開啟加密(SQLCipher)的 SQLite 資料庫。", diff --git a/apps/desktop/src/lib/connection/__tests__/sqliteRemoteTransport.spec.ts b/apps/desktop/src/lib/connection/__tests__/sqliteRemoteTransport.spec.ts new file mode 100644 index 0000000000..ac3ad7f904 --- /dev/null +++ b/apps/desktop/src/lib/connection/__tests__/sqliteRemoteTransport.spec.ts @@ -0,0 +1,35 @@ +import { describe, expect, it } from "vitest"; +import type { TransportLayerConfig } from "@/types/database"; +import { insertSqliteRemoteTransportLayer, isSqliteRemoteTransportLayerType, sqliteRemoteTransportError } from "../sqliteRemoteTransport"; + +function layer(type: TransportLayerConfig["type"], enabled = true): Pick { + return { type, enabled }; +} + +describe("SQLite remote transport", () => { + it("allows SSH and proxy layer types", () => { + expect(isSqliteRemoteTransportLayerType("ssh")).toBe(true); + expect(isSqliteRemoteTransportLayerType("proxy")).toBe(true); + expect(isSqliteRemoteTransportLayerType("http_tunnel")).toBe(false); + }); + + it("accepts proxy layers before the final SSH hop", () => { + expect(sqliteRemoteTransportError([layer("proxy"), layer("ssh")])).toBeNull(); + expect(sqliteRemoteTransportError([layer("proxy"), layer("ssh"), layer("ssh")])).toBeNull(); + }); + + it("inserts a new proxy before an existing final SSH hop", () => { + expect(insertSqliteRemoteTransportLayer([layer("proxy"), layer("ssh")], layer("proxy"))).toEqual([layer("proxy"), layer("proxy"), layer("ssh")]); + expect(insertSqliteRemoteTransportLayer([layer("proxy")], layer("ssh"))).toEqual([layer("proxy"), layer("ssh")]); + }); + + it("requires the final enabled layer to be SSH", () => { + expect(sqliteRemoteTransportError([layer("proxy")])).toBe("final_ssh"); + expect(sqliteRemoteTransportError([layer("ssh"), layer("proxy")])).toBe("final_ssh"); + expect(sqliteRemoteTransportError([layer("ssh"), layer("proxy", false)])).toBeNull(); + }); + + it("rejects script HTTP tunnel layers", () => { + expect(sqliteRemoteTransportError([layer("http_tunnel"), layer("ssh")])).toBe("http_tunnel"); + }); +}); diff --git a/apps/desktop/src/lib/connection/sqliteRemoteTransport.ts b/apps/desktop/src/lib/connection/sqliteRemoteTransport.ts new file mode 100644 index 0000000000..9b5abdebbf --- /dev/null +++ b/apps/desktop/src/lib/connection/sqliteRemoteTransport.ts @@ -0,0 +1,37 @@ +import type { TransportLayerConfig } from "@/types/database"; + +type SqliteTransportLayer = Pick; + +export type SqliteRemoteTransportError = "http_tunnel" | "final_ssh"; + +export function isSqliteRemoteTransportLayerType(type: TransportLayerConfig["type"]): boolean { + return type === "ssh" || type === "proxy"; +} + +export function insertSqliteRemoteTransportLayer(layers: readonly T[], layer: T): T[] { + const next = [...layers]; + if (layer.type !== "proxy") { + next.push(layer); + return next; + } + let lastEnabledIndex = -1; + for (let index = next.length - 1; index >= 0; index--) { + if (next[index]?.enabled !== false) { + lastEnabledIndex = index; + break; + } + } + if (lastEnabledIndex >= 0 && next[lastEnabledIndex]?.type === "ssh") { + next.splice(lastEnabledIndex, 0, layer); + } else { + next.push(layer); + } + return next; +} + +export function sqliteRemoteTransportError(layers: readonly SqliteTransportLayer[]): SqliteRemoteTransportError | null { + const enabledLayers = layers.filter((layer) => layer.enabled !== false); + if (enabledLayers.some((layer) => layer.type === "http_tunnel")) return "http_tunnel"; + if (enabledLayers.length > 0 && enabledLayers[enabledLayers.length - 1]?.type !== "ssh") return "final_ssh"; + return null; +} diff --git a/crates/dbx-core/src/connection/mod.rs b/crates/dbx-core/src/connection/mod.rs index 2912b10fbd..160be3a939 100644 --- a/crates/dbx-core/src/connection/mod.rs +++ b/crates/dbx-core/src/connection/mod.rs @@ -2623,10 +2623,12 @@ impl AppState { PoolKind::Postgres(pg_pool) } DatabaseType::Sqlite => { - if db::sqlite_worker::sqlite_ssh_worker_requested(&db_config) { + if db::sqlite_worker::sqlite_remote_worker_requested(&db_config) { let transport_layers = self.resolved_transport_layers(&db_config).await?; let worker = db::sqlite_worker::connect_sqlite_worker( &self.tunnels, + &self.proxy_tunnels, + &self.http_tunnels, &self.agent_manager, self.storage.data_dir(), connection_id, @@ -3423,7 +3425,7 @@ impl AppState { config: &ConnectionConfig, ) -> Result { let transport_layers = self.resolved_transport_layers(config).await?; - if transport_layers.is_empty() || db::sqlite_worker::sqlite_ssh_worker_requested(config) { + if transport_layers.is_empty() || db::sqlite_worker::sqlite_remote_worker_requested(config) { return Ok(ConnectionEndpoint::direct(config.host.clone(), config.port)); } if config.uses_oracle_tns() { @@ -5248,6 +5250,8 @@ impl AppState { self.http_tunnels.stop_tunnels_with_prefix(&redis_sentinel_prefix).await; let sqlite_worker_prefix = db::sqlite_worker::sqlite_worker_chain_id(connection_id); self.tunnels.stop_tunnels_with_prefix(&sqlite_worker_prefix).await; + self.proxy_tunnels.stop_tunnels_with_prefix(&sqlite_worker_prefix).await; + self.http_tunnels.stop_tunnels_with_prefix(&sqlite_worker_prefix).await; db::transport_layer_tunnel::stop_transport_layers( connection_id, layer_count, diff --git a/crates/dbx-drivers/src/db/sqlite_worker.rs b/crates/dbx-drivers/src/db/sqlite_worker.rs index d76627f86f..3c8b63bff6 100644 --- a/crates/dbx-drivers/src/db/sqlite_worker.rs +++ b/crates/dbx-drivers/src/db/sqlite_worker.rs @@ -14,8 +14,11 @@ use tokio::process::{Child, ChildStdin}; use tokio::sync::Mutex as AsyncMutex; use crate::agent_manager::{AgentManager, SQLITE_WORKER_DRIVER_KEY}; +use crate::db::http_tunnel::HttpTunnelManager; +use crate::db::proxy_tunnel::ProxyTunnelManager; use crate::db::ssh_prompt::{self, SshPromptAnswer, SshPromptKind, SshPromptRequest}; use crate::db::ssh_tunnel::{self, SshClient, TunnelManager}; +use crate::db::transport_layer_tunnel; use crate::models::connection::{ConnectionConfig, DatabaseType, SshTunnelConfig, TransportLayerConfig}; use crate::types::QueryResult; @@ -49,8 +52,8 @@ pub enum SqliteWorkerPlacement { Preplaced, } -pub fn sqlite_ssh_worker_requested(config: &ConnectionConfig) -> bool { - config.db_type == DatabaseType::Sqlite && config.has_effective_ssh_tunnels() +pub fn sqlite_remote_worker_requested(config: &ConnectionConfig) -> bool { + config.db_type == DatabaseType::Sqlite && config.has_effective_transport_layers() } fn sqlite_worker_placement(config: &ConnectionConfig) -> SqliteWorkerPlacement { @@ -327,6 +330,8 @@ async fn read_jsonl_line(reader: &mut R) -> Result 1).then(|| sqlite_worker_chain_id(connection_id)); + let route = sqlite_worker_route(transport_layers)?; + let chain_id = (!route.prefix_layers.is_empty()).then(|| sqlite_worker_chain_id(connection_id)); let db_path = config.host.trim(); if db_path.is_empty() { return Err("Remote SQLite path is empty".to_string()); @@ -360,7 +365,15 @@ pub async fn connect_sqlite_worker( let placement = sqlite_worker_placement(config); let remove_remote_on_close = removes_remote_worker_on_disconnect(placement); let configured_path = sqlite_worker_remote_path(config); - let session = open_final_hop_session(tunnels, connection_id, &hops).await?; + let session = open_final_hop_session( + tunnels, + proxy_tunnels, + http_tunnels, + connection_id, + &route.prefix_layers, + &route.final_ssh, + ) + .await?; let remote_home = ssh_capture(&session, "printf %s \"$HOME\"").await?; let expand_home = |path: &str| { if let Some(rest) = path.strip_prefix("~/") { @@ -381,7 +394,7 @@ pub async fn connect_sqlite_worker( } let local_worker = resolve_local_worker(agent_manager, &platform).await?; let digest = local_worker.digest.clone(); - let identity = hop_identity(hops.last().ok_or("SSH hop list is empty")?); + let identity = hop_identity(&route.final_ssh); let remote_path = match placement { SqliteWorkerPlacement::Preplaced => { @@ -439,7 +452,7 @@ pub async fn connect_sqlite_worker( remove_uploaded_session_worker(session.as_ref(), &remote_path).await; } if let Some(chain_id) = chain_id.as_deref() { - tunnels.stop_tunnel(chain_id).await; + stop_sqlite_transport_layers(chain_id, tunnels, proxy_tunnels, http_tunnels).await; } Err(error) } @@ -534,55 +547,84 @@ fn remember_consent(data_dir: &Path, identity: &str, digest: &str) { async fn open_final_hop_session( tunnels: &TunnelManager, + proxy_tunnels: &ProxyTunnelManager, + http_tunnels: &HttpTunnelManager, connection_id: &str, - hops: &[SshTunnelConfig], + prefix_layers: &[TransportLayerConfig], + final_ssh: &SshTunnelConfig, ) -> Result, String> { - let last = hops.last().ok_or("SSH hop list is empty")?; - if hops.len() == 1 { + if prefix_layers.is_empty() { return ssh_tunnel::connect_and_authenticate( - &last.host, - last.port, - &last.host, - last.port, - &last.user, - &last.password, - &last.key_path, - &last.key_passphrase, - last.use_ssh_agent, - &last.ssh_agent_sock_path, - &last.auth_method, - ssh_tunnel::effective_hop_timeout(last), + &final_ssh.host, + final_ssh.port, + &final_ssh.host, + final_ssh.port, + &final_ssh.user, + &final_ssh.password, + &final_ssh.key_path, + &final_ssh.key_passphrase, + final_ssh.use_ssh_agent, + &final_ssh.ssh_agent_sock_path, + &final_ssh.auth_method, + ssh_tunnel::effective_hop_timeout(final_ssh), tunnels.known_hosts_path(), ) .await; } let chain_id = sqlite_worker_chain_id(connection_id); - let local_port = tunnels.start_chain(&chain_id, &hops[..hops.len() - 1], &last.host, last.port).await?; + let local_port = match transport_layer_tunnel::start_transport_layers( + &chain_id, + prefix_layers, + &final_ssh.host, + final_ssh.port, + tunnels, + proxy_tunnels, + http_tunnels, + ) + .await + { + Ok(local_port) => local_port, + Err(error) => { + stop_sqlite_transport_layers(&chain_id, tunnels, proxy_tunnels, http_tunnels).await; + return Err(error); + } + }; match ssh_tunnel::connect_and_authenticate( "127.0.0.1", local_port, - &last.host, - last.port, - &last.user, - &last.password, - &last.key_path, - &last.key_passphrase, - last.use_ssh_agent, - &last.ssh_agent_sock_path, - &last.auth_method, - ssh_tunnel::effective_hop_timeout(last), + &final_ssh.host, + final_ssh.port, + &final_ssh.user, + &final_ssh.password, + &final_ssh.key_path, + &final_ssh.key_passphrase, + final_ssh.use_ssh_agent, + &final_ssh.ssh_agent_sock_path, + &final_ssh.auth_method, + ssh_tunnel::effective_hop_timeout(final_ssh), tunnels.known_hosts_path(), ) .await { Ok(session) => Ok(session), Err(error) => { - tunnels.stop_tunnel(&chain_id).await; + stop_sqlite_transport_layers(&chain_id, tunnels, proxy_tunnels, http_tunnels).await; Err(error) } } } +async fn stop_sqlite_transport_layers( + chain_id: &str, + tunnels: &TunnelManager, + proxy_tunnels: &ProxyTunnelManager, + http_tunnels: &HttpTunnelManager, +) { + tunnels.stop_tunnels_with_prefix(chain_id).await; + proxy_tunnels.stop_tunnels_with_prefix(chain_id).await; + http_tunnels.stop_tunnels_with_prefix(chain_id).await; +} + async fn remote_linux_platform(session: &Handle) -> Result { linux_platform_from_uname(ssh_capture(session, "uname -m").await?.trim()) } @@ -789,24 +831,37 @@ async fn verify_remote_digest(session: &Handle, path: &str, digest: & Ok(()) } -fn ssh_hops(layers: &[TransportLayerConfig]) -> Result, String> { - let hops = layers - .iter() - .map(|layer| match layer { - TransportLayerConfig::Ssh(ssh) => { - let ssh = crate::ssh_config::resolve_ssh_tunnel_config(ssh); - if ssh.host.trim().is_empty() { - return Err("SSH host is required.".to_string()); - } - Ok(ssh) - } - _ => Err("Remote SQLite over SSH does not support proxy or HTTP tunnel layers".to_string()), - }) - .collect::, _>>()?; - if hops.is_empty() { - return Err("Remote SQLite requires at least one SSH hop".to_string()); +#[derive(Debug)] +struct SqliteWorkerRoute { + prefix_layers: Vec, + final_ssh: SshTunnelConfig, +} + +fn sqlite_worker_route(layers: &[TransportLayerConfig]) -> Result { + if layers.iter().any(|layer| matches!(layer, TransportLayerConfig::HttpTunnel(_))) { + return Err("Remote SQLite does not support HTTP tunnel layers".to_string()); } - Ok(hops) + let Some((last, prefix_layers)) = layers.split_last() else { + return Err("Remote SQLite requires at least one SSH hop".to_string()); + }; + let TransportLayerConfig::Ssh(final_ssh) = last else { + return Err("Remote SQLite transport must end with an SSH hop".to_string()); + }; + let final_ssh = crate::ssh_config::resolve_ssh_tunnel_config(final_ssh); + if final_ssh.host.trim().is_empty() { + return Err("SSH host is required.".to_string()); + } + let prefix_layers = prefix_layers + .iter() + .cloned() + .map(|mut layer| { + if let TransportLayerConfig::Ssh(ssh) = &mut layer { + ssh.expose_lan = false; + } + layer + }) + .collect(); + Ok(SqliteWorkerRoute { prefix_layers, final_ssh }) } fn hop_identity(hop: &SshTunnelConfig) -> String { @@ -943,37 +998,90 @@ mod tests { } #[test] - fn remote_sqlite_requires_ssh() { + fn remote_sqlite_requires_a_transport_layer() { let config = empty_config(); - assert!(!sqlite_ssh_worker_requested(&config)); + assert!(!sqlite_remote_worker_requested(&config)); } #[test] - fn ssh_hops_uses_resolved_layers_instead_of_profile_stubs() { - let hops = ssh_hops(&[ssh_layer("203.0.113.10", "testuser")]).unwrap(); - assert_eq!(hops.len(), 1); - assert_eq!(hops[0].host, "203.0.113.10"); - assert_eq!(hops[0].user, "testuser"); + fn sqlite_worker_route_uses_resolved_final_ssh() { + let layers = [ssh_layer("203.0.113.10", "testuser")]; + let route = sqlite_worker_route(&layers).unwrap(); + assert!(route.prefix_layers.is_empty()); + assert_eq!(route.final_ssh.host, "203.0.113.10"); + assert_eq!(route.final_ssh.user, "testuser"); } #[test] - fn ssh_hops_rejects_unresolved_profile_stubs() { - let error = ssh_hops(&[ssh_layer("", "")]).unwrap_err(); + fn sqlite_worker_route_rejects_unresolved_profile_stubs() { + let error = sqlite_worker_route(&[ssh_layer("", "")]).unwrap_err(); assert!(error.contains("SSH host is required"), "{error}"); } #[test] - fn ssh_hops_rejects_non_ssh_layers() { + fn sqlite_worker_route_accepts_proxy_before_final_ssh() { + let layers = [proxy_layer("proxy-1"), ssh_layer("203.0.113.10", "testuser")]; + let route = sqlite_worker_route(&layers).unwrap(); + assert_eq!(route.prefix_layers, layers[..1]); + assert_eq!(route.final_ssh.host, "203.0.113.10"); + } + + #[test] + fn sqlite_worker_route_keeps_earlier_ssh_hops_in_the_prefix() { + let mut jump = ssh_layer("203.0.113.10", "jump"); + if let TransportLayerConfig::Ssh(ssh) = &mut jump { + ssh.expose_lan = true; + } + let layers = [jump, ssh_layer("203.0.113.11", "target")]; + let route = sqlite_worker_route(&layers).unwrap(); + assert_eq!(route.prefix_layers.len(), 1); + let TransportLayerConfig::Ssh(prefix) = &route.prefix_layers[0] else { panic!("expected SSH prefix") }; + assert_eq!(prefix.host, "203.0.113.10"); + assert!(!prefix.expose_lan); + assert_eq!(route.final_ssh.host, "203.0.113.11"); + } + + #[test] + fn sqlite_worker_route_rejects_proxy_only() { + let error = sqlite_worker_route(&[proxy_layer("proxy-1")]).unwrap_err(); + assert!(error.contains("must end with an SSH hop"), "{error}"); + } + + #[test] + fn sqlite_worker_route_rejects_ssh_followed_by_proxy() { + let error = sqlite_worker_route(&[ssh_layer("203.0.113.10", "testuser"), proxy_layer("proxy-1")]).unwrap_err(); + assert!(error.contains("must end with an SSH hop"), "{error}"); + } + + #[test] + fn sqlite_worker_route_rejects_http_tunnel_layers() { let layer = serde_json::from_value(serde_json::json!({ + "type": "http_tunnel", + "id": "http-1", + "enabled": true, + "url": "https://example.com/tunnel.php" + })) + .unwrap(); + let error = sqlite_worker_route(&[layer, ssh_layer("203.0.113.10", "testuser")]).unwrap_err(); + assert!(error.contains("does not support HTTP tunnel"), "{error}"); + } + + #[test] + fn proxy_only_sqlite_uses_remote_worker_validation() { + let mut config = empty_config(); + config.transport_layers = vec![proxy_layer("proxy-1")]; + assert!(sqlite_remote_worker_requested(&config)); + } + + fn proxy_layer(id: &str) -> TransportLayerConfig { + serde_json::from_value(serde_json::json!({ "type": "proxy", - "id": "proxy-1", + "id": id, "enabled": true, "host": "203.0.113.10", "port": 1080 })) - .unwrap(); - let error = ssh_hops(&[layer]).unwrap_err(); - assert!(error.contains("proxy or HTTP"), "{error}"); + .unwrap() } fn ssh_layer(host: &str, user: &str) -> TransportLayerConfig { diff --git a/src-tauri/src/commands/connection.rs b/src-tauri/src/commands/connection.rs index 35e099b485..bde301e5f6 100644 --- a/src-tauri/src/commands/connection.rs +++ b/src-tauri/src/commands/connection.rs @@ -918,7 +918,7 @@ async fn save_connection_configs( removed_ids: Vec, ) -> Result<(), String> { for config in configs { - if config.db_type == DatabaseType::Sqlite && !db::sqlite_worker::sqlite_ssh_worker_requested(config) { + if config.db_type == DatabaseType::Sqlite && !db::sqlite_worker::sqlite_remote_worker_requested(config) { db::sqlite::validate_persistent_attachments( &config.host, &config.password, @@ -1093,12 +1093,14 @@ async fn connect_sqlite_from_config_with_state( connection_id: &str, config: &ConnectionConfig, ) -> Result { - if db::sqlite_worker::sqlite_ssh_worker_requested(config) { + if db::sqlite_worker::sqlite_remote_worker_requested(config) { let state = state.ok_or_else(|| "Remote SQLite over SSH is only available in the DBX Desktop app".to_string())?; let transport_layers = state.resolved_transport_layers(config).await?; let worker = db::sqlite_worker::connect_sqlite_worker( &state.tunnels, + &state.proxy_tunnels, + &state.http_tunnels, &state.agent_manager, state.storage.data_dir(), connection_id, @@ -1740,7 +1742,7 @@ pub async fn connect_db( client_attempt: Option, ) -> Result { let config = config.canonicalized(); - if config.db_type == DatabaseType::Sqlite && !db::sqlite_worker::sqlite_ssh_worker_requested(&config) { + if config.db_type == DatabaseType::Sqlite && !db::sqlite_worker::sqlite_remote_worker_requested(&config) { db::sqlite::validate_persistent_attachments( &config.host, &config.password, @@ -2190,7 +2192,7 @@ pub async fn connection_final_proxy_port( return Err("Connection has no configured transport layers".to_string()); } if runtime_config.db_type == DatabaseType::Sqlite - && !db::sqlite_worker::sqlite_ssh_worker_requested(&runtime_config) + && !db::sqlite_worker::sqlite_remote_worker_requested(&runtime_config) { db::sqlite::validate_persistent_attachments( &runtime_config.host,