CandyGitServer
Git server: smart-HTTP clone/fetch/push/LFS live
candy-git-server is a self-hostable Git server in PHP 8.3+. It is a port of parts of charmbracelet/soft-serve. The smart-HTTP transport is live: serve --http runs a listener that real git clone, git fetch and authenticated git push work against, with the Git LFS batch and object routes beside it. The SSH and git-daemon transports exist as classes that a host has to wire up. There is no terminal UI.
Install
composer require sugarcraft/candy-git-server
vendor/bin/candy-git-server help
Requires PHP 8.3 or newer and the system git binary on PATH. Both the read path and the push path run through git upload-pack and git receive-pack --stateless-rpc, and the protocol tests run against git 2.43. Without git, serve --http still starts, but every request answers 500.
ext-sockets is a hard requirement, because the blocking GitDaemon::serve() loop calls socket_create() directly. ext-pcntl is optional, and it enables the graceful SIGINT and SIGTERM exit and the one-process-per-connection HTTP worker. Without it the listener still runs, and a stop signal ends the process with status 130 or 143.
A single-file candy-git-server.phar is built on each push to master. It needs only PHP on the host, and it is started the same way: php candy-git-server.phar serve --http --repo-root /srv/git/repositories.
Quickstart
This run takes a fresh data directory from init to a clone. The output is trimmed from a real run: the data path is shortened to /var/lib/candy-git-server, and the listener is shown on its default port. The password for the first admin is read from stdin, never from argv.
D=/var/lib/candy-git-server
# 1. initialize the data directory and mint the first admin
printf '%s\n' 'correct horse battery staple' |
candy-git-server init "$D" --admin alice --admin-password-stdin
# 2. add a least-privilege account: non-admin unless --admin is passed
printf '%s\n' 'hunter2hunter2' | candy-git-server user add bob "$D" --password
# 3. create a repository: private by default, --public marks it public
candy-git-server repo create myrepo "$D"
candy-git-server repo collaborator myrepo add bob "$D"
# 4. serve it over smart HTTP
candy-git-server serve --http --repo-root "$D/repositories" --config "$D/config.yaml"
# 5. from another shell, clone and push as a collaborator
git clone http://bob@localhost:23232/myrepo.git
User 'bob' created (admin: false)
Password stored as a hash.
Persisted to /var/lib/candy-git-server/users.json
Repository 'myrepo' created at /var/lib/candy-git-server/repositories/myrepo
Note: start a listener to serve it: candy-git-server serve --http --repo-root /var/lib/candy-git-server/repositories (private until --public; anonymous-read needs git.allow_anonymous_read).
Repo 'myrepo': collaborator 'bob' added (plane now: bob)
candy-git-server: smart-HTTP listener on 127.0.0.1:23232 (1 repos, 0 published; 2 accounts; anonymous-read=off; push is served too — hook declines ride in-band)
access 127.0.0.1 GET /myrepo.git/info/refs 401 23 1.6ms
access 127.0.0.1 GET /myrepo.git/info/refs 200 288 69.0ms
access 127.0.0.1 POST /myrepo.git/git-receive-pack 200 50 72.4ms
The first info/refs request answers 401 because git has no credentials yet. The retry with Basic auth answers 200. Two more facts matter here. Anonymous reads of a public repo still answer 401 unless git.allow_anonymous_read is turned on, which it is not by default. And a plain init or user add run on a directory under the system temp directory prints a warning, because local users can read it there. Set CANDY_GIT_SERVER_DATA_PATH to a real path before a deployment.
Concepts
The package is organized around four nouns. A Repo is an immutable description of a bare Git repository on disk, with its visibility, collaborators, push setting and optional mirror source. A User is an immutable account, with a password hash and any authorized SSH keys. AccessControl answers whether a user, or an anonymous caller, may read, write or administer a repo. A transport is the way bytes reach Git: the smart-HTTP listener, the SSH dispatcher or the git-daemon class.
Every access check runs before any Git child is spawned or any ref byte is written. A request that fails authorization is refused with no repository data sent. Hook declines from a push ride back in-band, in the report-status stream that the Git client expects.
Visibility and access
A repo has one of three visibilities, and the enum Visibility holds them. Visibility::Public is readable without credentials, but only while git.allow_anonymous_read is on. Visibility::CollaboratorOnly admits only collaborators and admins. Visibility::Private admits the same people, and it is the default for a repo created without --public. Authenticated collaborators can push. allowPush widens push to every authenticated user, but only on a repo that is also publicly visible. On a private or collaborator-only repo it changes nothing, and it never admits an anonymous caller.
Visibility is a marker on disk, and directory presence alone never publishes a repository. Every path that resolves a repo consults the marker and falls back to private when it is absent.
Accounts persist, and the store is refused when corrupt
Accounts live in <data_path>/users.json. Writes are atomic, through a temporary file and a rename, and the file is mode 0600. A corrupt store refuses to load rather than silently starting with zero accounts. Passwords are stored only as password_hash digests, so cleartext never reaches disk.
Tasks
Create a repo from PHP and check who may write
use SugarCraft\GitServer\{AccessControl, Config, Repo, User};
$config = Config::fromDefaults(); // reads CANDY_GIT_SERVER_DATA_PATH, else defaults
$repo = Repo::new('my-project', $config->reposPath() . '/my-project.git')
->withDescription('Greeting service')
->withPublic(true)
->addCollaborator('alice')
->init(); // creates the bare repository on disk
$acl = AccessControl::instance();
$acl->canWrite(User::new('alice'), $repo); // true: collaborator
$acl->canWrite(User::new('bob'), $repo); // false: not a collaborator
$acl->canRead(null, $repo); // false: anonymous reads are off
Each with*() call returns a new immutable Repo, so keep the result of the chain. The init() call creates the repository on disk. The setters only build a new value in memory, and the metadata writers listed in the API reference are the other calls that write to disk. examples/repo.php exercises the same metadata and permission calls in a private temporary directory. It does not call init(), so no git repository is created.
Let anonymous clients read a public repo
; config.yaml
git:
allow_anonymous_read: true
Anonymous reads need both the repo marked public and the git.allow_anonymous_read lever on. Either one alone refuses. The same lever is consulted by the smart-HTTP router and by the daemon. Leave it off on a host that serves private work.
Mint a proxy token for a trusted front end
candy-git-server user token alice 3600 "$D" # TTL in seconds, then the data path
The command prints an expiring <expiry-unix>.<hex-hmac> value. It needs http.auth_secret set in config.yaml, and the TTL is capped by http.token_max_ttl. Under http.user_trust_mode: token, the value is sent in the X-CandyGitServer-User-Sig header together with X-CandyGitServer-User. The HMAC is checked against http.auth_secret, and it expires. Under proxy mode a trusted reverse proxy sets the identity header instead, and the proxy must replace any header a client sends.
Mirror an upstream repository on a schedule
use SugarCraft\GitServer\Config;
use SugarCraft\GitServer\Jobs\MirrorPuller;
use SugarCraft\GitServer\Repo;
$mirror = Repo::new('linux', $config->reposPath() . '/linux.git')
->withMirrorFrom('https://github.com/torvalds/linux.git');
$puller = new MirrorPuller($config); // reads jobs.mirror_pull
$puller->registerRepo($mirror);
$puller->runOnce(); // from cron: pull every due mirror now
// or, in a ReactPHP host: $puller->attach($loop);
Each due mirror is fetched with git fetch --prune and the full +refs/*:refs/* refspec, so refs deleted upstream are removed locally. The schedule accepts @every with a Go-style duration such as 10m or 1h30m, and the aliases @hourly, @daily, @weekly, @monthly and @yearly. Full cron expressions are refused.
Watch the counters on a loopback endpoint
curl -s localhost:23233/stats
{"uptime_seconds":42.1,"connections":7,"pack_uploads":1,"pack_downloads":4,
"lfs_batch_requests":2,"lfs_object_downloads":2,"lfs_object_uploads":1}
StatsServer runs only on a ReactPHP loop, so a host has to start it. The endpoint is unauthenticated. A hostless stats.listen_addr, such as the default :23233, binds to loopback, and only an explicit non-loopback host makes the counters reachable from the network. Set stats.persist_path to keep counters across restarts, since the default is volatile.
Put TLS in front of the listener
The library never terminates TLS. Setting http.tls_key_path or http.tls_cert_path refuses the config at load. Put a reverse proxy in front, as shown under Deployment, and point http.public_url at the https:// origin, so the LFS batch hrefs never downgrade a client to cleartext.
API reference
The public classes live in SugarCraft\GitServer\. Sub-namespaces follow the directory layout in the Architecture section. The tables give the members a host is most likely to call. Constructors and methods that take a stream or a loop have the same types as the source.
Configuration, repositories and accounts
| Class | Method | Description |
|---|---|---|
Config | static fromDefaults(), static load(string $path) | Configuration from env and defaults, or from a YAML file parsed by symfony/yaml. |
Config | reposPath(), sshPath(), lfsPath(), ensureReposPath() | The data directories. The ensure* variants create the directory. |
Repo | static new(string $name, string $path) | An immutable repo description. A fresh handle is private. |
Repo | withDescription(), withVisibility(Visibility $v), withPublic(bool $v = true), withPrivate(), withAllowPush(), withMirrorFrom(?string $url), withHighlightLanguage(string $lang) | Each returns a new instance. |
Repo | addCollaborator(string $username), removeCollaborator(string $username), collaborators(), isCollaborator(string $username) | The collaborator list, kept in the repo's metadata plane. The add and remove calls return a new value and write nothing. |
Repo | init(), exists(), path(), branches(), tags(), refs(string $prefix = 'refs/heads'), readFile(string $commitHash, string $path), readme() | Create the bare repository and inspect it. init() creates it, and the inspection calls do not write. |
Repo | writeMeta(), mutateMeta(callable $mutator), stampMirrorAttempt(int $when), writeVisibilityMarker() | Write into the repo's git directory: the metadata plane, the mirror pull-attempt stamp and the visibility marker. mutateMeta() and stampMirrorAttempt() throw unless the git directory already exists. |
Repo | isPrivate(), isVisiblePublic(), isMirror() | Visibility and mirror predicates. |
Visibility | Public, CollaboratorOnly, Private | The enum on each repo. fromBools() maps the legacy pair. |
User | static new(string $username), withAdmin(), withActive(), withPasswordHash(?string $hash), withAuthorizedKeys(string $keys), addAuthorizedKey(string $pubKey), verifyPublicKey(string $presentedKey) | An immutable account and its SSH key matching. |
UserStore | static forDataPath(string $dataPath), find(), all(), add(), put(), remove(), deactivate(), transaction(callable $mutator) | The atomic users.json store. |
AccessControl | static instance(), setAllowAnonymousRead(bool $allowed) | The process-global posture, shared with the daemon and SSH transports. |
AccessControl | canRead(?User $user, Repo $repo), canWrite(), canAdmin(), canCreateRepos() | Permission checks. A null user is anonymous, and canWrite() refuses it unconditionally. |
Transports
| Class | Method | Description |
|---|---|---|
HttpSmartProtocol\Server | __construct(Config $config, ?AccessControl $accessControl = null), registerRepo(), registerUser(), setAllowAnonymousRead(), handleRequest(), static mintUserToken(string $username, int $expiry, string $secret) | The smart-HTTP and LFS router. It enforces the same gates as the listener. |
HttpSmartProtocol\HttpListener | start(), stop(), listenAddress(), activeConnectionCount() | The HTTP/1.1 socket listener behind serve --http. Its event loop is passed to the constructor, not to start(). |
Git\GitDaemon | __construct(Config $config), registerRepo(), registerRepos(), serve(string $pidFile = ''), serveAsync(?LoopInterface $loop = null, string $pidFile = ''), shutdown() | The git:// advertisement daemon. It is read-only, and it is not started by the shipped CLI. |
SSH\SSHServer | __construct(Config $config), registerUser(), registerRepo(), handleConnection($stream, string $username, string $command, ?string $publicKey = null) | A ForceCommand-style gate for host sshd. It does not implement the SSH wire protocol. |
Git\PktLine | static encode(string $payload), static flush(), static decode(string $bytes), static isServiceHeader(string $payload, string $service) | The one pkt-line codec, with 4-hex length prefixes. |
Git\StatelessRpc | static advertise(string $service, string $repoPath, ?float $deadlineSeconds = null), static negotiate(), static binaryFor(string $service) | The --stateless-rpc git children, with a bounded drain and a TERM-to-KILL reap. |
LFS, jobs, stats and support
| Class | Method | Description |
|---|---|---|
LFS\LFSHandler | handleBatch(array $request), handleBatchAsync(array $request, ?LoopInterface $loop = null), withStorageBackend(LFSStorageBackendInterface $backend) | The Git LFS batch API, synchronous and promise-based. |
LFS\LocalStorageBackend | implements LFSStorageBackendInterface | The default object store, in the aa/bb/oid layout under lfsPath(). |
Jobs\MirrorPuller | __construct(Config $config, ?\Closure $exec = null), registerRepo(Repo $repo), runOnce(?int $now = null, ?float $budgetSeconds = null), attach(?LoopInterface $loop = null) | The mirror-pull job, driven by cron or by the event loop. |
Jobs\Schedule | parses @every and the aliases | The job schedule grammar. Cron expressions are not supported. |
StatsServer | __construct(Config $config), start(?LoopInterface $loop = null), stop(), listenAddress() | The JSON counters endpoint. It runs only on a ReactPHP loop. |
Stats | static instance(), recordConnection(), recordPackUpload(), connections(), snapshot(), toJson(), flushNow() | The shared counters, persisted when stats.persist_path is set. |
Support\BoundedCommand | static run(array $argv, float $timeoutSeconds = ...), runRaw() | The argv-only subprocess runner with caps, a deadline and reaping. It takes no shell string. |
Support\PromisePool | bounded-concurrency helper | Caps how many promises run at once. It bounds LFS transfers. |
Support\Version | resolve(string $archive, string $fallback), fromPharMetadata(string $archivePath), isDev(string $version), displayLabel(string $archive, string $fallback) | The version resolver. The compiled-in version is the VERSION constant in bin/candy-git-server, 0.1.0, and a phar build stamp replaces it. |
Only methods declared in candy-git-server/src, or inherited from a parent declared there, are listed. A type that extends a class outside that tree, such as \RuntimeException, does not show the methods of that class.
SugarCraft\GitServer
AccessControl final class
Access control for repositories and operations.
| Method | Summary |
|---|---|
static instance(): self | |
static setInstance(self $ac): void | |
setAllowAnonymousRead(bool $allowed): void | Set whether requests with no authenticated identity may read public repos. Authenticated users are never gated by this lever. |
canRead(?User $user, Repo $repo): bool | Check if a user can read a repo. |
canWrite(?User $user, Repo $repo): bool | Check if a user can push to a repo. |
canAdmin(?User $user, Repo $repo): bool | Check if a user can administer a repo (change settings, add collaborators). |
canCreateRepos(?User $user): bool | Check if a user can create repos. |
allowAnonymousRead(): bool | Check if anonymous access (public key) is allowed for reading. |
static permissionName(int $level): string | Resolve the permission level name. |
Config final class
Server configuration loaded from config.yaml.
| Method | Summary |
|---|---|
static load(string $path): self | Load config from a YAML file. |
static fromDefaults(): self | Load config from env + defaults. |
reposPath(): string | Repository jail path — PURE (091): returns the location without creating it. Read-side lookups (daemon/SSH repo resolution) run this on every request, and an accessor that mkdirs let a network mount point or a read-only scanner mint 0755 directories as a lookup side effect. Servers and writers call the ensure* twin. |
sshPath(): string | SSH host-key + user-store directory — PURE (091), see reposPath(). |
lfsPath(): string | LFS object root — PURE (091), see reposPath(). |
ensureReposPath(): string | Create the repository jail with an explicit mode (038: 0750, not a umask-roll — a world-readable jail lets local users clone private repos straight off the disk, bypassing every access check). |
ensureSshPath(): string | Create the ssh/user-store directory, owner-only (0700). |
ensureLfsPath(): string | Create the LFS object root with an explicit mode (038: 0750). |
Lang final class
Per-library translation facade for candy-git-server.
Repo final class
A Git repository managed by CandyGitServer.
| Method | Summary |
|---|---|
static new(string $name, string $path): self | A repo handle for ($name, $path). The posture DEFAULT is Private (009): a handle is un-trusted for the world until visibility is set explicitly (withVisibility/withPublic, marker overlay, or the CLI's --public at create). Callers wanting public pass it on purpose. |
static isJailSafeName(string $name): bool | Is $name safe to use as a single repository directory component? |
static markerVisibility(string $gitDir): Visibility | Visibility recorded by the marker inside a git directory — the launcher's persistence. FAIL-CLOSED: a missing, unreadable, or unrecognizable marker means PRIVATE. Repos are only world-visible because an operator explicitly published them; scanning a directory of ordinary clones must never mint anonymous readability. |
static gitDirFor(string $path): string | The git directory for a path (path itself when bare — a HEAD file at the root — else path/.git). Static so discovery gates that only have a path on hand (transport disk fallbacks) resolve the same layout the marker writer does, never a hardcoded '/.git' that silently misses a bare repo's marker and fail-closes a published repo to private. |
gitDir(): string | The git directory for this repo (path itself when bare, else path/.git). |
writeVisibilityMarker(): void | Persist the current visibility marker into the repo's git directory. |
static metaPathFor(string $gitDir): string | |
static readMeta(string $gitDir): array | Read the metadata plane with the lib's strict-vocabulary discipline (S07 kin): every field is CHECKED, garbage falls back to its safe default with one named error_log line — never a cast of junk into a security posture (a string-'false' allowPush must not read TRUE). A version NEWER than this build understands is refused wholesale: silently dropping fields the future added would UNDO the operator's metadata on the next publish, which is exactly the loss 012 is about. Missing/unreadable file = plain defaults (a fresh repo has no meta). |
metaSnapshot(): array | This handle's persistable fields as a metadata-plane array. |
writeMeta(): void | Publish this handle's fields to the metadata plane atomically. The mirror last-attempt stamp is PRESERVED across a snapshot publish — it belongs to the job, not to whoever edited the description. |
mutateMeta(callable $mutator): array | Load→mutate→publish the metadata plane under an exclusive sidecar lock (UserStore's S11 discipline in miniature): concurrent repo collaborator processes serialize instead of each publishing over the other's bytes. The mutator receives the validated on-disk array and returns the array to publish; its value comes back out. |
withMetaFromDisk(): self | Overlay this handle with the on-disk metadata plane (the scan path's missing half — pre-012 the launcher rebuilt visibility only, and every CollaboratorOnly repo silently degraded to admin-only across a restart). Visibility stays the marker's business; the meta never carries it. |
mirrorLastAttempt(): ?int | The mirror job's persisted last-attempt for this repo (null = never), read straight from the metadata plane. |
stampMirrorAttempt(int $when): void | Persist a mirror pull-attempt stamp (finding 044). |
withDescription(string $d): self | |
withVisibility(Visibility $v): self | |
withPublic(bool $v = true): self | BC setter for the old boolean model. withPublic(false) on a Private repo stays Private (the old code kept the private bit); on a Public repo it demotes to CollaboratorOnly. |
withPrivate(bool $v = true): self | BC setter for the old boolean model. withPrivate(false) on a Private repo resolves to CollaboratorOnly (the conservative reading — the old public bit is no longer tracked separately). |
withAllowPush(bool $v = true): self | |
withMirrorFrom(?string $url): self | |
withHighlightLanguage(string $lang): self | |
addCollaborator(string $username): self | |
removeCollaborator(string $username): self | |
init(): self | Initialize a bare Git repository layout under $path: the Git itself lives at $path/.git, matching exists() and every discovery gate (bin repo list/info, GitDaemon::findRepoByPath, SSHServer). Before this fix git init --bare made $path itself the bare repo, so a freshly created repository was invisible to every gate that looks for $path/.git. |
path(): string | Get the path to the bare Git repository. |
exists(): bool | Whether a Git repository lives at this path in EITHER supported layout — the lib's own $path/.git bare-Git shape (init()) or a true bare directory (HEAD at the root). Mirrors gitDir() so the registerRepo marker gate, and everything else that asks "does this repo exist", cannot go blind to bare shapes the marker writer itself handles. |
branches(): array | |
tags(): array | |
refs(string $prefix = 'refs/heads'): array | Get a list of { ref => hash } for refs matching $prefix. |
readFile(string $commitHash, string $path): ?string | Read a file from the repo at a given commit + path. |
readme(): ?array | Get the README content (tries common names). |
isPrivate(): bool | |
isVisiblePublic(): bool | Whether this repo is publicly visible. A repo that is not explicitly public is collaborator-only (or private). |
isMirror(): bool | Whether this repo mirrors an upstream remote (has a pull URL). |
isCollaborator(string $username): bool | |
collaborators(): array |
Stats final class
In-process counters for the stats collection server.
| Method | Summary |
|---|---|
__construct(?string $persistPath = null, int $flushIntervalSeconds = 60) | |
static instance(): self | |
static setInstance(self $stats): void | |
recordConnection(): void | A transport (git daemon or HTTP) handled a connection/request. |
recordPackUpload(): void | A pack was received from a client (git-receive-pack / push). |
recordPackDownload(): void | A pack was sent to a client (git-upload-pack / clone, fetch). |
recordLfsBatch(): void | |
recordLfsDownload(): void | |
recordLfsUpload(): void | |
connections(): int | |
packUploads(): int | |
packDownloads(): int | |
lfsBatchRequests(): int | |
lfsObjectDownloads(): int | |
lfsObjectUploads(): int | |
uptimeSeconds(): float | |
snapshot(): array | |
toJson(): string | |
reset(): void | Zero every counter and restart the uptime clock (test isolation). On a PERSISTING instance this is still a live-plane reset, but the merge discipline means the next flush pulls the file's higher counters back up — history never un-happens; use a fresh volatile instance for test isolation. |
flushNow(): bool | Force a merge-and-write regardless of the cadence (stop path, tests). |
StatsServer final class
Minimal HTTP stats endpoint on stats.listen_addr.
| Method | Summary |
|---|---|
__construct(Config $config, ?Stats $stats = null, private readonly float $idleTimeoutSeconds = self::IDLE_TIMEOUT_SECONDS, private readonly float $absoluteDeadlineSeconds = self::ABSOLUTE_DEADLINE_SECONDS, private readonly int $maxClients = self::MAX_CLIENTS) | |
start(?LoopInterface $loop = null): void | Bind stats.listen_addr and start answering on the event loop. |
stop(): void | Tear down every loop registration and close all sockets. Idempotent. |
isRunning(): bool | |
activeConnectionCount(): int | Seats currently held (accepted, request unfinished). |
listenAddress(): ?string | Actual bound address (useful when the configured port is 0). |
User final class
User account with SSH public key authentication.
Not listed: the methods of SugarCraft\Core\Concerns\Mutable, a trait declared outside src/.
| Method | Summary |
|---|---|
static new(string $username): self | |
withUsername(string $u): self | |
withAdmin(bool $v = true): self | |
withActive(bool $v = true): self | |
withPasswordHash(?string $hash): self | Attach a password_hash() digest (the only password form the store keeps). |
toArray(): array | Serializable form used by UserStore. Deliberately never emits a cleartext password: persistence carries the digest only. |
static fromArray(array $row): self | |
withAuthorizedKeys(string $keys): self | |
addAuthorizedKey(string $pubKey): self | Add a public key to this user's authorized_keys. Supports ssh-ed25519, ssh-rsa, ecdsa-sha2-*, sk-ssh-ed25519@openssh.com |
verifyPublicKey(string $presentedKey): bool | Verify a presented public key matches one of this user's authorized keys. |
authorizedKeysList(): array | Get all authorized keys. |
publicKeyComment(): string | The default SSH public key comment for generated keys. |
generateKeyPair(): ?array | Generate an ssh-ed25519 key pair by delegating to ssh-keygen(1). |
UserStore final class
Persistent user accounts store — JSON file, one per data directory.
| Method | Summary |
|---|---|
__construct(string $filePath) | |
static forDataPath(string $dataPath): self | |
path(): string | |
all(): array | |
find(string $username): ?User | |
add(User $user): bool | Register a new account. Returns false (and changes nothing) when the username is already taken — callers must surface a refusal, never a silent overwrite. (Finding 010's other half: the CLI USED to discard exactly this bool while printing success.) |
put(User $user): void | Upsert an existing account (for key edits / deactivation). |
remove(string $username): bool | Remove an account outright. Returns false (and changes nothing) when no such user exists — the same checked-answer contract add() honors. S23 (finding 040): this is the revocation door the enforced isActive machinery always needed but never had; without it, deactivating an account meant hand-editing users.json (and walking straight into the strict-vocabulary refusals). |
deactivate(string $username): ?User | Flip an account inactive, keeping every credential intact (an inactive account can be reactivated by editing nothing but this row). Returns the UPDATED immutable VO — the echo's truth rides the object the store just committed — or null when the account does not exist. Callers wrap this in transaction() like every other mutation. |
transaction(callable $mutator): mixed | Run one whole-file transaction under an exclusive sidecar lock: re-read the on-disk bytes, hand this instance to $mutator, and publish iff the mutator changed anything. Concurrent control-plane processes therefore serialize on the lock — each one's mutator sees the OTHER's committed rows, which is what kills the lost-update window. The mutator's value is returned; an exception aborts without publishing and the lock still releases. |
save(): void | Persist the whole store atomically with tight permissions: the file holds authentication material, so it is created 0600 and the directory 0700 (umask-independent — the mode is set on the temp inode BEFORE the payload lands, and rename carries it onto the target). Raw write of the current snapshot — concurrency-safe mutation goes through transaction() instead. |
Visibility enum
Repository visibility.
Cases: Public · CollaboratorOnly · Private
PHP also provides cases(), from() and tryFrom().
| Method | Summary |
|---|---|
static fromBools(bool $isPublic, bool $private): self | Map the legacy two-boolean model onto the enum. A set private flag always wins, matching the old isPrivate() accessor. |
isPublic(): bool | Anyone (including anonymous users) may read the repo. |
isPrivate(): bool | Explicitly private: collaborators/admins only. |
SugarCraft\GitServer\Clipboard
Osc52 final class
OSC 52 clipboard handler for candy-git-server.
| Method | Summary |
|---|---|
parse(string $data): ?array | Parse and apply an OSC 52 payload. |
write(string $selection, string $data): void | Write clipboard data (decodes base64 and stores). |
read(string $selection): ?string | Read clipboard data for a selection. |
has(string $selection): bool | Check if a selection has content. |
clear(string $selection): void | Clear a clipboard selection. |
pendingEvents(): array | Get all pending clipboard events. |
buildReadResponse(string $selection, string $data): string | Generate an OSC 52 response string for a clipboard read. |
onChange(callable $listener): void | Register a listener for clipboard changes. |
offChange(callable $listener): bool | Remove a previously registered onChange listener (104 — the API was append-only, so a listener outliving its session or transport could never be detached). Identity match on the same callable; returns whether anything was removed. |
static validSelections(): array | Get the list of valid selection names. |
SugarCraft\GitServer\Git
GitDaemon final class
Real daemon-mode Git daemon: binds to a port and answers the git-upload-pack advertisement over the anonymous git:// transport. Each request delegates to a one-shot REAL git upload-pack --advertise-refs child, so the advertisement is byte-exact git output; completing the negotiation past the advertisement is a disclosed follow-up (a stateless-rpc relay per connection), and clients that send wants are closed after the flush — visibly, never as a corrupted half-transfer. The daemon is READ-ONLY by construction — the git protocol carries no authentication, so receive-pack (push) is refused outright and lives on the authenticated transports.
| Method | Summary |
|---|---|
__construct(Config $config) | |
setStats(Stats $stats): void | Inject a stats collector (default: the shared Stats instance). |
registerRepo(Repo $repo): void | |
registerRepos(iterable $repos): void | |
registerUser(User $user): void | |
setUsers(iterable $users): void | |
addSubscription(Subscription $subscription): void | Register a subscription for cleanup on graceful shutdown. |
clearSubscriptions(): void | Unregister all subscriptions (used after shutdown). |
serve(string $pidFile = ''): int | Start the daemon in blocking mode. |
serveAsync(?LoopInterface $loop = null, string $pidFile = ''): PromiseInterface | Start the daemon in async (event-loop) mode — the opt-in counterpart to the blocking serve(). Connections are accepted via Loop::addReadStream() on the listening socket and each client stream is registered with the loop, so request handling never blocks the loop waiting for readability. The per-request protocol work is the same synchronous delegation the blocking mode runs — a git upload-pack child driven through the bounded StdioPipe pump — executing inside the readiness callback, so a long transfer still delays the other clients on THIS transport for its duration. That is the git:// daemon's own serial contract, disclosed and standing (it is the shape git's reference daemon shipped too); the smart-HTTP front door took a different path with the owner-8b worker pool — each HTTP connection is served by its own forked worker (\SugarCraft\GitServer\HttpSmartProtocol\HttpListener and \SugarCraft\GitServer\Support\WorkerFork) — and the git:// and SSH transports remain on the shared-loop design described here. |
shutdown(): void | Request graceful shutdown. In sync mode the main loop observes the flag on its next select timeout; in async mode teardown is scheduled on the loop immediately. |
listenAddress(): ?string | Actual bound address in async mode (useful when the configured port is 0 = ephemeral). Null when not listening asynchronously. |
config(): Config | |
repos(): array | |
isRunning(): bool | |
activeConnections(): int | |
subscriptions(): Subscriptions |
PktLine final class
The ONE pkt-line codec for every wire emitter in this package.
| Method | Summary |
|---|---|
static encode(string $payload): string | Frame one payload as a spec pkt-line. |
static flush(): string | The flush-pkt. |
static isServiceHeader(string $payload, string $service): bool | True when $payload is exactly the smart-HTTP service header for $service ("# service=<name>", with or without the trailing LF git clients include in the packet). |
ReceivePack final class
Handles git-receive-pack requests (push) over the SSH transport.
| Method | Summary |
|---|---|
__construct(Repo $repo, ?User $user = null) | |
repo(): Repo | |
serve($in = null, $out = null): int | Serve one git-receive-pack session over the given stdio pair. |
StatelessRpc final class
The single stateless-rpc delegate: this package never re-implements git's protocol brain, it pumps bytes to and from the real binary.
| Method | Summary |
|---|---|
static binaryFor(string $service): ?string | The git sub-command implementing a smart-HTTP service, or null when the service name is not a git transport service at all. |
static advertise(string $service, string $repoPath, ?float $deadlineSeconds = null, int $maxBytes = self::ADVERTISE_MAX_RESPONSE_BYTES): string | Run git <binary> --stateless-rpc --advertise-refs over $repoPath and return its raw pkt-framed advertisement bytes. |
static negotiate(string $service, string $repoPath, string $body, int $maxBytes, ?float $deadlineSeconds = null): array | Run one stateless-rpc negotiation: feed $body (the smart-HTTP request body, service header included — clients send it) to git <binary> --stateless-rpc and return the response. |
StdioPipe final class
Bounded bidirectional stdio pump between a client connection and a short-lived git child process.
| Method | Summary |
|---|---|
static run($in, $out, array $argv, string $cwd, string $seed = '', ?float $idleSeconds = null, ?float $hardSeconds = null): int | Pump one request between the client pair and the spawned child. |
UploadPack final class
Handles git-upload-pack requests (clone / fetch) over the SSH transport.
| Method | Summary |
|---|---|
__construct(Repo $repo, ?User $user = null) | |
repo(): Repo | |
serve($in = null, $out = null): int | Serve one git-upload-pack session over the given stdio pair. |
SugarCraft\GitServer\HttpSmartProtocol
AuthAttemptBudget final class
File-backed token budget for HTTP Basic authentication attempts (finding 008).
| Method | Summary |
|---|---|
__construct(private readonly string $stateFile, private readonly int $capacity, private readonly int $refillSeconds, ?callable $clock = null) | |
charge(string $peer, string $username): ?int | Charge one authentication attempt against the peer AND username buckets. Returns null when the attempt may proceed (tokens were consumed), or the seconds the client must wait when either bucket is empty — in which case nothing was consumed and nothing hashed. |
refund(string $peer, string $username): void | Give the token back after a verify actually succeeded: correct credentials must never drain a bucket, or a long clone session (which re-sends Basic auth per request) would rate-limit itself. A verify that succeeded but yields no identity (deactivated account) also counts as honest work paid for, and refunds. |
AuthBudgetExhausted final class
Control-flow signal that the AuthAttemptBudget refused an authentication attempt before any bcrypt work was paid for. It is caught by Server::handleRequest() and answered 429 + Retry-After; it never denotes a server fault, so it must never reach the 500 path.
| Method | Summary |
|---|---|
__construct(public readonly int $retryAfterSeconds) |
HttpListener final class
The socket half of smart HTTP: accepts TCP connections, buffers complete HTTP/1.1 requests (Content-Length or chunked bodies — git's own client POSTs its negotiation chunked), hands them to the synchronous router Server::handleRequest(), and writes the buffered response back in full — a bounded drain that keeps feeding a non-blocking socket until the kernel window empties repeatedly or the client stalls — before closing. One request per connection: every response carries Connection: close, matching the router's own header.
| Method | Summary |
|---|---|
__construct(private readonly Server $router, private readonly string $host = '127.0.0.1', private readonly int $port = 0, ?LoopInterface $loop = null, private readonly float $idleTimeoutSeconds = self::IDLE_TIMEOUT_SECONDS, private readonly float $absoluteDeadlineSeconds = self::ABSOLUTE_DEADLINE_SECONDS, private readonly int $maxClients = self::MAX_CLIENTS, ?WorkerFork $workers = null) | |
start(): void | Bind and start accepting. Port 0 asks the kernel for an ephemeral one — read it back through listenAddress(). Throws on bind failure (fail-fast; a half-listening server is the scaffold sin this listener exists to keep out). |
stop(): void | Stop accepting, drop the watches, end every worker, and drop every client; idempotent. |
listenAddress(): ?string | Bound address as "host:port" (with the concrete ephemeral port), or null when stopped. |
activeConnectionCount(): int | Seats currently held (accepted, request unfinished), worker-owned included. |
PasswordVerifyCache final class
Small capped LRU of bcrypt results (finding 048).
| Method | Summary |
|---|---|
__construct(?callable $clock = null) | Without an injected clock, TTL math runs on LruMap's monotonic hrtime clock. The pre-P1-11 cache read the wall clock (microtime), which a backwards NTP step could stretch past TTL_SECONDS; a monotonic clock keeps the freshness bound in the class docblock true. |
verify(string $password, string $hash, string $username): bool | password_verify() with memoization: an unexpired hit is returned WITHOUT touching the $hash argument at all (which the unit pins use to prove the bcrypt was skipped), anything else verifies and records the outcome. |
size(): int | Live entries (tests + introspection). |
Server final class
HTTP server that speaks the Git smart protocol.
| Method | Summary |
|---|---|
__construct(Config $config, ?AccessControl $accessControl = null) | |
setAllowAnonymousRead(bool $allowed): void | Runtime arm surface for THIS server's own matrix (fixtures and embedders): raises or lowers only the instance posture, never the process-global lever the daemon and SSH transports own. |
accessControl(): AccessControl | The matrix this server consults: hosts that want to share one posture across transports pass the same object in at construction, fixtures can flip the lever without reaching through the server. |
watchUserStore(string $dataPath): void | Arm the live account store watch: users are then resolved from this file (re-checked cheaply per authenticated request) underneath the instance registry. Pass the data directory holding users.json. |
setStats(Stats $stats): void | Inject a stats collector (default: the shared Stats instance). |
maxRequestBodyBytes(): int | Effective single-source request-body cap (config or the default). |
registerRepo(Repo $repo): void | |
registerUser(User $user): void | |
setRepos(iterable $repos): void | |
handleRequest(string $method, string $path, string $query, array $headers, string $body, ?string $peerIp = null): array | Handle an incoming HTTP request. |
static mintUserToken(string $username, int $expiry, string $secret): string | Mint the wire value for X-CandyGitServer-User-Sig: an unix expiry and an HMAC-SHA256 over username NL expiry, joined by a dot. Shared by the CLI (user token) and the verifier so minted and checked shapes cannot drift apart. |
SugarCraft\GitServer\Jobs
MirrorPuller final class
Mirror-pull background job.
| Method | Summary |
|---|---|
__construct(Config $config, ?\Closure $exec = null) | |
registerRepo(Repo $repo): void | |
registerRepos(iterable $repos): void | |
schedule(): Schedule | |
mirrors(): array | |
dueMirrors(?int $now = null): array | |
lastPullAt(string $repoName): ?int | When the last pull of a repo was attempted (null = never). |
effectiveLastPull(Repo $repo): ?int | The cadence memory finding 044 lacked: this process's stamp if it has one, else the metadata plane's persisted stamp (a fresh cron process re-reads disk instead of re-pulling everything), and the LATER of the two when both exist. |
tickBudgetSeconds(): float | Wall-clock budget one runOnce() batch may spend (S05, finding 005). |
runOnce(?int $now = null, ?float $budgetSeconds = null): int | Pull every due mirror now. Synchronous — callable from a blocking host's housekeeping or standalone (e.g. cron). |
pull(Repo $repo, ?int $now = null, ?float $timeoutSeconds = null): bool | Pull a single mirror from its upstream. The attempt is recorded even on failure — and on refusal — so a broken or unfit config cannot hot-loop the job. The stamp is BOTH in-memory (this process's cadence) and persisted to the metadata plane (finding 044), and the whole fetch runs under the repo's non-blocking mirror lock: a concurrent cron tick holding it means the pull is already happening, and this call skips with a log line. |
static upstreamRefusal(string $url, bool $allowGit = false): ?string | Why an operator-supplied upstream URL is unfit to fetch, or null. Public (S25, finding 012): the CLI consults the SAME admission at the door, so repo mirror refuses ext::/scheme-garbage before it can ever sit in the plane waiting for a tick to complain. |
attach(?LoopInterface $loop = null): void | Schedule the job on a ReactPHP loop: runOnce() fires every schedule interval (the async-daemon counterpart of calling runOnce() from blocking housekeeping). |
detach(): void | Cancel the loop timer. Idempotent. |
isAttached(): bool |
Schedule final class
Background-job schedule parsed from config.
| Method | Summary |
|---|---|
static parse(string $expression): self | |
isDue(?int $lastRun, int $now): bool | Whether a job last run at $lastRun (null = never) is due at $now. |
SugarCraft\GitServer\LFS
LFSHandler final class
Git LFS batch API handler.
Not listed: the methods of SugarCraft\Core\Concerns\Mutable, a trait declared outside src/.
| Method | Summary |
|---|---|
__construct(Repo $repo, ?User $user, string $lfsPath, ?LFSStorageBackendInterface $storageBackend = null, int $concurrentTransfers = 4, ?Stats $stats = null, ?int $maxObjectBytes = null, string $publicBaseUrl = 'http://localhost:23232', ?AccessControl $accessControl = null) | |
withStorageBackend(LFSStorageBackendInterface $backend): self | Create with a custom storage backend (050: the named swap point — every other setting is forwarded; see the LFSStorageBackendInterface @note for which guarantees a swap hands over from the default class to the custom one). |
withConcurrentTransfers(int $count): self | Create with concurrent transfer limit. |
static isValidOid(string $oid): bool | An LFS object id is a sha256 hex digest — 64 lowercase hex characters. Anything else (path-shaped, oversized, non-hex) must never reach the storage layer, whose object paths are derived from the id. |
handleBatch(array $request): array | Handle an LFS batch request. |
handleBatchAsync(array $request, ?LoopInterface $loop = null): PromiseInterface | Handle an LFS batch request on a ReactPHP event loop with bounded concurrency — the opt-in async counterpart to handleBatch(). Gates and per-entry validation run synchronously through the SAME predicates first, so the two paths can never disagree; at most $concurrentTransfers validated objects are in flight at once (via a sugar-core Semaphore), and the resolved payload is byte-identical to what the sequential path returns, including per-object error entries (400 malformed, 404 missing). A storage-backend exception on one object never sinks the batch: it is captured as a GENERIC code-500 error entry for that object (the exception detail goes to the server error log, never onto the wire) and the remaining objects still resolve. |
storageBackend(): LFSStorageBackendInterface | Get the storage backend being used. |
concurrentTransfers(): int | Get the concurrent transfer limit. |
maxObjectBytes(): int | The configured per-object size ceiling. |
LFSStorageBackendInterface interface
Interface for LFS storage backends.
| Method | Summary |
|---|---|
exists(string $oid): bool | Check if an object exists in storage. |
size(string $oid): int | Get the size of an object in storage. |
read(string $oid) | Get a readable stream for an object. |
write(string $oid, $stream): void | Write a file to storage from a stream. |
delete(string $oid): void | Delete an object from storage. |
path(string $oid): ?string | Get the path for an object (if applicable). This is used for generating download URLs. |
LocalStorageBackend final class
Local filesystem storage backend for LFS objects.
| Method | Summary |
|---|---|
__construct(private readonly string $lfsPath) | |
static isValidOid(string $oid): bool | |
exists(string $oid): bool | |
size(string $oid): int | |
read(string $oid) | |
readAll(string $oid): string | Read an object fully into memory and close the handle. |
write(string $oid, $stream): void | Publish an object atomically: bytes land in a same-directory temp file (chmod first, rename carries the mode onto the target), and the final path appears only when the whole payload is flushed — a reader can never observe a truncated object, and a failed write leaves no residue behind. 'xb' refuses even a pre-planted file at the temp name. Mode 0600: objects are secrets-adjacent payloads, and the serving process is the same uid that wrote them. |
writeBytes(string $oid, string $bytes): void | Publish straight from an in-memory payload (049). The upload router already holds the complete, hash-VERIFIED bytes; before this seam it round-tripped them through php://temp merely to satisfy the stream API, materializing the object one extra time per upload for a default backend that only ever wants the bytes. Same atomic 0600 publish as write(), sliced at the lib's 64 KiB law so no oversized temporary ever rides the copy. |
delete(string $oid): void | Remove an object. No production path calls this today (upload is content-addressed and objects are immutable); it is the storage-side API for prune/GC tooling, so it stays honest and idempotent. |
path(string $oid): ?string |
SugarCraft\GitServer\SSH
SSHServer final class
Git-over-SSH service dispatcher for a host sshd ForceCommand wiring.
| Method | Summary |
|---|---|
__construct(Config $config) | |
registerUser(User $user): void | |
registerRepo(Repo $repo): void | |
setUsers(iterable $users): void | |
handleConnection($stream, string $username, string $command, ?string $publicKey = null): int | Handle an incoming SSH connection. |
config(): Config | |
users(): array | |
repos(): array | |
authenticatedUser(): ?User |
SugarCraft\GitServer\Support
AtomicWriter final class
The library's single atomic-write discipline (042): content lands on an exclusive temp inode in the TARGET DIRECTORY, gets its mode settled before payload bytes, is fsynced, and only then is renamed over the destination. A crash or a full disk can therefore only ever leave the OLD bytes or the orphaned temp visible — never a truncated file that silently un-publishes a visibility marker or zeroes a config.
| Method | Summary |
|---|---|
static write(string $path, string $contents, int $mode = 0600): void | Publish $contents at $path atomically. |
static ensureDir(string $path, int $mode): void | Create (or mode-settle) a directory with an EXPLICIT mode — mkdir's mode argument is umask-eroded, so the chmod after creation is what actually makes the requested bits true (038: the init jail must not land 0755 on a permissive-umask box). |
static sweepStaleTemps(string $dir, int $olderThanSeconds = self::STALE_TEMP_AGE_SECONDS, int $maxDepth = 0): int | Sweep stray temps we minted (107): files matching our temp signature whose mtime is older than $olderThanSeconds and whose owner is the running user. $maxDepth > 0 descends subdirectories (the LFS shard tree) but only through plain directories, and the walk is capped — it is a hygiene sweep, not a catalogue. |
BoundedCommand final class
Synchronous argv-only subprocess runner with a hard deadline.
| Method | Summary |
|---|---|
static reapPending(): int | Collect any parked children that have exited since. Returns the number reaped; public so a test (or a shutdown path) can force a sweep without fabricating another spawn. |
static pendingCount(): int | Number of handles parked awaiting a non-blocking reap. |
static run(array $argv, float $timeoutSeconds = self::DEFAULT_TIMEOUT_SECONDS, array $extraEnv = [], ?int $maxOutputBytes = null): array | Line-oriented contract (the historical shape every metadata parser here depends on): stdout split into lines, stderr merged in on failure only. |
static runRaw(array $argv, float $timeoutSeconds = self::DEFAULT_TIMEOUT_SECONDS, array $extraEnv = [], ?int $maxOutputBytes = null): array | Byte-exact contract (S16, finding 031): stdout arrives as written, no line-split and no implode — a CRLF file round-trips as CRLF. Callers serving blob content use this so the bytes they hand out are the repository's bytes. |
HttpWire final class
Shared HTTP transport primitives for the lib's two socket faces.
| Method | Summary |
|---|---|
static writeAll($stream, string $bytes, ?float $stallSeconds = null, ?float $absoluteSeconds = null): int | Push $bytes through a non-blocking stream, retrying every partial accept until the whole payload is handed to the kernel — or until the client makes zero progress for $stallSeconds, or the write outlives the absolute ceiling, or the socket errors. Returns the byte count actually written (== strlen($bytes) on success); the caller's close path is identical either way because a half-delivered response is already protocol-dead to the client. |
LogSafety final class
The lib's single client-token neutralizer for the operator log (027).
| Method | Summary |
|---|---|
static token(string $token): string | Neutralize a client-claimed token for the operator log. The token arrives straight from the peer: a CR/LF inside it forges additional STDERR lines, and an unbounded one floods the log. Strip C0 controls and DEL, collapse whitespace runs, and clip. Identity on any legitimate name — lookups and dispatch still run on the RAW token, so sanitizing here cannot alias a real account or rewrite which route was served. |
Version final class
Reads the version stamped into a running phar archive's metadata.
| Method | Summary |
|---|---|
static resolve(string $archive, string $fallback): string | Resolve the version for the current run. |
static fromPharMetadata(string $archivePath): ?string | Read and normalize the version stamp inside an archive, or null when the path is empty, is not a file, is not a readable phar, or its stamp is neither a comparable X.Y.Z release nor a canonical commit-naming dev-<hex> build stamp. Every failure mode falls back to null rather than throwing — a corrupt archive must not crash --version. |
static isDev(string $version): bool | Whether $version names a DEV build: its lowercase spelling starts with DEV_PREFIX. Deliberately the literal rule and nothing more (mirror of candy-code's isDev) — dev-master classifies as dev, and self::displayLabel() simply has no commit to render from it because fromPharMetadata() never surfaces one. |
static displayLabel(string $archive, string $fallback): string | The string --version prints (053): a comparable release — or any run outside an archive, or one whose stamp names nothing readable — answers exactly as self::resolve() does; a dev build carries its commit as a parenthetical over the compiled-in base triple, 0.1.0 (dev-abc1234), so the output names BOTH the product's train and the exact build. The phar-latest smoke gate greps for the raw dev-<sha> substring, which is why the stamp travels verbatim inside the label. |
WorkerFork final class
Fork-per-request worker pool — owner ruling 8b (G-5/G-1 wave).
| Method | Summary |
|---|---|
__construct(private readonly int $maxWorkers = self::DEFAULT_MAX_WORKERS, private readonly float $ceilingSeconds = self::DEFAULT_CEILING_SECONDS) | |
static supported(): bool | |
fork(callable $handler, $client, array $foreign = []): bool | Spawn a worker owning $client. $foreign are the parent's other live descriptors (listener socket, other clients) which the child closes IMMEDIATELY so a wedged-or-alive worker can never hold a port or another client's stream open. $handler is a blocking pump: called repeatedly in the child, returns false when the connection is done. |
reap(): int | Non-blocking collect of every worker that has exited. Returns the count reaped; each reap also closes that worker's death-pipe end, which is what lets a live worker see EOF if the parent stops the pool. |
live(): int | Live workers right now (sweeps first). |
terminateAll(): void | Orderly end for every worker: TERM, bounded poll, KILL the stragglers. Idempotent; safe on an empty pool. |
peakCount(): int | Maximum simultaneous workers any run of this pool has held. |
totalSpawned(): int | Total workers this pool has ever spawned. |
Configuration
Create config.yaml in the data directory. candy-git-server init writes a skeleton with every key. The census below is the authoritative list of which keys Config parses and which code path consults each one. A key marked dead is accepted and held on the object, but nothing reads it yet. Changing it changes nothing.
Keys that take effect
| Key | Default | Effect |
|---|---|---|
git.allow_anonymous_read | false | Turns on anonymous reads of public repos, over HTTP and through the daemon. |
git.max_timeout | 0 | Deadline for a stateless git child on the smart-HTTP path. |
git.listen_addr | :9418 | The daemon's bind address. |
git.idle_timeout | 3 | The daemon's idle timer. |
git.max_connections | 32 | The daemon's connection cap. Newcomers are refused past the cap, and an established transfer is never evicted. |
git.mirror_allow_git_protocol | false | Lets mirror pulls reach their upstream over the unauthenticated git:// protocol. Each such pull is logged. |
http.max_pack_bytes | 268435456 | The one request-body cap, shared by pack POSTs and LFS object PUTs. Larger bodies answer 413. |
http.public_url | http://localhost:23232 | The origin used in LFS batch hrefs. Set it to the https:// origin behind a proxy. |
http.user_trust_mode | off | Selects one of off, proxy or token for the identity headers. |
http.trusted_proxies | empty | For proxy mode. Exact IPv4 or IPv6 addresses, or CIDR ranges, as a YAML list or a comma-separated string. |
http.auth_secret | empty | The HMAC key for token mode. Generate it with php -r "echo bin2hex(random_bytes(32));". |
http.token_max_ttl | 2592000 | The ceiling on the lifetime of a minted proxy token, in seconds. Values above one year are refused at load. |
http.worker_per_request | true | Forks one worker per connection when ext-pcntl is present. Set it to false to serve connections one at a time. |
http.auth_max_attempts | 10 | The failed Basic-auth budget per peer and per username. An exhausted budget refuses the attempt before any bcrypt work. |
http.auth_refill_seconds | 60 | The window over which the failed-attempt budget refills. |
lfs.enabled | true | Gates the LFS routes. |
jobs.mirror_pull | @every 10m | The mirror-pull schedule. Cron expressions are refused. |
stats.listen_addr | :23233 | The stats endpoint bind. A hostless value resolves to loopback. |
stats.persist_path | empty | Keeps counter history across restarts. Empty means the counters reset on each start. |
stats.flush_interval_seconds | 60 | How often to flush the counters, as an integer from 1 to 86400. |
Keys that are read by nothing
| Key | What happens |
|---|---|
http.listen_addr | Parsed, but serve --http binds from its --http-host and --http-port flags only. |
http.tls_key_path, http.tls_cert_path | Validated only. Setting either refuses the config at load, with config.tls_not_supported. |
ssh.*, lfs.ssh_enabled, log_format | Parsed and held, and used by no shipped code path. |
name | Reaches only the example script. |
db | Not parsed. Config has no database concept, so a db: block is silently ignored. |
Example file
name: "My Git Server"
git:
listen_addr: ":9418" # daemon bind, if a host runs the class
allow_anonymous_read: false # default off
http:
public_url: "http://localhost:23232"
max_pack_bytes: 268435456
user_trust_mode: "off"
lfs:
enabled: true
jobs:
mirror_pull: "@every 10m"
stats:
listen_addr: ":23233" # hostless bind stays on loopback
Quote values that start with a YAML indicator, such as listen addresses like ":23232" and schedules like "@every 10m". The data path is set by --config F, which makes its directory the data path, or by CANDY_GIT_SERVER_DATA_PATH. Without either, the default is sys_get_temp_dir()/candy-git-server, which is for trials only.
Environment
| Variable | Effect |
|---|---|
CANDY_GIT_SERVER_DATA_PATH | The data path. The explicit command-line argument outranks it. |
CANDY_GIT_SERVER_LANG | The CLI message locale. An unknown value falls back to English. |
CANDY_GIT_SERVER_BOOTSTRAP_ADMIN | Does the same as init --admin <name>. It applies to init only. |
CANDY_SERVE_* | Legacy names from the package's earlier life. They are still honored through LegacyEnv, with a deprecation notice on stderr. |
Run
serve --http is the only long-running entry point. It runs in the foreground, and it has no daemon mode. Its flags are listed below.
| Flag | Meaning | Default |
|---|---|---|
--repo-root DIR | The directory whose subdirectories are served. Required. | none |
--http-port N | The listen port. --port is a deprecated alias. | 23232 |
--http-host H | The listen host. | 127.0.0.1 |
--config F | The YAML config, whose directory is the data path. | defaults applied |
--daemon, --pid-file, --verbose | Refused on this path, because the listener always stays in the foreground. | n/a |
The bare command serve refuses with exit 1 and an honest message, because the SSH and git-daemon transports are not wired. The exit codes are 0 for success and graceful shutdown, and 1 for any refusal. A refusal covers a bad flag, a bind failure, an unknown user or repo, an existing admin, a corrupt store and a bare serve.
candy-git-server serve
candy-git-server: 'serve' refuses to start: the ssh and git listeners are not wired yet, only 'serve --http' runs (see the README, Known gaps)
$ echo $?
1
Admin and account commands
candy-git-server init /var/lib/candy-git-server --admin alice --admin-password-stdin
candy-git-server user add bob /var/lib/candy-git-server --password
candy-git-server user key bob ~/.ssh/id_ed25519.pub
candy-git-server user token alice 3600 /var/lib/candy-git-server
candy-git-server user deactivate bob /var/lib/candy-git-server
candy-git-server repo collaborator myrepo add bob /var/lib/candy-git-server
candy-git-server repo list /var/lib/candy-git-server
init --admin refuses when an admin already exists, unless --force replaces the named account. A --password with no value reads stdin. An account with no password and no key is warned about, because it authenticates nothing. user add without flags creates a non-admin, and --admin raises a global admin that passes every check.
Keys and signals
There are no keybindings, because there is no terminal interface. The signals are the only control surface. serve --http arms SIGINT and SIGTERM when ext-pcntl is loaded, and both stop the listener and exit 0. It has no reload path, and SIGHUP keeps its default disposition, which kills the process. The GitDaemon class routes SIGTERM, SIGINT and SIGHUP into one shutdown handler, so a daemon you host yourself also stops on SIGHUP.
Theming and styling
This package draws nothing. It has no TUI, and no theme. The Clipboard\Osc52 class encodes OSC 52 clipboard sequences, but no code path consumes it, so it does nothing in this release. Output from the CLI is plain text, localized through the same catalogs used for errors.
Examples
The examples/ directory holds two PHP programs. They load the Composer autoloader, so run them from a checkout after composer install. Both are safe to run without a server.
examples/config.phpprints the default configuration and the values from a sample YAML file, usingConfig::fromDefaults()andConfig::load().examples/repo.phpbuilds a repo description in a private temporary directory, prints its metadata, and prints the access matrix for three callers: a collaborator, a second user and an anonymous caller.
php examples/config.php < /dev/null
php examples/repo.php < /dev/null
=== Access matrix ===
alice read=yes write=yes admin=no
bob read=yes write=yes admin=no
guest read=no (anonymous read = off)
Testing
The suite runs under PHPUnit 10. Run it once from the package root, with stdin redirected:
cd candy-git-server && composer install && vendor/bin/phpunit < /dev/null
The tests are grouped by the transport they cover. tests/HttpSmartProtocol/ covers the clone, fetch, push and LFS routes, the trust modes and the listener's hardening. It includes BinServeLiveE2ETest, which drives the launched bin/candy-git-server over a live socket. tests/Git/ covers the pkt-line codec, the stateless-rpc children and the daemon. tests/SSH/ covers the dispatcher. tests/Jobs/ covers the mirror schedule. UserStoreTwoProcessTest checks the account store across two processes.
Troubleshooting
The repo create command fails with a class not found error
This means the sugar-core in vendor/ is older than the one candy-git-server was written against. Run composer update in the package, or rebuild the monorepo wiring with php scripts/refresh-deps.php --mode=linked when you develop inside the monorepo.
Clone prompts for a password, then refuses, on a public repo
Anonymous reads need two things: the repo's visibility is public, and git.allow_anonymous_read is true. The listener logs the 401 it returns. Set the lever in config.yaml and restart the listener so it loads the new config. An authenticated clone works either way.
A push of a large file answers 413
http.max_pack_bytes caps the request body, and the default is 256 MiB. Raise it in config.yaml and restart. Behind nginx, set client_max_body_size to at least the same value, or nginx refuses the push before the server sees it.
Every identity header is ignored, or every request is refused in proxy mode
off is the default, and it ignores the identity headers entirely. proxy mode trusts a header only from a peer listed in http.trusted_proxies, so an empty list refuses everything. List the proxy's exact address or its CIDR range. Under token mode, a header with an expired or wrong HMAC is refused, so mint a new value with user token.
The server stops on a SIGHUP, or exits with 130 or 143
serve --http has no reload. SIGHUP kills it, so do not write an ExecReload line. Without ext-pcntl, a stop signal is not caught, and the shell reports 130 or 143 instead of 0. Install the extension in the container image, or accept that the exit code is not clean.
The CLI says Repository not found
The name you passed does not match a repository under the data path. Check the spelling and the data path argument. Create the repo first with repo create, or point the command at the data directory where it lives.
Architecture
The CLI is bin/candy-git-server. It parses commands and flags, then calls into the library. The library is organized around the transports, and each transport reuses the same access checks, the same pkt-line codec and the same bounded subprocess runner.
| File | Role |
|---|---|
src/Config.php | The YAML loader and its typed accessors. |
src/Repo.php, src/Visibility.php | The bare-repository model and its visibility enum. |
src/User.php, src/UserStore.php | The account model and the atomic users.json store. |
src/AccessControl.php | Read, write and admin decisions. |
src/HttpSmartProtocol/Server.php, HttpListener.php | The smart-HTTP and LFS router, and the socket listener that hosts it. |
src/Git/StatelessRpc.php, PktLine.php, StdioPipe.php | The stateless-rpc children, the pkt-line codec and the bounded stdio pump. |
src/Git/GitDaemon.php, UploadPack.php, ReceivePack.php | The git:// daemon class and the daemon-shape handlers. |
src/SSH/SSHServer.php | The ForceCommand gate for host sshd. |
src/LFS/LFSHandler.php, LocalStorageBackend.php | The LFS batch API and the default object store. |
src/Jobs/Schedule.php, MirrorPuller.php | The schedule grammar and the mirror-pull job. |
src/Stats.php, StatsServer.php | The counters and their JSON endpoint. |
src/Support/BoundedCommand.php, PromisePool.php, Version.php | The subprocess runner, the concurrency cap and the version resolver. |
Every subprocess is bounded and reaped
Each served request spawns a git child through BoundedCommand. That runner takes an argv array, never a shell string. It enforces a cap on the output bytes and a deadline, and it reaps the child with TERM and then KILL. A child that outlives its deadline is killed, not waited on.
Workers isolate connections
By default the HTTP listener forks one worker per connection, when ext-pcntl is present and http.worker_per_request is not set to false. Each worker serves its connection to completion and exits, so one stalled request cannot delay the others. With the knob off, or without pcntl, connections are served one at a time, and the CLI says so on stderr at startup.
Upstream mapping
| Upstream | Where it shows up here |
|---|---|
| charmbracelet/soft-serve (Go) | The design antecedent. The repo, user and access model, the smart-HTTP serving and the LFS routes are ported in part. Soft-serve's TUI is not ported. |
soft-serve's default ports, 8022 and 8080 | Not used. The defaults here are 23231 for the reserved SSH slot, 23232 for HTTP, 23233 for stats and 9418 for git. |
SugarCraft is a native PHP project. The classes in src/ carry docblocks that cite the soft-serve source where a behavior was taken from it.
Changelog and versioning
The version is the VERSION constant in bin/candy-git-server, 0.1.0. Inside a phar, the build stamp replaces it, as Support\Version::resolve() reads it. The package was published as sugarcraft/candy-serve until the 2026-10 rename, and its namespace moved from SugarCraft\Serve\ to SugarCraft\GitServer\. The CANDY_SERVE_* environment names still work through LegacyEnv, with a stderr notice. Known gaps are listed in the README, and they are the authority on what is not yet built.
The gaps in short. git:// completes no fetch past the advertisement, no shipped SSH deployment recipe exists, nothing starts the mirror job or the stats endpoint on its own, and there is no TLS termination. Locale coverage is machine-assisted and not reviewed by a native speaker.
Related
- sugar-ssh-server: a general SSH middleware and session framework, also run under host sshd. Its auth model differs, because it trusts sshd and allowlists by username and key fingerprint.
- sugar-async: the
Subscriptionsmachinery that the daemon uses for shutdown. - sugar-core: the runtime and the
Util\Prochelpers that the bounded runner builds on.
Demos.
This package has no terminal interface, so there is no recording to show. The quickstart above and the live listener log are the demonstration.