@zergai/ztc 0.26.2-dev.202611210149 → 0.26.4-dev.202611231953
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +590 -28
- package/bin/zmux-darwin-arm64 +0 -0
- package/bin/zmux-linux-x64 +0 -0
- package/bin/ztc-audio-darwin-arm64 +0 -0
- package/bin/ztc-capture-darwin-arm64 +0 -0
- package/bin/ztc-tui-darwin-arm64 +0 -0
- package/bin/ztc-tui-linux-x64 +0 -0
- package/bin/zterm-darwin-arm64 +2 -2
- package/dist/App.js +18 -1
- package/dist/agent/agent.d.ts +25 -1
- package/dist/agent/agent.js +26 -1
- package/dist/agent/attached_images.d.ts +58 -0
- package/dist/agent/attached_images.js +145 -0
- package/dist/agent/backends/anthropic.d.ts +14 -0
- package/dist/agent/backends/anthropic.js +49 -2
- package/dist/agent/backends/codex_app_server.d.ts +3 -1
- package/dist/agent/backends/codex_app_server.js +9 -6
- package/dist/agent/backends/codex_auth.js +3 -0
- package/dist/agent/backends/gemini.js +3 -0
- package/dist/agent/backends/host_effort_policy.js +14 -2
- package/dist/agent/backends/http_error.d.ts +17 -0
- package/dist/agent/backends/http_error.js +50 -1
- package/dist/agent/backends/index.js +2 -1
- package/dist/agent/backends/model_redirect.d.ts +47 -0
- package/dist/agent/backends/model_redirect.js +97 -0
- package/dist/agent/backends/openai_compatible.js +5 -0
- package/dist/agent/backends/openai_responses.d.ts +9 -1
- package/dist/agent/backends/openai_responses.js +21 -12
- package/dist/agent/backends/prompt_cache.d.ts +8 -0
- package/dist/agent/backends/prompt_cache.js +10 -0
- package/dist/agent/backends/provider_ids.d.ts +1 -1
- package/dist/agent/backends/provider_ids.js +1 -1
- package/dist/agent/backends/types.d.ts +8 -0
- package/dist/agent/backends/zerg-api.js +5 -1
- package/dist/agent/backends/zrouter_stream.d.ts +75 -9
- package/dist/agent/backends/zrouter_stream.js +250 -49
- package/dist/agent/commands/config.js +51 -4
- package/dist/agent/commands/connect.js +20 -0
- package/dist/agent/commands/credential_status.js +5 -3
- package/dist/agent/commands/debug.js +3 -0
- package/dist/agent/commands/diff.js +9 -5
- package/dist/agent/commands/emulation.js +7 -1
- package/dist/agent/commands/inbox.js +4 -3
- package/dist/agent/commands/mcp.js +3 -0
- package/dist/agent/commands/models.js +20 -3
- package/dist/agent/commands/permissions.js +16 -2
- package/dist/agent/commands/provider_selection.js +13 -6
- package/dist/agent/commands/settings.js +15 -4
- package/dist/agent/commands/status.js +23 -1
- package/dist/agent/commands/types.d.ts +34 -3
- package/dist/agent/commands/update.d.ts +2 -1
- package/dist/agent/commands/update.js +8 -3
- package/dist/agent/commands/zerg.d.ts +6 -0
- package/dist/agent/commands/zerg.js +152 -28
- package/dist/agent/commands/ztc_pane.js +8 -5
- package/dist/agent/factory.js +22 -4
- package/dist/agent/request_encoder.js +11 -2
- package/dist/agent/runtime/command_jobs.js +16 -1
- package/dist/agent/runtime/command_panes.js +4 -1
- package/dist/agent/runtime/execution_context.d.ts +8 -1
- package/dist/agent/runtime/execution_context.js +8 -2
- package/dist/agent/runtime/policy.d.ts +66 -5
- package/dist/agent/runtime/policy.js +161 -33
- package/dist/agent/runtime/remote_broker_transport.d.ts +7 -0
- package/dist/agent/runtime/remote_broker_transport.js +33 -3
- package/dist/agent/runtime/remote_resource_errors.d.ts +7 -0
- package/dist/agent/runtime/remote_resource_errors.js +10 -0
- package/dist/agent/runtime/remote_resources.d.ts +1 -1
- package/dist/agent/runtime/remote_resources.js +7 -3
- package/dist/agent/runtime/source_verification.js +15 -12
- package/dist/agent/runtime/tool_runtime.js +165 -58
- package/dist/agent/runtime/verifier_capture.d.ts +1 -1
- package/dist/agent/runtime/verifier_capture.js +6 -0
- package/dist/agent/runtime/work_base.js +46 -14
- package/dist/agent/tools/adaptation.js +29 -12
- package/dist/agent/tools/apply_patch.js +62 -5
- package/dist/agent/tools/background.js +2 -0
- package/dist/agent/tools/benchmark_cpu.js +2 -0
- package/dist/agent/tools/bus_message.d.ts +4 -2
- package/dist/agent/tools/bus_message.js +21 -3
- package/dist/agent/tools/delegate.js +2 -0
- package/dist/agent/tools/file.d.ts +12 -1
- package/dist/agent/tools/file.js +92 -11
- package/dist/agent/tools/lsp.d.ts +12 -0
- package/dist/agent/tools/lsp.js +61 -5
- package/dist/agent/tools/pane.js +20 -45
- package/dist/agent/tools/project_context.js +5 -2
- package/dist/agent/tools/routine.js +20 -4
- package/dist/agent/tools/screenshot.d.ts +8 -0
- package/dist/agent/tools/screenshot.js +39 -25
- package/dist/agent/tools/search.js +31 -3
- package/dist/agent/tools/shell.js +7 -1
- package/dist/agent/tools/supervision.js +6 -0
- package/dist/agent/tools/types.d.ts +18 -0
- package/dist/agent/tools/zerg.js +15 -19
- package/dist/agent/tools/ztc_command.d.ts +15 -4
- package/dist/agent/tools/ztc_command.js +48 -34
- package/dist/app/agent_runner.js +8 -6
- package/dist/app/conversation_compaction.d.ts +6 -3
- package/dist/app/conversation_compaction.js +6 -3
- package/dist/app/tool_callbacks.js +1 -0
- package/dist/audio/sfx.js +6 -0
- package/dist/batch/worktree.js +22 -10
- package/dist/board/client.js +2 -1
- package/dist/cli_main.d.ts +1 -0
- package/dist/cli_main.js +141 -45
- package/dist/cli_ratatui.d.ts +49 -4
- package/dist/cli_ratatui.js +355 -79
- package/dist/conductor_branch.js +4 -1
- package/dist/config/host_credentials.d.ts +157 -0
- package/dist/config/host_credentials.js +589 -0
- package/dist/config/model_pin.d.ts +111 -0
- package/dist/config/model_pin.js +182 -0
- package/dist/config/own_state_files.d.ts +35 -0
- package/dist/config/own_state_files.js +161 -0
- package/dist/config/permission_pin.d.ts +148 -0
- package/dist/config/permission_pin.js +203 -0
- package/dist/config/permissions.d.ts +9 -2
- package/dist/config/permissions.js +14 -3
- package/dist/config/platform_login.d.ts +72 -0
- package/dist/config/platform_login.js +111 -0
- package/dist/config/profile_limits.d.ts +34 -0
- package/dist/config/profile_limits.js +66 -0
- package/dist/config/provider_api_key_env.js +3 -2
- package/dist/config/provider_models.d.ts +6 -1
- package/dist/config/provider_models.js +38 -11
- package/dist/config/repo_config.d.ts +22 -0
- package/dist/config/repo_config.js +77 -3
- package/dist/config/router_runtime_grant.d.ts +53 -0
- package/dist/config/router_runtime_grant.js +131 -0
- package/dist/config/settings_merge.d.ts +22 -0
- package/dist/config/settings_merge.js +75 -0
- package/dist/config/types.d.ts +8 -0
- package/dist/config.d.ts +334 -4
- package/dist/config.js +1024 -41
- package/dist/context/project_intelligence.d.ts +11 -2
- package/dist/context/project_intelligence.js +38 -15
- package/dist/desktop/daily/desktop_wiring.js +8 -6
- package/dist/desktop/daily/native_pane_launcher.js +2 -1
- package/dist/desktop/daily/native_tool.d.ts +1 -1
- package/dist/desktop/daily/native_tool.js +4 -3
- package/dist/desktop/daily/process_identity.js +10 -2
- package/dist/desktop/daily/source_baseline.js +4 -3
- package/dist/diagnostics/native_terminal_benchmark.js +3 -2
- package/dist/diagnostics/session_export.js +27 -14
- package/dist/embedded/anempa_runtime.js +3 -3
- package/dist/embedded/gameboy_runtime.js +5 -4
- package/dist/embedded/zergpod_runtime.js +5 -4
- package/dist/emulation/catalog.js +6 -1
- package/dist/emulation/tool_adapters.js +13 -3
- package/dist/environment/store.js +5 -4
- package/dist/extension_discovery.d.ts +12 -2
- package/dist/extension_discovery.js +52 -7
- package/dist/headless.d.ts +8 -0
- package/dist/headless.js +52 -13
- package/dist/headless_cli.js +16 -1
- package/dist/headless_workflow_trigger.js +1 -1
- package/dist/hooks/dispatcher.d.ts +8 -0
- package/dist/hooks/dispatcher.js +22 -2
- package/dist/hooks/lifecycle.d.ts +6 -0
- package/dist/hooks/lifecycle.js +1 -0
- package/dist/hooks/program_files.d.ts +10 -0
- package/dist/hooks/program_files.js +175 -0
- package/dist/hooks/runner.d.ts +11 -1
- package/dist/hooks/runner.js +112 -11
- package/dist/hooks/types.d.ts +2 -0
- package/dist/host_credentials_startup.d.ts +6 -0
- package/dist/host_credentials_startup.js +17 -0
- package/dist/instance_registry.d.ts +6 -2
- package/dist/instance_registry.js +9 -15
- package/dist/intake/format.d.ts +6 -0
- package/dist/intake/format.js +9 -0
- package/dist/intake/notifications.js +2 -1
- package/dist/lsp/manager.d.ts +1 -1
- package/dist/lsp/manager.js +4 -5
- package/dist/mcp/client.d.ts +2 -0
- package/dist/mcp/client.js +116 -18
- package/dist/mcp/registry.d.ts +12 -0
- package/dist/mcp/registry.js +15 -1
- package/dist/modes/handlers.js +14 -5
- package/dist/panes/agent_cli.d.ts +23 -1
- package/dist/panes/agent_cli.js +96 -1
- package/dist/panes/agent_panes.d.ts +27 -4
- package/dist/panes/agent_panes.js +73 -11
- package/dist/panes/editor_program.d.ts +8 -0
- package/dist/panes/editor_program.js +25 -0
- package/dist/panes/motsi.d.ts +11 -1
- package/dist/panes/motsi.js +14 -1
- package/dist/panes/pane_registry.d.ts +28 -1
- package/dist/panes/pane_registry.js +25 -0
- package/dist/panes/worker_route.js +5 -3
- package/dist/panes/ztc_launch.d.ts +8 -0
- package/dist/panes/ztc_launch.js +26 -1
- package/dist/profile_baseline.js +2 -0
- package/dist/router_auth.d.ts +8 -3
- package/dist/router_auth.js +34 -2
- package/dist/runtime_info.js +56 -38
- package/dist/session.js +12 -2
- package/dist/shannon/runtime.js +13 -1
- package/dist/simulation/domains/loader.d.ts +2 -1
- package/dist/simulation/domains/loader.js +19 -2
- package/dist/simulation/living/context.d.ts +8 -8
- package/dist/simulation/living/types.d.ts +2 -2
- package/dist/simulation/memory/embedding.d.ts +2 -1
- package/dist/simulation/memory/embedding.js +25 -6
- package/dist/terminal_attach.js +2 -1
- package/dist/types.d.ts +21 -0
- package/dist/ui/ratatui/headless_pane_manager.d.ts +12 -6
- package/dist/ui/ratatui/headless_pane_manager.js +65 -21
- package/dist/ui/ratatui/ipc_path.d.ts +41 -2
- package/dist/ui/ratatui/ipc_path.js +164 -5
- package/dist/ui/ratatui/pane_credential_broker.d.ts +17 -4
- package/dist/ui/ratatui/pane_credential_broker.js +23 -5
- package/dist/ui/ratatui/pane_relay.d.ts +74 -0
- package/dist/ui/ratatui/pane_relay.js +188 -13
- package/dist/ui/ratatui/process.d.ts +15 -1
- package/dist/ui/ratatui/process.js +129 -163
- package/dist/ui/ratatui/protocol.d.ts +11 -1
- package/dist/ui/ratatui/protocol.js +6 -0
- package/dist/ui/ratatui/ztc_launch_trust.d.ts +87 -0
- package/dist/ui/ratatui/ztc_launch_trust.js +249 -0
- package/dist/utils/admitted_open.d.ts +40 -0
- package/dist/utils/admitted_open.js +111 -0
- package/dist/utils/clipboard.js +2 -1
- package/dist/utils/computer_native.js +12 -56
- package/dist/utils/dictation.js +15 -12
- package/dist/utils/dictation_native.js +17 -60
- package/dist/utils/git_probe_options.d.ts +28 -0
- package/dist/utils/git_probe_options.js +30 -0
- package/dist/utils/git_program_files.d.ts +145 -0
- package/dist/utils/git_program_files.js +1282 -0
- package/dist/utils/git_repository_programs.d.ts +13 -0
- package/dist/utils/git_repository_programs.js +38 -0
- package/dist/utils/host_shell.js +2 -1
- package/dist/utils/idle_compaction.js +8 -1
- package/dist/utils/image_fit.d.ts +4 -1
- package/dist/utils/image_fit.js +6 -2
- package/dist/utils/image_preview.js +3 -2
- package/dist/utils/mirror_media.d.ts +22 -4
- package/dist/utils/mirror_media.js +87 -86
- package/dist/utils/ml_native.js +11 -56
- package/dist/utils/native_install.d.ts +55 -0
- package/dist/utils/native_install.js +107 -0
- package/dist/utils/open_url.js +2 -0
- package/dist/utils/process_end.d.ts +16 -0
- package/dist/utils/process_end.js +73 -0
- package/dist/utils/router_catalog.js +9 -2
- package/dist/utils/sandbox.d.ts +64 -1
- package/dist/utils/sandbox.js +397 -89
- package/dist/utils/shell.js +31 -12
- package/dist/utils/subprocess_env.d.ts +218 -2
- package/dist/utils/subprocess_env.js +429 -11
- package/dist/utils/system_ps.d.ts +5 -0
- package/dist/utils/system_ps.js +30 -0
- package/dist/utils/tts.js +5 -0
- package/dist/utils/tts_native.js +13 -60
- package/dist/utils/zlicky_overlay.js +17 -50
- package/dist/utils/ztc_own_state.d.ts +58 -0
- package/dist/utils/ztc_own_state.js +236 -0
- package/dist/web/mirror_authenticator.d.ts +67 -6
- package/dist/web/mirror_authenticator.js +131 -22
- package/dist/web/mirror_stream.d.ts +54 -10
- package/dist/web/mirror_stream.js +379 -92
- package/dist/web/observer_query_redaction.js +53 -13
- package/dist/web/observer_secret_redaction.d.ts +59 -0
- package/dist/web/observer_secret_redaction.js +714 -0
- package/dist/web/pane_credentials.d.ts +20 -2
- package/dist/web/pane_credentials.js +58 -5
- package/dist/worker/executor.js +3 -1
- package/dist/workspace_collision.js +19 -15
- package/dist/zerg/local_zerg_launches.d.ts +27 -0
- package/dist/zerg/local_zerg_launches.js +198 -0
- package/dist/zlm-embed.mjs +6257 -2791
- package/npm-shrinkwrap.json +1 -1
- package/package.json +42 -15
|
@@ -0,0 +1,1282 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The files where a repository names the programs git starts, which a command in an OS sandbox whose profile lets it
|
|
3
|
+
* write may not change (utils/sandbox.ts). A sandboxed command that commits could otherwise write .git/config (an
|
|
4
|
+
* fsmonitor, an external diff, a textconv driver or clean filter, a signature program, core.hooksPath) or a hook, and
|
|
5
|
+
* git would start that program later as whoever runs git there next, outside the sandbox: the person's own git, ZTC's
|
|
6
|
+
* own (utils/git_probe_options.ts), a later session under a profile that limits nothing (the reviewer's round-1 probe,
|
|
7
|
+
* item 3). The file tools refuse .git, and what this names outside it (agent/runtime/policy.ts).
|
|
8
|
+
*
|
|
9
|
+
* For each repository a command may write: the one its working directory is in, the session's own (wherever the
|
|
10
|
+
* command runs), each writable root's, each one whose work tree a bounded walk of a writable root finds (a folder ZTC
|
|
11
|
+
* started in that holds repositories, a command whose cwd is the writable root above its repository: the reviewer's
|
|
12
|
+
* round-1 probe), each linked worktree and submodule of one of them in a writable root, and every one an earlier plan
|
|
13
|
+
* of this ZTC process found (knownGitDirectories). A plan asks git about them, and protects too, by where it is, each
|
|
14
|
+
* .git it looks at that holds a git directory, whether or not git takes it for a repository now (the folders from the
|
|
15
|
+
* command's and the session's up to their writable root, and each work tree the walk finds), and each submodule's git
|
|
16
|
+
* directory in .git/modules that holds a config, HEAD or not: a command may remove a repository's HEAD, refs and
|
|
17
|
+
* objects, which it may write since checkouts and commits do, and git then takes its .git for none; it may fill the
|
|
18
|
+
* folders a plan's walk reads, the git runs it makes and a modules folder; and an rm -r it starts leaves .git, its
|
|
19
|
+
* config and hooks. None of that lets the next command write what a plan protected (the reviewer's round-1 follow-up
|
|
20
|
+
* probes):
|
|
21
|
+
* - its config (<commondir>/config, and <gitdir>/config where that differs), config.worktree (the worktree's and the
|
|
22
|
+
* common directory's), and the commondir of each git directory, which would point git at another common directory
|
|
23
|
+
* and its config;
|
|
24
|
+
* - a linked worktree's .git file, which names its git directory;
|
|
25
|
+
* - the hooks folders: <commondir>/hooks and the folder core.hooksPath names, unless the repository tracks files in that
|
|
26
|
+
* one (a .githooks, husky 8's .husky): those hooks are its code, which a command changes as it changes any tracked file
|
|
27
|
+
* (through the index or a commit), so a read-only folder would only keep a checkout, merge or stash from updating them
|
|
28
|
+
* (the reviewer's round-1 probe). The plan says so instead (`notes`);
|
|
29
|
+
* - every other linked worktree's folder in the common directory, <commondir>/worktrees/<name>: its commondir and
|
|
30
|
+
* config.worktree, and the .git file its gitdir names, wherever that worktree lies (the person's git there would
|
|
31
|
+
* follow a commondir the command rewrote to a common directory of its own: the reviewer's round-1 probe). Only those
|
|
32
|
+
* there when the command starts: a worktree it adds (git worktree add) is its own, as a repository it creates is;
|
|
33
|
+
* - every submodule's git directory, <commondir>/modules/<name> and the ones nested in each: its config, config.worktree,
|
|
34
|
+
* commondir and hooks folder, and, asked of git, the .git file of its work tree and its own core.hooksPath folder (the
|
|
35
|
+
* person's git status in the superproject runs git status in each submodule, with its config: the reviewer's round-1
|
|
36
|
+
* probe);
|
|
37
|
+
* - pinned, so that none of them is carried off under another name and its name taken by a new one: the git
|
|
38
|
+
* directories, the .git entry, and each folder from a writable root down to them, which may not be renamed, removed
|
|
39
|
+
* or replaced, while what they hold still can be (objects, refs, the index, HEAD, logs, FETCH_HEAD: commits, staging,
|
|
40
|
+
* branches and fetches work). So rm -r of a folder that holds such a repository still fails, once it has removed what
|
|
41
|
+
* the command may write there: Seatbelt checks a rename's source as a removal, so a folder a command may remove is one
|
|
42
|
+
* it may rename, out of reach of rules that go by path, and write the config of at its new name.
|
|
43
|
+
* A link among them counts as its name and as its target. Only what lies inside a writable root is listed: nothing else
|
|
44
|
+
* is the command's to write. Every name is as the filesystem spells it (realpath(3)), since Seatbelt matches the paths
|
|
45
|
+
* the kernel reports; on a volume that ignores case, Seatbelt matches a name in any letter case, missing ones too.
|
|
46
|
+
*
|
|
47
|
+
* Both backends protect the repositories the plan finds or an earlier plan of this process found when the command
|
|
48
|
+
* starts, and only those: a repository the command makes (git init, git clone, git worktree add, a submodule it checks
|
|
49
|
+
* out or absorbs) is its own in that command, on macOS as on Linux, and the next command's plan finds it, where the walk
|
|
50
|
+
* reaches, and protects it from then on. (The item owner's decision, round 1: Seatbelt rules by name that refused such
|
|
51
|
+
* repositories kept a command from cloning, initializing a repository or adding a worktree, the agent's common work,
|
|
52
|
+
* against a narrow risk, a program planted in the config of a repository the same command made.) bwrap can refuse only
|
|
53
|
+
* what exists when the command starts, and not a new name in a folder it binds writable: the step after a command there
|
|
54
|
+
* (undoGitProgramWrites) removes a protected file it made and puts back a protected link it replaced. On both, the step
|
|
55
|
+
* after a command puts back what it broke of a repository the plan knew, so that git takes its folder for that
|
|
56
|
+
* repository again before anything reads the command's result (putBackBrokenRepositories): a repository the same command
|
|
57
|
+
* made in a folder above it, which git would read once that repository's HEAD is broken (the walk-up route of the R3e
|
|
58
|
+
* review), is never read in its place. Where a plan stops looking (the walk's folders, its git runs, a modules or
|
|
59
|
+
* worktrees folder), it says so (`notes`). What stays open, a repository past those limits that no plan of this process
|
|
60
|
+
* found (a ZTC started after a command filled them), and a repository broken while its command still runs, or by a
|
|
61
|
+
* process the command left running, is in the README's Limits.
|
|
62
|
+
*/
|
|
63
|
+
import { execFileSync } from 'node:child_process';
|
|
64
|
+
import { randomBytes } from 'node:crypto';
|
|
65
|
+
import { accessSync, chmodSync, closeSync, constants, existsSync, fchmodSync, fstatSync, lstatSync, mkdirSync, openSync, readdirSync, readlinkSync, readSync, realpathSync, renameSync, rmSync, statSync, symlinkSync, unlinkSync, writeFileSync, writeSync } from 'node:fs';
|
|
66
|
+
import { homedir } from 'node:os';
|
|
67
|
+
import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
|
|
68
|
+
import { GIT_PROBE_OPTIONS } from './git_probe_options.js';
|
|
69
|
+
import { buildGitSubprocessEnv, buildGitSubprocessEnvFor } from './subprocess_env.js';
|
|
70
|
+
const inside = (path, root) => path === root || path.startsWith(root.endsWith(sep) ? root : `${root}${sep}`);
|
|
71
|
+
/** PATH's nearest existing folder or file as the filesystem spells it, and the names after it, as given. */
|
|
72
|
+
function existingPart(path) {
|
|
73
|
+
const rest = [];
|
|
74
|
+
for (let current = path;; current = dirname(current)) {
|
|
75
|
+
try {
|
|
76
|
+
return { existing: realpathSync.native(current), rest };
|
|
77
|
+
}
|
|
78
|
+
catch {
|
|
79
|
+
if (dirname(current) === current)
|
|
80
|
+
return { existing: current, rest };
|
|
81
|
+
rest.unshift(basename(current));
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
/** PATH as it really is, or, for what does not exist, its nearest existing folder as it really is with the rest after it. */
|
|
86
|
+
function realOrNamed(path) {
|
|
87
|
+
const { existing, rest } = existingPart(path);
|
|
88
|
+
return rest.length === 0 ? existing : join(existing, ...rest);
|
|
89
|
+
}
|
|
90
|
+
/** The names a write to PATH reaches it by: its entry (the folders above it as they really are), and a link's target. */
|
|
91
|
+
function spellings(path) {
|
|
92
|
+
const parent = dirname(path);
|
|
93
|
+
const entry = parent === path ? path : join(realOrNamed(parent), basename(path));
|
|
94
|
+
let target;
|
|
95
|
+
try {
|
|
96
|
+
if (lstatSync(entry).isSymbolicLink()) {
|
|
97
|
+
try {
|
|
98
|
+
target = realpathSync.native(entry);
|
|
99
|
+
}
|
|
100
|
+
catch {
|
|
101
|
+
target = realOrNamed(resolve(dirname(entry), readlinkSync(entry)));
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
catch { /* nothing there yet: its entry is all there is */ }
|
|
106
|
+
return target && target !== entry ? [entry, target] : [entry];
|
|
107
|
+
}
|
|
108
|
+
/**
|
|
109
|
+
* The repository PROBE names, as git finds it (with the options and environment ZTC's own git takes), or null: git's
|
|
110
|
+
* own answers, so a linked worktree's common directory, a submodule's work tree (its core.worktree) and core.hooksPath
|
|
111
|
+
* (relative to the work tree, or with ~) are what git itself would use.
|
|
112
|
+
*/
|
|
113
|
+
function repositoryLayout(probe) {
|
|
114
|
+
const gitDirProbe = 'gitDir' in probe;
|
|
115
|
+
let output;
|
|
116
|
+
try {
|
|
117
|
+
output = execFileSync('git', [...(gitDirProbe ? ['--git-dir', probe.gitDir] : ['-C', probe.directory]), ...GIT_PROBE_OPTIONS,
|
|
118
|
+
'rev-parse', '--path-format=absolute', '--git-dir', '--git-common-dir', '--git-path', 'hooks', '--git-path', 'config',
|
|
119
|
+
'--git-path', 'config.worktree', '--show-toplevel'], {
|
|
120
|
+
// A git directory named outright is git's own whatever the environment says; it runs from inside it, so git takes no
|
|
121
|
+
// other folder for its work tree than the one its core.worktree names.
|
|
122
|
+
cwd: gitDirProbe ? probe.gitDir : undefined,
|
|
123
|
+
env: gitDirProbe ? buildGitSubprocessEnv() : buildGitSubprocessEnvFor(probe.directory),
|
|
124
|
+
encoding: 'utf8', timeout: 2000, maxBuffer: 64 * 1024, stdio: ['ignore', 'pipe', 'ignore'], windowsHide: true,
|
|
125
|
+
});
|
|
126
|
+
}
|
|
127
|
+
catch (error) {
|
|
128
|
+
// Outside a work tree, --show-toplevel fails after git has answered the rest.
|
|
129
|
+
const stdout = error.stdout;
|
|
130
|
+
output = typeof stdout === 'string' ? stdout : '';
|
|
131
|
+
}
|
|
132
|
+
const lines = output.split('\n').filter(Boolean);
|
|
133
|
+
if (lines.length < 5 || lines.slice(0, 5).some(line => !isAbsolute(line)))
|
|
134
|
+
return null;
|
|
135
|
+
const [gitDir, commonDir, hooks, config, worktreeConfig, top] = lines;
|
|
136
|
+
// A git directory without a core.worktree has no work tree of its own: git took the folder it ran in for one.
|
|
137
|
+
const workTree = top !== undefined && isAbsolute(top) && !(gitDirProbe && inside(realOrNamed(top), realOrNamed(gitDir))) ? top : null;
|
|
138
|
+
return { gitDir, commonDir, hooks, config, worktreeConfig, top: workTree };
|
|
139
|
+
}
|
|
140
|
+
const depth = (path) => path.split(sep).length;
|
|
141
|
+
const count = (value) => value.toLocaleString('en-US');
|
|
142
|
+
/** How many repositories one plan asks git about, at most: each is a git run, and a plan runs before every command. */
|
|
143
|
+
const MAX_PROBES = 48;
|
|
144
|
+
/** How deep below a writable root the walk for work trees looks, and how many folders it reads in all. */
|
|
145
|
+
const MAX_WALK_DEPTH = 4;
|
|
146
|
+
const MAX_WALK_FOLDERS = 2000;
|
|
147
|
+
/** Folders the walk does not enter: package trees, which hold no repository of the person's and can hold thousands of folders. */
|
|
148
|
+
const WALK_SKIPPED = new Set(['node_modules']);
|
|
149
|
+
/**
|
|
150
|
+
* Each folder in ROOTS, or below one down to MAX_WALK_DEPTH, that holds a .git entry (in any letter case, as git finds
|
|
151
|
+
* one on a volume that ignores case): where a repository's work tree begins. Breadth first, so the shallow ones are
|
|
152
|
+
* found before the walk stops; no link is followed, and no .git or node_modules is entered. With them, each of ROOTS
|
|
153
|
+
* (as the filesystem spells it) that still held folders unread when the walk stopped at MAX_WALK_FOLDERS.
|
|
154
|
+
*/
|
|
155
|
+
function workTreesBelow(roots) {
|
|
156
|
+
const found = [];
|
|
157
|
+
const starts = [...new Set(roots.map(root => realOrNamed(resolve(root))))];
|
|
158
|
+
let level = starts;
|
|
159
|
+
let read = 0;
|
|
160
|
+
for (let depth = 0; level.length > 0 && depth <= MAX_WALK_DEPTH; depth++) {
|
|
161
|
+
const next = [];
|
|
162
|
+
for (const [index, folder] of level.entries()) {
|
|
163
|
+
if (read++ >= MAX_WALK_FOLDERS) {
|
|
164
|
+
const unread = [...level.slice(index), ...(depth < MAX_WALK_DEPTH ? next : [])];
|
|
165
|
+
return { found, stoppedIn: starts.filter(start => unread.some(path => inside(path, start))) };
|
|
166
|
+
}
|
|
167
|
+
let entries;
|
|
168
|
+
try {
|
|
169
|
+
entries = readdirSync(folder, { withFileTypes: true });
|
|
170
|
+
}
|
|
171
|
+
catch {
|
|
172
|
+
continue;
|
|
173
|
+
}
|
|
174
|
+
for (const entry of entries) {
|
|
175
|
+
const name = entry.name.toLowerCase();
|
|
176
|
+
if (name === '.git')
|
|
177
|
+
found.push(folder);
|
|
178
|
+
else if (entry.isDirectory() && !WALK_SKIPPED.has(name))
|
|
179
|
+
next.push(join(folder, entry.name));
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
level = next;
|
|
183
|
+
}
|
|
184
|
+
return { found, stoppedIn: [] };
|
|
185
|
+
}
|
|
186
|
+
/** How many of a common directory's linked worktrees one plan reads, at most. */
|
|
187
|
+
const MAX_WORKTREES = 256;
|
|
188
|
+
/**
|
|
189
|
+
* A small regular file's text, or undefined: a pointer git wrote (a gitdir or commondir file), which lies where the
|
|
190
|
+
* command could have written it before, so a FIFO or a link to /dev/zero there is seen for what it is.
|
|
191
|
+
*/
|
|
192
|
+
function readPointer(path, limit = 4096) {
|
|
193
|
+
let fd;
|
|
194
|
+
try {
|
|
195
|
+
fd = openSync(path, constants.O_RDONLY | (constants.O_NONBLOCK ?? 0));
|
|
196
|
+
const info = fstatSync(fd);
|
|
197
|
+
if (!info.isFile() || info.size > limit)
|
|
198
|
+
return undefined;
|
|
199
|
+
const buffer = Buffer.alloc(limit + 1);
|
|
200
|
+
const read = readSync(fd, buffer, 0, buffer.length, 0);
|
|
201
|
+
return read > limit ? undefined : buffer.subarray(0, read).toString('utf8');
|
|
202
|
+
}
|
|
203
|
+
catch {
|
|
204
|
+
return undefined;
|
|
205
|
+
}
|
|
206
|
+
finally {
|
|
207
|
+
if (fd !== undefined)
|
|
208
|
+
closeSync(fd);
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
/**
|
|
212
|
+
* Whether the repository whose work tree is TOP tracks files in FOLDER, a folder in that work tree (its top included),
|
|
213
|
+
* as git ls-files says: then the hooks core.hooksPath runs from there are the repository's code.
|
|
214
|
+
*/
|
|
215
|
+
function tracksFilesIn(top, folder) {
|
|
216
|
+
const realTop = realOrNamed(top);
|
|
217
|
+
const realFolder = realOrNamed(folder);
|
|
218
|
+
if (!inside(realFolder, realTop))
|
|
219
|
+
return false;
|
|
220
|
+
const path = relative(realTop, realFolder);
|
|
221
|
+
if (path.split(sep).some(part => part.toLowerCase() === '.git'))
|
|
222
|
+
return false;
|
|
223
|
+
try {
|
|
224
|
+
return execFileSync('git', ['-C', realTop, ...GIT_PROBE_OPTIONS, 'ls-files', '-z', '--', `:(literal)${path || '.'}`], {
|
|
225
|
+
env: buildGitSubprocessEnv(), encoding: 'utf8', timeout: 2000, maxBuffer: 64 * 1024, stdio: ['ignore', 'pipe', 'ignore'],
|
|
226
|
+
windowsHide: true,
|
|
227
|
+
}).length > 0;
|
|
228
|
+
}
|
|
229
|
+
catch (error) {
|
|
230
|
+
// More tracked files there than the answer may hold is tracked files there.
|
|
231
|
+
return error.code === 'ENOBUFS';
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
/** How many folders of a common directory's modules folder one plan reads, at most. */
|
|
235
|
+
const MAX_MODULE_FOLDERS = 512;
|
|
236
|
+
/** Whether what is at PATH is one of KINDS. */
|
|
237
|
+
const isKind = (path, ...kinds) => kinds.includes(kindOf(path));
|
|
238
|
+
/**
|
|
239
|
+
* Whether FOLDER, in a modules folder, is a submodule's git directory rather than a folder its name passes through
|
|
240
|
+
* (modules/libs of modules/libs/foo): it holds a config, which no sandboxed command may remove, or a HEAD beside its
|
|
241
|
+
* objects. Not a HEAD alone, which a command may remove (git then takes the git directory for none) and which a
|
|
242
|
+
* reflog's folder (logs) and a remote's (refs/remotes/origin) hold too; nor a hooks or objects folder, which a folder
|
|
243
|
+
* its name passes through holds when a submodule is named libs/hooks or libs/objects.
|
|
244
|
+
*/
|
|
245
|
+
const isSubmoduleGitDir = (folder) => isKind(join(folder, 'config'), 'file', 'link')
|
|
246
|
+
|| (isKind(join(folder, 'HEAD'), 'file', 'link') && isKind(join(folder, 'objects'), 'folder', 'link'));
|
|
247
|
+
/**
|
|
248
|
+
* The git directories of the submodules git keeps in COMMON_DIR/modules, as git names them there (a name may hold a
|
|
249
|
+
* slash: modules/libs/foo), and those nested in each one's own modules folder, shallowest first; and whether the plan
|
|
250
|
+
* stopped reading them at MAX_MODULE_FOLDERS.
|
|
251
|
+
*/
|
|
252
|
+
function submoduleGitDirs(commonDir) {
|
|
253
|
+
const found = [];
|
|
254
|
+
const folders = [join(commonDir, 'modules')];
|
|
255
|
+
for (let read = 0; folders.length > 0; read++) {
|
|
256
|
+
if (read >= MAX_MODULE_FOLDERS)
|
|
257
|
+
return { found, cut: true };
|
|
258
|
+
const folder = folders.shift();
|
|
259
|
+
let names;
|
|
260
|
+
try {
|
|
261
|
+
names = readdirSync(folder).sort();
|
|
262
|
+
}
|
|
263
|
+
catch {
|
|
264
|
+
continue;
|
|
265
|
+
}
|
|
266
|
+
for (const name of names) {
|
|
267
|
+
const path = join(folder, name);
|
|
268
|
+
if (kindOf(path) !== 'folder')
|
|
269
|
+
continue;
|
|
270
|
+
if (isSubmoduleGitDir(path)) {
|
|
271
|
+
found.push(path);
|
|
272
|
+
folders.push(join(path, 'modules'));
|
|
273
|
+
}
|
|
274
|
+
else {
|
|
275
|
+
folders.push(path);
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
return { found, cut: false };
|
|
280
|
+
}
|
|
281
|
+
/**
|
|
282
|
+
* The linked worktrees git keeps in COMMON_DIR/worktrees: each one's folder there, and the .git file of its work tree
|
|
283
|
+
* that the folder's gitdir names (absolute, or relative to the folder under worktree.useRelativePaths), when it names
|
|
284
|
+
* one; and whether there were more than MAX_WORKTREES to read.
|
|
285
|
+
*/
|
|
286
|
+
function linkedWorktrees(commonDir) {
|
|
287
|
+
let names;
|
|
288
|
+
try {
|
|
289
|
+
names = readdirSync(join(commonDir, 'worktrees')).sort();
|
|
290
|
+
}
|
|
291
|
+
catch {
|
|
292
|
+
return { found: [], cut: false };
|
|
293
|
+
}
|
|
294
|
+
const worktrees = [];
|
|
295
|
+
for (const name of names.slice(0, MAX_WORKTREES)) {
|
|
296
|
+
const folder = join(commonDir, 'worktrees', name);
|
|
297
|
+
if (kindOf(folder) !== 'folder')
|
|
298
|
+
continue;
|
|
299
|
+
const named = readPointer(join(folder, 'gitdir'))?.split(/\r?\n/, 1)[0]?.trim();
|
|
300
|
+
const gitFile = named ? resolve(folder, named) : null;
|
|
301
|
+
worktrees.push({ folder, gitFile: gitFile !== null && basename(gitFile).toLowerCase() === '.git' ? gitFile : null });
|
|
302
|
+
}
|
|
303
|
+
return { found: worktrees, cut: names.length > MAX_WORKTREES };
|
|
304
|
+
}
|
|
305
|
+
/** The folder a .git file at ENTRY names (its `gitdir:` line, relative to the file's folder), or undefined. */
|
|
306
|
+
function gitFileTarget(entry) {
|
|
307
|
+
const line = readPointer(entry)?.split(/\r?\n/, 1)[0];
|
|
308
|
+
const named = line === undefined ? undefined : /^gitdir:\s*(.*?)\s*$/.exec(line)?.[1];
|
|
309
|
+
return named ? resolve(dirname(entry), named) : undefined;
|
|
310
|
+
}
|
|
311
|
+
/**
|
|
312
|
+
* Whether FOLDER, which a .git is or names, holds what names a git directory's programs or makes it one again: a
|
|
313
|
+
* config, a HEAD, a commondir or a hooks folder. A command may remove a repository's HEAD, refs and objects, and git
|
|
314
|
+
* then takes its .git for none; never its config or hooks once a plan has protected them (an rm -r leaves those).
|
|
315
|
+
*/
|
|
316
|
+
const holdsGitDirectory = (folder) => ['config', 'HEAD', 'commondir'].some(name => isKind(join(folder, name), 'file', 'link'))
|
|
317
|
+
|| isKind(join(folder, 'hooks'), 'folder', 'link');
|
|
318
|
+
/**
|
|
319
|
+
* The git directory the .git at ENTRY is (a folder, or a link to one) or names (a .git file), as the filesystem spells
|
|
320
|
+
* it, when it holds one (holdsGitDirectory), whether or not git takes it for a repository; else null.
|
|
321
|
+
*/
|
|
322
|
+
function gitDirectoryAt(entry) {
|
|
323
|
+
const kind = kindOf(entry);
|
|
324
|
+
const named = kind === 'folder' || kind === 'link' ? entry : kind === 'file' ? gitFileTarget(entry) : undefined;
|
|
325
|
+
if (named === undefined)
|
|
326
|
+
return null;
|
|
327
|
+
const gitDir = realOrNamed(named);
|
|
328
|
+
return kindOf(gitDir) === 'folder' && holdsGitDirectory(gitDir) ? gitDir : null;
|
|
329
|
+
}
|
|
330
|
+
/**
|
|
331
|
+
* Whether git can take the .git at ENTRY for a repository, so asking it is worth one of a plan's git runs: what it is
|
|
332
|
+
* or names holds a HEAD. A .git that is no repository (an empty .git file, a folder of no git directory) is not asked
|
|
333
|
+
* about, so folders of them do not use up the git runs a plan makes.
|
|
334
|
+
*/
|
|
335
|
+
function mayAnswer(entry) {
|
|
336
|
+
const kind = kindOf(entry);
|
|
337
|
+
const named = kind === 'folder' || kind === 'link' ? entry : kind === 'file' ? gitFileTarget(entry) : undefined;
|
|
338
|
+
return named !== undefined && isKind(join(realOrNamed(named), 'HEAD'), 'file', 'link');
|
|
339
|
+
}
|
|
340
|
+
const PROTECTIONS = ['config', 'file', 'folder', 'pin'];
|
|
341
|
+
/**
|
|
342
|
+
* Every git directory a plan of this ZTC process has found, by git's answer or by where it is, with what that plan
|
|
343
|
+
* protected for it, and every one an earlier ZTC kept in the record this one took as it started (knownRepositoryRecord):
|
|
344
|
+
* every later plan protects it again before it looks for repositories, outside the limits it looks within, whether or
|
|
345
|
+
* not git still takes it for a repository (the reviewer's round-1 follow-up probes). A command may write a repository's
|
|
346
|
+
* HEAD, refs and objects (checkouts and commits do), and git takes a .git without them for none; it may remove all of a
|
|
347
|
+
* repository that it may write; and it may fill the folders a plan's walk reads, the git runs it makes, or a modules
|
|
348
|
+
* folder. Without this record the next plan found none of those repositories, and the next command wrote their config;
|
|
349
|
+
* kept only per process, a ZTC started after such a command found none of them either. A record goes once its git
|
|
350
|
+
* directory is gone, which no sandboxed command can make so (it is pinned): the person removed it, and the next plan
|
|
351
|
+
* finds what is there now.
|
|
352
|
+
*/
|
|
353
|
+
const knownGitDirectories = new Map();
|
|
354
|
+
/**
|
|
355
|
+
* Where ZTC keeps knownGitDirectories for the ZTCs started after it: in its own state under HOME (~/.ztc), which no
|
|
356
|
+
* command under a profile that limits the agent reaches (utils/ztc_own_state.ts), and not in its config folder, which a
|
|
357
|
+
* hosted resident's start rewrites (its ZTC_CONFIG_DIR is a tmpfs).
|
|
358
|
+
*/
|
|
359
|
+
export function knownRepositoryRecordPath() {
|
|
360
|
+
return join(homedir(), '.ztc', 'sandbox', 'known-repositories.json');
|
|
361
|
+
}
|
|
362
|
+
/** How many repositories the record keeps: those plans found last are kept first. */
|
|
363
|
+
const MAX_RECORDED = 512;
|
|
364
|
+
/** How many paths of one kind the record keeps for one repository; a plan protects a handful. */
|
|
365
|
+
const MAX_RECORDED_PATHS = 64;
|
|
366
|
+
/** The largest record ZTC writes or reads. */
|
|
367
|
+
const MAX_RECORD_BYTES = 4 * 1024 * 1024;
|
|
368
|
+
/** This process's record, as read from PATH: what ZTC says of it (once), and whether it is to be written again. */
|
|
369
|
+
let recordState = null;
|
|
370
|
+
/** What ZTC says when it starts without the record of a ZTC before it: what this costs the command. */
|
|
371
|
+
const UNRECORDED = 'a repository an earlier ZTC found that this one\'s plans do not (deeper than they look, or past the folders they '
|
|
372
|
+
+ 'read) is not protected from this command.';
|
|
373
|
+
const isRecord = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
374
|
+
const isPath = (value) => typeof value === 'string' && value.length <= 4096 && isAbsolute(value) && !value.includes('\0');
|
|
375
|
+
const isMode = (value) => typeof value === 'number' && Number.isInteger(value) && value >= 0 && value <= 0o7777;
|
|
376
|
+
/** A whole repository as a record holds it, or undefined where it is not one (wholeHead's test of a HEAD among it). */
|
|
377
|
+
function recordedWhole(value) {
|
|
378
|
+
if (!isRecord(value) || !isRecord(value.head) || !isRecord(value.modes))
|
|
379
|
+
return undefined;
|
|
380
|
+
const { head, modes } = value;
|
|
381
|
+
if (!isMode(modes.gitDir) || !isMode(modes.refs) || !isMode(modes.objects))
|
|
382
|
+
return undefined;
|
|
383
|
+
const whole = { gitDir: modes.gitDir, refs: modes.refs, objects: modes.objects };
|
|
384
|
+
const listed = value.reach ?? [];
|
|
385
|
+
if (!Array.isArray(listed) || listed.length > MAX_RECORDED_PATHS
|
|
386
|
+
|| !listed.every(step => isRecord(step) && isPath(step.folder) && isMode(step.mode)))
|
|
387
|
+
return undefined;
|
|
388
|
+
const reach = listed.map(({ folder, mode }) => ({ folder, mode }));
|
|
389
|
+
if (typeof head.link === 'string') {
|
|
390
|
+
return head.link.length <= 4096 && head.link.startsWith('refs/') ? { head: { link: head.link }, modes: whole, reach } : undefined;
|
|
391
|
+
}
|
|
392
|
+
if (typeof head.text !== 'string' || head.text.length > 4096 || !isMode(head.mode))
|
|
393
|
+
return undefined;
|
|
394
|
+
const start = head.text.slice(0, HEAD_READ);
|
|
395
|
+
return /^ref:[ \t\n\r]*refs\//.test(start) || /^[0-9a-fA-F]{40}/.test(start)
|
|
396
|
+
? { head: { text: head.text, mode: head.mode }, modes: whole, reach } : undefined;
|
|
397
|
+
}
|
|
398
|
+
/** The repositories TEXT records, by git directory, or why it is no record ZTC wrote. */
|
|
399
|
+
function parseRecord(text) {
|
|
400
|
+
let data;
|
|
401
|
+
try {
|
|
402
|
+
data = JSON.parse(text);
|
|
403
|
+
}
|
|
404
|
+
catch {
|
|
405
|
+
return 'it is not JSON';
|
|
406
|
+
}
|
|
407
|
+
if (!isRecord(data) || data.version !== 1 || !isRecord(data.repositories))
|
|
408
|
+
return 'it is not version 1 of ZTC\'s record';
|
|
409
|
+
const entries = Object.entries(data.repositories);
|
|
410
|
+
if (entries.length > MAX_RECORDED)
|
|
411
|
+
return `it holds more than ${count(MAX_RECORDED)} repositories`;
|
|
412
|
+
const repositories = new Map();
|
|
413
|
+
for (const [key, value] of entries) {
|
|
414
|
+
if (!isPath(key) || !isRecord(value) || !isPath(value.gitDir) || !isPath(value.commonDir))
|
|
415
|
+
return `${key} is not a repository's entry`;
|
|
416
|
+
const paths = { config: new Set(), file: new Set(), folder: new Set(), pin: new Set() };
|
|
417
|
+
for (const kind of PROTECTIONS) {
|
|
418
|
+
const listed = value[kind];
|
|
419
|
+
if (!Array.isArray(listed) || listed.length > MAX_RECORDED_PATHS || !listed.every(isPath))
|
|
420
|
+
return `${key} lists no ${kind} paths ZTC wrote`;
|
|
421
|
+
for (const path of listed)
|
|
422
|
+
paths[kind].add(path);
|
|
423
|
+
}
|
|
424
|
+
const whole = value.whole === undefined ? null : recordedWhole(value.whole);
|
|
425
|
+
if (whole === undefined)
|
|
426
|
+
return `${key} holds no HEAD ZTC saw whole`;
|
|
427
|
+
repositories.set(value.gitDir, { paths, commonDir: value.commonDir, workTree: key === value.gitDir ? null : key, whole });
|
|
428
|
+
}
|
|
429
|
+
return repositories;
|
|
430
|
+
}
|
|
431
|
+
/**
|
|
432
|
+
* The record at PATH, read as ZTC reads its own state: only a regular file of its own with one name (a link or another
|
|
433
|
+
* name could lead into the agent's workspace), opened without following a link, no larger than ZTC writes one, and one
|
|
434
|
+
* ZTC wrote. Else what ZTC says, starting a new one; or, where there is none, that it is not there.
|
|
435
|
+
*/
|
|
436
|
+
function readRecord(path) {
|
|
437
|
+
const unread = (why) => ({ problem: `ZTC did not read its record of the repositories earlier ZTCs found: ${path} ${why}, `
|
|
438
|
+
+ `and ZTC reads its own state only from a regular file of its own with one name. It starts a new one: ${UNRECORDED}` });
|
|
439
|
+
const unreadable = (error) => ({ problem: `ZTC could not read its record of the repositories earlier ZTCs found `
|
|
440
|
+
+ `(${path}: ${error.code ?? error.message}), so it starts a new one: ${UNRECORDED}` });
|
|
441
|
+
const notOurs = (why) => ({ problem: `ZTC did not take ${path} as its record of the repositories earlier ZTCs `
|
|
442
|
+
+ `found: it is not a record ZTC wrote (${why}). It starts a new one: ${UNRECORDED}` });
|
|
443
|
+
let info;
|
|
444
|
+
try {
|
|
445
|
+
info = lstatSync(path);
|
|
446
|
+
}
|
|
447
|
+
catch (error) {
|
|
448
|
+
return ['ENOENT', 'ENOTDIR'].includes(error.code ?? '') ? { missing: true } : unreadable(error);
|
|
449
|
+
}
|
|
450
|
+
if (info.isSymbolicLink()) {
|
|
451
|
+
let target = '';
|
|
452
|
+
try {
|
|
453
|
+
target = ` (to ${resolve(dirname(path), readlinkSync(path))})`;
|
|
454
|
+
}
|
|
455
|
+
catch { /* gone since: still a link when seen */ }
|
|
456
|
+
return unread(`is a symbolic link${target}`);
|
|
457
|
+
}
|
|
458
|
+
if (!info.isFile())
|
|
459
|
+
return unread('is not a regular file');
|
|
460
|
+
if (info.nlink > 1)
|
|
461
|
+
return unread(`has ${info.nlink} names`);
|
|
462
|
+
if (info.size > MAX_RECORD_BYTES)
|
|
463
|
+
return notOurs('larger than ZTC writes one');
|
|
464
|
+
let fd;
|
|
465
|
+
let text;
|
|
466
|
+
try {
|
|
467
|
+
fd = openSync(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0));
|
|
468
|
+
const opened = fstatSync(fd);
|
|
469
|
+
if (!opened.isFile() || opened.dev !== info.dev || opened.ino !== info.ino)
|
|
470
|
+
return unread('changed while ZTC opened it');
|
|
471
|
+
// A byte past its size tells one that grows as ZTC reads it, which no ZTC's record does (each is written whole).
|
|
472
|
+
const buffer = Buffer.alloc(Math.min(opened.size, MAX_RECORD_BYTES) + 1);
|
|
473
|
+
let read = 0;
|
|
474
|
+
while (read < buffer.length) {
|
|
475
|
+
const chunk = readSync(fd, buffer, read, buffer.length - read, read);
|
|
476
|
+
if (chunk === 0)
|
|
477
|
+
break;
|
|
478
|
+
read += chunk;
|
|
479
|
+
}
|
|
480
|
+
if (read === buffer.length)
|
|
481
|
+
return unread('changed while ZTC read it');
|
|
482
|
+
text = buffer.subarray(0, read).toString('utf8');
|
|
483
|
+
}
|
|
484
|
+
catch (error) {
|
|
485
|
+
return unreadable(error);
|
|
486
|
+
}
|
|
487
|
+
finally {
|
|
488
|
+
if (fd !== undefined)
|
|
489
|
+
closeSync(fd);
|
|
490
|
+
}
|
|
491
|
+
const repositories = parseRecord(text);
|
|
492
|
+
return typeof repositories === 'string' ? notOurs(repositories) : { repositories };
|
|
493
|
+
}
|
|
494
|
+
/**
|
|
495
|
+
* Take the record of the repositories earlier ZTCs' plans found into knownGitDirectories, once per process (and again
|
|
496
|
+
* should HOME name another): ZTC loads it as it starts (cli_main.ts) and before its first plan. One it cannot take leaves
|
|
497
|
+
* it starting a new one, which every plan of the process notes and the first command's result says (sandbox notices are
|
|
498
|
+
* told once), and which the next plan writes. Where no ZTC has kept anything of its sandbox yet (a fresh HOME, with no
|
|
499
|
+
* folder for the record), there was no record to miss: it starts one without a word.
|
|
500
|
+
*/
|
|
501
|
+
export function loadKnownRepositoryRecord() {
|
|
502
|
+
const path = knownRepositoryRecordPath();
|
|
503
|
+
if (recordState?.path === path)
|
|
504
|
+
return;
|
|
505
|
+
const read = readRecord(path);
|
|
506
|
+
if ('repositories' in read) {
|
|
507
|
+
for (const [gitDir, repository] of read.repositories)
|
|
508
|
+
if (!knownGitDirectories.has(gitDir))
|
|
509
|
+
knownGitDirectories.set(gitDir, repository);
|
|
510
|
+
recordState = { path, note: null, unsaved: false };
|
|
511
|
+
return;
|
|
512
|
+
}
|
|
513
|
+
const note = !('missing' in read) ? read.problem
|
|
514
|
+
: !existsSync(dirname(path)) ? null
|
|
515
|
+
: `ZTC has no record of the repositories earlier ZTCs found: ${path} is not there, so it starts a new one, and ${UNRECORDED}`;
|
|
516
|
+
recordState = { path, note, unsaved: true };
|
|
517
|
+
}
|
|
518
|
+
/** At most the first MAX of VALUES. */
|
|
519
|
+
const capped = (values, max) => [...values].slice(0, max);
|
|
520
|
+
/** ENTRIES as the record holds them, by work tree (by git directory where there is none, or where two share one). */
|
|
521
|
+
function recordText(entries) {
|
|
522
|
+
const repositories = {};
|
|
523
|
+
for (const [gitDir, { paths, commonDir, workTree, whole }] of entries) {
|
|
524
|
+
const key = workTree !== null && !Object.hasOwn(repositories, workTree) ? workTree : gitDir;
|
|
525
|
+
if (Object.hasOwn(repositories, key))
|
|
526
|
+
continue;
|
|
527
|
+
repositories[key] = { gitDir, commonDir, config: capped(paths.config, MAX_RECORDED_PATHS), file: capped(paths.file, MAX_RECORDED_PATHS),
|
|
528
|
+
folder: capped(paths.folder, MAX_RECORDED_PATHS), pin: capped(paths.pin, MAX_RECORDED_PATHS), ...(whole ? { whole } : {}) };
|
|
529
|
+
}
|
|
530
|
+
return `${JSON.stringify({ version: 1, repositories })}\n`;
|
|
531
|
+
}
|
|
532
|
+
/**
|
|
533
|
+
* Write knownGitDirectories to the record, with what another ZTC has kept there since that this one does not know, the
|
|
534
|
+
* repositories plans found last kept first within its bounds, and none whose git directory is gone (the person removed
|
|
535
|
+
* it: a plan pins it): a file of ZTC's own made beside it and moved into place, so a ZTC reading it sees the old record
|
|
536
|
+
* or the new one, and a link or another name at its place is replaced, never written through. What ZTC says when it
|
|
537
|
+
* could not.
|
|
538
|
+
*/
|
|
539
|
+
function saveKnownRepositoryRecord(path) {
|
|
540
|
+
const theirs = readRecord(path);
|
|
541
|
+
const merged = new Map();
|
|
542
|
+
if ('repositories' in theirs) {
|
|
543
|
+
for (const [gitDir, repository] of theirs.repositories) {
|
|
544
|
+
if (!knownGitDirectories.has(gitDir) && kindOf(gitDir) === 'folder')
|
|
545
|
+
merged.set(gitDir, repository);
|
|
546
|
+
}
|
|
547
|
+
}
|
|
548
|
+
for (const [gitDir, repository] of knownGitDirectories) {
|
|
549
|
+
if (kindOf(gitDir) === 'folder')
|
|
550
|
+
merged.set(gitDir, repository);
|
|
551
|
+
else
|
|
552
|
+
knownGitDirectories.delete(gitDir);
|
|
553
|
+
}
|
|
554
|
+
let entries = [...merged].slice(-MAX_RECORDED);
|
|
555
|
+
let text = recordText(entries);
|
|
556
|
+
while (Buffer.byteLength(text) > MAX_RECORD_BYTES && entries.length > 0) {
|
|
557
|
+
entries = entries.slice(Math.ceil(entries.length / 2));
|
|
558
|
+
text = recordText(entries);
|
|
559
|
+
}
|
|
560
|
+
const temporary = join(dirname(path), `.known-repositories.${process.pid}.${randomBytes(4).toString('hex')}.tmp`);
|
|
561
|
+
try {
|
|
562
|
+
mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
|
|
563
|
+
writeFileSync(temporary, text, { encoding: 'utf8', mode: 0o600, flag: 'wx' });
|
|
564
|
+
renameSync(temporary, path);
|
|
565
|
+
return null;
|
|
566
|
+
}
|
|
567
|
+
catch (error) {
|
|
568
|
+
try {
|
|
569
|
+
unlinkSync(temporary);
|
|
570
|
+
}
|
|
571
|
+
catch { /* never made */ }
|
|
572
|
+
return `ZTC could not keep its record of the repositories it found in ${path} (${error.code ?? error.message}): `
|
|
573
|
+
+ 'a ZTC started later protects only those its own plans find.';
|
|
574
|
+
}
|
|
575
|
+
}
|
|
576
|
+
/** The most of a HEAD git reads to tell whether it names a ref or a commit (validate_headref). */
|
|
577
|
+
const HEAD_READ = 255;
|
|
578
|
+
/**
|
|
579
|
+
* GIT_DIR's HEAD as git takes it for a repository's (validate_headref), or null: a link that leads into refs/, or a
|
|
580
|
+
* regular file whose first bytes name a ref (`ref: refs/...`) or a commit (an object name). Opened without following a
|
|
581
|
+
* link or waiting, so a FIFO there is seen for what it is; the text is kept as its bytes, for putting it back.
|
|
582
|
+
*/
|
|
583
|
+
function wholeHead(gitDir) {
|
|
584
|
+
const path = join(gitDir, 'HEAD');
|
|
585
|
+
let info;
|
|
586
|
+
try {
|
|
587
|
+
info = lstatSync(path);
|
|
588
|
+
}
|
|
589
|
+
catch {
|
|
590
|
+
return null;
|
|
591
|
+
}
|
|
592
|
+
if (info.isSymbolicLink()) {
|
|
593
|
+
try {
|
|
594
|
+
const link = readlinkSync(path);
|
|
595
|
+
return link.startsWith('refs/') ? { link } : null;
|
|
596
|
+
}
|
|
597
|
+
catch {
|
|
598
|
+
return null;
|
|
599
|
+
}
|
|
600
|
+
}
|
|
601
|
+
if (!info.isFile())
|
|
602
|
+
return null;
|
|
603
|
+
let fd;
|
|
604
|
+
try {
|
|
605
|
+
fd = openSync(path, constants.O_RDONLY | (constants.O_NONBLOCK ?? 0) | (constants.O_NOFOLLOW ?? 0));
|
|
606
|
+
const buffer = Buffer.alloc(4096);
|
|
607
|
+
const text = buffer.subarray(0, readSync(fd, buffer, 0, buffer.length, 0)).toString('latin1');
|
|
608
|
+
const start = text.slice(0, HEAD_READ);
|
|
609
|
+
return /^ref:[ \t\n\r]*refs\//.test(start) || /^[0-9a-fA-F]{40}/.test(start) ? { text, mode: info.mode & 0o7777 } : null;
|
|
610
|
+
}
|
|
611
|
+
catch {
|
|
612
|
+
return null;
|
|
613
|
+
}
|
|
614
|
+
finally {
|
|
615
|
+
if (fd !== undefined)
|
|
616
|
+
closeSync(fd);
|
|
617
|
+
}
|
|
618
|
+
}
|
|
619
|
+
/** Whether git may enter PATH, as it asks (access X_OK): a folder it can search, or a link to one. */
|
|
620
|
+
function enterable(path) {
|
|
621
|
+
try {
|
|
622
|
+
accessSync(path, constants.X_OK);
|
|
623
|
+
return true;
|
|
624
|
+
}
|
|
625
|
+
catch {
|
|
626
|
+
return false;
|
|
627
|
+
}
|
|
628
|
+
}
|
|
629
|
+
/**
|
|
630
|
+
* GIT_DIR, whose common directory is COMMON_DIR, as git takes it for a repository (is_git_directory), or null: a HEAD it
|
|
631
|
+
* takes (wholeHead), and refs and objects folders it may enter; and REACH, the folders from below the writable root down
|
|
632
|
+
* to its work tree's top, each one git may pass through. Else git takes the folder for no repository, and in a work
|
|
633
|
+
* tree whose .git it is, looks for one in the folders above (a shell already in a folder git cannot reach from the top,
|
|
634
|
+
* on Linux, where getcwd answers whatever the permissions above, does the same).
|
|
635
|
+
*/
|
|
636
|
+
function wholeRepository(gitDir, commonDir, reach) {
|
|
637
|
+
if (!reach.every(enterable))
|
|
638
|
+
return null;
|
|
639
|
+
const head = wholeHead(gitDir);
|
|
640
|
+
const refs = join(commonDir, 'refs');
|
|
641
|
+
const objects = join(commonDir, 'objects');
|
|
642
|
+
if (head === null || !enterable(refs) || !enterable(objects))
|
|
643
|
+
return null;
|
|
644
|
+
const mode = (path) => statSync(path).mode & 0o7777;
|
|
645
|
+
try {
|
|
646
|
+
return { head, modes: { gitDir: mode(gitDir), refs: mode(refs), objects: mode(objects) }, reach: reach.map(folder => ({ folder, mode: mode(folder) })) };
|
|
647
|
+
}
|
|
648
|
+
catch {
|
|
649
|
+
return null;
|
|
650
|
+
}
|
|
651
|
+
}
|
|
652
|
+
/**
|
|
653
|
+
* What a sandboxed command working in DIRECTORIES (its cwd, the session's, the writable roots), with WRITE_ROOTS
|
|
654
|
+
* writable, may not change of the repositories there and of those a walk of the writable roots finds, and of every
|
|
655
|
+
* repository an earlier plan of this process found (knownGitDirectories).
|
|
656
|
+
*/
|
|
657
|
+
export function gitProgramFiles(directories, writeRoots, options = {}) {
|
|
658
|
+
const roots = [...new Set(writeRoots.flatMap(root => [resolve(root), realOrNamed(resolve(root))]))];
|
|
659
|
+
/** What the plan says of a core.hooksPath folder the repository tracks, by that folder. */
|
|
660
|
+
const trackedHooks = new Map();
|
|
661
|
+
/** Where the plan stopped looking for repositories. */
|
|
662
|
+
const stopped = new Set();
|
|
663
|
+
const rootHolding = (path) => roots.filter(root => inside(path, root)).sort((a, b) => b.length - a.length)[0];
|
|
664
|
+
const files = new Set();
|
|
665
|
+
const configs = new Set();
|
|
666
|
+
const folders = new Set();
|
|
667
|
+
const pinned = new Set();
|
|
668
|
+
/** Each folder from the writable root holding PATH down to PATH's own folder, the root itself aside. */
|
|
669
|
+
const pinFoldersAbove = (path) => {
|
|
670
|
+
for (let folder = dirname(path); dirname(folder) !== folder; folder = dirname(folder)) {
|
|
671
|
+
const root = rootHolding(folder);
|
|
672
|
+
if (!root || folder === root)
|
|
673
|
+
return;
|
|
674
|
+
pinned.add(folder);
|
|
675
|
+
}
|
|
676
|
+
};
|
|
677
|
+
const protect = (into, path) => {
|
|
678
|
+
const writable = spellings(path).filter(spelling => rootHolding(spelling) !== undefined);
|
|
679
|
+
for (const spelling of writable) {
|
|
680
|
+
into.add(spelling);
|
|
681
|
+
pinFoldersAbove(spelling);
|
|
682
|
+
}
|
|
683
|
+
return writable;
|
|
684
|
+
};
|
|
685
|
+
const pin = (path) => {
|
|
686
|
+
for (const spelling of spellings(path)) {
|
|
687
|
+
if (rootHolding(spelling) === undefined || rootHolding(spelling) === spelling)
|
|
688
|
+
continue;
|
|
689
|
+
pinned.add(spelling);
|
|
690
|
+
pinFoldersAbove(spelling);
|
|
691
|
+
}
|
|
692
|
+
};
|
|
693
|
+
/** Protect PATH as KIND, in this plan's writable roots (a path outside them is not the command's to write). */
|
|
694
|
+
const apply = (kind, path) => {
|
|
695
|
+
if (kind === 'pin')
|
|
696
|
+
pin(path);
|
|
697
|
+
else if (kind === 'folder')
|
|
698
|
+
protect(folders, path);
|
|
699
|
+
else
|
|
700
|
+
for (const spelling of protect(files, path))
|
|
701
|
+
if (kind === 'config')
|
|
702
|
+
configs.add(spelling);
|
|
703
|
+
};
|
|
704
|
+
const records = new Map();
|
|
705
|
+
/** What this plan keeps of the git directory GIT_DIR, for every later plan of this process. */
|
|
706
|
+
const recordOf = (gitDir) => {
|
|
707
|
+
let record = records.get(gitDir);
|
|
708
|
+
if (!record) {
|
|
709
|
+
const earlier = knownGitDirectories.get(gitDir);
|
|
710
|
+
records.set(gitDir, record = { paths: { config: new Set(), file: new Set(), folder: new Set(), pin: new Set() },
|
|
711
|
+
commonDir: earlier?.commonDir ?? gitDir, workTree: earlier?.workTree ?? null, whole: null });
|
|
712
|
+
}
|
|
713
|
+
return record;
|
|
714
|
+
};
|
|
715
|
+
/** Protect PATH as KIND for the git directory GIT_DIR, and keep it so for every later plan of this process. */
|
|
716
|
+
const keep = (gitDir, kind, path) => {
|
|
717
|
+
recordOf(gitDir).paths[kind].add(path);
|
|
718
|
+
apply(kind, path);
|
|
719
|
+
};
|
|
720
|
+
/** That GIT_DIR's common directory is COMMON_DIR, and its work tree WORK_TREE where one is known. */
|
|
721
|
+
const describe = (gitDir, commonDir, workTree) => {
|
|
722
|
+
const record = recordOf(gitDir);
|
|
723
|
+
record.commonDir = commonDir;
|
|
724
|
+
if (workTree !== null)
|
|
725
|
+
record.workTree = workTree;
|
|
726
|
+
};
|
|
727
|
+
/** A work tree's .git at ENTRY, for GIT_DIR: a .git file is protected, a folder or a link pinned, a missing one too. */
|
|
728
|
+
const keepEntry = (gitDir, entry) => keep(gitDir, kindOf(entry) === 'file' ? 'file' : 'pin', entry);
|
|
729
|
+
// First what every earlier plan found, of this process or a ZTC before it (its record, taken once), whether or not git
|
|
730
|
+
// still answers for it, and whatever this plan's limits reach below. Another workspace's, of which nothing lies in a
|
|
731
|
+
// writable root, is not this command's to write. A work tree's .git that is gone since is left out: no sandboxed
|
|
732
|
+
// command can remove one a plan protected or pinned, so the person removed it (a linked worktree's or a submodule's
|
|
733
|
+
// folder, by hand), and its path is no longer a repository's to keep.
|
|
734
|
+
loadKnownRepositoryRecord();
|
|
735
|
+
/** Whether what plans keep of the repositories changed in this plan, for the record. */
|
|
736
|
+
let changed = false;
|
|
737
|
+
const inRoots = (path) => path !== null && roots.some(root => inside(path, root));
|
|
738
|
+
const known = new Set();
|
|
739
|
+
for (const [gitDir, record] of knownGitDirectories) {
|
|
740
|
+
if (![gitDir, record.commonDir, record.workTree].some(inRoots) && !PROTECTIONS.some(kind => [...record.paths[kind]].some(inRoots)))
|
|
741
|
+
continue;
|
|
742
|
+
if (kindOf(gitDir) !== 'folder') {
|
|
743
|
+
knownGitDirectories.delete(gitDir);
|
|
744
|
+
changed = true;
|
|
745
|
+
continue;
|
|
746
|
+
}
|
|
747
|
+
known.add(gitDir);
|
|
748
|
+
for (const kind of PROTECTIONS) {
|
|
749
|
+
for (const path of record.paths[kind]) {
|
|
750
|
+
if (basename(path).toLowerCase() === '.git' && kindOf(path) === 'none')
|
|
751
|
+
continue;
|
|
752
|
+
apply(kind, path);
|
|
753
|
+
}
|
|
754
|
+
}
|
|
755
|
+
}
|
|
756
|
+
const seen = new Set();
|
|
757
|
+
const seenCommon = new Set();
|
|
758
|
+
const queue = [];
|
|
759
|
+
const queued = new Set();
|
|
760
|
+
/** What the git directory a probe asks about was before this plan: found by an earlier plan, or not. */
|
|
761
|
+
const fresh = new Map();
|
|
762
|
+
const enqueue = (probe, isFresh = true) => {
|
|
763
|
+
const key = 'gitDir' in probe ? `git:${probe.gitDir}` : `dir:${probe.directory}`;
|
|
764
|
+
if (queued.has(key))
|
|
765
|
+
return;
|
|
766
|
+
queued.add(key);
|
|
767
|
+
fresh.set(key, isFresh);
|
|
768
|
+
queue.push(probe);
|
|
769
|
+
};
|
|
770
|
+
/** Ask git about the work tree at TOP too, when a writable root holds it: its core.hooksPath is its own. */
|
|
771
|
+
const probeWorkTree = (top) => {
|
|
772
|
+
const real = realOrNamed(top);
|
|
773
|
+
if (rootHolding(real) === undefined)
|
|
774
|
+
return;
|
|
775
|
+
const gitDir = gitDirectoryAt(join(real, '.git'));
|
|
776
|
+
enqueue({ directory: real }, gitDir === null || !known.has(gitDir));
|
|
777
|
+
};
|
|
778
|
+
/**
|
|
779
|
+
* Every linked worktree and submodule of the repository whose git directory is GIT_DIR and common directory
|
|
780
|
+
* COMMON_DIR, once per common directory: what names programs in each of their git directories there, and each one's
|
|
781
|
+
* .git file; each work tree in a writable root, the main one among them, and each submodule's git directory there,
|
|
782
|
+
* are asked about in turn.
|
|
783
|
+
*/
|
|
784
|
+
const listCommonDirectory = (gitDir, commonDir) => {
|
|
785
|
+
if (seenCommon.has(commonDir))
|
|
786
|
+
return;
|
|
787
|
+
seenCommon.add(commonDir);
|
|
788
|
+
if (gitDir !== commonDir && basename(commonDir).toLowerCase() === '.git')
|
|
789
|
+
probeWorkTree(dirname(commonDir));
|
|
790
|
+
const worktrees = linkedWorktrees(commonDir);
|
|
791
|
+
if (worktrees.cut) {
|
|
792
|
+
stopped.add(`ZTC read ${count(MAX_WORKTREES)} of the linked worktrees in ${join(commonDir, 'worktrees')} and no more: one past `
|
|
793
|
+
+ 'them that ZTC has not found before is not protected from this command.');
|
|
794
|
+
}
|
|
795
|
+
for (const { folder, gitFile } of worktrees.found) {
|
|
796
|
+
const worktree = realOrNamed(folder);
|
|
797
|
+
const hasGitFile = gitFile !== null && kindOf(gitFile) === 'file';
|
|
798
|
+
describe(worktree, commonDir, hasGitFile ? realOrNamed(dirname(gitFile)) : null);
|
|
799
|
+
for (const name of ['commondir', 'config.worktree'])
|
|
800
|
+
keep(worktree, 'file', join(folder, name));
|
|
801
|
+
if (!hasGitFile)
|
|
802
|
+
continue;
|
|
803
|
+
keep(worktree, 'file', gitFile);
|
|
804
|
+
probeWorkTree(dirname(gitFile));
|
|
805
|
+
}
|
|
806
|
+
const modules = submoduleGitDirs(commonDir);
|
|
807
|
+
if (modules.cut) {
|
|
808
|
+
stopped.add(`ZTC read ${count(MAX_MODULE_FOLDERS)} folders of ${join(commonDir, 'modules')} and no more: a submodule's git `
|
|
809
|
+
+ 'directory past them that ZTC has not found before is not protected from this command.');
|
|
810
|
+
}
|
|
811
|
+
for (const module of modules.found) {
|
|
812
|
+
const moduleDir = realOrNamed(module);
|
|
813
|
+
describe(moduleDir, moduleDir, null);
|
|
814
|
+
for (const name of ['config', 'config.worktree', 'commondir'])
|
|
815
|
+
keep(moduleDir, 'file', join(module, name));
|
|
816
|
+
keep(moduleDir, 'folder', join(module, 'hooks'));
|
|
817
|
+
keep(moduleDir, 'pin', module);
|
|
818
|
+
if (rootHolding(module) !== undefined)
|
|
819
|
+
enqueue({ gitDir: module }, !known.has(moduleDir));
|
|
820
|
+
}
|
|
821
|
+
};
|
|
822
|
+
/**
|
|
823
|
+
* The .git in TOP, a folder the plan looks at, protected by where it is when it holds a git directory
|
|
824
|
+
* (gitDirectoryAt), whether or not git takes it for a repository now: its config, config.worktree, commondir and
|
|
825
|
+
* hooks, its common directory's where its commondir names one, its linked worktrees and submodules, the .git itself
|
|
826
|
+
* and the folders above them. What git's answer adds (core.hooksPath) waits for that answer.
|
|
827
|
+
*/
|
|
828
|
+
const keepByPlace = (top) => {
|
|
829
|
+
const entry = join(top, '.git');
|
|
830
|
+
const gitDir = gitDirectoryAt(entry);
|
|
831
|
+
if (gitDir === null)
|
|
832
|
+
return;
|
|
833
|
+
const named = readPointer(join(gitDir, 'commondir'))?.split(/\r?\n/, 1)[0]?.trim();
|
|
834
|
+
const pointed = named ? realOrNamed(resolve(gitDir, named)) : gitDir;
|
|
835
|
+
const commonDir = pointed !== gitDir && kindOf(pointed) === 'folder' ? pointed : gitDir;
|
|
836
|
+
describe(gitDir, commonDir, top);
|
|
837
|
+
listCommonDirectory(gitDir, commonDir);
|
|
838
|
+
keep(gitDir, 'config', join(commonDir, 'config'));
|
|
839
|
+
for (const path of [join(gitDir, 'config'), join(gitDir, 'config.worktree'), join(commonDir, 'config.worktree'), join(gitDir, 'commondir'),
|
|
840
|
+
join(commonDir, 'commondir')]) {
|
|
841
|
+
keep(gitDir, 'file', path);
|
|
842
|
+
}
|
|
843
|
+
keep(gitDir, 'folder', join(commonDir, 'hooks'));
|
|
844
|
+
keep(gitDir, 'pin', gitDir);
|
|
845
|
+
keep(gitDir, 'pin', commonDir);
|
|
846
|
+
keepEntry(gitDir, entry);
|
|
847
|
+
};
|
|
848
|
+
for (const directory of directories)
|
|
849
|
+
enqueue({ directory: resolve(directory) });
|
|
850
|
+
// Where a command runs and the session's folder, and each folder from them up to the writable root holding them (git
|
|
851
|
+
// looks there for the repository of a folder whose own .git it takes for none); then each work tree a walk of the
|
|
852
|
+
// writable roots finds. Those git may answer for are asked about after, those found before last.
|
|
853
|
+
for (const directory of directories) {
|
|
854
|
+
const real = realOrNamed(resolve(directory));
|
|
855
|
+
const root = rootHolding(real);
|
|
856
|
+
for (let folder = real; root !== undefined && inside(folder, root); folder = dirname(folder)) {
|
|
857
|
+
keepByPlace(folder);
|
|
858
|
+
if (folder === root || dirname(folder) === folder)
|
|
859
|
+
break;
|
|
860
|
+
}
|
|
861
|
+
}
|
|
862
|
+
const walk = workTreesBelow(options.walk ?? writeRoots);
|
|
863
|
+
for (const root of walk.stoppedIn) {
|
|
864
|
+
stopped.add(`ZTC looked for repositories through ${count(MAX_WALK_FOLDERS)} folders of ${root} and no further: a repository in a `
|
|
865
|
+
+ 'folder past them that ZTC has not found before is not protected from this command.');
|
|
866
|
+
}
|
|
867
|
+
const askedLater = [];
|
|
868
|
+
for (const top of walk.found) {
|
|
869
|
+
keepByPlace(top);
|
|
870
|
+
if (!mayAnswer(join(top, '.git')))
|
|
871
|
+
continue;
|
|
872
|
+
const gitDir = gitDirectoryAt(join(top, '.git'));
|
|
873
|
+
if (gitDir !== null && known.has(gitDir))
|
|
874
|
+
askedLater.push(top);
|
|
875
|
+
else
|
|
876
|
+
enqueue({ directory: top });
|
|
877
|
+
}
|
|
878
|
+
for (const top of askedLater)
|
|
879
|
+
enqueue({ directory: top }, false);
|
|
880
|
+
for (let probes = 0; queue.length > 0; probes++) {
|
|
881
|
+
if (probes >= MAX_PROBES) {
|
|
882
|
+
const unasked = queue.filter(probe => fresh.get('gitDir' in probe ? `git:${probe.gitDir}` : `dir:${probe.directory}`));
|
|
883
|
+
for (const root of new Set(unasked.map(probe => rootHolding(realOrNamed('gitDir' in probe ? probe.gitDir : probe.directory))))) {
|
|
884
|
+
if (root === undefined)
|
|
885
|
+
continue;
|
|
886
|
+
stopped.add(`ZTC asked git about ${count(MAX_PROBES)} repositories and stopped: a repository in ${root} that it has not asked `
|
|
887
|
+
+ 'about before keeps its core.hooksPath folder writable to this command (its .git/config and .git/hooks stay read-only).');
|
|
888
|
+
}
|
|
889
|
+
break;
|
|
890
|
+
}
|
|
891
|
+
const layout = repositoryLayout(queue.shift());
|
|
892
|
+
if (!layout)
|
|
893
|
+
continue;
|
|
894
|
+
const gitDir = realOrNamed(layout.gitDir);
|
|
895
|
+
const commonDir = realOrNamed(layout.commonDir);
|
|
896
|
+
if (seen.has(gitDir))
|
|
897
|
+
continue;
|
|
898
|
+
seen.add(gitDir);
|
|
899
|
+
describe(gitDir, commonDir, layout.top === null ? null : realOrNamed(layout.top));
|
|
900
|
+
listCommonDirectory(gitDir, commonDir);
|
|
901
|
+
keep(gitDir, 'config', layout.config);
|
|
902
|
+
for (const path of [join(gitDir, 'config'), layout.worktreeConfig, join(commonDir, 'config.worktree'), join(gitDir, 'commondir'),
|
|
903
|
+
join(commonDir, 'commondir')]) {
|
|
904
|
+
keep(gitDir, 'file', path);
|
|
905
|
+
}
|
|
906
|
+
// The folder core.hooksPath names, unless the repository tracks files there: its hooks are then the repository's
|
|
907
|
+
// code, and the plan says so. The common directory's own hooks folder is git's, never tracked.
|
|
908
|
+
if (layout.top !== null && tracksFilesIn(layout.top, layout.hooks)) {
|
|
909
|
+
trackedHooks.set(realOrNamed(layout.hooks), `core.hooksPath names ${realOrNamed(layout.hooks)}, which the repository tracks: its `
|
|
910
|
+
+ 'hooks are the repository\'s code, which a sandboxed command may change as it changes any tracked file, and git runs them as '
|
|
911
|
+
+ 'whoever commits or checks out there next. Review a change to them as you would any code.');
|
|
912
|
+
}
|
|
913
|
+
else {
|
|
914
|
+
keep(gitDir, 'folder', layout.hooks);
|
|
915
|
+
}
|
|
916
|
+
keep(gitDir, 'folder', join(commonDir, 'hooks'));
|
|
917
|
+
keep(gitDir, 'pin', gitDir);
|
|
918
|
+
keep(gitDir, 'pin', commonDir);
|
|
919
|
+
// None there: git found the repository by GIT_DIR, and none may be made.
|
|
920
|
+
if (layout.top !== null)
|
|
921
|
+
keepEntry(gitDir, join(layout.top, '.git'));
|
|
922
|
+
}
|
|
923
|
+
// Kept for every later plan, added to what earlier ones kept; what this plan found is the record's newest.
|
|
924
|
+
for (const [gitDir, record] of records) {
|
|
925
|
+
const kept = knownGitDirectories.get(gitDir);
|
|
926
|
+
knownGitDirectories.delete(gitDir);
|
|
927
|
+
if (!kept) {
|
|
928
|
+
knownGitDirectories.set(gitDir, record);
|
|
929
|
+
changed = true;
|
|
930
|
+
continue;
|
|
931
|
+
}
|
|
932
|
+
knownGitDirectories.set(gitDir, kept);
|
|
933
|
+
for (const kind of PROTECTIONS) {
|
|
934
|
+
for (const path of record.paths[kind]) {
|
|
935
|
+
if (kept.paths[kind].has(path))
|
|
936
|
+
continue;
|
|
937
|
+
kept.paths[kind].add(path);
|
|
938
|
+
changed = true;
|
|
939
|
+
}
|
|
940
|
+
}
|
|
941
|
+
changed ||= kept.commonDir !== record.commonDir || (record.workTree !== null && kept.workTree !== record.workTree);
|
|
942
|
+
kept.commonDir = record.commonDir;
|
|
943
|
+
if (record.workTree !== null)
|
|
944
|
+
kept.workTree = record.workTree;
|
|
945
|
+
}
|
|
946
|
+
// What git needs of each repository the command may write to take its folder for it, as it is now, where it is whole:
|
|
947
|
+
// the step after the command puts back what the command broke of it, from this or, for one already broken, from what
|
|
948
|
+
// an earlier plan saw, of this ZTC or one before it (putBackBrokenRepositories).
|
|
949
|
+
const repositories = [];
|
|
950
|
+
/** The folders from below the writable root holding WORK_TREE down to it: git passes through them to reach its .git. */
|
|
951
|
+
const reachOf = (workTree) => {
|
|
952
|
+
const root = workTree === null ? undefined : rootHolding(workTree);
|
|
953
|
+
if (workTree === null || root === undefined)
|
|
954
|
+
return [];
|
|
955
|
+
const reach = [];
|
|
956
|
+
for (let folder = workTree; folder !== root && inside(folder, root) && dirname(folder) !== folder; folder = dirname(folder))
|
|
957
|
+
reach.unshift(folder);
|
|
958
|
+
return reach;
|
|
959
|
+
};
|
|
960
|
+
for (const [gitDir, record] of knownGitDirectories) {
|
|
961
|
+
const { commonDir, workTree } = record;
|
|
962
|
+
if ([join(gitDir, 'HEAD'), join(commonDir, 'refs'), join(commonDir, 'objects')].every(path => rootHolding(path) === undefined))
|
|
963
|
+
continue;
|
|
964
|
+
const whole = wholeRepository(gitDir, commonDir, reachOf(workTree));
|
|
965
|
+
if (whole !== null && JSON.stringify(whole) !== JSON.stringify(record.whole)) {
|
|
966
|
+
record.whole = whole;
|
|
967
|
+
changed = true;
|
|
968
|
+
}
|
|
969
|
+
repositories.push({ gitDir, commonDir, workTree, whole: record.whole, brokenAtStart: whole === null });
|
|
970
|
+
}
|
|
971
|
+
// The record for the ZTCs started later, written when it changed, or where this ZTC found none it could take.
|
|
972
|
+
const said = recordState?.note ? [recordState.note] : [];
|
|
973
|
+
if (recordState && (changed || recordState.unsaved)) {
|
|
974
|
+
const failed = saveKnownRepositoryRecord(recordState.path);
|
|
975
|
+
recordState.unsaved = failed !== null;
|
|
976
|
+
if (failed !== null)
|
|
977
|
+
said.push(failed);
|
|
978
|
+
}
|
|
979
|
+
return {
|
|
980
|
+
files: [...files],
|
|
981
|
+
configs: [...configs],
|
|
982
|
+
folders: [...folders],
|
|
983
|
+
pinned: [...pinned].sort((a, b) => depth(a) - depth(b) || a.localeCompare(b)),
|
|
984
|
+
absent: [...files].filter(path => !configs.has(path) && kindOf(path) === 'none'),
|
|
985
|
+
links: [...files, ...folders, ...pinned].flatMap(path => {
|
|
986
|
+
try {
|
|
987
|
+
return lstatSync(path).isSymbolicLink() ? [{ path, target: readlinkSync(path) }] : [];
|
|
988
|
+
}
|
|
989
|
+
catch {
|
|
990
|
+
return [];
|
|
991
|
+
}
|
|
992
|
+
}),
|
|
993
|
+
// A hooks folder an earlier plan protected stays so, tracked since or not (an entry a command adds to the index
|
|
994
|
+
// would otherwise make it the command's): the plan says nothing of it then.
|
|
995
|
+
notes: [...[...trackedHooks].filter(([folder]) => !folders.has(folder)).map(([, note]) => note), ...stopped, ...said],
|
|
996
|
+
repositories,
|
|
997
|
+
};
|
|
998
|
+
}
|
|
999
|
+
const octal = (mode) => mode.toString(8).padStart(3, '0');
|
|
1000
|
+
/**
|
|
1001
|
+
* Clear PATH for ZTC to put back what belongs there, without following a link: a file, a link or anything else is
|
|
1002
|
+
* removed; a folder is moved aside, to a name beside it that ZTC returns, so that what it holds stays and nothing is
|
|
1003
|
+
* removed through a link a command swaps in while ZTC removes it.
|
|
1004
|
+
*/
|
|
1005
|
+
function clearForPutBack(path) {
|
|
1006
|
+
const kind = kindOf(path);
|
|
1007
|
+
if (kind === 'none')
|
|
1008
|
+
return null;
|
|
1009
|
+
if (kind !== 'folder') {
|
|
1010
|
+
unlinkSync(path);
|
|
1011
|
+
return null;
|
|
1012
|
+
}
|
|
1013
|
+
const aside = `${path}.ztc-${randomBytes(4).toString('hex')}`;
|
|
1014
|
+
renameSync(path, aside);
|
|
1015
|
+
return aside;
|
|
1016
|
+
}
|
|
1017
|
+
/** HEAD as a plan saw it, written where nothing is now: a link made again, a file with its text and mode, made new. */
|
|
1018
|
+
function writeHead(path, head) {
|
|
1019
|
+
if ('link' in head) {
|
|
1020
|
+
symlinkSync(head.link, path);
|
|
1021
|
+
return;
|
|
1022
|
+
}
|
|
1023
|
+
const fd = openSync(path, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | (constants.O_NOFOLLOW ?? 0), head.mode);
|
|
1024
|
+
try {
|
|
1025
|
+
writeSync(fd, Buffer.from(head.text, 'latin1'));
|
|
1026
|
+
fchmodSync(fd, head.mode);
|
|
1027
|
+
}
|
|
1028
|
+
finally {
|
|
1029
|
+
closeSync(fd);
|
|
1030
|
+
}
|
|
1031
|
+
}
|
|
1032
|
+
/**
|
|
1033
|
+
* The step after a command, on both backends (utils/sandbox.ts), once it has ended and before anything reads its result
|
|
1034
|
+
* or any other git runs there: each repository the plan knew (FILES.repositories) that git takes for none now, put back
|
|
1035
|
+
* as a plan last saw it whole. A command may write a repository's HEAD, refs and objects (checkouts, commits and fetches
|
|
1036
|
+
* do), and git takes a git directory whose HEAD names no ref or commit, or whose refs or objects folder it cannot enter,
|
|
1037
|
+
* for no repository: in a work tree whose .git that is, it looks for one in the folders above, where the same command
|
|
1038
|
+
* may have made one (git init, which a command may run anywhere it writes, or a .git file naming a git directory of its
|
|
1039
|
+
* own), and the person's git there, or a host service's, would read that config and start what it names (the walk-up
|
|
1040
|
+
* route of the R3e review). So HEAD is put back as it was, the permissions of the git directory and of the folders from
|
|
1041
|
+
* below the writable root down to the work tree too (bwrap lets a command change a pinned folder's; git, in a shell
|
|
1042
|
+
* already in a folder it cannot reach from the top, looks above on Linux), and a refs or objects folder git cannot enter
|
|
1043
|
+
* is an empty one again: one that is missing made new, one git may not enter moved aside first. A repository git takes
|
|
1044
|
+
* for one is the command's as it left it: a checkout, a commit, a branch switch, a detached HEAD, refs packed or
|
|
1045
|
+
* emptied. What ZTC did, for the command's result.
|
|
1046
|
+
*/
|
|
1047
|
+
export function putBackBrokenRepositories(files) {
|
|
1048
|
+
const said = [];
|
|
1049
|
+
for (const { gitDir, commonDir, workTree, whole, brokenAtStart } of files.repositories) {
|
|
1050
|
+
// Never seen whole, or whole, as the command left it.
|
|
1051
|
+
if (whole === null || wholeRepository(gitDir, commonDir, whole.reach.map(({ folder }) => folder)) !== null)
|
|
1052
|
+
continue;
|
|
1053
|
+
/** What ZTC put back, or could not, each told once all is done, when what git finds there is known. */
|
|
1054
|
+
const done = [];
|
|
1055
|
+
// The folders down to its work tree, which git passes through to reach it: a plan pins them, so each is still the
|
|
1056
|
+
// folder the plan saw, but bwrap lets a command change a pinned folder's permissions (Seatbelt refuses it).
|
|
1057
|
+
for (const { folder, mode } of whole.reach) {
|
|
1058
|
+
if (enterable(folder))
|
|
1059
|
+
continue;
|
|
1060
|
+
try {
|
|
1061
|
+
chmodSync(folder, mode);
|
|
1062
|
+
done.push({ path: folder, what: ` (its permissions, ${octal(mode)})` });
|
|
1063
|
+
}
|
|
1064
|
+
catch (error) {
|
|
1065
|
+
done.push({ path: folder, what: ` (its permissions, ${octal(mode)})`, error });
|
|
1066
|
+
}
|
|
1067
|
+
}
|
|
1068
|
+
// Gone, which a plan's pin leaves to the person; or whole now that git may reach it.
|
|
1069
|
+
if (kindOf(gitDir) === 'folder' && wholeRepository(gitDir, commonDir, []) === null)
|
|
1070
|
+
putBackGitDirectory(gitDir, commonDir, whole, done);
|
|
1071
|
+
if (done.length === 0)
|
|
1072
|
+
continue;
|
|
1073
|
+
const folder = workTree ?? gitDir;
|
|
1074
|
+
const entry = workTree === null ? 'none' : kindOf(join(workTree, '.git'));
|
|
1075
|
+
const why = entry === 'folder' || entry === 'link'
|
|
1076
|
+
? 'git there would look for a repository in the folders above it instead, where a command may make one, and start the programs its config names.'
|
|
1077
|
+
: 'git there would stop, finding no repository.';
|
|
1078
|
+
// Broken before the command started (by a process an earlier command left running, or the person), it is put back
|
|
1079
|
+
// as a plan saw it last, this ZTC's or one before it.
|
|
1080
|
+
const left = brokenAtStart
|
|
1081
|
+
? `as an earlier plan saw it: git took ${folder} for no repository already when the command started, and`
|
|
1082
|
+
: `which the command left so git took ${folder} for no repository:`;
|
|
1083
|
+
for (const { path, what, error } of done) {
|
|
1084
|
+
said.push(error === undefined
|
|
1085
|
+
? `ZTC put back ${path}${what}, ${left} ${why}`
|
|
1086
|
+
: `ZTC could not put back ${path}${what} (${error.message}), so git takes ${folder} for no repository: run no git there `
|
|
1087
|
+
+ `until it is one again, since ${why}`);
|
|
1088
|
+
}
|
|
1089
|
+
}
|
|
1090
|
+
return said;
|
|
1091
|
+
}
|
|
1092
|
+
/**
|
|
1093
|
+
* GIT_DIR (common directory COMMON_DIR), which git takes for no repository, put back as WHOLE says it was, each step in
|
|
1094
|
+
* DONE: its permissions, where git cannot enter it; its HEAD; a refs or objects folder git cannot enter.
|
|
1095
|
+
*/
|
|
1096
|
+
function putBackGitDirectory(gitDir, commonDir, whole, done) {
|
|
1097
|
+
const tell = (path, what, error) => {
|
|
1098
|
+
done.push(error === undefined ? { path, what } : { path, what, error });
|
|
1099
|
+
};
|
|
1100
|
+
// The git directory, which git enters: a plan pins it, so it is still the folder the plan saw.
|
|
1101
|
+
if (!enterable(gitDir)) {
|
|
1102
|
+
try {
|
|
1103
|
+
chmodSync(gitDir, whole.modes.gitDir);
|
|
1104
|
+
tell(gitDir, ` (its permissions, ${octal(whole.modes.gitDir)})`);
|
|
1105
|
+
}
|
|
1106
|
+
catch (error) {
|
|
1107
|
+
tell(gitDir, ` (its permissions, ${octal(whole.modes.gitDir)})`, error);
|
|
1108
|
+
}
|
|
1109
|
+
}
|
|
1110
|
+
if (wholeHead(gitDir) === null) {
|
|
1111
|
+
const head = join(gitDir, 'HEAD');
|
|
1112
|
+
try {
|
|
1113
|
+
const aside = clearForPutBack(head);
|
|
1114
|
+
writeHead(head, whole.head);
|
|
1115
|
+
tell(head, aside === null ? '' : ` (what the command left there is at ${aside})`);
|
|
1116
|
+
}
|
|
1117
|
+
catch (error) {
|
|
1118
|
+
tell(head, '', error);
|
|
1119
|
+
}
|
|
1120
|
+
}
|
|
1121
|
+
for (const name of ['refs', 'objects']) {
|
|
1122
|
+
const path = join(commonDir, name);
|
|
1123
|
+
if (enterable(path))
|
|
1124
|
+
continue;
|
|
1125
|
+
try {
|
|
1126
|
+
const aside = clearForPutBack(path);
|
|
1127
|
+
mkdirSync(path, { mode: whole.modes[name] });
|
|
1128
|
+
tell(path, aside === null ? ', an empty folder (what it held is gone, or where the command moved it)'
|
|
1129
|
+
: `, an empty folder (the one the command left, which git could not enter, is at ${aside})`);
|
|
1130
|
+
}
|
|
1131
|
+
catch (error) {
|
|
1132
|
+
tell(path, ', an empty folder', error);
|
|
1133
|
+
}
|
|
1134
|
+
}
|
|
1135
|
+
}
|
|
1136
|
+
/** What git says when the OS sandbox kept a protected file from its write: the file, or none where it names none. */
|
|
1137
|
+
const GIT_WRITE_REFUSED = [
|
|
1138
|
+
/could not (?:write|lock) config file ([^:\n]+): Operation not permitted/g,
|
|
1139
|
+
/unable to (?:unlink|write|create) '([^'\n]+)': Operation not permitted/g,
|
|
1140
|
+
/failed to delete '([^'\n]+)': Operation not permitted/g,
|
|
1141
|
+
];
|
|
1142
|
+
/** What git says when it did what it couldn't record in the repository's config (a renamed branch, a submodule's URL). */
|
|
1143
|
+
const GIT_CONFIG_UNRECORDED = /update of config-file failed|Failed to register url for submodule path|could not (?:write|lock) config file/;
|
|
1144
|
+
/** rm's word for a file under a .git it could not remove. */
|
|
1145
|
+
const RM_REFUSED = /^rm: (\S[^\n]*?\/\.git(?:\/[^\n:]*)?): Operation not permitted$/gm;
|
|
1146
|
+
/** FILES in words, the first three and how many more. */
|
|
1147
|
+
function someFiles(files) {
|
|
1148
|
+
const named = files.slice(0, 3).join(', ');
|
|
1149
|
+
return files.length > 3 ? `${named} and ${files.length - 3} more` : named;
|
|
1150
|
+
}
|
|
1151
|
+
/**
|
|
1152
|
+
* What a sandboxed COMMAND's result says, run in CWD under a plan that protects the repositories it can write, when its
|
|
1153
|
+
* OUTPUT shows the OS sandbox kept one of their protected files (config, hooks, worktree records) from it: which files,
|
|
1154
|
+
* why, and that the person runs the command themselves where they want it done. git that writes a protected config
|
|
1155
|
+
* fails, or says it did what it could not record there ("set up to track"); an rm of a repository leaves those files
|
|
1156
|
+
* behind. Nothing when the output shows neither.
|
|
1157
|
+
*/
|
|
1158
|
+
export function refusedGitWriteNotes(output, command, cwd) {
|
|
1159
|
+
const said = [];
|
|
1160
|
+
const written = new Set();
|
|
1161
|
+
for (const pattern of GIT_WRITE_REFUSED)
|
|
1162
|
+
for (const match of output.matchAll(pattern))
|
|
1163
|
+
written.add(match[1].trim());
|
|
1164
|
+
if (written.size > 0 || GIT_CONFIG_UNRECORDED.test(output)) {
|
|
1165
|
+
said.push(`The OS sandbox kept ${written.size > 0 ? someFiles([...written]) : 'the repository\'s config'} read-only: under this `
|
|
1166
|
+
+ 'permission profile a command can\'t change what git starts in a repository ZTC protects (its config, hooks and '
|
|
1167
|
+
+ 'worktree records), so what the command would have recorded there (a setting, a remote, an upstream, a renamed '
|
|
1168
|
+
+ 'branch\'s or a submodule\'s config, a worktree\'s removal) is not, whatever git printed. Where it should be, the '
|
|
1169
|
+
+ `person runs it themselves, in ${cwd}: ${command}`);
|
|
1170
|
+
}
|
|
1171
|
+
const removed = [...new Set([...output.matchAll(RM_REFUSED)].map(match => match[1].trim()))];
|
|
1172
|
+
if (removed.length > 0) {
|
|
1173
|
+
const kept = removed.filter(path => /\/\.git\/(?:config|hooks)/.test(path));
|
|
1174
|
+
said.push(`The OS sandbox kept ${someFiles(kept.length > 0 ? kept : removed)}, which ZTC protects in a repository it found, `
|
|
1175
|
+
+ 'so the command could not remove them, nor the folders that hold them. Where they should go, the person runs it '
|
|
1176
|
+
+ `themselves, in ${cwd}: ${command}`);
|
|
1177
|
+
}
|
|
1178
|
+
return said;
|
|
1179
|
+
}
|
|
1180
|
+
/**
|
|
1181
|
+
* The step after a command bwrap ran (utils/sandbox.ts), once it has ended and before any other git runs there: what it
|
|
1182
|
+
* did where FILES (the plan's record) protects that bwrap could not refuse, undone. bwrap keeps a path that exists
|
|
1183
|
+
* read-only, but not a name a command creates in a folder it may write, nor a link's own name, since a mount follows a
|
|
1184
|
+
* link: so a protected file the command made (a commondir, which points git at a common directory and config of its
|
|
1185
|
+
* own, a config.worktree) is removed, and a protected link it replaced or removed is put back as it was (the reviewer's
|
|
1186
|
+
* round-1 probe: one write to .git/commondir, and the person's git status ran the command's fsmonitor). What ZTC did,
|
|
1187
|
+
* for the command's result; nothing when it left them alone. Seatbelt refuses both, since its rules go by a path, which
|
|
1188
|
+
* a name not made yet has too and a link's own name is, so it has no such step.
|
|
1189
|
+
*/
|
|
1190
|
+
export function undoGitProgramWrites(files) {
|
|
1191
|
+
const said = [];
|
|
1192
|
+
for (const path of files.absent) {
|
|
1193
|
+
if (kindOf(path) === 'none')
|
|
1194
|
+
continue;
|
|
1195
|
+
try {
|
|
1196
|
+
rmSync(path, { recursive: true, force: true });
|
|
1197
|
+
said.push(`ZTC removed ${path}, which the command made: git would read it outside the sandbox, and a sandboxed command may `
|
|
1198
|
+
+ 'not change where the repository names the programs git starts.');
|
|
1199
|
+
}
|
|
1200
|
+
catch (error) {
|
|
1201
|
+
said.push(`ZTC could not remove ${path}, which the command made (${error.message}): run no git in that repository `
|
|
1202
|
+
+ 'until it is gone.');
|
|
1203
|
+
}
|
|
1204
|
+
}
|
|
1205
|
+
for (const { path, target } of files.links) {
|
|
1206
|
+
let now;
|
|
1207
|
+
try {
|
|
1208
|
+
now = lstatSync(path).isSymbolicLink() ? readlinkSync(path) : '\0';
|
|
1209
|
+
}
|
|
1210
|
+
catch {
|
|
1211
|
+
now = null;
|
|
1212
|
+
}
|
|
1213
|
+
if (now === target)
|
|
1214
|
+
continue;
|
|
1215
|
+
try {
|
|
1216
|
+
rmSync(path, { recursive: true, force: true });
|
|
1217
|
+
symlinkSync(target, path);
|
|
1218
|
+
said.push(`ZTC put back ${path}, a link to ${target}, which the command ${now === null ? 'removed' : 'replaced'}: git would read `
|
|
1219
|
+
+ 'what it left there outside the sandbox.');
|
|
1220
|
+
}
|
|
1221
|
+
catch (error) {
|
|
1222
|
+
said.push(`ZTC could not put back ${path}, a link to ${target} (${error.message}): run no git in that repository `
|
|
1223
|
+
+ 'until it is a link again.');
|
|
1224
|
+
}
|
|
1225
|
+
}
|
|
1226
|
+
return said;
|
|
1227
|
+
}
|
|
1228
|
+
/**
|
|
1229
|
+
* The Seatbelt rules for FILES, after the rule that lets a writable root be written: each file denied every write, a
|
|
1230
|
+
* hooks folder's within it, a pinned folder's as itself (what it holds stays writable). They go by the paths the plan
|
|
1231
|
+
* found, so a name that does not exist yet is refused as one that does, and Seatbelt matches a name as the volume does:
|
|
1232
|
+
* on one that ignores case `.git/COMMONDIR`, which git reads as `.git/commondir`, is refused too. Nothing is refused by a
|
|
1233
|
+
* pattern: a repository the command makes is its own until the next command's plan finds it, as under bwrap.
|
|
1234
|
+
*/
|
|
1235
|
+
export function seatbeltGitProgramRules(files, quote) {
|
|
1236
|
+
return [
|
|
1237
|
+
...[...files.files, ...files.pinned].map(path => `(deny file-write* (literal ${quote(path)}))`),
|
|
1238
|
+
...files.folders.map(path => `(deny file-write* (subpath ${quote(path)}))`),
|
|
1239
|
+
];
|
|
1240
|
+
}
|
|
1241
|
+
/** What is at PATH, not following a link. */
|
|
1242
|
+
function kindOf(path) {
|
|
1243
|
+
try {
|
|
1244
|
+
const info = lstatSync(path);
|
|
1245
|
+
return info.isDirectory() ? 'folder' : info.isFile() ? 'file' : info.isSymbolicLink() ? 'link' : 'other';
|
|
1246
|
+
}
|
|
1247
|
+
catch {
|
|
1248
|
+
return 'none';
|
|
1249
|
+
}
|
|
1250
|
+
}
|
|
1251
|
+
/**
|
|
1252
|
+
* bwrap options for FILES, after the writable roots are bound and before anything is hidden. bwrap protects a path with
|
|
1253
|
+
* a mount, which a rename or a removal cannot move (EBUSY) and a read-only one no write gets through: each pinned folder
|
|
1254
|
+
* is bound onto itself, writable; each file is bound read-only, and a missing common config is an empty one (git reads
|
|
1255
|
+
* an empty config as none, and a command cannot create one there); each hooks folder is bound read-only, or, missing,
|
|
1256
|
+
* an empty read-only folder. The mount points of the last two are left behind, empty. A link is bound at its target
|
|
1257
|
+
* (a mount follows a link), so the link itself can still be replaced, and a file the command creates where none was
|
|
1258
|
+
* (a commondir, a config.worktree) cannot be refused: bwrap stops writes to a path that exists, not a new name in a
|
|
1259
|
+
* folder that stays writable. The step after the command undoes both (undoGitProgramWrites); Seatbelt's rules, which go
|
|
1260
|
+
* by path, deny both.
|
|
1261
|
+
*/
|
|
1262
|
+
export function bubblewrapGitProgramBinds(files) {
|
|
1263
|
+
const args = [];
|
|
1264
|
+
for (const folder of files.pinned)
|
|
1265
|
+
if (kindOf(folder) === 'folder')
|
|
1266
|
+
args.push('--bind', folder, folder);
|
|
1267
|
+
for (const file of files.files) {
|
|
1268
|
+
const kind = kindOf(file);
|
|
1269
|
+
if (kind === 'file')
|
|
1270
|
+
args.push('--ro-bind', file, file);
|
|
1271
|
+
else if (kind === 'none' && files.configs.includes(file))
|
|
1272
|
+
args.push('--ro-bind', '/dev/null', file);
|
|
1273
|
+
}
|
|
1274
|
+
for (const folder of files.folders) {
|
|
1275
|
+
const kind = kindOf(folder);
|
|
1276
|
+
if (kind === 'folder')
|
|
1277
|
+
args.push('--ro-bind', folder, folder);
|
|
1278
|
+
else if (kind === 'none')
|
|
1279
|
+
args.push('--tmpfs', folder, '--remount-ro', folder);
|
|
1280
|
+
}
|
|
1281
|
+
return args;
|
|
1282
|
+
}
|