diff --git a/CHANGELOG.md b/CHANGELOG.md index 6d1e013..618a0a5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,11 @@ # Changelog +## [Unreleased] + +### Fixed + +- **A `repoDir` inside an unrelated outer git worktree no longer hijacks the outer repository.** `isRepo()` used `rev-parse --is-inside-work-tree`, which is true for any subdirectory of any worktree, so `ensureRepo()` skipped initialization and wrote the sync identity, `core.autocrlf`, the `origin` remote, and commits into the outer repository (observed: a workspace repo's origin and identity rewritten, a stray whole-tree commit). `isRepo()` now compares `rev-parse --show-toplevel` against `repoDir` by realpath identity: a `repoDir` that is merely a subdirectory of an outer repo takes the init path and gets its own dedicated repository, leaving the outer repo's config, origin, and history untouched. Correctly-placed repoDirs behave exactly as before. Regression tests cover the outer-worktree bootstrap, the root-only `isRepo` semantics, and idempotency. + ## [0.3.1] - 2026-11-14 ### Fixed diff --git a/README.en.md b/README.en.md index 712c687..e13fa76 100644 --- a/README.en.md +++ b/README.en.md @@ -244,6 +244,7 @@ Session files are copied as opaque bytes and never parsed; every git command has ## Security boundaries - **Never silently overwrite.** The append-only three-way merge keeps both sides on any divergence, including delete/modify (modified bytes kept, deletion intent honored); fork files are never deleted, and git never force-pushes, resets, rebases, or switches branches. +- **Dedicated repository.** `repoDir` must be the root of its own git worktree: if it is merely a subdirectory of an unrelated outer repository, the plugin initializes a dedicated mirror repository at `repoDir` and never writes configuration, origin, or commits into the outer repository. - **Path containment.** Files are mirrored as opaque bytes with symlinks refused and every joined path containment-checked (`PATH_UNSAFE` fails loud). - **Sanitized output.** Remote-URL credentials, tokens, and `key=value` secrets are redacted before reaching the model or the log; path display refuses anything outside its root. - **No credential storage.** The plugin stores no credentials; git credentials live in your normal git credential helper. age identities/recipients are yours to manage, and keys never enter the sync repository. diff --git a/README.es.md b/README.es.md index 98203ca..c2676b1 100644 --- a/README.es.md +++ b/README.es.md @@ -244,6 +244,7 @@ Los archivos de sesión se copian como bytes opacos y nunca se analizan; cada co ## Límites de seguridad - **Nunca sobrescribe en silencio.** El merge de tres vías append-only conserva ambos lados ante cualquier divergencia, incluido delete/modify (los bytes modificados se conservan, la intención de borrado se respeta); los archivos fork nunca se eliminan y git nunca fuerza push, resetea, rebase ni cambia de rama. +- **Repositorio dedicado.** `repoDir` debe ser la raíz de su propio worktree git: si es solo un subdirectorio de un repositorio externo no relacionado, el plugin inicializa un repositorio espejo dedicado en `repoDir` y nunca escribe configuración, origin ni commits en el repositorio externo. - **Contención de rutas.** Los archivos se reflejan como bytes opacos con enlaces simbólicos rechazados y cada ruta unida se comprueba por contención (`PATH_UNSAFE` falla alto). - **Salida saneada.** Las credenciales de URL remota, los tokens y los secretos `key=value` se redactan antes de llegar al modelo o al registro; la visualización de rutas rechaza todo lo que esté fuera de su raíz. - **Sin almacenamiento de credenciales.** El plugin no almacena credenciales; las credenciales de git viven en tu helper de credenciales normal. Las identidades/destinatarios age los gestionas tú, y las claves nunca entran en el repositorio de sincronización. diff --git a/README.hi.md b/README.hi.md index 4d25596..bc51003 100644 --- a/README.hi.md +++ b/README.hi.md @@ -244,6 +244,7 @@ sync: cancelled: approval requires an open turn; /sync commands run between turn ## सुरक्षा सीमाएँ - **कभी चुपचाप अधिलेखन नहीं।** append-only तीन-तरफ़ा merge किसी भी विचलन पर दोनों पक्ष रखता है, delete/modify सहित (बदली हुई बाइट्स रखी जाती हैं, हटाने का इरादा सम्मानित होता है); fork फ़ाइलें कभी नहीं मिटाई जातीं, और git कभी force-push, reset, rebase या branch बदलाव नहीं करता। +- **समर्पित रिपॉज़िटरी.** `repoDir` को अपने स्वयं के git worktree की जड़ होना चाहिए: यदि वह किसी असंबंधित बाहरी रिपॉज़िटरी की केवल उपनिर्देशिका है, तो प्लगइन `repoDir` पर एक समर्पित मिरर रिपॉज़िटरी आरंभ करता है और बाहरी रिपॉज़िटरी में कभी कॉन्फ़िगरेशन, origin या commit नहीं लिखता। - **पथ संकोचन।** फ़ाइलें अपारदर्शी बाइट्स के रूप में मिरर होती हैं, symlinks अस्वीकार किए जाते हैं, और हर जोड़े गए पथ की संकोचन-जाँच होती है (`PATH_UNSAFE` ज़ोर से विफल)। - **सैनिटाइज़्ड आउटपुट।** रिमोट-URL क्रेडेंशियल, टोकन और `key=value` रहस्य मॉडल या लॉग तक पहुँचने से पहले छिपाए जाते हैं; पथ प्रदर्शन अपने मूल से बाहर कुछ भी अस्वीकार करता है। - **कोई क्रेडेंशियल संग्रहण नहीं।** प्लगइन कोई क्रेडेंशियल संग्रहीत नहीं करता; git क्रेडेंशियल आपके सामान्य git credential helper में रहते हैं। age identity/recipient आप प्रबंधित करते हैं, और कुंजियाँ कभी सिंक रिपॉज़िटरी में नहीं जातीं। diff --git a/README.md b/README.md index 63f3a63..3b42813 100644 --- a/README.md +++ b/README.md @@ -244,6 +244,7 @@ sync: cancelled: approval requires an open turn; /sync commands run between turn ## 安全边界 - **绝不静默覆盖。** append-only 三方合并在任何分歧时都保留两边,包括 delete/modify(修改后的字节保留、删除意图被尊重);fork 文件永不被删除,git 绝不强推、reset、rebase 或切换分支。 +- **独立仓库。** `repoDir` 必须是自身 git 工作树的根:它若只是外层仓库的子目录,插件会在 `repoDir` 初始化独立镜像仓库,绝不把配置、origin 或提交写进外层仓库。 - **路径收容。** 文件按不透明字节镜像、拒绝符号链接,每次路径拼接都做收容校验(`PATH_UNSAFE` 响亮失败)。 - **脱敏输出。** 远端 URL 凭据、令牌与 `key=value` 密钥在进入模型或日志前被打码;路径展示拒绝根外路径。 - **不存凭据。** 插件自身不存凭据;git 凭据由你常规的 git credential helper 管理。age 身份/接收方文件由你管理,密钥绝不进入同步仓库。 diff --git a/README.pt.md b/README.pt.md index 66cca0c..9c299c8 100644 --- a/README.pt.md +++ b/README.pt.md @@ -244,6 +244,7 @@ Os arquivos de sessão são copiados como bytes opacos e nunca analisados; cada ## Limites de segurança - **Nunca sobrescreve em silêncio.** O merge de três vias append-only mantém os dois lados diante de qualquer divergência, incluindo delete/modify (os bytes modificados são mantidos, a intenção de exclusão é respeitada); arquivos fork nunca são apagados e o git nunca força push, reseta, faz rebase ou troca de branch. +- **Repositório dedicado.** `repoDir` deve ser a raiz do seu próprio worktree git: se for apenas um subdiretório de um repositório externo não relacionado, o plugin inicializa um repositório espelho dedicado em `repoDir` e nunca grava configuração, origin ou commits no repositório externo. - **Contenção de caminhos.** Os arquivos são espelhados como bytes opacos com links simbólicos recusados e cada caminho unido é verificado por contenção (`PATH_UNSAFE` falha alto). - **Saída higienizada.** Credenciais de URL remota, tokens e segredos `key=value` são redigidos antes de chegar ao modelo ou ao log; a exibição de caminhos recusa tudo fora da sua raiz. - **Sem armazenamento de credenciais.** O plugin não armazena credenciais; as credenciais git ficam no seu helper de credenciais normal. As identidades/destinatários age são gerenciados por você, e as chaves nunca entram no repositório de sincronização. diff --git a/lib/git.mjs b/lib/git.mjs index e3ac723..0a869f7 100644 --- a/lib/git.mjs +++ b/lib/git.mjs @@ -11,6 +11,8 @@ // run(args, { cwd, signal, timeoutMs, binary, maxBytes }) → { code, stdout, stderr } // stdout:binary=false 时为 UTF-8 文本;binary=true 时为 Buffer(原始字节)。 +import { promises as fs } from 'node:fs' +import path from 'node:path' import { redactText } from './sanitize.mjs' import { gitFailed, pushRejected } from './errors.mjs' import { LIMITS } from './constants.mjs' @@ -149,10 +151,26 @@ export class GitBackend { return result.code === 0 ? result : null } - /** 该目录是否已是 git 仓库。 */ + /** + * 该目录是否**自身**就是一个 git 工作树的根。 + * 不能用 `--is-inside-work-tree`:它对任何外层仓库的子目录也返回 true, + * 于是 ensureRepo 跳过 init,把 config/origin/提交写进外层仓库(劫持)。 + * 这里用 `--show-toplevel` 与 repoDir 做 realpath 同一性比较:repoDir 只是 + * 外层仓库的子目录时返回 false,ensureRepo 会在 repoDir 初始化独立仓库, + * 外层仓库分毫不动。realpath 两侧消解 symlink、Windows 大小写与分隔符差异。 + */ async isRepo() { - const out = await this.#maybe(['rev-parse', '--is-inside-work-tree']) - return out !== null && String(out.stdout).trim() === 'true' + const out = await this.#maybe(['rev-parse', '--show-toplevel']) + if (out === null) return false + const toplevel = String(out.stdout).trim() + if (toplevel === '') return false + // realpath 消解 symlink/大小写/分隔符差异;路径不存在时(如 scripted 测试 + // 的假路径)退回 path.resolve,两侧同口径比较。 + const normalize = async (p) => { + try { return path.resolve(await fs.realpath(p)) } catch { return path.resolve(p) } + } + const [realRoot, realRepo] = await Promise.all([normalize(toplevel), normalize(this.#repoDir)]) + return realRoot === realRepo } /** diff --git a/test/git.test.mjs b/test/git.test.mjs index 2af01ac..c7030da 100644 --- a/test/git.test.mjs +++ b/test/git.test.mjs @@ -72,7 +72,7 @@ test('whitelist rejects destructive verbs and force-push arguments', () => { test('bootstrap sequence: init, identity, remote, initial commit', async () => { const { git, calls } = makeGit([ - { assert: ['rev-parse', '--is-inside-work-tree'], stdout: 'false\n' }, + { assert: ['rev-parse', '--show-toplevel'], code: 128, stderr: 'not a git repository' }, { assert: ['init', '-b', 'main'] }, { assert: ['config', 'core.autocrlf', 'false'] }, { assert: ['config', 'user.name', 'sync'] }, @@ -92,7 +92,7 @@ test('bootstrap sequence: init, identity, remote, initial commit', async () => { test('bootstrap keeps existing repo and rewrites a changed remote url', async () => { const { git, calls } = makeGit([ - { stdout: 'true\n' }, // is-inside-work-tree + { assert: ['rev-parse', '--show-toplevel'], stdout: '/repo\n' }, // worktree root == repoDir { assert: ['config', 'core.autocrlf', 'false'] }, {}, {}, // identity config { stdout: 'https://old.example.com/r.git\n' }, // remote get-url diff --git a/test/repo-isolation.test.mjs b/test/repo-isolation.test.mjs new file mode 100644 index 0000000..7c3a3e6 --- /dev/null +++ b/test/repo-isolation.test.mjs @@ -0,0 +1,164 @@ +// test/repo-isolation.test.mjs — repoDir 必须是自身工作树的根(真实 git + 临时目录)。 +// 回归:repoDir 位于无关外层仓库子目录时,bootstrap 不得把 config/origin/提交 +// 写进外层仓库(劫持),而应在 repoDir 初始化独立镜像仓库。 +// 隔离纪律:所有仓库建在 os.tmpdir() 下,且断言 --show-toplevel 与预期一致。 + +import test from 'node:test' +import assert from 'node:assert/strict' +import { spawnSync } from 'node:child_process' +import { promises as fs } from 'node:fs' +import os from 'node:os' +import path from 'node:path' +import { GitBackend } from '../lib/git.mjs' + +const GIT_OK = (() => { + try { + return spawnSync('git', ['--version'], { stdio: 'ignore' }).status === 0 + } catch { + return false + } +})() + +function realRunner(args, opts = {}) { + const res = spawnSync('git', args, { + cwd: opts.cwd, + env: { ...process.env, GIT_TERMINAL_PROMPT: '0', GIT_OPTIONAL_LOCKS: '0' }, + encoding: opts.binary === true ? null : 'utf8', + maxBuffer: 64 * 1024 * 1024, + windowsHide: true, + }) + const stdout = opts.binary === true ? (res.stdout ?? Buffer.alloc(0)) : String(res.stdout ?? '') + return Promise.resolve({ code: res.status ?? 0, stdout, stderr: String(res.stderr ?? '') }) +} + +function git(cwd, ...args) { + const res = spawnSync('git', args, { cwd, encoding: 'utf8', env: { ...process.env, GIT_TERMINAL_PROMPT: '0', GIT_OPTIONAL_LOCKS: '0' }, windowsHide: true }) + assert.equal(res.status, 0, `git ${args.join(' ')} failed: ${res.stderr}`) + return String(res.stdout ?? '').trim() +} + +async function makeTemp() { + const root = await fs.mkdtemp(path.join(os.tmpdir(), 'dsh-session-sync-isolation-')) + return { root, clean: () => fs.rm(root, { recursive: true, force: true }) } +} + +function backend(repoDir, remote = 'https://example.com/sync.git') { + return new GitBackend({ + repoDir, + remote, + branch: 'main', + commitName: 'sync-identity', + commitEmail: 'sync@local', + run: realRunner, + timeoutMs: 60000, + }) +} + +/** 建一个带独特身份与 origin 的外层仓库,并断言其工作树根就是预期目录。 */ +async function makeOuter(root) { + const outer = path.join(root, 'outer') + await fs.mkdir(outer, { recursive: true }) + git(outer, 'init', '-b', 'main') + git(outer, 'config', 'user.name', 'OUTER-NAME') + git(outer, 'config', 'user.email', 'outer@example.com') + git(outer, 'remote', 'add', 'origin', 'https://example.com/outer.git') + await fs.writeFile(path.join(outer, 'file.txt'), 'outer\n') + git(outer, 'add', '.') + git(outer, 'commit', '-m', 'outer commit') + assert.equal(path.resolve(git(outer, 'rev-parse', '--show-toplevel')), path.resolve(outer), 'fixture isolation: outer toplevel') + return outer +} + +test('bootstrap inside an outer worktree initializes a dedicated repo and never touches the outer', { skip: !GIT_OK && 'git binary not available' }, async (t) => { + const { root, clean } = await makeTemp() + t.after(clean) + const outer = await makeOuter(root) + const outerHead = git(outer, 'rev-parse', 'HEAD') + const outerCount = git(outer, 'rev-list', '--count', 'HEAD') + + const repoDir = path.join(outer, 'mirror') + await fs.mkdir(repoDir, { recursive: true }) + await backend(repoDir).bootstrap() + + // 外层仓库分毫不动:身份、origin、HEAD、提交数。 + assert.equal(git(outer, 'config', 'user.name'), 'OUTER-NAME') + assert.equal(git(outer, 'config', 'user.email'), 'outer@example.com') + assert.equal(git(outer, 'remote', 'get-url', 'origin'), 'https://example.com/outer.git') + assert.equal(git(outer, 'rev-parse', 'HEAD'), outerHead) + assert.equal(git(outer, 'rev-list', '--count', 'HEAD'), outerCount) + + // 内层独立仓库:自己的 .git、配置的身份与 origin。 + assert.equal((await fs.stat(path.join(repoDir, '.git'))).isDirectory(), true) + assert.equal(path.resolve(git(repoDir, 'rev-parse', '--show-toplevel')), path.resolve(repoDir), 'fixture isolation: inner toplevel') + assert.equal(git(repoDir, 'config', 'user.name'), 'sync-identity') + assert.equal(git(repoDir, 'remote', 'get-url', 'origin'), 'https://example.com/sync.git') +}) + +test('isRepo is true only at the worktree root, not inside an outer worktree', { skip: !GIT_OK && 'git binary not available' }, async (t) => { + const { root, clean } = await makeTemp() + t.after(clean) + const outer = await makeOuter(root) + + const inner = path.join(outer, 'mirror') + await fs.mkdir(inner, { recursive: true }) + assert.equal(await backend(inner).isRepo(), false, 'a bare subdirectory of an outer repo is not our repo') + assert.equal(await backend(outer).isRepo(), true, 'the outer root is a repo root') + + const plain = path.join(root, 'plain') + await fs.mkdir(plain, { recursive: true }) + assert.equal(await backend(plain).isRepo(), false, 'a non-repo directory is not a repo') + + await backend(inner).bootstrap() + assert.equal(await backend(inner).isRepo(), true, 'after init the dedicated dir is its own root') + assert.equal(await backend(outer).isRepo(), true, 'the outer root stays its own root') +}) + +test('a second bootstrap is idempotent and still leaves the outer untouched', { skip: !GIT_OK && 'git binary not available' }, async (t) => { + const { root, clean } = await makeTemp() + t.after(clean) + const outer = await makeOuter(root) + const repoDir = path.join(outer, 'mirror') + await fs.mkdir(repoDir, { recursive: true }) + const b = backend(repoDir) + await b.bootstrap() + const innerHead = git(repoDir, 'rev-parse', 'HEAD') + const outerHead = git(outer, 'rev-parse', 'HEAD') + await b.bootstrap() + assert.equal(git(repoDir, 'rev-parse', 'HEAD'), innerHead, 'no empty commit on the second bootstrap') + assert.equal(git(outer, 'rev-parse', 'HEAD'), outerHead) + assert.equal(git(outer, 'config', 'user.name'), 'OUTER-NAME') + assert.equal(git(outer, 'remote', 'get-url', 'origin'), 'https://example.com/outer.git') +}) + +test('a case-variant repoDir path at the true root is still the same repo (Windows)', { skip: !GIT_OK && 'git binary not available' }, async (t) => { + if (process.platform !== 'win32') return t.skip('case-insensitive paths are Windows-specific; the symlink test pins realpath on POSIX') + const { root, clean } = await makeTemp() + t.after(clean) + const repoDir = path.join(root, 'MirrorCase') + await fs.mkdir(repoDir, { recursive: true }) + await backend(repoDir).bootstrap() + const head = git(repoDir, 'rev-parse', 'HEAD') + const variant = path.join(root, 'mirrorcase') + assert.equal(await backend(variant).isRepo(), true, 'realpath must canonicalize case, not compare raw strings') + await backend(variant).bootstrap() + assert.equal(git(repoDir, 'rev-parse', 'HEAD'), head, 'no spurious re-init or commit') +}) + +test('a symlinked repoDir resolves to its target root', { skip: !GIT_OK && 'git binary not available' }, async (t) => { + const { root, clean } = await makeTemp() + t.after(clean) + const target = path.join(root, 'target') + await fs.mkdir(target, { recursive: true }) + await backend(target).bootstrap() + const head = git(target, 'rev-parse', 'HEAD') + const link = path.join(root, 'link') + try { + await fs.symlink(target, link, process.platform === 'win32' ? 'junction' : 'dir') + } catch (error) { + if (error?.code === 'EPERM' || error?.code === 'EACCES') return t.skip('directory link creation not permitted here') + throw error + } + assert.equal(await backend(link).isRepo(), true, 'realpath must resolve the link to the target root') + await backend(link).bootstrap() + assert.equal(git(target, 'rev-parse', 'HEAD'), head, 'bootstrap through the link touches only the target repo') +})