fix(folders): keep a remote terminal for sessions in mirror subfolders
remote-ssh resolves a session's remote side by reading .remote-ssh.json at the session cwd and never walks up, so a session started in <mirror>/sub silently fell back to a local terminal. The folders route gained POST, which stamps the workspace's connection record into the new subfolder with remotePath adjusted to the matching remote directory; remote-ssh always excludes that file from sync. The client asks for the stamp right after adding such a folder.
This commit is contained in:
parent
d166d4a872
commit
a17f2ef153
|
|
@ -34,7 +34,7 @@ git 历史里 `942babe` 及更早的提交原样保留;重建工作作为 `b30
|
|||
|
||||
| 文件 | 职责 |
|
||||
| --- | --- |
|
||||
| `src/index.ts` | 插件入口。`inject = ['webServer']`,注册 4 组路由:`GET /workspace-groups/config`、`GET|PUT /workspace-groups/tabs`、`PUT /workspace-groups/manual`、`GET|PUT /workspace-groups/folders` |
|
||||
| `src/index.ts` | 插件入口。`inject = ['webServer']`,注册 4 组路由:`GET /workspace-groups/config`、`GET|PUT /workspace-groups/tabs`、`PUT /workspace-groups/manual`、`GET|PUT|POST /workspace-groups/folders` |
|
||||
| `src/host-config.ts` | 读用户 YAML 分类规则(默认 `~/.dsh/workspace-groups.yaml`),校验后以 JSON 下发 |
|
||||
| `src/host-manual.ts` | 运行期分组覆盖(手动分组 + 单工作区归类覆盖),落 `$DSH_HOME/workspace-groups.manual.json` |
|
||||
| `src/host-folders.ts` | 每个工作区的额外文件夹 + 根目录,落 `$DSH_HOME/workspace-groups.folders.json`(写时严格、读时宽容)。另提供 `defaultRemoteMirrorBase()`:`~/.dsh/remote-workspaces`,即 `@zhangfengshun/dsh-remote-ssh` 的本地镜像根,GET 时随文档下发 |
|
||||
|
|
@ -179,3 +179,7 @@ $installed = "C:\Users\qyh15\.dsh\profiles\desktop\node_modules\@dsh-xhl\workspa
|
|||
额外文件夹只能是镜像内子目录(用 `joinSubpath` 拼、`isUnderBase` 判定,**绝不要让
|
||||
用户用原生选择器挑任意本地目录**);`cwd` 分区逻辑照常可用,因为会话本身也在本地跑。
|
||||
真正"服务器上另一个根目录"应当由 SSH 插件单独建成工作区,再用分组归到一起。
|
||||
另外 `POST /workspace-groups/folders` 会在**镜像内新增的子目录**里补一份
|
||||
`.remote-ssh.json`(`remotePath` 拼到对应远端子目录):SSH 插件的 shell wrapper 与
|
||||
部分 fs 桥只在**会话 cwd 本身**找这个标记、不向上遍历,缺了它子目录会话会退化成
|
||||
本地终端。该文件被同步流程永久排除,不会落到服务器。
|
||||
|
|
|
|||
|
|
@ -101,6 +101,10 @@
|
|||
subdirectory of that mirror — i.e. a directory that also exists on the server. Picking an
|
||||
unrelated local directory is refused, because a session there would never sync: a separate
|
||||
remote root should be its own workspace (add it with the SSH plugin), grouped next to this one
|
||||
- Such an extra folder gets a **`.remote-ssh.json` stamped into it** (same connection record,
|
||||
`remotePath` pointing at the matching remote subdirectory). The SSH plugin reads that record at
|
||||
the session cwd only, never walking up, so without it a session in the subdirectory would fall
|
||||
back to a LOCAL terminal. The file is always excluded from sync, so it never reaches the server
|
||||
|
||||
### Search & operations
|
||||
- **Tree-shaped search**: results keep the three-level structure (category → project → matched
|
||||
|
|
|
|||
|
|
@ -82,6 +82,9 @@ DeepSeek峰谷小组件 等)归入一个「DSH 插件」分类文件夹,点
|
|||
这类项目里弹窗会把“挑文件夹”换成**相对路径输入框**,额外文件夹只能是该镜像内的子目录
|
||||
——也就是服务器上同样存在的目录;挑一个无关的本地目录会被拒绝,因为那种会话永远不会同步。
|
||||
服务器上另一个不相干的根目录,应该用 SSH 插件单独建成一个工作区,再用分组放到一起
|
||||
- 远程项目的额外文件夹会**自动补一个 `.remote-ssh.json`**(连接信息,`remotePath` 指向
|
||||
对应远端子目录)。原因:SSH 插件只在“当前工作目录”读这个标记、不向上找,缺了它这些
|
||||
子目录里的会话会退化成**本地终端**。该文件永远被同步排除,不会推到服务器上
|
||||
|
||||
### 搜索与操作
|
||||
- **树形搜索**:命中后仍保留三层树结构(分类 → 项目 → 命中会话),命中行高亮 +
|
||||
|
|
|
|||
|
|
@ -2199,6 +2199,39 @@ window.__ModuleLoader__.load({
|
|||
});
|
||||
if (!response.ok) throw new Error(`PUT ${FOLDERS_ROUTE}: ${response.status}`);
|
||||
}
|
||||
/**
|
||||
* Ask the host to stamp the remote-ssh connection record into an extra folder of
|
||||
* a MIRROR workspace.
|
||||
*
|
||||
* remote-ssh decides "remote backed" by reading `.remote-ssh.json` at the
|
||||
* session cwd and never walks up, so a folder below the mirror root would
|
||||
* otherwise get a local terminal. Best-effort: the folder itself is already
|
||||
* persisted by the time this runs, and a local workspace answers `marked:false`
|
||||
* (nothing to stamp) rather than failing.
|
||||
* @param workspacePath - the workspace's canonical directory (mirror root).
|
||||
* @param folderPath - the extra folder just added.
|
||||
* @param fetchImpl - fetch implementation (injectable for tests).
|
||||
* @returns true when a record was written.
|
||||
*/
|
||||
async function ensureRemoteFolderMarker(workspacePath, folderPath, fetchImpl = fetch) {
|
||||
try {
|
||||
const response = await fetchImpl(FOLDERS_ROUTE, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
workspacePath,
|
||||
folderPath
|
||||
}),
|
||||
cache: "no-store"
|
||||
});
|
||||
if (!response.ok) return false;
|
||||
const body = await response.json();
|
||||
if (typeof body !== "object" || body === null) return false;
|
||||
return body.marked === true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
//#endregion
|
||||
//#region src/client/open-folder.ts
|
||||
/**
|
||||
|
|
@ -4106,6 +4139,7 @@ window.__ModuleLoader__.load({
|
|||
return;
|
||||
}
|
||||
writeFolderEntry(workspaceId, addFolder(entry, path));
|
||||
ensureRemoteFolderMarker(workspace.path, path);
|
||||
};
|
||||
const setFolderRoot = (workspaceId, path) => {
|
||||
writeFolderEntry(workspaceId, setRoot(entryFor(foldersDoc, workspaceId), path));
|
||||
|
|
|
|||
File diff suppressed because one or more lines are too long
124
lib/index.js
124
lib/index.js
|
|
@ -1,5 +1,5 @@
|
|||
import { mkdir, open, readFile, rename, unlink } from "node:fs/promises";
|
||||
import { dirname, resolve } from "node:path";
|
||||
import { mkdir, open, readFile, rename, unlink, writeFile } from "node:fs/promises";
|
||||
import { dirname, relative, resolve, sep } from "node:path";
|
||||
import { homedir } from "node:os";
|
||||
//#region node_modules/.pnpm/js-yaml@4.3.1/node_modules/js-yaml/dist/js-yaml.mjs
|
||||
function getDefaultExportFromCjs(x) {
|
||||
|
|
@ -3170,6 +3170,95 @@ async function writeFoldersDocument(path, document) {
|
|||
throw error;
|
||||
}
|
||||
}
|
||||
/** Connection record of the remote-ssh plugin at a mirror root. */
|
||||
const REMOTE_MARKER_FILE_NAME = ".remote-ssh.json";
|
||||
/**
|
||||
* Read the remote-ssh connection record of a directory.
|
||||
* @param dir - directory that may hold the record (a mirror root, usually).
|
||||
* @returns the record, or null when the directory is not remote-backed.
|
||||
*/
|
||||
async function readRemoteMarker(dir) {
|
||||
let text;
|
||||
try {
|
||||
text = await readFile(resolve(dir, REMOTE_MARKER_FILE_NAME), "utf8");
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
let parsed;
|
||||
try {
|
||||
parsed = JSON.parse(text);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return null;
|
||||
const row = parsed;
|
||||
if (typeof row.host !== "string" || row.host === "") return null;
|
||||
if (typeof row.user !== "string" || row.user === "") return null;
|
||||
const port = typeof row.port === "number" && Number.isInteger(row.port) && row.port > 0 ? row.port : 22;
|
||||
const remotePath = typeof row.remotePath === "string" ? row.remotePath.trim() : "";
|
||||
if (remotePath === "") return null;
|
||||
return {
|
||||
...typeof row.profileId === "string" && row.profileId !== "" ? { profileId: row.profileId } : {},
|
||||
host: row.host,
|
||||
port,
|
||||
user: row.user,
|
||||
...typeof row.keyPath === "string" ? { keyPath: row.keyPath } : {},
|
||||
...typeof row.proxyJump === "string" && row.proxyJump !== "" ? { proxyJump: row.proxyJump } : {},
|
||||
remotePath
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Join a remote path with a mirror-relative subpath.
|
||||
*
|
||||
* The remote path is POSIX (the server's), so this never uses `node:path`:
|
||||
* a Windows host would otherwise hand `/home/me/proj\data` to the remote shell.
|
||||
* @param remotePath - the workspace's remote root (`~`, `~/proj`, `/srv/proj`).
|
||||
* @param relativePath - subpath inside the mirror, either separator style.
|
||||
* @returns the remote counterpart, or null for an empty or escaping subpath.
|
||||
*/
|
||||
function remoteSubpath(remotePath, relativePath) {
|
||||
const rel = relativePath.trim().replace(/\\/gu, "/").replace(/^\/+|\/+$/gu, "");
|
||||
if (rel === "") return null;
|
||||
if (rel.split("/").some((segment) => segment === ".." || segment === ".")) return null;
|
||||
const base = remotePath === "~" ? "~" : remotePath.replace(/\/+$/u, "");
|
||||
return base === "" ? rel : `${base}/${rel}`;
|
||||
}
|
||||
/**
|
||||
* Stamp the remote-ssh connection record into a subdirectory of a mirror, so
|
||||
* that sessions started there keep a remote terminal (see the block comment).
|
||||
*
|
||||
* A workspace that is not remote-backed is left untouched: no record at the
|
||||
* workspace root means the plugin has nothing to reproduce.
|
||||
* @param workspacePath - the workspace's canonical directory (the mirror root).
|
||||
* @param folderPath - subdirectory added as an extra folder.
|
||||
* @returns `{ marked: false }` for a local workspace, otherwise the remote path
|
||||
* written into the subdirectory record.
|
||||
*/
|
||||
async function ensureRemoteMarker(workspacePath, folderPath) {
|
||||
const base = resolve(workspacePath);
|
||||
const folder = resolve(folderPath);
|
||||
const rel = relative(base, folder);
|
||||
if (rel === "" || rel.startsWith("..")) throw invalid("folder is not inside the workspace directory");
|
||||
const marker = await readRemoteMarker(base);
|
||||
if (marker === null) return { marked: false };
|
||||
const remotePath = remoteSubpath(marker.remotePath, rel.split(sep).join("/"));
|
||||
if (remotePath === null) throw invalid("remote subpath is unusable");
|
||||
const record = {
|
||||
...marker.profileId === void 0 ? {} : { profileId: marker.profileId },
|
||||
host: marker.host,
|
||||
port: marker.port,
|
||||
user: marker.user,
|
||||
...marker.keyPath === void 0 ? {} : { keyPath: marker.keyPath },
|
||||
...marker.proxyJump === void 0 ? {} : { proxyJump: marker.proxyJump },
|
||||
remotePath
|
||||
};
|
||||
await mkdir(folder, { recursive: true });
|
||||
await writeFile(resolve(folder, REMOTE_MARKER_FILE_NAME), JSON.stringify(record, null, 2), "utf8");
|
||||
return {
|
||||
marked: true,
|
||||
remotePath
|
||||
};
|
||||
}
|
||||
//#endregion
|
||||
//#region src/index.ts
|
||||
/** Plugin identity for cordis.yml rows. */
|
||||
|
|
@ -3377,6 +3466,37 @@ function apply(ctx) {
|
|||
res.end(req.method === "HEAD" ? void 0 : body);
|
||||
return;
|
||||
}
|
||||
if (req.method === "POST") {
|
||||
let raw;
|
||||
try {
|
||||
raw = JSON.parse(await readBody(req, MAX_MANUAL_BODY_BYTES));
|
||||
} catch (error) {
|
||||
writeError(res, error instanceof HttpError ? error.status : 400, `workspace-groups: ${error instanceof Error ? error.message : String(error)}`);
|
||||
return;
|
||||
}
|
||||
const payload = typeof raw === "object" && raw !== null ? raw : {};
|
||||
const workspacePath = typeof payload.workspacePath === "string" ? payload.workspacePath.trim() : "";
|
||||
const folderPath = typeof payload.folderPath === "string" ? payload.folderPath.trim() : "";
|
||||
if (workspacePath === "" || folderPath === "") {
|
||||
writeError(res, 400, "workspace-groups: workspacePath and folderPath are required");
|
||||
return;
|
||||
}
|
||||
let result;
|
||||
try {
|
||||
result = await ensureRemoteMarker(workspacePath, folderPath);
|
||||
} catch (error) {
|
||||
writeError(res, 400, `workspace-groups: ${error instanceof Error ? error.message : String(error)}`);
|
||||
return;
|
||||
}
|
||||
const marked = JSON.stringify(result);
|
||||
res.writeHead(200, {
|
||||
"Content-Type": "application/json; charset=utf-8",
|
||||
"Cache-Control": "no-store",
|
||||
"Content-Length": Buffer.byteLength(marked)
|
||||
});
|
||||
res.end(marked);
|
||||
return;
|
||||
}
|
||||
if (req.method !== "PUT") {
|
||||
writeError(res, 405, "method not allowed");
|
||||
return;
|
||||
|
|
|
|||
|
|
@ -42,3 +42,18 @@ export declare function loadFolders(fetchImpl?: typeof fetch): Promise<FoldersSn
|
|||
* @param fetchImpl - fetch implementation (injectable for tests).
|
||||
*/
|
||||
export declare function saveFolders(document: FoldersDocument, fetchImpl?: typeof fetch): Promise<void>;
|
||||
/**
|
||||
* Ask the host to stamp the remote-ssh connection record into an extra folder of
|
||||
* a MIRROR workspace.
|
||||
*
|
||||
* remote-ssh decides "remote backed" by reading `.remote-ssh.json` at the
|
||||
* session cwd and never walks up, so a folder below the mirror root would
|
||||
* otherwise get a local terminal. Best-effort: the folder itself is already
|
||||
* persisted by the time this runs, and a local workspace answers `marked:false`
|
||||
* (nothing to stamp) rather than failing.
|
||||
* @param workspacePath - the workspace's canonical directory (mirror root).
|
||||
* @param folderPath - the extra folder just added.
|
||||
* @param fetchImpl - fetch implementation (injectable for tests).
|
||||
* @returns true when a record was written.
|
||||
*/
|
||||
export declare function ensureRemoteFolderMarker(workspacePath: string, folderPath: string, fetchImpl?: typeof fetch): Promise<boolean>;
|
||||
|
|
|
|||
|
|
@ -58,3 +58,46 @@ export declare function readFoldersDocument(path: string): Promise<FoldersDocume
|
|||
* @param document - validated document to persist.
|
||||
*/
|
||||
export declare function writeFoldersDocument(path: string, document: FoldersDocument): Promise<void>;
|
||||
/** Connection record of the remote-ssh plugin at a mirror root. */
|
||||
export declare const REMOTE_MARKER_FILE_NAME = ".remote-ssh.json";
|
||||
/** The subset of that record this plugin needs to reproduce it. */
|
||||
export interface RemoteMarker {
|
||||
readonly profileId?: string;
|
||||
readonly host: string;
|
||||
readonly port: number;
|
||||
readonly user: string;
|
||||
readonly keyPath?: string;
|
||||
readonly proxyJump?: string;
|
||||
readonly remotePath: string;
|
||||
}
|
||||
/**
|
||||
* Read the remote-ssh connection record of a directory.
|
||||
* @param dir - directory that may hold the record (a mirror root, usually).
|
||||
* @returns the record, or null when the directory is not remote-backed.
|
||||
*/
|
||||
export declare function readRemoteMarker(dir: string): Promise<RemoteMarker | null>;
|
||||
/**
|
||||
* Join a remote path with a mirror-relative subpath.
|
||||
*
|
||||
* The remote path is POSIX (the server's), so this never uses `node:path`:
|
||||
* a Windows host would otherwise hand `/home/me/proj\data` to the remote shell.
|
||||
* @param remotePath - the workspace's remote root (`~`, `~/proj`, `/srv/proj`).
|
||||
* @param relativePath - subpath inside the mirror, either separator style.
|
||||
* @returns the remote counterpart, or null for an empty or escaping subpath.
|
||||
*/
|
||||
export declare function remoteSubpath(remotePath: string, relativePath: string): string | null;
|
||||
/**
|
||||
* Stamp the remote-ssh connection record into a subdirectory of a mirror, so
|
||||
* that sessions started there keep a remote terminal (see the block comment).
|
||||
*
|
||||
* A workspace that is not remote-backed is left untouched: no record at the
|
||||
* workspace root means the plugin has nothing to reproduce.
|
||||
* @param workspacePath - the workspace's canonical directory (the mirror root).
|
||||
* @param folderPath - subdirectory added as an extra folder.
|
||||
* @returns `{ marked: false }` for a local workspace, otherwise the remote path
|
||||
* written into the subdirectory record.
|
||||
*/
|
||||
export declare function ensureRemoteMarker(workspacePath: string, folderPath: string): Promise<{
|
||||
marked: boolean;
|
||||
remotePath?: string;
|
||||
}>;
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
{
|
||||
"name": "@dsh-xhl/workspace-groups",
|
||||
"version": "0.6.1",
|
||||
"version": "0.6.2",
|
||||
"description": "Complete workspace grouping manager for the DSH web sidebar: 分类 → 项目 → 会话 three-level tree with optional per-project folders (multi-root), manual group create/rename/delete, drag-and-drop grouping & ordering with insertion indicator, rule-based auto-classification, tree search, group colour/icon/pin, plus the session tab strip seated in the conversation column head. Sidecar YAML + runtime overlays, zero core-storage intrusion.",
|
||||
"keywords": [
|
||||
"dsh",
|
||||
|
|
|
|||
|
|
@ -56,7 +56,7 @@ import { deriveGroups, deriveSearchGroups, deriveSearchMatches, deriveTopLevel,
|
|||
import { CategoryGlyph, CategoryRow, DND_CATEGORY_TYPE, DND_WORKSPACE_TYPE, FolderRow, hasPluginDragType, RowGroup, SessionRow, WorkspaceRow } from './rows.tsx'
|
||||
import type { WorkspaceGroupsKey } from './locales.ts'
|
||||
import { EMPTY_FOLDERS_DOCUMENT, addFolder, effectiveFolders, entryFor, isUnderBase, joinSubpath, removeFolder, rootOf, samePath, setRoot, type FoldersDocument, type WorkspaceFolderEntry } from '../core/folders.ts'
|
||||
import { loadFolders, saveFolders } from './folders-persist.ts'
|
||||
import { ensureRemoteFolderMarker, loadFolders, saveFolders } from './folders-persist.ts'
|
||||
import { fetchOpenInApps, folderAppId, openPathInApp } from './open-folder.ts'
|
||||
import { QuickPanel } from './QuickPanel.tsx'
|
||||
import { SessionTabs } from './SessionTabs.tsx'
|
||||
|
|
@ -667,6 +667,10 @@ export function GroupsBrowser({
|
|||
return
|
||||
}
|
||||
writeFolderEntry(workspaceId, addFolder(entry, path))
|
||||
// Mirror subdirectory: also stamp the remote-ssh record, otherwise the new
|
||||
// folder's sessions would lose the remote terminal (remote-ssh reads the
|
||||
// record at the cwd only). Fire and forget — the folder row already works.
|
||||
void ensureRemoteFolderMarker(workspace.path, path)
|
||||
}
|
||||
|
||||
const setFolderRoot = (workspaceId: WorkspaceId, path: string): void => {
|
||||
|
|
|
|||
|
|
@ -111,3 +111,38 @@ export async function saveFolders(
|
|||
})
|
||||
if (!response.ok) throw new Error(`PUT ${FOLDERS_ROUTE}: ${response.status}`)
|
||||
}
|
||||
|
||||
/**
|
||||
* Ask the host to stamp the remote-ssh connection record into an extra folder of
|
||||
* a MIRROR workspace.
|
||||
*
|
||||
* remote-ssh decides "remote backed" by reading `.remote-ssh.json` at the
|
||||
* session cwd and never walks up, so a folder below the mirror root would
|
||||
* otherwise get a local terminal. Best-effort: the folder itself is already
|
||||
* persisted by the time this runs, and a local workspace answers `marked:false`
|
||||
* (nothing to stamp) rather than failing.
|
||||
* @param workspacePath - the workspace's canonical directory (mirror root).
|
||||
* @param folderPath - the extra folder just added.
|
||||
* @param fetchImpl - fetch implementation (injectable for tests).
|
||||
* @returns true when a record was written.
|
||||
*/
|
||||
export async function ensureRemoteFolderMarker(
|
||||
workspacePath: string,
|
||||
folderPath: string,
|
||||
fetchImpl: typeof fetch = fetch,
|
||||
): Promise<boolean> {
|
||||
try {
|
||||
const response = await fetchImpl(FOLDERS_ROUTE, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ workspacePath, folderPath }),
|
||||
cache: 'no-store',
|
||||
})
|
||||
if (!response.ok) return false
|
||||
const body: unknown = await response.json()
|
||||
if (typeof body !== 'object' || body === null) return false
|
||||
return (body as { marked?: unknown }).marked === true
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -12,8 +12,8 @@
|
|||
* same reason the manual overlay does: a stale or malformed sidecar must never
|
||||
* freeze the tree.
|
||||
*/
|
||||
import { mkdir, open, readFile, rename, unlink } from 'node:fs/promises'
|
||||
import { dirname, resolve } from 'node:path'
|
||||
import { mkdir, open, readFile, rename, unlink, writeFile } from 'node:fs/promises'
|
||||
import { dirname, relative, resolve, sep } from 'node:path'
|
||||
import { homedir } from 'node:os'
|
||||
import {
|
||||
EMPTY_FOLDERS_DOCUMENT,
|
||||
|
|
@ -255,3 +255,125 @@ export async function writeFoldersDocument(path: string, document: FoldersDocume
|
|||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// remote-ssh markers
|
||||
//
|
||||
// `@zhangfengshun/dsh-remote-ssh` decides "this directory belongs to a remote
|
||||
// workspace" by looking for a `.remote-ssh.json` connection record at the
|
||||
// directory itself (the shell wrapper and several fs bridges read exactly one
|
||||
// path, they do NOT walk up). Its mirror root carries one; a plain subdirectory
|
||||
// of the mirror does not, so a session whose cwd is such a subdirectory falls
|
||||
// back to a LOCAL terminal even though every file under it is remote-backed.
|
||||
//
|
||||
// Stamping the record into the subdirectory fixes that: the record holds the
|
||||
// same connection with `remotePath` adjusted to the matching remote folder, and
|
||||
// remote-ssh always excludes `.remote-ssh.json` from sync, so it never travels
|
||||
// to the server.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/** Connection record of the remote-ssh plugin at a mirror root. */
|
||||
export const REMOTE_MARKER_FILE_NAME = '.remote-ssh.json'
|
||||
|
||||
/** The subset of that record this plugin needs to reproduce it. */
|
||||
export interface RemoteMarker {
|
||||
readonly profileId?: string
|
||||
readonly host: string
|
||||
readonly port: number
|
||||
readonly user: string
|
||||
readonly keyPath?: string
|
||||
readonly proxyJump?: string
|
||||
readonly remotePath: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the remote-ssh connection record of a directory.
|
||||
* @param dir - directory that may hold the record (a mirror root, usually).
|
||||
* @returns the record, or null when the directory is not remote-backed.
|
||||
*/
|
||||
export async function readRemoteMarker(dir: string): Promise<RemoteMarker | null> {
|
||||
let text: string
|
||||
try {
|
||||
text = await readFile(resolve(dir, REMOTE_MARKER_FILE_NAME), 'utf8')
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
let parsed: unknown
|
||||
try {
|
||||
parsed = JSON.parse(text)
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) return null
|
||||
const row = parsed as Record<string, unknown>
|
||||
if (typeof row.host !== 'string' || row.host === '') return null
|
||||
if (typeof row.user !== 'string' || row.user === '') return null
|
||||
const port = typeof row.port === 'number' && Number.isInteger(row.port) && row.port > 0 ? row.port : 22
|
||||
const remotePath = typeof row.remotePath === 'string' ? row.remotePath.trim() : ''
|
||||
if (remotePath === '') return null
|
||||
return {
|
||||
...(typeof row.profileId === 'string' && row.profileId !== '' ? { profileId: row.profileId } : {}),
|
||||
host: row.host,
|
||||
port,
|
||||
user: row.user,
|
||||
...(typeof row.keyPath === 'string' ? { keyPath: row.keyPath } : {}),
|
||||
...(typeof row.proxyJump === 'string' && row.proxyJump !== '' ? { proxyJump: row.proxyJump } : {}),
|
||||
remotePath,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Join a remote path with a mirror-relative subpath.
|
||||
*
|
||||
* The remote path is POSIX (the server's), so this never uses `node:path`:
|
||||
* a Windows host would otherwise hand `/home/me/proj\data` to the remote shell.
|
||||
* @param remotePath - the workspace's remote root (`~`, `~/proj`, `/srv/proj`).
|
||||
* @param relativePath - subpath inside the mirror, either separator style.
|
||||
* @returns the remote counterpart, or null for an empty or escaping subpath.
|
||||
*/
|
||||
export function remoteSubpath(remotePath: string, relativePath: string): string | null {
|
||||
const rel = relativePath.trim().replace(/\\/gu, '/').replace(/^\/+|\/+$/gu, '')
|
||||
if (rel === '') return null
|
||||
if (rel.split('/').some(segment => segment === '..' || segment === '.')) return null
|
||||
const base = remotePath === '~' ? '~' : remotePath.replace(/\/+$/u, '')
|
||||
return base === '' ? rel : `${base}/${rel}`
|
||||
}
|
||||
|
||||
/**
|
||||
* Stamp the remote-ssh connection record into a subdirectory of a mirror, so
|
||||
* that sessions started there keep a remote terminal (see the block comment).
|
||||
*
|
||||
* A workspace that is not remote-backed is left untouched: no record at the
|
||||
* workspace root means the plugin has nothing to reproduce.
|
||||
* @param workspacePath - the workspace's canonical directory (the mirror root).
|
||||
* @param folderPath - subdirectory added as an extra folder.
|
||||
* @returns `{ marked: false }` for a local workspace, otherwise the remote path
|
||||
* written into the subdirectory record.
|
||||
*/
|
||||
export async function ensureRemoteMarker(
|
||||
workspacePath: string,
|
||||
folderPath: string,
|
||||
): Promise<{ marked: boolean; remotePath?: string }> {
|
||||
const base = resolve(workspacePath)
|
||||
const folder = resolve(folderPath)
|
||||
const rel = relative(base, folder)
|
||||
if (rel === '' || rel.startsWith('..')) {
|
||||
throw invalid('folder is not inside the workspace directory')
|
||||
}
|
||||
const marker = await readRemoteMarker(base)
|
||||
if (marker === null) return { marked: false }
|
||||
const remotePath = remoteSubpath(marker.remotePath, rel.split(sep).join('/'))
|
||||
if (remotePath === null) throw invalid('remote subpath is unusable')
|
||||
const record: RemoteMarker = {
|
||||
...(marker.profileId === undefined ? {} : { profileId: marker.profileId }),
|
||||
host: marker.host,
|
||||
port: marker.port,
|
||||
user: marker.user,
|
||||
...(marker.keyPath === undefined ? {} : { keyPath: marker.keyPath }),
|
||||
...(marker.proxyJump === undefined ? {} : { proxyJump: marker.proxyJump }),
|
||||
remotePath,
|
||||
}
|
||||
await mkdir(folder, { recursive: true })
|
||||
await writeFile(resolve(folder, REMOTE_MARKER_FILE_NAME), JSON.stringify(record, null, 2), 'utf8')
|
||||
return { marked: true, remotePath }
|
||||
}
|
||||
|
|
|
|||
41
src/index.ts
41
src/index.ts
|
|
@ -17,6 +17,9 @@
|
|||
* - `PUT /workspace-groups/folders` — replace the folder overlay whole.
|
||||
* Strictly validated (absolute paths, no duplicates, root membership) and
|
||||
* written atomically; the saved document is echoed back.
|
||||
* - `POST /workspace-groups/folders` — stamp the remote-ssh connection record
|
||||
* into an extra folder of a mirror workspace, so sessions started there keep
|
||||
* a remote terminal (see the mirror block comment in host-folders.ts).
|
||||
*
|
||||
* Core workspace.json / session storage is never touched.
|
||||
*/
|
||||
|
|
@ -42,6 +45,7 @@ import {
|
|||
import {
|
||||
defaultFoldersPath,
|
||||
defaultRemoteMirrorBase,
|
||||
ensureRemoteMarker,
|
||||
readFoldersDocument,
|
||||
validateFoldersDocument,
|
||||
writeFoldersDocument,
|
||||
|
|
@ -263,6 +267,43 @@ export function apply(ctx: GroupsContext): void {
|
|||
res.end(req.method === 'HEAD' ? undefined : body)
|
||||
return
|
||||
}
|
||||
if (req.method === 'POST') {
|
||||
// `{ workspacePath, folderPath }` → stamp the remote-ssh connection
|
||||
// record into an extra folder of a MIRROR workspace. The client sends
|
||||
// this right after adding such a folder: remote-ssh reads the record at
|
||||
// the session cwd (it never walks up), so without it a session started
|
||||
// in `<mirror>/sub` would silently get a local terminal.
|
||||
let raw: unknown
|
||||
try {
|
||||
raw = JSON.parse(await readBody(req, MAX_MANUAL_BODY_BYTES))
|
||||
} catch (error) {
|
||||
const status = error instanceof HttpError ? error.status : 400
|
||||
writeError(res, status, `workspace-groups: ${error instanceof Error ? error.message : String(error)}`)
|
||||
return
|
||||
}
|
||||
const payload = typeof raw === 'object' && raw !== null ? raw as Record<string, unknown> : {}
|
||||
const workspacePath = typeof payload.workspacePath === 'string' ? payload.workspacePath.trim() : ''
|
||||
const folderPath = typeof payload.folderPath === 'string' ? payload.folderPath.trim() : ''
|
||||
if (workspacePath === '' || folderPath === '') {
|
||||
writeError(res, 400, 'workspace-groups: workspacePath and folderPath are required')
|
||||
return
|
||||
}
|
||||
let result: { marked: boolean; remotePath?: string }
|
||||
try {
|
||||
result = await ensureRemoteMarker(workspacePath, folderPath)
|
||||
} catch (error) {
|
||||
writeError(res, 400, `workspace-groups: ${error instanceof Error ? error.message : String(error)}`)
|
||||
return
|
||||
}
|
||||
const marked = JSON.stringify(result)
|
||||
res.writeHead(200, {
|
||||
'Content-Type': 'application/json; charset=utf-8',
|
||||
'Cache-Control': 'no-store',
|
||||
'Content-Length': Buffer.byteLength(marked),
|
||||
})
|
||||
res.end(marked)
|
||||
return
|
||||
}
|
||||
if (req.method !== 'PUT') {
|
||||
writeError(res, 405, 'method not allowed')
|
||||
return
|
||||
|
|
|
|||
|
|
@ -30,8 +30,11 @@ const {
|
|||
setRoot,
|
||||
} = await import(coreUrl.href)
|
||||
const {
|
||||
ensureRemoteMarker,
|
||||
parseFoldersDocument,
|
||||
readFoldersDocument,
|
||||
readRemoteMarker,
|
||||
remoteSubpath,
|
||||
validateFoldersDocument,
|
||||
writeFoldersDocument,
|
||||
} = await import(hostUrl.href)
|
||||
|
|
@ -172,5 +175,59 @@ equal(joinSubpath(MIRROR_WS, './ok'), `${MIRROR_WS}\\ok`, 'a leading dot segment
|
|||
equal(folderOfCwd(`${MIRROR_WS}\\data\\file`, MIRROR_WS, entry), `${MIRROR_WS}\\data`, 'sessions under the mirror subpath belong to it')
|
||||
}
|
||||
|
||||
// --- remote-ssh markers ------------------------------------------------------
|
||||
// remote-ssh reads `.remote-ssh.json` at the session cwd only (never walking
|
||||
// up), so an extra folder inside a mirror needs its own record or its sessions
|
||||
// silently lose the remote terminal.
|
||||
equal(remoteSubpath('~/projects/cloud-memory', 'data'), '~/projects/cloud-memory/data', 'a ~ root joins with a slash')
|
||||
equal(remoteSubpath('~', 'data'), '~/data', 'a bare ~ keeps its home meaning')
|
||||
equal(remoteSubpath('/srv/proj/', 'a/b'), '/srv/proj/a/b', 'an absolute remote root joins with a POSIX slash')
|
||||
equal(remoteSubpath('/srv/proj', 'a\\b'), '/srv/proj/a/b', 'a Windows-styled subpath still joins POSIX')
|
||||
equal(remoteSubpath('/srv/proj', '..'), null, 'a parent traversal never reaches the remote shell')
|
||||
equal(remoteSubpath('/srv/proj', 'a/../b'), null, 'an embedded traversal never reaches the remote shell')
|
||||
equal(remoteSubpath('/srv/proj', ' '), null, 'a blank subpath is refused')
|
||||
|
||||
{
|
||||
const mirror = await mkdtemp(join(tmpdir(), 'wg-mirror-verify-'))
|
||||
try {
|
||||
equal(await readRemoteMarker(mirror), null, 'a directory without a record is not remote-backed')
|
||||
const local = await mkdtemp(join(tmpdir(), 'wg-local-verify-'))
|
||||
try {
|
||||
equal(
|
||||
await ensureRemoteMarker(local, join(local, 'sub')),
|
||||
{ marked: false },
|
||||
'a local workspace is left untouched',
|
||||
)
|
||||
const marker = {
|
||||
profileId: 'p-1', host: 'qyhhh.top', port: 22, user: 'ubuntu',
|
||||
keyPath: 'C:\\Users\\me\\.ssh\\id_ed25519', remotePath: '~/projects/cloud-memory',
|
||||
}
|
||||
await writeFile(join(mirror, '.remote-ssh.json'), JSON.stringify(marker, null, 2), 'utf8')
|
||||
equal(await readRemoteMarker(mirror), marker, 'the record round-trips')
|
||||
|
||||
const sub = join(mirror, 'data', 'raw')
|
||||
equal(
|
||||
await ensureRemoteMarker(mirror, sub),
|
||||
{ marked: true, remotePath: '~/projects/cloud-memory/data/raw' },
|
||||
'a nested extra folder gets the remote counterpart of its own path',
|
||||
)
|
||||
equal(
|
||||
await readRemoteMarker(sub),
|
||||
{ ...marker, remotePath: '~/projects/cloud-memory/data/raw' },
|
||||
'the stamped record keeps the connection and only rewrites remotePath',
|
||||
)
|
||||
await assert.rejects(
|
||||
() => ensureRemoteMarker(mirror, join(mirror, '..', 'outside')),
|
||||
/folder is not inside the workspace directory/u,
|
||||
'a folder outside the mirror is refused, never stamped',
|
||||
)
|
||||
} finally {
|
||||
await rm(local, { recursive: true, force: true })
|
||||
}
|
||||
} finally {
|
||||
await rm(mirror, { recursive: true, force: true })
|
||||
}
|
||||
}
|
||||
|
||||
// Success is a single machine-checkable line: the harness pastes this output.
|
||||
process.stdout.write('folders: all assertions passed\n')
|
||||
|
|
|
|||
Loading…
Reference in New Issue