From 06d2df6e206afa133fde614c010001ebe23488a6 Mon Sep 17 00:00:00 2001 From: Exelo Date: Mon, 23 Nov 2026 02:04:56 +0100 Subject: [PATCH 1/4] fix(server-core): only read with git in an untrusted folder --- AGENTS.md | 2 +- docs/docs/editor/git.mdx | 2 + packages/server-core/src/git/git-service.ts | 86 +++++++++- .../server-core/test/git/git-service.spec.ts | 152 ++++++++++++++++++ 4 files changed, 235 insertions(+), 7 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 48bc212f..c35b318f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -178,7 +178,7 @@ Everything in our registry has a `nanoforge.manifest.json` and a name `@scope/na ### Folder trust (local editors) - A local project's code runs only in a **trusted folder** (`TrustStore`, `DATA_DIR/trusted-folders.json`, by real path; seeded with the recent projects when first created). Trusted: `nanoforge.config.ts` is executed, project plugins load and their server entries run, builds, games, dependency installs, the project's Prettier and its git hooks run. -- An untrusted folder opens in **restricted mode**: the config is read statically (as in a hosted editor), project plugins stay out, Play explains why, git runs with the hosted hardening, formatting uses the bundled Prettier. A sticky notification and `project.trust` offer **Trust this folder** (`projects.trust`, then the project reopens). +- An untrusted folder opens in **restricted mode**: the config is read statically (as in a hosted editor), project plugins stay out, Play explains why, git only reads (`GitService`: status, history, branches and stashes listed; the hosted hardening on, the folder's own filter, diff and merge drivers off, no lazy fetch or transport, submodules skipped; a config it cannot list in full refuses the command) and refuses every write or remote with `FORBIDDEN`, formatting uses the bundled Prettier. A sticky notification and `project.trust` offer **Trust this folder** (`projects.trust`, then the project reopens). - Server gates go through `ProjectRegistry.assertTrusted(project, what)`; `OpenProject.trusted` and `ClientProject.trusted` carry the state. A new code path that runs project code needs the gate. - `plugins.list` never runs anything: the client calls `plugins.runProjectServers` with the project plugins that loaded. - The editor shell is served with `frame-ancestors 'self'` / `X-Frame-Options: SAMEORIGIN`, so another site cannot frame it and get a click on **Trust and open**. diff --git a/docs/docs/editor/git.mdx b/docs/docs/editor/git.mdx index 242811a6..88ccdadf 100644 --- a/docs/docs/editor/git.mdx +++ b/docs/docs/editor/git.mdx @@ -8,6 +8,8 @@ In a local editor, the **VCS** menu and two panels work with the project's Git r A project that is not a repository yet: _VCS › Initialize repository_. +In a folder opened in restricted mode, Git only shows the repository: its changes, history, branches and stashes. Committing, staging, rolling back, branches, stashes and remotes need **Trust this folder** first, since the folder's own Git settings could run commands. + ## Commit The **Commit** panel on the left lists what changed since the last commit, as files with their folder beside the name: diff --git a/packages/server-core/src/git/git-service.ts b/packages/server-core/src/git/git-service.ts index cb912983..65569a80 100644 --- a/packages/server-core/src/git/git-service.ts +++ b/packages/server-core/src/git/git-service.ts @@ -28,8 +28,35 @@ const HOSTED_CONFIG = [ ['core.sshCommand', 'ssh'], ['core.askPass', ''], ['credential.helper', ''], + ['log.showSignature', 'false'], ] as const; +/** + * What git may run in an untrusted folder: reads, with the arguments `GitService` gives them. + * Anything else (a write, a remote, a new command) is refused, so a setting of the folder's own + * `.git/config` (filter, merge driver, signing program, `remote.*.uploadpack`…) never runs. + */ +const readsOnly = (args: readonly string[]): boolean => { + const [command = '', sub] = args; + if (command === 'stash') return sub === 'list'; + if (command === 'config') return sub === '--get'; + if (command === 'remote') return sub === 'get-url'; + if (command === 'symbolic-ref') return sub === '--short'; + return ['status', 'for-each-ref', 'rev-parse', 'log', 'show', 'ls-tree', 'ls-files'].includes( + command, + ); +}; + +/** + * Driver settings of `.gitattributes` that run a command; `status` hashes changed files through + * the filters. Turned off (`''`) when the folder's own config sets them. + */ +const DRIVER_COMMAND = + /^(?:filter\..+\.(?:clean|smudge|process|required)|diff\..+\.(?:textconv|command)|merge\..+\.driver)$/; + +/** Restricted mode also never reaches a remote: no lazy fetch of a missing object, no transport. */ +const RESTRICTED_CONFIG = [...HOSTED_CONFIG, ['protocol.allow', 'never']] as const; + /** Git CLI wrapper; operations on the same repository are serialized. */ export class GitService { private readonly _mutex = new KeyedMutex(); @@ -39,8 +66,9 @@ export class GitService { /** How long a command that talks to a remote may take before it is stopped. */ private readonly _networkTimeoutMs = 60_000, /** - * Whether a local repository is in a trusted folder: an untrusted one gets the hosted - * hardening too (its hooks and command settings never run). Trusted when not given. + * Whether a local repository is in a trusted folder. In an untrusted one git only reads + * (`readsOnly`), with the hosted hardening, no remote, and the folder's own drivers turned + * off: nothing its `.git` sets runs. Trusted when not given. */ private readonly _trusted?: (root: string) => Promise, ) {} @@ -411,14 +439,27 @@ export class GitService { network = false, extraEnv: Record = {}, ) { - const hosted = - this._env.mode === 'ONLINE' || (this._trusted ? !(await this._trusted(cwd)) : false); + const restricted = + this._env.mode !== 'ONLINE' && this._trusted ? !(await this._trusted(cwd)) : false; + const hosted = this._env.mode === 'ONLINE' || restricted; + if (restricted && !readsOnly(args)) { + throw new RpcError( + 'FORBIDDEN', + `git ${args[0]} needs a trusted folder: trust this folder to change its repository`, + ); + } + const hardening = restricted + ? [...RESTRICTED_CONFIG, ...(await this._ownDrivers(cwd)).map((key) => [key, ''] as const)] + : HOSTED_CONFIG; const batchSsh = network && !process.env.GIT_SSH_COMMAND && !process.env.GIT_SSH && (hosted || !(await this._configured(cwd, 'core.sshCommand'))); - return runProcess(this._env.gitPath, args, { + /** A submodule's status runs git inside it, with its own config: restricted mode skips them. */ + const command = + restricted && args[0] === 'status' ? [...args, '--ignore-submodules=all'] : args; + return runProcess(this._env.gitPath, command, { cwd, env: { GIT_TERMINAL_PROMPT: '0', @@ -427,12 +468,45 @@ export class GitService { GIT_OPTIONAL_LOCKS: '0', LC_ALL: 'C', ...(batchSsh && { GIT_SSH_COMMAND: 'ssh -o BatchMode=yes' }), - ...(hosted ? withGitConfig(extraEnv, HOSTED_CONFIG) : extraEnv), + ...(restricted && { GIT_NO_LAZY_FETCH: '1', GIT_ALLOW_PROTOCOL: '' }), + ...(hosted ? withGitConfig(extraEnv, hardening) : extraEnv), }, ...(network && { signal: AbortSignal.timeout(this._networkTimeoutMs) }), }).done; } + /** + * The driver settings of the repository's own config (local, worktree and what they include). + * A listing that failed or was cut short could hide one: the command is refused. + */ + private async _ownDrivers(cwd: string): Promise { + const { stdout, exitCode, truncated } = await runProcess( + this._env.gitPath, + ['config', '--list', '--show-scope', '--includes', '--name-only', '-z'], + { + cwd, + env: { + GIT_CEILING_DIRECTORIES: dirname(cwd), + LC_ALL: 'C', + ...withGitConfig({}, HOSTED_CONFIG), + }, + }, + ).done; + if (exitCode !== 0 || truncated) { + throw new RpcError( + 'FORBIDDEN', + "This folder's git config could not be checked: trust this folder to use git here", + ); + } + const fields = stdout.split('\0'); + return fields.filter( + (key, index) => + index % 2 === 1 && + (fields[index - 1] === 'local' || fields[index - 1] === 'worktree') && + DRIVER_COMMAND.test(key), + ); + } + private async _configured(cwd: string, key: string): Promise { const result = await this._exec(cwd, ['config', '--get', key]).catch(() => undefined); return result?.exitCode === 0 && result.stdout.trim() !== ''; diff --git a/packages/server-core/test/git/git-service.spec.ts b/packages/server-core/test/git/git-service.spec.ts index 04d96a14..2f532e41 100644 --- a/packages/server-core/test/git/git-service.spec.ts +++ b/packages/server-core/test/git/git-service.spec.ts @@ -123,6 +123,158 @@ describe('repository settings that run commands', () => { }); }); +describe('an untrusted folder', () => { + const untrusted = () => + new GitService(loadEnv({ NODE_ENV: 'test', FS_ROOT: workspace }, workspace), undefined, () => + Promise.resolve(false), + ); + /** A repository whose own config runs a filter, a diff driver and a signing program. */ + const armed = async (name: string) => { + const root = await repository(name); + const marks = join(workspace, `${name}-marks`); + mkdirSync(marks); + const mark = (what: string) => `touch "${join(marks, what)}"`; + write(root, '.gitattributes', '*.txt filter=evil diff=evil merge=evil\n'); + raw(root, 'add', '.gitattributes'); + raw(root, 'commit', '-q', '-m', 'attributes'); + raw(root, 'branch', 'other'); + raw(root, 'remote', 'add', 'origin', 'https://git.test/a.git'); + write(root, 'a.txt', 'stashed\n'); + raw(root, 'stash', 'push', '--quiet'); + raw(root, 'config', 'filter.evil.clean', `${mark('clean')}; cat`); + raw(root, 'config', 'filter.evil.smudge', `${mark('smudge')}; cat`); + raw(root, 'config', 'filter.evil.process', mark('process')); + raw(root, 'config', 'filter.evil.required', 'true'); + raw(root, 'config', 'diff.evil.textconv', `${mark('textconv')}; cat`); + raw(root, 'config', 'diff.external', mark('external')); + raw(root, 'config', 'merge.evil.driver', mark('merge')); + raw(root, 'config', 'gpg.program', mark('gpg')); + raw(root, 'config', 'commit.gpgSign', 'true'); + raw(root, 'config', 'log.showSignature', 'true'); + raw(root, 'config', 'core.fsmonitor', mark('fsmonitor')); + /** Same size as `one\n`: status hashes it again, through the filter. */ + write(root, 'a.txt', 'two\n'); + return { root, marks }; + }; + const ran = (marks: string) => + ['clean', 'smudge', 'process', 'textconv', 'external', 'merge', 'gpg', 'fsmonitor'].filter( + (what) => existsSync(join(marks, what)), + ); + + it('reads the repository without running its commands', async () => { + const service = untrusted(); + const { root, marks } = await armed('untrusted-read'); + const status = await service.projectStatus(root); + expect(status.files.map((file) => file.path)).toEqual(['a.txt']); + expect(await service.show(root, 'a.txt', 'HEAD')).toBe('one\n'); + expect(await service.show(root, 'a.txt', 'INDEX')).toBe('one\n'); + const [last] = await service.log(root); + expect(last?.subject).toBe('attributes'); + await service.commitFiles(root, 'HEAD'); + await service.headMessage(root); + await service.branches(root); + await service.stashes(root); + await service.outgoing(root); + expect(ran(marks)).toEqual([]); + }); + + it('never fetches a missing object from a promisor remote', async () => { + const service = untrusted(); + const remote = await repository('untrusted-promisor-remote'); + const root = await repository('untrusted-promisor'); + const marks = join(workspace, 'untrusted-promisor-marks'); + mkdirSync(marks); + raw(root, 'config', 'core.repositoryformatversion', '1'); + raw(root, 'config', 'extensions.partialClone', 'origin'); + raw(root, 'remote', 'add', 'origin', remote); + raw(root, 'config', 'remote.origin.promisor', 'true'); + raw( + root, + 'config', + 'remote.origin.uploadpack', + `touch "${join(marks, 'uploadpack')}"; git-upload-pack`, + ); + raw(root, 'config', 'protocol.file.allow', 'always'); + const blob = raw(root, 'rev-parse', 'HEAD:a.txt').trim(); + rmSync(join(root, '.git/objects', blob.slice(0, 2), blob.slice(2))); + expect(await service.show(root, 'a.txt', 'HEAD')).toBeNull(); + await service.projectStatus(root); + expect(existsSync(join(marks, 'uploadpack'))).toBe(false); + }); + + it('refuses to run when the listing of its config is cut short', async () => { + const service = untrusted(); + const root = await repository('untrusted-long-config'); + const marks = join(workspace, 'untrusted-long-config-marks'); + mkdirSync(marks); + write(root, '.gitattributes', '*.txt filter=evil\n'); + raw(root, 'add', '.gitattributes'); + raw(root, 'commit', '-q', '-m', 'attributes'); + /** Past the 16 MiB a listing keeps, so the filter's keys come after the cut. */ + writeFileSync(join(root, '.git/padding'), `[pad]\n${'k = v\n'.repeat(1_800_000)}`); + raw(root, 'config', 'include.path', 'padding'); + raw(root, 'config', '--add', 'include.path', 'evil'); + writeFileSync( + join(root, '.git/evil'), + `[filter "evil"]\n process = touch "${join(marks, 'process')}"\n`, + ); + write(root, 'a.txt', 'two\n'); + await expect(service.projectStatus(root)).rejects.toMatchObject({ code: 'FORBIDDEN' }); + expect(existsSync(join(marks, 'process'))).toBe(false); + }, 30_000); + + it("does not run a submodule's own commands either", async () => { + const service = untrusted(); + const inner = await repository('untrusted-inner'); + const root = await repository('untrusted-outer'); + raw(root, '-c', 'protocol.file.allow=always', 'submodule', 'add', '-q', inner, 'inner'); + raw(root, 'commit', '-q', '-m', 'submodule'); + const sub = join(root, 'inner'); + const marks = join(workspace, 'untrusted-submodule-marks'); + mkdirSync(marks); + write(sub, '.gitattributes', '*.txt filter=evil\n'); + raw(sub, 'add', '.gitattributes'); + raw(sub, 'commit', '-q', '-m', 'attributes'); + raw(sub, 'config', 'filter.evil.process', `touch "${join(marks, 'process')}"`); + raw(sub, 'config', 'filter.evil.clean', `touch "${join(marks, 'clean')}"; cat`); + write(sub, 'a.txt', 'two\n'); + await service.projectStatus(root); + expect(ran(marks)).toEqual([]); + }); + + it('refuses what writes to the repository or talks to a remote', async () => { + const service = untrusted(); + const { root, marks } = await armed('untrusted-write'); + const [stash] = await service.stashes(root); + const refused = [ + service.init(root), + service.stage(root, ['a.txt']), + service.unstage(root, ['a.txt']), + service.discard(root, ['a.txt']), + service.commit(root, 'evil', { all: true }), + service.commit(root, 'evil', { paths: ['a.txt'] }), + service.switchBranch(root, 'other'), + service.createBranch(root, 'evil'), + service.deleteBranch(root, 'other'), + service.stash(root), + service.applyStash(root, stash!.hash), + service.applyStash(root, stash!.hash, true), + service.dropStash(root, stash!.hash), + service.fetch(root), + service.mergePull(root), + service.push(root), + service.pull(root, 'https://git.test/a.git'), + ]; + const results = await Promise.allSettled(refused); + expect(ran(marks)).toEqual([]); + expect( + results.map((result) => (result.status === 'rejected' ? result.reason.code : 'ran')), + ).toEqual(refused.map(() => 'FORBIDDEN')); + expect(raw(root, 'stash', 'list')).toContain('stash@{0}'); + expect(readFileSync(join(root, 'a.txt'), 'utf8')).toBe('two\n'); + }); +}); + describe('parseStatus', () => { it('reads the branch, the upstream counts and every kind of entry', () => { const output = [ From 7cfa113d8843cd411aa3a6916b7309e8c7332294 Mon Sep 17 00:00:00 2001 From: Exelo Date: Mon, 23 Nov 2026 02:20:13 +0100 Subject: [PATCH 2/4] fix(server-core): turn off global git drivers and refuse outside repositories when untrusted --- AGENTS.md | 2 +- docs/docs/editor/git.mdx | 2 +- packages/server-core/src/git/git-service.ts | 63 +++++++++++-------- .../server-core/test/git/git-service.spec.ts | 45 ++++++++++++- 4 files changed, 83 insertions(+), 29 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index c35b318f..cc3c5fdf 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -178,7 +178,7 @@ Everything in our registry has a `nanoforge.manifest.json` and a name `@scope/na ### Folder trust (local editors) - A local project's code runs only in a **trusted folder** (`TrustStore`, `DATA_DIR/trusted-folders.json`, by real path; seeded with the recent projects when first created). Trusted: `nanoforge.config.ts` is executed, project plugins load and their server entries run, builds, games, dependency installs, the project's Prettier and its git hooks run. -- An untrusted folder opens in **restricted mode**: the config is read statically (as in a hosted editor), project plugins stay out, Play explains why, git only reads (`GitService`: status, history, branches and stashes listed; the hosted hardening on, the folder's own filter, diff and merge drivers off, no lazy fetch or transport, submodules skipped; a config it cannot list in full refuses the command) and refuses every write or remote with `FORBIDDEN`, formatting uses the bundled Prettier. A sticky notification and `project.trust` offer **Trust this folder** (`projects.trust`, then the project reopens). +- An untrusted folder opens in **restricted mode**: the config is read statically (as in a hosted editor), project plugins stay out, Play explains why, git only reads (`GitService`: status, history, branches and stashes listed; the hosted hardening on, every filter, diff and merge driver off whatever config sets it, so Git LFS files may show as modified, no lazy fetch or transport, submodules skipped; a config it cannot list in full, or a repository or work tree outside the folder (gitfile, `.git` link, `core.worktree`, a linked worktree), refuses the command) and refuses every write or remote with `FORBIDDEN`, formatting uses the bundled Prettier. A sticky notification and `project.trust` offer **Trust this folder** (`projects.trust`, then the project reopens). - Server gates go through `ProjectRegistry.assertTrusted(project, what)`; `OpenProject.trusted` and `ClientProject.trusted` carry the state. A new code path that runs project code needs the gate. - `plugins.list` never runs anything: the client calls `plugins.runProjectServers` with the project plugins that loaded. - The editor shell is served with `frame-ancestors 'self'` / `X-Frame-Options: SAMEORIGIN`, so another site cannot frame it and get a click on **Trust and open**. diff --git a/docs/docs/editor/git.mdx b/docs/docs/editor/git.mdx index 88ccdadf..3b9c67f8 100644 --- a/docs/docs/editor/git.mdx +++ b/docs/docs/editor/git.mdx @@ -8,7 +8,7 @@ In a local editor, the **VCS** menu and two panels work with the project's Git r A project that is not a repository yet: _VCS › Initialize repository_. -In a folder opened in restricted mode, Git only shows the repository: its changes, history, branches and stashes. Committing, staging, rolling back, branches, stashes and remotes need **Trust this folder** first, since the folder's own Git settings could run commands. +In a folder opened in restricted mode, Git only shows the repository: its changes, history, branches and stashes. Initializing, committing, staging, rolling back, branches, stashes and remotes need **Trust this folder** first, since the folder's own Git settings could run commands. Git LFS files may show as modified until then, because no filter runs. ## Commit diff --git a/packages/server-core/src/git/git-service.ts b/packages/server-core/src/git/git-service.ts index 65569a80..413d0407 100644 --- a/packages/server-core/src/git/git-service.ts +++ b/packages/server-core/src/git/git-service.ts @@ -1,4 +1,5 @@ import { existsSync } from 'node:fs'; +import { realpath } from 'node:fs/promises'; import { dirname, join } from 'node:path'; import type { @@ -49,7 +50,7 @@ const readsOnly = (args: readonly string[]): boolean => { /** * Driver settings of `.gitattributes` that run a command; `status` hashes changed files through - * the filters. Turned off (`''`) when the folder's own config sets them. + * the filters. Restricted mode turns off (`''`) every one it finds, whatever config sets it. */ const DRIVER_COMMAND = /^(?:filter\..+\.(?:clean|smudge|process|required)|diff\..+\.(?:textconv|command)|merge\..+\.driver)$/; @@ -67,8 +68,8 @@ export class GitService { private readonly _networkTimeoutMs = 60_000, /** * Whether a local repository is in a trusted folder. In an untrusted one git only reads - * (`readsOnly`), with the hosted hardening, no remote, and the folder's own drivers turned - * off: nothing its `.git` sets runs. Trusted when not given. + * (`readsOnly`) a repository that is the folder's own, with the hosted hardening, no remote, + * and every attribute driver turned off: nothing its `.git` sets runs. Trusted when not given. */ private readonly _trusted?: (root: string) => Promise, ) {} @@ -449,7 +450,10 @@ export class GitService { ); } const hardening = restricted - ? [...RESTRICTED_CONFIG, ...(await this._ownDrivers(cwd)).map((key) => [key, ''] as const)] + ? [ + ...RESTRICTED_CONFIG, + ...(await this._restrictedDrivers(cwd)).map((key) => [key, ''] as const), + ] : HOSTED_CONFIG; const batchSsh = network && @@ -476,35 +480,42 @@ export class GitService { } /** - * The driver settings of the repository's own config (local, worktree and what they include). - * A listing that failed or was cut short could hide one: the command is refused. + * Checks a restricted repository and returns the driver settings to turn off: every scope's, + * since the folder's `.gitattributes` picks which driver runs (git-lfs reads the repository's + * own `lfs.*` commands). The repository and its work tree must be the folder itself (no + * gitfile, `.git` link or `core.worktree` elsewhere). Anything it cannot check is refused. */ - private async _ownDrivers(cwd: string): Promise { - const { stdout, exitCode, truncated } = await runProcess( - this._env.gitPath, - ['config', '--list', '--show-scope', '--includes', '--name-only', '-z'], - { + private async _restrictedDrivers(cwd: string): Promise { + const git = (args: string[]) => + runProcess(this._env.gitPath, args, { cwd, env: { GIT_CEILING_DIRECTORIES: dirname(cwd), + GIT_NO_LAZY_FETCH: '1', + GIT_ALLOW_PROTOCOL: '', LC_ALL: 'C', - ...withGitConfig({}, HOSTED_CONFIG), + ...withGitConfig({}, RESTRICTED_CONFIG), }, - }, - ).done; - if (exitCode !== 0 || truncated) { - throw new RpcError( - 'FORBIDDEN', - "This folder's git config could not be checked: trust this folder to use git here", - ); + }).done; + const refuse = (why: string) => + new RpcError('FORBIDDEN', `${why}: trust this folder to use git here`); + const [config, where] = await Promise.all([ + git(['config', '--list', '--name-only', '--includes', '-z']), + git(['rev-parse', '--show-toplevel', '--absolute-git-dir']), + ]); + if (config.exitCode !== 0 || config.truncated) + throw refuse("This folder's git config could not be checked"); + const [top = '', gitDir = ''] = where.stdout.split('\n'); + const folder = await realpath(cwd); + const real = (path: string) => realpath(path).catch(() => ''); + if ( + where.exitCode !== 0 || + (await real(top)) !== folder || + (await real(gitDir)) !== join(folder, '.git') + ) { + throw refuse("This folder's repository is not inside it"); } - const fields = stdout.split('\0'); - return fields.filter( - (key, index) => - index % 2 === 1 && - (fields[index - 1] === 'local' || fields[index - 1] === 'worktree') && - DRIVER_COMMAND.test(key), - ); + return config.stdout.split('\0').filter((key) => DRIVER_COMMAND.test(key)); } private async _configured(cwd: string, key: string): Promise { diff --git a/packages/server-core/test/git/git-service.spec.ts b/packages/server-core/test/git/git-service.spec.ts index 2f532e41..479cf2a2 100644 --- a/packages/server-core/test/git/git-service.spec.ts +++ b/packages/server-core/test/git/git-service.spec.ts @@ -6,6 +6,7 @@ import { mkdtempSync, readFileSync, rmSync, + symlinkSync, writeFileSync, } from 'node:fs'; import { tmpdir } from 'node:os'; @@ -211,7 +212,7 @@ describe('an untrusted folder', () => { raw(root, 'add', '.gitattributes'); raw(root, 'commit', '-q', '-m', 'attributes'); /** Past the 16 MiB a listing keeps, so the filter's keys come after the cut. */ - writeFileSync(join(root, '.git/padding'), `[pad]\n${'k = v\n'.repeat(1_800_000)}`); + writeFileSync(join(root, '.git/padding'), `[pad]\n${'k = v\n'.repeat(3_500_000)}`); raw(root, 'config', 'include.path', 'padding'); raw(root, 'config', '--add', 'include.path', 'evil'); writeFileSync( @@ -223,6 +224,48 @@ describe('an untrusted folder', () => { expect(existsSync(join(marks, 'process'))).toBe(false); }, 30_000); + it("does not run the user's own drivers on the folder's files", async () => { + const service = untrusted(); + const root = await repository('untrusted-global-driver'); + const marks = join(workspace, 'untrusted-global-driver-marks'); + const home = join(workspace, 'untrusted-global-driver-home'); + mkdirSync(marks); + mkdirSync(home); + write(root, '.gitattributes', '* filter=evil\n'); + raw(root, 'add', '.gitattributes'); + raw(root, 'commit', '-q', '-m', 'attributes'); + writeFileSync( + join(home, '.gitconfig'), + `[filter "evil"]\n process = touch "${join(marks, 'process')}"\n required = true\n`, + ); + write(root, 'a.txt', 'two\n'); + const previous = process.env.HOME; + process.env.HOME = home; + try { + await service.projectStatus(root); + } finally { + process.env.HOME = previous; + } + expect(existsSync(join(marks, 'process'))).toBe(false); + }); + + it('refuses a repository that lives outside the folder', async () => { + const service = untrusted(); + const outside = await repository('untrusted-outside-repo'); + const root = join(workspace, 'untrusted-gitfile'); + mkdirSync(root); + writeFileSync(join(root, '.git'), `gitdir: ${join(outside, '.git')}\n`); + await expect(service.branches(root)).rejects.toMatchObject({ code: 'FORBIDDEN' }); + const worktree = await repository('untrusted-core-worktree'); + raw(worktree, 'config', 'core.worktree', outside); + await expect(service.branches(worktree)).rejects.toMatchObject({ code: 'FORBIDDEN' }); + const linked = join(workspace, 'untrusted-git-symlink'); + mkdirSync(linked); + symlinkSync(join(outside, '.git'), join(linked, '.git')); + await expect(service.branches(linked)).rejects.toMatchObject({ code: 'FORBIDDEN' }); + expect((await service.log(outside)).length).toBe(1); + }); + it("does not run a submodule's own commands either", async () => { const service = untrusted(); const inner = await repository('untrusted-inner'); From 8e6dfa95aaaf3b94242220891a6b5c92b3c24914 Mon Sep 17 00:00:00 2001 From: Exelo Date: Mon, 23 Nov 2026 02:26:27 +0100 Subject: [PATCH 3/4] fix(server-core): check the common dir and alternates of an untrusted repository --- AGENTS.md | 2 +- docs/docs/editor/git.mdx | 2 +- packages/server-core/src/git/git-service.ts | 20 +++++++++++++++---- .../server-core/test/git/git-service.spec.ts | 18 ++++++++++++++++- 4 files changed, 35 insertions(+), 7 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index cc3c5fdf..743823e4 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -178,7 +178,7 @@ Everything in our registry has a `nanoforge.manifest.json` and a name `@scope/na ### Folder trust (local editors) - A local project's code runs only in a **trusted folder** (`TrustStore`, `DATA_DIR/trusted-folders.json`, by real path; seeded with the recent projects when first created). Trusted: `nanoforge.config.ts` is executed, project plugins load and their server entries run, builds, games, dependency installs, the project's Prettier and its git hooks run. -- An untrusted folder opens in **restricted mode**: the config is read statically (as in a hosted editor), project plugins stay out, Play explains why, git only reads (`GitService`: status, history, branches and stashes listed; the hosted hardening on, every filter, diff and merge driver off whatever config sets it, so Git LFS files may show as modified, no lazy fetch or transport, submodules skipped; a config it cannot list in full, or a repository or work tree outside the folder (gitfile, `.git` link, `core.worktree`, a linked worktree), refuses the command) and refuses every write or remote with `FORBIDDEN`, formatting uses the bundled Prettier. A sticky notification and `project.trust` offer **Trust this folder** (`projects.trust`, then the project reopens). +- An untrusted folder opens in **restricted mode**: the config is read statically (as in a hosted editor), project plugins stay out, Play explains why, git only reads (`GitService`: status, history, branches and stashes listed; the hosted hardening on, every filter, diff and merge driver off whatever config sets it, so Git LFS files may show as modified, no lazy fetch or transport, submodules skipped; a config it cannot list in full, or a repository or work tree outside the folder (gitfile, `.git` link, `commondir`, object alternates, `core.worktree`, a linked worktree or submodule folder), refuses the command) and refuses every write or remote with `FORBIDDEN`, formatting uses the bundled Prettier. A sticky notification and `project.trust` offer **Trust this folder** (`projects.trust`, then the project reopens). - Server gates go through `ProjectRegistry.assertTrusted(project, what)`; `OpenProject.trusted` and `ClientProject.trusted` carry the state. A new code path that runs project code needs the gate. - `plugins.list` never runs anything: the client calls `plugins.runProjectServers` with the project plugins that loaded. - The editor shell is served with `frame-ancestors 'self'` / `X-Frame-Options: SAMEORIGIN`, so another site cannot frame it and get a click on **Trust and open**. diff --git a/docs/docs/editor/git.mdx b/docs/docs/editor/git.mdx index 3b9c67f8..2d1f8e11 100644 --- a/docs/docs/editor/git.mdx +++ b/docs/docs/editor/git.mdx @@ -8,7 +8,7 @@ In a local editor, the **VCS** menu and two panels work with the project's Git r A project that is not a repository yet: _VCS › Initialize repository_. -In a folder opened in restricted mode, Git only shows the repository: its changes, history, branches and stashes. Initializing, committing, staging, rolling back, branches, stashes and remotes need **Trust this folder** first, since the folder's own Git settings could run commands. Git LFS files may show as modified until then, because no filter runs. +In a folder opened in restricted mode, Git only shows the repository: its changes, history, branches and stashes. Initializing, committing, staging, rolling back, branches, stashes and remotes need **Trust this folder** first, since the folder's own Git settings could run commands. Git LFS files may show as modified until then, because no filter runs. A folder whose repository is not inside it (a linked worktree, a submodule's folder, a `.git` file or link, a `core.worktree` setting) shows no Git until it is trusted. ## Commit diff --git a/packages/server-core/src/git/git-service.ts b/packages/server-core/src/git/git-service.ts index 413d0407..7ca814f6 100644 --- a/packages/server-core/src/git/git-service.ts +++ b/packages/server-core/src/git/git-service.ts @@ -483,7 +483,8 @@ export class GitService { * Checks a restricted repository and returns the driver settings to turn off: every scope's, * since the folder's `.gitattributes` picks which driver runs (git-lfs reads the repository's * own `lfs.*` commands). The repository and its work tree must be the folder itself (no - * gitfile, `.git` link or `core.worktree` elsewhere). Anything it cannot check is refused. + * gitfile, `.git` link, `commondir`, `core.worktree` or object alternates elsewhere). + * Anything it cannot check is refused. */ private async _restrictedDrivers(cwd: string): Promise { const git = (args: string[]) => @@ -501,17 +502,28 @@ export class GitService { new RpcError('FORBIDDEN', `${why}: trust this folder to use git here`); const [config, where] = await Promise.all([ git(['config', '--list', '--name-only', '--includes', '-z']), - git(['rev-parse', '--show-toplevel', '--absolute-git-dir']), + git([ + 'rev-parse', + '--path-format=absolute', + '--show-toplevel', + '--git-dir', + '--git-common-dir', + ]), ]); if (config.exitCode !== 0 || config.truncated) throw refuse("This folder's git config could not be checked"); - const [top = '', gitDir = ''] = where.stdout.split('\n'); + /** No `.git` at all: the command fails as in any folder ("not a git repository"). */ + if (where.exitCode !== 0 && !existsSync(join(cwd, '.git'))) return []; + const [top = '', gitDir = '', commonDir = ''] = where.stdout.split('\n'); const folder = await realpath(cwd); + const own = join(folder, '.git'); const real = (path: string) => realpath(path).catch(() => ''); if ( where.exitCode !== 0 || (await real(top)) !== folder || - (await real(gitDir)) !== join(folder, '.git') + (await real(gitDir)) !== own || + (await real(commonDir)) !== own || + existsSync(join(own, 'objects/info/alternates')) ) { throw refuse("This folder's repository is not inside it"); } diff --git a/packages/server-core/test/git/git-service.spec.ts b/packages/server-core/test/git/git-service.spec.ts index 479cf2a2..5e39b58d 100644 --- a/packages/server-core/test/git/git-service.spec.ts +++ b/packages/server-core/test/git/git-service.spec.ts @@ -244,7 +244,8 @@ describe('an untrusted folder', () => { try { await service.projectStatus(root); } finally { - process.env.HOME = previous; + if (previous === undefined) delete process.env.HOME; + else process.env.HOME = previous; } expect(existsSync(join(marks, 'process'))).toBe(false); }); @@ -263,9 +264,24 @@ describe('an untrusted folder', () => { mkdirSync(linked); symlinkSync(join(outside, '.git'), join(linked, '.git')); await expect(service.branches(linked)).rejects.toMatchObject({ code: 'FORBIDDEN' }); + const common = await repository('untrusted-commondir'); + writeFileSync(join(common, '.git/commondir'), `${join(outside, '.git')}\n`); + await expect(service.branches(common)).rejects.toMatchObject({ code: 'FORBIDDEN' }); + const borrowing = await repository('untrusted-alternates'); + writeFileSync( + join(borrowing, '.git/objects/info/alternates'), + `${join(outside, '.git/objects')}\n`, + ); + await expect(service.branches(borrowing)).rejects.toMatchObject({ code: 'FORBIDDEN' }); expect((await service.log(outside)).length).toBe(1); }); + it('still says a plain folder is not a repository', async () => { + const plain = join(workspace, 'untrusted-plain'); + mkdirSync(plain); + await expect(untrusted().branches(plain)).rejects.toThrow(/not a git repository/); + }); + it("does not run a submodule's own commands either", async () => { const service = untrusted(); const inner = await repository('untrusted-inner'); From 65d1b8fb068c3f8374bf1dcac4a277d6c4c334d5 Mon Sep 17 00:00:00 2001 From: Exelo Date: Mon, 23 Nov 2026 02:35:58 +0100 Subject: [PATCH 4/4] fix(server-core): refuse a bare or foreign repository in an untrusted folder --- docs/docs/editor/git.mdx | 2 +- packages/server-core/src/git/git-service.ts | 7 ++++--- .../server-core/test/git/git-service.spec.ts | 16 ++++++++++++++++ 3 files changed, 21 insertions(+), 4 deletions(-) diff --git a/docs/docs/editor/git.mdx b/docs/docs/editor/git.mdx index 2d1f8e11..27652be2 100644 --- a/docs/docs/editor/git.mdx +++ b/docs/docs/editor/git.mdx @@ -8,7 +8,7 @@ In a local editor, the **VCS** menu and two panels work with the project's Git r A project that is not a repository yet: _VCS › Initialize repository_. -In a folder opened in restricted mode, Git only shows the repository: its changes, history, branches and stashes. Initializing, committing, staging, rolling back, branches, stashes and remotes need **Trust this folder** first, since the folder's own Git settings could run commands. Git LFS files may show as modified until then, because no filter runs. A folder whose repository is not inside it (a linked worktree, a submodule's folder, a `.git` file or link, a `core.worktree` setting) shows no Git until it is trusted. +In a folder opened in restricted mode, Git only shows the repository: its changes, history, branches and stashes. Initializing, committing, staging, rolling back, branches, stashes and remotes need **Trust this folder** first, since the folder's own Git settings could run commands. Git LFS files may show as modified until then, because no filter runs. A folder whose repository is not inside it (a linked worktree, a submodule's folder, a `.git` file or link, a `core.worktree` setting, a repository that borrows objects from another with `clone --shared` or `--reference`) shows no Git until it is trusted. This check needs Git 2.31 or later: an older Git shows no Git in any folder until it is trusted. ## Commit diff --git a/packages/server-core/src/git/git-service.ts b/packages/server-core/src/git/git-service.ts index 7ca814f6..3cda02e6 100644 --- a/packages/server-core/src/git/git-service.ts +++ b/packages/server-core/src/git/git-service.ts @@ -512,8 +512,9 @@ export class GitService { ]); if (config.exitCode !== 0 || config.truncated) throw refuse("This folder's git config could not be checked"); - /** No `.git` at all: the command fails as in any folder ("not a git repository"). */ - if (where.exitCode !== 0 && !existsSync(join(cwd, '.git'))) return []; + /** Git finds no repository: the command fails as in any folder. Any other failure is refused. */ + const drivers = config.stdout.split('\0').filter((key) => DRIVER_COMMAND.test(key)); + if (where.exitCode !== 0 && /not a git repository/.test(where.stderr)) return drivers; const [top = '', gitDir = '', commonDir = ''] = where.stdout.split('\n'); const folder = await realpath(cwd); const own = join(folder, '.git'); @@ -527,7 +528,7 @@ export class GitService { ) { throw refuse("This folder's repository is not inside it"); } - return config.stdout.split('\0').filter((key) => DRIVER_COMMAND.test(key)); + return drivers; } private async _configured(cwd: string, key: string): Promise { diff --git a/packages/server-core/test/git/git-service.spec.ts b/packages/server-core/test/git/git-service.spec.ts index 5e39b58d..30f4818f 100644 --- a/packages/server-core/test/git/git-service.spec.ts +++ b/packages/server-core/test/git/git-service.spec.ts @@ -276,6 +276,22 @@ describe('an untrusted folder', () => { expect((await service.log(outside)).length).toBe(1); }); + it('refuses a folder that is a bare repository or a git dir', async () => { + const service = untrusted(); + const outside = await repository('untrusted-bare-source'); + const bare = join(workspace, 'untrusted-bare'); + raw(workspace, 'clone', '-q', '--bare', outside, bare); + await expect(service.log(bare)).resolves.toEqual([]); + await expect(service.branches(bare)).rejects.toMatchObject({ code: 'FORBIDDEN' }); + const layout = join(workspace, 'untrusted-bare-commondir'); + raw(workspace, 'init', '-q', '--bare', layout); + writeFileSync(join(layout, 'commondir'), `${join(outside, '.git')}\n`); + await expect(service.branches(layout)).rejects.toMatchObject({ code: 'FORBIDDEN' }); + await expect(service.branches(join(outside, '.git'))).rejects.toMatchObject({ + code: 'FORBIDDEN', + }); + }); + it('still says a plain folder is not a repository', async () => { const plain = join(workspace, 'untrusted-plain'); mkdirSync(plain);