Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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, 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**.
Expand Down
2 changes: 2 additions & 0 deletions docs/docs/editor/git.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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. 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

The **Commit** panel on the left lists what changed since the last commit, as files with their folder beside the name:
Expand Down
110 changes: 104 additions & 6 deletions packages/server-core/src/git/git-service.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { existsSync } from 'node:fs';
import { realpath } from 'node:fs/promises';
import { dirname, join } from 'node:path';

import type {
Expand Down Expand Up @@ -28,8 +29,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. 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)$/;

/** 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();
Expand All @@ -39,8 +67,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`) 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<boolean>,
) {}
Expand Down Expand Up @@ -411,14 +440,30 @@ export class GitService {
network = false,
extraEnv: Record<string, string> = {},
) {
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._restrictedDrivers(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',
Expand All @@ -427,12 +472,65 @@ 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;
}

/**
* 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, `commondir`, `core.worktree` or object alternates elsewhere).
* Anything it cannot check is refused.
*/
private async _restrictedDrivers(cwd: string): Promise<string[]> {
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({}, RESTRICTED_CONFIG),
},
}).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',
'--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");
/** 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');
const real = (path: string) => realpath(path).catch(() => '');
if (
where.exitCode !== 0 ||
(await real(top)) !== folder ||
(await real(gitDir)) !== own ||
(await real(commonDir)) !== own ||
existsSync(join(own, 'objects/info/alternates'))
) {
throw refuse("This folder's repository is not inside it");
}
return drivers;
}

private async _configured(cwd: string, key: string): Promise<boolean> {
const result = await this._exec(cwd, ['config', '--get', key]).catch(() => undefined);
return result?.exitCode === 0 && result.stdout.trim() !== '';
Expand Down
Loading
Loading