17 files changed
+285
-99
No files matched your search
@@ -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) {
|
||||
<Plus class="mr-1.5 h-3.5 w-3.5" />
|
||||
{{ t("connection.sshHopAdd") }}
|
||||
</Button>
|
||||
<Button v-if="!sqliteSshOnlyTransport" type="button" variant="outline" size="sm" @click="addProxyTunnel">
|
||||
<Button type="button" variant="outline" size="sm" @click="addProxyTunnel">
|
||||
<Plus class="mr-1.5 h-3.5 w-3.5" />
|
||||
{{ t("connection.proxy") }}
|
||||
</Button>
|
||||
<Button v-if="!sqliteSshOnlyTransport" type="button" variant="outline" size="sm" @click="addHttpTunnel">
|
||||
<Button v-if="!sqliteRemoteTransportRestricted" type="button" variant="outline" size="sm" @click="addHttpTunnel">
|
||||
<Plus class="mr-1.5 h-3.5 w-3.5" />
|
||||
{{ t("connection.httpTunnelAdd") }}
|
||||
</Button>
|
||||
@@ -10047,7 +10047,7 @@ function openExternalUrl(url: string) {
|
||||
<span v-else class="text-red-500">{{ t("connection.tunnelProfileMissing") }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div v-if="!selectedLayerProfileId && !sqliteSshOnlyTransport" class="grid grid-cols-4 items-center gap-4">
|
||||
<div v-if="!selectedLayerProfileId" class="grid grid-cols-4 items-center gap-4">
|
||||
<Label :class="connectionLabelSmallClass">Type</Label>
|
||||
<Select :model-value="selectedTransportLayer.type" @update:model-value="(value: any) => changeSelectedTransportLayerType(value)">
|
||||
<SelectTrigger class="col-span-3 h-9">
|
||||
@@ -10056,7 +10056,7 @@ function openExternalUrl(url: string) {
|
||||
<SelectContent>
|
||||
<SelectItem value="ssh">SSH</SelectItem>
|
||||
<SelectItem value="proxy">Proxy</SelectItem>
|
||||
<SelectItem value="http_tunnel">{{ t("connection.httpTunnel") }}</SelectItem>
|
||||
<SelectItem v-if="!sqliteRemoteTransportRestricted" value="http_tunnel">{{ t("connection.httpTunnel") }}</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
@@ -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.",
|
||||
|
||||
@@ -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.",
|
||||
|
||||
@@ -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.",
|
||||
|
||||
@@ -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.",
|
||||
|
||||
@@ -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 データベースの接続にはまだ対応していません。",
|
||||
|
||||
@@ -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 데이터베이스 연결은 아직 지원되지 않습니다.",
|
||||
|
||||
@@ -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.",
|
||||
|
||||
@@ -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.",
|
||||
|
||||
@@ -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.",
|
||||
|
||||
@@ -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 数据库。",
|
||||
|
||||
@@ -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 資料庫。",
|
||||
|
||||
@@ -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<TransportLayerConfig, "type" | "enabled"> {
|
||||
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");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,37 @@
|
||||
import type { TransportLayerConfig } from "@/types/database";
|
||||
|
||||
type SqliteTransportLayer = Pick<TransportLayerConfig, "type" | "enabled">;
|
||||
|
||||
export type SqliteRemoteTransportError = "http_tunnel" | "final_ssh";
|
||||
|
||||
export function isSqliteRemoteTransportLayerType(type: TransportLayerConfig["type"]): boolean {
|
||||
return type === "ssh" || type === "proxy";
|
||||
}
|
||||
|
||||
export function insertSqliteRemoteTransportLayer<T extends SqliteTransportLayer>(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;
|
||||
}
|
||||
Reference in new issue
Block a user