Skip to content

Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.

fix(ssh): Share with team never shares a home directory

reviewc84cb8acff00
diff --git a/CLAUDE.md b/CLAUDE.md
index 51320eaad..210a80249 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -8429,9 +8429,21 @@ SSH project's "Share with team…" installs (or just probes) nodeterm-server on
login user, runs `team bootstrap` (init + owner + adoption by real path + share, one idempotent
admin verb), hands the terminals over (`team resume`) and joins. The renderer sequences it
(`lib/shareSshTeam.ts`, pure, every effect injected), main runs each step as ONE generated command
-over the ControlMaster (`main/remote-ssh/share-team.ts`; the server binary, `main.cjs` and data dir
-come from the cached, validated probe, never from the renderer), and every command is built in
-`core/remote-ssh/share-team-remote.ts` and run under a real `/bin/sh` by its test. The invariants:
+over the ControlMaster (`main/remote-ssh/share-team.ts`; the server binary, `main.cjs`, data dir and
+the adopted folder come from the cached, validated probe, never from the renderer), and every command
+is built in `core/remote-ssh/share-team-remote.ts` and run under a real `/bin/sh` by its test. The
+invariants:
+
+- **Never a home directory, at three layers.** A new SSH project's folder is `~`, and every teammate,
+ Viewers included, may `fs:read` anything under a shared folder (the jail is the shared root and
+ nothing else), so sharing the home hands out `~/.ssh`, the agents' credentials and the hook
+ tokens. The probe prints the home's real path (`homeReal`); `sharePlan` refuses the root, the home
+ and any ancestor of it, segment-wise (`SHARE_REFUSAL.homeFolder` / `homeAncestor`), and a home it
+ could not read refuses rather than guess (`homeUnknown`). Main re-reads the cached probe's plan
+ before every step (install only for a plan that does not refuse, bootstrap and resume only for a
+ ready one) and bootstrap adopts THAT probe's folder; `bootstrap(projectId)` takes no path. The
+ server's `adoptFolderNow` refuses the same set on real paths (`E_BAD_CWD`, against
+ `os.homedir()`), so a hand-run `team bootstrap --adopt ~` is refused too.
- **Handover ordering: nothing ends before `bootstrap` succeeded; nothing is resumed before its old
session is VERIFIED gone.** The kill runs on `nodeterm-rmt` ONLY (`RMT_TMUX_SOCKET`), with the
diff --git a/docs/hosted-team-relay.md b/docs/hosted-team-relay.md
index 30f834efc..2f9d0ffc6 100644
--- a/docs/hosted-team-relay.md
+++ b/docs/hosted-team-relay.md
@@ -97,8 +97,10 @@ One idempotent call, in this order:
2. **Owner.** Makes the device key an owner, as `team add-owner` does. A member is promoted; an
existing owner is left as it is.
3. **Adopt.** Adds the folder to this core's workspace. `--adopt` must be an absolute path to an
- existing directory, and it is resolved with `realpath`: a folder already in the workspace (by
- real path) is reused, never added twice, and reopened if it was closed. A folder with a
+ existing directory, and it is resolved with `realpath`. The root, this user's home directory and
+ any folder that contains it are refused (`E_BAD_CWD`): every teammate, Viewers included, may
+ read any file under a shared folder, and a home holds the ssh keys and the agents' credentials.
+ A folder already in the workspace (by real path) is reused, never added twice, and reopened if it was closed. A folder with a
`.nodeterm/project.json` is adopted the way the desktop's "Open folder…" adopts one: a fresh
project id, with the node ids (they are the tmux session names), canvas and board kept, and each
node's `~/…` folder expanded to this user's home (an SSH project writes its folders that way). A
@@ -122,7 +124,7 @@ sentence:
| Code | Meaning |
|---|---|
| `E_BAD_KEY` | `--owner-key` is not a canonical 44-character base64 public key. |
-| `E_BAD_CWD` | `--adopt` is not an absolute path, does not exist, or is not a directory. |
+| `E_BAD_CWD` | `--adopt` is not an absolute path, does not exist, is not a directory, or is the root, the home directory or a folder that contains the home. |
| `E_HOSTING_OFF` | Hosting could not start (the scheduler's reason follows), or it stopped before a join code could be issued. |
| `E_ADOPT_FAILED` | The folder's `.nodeterm/project.json`, or this core's own workspace index, is there but cannot be read. Nothing is set aside; fix the file and run it again. |
| `E_BAD_REQUEST` | A malformed request: a bad label, project id or resume list. |
@@ -275,8 +277,10 @@ again.
refused too.
2. **Probe**, one generated command over the project's ControlMaster: the OS and the login, git and
curl, which unit runs nodeterm-server and with which binary, its version, whether it knows
- `team bootstrap`, whether it answers, the project folder's real path, and what each of this
- desktop's remote panes is running. A refusal stops here (see [Refusals](#refusals)).
+ `team bootstrap`, whether it answers, the real paths of the home directory and the project
+ folder, and what each of this desktop's remote panes is running. A refusal stops here (see
+ [Refusals](#refusals)). Main keeps this probe and re-reads its plan before every later step: it
+ installs only for a plan that does not refuse, and bootstraps and resumes only for a ready one.
3. **Confirm.** Cancel changes nothing.
4. **Install**, only when needed, then probe again. The server must now be ready, or the share stops
with nothing changed.
@@ -289,7 +293,8 @@ again.
again in a moment."
8. **Close the SSH project**, non-destructively: it moves to "Recently closed", and its tmux sessions
keep running.
-9. **`team bootstrap`**, as the login user, with the folder's real path.
+9. **`team bootstrap`**, as the login user, with the folder's real path from main's own probe (the
+ renderer names no folder).
10. **Record the handover**: `handedOffTo` now names the team (`hostId`) and the project's id on the
server.
11. **End the sessions, and check.** One generated command kills each node's session on this
@@ -374,6 +379,9 @@ teammate's, still compares the SAS.
| The host has a root (system) install | "This host runs nodeterm-server as a system service (root). Share with team needs a per-user install; see docs/hosted-team-relay.md." |
| The host is not Linux | "Share with team needs a Linux host (nodeterm-server runs on Linux)." |
| The project folder is missing on the host | "The project folder does not exist on the host." |
+| The project folder is your home directory (a new SSH project starts at `~`) | "This project's folder is your home directory. Everyone in the team, Viewers included, could read every file in it. Move the project into its own folder, then share it." |
+| The project folder is `/` or contains your home directory | "This project's folder contains your home directory. Everyone in the team, Viewers included, could read every file in it. Move the project into its own folder, then share it." |
+| The host's home directory could not be read | "Could not read your home directory on the host, so Share with team cannot check that this project's folder is safe to share. Try again." |
| git or curl is missing, and the installer has to run | "Installing nodeterm-server needs git and curl on the host (missing: …)." |
| The folder path contains `'` or `\` | "The folder path contains a quote or backslash, which cannot be passed safely to every login shell." |
| Hosting cannot start | "Could not share: Hosting could not start on the host: …" with the relay's reason; the SSH project is reopened. |
diff --git a/src/core/remote-ssh/share-team-remote.test.ts b/src/core/remote-ssh/share-team-remote.test.ts
index 9a2e93184..aa38c72db 100644
--- a/src/core/remote-ssh/share-team-remote.test.ts
+++ b/src/core/remote-ssh/share-team-remote.test.ts
@@ -135,7 +135,7 @@ describe.skipIf(process.platform === 'win32')('share-team remote shell (real /bi
os: 'Linux', uid: 1000, user: 'alice', home, unit: 'user', node: path.join(bin, 'node'),
dataDir: path.join(home, '.nodeterm-server'), meta: { version: '0.4.0', commit: 'abc1234' },
hasBootstrap: true, statusRc: 0, teamExists: true, adoptCwd: fs.realpathSync(path.join(home, 'proj')),
- have: { git: true, curl: expect.any(Boolean) } // curl is whatever /usr/bin holds on the test machine
+ homeReal: fs.realpathSync(home), have: { git: true, curl: expect.any(Boolean) } // curl is whatever /usr/bin holds on the test machine
})
expect(p.panes).toEqual(expect.arrayContaining([{ session: 'nt-term-a', command: 'claude' }, { session: 'nt-term-b', command: 'bash' }]))
fs.rmSync(path.join(state, 'nt-term-a'))
@@ -151,6 +151,20 @@ describe.skipIf(process.platform === 'win32')('share-team remote shell (real /bi
if ('error' in p) throw new Error(p.error)
expect(p).toMatchObject({ unit: 'none', node: '', main: '', hasBootstrap: false, statusRc: null, adoptCwd: null, meta: null })
})
+ // Symlinks need a privilege a stock Windows account does not hold (and the suite is POSIX-only).
+ it('reports the real path of the home directory, and none when it cannot be entered', async () => {
+ const realHome = path.join(dir, 'real-home')
+ fs.mkdirSync(realHome, { recursive: true })
+ const linkHome = path.join(dir, 'link-home')
+ fs.symlinkSync(realHome, linkHome)
+ const viaLink = parseShareProbe(await sh(shareProbeCommand('~', noSystemUnit()), undefined, { HOME: linkHome }))
+ if ('error' in viaLink) throw new Error(viaLink.error)
+ // `~` there is the home itself, so the plan can tell the two apart only through real paths.
+ expect(viaLink).toMatchObject({ home: linkHome, homeReal: fs.realpathSync(realHome), adoptCwd: fs.realpathSync(realHome) })
+ const gone = parseShareProbe(await sh(shareProbeCommand('/', noSystemUnit()), undefined, { HOME: path.join(dir, 'no-such-home') }))
+ if ('error' in gone) throw new Error(gone.error)
+ expect(gone).toMatchObject({ homeReal: null, adoptCwd: '/' })
+ })
it('a system unit with no user unit is reported as system', async () => {
const bare = path.join(dir, 'sys-home')
fs.mkdirSync(bare, { recursive: true })
diff --git a/src/core/remote-ssh/share-team-remote.ts b/src/core/remote-ssh/share-team-remote.ts
index 092b974ef..c420b56f7 100644
--- a/src/core/remote-ssh/share-team-remote.ts
+++ b/src/core/remote-ssh/share-team-remote.ts
@@ -68,8 +68,9 @@ export const SHARE_INSTALL_SCRIPT = [
/**
* One round trip that tells `sharePlan` everything: the OS and login, whether git/curl exist, which
* unit runs nodeterm-server and with which node + main.cjs + data dir, the install meta, whether
- * that build knows `team bootstrap`, whether the CLI answers `team status`, the project folder's
- * real path, and the live panes on this desktop's remote tmux socket. Read by `parseShareProbe`.
+ * that build knows `team bootstrap`, whether the CLI answers `team status`, the real paths of the
+ * home directory and the project folder, and the live panes on this desktop's remote tmux socket.
+ * Read by `parseShareProbe`.
*
* Bootstrap support is read from main.cjs's text (`BOOTSTRAP_MARKER`), and the server is run only
* when that text is there: under `timeout`, with no stdin. A host with no `timeout` binary does
@@ -90,6 +91,8 @@ export function shareProbeCommand(remoteCwd: string, systemUnit: string = SYSTEM
`printf '##UID %s\\n' "$(id -u 2>/dev/null)"`,
`printf '##USER %s\\n' "$(id -un 2>/dev/null)"`,
`printf '##HOME %s\\n' "$HOME"`,
+ // The home's REAL path: the plan refuses to share the home itself or anything above it.
+ `printf '##HOMEREAL %s\\n' "$(if [ -n "$HOME" ] && cd "$HOME" 2>/dev/null; then pwd -P; fi)"`,
`for t in git curl; do if command -v "$t" >/dev/null 2>&1; then printf '##HAVE %s yes\\n' "$t"; else printf '##HAVE %s no\\n' "$t"; fi; done`,
'U="$HOME/.config/systemd/user/nodeterm-server.service"',
"NODE=''; MAIN=''; DD=''",
@@ -168,6 +171,7 @@ export function parseShareProbe(stdout: string): ShareProbe | { error: string }
statusRc: null,
teamExists: false,
adoptCwd: null,
+ homeReal: null,
panes: []
}
let unitSeen = false
@@ -229,6 +233,9 @@ export function parseShareProbe(stdout: string): ShareProbe | { error: string }
case '##HOME':
probe.home = value
break
+ case '##HOMEREAL':
+ probe.homeReal = value === '' ? null : value
+ break
case '##HAVE': {
const m = /^(git|curl) (yes|no)$/.exec(value)
if (m) probe.have[m[1] as 'git' | 'curl'] = m[2] === 'yes'
diff --git a/src/core/workspace-store.adopt.test.ts b/src/core/workspace-store.adopt.test.ts
index 317ad9775..d413579e5 100644
--- a/src/core/workspace-store.adopt.test.ts
+++ b/src/core/workspace-store.adopt.test.ts
@@ -109,6 +109,25 @@ describe('WorkspaceStore.adoptFolder', () => {
await expect(store.adoptFolder(file, { home: dir })).rejects.toMatchObject({ code: 'E_BAD_CWD' })
})
+ it('E_BAD_CWD for the home directory, the root, or a folder that contains the home (nothing saved)', async () => {
+ // Every teammate, Viewers included, may read any file under a shared folder.
+ const home = folder('home/u')
+ await expect(store.adoptFolder(home, { home })).rejects.toMatchObject({ code: 'E_BAD_CWD' })
+ await expect(store.adoptFolder(path.join(dir, 'home'), { home })).rejects.toMatchObject({ code: 'E_BAD_CWD' })
+ await expect(store.adoptFolder(path.parse(dir).root, { home })).rejects.toMatchObject({ code: 'E_BAD_CWD' })
+ // Judged on real paths: a home reached through a link is still the home.
+ if (process.platform !== 'win32') {
+ const link = path.join(dir, 'home-link')
+ fs.symlinkSync(home, link)
+ await expect(store.adoptFolder(link, { home })).rejects.toMatchObject({ code: 'E_BAD_CWD' })
+ await expect(store.adoptFolder(home, { home: link })).rejects.toMatchObject({ code: 'E_BAD_CWD' })
+ }
+ expect(fs.existsSync(indexFile())).toBe(false)
+ // A folder inside the home, or beside it, is fine.
+ expect((await store.adoptFolder(folder('home/u/proj'), { home })).created).toBe(true)
+ expect((await store.adoptFolder(folder('home/u2'), { home })).created).toBe(true)
+ })
+
it('E_ADOPT_FAILED for a corrupt project file, which is left in place (never sidelined, never adopted empty)', async () => {
const f = folder('delta')
fs.mkdirSync(path.join(f, '.nodeterm'))
diff --git a/src/core/workspace-store.ts b/src/core/workspace-store.ts
index a5ad186ca..dc6ed6998 100644
--- a/src/core/workspace-store.ts
+++ b/src/core/workspace-store.ts
@@ -246,6 +246,20 @@ async function sweepStaleTmp(target: string): Promise<void> {
}
}
+/**
+ * Whether `real` (already a real path) is the filesystem root, the real home directory, or a folder
+ * that contains it. A shared folder is readable by every teammate, Viewers included, and a home
+ * holds the ssh keys, the agents' credentials and nodeterm's own hook tokens. An unreadable home is
+ * judged by the path as given; an empty one only refuses the root.
+ */
+async function containsHome(real: string, home: string): Promise<boolean> {
+ if (path.parse(real).root === real) return true
+ if (!home) return false
+ const homeReal = await fs.realpath(home).catch(() => home)
+ const rel = path.relative(real, homeReal)
+ return rel === '' || (!path.isAbsolute(rel) && rel.split(path.sep)[0] !== '..')
+}
+
/**
* v3 persistence: workspace.json is an index (refs + inline canvases); each local
* project's data lives in <cwd>/.nodeterm/project.json (source of truth). The
@@ -1746,7 +1760,9 @@ export class WorkspaceStore {
* the authority could not read) — and an index this load could not read, which the save below
* would replace with one holding only the adopted project (and, when an earlier load this run did
* read it, `sweepRemovedDataFiles` would then delete every inline project's data file with it).
- * Nothing here sidelines a corrupt file either; it is left in place for the user to fix.
+ * Nothing here sidelines a corrupt file either; it is left in place for the user to fix. The root,
+ * the home directory and any folder containing the home are refused with E_BAD_CWD
+ * (`containsHome`): every teammate, Viewers included, may read any file under a shared folder.
*
* `home` expands the SSH project's `~` paths and drops its SSH-only node flags
* (`localizeAdoptedNode`), on a reused project too: a browser's "Open folder…" or an older
@@ -1775,6 +1791,12 @@ export class WorkspaceStore {
} catch {
throw codedError('E_BAD_CWD', `Not a directory on this host: ${cwd}`)
}
+ if (await containsHome(real, opts.home)) {
+ throw codedError(
+ 'E_BAD_CWD',
+ `Refusing to share ${real}: it is the home directory or contains it, and every teammate, Viewers included, could read every file in it. Share a project folder instead.`
+ )
+ }
// `load` does not queue on `saveChain`, so calling it from this chain step cannot deadlock.
// Read-only (no sideline): adoption must not rename some OTHER project's conflict-marked file.
const workspace = structuredClone(await this.load({ sideline: false }))
diff --git a/src/main/remote-ssh/share-team-ipc.ts b/src/main/remote-ssh/share-team-ipc.ts
index 83e45df15..ab50d0566 100644
--- a/src/main/remote-ssh/share-team-ipc.ts
+++ b/src/main/remote-ssh/share-team-ipc.ts
@@ -13,9 +13,7 @@ export function registerShareTeamIpc(h: ShareTeamHandlers, send: (channel: strin
)
ipcMain.handle(IPC.shareTeamCancelInstall, (_e, projectId: string) => h.cancelInstall(String(projectId)))
ipcMain.handle(IPC.shareTeamFlushMirror, (_e, projectId: string) => h.flushMirror(String(projectId)))
- ipcMain.handle(IPC.shareTeamBootstrap, (_e, projectId: string, adoptCwd: string) =>
- h.bootstrap(String(projectId), String(adoptCwd))
- )
+ ipcMain.handle(IPC.shareTeamBootstrap, (_e, projectId: string) => h.bootstrap(String(projectId)))
ipcMain.handle(IPC.shareTeamKillSessions, (_e, projectId: string, nodeIds: unknown) =>
h.killSessions(String(projectId), Array.isArray(nodeIds) ? nodeIds.map(String) : [])
)
diff --git a/src/main/remote-ssh/share-team.test.ts b/src/main/remote-ssh/share-team.test.ts
index 786fd7f9e..9de2ee076 100644
--- a/src/main/remote-ssh/share-team.test.ts
+++ b/src/main/remote-ssh/share-team.test.ts
@@ -1,5 +1,6 @@
import { describe, it, expect } from 'vitest'
import { createShareTeamHandlers, SHARE_TIMEOUTS, type ShareTeamDeps } from './share-team'
+import { SHARE_REFUSAL } from '../../shared/share-team'
import { encodeJoinCode } from '../../core/relay/join-code'
import { genKeyPair, publicKeyToB64 } from '../../core/relay/e2ee'
import { hostIdFromPublicKeyB64 } from '../../core/relay/relay-id'
@@ -10,7 +11,7 @@ const hostKey = publicKeyToB64(genKeyPair().publicKey)
const CODE = encodeJoinCode({ v: 1, relayEndpoint: 'wss://relay.example', hostId: hostIdFromPublicKeyB64(hostKey), hostPublicKeyB64: hostKey, hostDeviceId: 'dev', label: 'box' })
const PROBE_OUT = [
- '##NTP 1', '##OS Linux', '##UID 1000', '##USER alice', '##HOME /home/alice', '##HAVE git yes', '##HAVE curl yes',
+ '##NTP 1', '##OS Linux', '##UID 1000', '##USER alice', '##HOME /home/alice', '##HOMEREAL /home/alice', '##HAVE git yes', '##HAVE curl yes',
'##UNIT user', '##NODE /usr/bin/node', '##MAIN /home/alice/app/out/server/main.cjs', '##DATADIR /home/alice/.nodeterm-server',
'##BOOTSTRAP yes', '##STATUSRC 0', '##STATUS', '{"enabled":true,"off":null}', '##STATUSEND',
'##CWD /home/alice/proj', '##PANES', 'nt-term-a|claude', 'nt-term-b|npm', '##PANESEND', '##END'
@@ -92,17 +93,42 @@ describe('share-team handlers', () => {
const { h } = deps({ replies: [PROBE_OUT, '##NTP 1\n##OS Linux\n'] })
await h.probe('p', [])
expect(await h.probe('p', [])).toMatchObject({ ok: false, error: expect.stringMatching(/did not finish/) })
- expect(await h.bootstrap('p', '/home/alice/proj')).toMatchObject({ ok: false, code: 'E_NOT_PROBED' })
+ expect(await h.bootstrap('p')).toMatchObject({ ok: false, code: 'E_NOT_PROBED' })
})
it('bootstrap needs a ready probe first', async () => {
const { h } = deps()
- expect(await h.bootstrap('p', '/home/alice/proj')).toMatchObject({ ok: false, code: 'E_NOT_PROBED' })
+ expect(await h.bootstrap('p')).toMatchObject({ ok: false, code: 'E_NOT_PROBED' })
+ })
+ it('bootstrap and install never run against a probe whose plan refuses (here: the home directory itself)', async () => {
+ // The folder Viewers could read is the whole home: ~/.ssh, agent credentials, hook tokens.
+ const home = PROBE_OUT.replace('##CWD /home/alice/proj', '##CWD /home/alice')
+ const { h, calls } = deps({ replies: [home] })
+ const probed = await h.probe('p', [])
+ expect(probed).toMatchObject({ ok: true, plan: { kind: 'refuse', reason: SHARE_REFUSAL.homeFolder } })
+ expect(await h.bootstrap('p')).toEqual({ ok: false, code: 'E_NOT_PROBED', error: SHARE_REFUSAL.homeFolder })
+ expect(await h.install('p', () => {})).toEqual({ ok: false, code: 'E_NOT_PROBED', error: SHARE_REFUSAL.homeFolder })
+ expect(await h.resume('p', 'project-1', [])).toMatchObject({ ok: false, code: 'E_NOT_PROBED' })
+ expect(calls).toHaveLength(1) // the probe, and nothing after it
+ })
+ it('bootstrap needs a READY plan: a server that is installed but not answering is installed first', async () => {
+ const down = PROBE_OUT.replace('##STATUSRC 0', '##STATUSRC 1')
+ const { h, calls } = deps({ replies: [down] })
+ expect(await h.probe('p', [])).toMatchObject({ ok: true, plan: { kind: 'install', reason: 'not-running' } })
+ expect(await h.bootstrap('p')).toMatchObject({ ok: false, code: 'E_NOT_PROBED' })
+ expect(calls).toHaveLength(1)
+ })
+ it('install needs a probe first', async () => {
+ let ran = false
+ const { h } = deps({ runInstall: async () => ((ran = true), { exitCode: 0 }) })
+ expect(await h.install('p', () => {})).toMatchObject({ ok: false, code: 'E_NOT_PROBED' })
+ expect(ran).toBe(false)
})
it('bootstrap: passes the owner key, a control-free label and the folder; validates the join code', async () => {
const good = GOOD()
+ // The folder comes from the cached probe's real path, never from the caller.
const { h, calls } = deps({ replies: [PROBE_OUT, cli(good)] })
await h.probe('p', [])
- const r = await h.bootstrap('p', '/home/alice/proj')
+ const r = await h.bootstrap('p')
expect(r).toMatchObject({ ok: true, result: good })
const cmd = lastArg(calls[1])
expect(cmd).toContain(OWNER)
@@ -110,39 +136,47 @@ describe('share-team handlers', () => {
expect(cmd).toContain("'/home/alice/proj'")
expect(calls[1].timeoutMs).toBe(SHARE_TIMEOUTS.bootstrap)
})
+ it('bootstrap adopts the folder of the LATEST probe (a re-probe after an install replaces the cache)', async () => {
+ const { h, calls } = deps({ replies: [PROBE_OUT.replace('##CWD /home/alice/proj', '##CWD /home/alice/old'), PROBE_OUT, cli(GOOD())] })
+ await h.probe('p', [])
+ await h.probe('p', [])
+ expect(await h.bootstrap('p')).toMatchObject({ ok: true })
+ expect(lastArg(calls[2])).toContain("'/home/alice/proj'")
+ expect(lastArg(calls[2])).not.toContain('/home/alice/old')
+ })
it('bootstrap: a label with an apostrophe or backslash goes through with them removed', async () => {
const { h, calls } = deps({ label: "Enes's \\Mac", replies: [PROBE_OUT, cli(GOOD())] })
await h.probe('p', [])
- expect(await h.bootstrap('p', '/home/alice/proj')).toMatchObject({ ok: true })
+ expect(await h.bootstrap('p')).toMatchObject({ ok: true })
expect(lastArg(calls[1])).toContain("'Eness Mac'")
})
it('bootstrap: an over-long label is capped, never refused', async () => {
const { h, calls } = deps({ label: 'x'.repeat(80), replies: [PROBE_OUT, cli(GOOD())] })
await h.probe('p', [])
- expect(await h.bootstrap('p', '/home/alice/proj')).toMatchObject({ ok: true })
+ expect(await h.bootstrap('p')).toMatchObject({ ok: true })
expect(lastArg(calls[1])).toContain(`'${'x'.repeat(60)}'`)
expect(lastArg(calls[1])).not.toContain('x'.repeat(61))
})
it('bootstrap: only the known result fields come back', async () => {
const { h } = deps({ replies: [PROBE_OUT, cli({ ...GOOD(), extra: 'ignored' })] })
await h.probe('p', [])
- const r = await h.bootstrap('p', '/home/alice/proj')
+ const r = await h.bootstrap('p')
expect(r.ok && Object.keys(r.result).sort()).toEqual(['created', 'hostId', 'hosting', 'joinCode', 'projectId', 'projectName'])
})
it('bootstrap: a server refusal keeps its code; a join code for another host is refused', async () => {
const { h } = deps({ replies: [PROBE_OUT, cli({ ok: false, code: 'E_HOSTING_OFF', error: 'refused (403)' }, 1)] })
await h.probe('p', [])
- expect(await h.bootstrap('p', '/x')).toEqual({ ok: false, code: 'E_HOSTING_OFF', error: 'refused (403)' })
+ expect(await h.bootstrap('p')).toEqual({ ok: false, code: 'E_HOSTING_OFF', error: 'refused (403)' })
const forged = { hostId: 'someone-else', projectId: 'project-1', projectName: 'p', joinCode: CODE, hosting: 'up', created: { team: false, owner: false, project: false, share: false } }
const d2 = deps({ replies: [PROBE_OUT, cli(forged)] })
await d2.h.probe('p', [])
- expect(await d2.h.bootstrap('p', '/x')).toMatchObject({ ok: false, error: expect.stringMatching(/join code/i) })
+ expect(await d2.h.bootstrap('p')).toMatchObject({ ok: false, error: expect.stringMatching(/join code/i) })
})
it('bootstrap: a refusal code outside the E_* shape is dropped, and a malformed result is refused', async () => {
const { h } = deps({ replies: [PROBE_OUT, cli({ ok: false, code: 'nope', error: 'no' }, 1), cli({ ...GOOD(), hosting: 'down' })] })
await h.probe('p', [])
- expect(await h.bootstrap('p', '/x')).toEqual({ ok: false, error: 'no' })
- expect(await h.bootstrap('p', '/x')).toMatchObject({ ok: false })
+ expect(await h.bootstrap('p')).toEqual({ ok: false, error: 'no' })
+ expect(await h.bootstrap('p')).toMatchObject({ ok: false })
})
it('bootstrap: a key that cannot be read is a reply, never a rejection, and keeps its code', async () => {
const locked = async (): Promise<string> => {
@@ -150,7 +184,7 @@ describe('share-team handlers', () => {
}
const { h, calls } = deps({ ownerKey: locked, replies: [PROBE_OUT] })
await h.probe('p', [])
- expect(await h.bootstrap('p', '/x')).toEqual({ ok: false, code: 'E_PEER_KEY_LOCKED', error: 'The keyring is locked.' })
+ expect(await h.bootstrap('p')).toEqual({ ok: false, code: 'E_PEER_KEY_LOCKED', error: 'The keyring is locked.' })
expect(calls).toHaveLength(1)
})
it('killSessions: refuses an unsafe id before running anything; parses per-node states', async () => {
@@ -196,12 +230,14 @@ describe('share-team handlers', () => {
let release: (v: { exitCode: number }) => void = () => {}
let seenSignal: AbortSignal | null = null
const { h } = deps({
+ replies: [PROBE_OUT],
runInstall: (_p, script, onChunk, signal) => {
seenSignal = signal
onChunk(script.includes('install-server.sh') ? 'installing\n' : '?')
return new Promise((r) => (release = r))
}
})
+ await h.probe('p', [])
const chunks: string[] = []
const first = h.install('p', (t) => chunks.push(t))
expect(await h.install('p', () => {})).toEqual({ ok: false, error: 'An install is already running.' })
diff --git a/src/main/remote-ssh/share-team.ts b/src/main/remote-ssh/share-team.ts
index e1897e024..735cb4e3b 100644
--- a/src/main/remote-ssh/share-team.ts
+++ b/src/main/remote-ssh/share-team.ts
@@ -11,7 +11,10 @@
// its own reply is refused.
//
// The probe is cached per project. `bootstrap` and `resume` run the server binary, main.cjs and data
-// dir from that cached, validated probe, never from paths the renderer sends.
+// dir from that cached, validated probe, never from paths the renderer sends, and bootstrap adopts
+// the folder that probe resolved. Each verb also re-asks the probe's plan: a host the plan refuses
+// (a home folder Viewers could read, a root login, a system install) is never installed on or run
+// against, whatever the renderer asks for.
//
// Electron-free on purpose (only core, shared and the bookmark TYPE), so it is unit-tested directly;
// share-team-ipc.ts is the only file that touches `ipcMain`. Every handler answers a `ShareReply`
@@ -41,6 +44,7 @@ import {
type BootstrapResult,
type ResumeResultEntry,
type ResumeStatus,
+ type SharePlan,
type ShareProbe,
type ShareReply,
type ShareTeamApi
@@ -184,10 +188,21 @@ export function createShareTeamHandlers(deps: ShareTeamDeps): ShareTeamHandlers
const probes = new Map<string, ShareProbe>()
const installs = new Map<string, AbortController>()
- /** The cached probe, when it found a server that can run `team bootstrap`. */
- const readyProbe = (projectId: string): ShareProbe | undefined => {
- const p = probes.get(projectId)
- return p && p.hasBootstrap && p.node && p.main ? p : undefined
+ /** The cached probe and its plan. A plan that refuses answers with its own reason, under the
+ * not-probed code: nothing ran, and the renderer must not read it as a server failure. */
+ const plannedProbe = (projectId: string): { probe: ShareProbe; plan: SharePlan } | ShareFail => {
+ const probe = probes.get(projectId)
+ if (!probe) return NOT_PROBED
+ const plan = sharePlan(probe)
+ return plan.kind === 'refuse' ? fail(plan.reason, NOT_PROBED.code) : { probe, plan }
+ }
+ /** The cached probe, only when its plan says the host can take the share now. */
+ const readyProbe = (projectId: string): (ShareProbe & { adoptCwd: string }) | ShareFail => {
+ const planned = plannedProbe(projectId)
+ if ('ok' in planned) return planned
+ const { probe, plan } = planned
+ // `ready` implies a folder (the plan refuses a missing one); the check only narrows the type.
+ return plan.kind === 'ready' && probe.adoptCwd !== null ? { ...probe, adoptCwd: probe.adoptCwd } : NOT_PROBED
}
return {
@@ -219,6 +234,8 @@ export function createShareTeamHandlers(deps: ShareTeamDeps): ShareTeamHandlers
async install(projectId, onChunk) {
try {
if (!deps.ref(projectId)) return NOT_CONNECTED
+ const planned = plannedProbe(projectId)
+ if ('ok' in planned) return planned
if (installs.has(projectId)) return fail('An install is already running.')
const ctrl = new AbortController()
installs.set(projectId, ctrl)
@@ -268,18 +285,18 @@ export function createShareTeamHandlers(deps: ShareTeamDeps): ShareTeamHandlers
}
},
- async bootstrap(projectId, adoptCwd) {
+ async bootstrap(projectId) {
try {
const ref = deps.ref(projectId)
if (!ref) return NOT_CONNECTED
const probe = readyProbe(projectId)
- if (!probe) return NOT_PROBED
+ if ('ok' in probe) return probe
const label = ownerLabelFor(deps.ownerLabel())
const args = [
'bootstrap',
...flag('owner-key', await deps.ownerKey()),
...(label ? flag('owner-label', label) : []),
- ...flag('adopt', adoptCwd),
+ ...flag('adopt', probe.adoptCwd),
'--json'
]
const r = await deps.run(childArgs(ref.conn, ref.controlPath, teamCliCommand(probe, args)), undefined, SHARE_TIMEOUTS.bootstrap)
@@ -325,7 +342,7 @@ export function createShareTeamHandlers(deps: ShareTeamDeps): ShareTeamHandlers
const ref = deps.ref(projectId)
if (!ref) return NOT_CONNECTED
const probe = readyProbe(projectId)
- if (!probe) return NOT_PROBED
+ if ('ok' in probe) return probe
const idProblem = projectIdProblem(serverProjectId)
if (idProblem) return fail(idProblem)
const list = parseResumeSessions(sessions)
diff --git a/src/preload/index.ts b/src/preload/index.ts
index 3ddc71f36..ee0bb5d6f 100644
--- a/src/preload/index.ts
+++ b/src/preload/index.ts
@@ -331,7 +331,7 @@ const api: NodeTerminalApi = {
return () => ipcRenderer.removeListener(IPC.shareTeamInstallOutput, h)
},
flushMirror: (projectId) => ipcRenderer.invoke(IPC.shareTeamFlushMirror, projectId),
- bootstrap: (projectId, adoptCwd) => ipcRenderer.invoke(IPC.shareTeamBootstrap, projectId, adoptCwd),
+ bootstrap: (projectId) => ipcRenderer.invoke(IPC.shareTeamBootstrap, projectId),
killSessions: (projectId, nodeIds) => ipcRenderer.invoke(IPC.shareTeamKillSessions, projectId, nodeIds),
resume: (projectId, serverProjectId, sessions) =>
ipcRenderer.invoke(IPC.shareTeamResume, projectId, serverProjectId, sessions),
diff --git a/src/renderer/bridge/stubs.test.ts b/src/renderer/bridge/stubs.test.ts
index e71a45ebc..cc918f19c 100644
--- a/src/renderer/bridge/stubs.test.ts
+++ b/src/renderer/bridge/stubs.test.ts
@@ -66,7 +66,7 @@ describe('bridge stubs', () => {
await expect(s.shareTeam.install('p')).rejects.toMatchObject({ code: E_UNSUPPORTED })
await expect(s.shareTeam.cancelInstall('p')).rejects.toMatchObject({ code: E_UNSUPPORTED })
await expect(s.shareTeam.flushMirror('p')).rejects.toMatchObject({ code: E_UNSUPPORTED })
- await expect(s.shareTeam.bootstrap('p', '/x')).rejects.toMatchObject({ code: E_UNSUPPORTED })
+ await expect(s.shareTeam.bootstrap('p')).rejects.toMatchObject({ code: E_UNSUPPORTED })
await expect(s.shareTeam.killSessions('p', [])).rejects.toMatchObject({ code: E_UNSUPPORTED })
await expect(s.shareTeam.resume('p', 'project-1', [])).rejects.toMatchObject({ code: E_UNSUPPORTED })
await expect(s.shareTeam.seedBookmark('code')).rejects.toMatchObject({ code: E_UNSUPPORTED })
diff --git a/src/renderer/lib/shareSshTeam.test.ts b/src/renderer/lib/shareSshTeam.test.ts
index 996b3cb2e..928a27329 100644
--- a/src/renderer/lib/shareSshTeam.test.ts
+++ b/src/renderer/lib/shareSshTeam.test.ts
@@ -318,17 +318,12 @@ describe('runShare', () => {
expect(log.lastIndexOf('probe')).toBeGreaterThan(log.indexOf('install'))
expect(log.indexOf('release')).toBeGreaterThan(log.lastIndexOf('probe'))
})
- it('bootstraps with the folder the re-probe after an install resolved', async () => {
- let n = 0
+ it('bootstrap names no folder: main adopts the one its own latest probe resolved', async () => {
const { deps } = setup()
- const seen: string[] = []
- deps.api.probe = async () =>
- (n++ === 0
- ? { ...READY, plan: { kind: 'install', reason: 'missing' } }
- : { ...READY, probe: { adoptCwd: '/srv/proj', teamExists: false } }) as never
- deps.api.bootstrap = async (_p, cwd) => (seen.push(cwd), BOOT as never)
+ const seen: unknown[][] = []
+ deps.api.bootstrap = async (...args: unknown[]) => (seen.push(args), BOOT as never)
await runShare(deps, INPUT)
- expect(seen).toEqual(['/srv/proj'])
+ expect(seen).toEqual([['ssh-1']])
})
it('says a shared install and re-probe failure once', async () => {
const { deps } = setup()
diff --git a/src/renderer/lib/shareSshTeam.ts b/src/renderer/lib/shareSshTeam.ts
index 80d43abc6..0bfb9d787 100644
--- a/src/renderer/lib/shareSshTeam.ts
+++ b/src/renderer/lib/shareSshTeam.ts
@@ -26,7 +26,6 @@ import { peekJoinCode } from '@shared/relay-join-code'
import { SAFE_SESSION_ID } from '@shared/session-id'
import {
SHARE_MAX_TERMINALS,
- SHARE_REFUSAL,
type ResumeEntry,
type ShareReply,
type ShareTeamApi
@@ -195,7 +194,7 @@ export async function runShare(deps: ShareDeps, input: ShareInput): Promise<Shar
const ids = terminals.map((n) => n.nodeId)
phase('probing')
- let probed = await call(() => api.probe(projectId, ids))
+ const probed = await call(() => api.probe(projectId, ids))
if (!probed.ok) return failed('probing', probed.error, false)
const plan = probed.plan
if (plan.kind === 'refuse') return { kind: 'refused', reason: plan.reason }
@@ -226,13 +225,7 @@ export async function runShare(deps: ShareDeps, input: ShareInput): Promise<Shar
// A dead connection fails the install and the re-probe with the same message: say it once.
return failed('checking-install', why && why !== base ? `${base} ${why}` : base, false)
}
- probed = again
}
- // The folder the server adopts comes from the LATEST probe. A ready plan implies it exists (the
- // plan refuses a missing folder); this only narrows the type.
- const adoptCwd = probed.probe.adoptCwd
- if (adoptCwd === null) return { kind: 'refused', reason: SHARE_REFUSAL.noFolder }
-
phase('releasing')
try {
await deps.prepare()
@@ -282,7 +275,8 @@ export async function runShare(deps: ShareDeps, input: ShareInput): Promise<Shar
}
phase('bootstrapping')
- const booted = await call(() => api.bootstrap(projectId, adoptCwd))
+ // The folder the server adopts is the one main's latest probe resolved; the renderer names none.
+ const booted = await call(() => api.bootstrap(projectId))
if (!booted.ok) {
// Any bootstrap failure reopens the project, even one without a server code that may have
// left the server set up: the desktop must never stay closed on an unconfirmed handover.
diff --git a/src/shared/share-team.test.ts b/src/shared/share-team.test.ts
index efba9dd4c..303162f8e 100644
--- a/src/shared/share-team.test.ts
+++ b/src/shared/share-team.test.ts
@@ -21,7 +21,7 @@ const probe = (o: Partial<ShareProbe> = {}): ShareProbe => ({
os: 'Linux', uid: 1000, user: 'u', home: '/home/u', have: { git: true, curl: true }, unit: 'user',
node: '/usr/bin/node', main: '/home/u/.nodeterm-server-app/out/server/main.cjs', dataDir: '/home/u/.nodeterm-server',
meta: { version: '0.4.0', commit: 'abc' }, hasBootstrap: true, statusRc: 0, teamExists: false,
- adoptCwd: '/home/u/proj', panes: [], ...o
+ adoptCwd: '/home/u/proj', homeReal: '/home/u', panes: [], ...o
})
describe('sharePlan', () => {
@@ -32,6 +32,22 @@ describe('sharePlan', () => {
expect(sharePlan(probe({ unit: 'system' }))).toEqual({ kind: 'refuse', reason: SHARE_REFUSAL.system })
expect(sharePlan(probe({ adoptCwd: null }))).toEqual({ kind: 'refuse', reason: SHARE_REFUSAL.noFolder })
})
+ it('never shares the home directory, the root, or a folder that contains the home directory', () => {
+ // Viewers may read any file under a shared folder: ~/.ssh, agent credentials, hook tokens.
+ expect(sharePlan(probe({ adoptCwd: '/home/u' }))).toEqual({ kind: 'refuse', reason: SHARE_REFUSAL.homeFolder })
+ expect(sharePlan(probe({ adoptCwd: '/' }))).toEqual({ kind: 'refuse', reason: SHARE_REFUSAL.homeAncestor })
+ expect(sharePlan(probe({ adoptCwd: '/home' }))).toEqual({ kind: 'refuse', reason: SHARE_REFUSAL.homeAncestor })
+ // Segment-wise: a sibling whose name merely starts with the home's is not an ancestor.
+ expect(sharePlan(probe({ adoptCwd: '/home/u2', homeReal: '/home/u2x' }))).toEqual({ kind: 'ready' })
+ expect(sharePlan(probe({ adoptCwd: '/home/u/proj/sub' }))).toEqual({ kind: 'ready' })
+ // Before the installer runs too: a host we would refuse is not worth minutes of install.
+ expect(sharePlan(probe({ adoptCwd: '/home/u', unit: 'none', node: '', main: '' }))).toEqual({
+ kind: 'refuse', reason: SHARE_REFUSAL.homeFolder
+ })
+ })
+ it('a home directory the probe could not read is a refusal, never a guess', () => {
+ expect(sharePlan(probe({ homeReal: null }))).toEqual({ kind: 'refuse', reason: SHARE_REFUSAL.homeUnknown })
+ })
it('install when missing, outdated (no bootstrap verb) or not running', () => {
expect(sharePlan(probe({ unit: 'none', node: '', main: '' }))).toEqual({ kind: 'install', reason: 'missing' })
expect(sharePlan(probe({ hasBootstrap: false }))).toEqual({ kind: 'install', reason: 'outdated' })
diff --git a/src/shared/share-team.ts b/src/shared/share-team.ts
index 34c8fd731..5caf5d2c8 100644
--- a/src/shared/share-team.ts
+++ b/src/shared/share-team.ts
@@ -2,6 +2,7 @@
// verbs. Everything here crosses an ssh exec channel as JSON, so every reader is strict.
import { NODE_ID_MAX } from './safe-id'
import { SESSION_ID_MAX } from './session-id'
+import { isAncestorPath } from './worktree'
/** `team bootstrap --json`'s answer: the team's address, the project it adopted and shared, the
* join code, and what this call changed (every `created` flag false on a re-run). */
@@ -92,6 +93,8 @@ export interface ShareProbe {
teamExists: boolean
/** realpath of the SSH project's remoteCwd on the host; null = it does not exist. */
adoptCwd: string | null
+ /** realpath of the login's home directory; null = it could not be read. */
+ homeReal: string | null
/** Live panes on this desktop's own remote tmux socket (`nt-*` sessions only; a session with
* several panes appears once per pane). */
panes: Array<{ session: string; command: string }>
@@ -108,17 +111,32 @@ export const SHARE_REFUSAL = Object.freeze({
root: 'This SSH login is root. Share with team runs nodeterm-server as your own user, so log in to the project as a regular user and try again.',
system: 'This host runs nodeterm-server as a system service (root). Share with team needs a per-user install; see docs/hosted-team-relay.md.',
nonLinux: 'Share with team needs a Linux host (nodeterm-server runs on Linux).',
- noFolder: 'The project folder does not exist on the host.'
+ noFolder: 'The project folder does not exist on the host.',
+ homeFolder:
+ "This project's folder is your home directory. Everyone in the team, Viewers included, could read every file in it. Move the project into its own folder, then share it.",
+ homeAncestor:
+ "This project's folder contains your home directory. Everyone in the team, Viewers included, could read every file in it. Move the project into its own folder, then share it.",
+ homeUnknown:
+ "Could not read your home directory on the host, so Share with team cannot check that this project's folder is safe to share. Try again."
})
/** Decide from a probe whether the host can take the share now, needs the installer first, or
* cannot take it at all. Refusals come first: installing on a host we would refuse anyway is
- * wasted minutes. git and curl matter only when the installer has to run. */
+ * wasted minutes. git and curl matter only when the installer has to run.
+ *
+ * The folder must not be the home directory, the root, or anything above the home: every
+ * teammate, Viewers included, may read any file under a shared folder, and a home holds the ssh
+ * keys, the agents' credentials and nodeterm's own hook tokens. Both paths are the host's real
+ * paths, compared segment by segment. A home the probe could not read refuses rather than guess. */
export function sharePlan(p: ShareProbe): SharePlan {
if (p.os !== 'Linux') return { kind: 'refuse', reason: SHARE_REFUSAL.nonLinux }
if (p.uid === 0) return { kind: 'refuse', reason: SHARE_REFUSAL.root }
if (p.unit === 'system') return { kind: 'refuse', reason: SHARE_REFUSAL.system }
if (p.adoptCwd === null) return { kind: 'refuse', reason: SHARE_REFUSAL.noFolder }
+ if (p.homeReal === null) return { kind: 'refuse', reason: SHARE_REFUSAL.homeUnknown }
+ if (isAncestorPath(p.adoptCwd, p.homeReal)) {
+ return { kind: 'refuse', reason: isAncestorPath(p.homeReal, p.adoptCwd) ? SHARE_REFUSAL.homeFolder : SHARE_REFUSAL.homeAncestor }
+ }
const reason: 'missing' | 'outdated' | 'not-running' | null =
p.unit === 'none' || !p.node || !p.main
? 'missing'
@@ -155,7 +173,8 @@ export interface ShareTeamApi {
cancelInstall(projectId: string): Promise<void>
onInstallOutput(projectId: string, listener: (text: string) => void): () => void
flushMirror(projectId: string): Promise<ShareReply<{ nodeIds: string[] }>>
- bootstrap(projectId: string, adoptCwd: string): Promise<ShareReply<{ result: BootstrapResult }>>
+ /** Adopts the folder the last probe resolved; the caller names no path. */
+ bootstrap(projectId: string): Promise<ShareReply<{ result: BootstrapResult }>>
killSessions(
projectId: string,
nodeIds: string[]