All 22 apps

CandyGitServer

Git server: smart-HTTP clone/fetch/push/LFS live

inspired by charmbracelet/soft-serve gitserversshself-hosted

CandyGitServer code coverage

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

ClassMethodDescription
Configstatic fromDefaults(), static load(string $path)Configuration from env and defaults, or from a YAML file parsed by symfony/yaml.
ConfigreposPath(), sshPath(), lfsPath(), ensureReposPath()The data directories. The ensure* variants create the directory.
Repostatic new(string $name, string $path)An immutable repo description. A fresh handle is private.
RepowithDescription(), withVisibility(Visibility $v), withPublic(bool $v = true), withPrivate(), withAllowPush(), withMirrorFrom(?string $url), withHighlightLanguage(string $lang)Each returns a new instance.
RepoaddCollaborator(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.
Repoinit(), 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.
RepowriteMeta(), 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.
RepoisPrivate(), isVisiblePublic(), isMirror()Visibility and mirror predicates.
VisibilityPublic, CollaboratorOnly, PrivateThe enum on each repo. fromBools() maps the legacy pair.
Userstatic 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.
UserStorestatic forDataPath(string $dataPath), find(), all(), add(), put(), remove(), deactivate(), transaction(callable $mutator)The atomic users.json store.
AccessControlstatic instance(), setAllowAnonymousRead(bool $allowed)The process-global posture, shared with the daemon and SSH transports.
AccessControlcanRead(?User $user, Repo $repo), canWrite(), canAdmin(), canCreateRepos()Permission checks. A null user is anonymous, and canWrite() refuses it unconditionally.

Transports

ClassMethodDescription
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\HttpListenerstart(), 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\PktLinestatic 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\StatelessRpcstatic 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

ClassMethodDescription
LFS\LFSHandlerhandleBatch(array $request), handleBatchAsync(array $request, ?LoopInterface $loop = null), withStorageBackend(LFSStorageBackendInterface $backend)The Git LFS batch API, synchronous and promise-based.
LFS\LocalStorageBackendimplements LFSStorageBackendInterfaceThe 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\Scheduleparses @every and the aliasesThe 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.
Statsstatic instance(), recordConnection(), recordPackUpload(), connections(), snapshot(), toJson(), flushNow()The shared counters, persisted when stats.persist_path is set.
Support\BoundedCommandstatic run(array $argv, float $timeoutSeconds = ...), runRaw()The argv-only subprocess runner with caps, a deadline and reaping. It takes no shell string.
Support\PromisePoolbounded-concurrency helperCaps how many promises run at once. It bounds LFS transfers.
Support\Versionresolve(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.

MethodSummary
static instance(): self
static setInstance(self $ac): void
setAllowAnonymousRead(bool $allowed): voidSet whether requests with no authenticated identity may read public repos. Authenticated users are never gated by this lever.
canRead(?User $user, Repo $repo): boolCheck if a user can read a repo.
canWrite(?User $user, Repo $repo): boolCheck if a user can push to a repo.
canAdmin(?User $user, Repo $repo): boolCheck if a user can administer a repo (change settings, add collaborators).
canCreateRepos(?User $user): boolCheck if a user can create repos.
allowAnonymousRead(): boolCheck if anonymous access (public key) is allowed for reading.
static permissionName(int $level): stringResolve the permission level name.

Config final class

Server configuration loaded from config.yaml.

MethodSummary
static load(string $path): selfLoad config from a YAML file.
static fromDefaults(): selfLoad config from env + defaults.
reposPath(): stringRepository 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(): stringSSH host-key + user-store directory — PURE (091), see reposPath().
lfsPath(): stringLFS object root — PURE (091), see reposPath().
ensureReposPath(): stringCreate 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(): stringCreate the ssh/user-store directory, owner-only (0700).
ensureLfsPath(): stringCreate 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.

MethodSummary
static new(string $name, string $path): selfA 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): boolIs $name safe to use as a single repository directory component?
static markerVisibility(string $gitDir): VisibilityVisibility 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): stringThe 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(): stringThe git directory for this repo (path itself when bare, else path/.git).
writeVisibilityMarker(): voidPersist the current visibility marker into the repo's git directory.
static metaPathFor(string $gitDir): string
static readMeta(string $gitDir): arrayRead 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(): arrayThis handle's persistable fields as a metadata-plane array.
writeMeta(): voidPublish 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): arrayLoad→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(): selfOverlay 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(): ?intThe mirror job's persisted last-attempt for this repo (null = never), read straight from the metadata plane.
stampMirrorAttempt(int $when): voidPersist a mirror pull-attempt stamp (finding 044).
withDescription(string $d): self
withVisibility(Visibility $v): self
withPublic(bool $v = true): selfBC 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): selfBC 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(): selfInitialize 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(): stringGet the path to the bare Git repository.
exists(): boolWhether 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'): arrayGet a list of { ref => hash } for refs matching $prefix.
readFile(string $commitHash, string $path): ?stringRead a file from the repo at a given commit + path.
readme(): ?arrayGet the README content (tries common names).
isPrivate(): bool
isVisiblePublic(): boolWhether this repo is publicly visible. A repo that is not explicitly public is collaborator-only (or private).
isMirror(): boolWhether 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.

MethodSummary
__construct(?string $persistPath = null, int $flushIntervalSeconds = 60)
static instance(): self
static setInstance(self $stats): void
recordConnection(): voidA transport (git daemon or HTTP) handled a connection/request.
recordPackUpload(): voidA pack was received from a client (git-receive-pack / push).
recordPackDownload(): voidA 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(): voidZero 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(): boolForce a merge-and-write regardless of the cadence (stop path, tests).

StatsServer final class

Minimal HTTP stats endpoint on stats.listen_addr.

MethodSummary
__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): voidBind stats.listen_addr and start answering on the event loop.
stop(): voidTear down every loop registration and close all sockets. Idempotent.
isRunning(): bool
activeConnectionCount(): intSeats currently held (accepted, request unfinished).
listenAddress(): ?stringActual 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/.

MethodSummary
static new(string $username): self
withUsername(string $u): self
withAdmin(bool $v = true): self
withActive(bool $v = true): self
withPasswordHash(?string $hash): selfAttach a password_hash() digest (the only password form the store keeps).
toArray(): arraySerializable 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): selfAdd a public key to this user's authorized_keys. Supports ssh-ed25519, ssh-rsa, ecdsa-sha2-*, sk-ssh-ed25519@openssh.com
verifyPublicKey(string $presentedKey): boolVerify a presented public key matches one of this user's authorized keys.
authorizedKeysList(): arrayGet all authorized keys.
publicKeyComment(): stringThe default SSH public key comment for generated keys.
generateKeyPair(): ?arrayGenerate an ssh-ed25519 key pair by delegating to ssh-keygen(1).

UserStore final class

Persistent user accounts store — JSON file, one per data directory.

MethodSummary
__construct(string $filePath)
static forDataPath(string $dataPath): self
path(): string
all(): array
find(string $username): ?User
add(User $user): boolRegister 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): voidUpsert an existing account (for key edits / deactivation).
remove(string $username): boolRemove 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): ?UserFlip 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): mixedRun 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(): voidPersist 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().

MethodSummary
static fromBools(bool $isPublic, bool $private): selfMap the legacy two-boolean model onto the enum. A set private flag always wins, matching the old isPrivate() accessor.
isPublic(): boolAnyone (including anonymous users) may read the repo.
isPrivate(): boolExplicitly private: collaborators/admins only.

SugarCraft\GitServer\Clipboard

Osc52 final class

OSC 52 clipboard handler for candy-git-server.

MethodSummary
parse(string $data): ?arrayParse and apply an OSC 52 payload.
write(string $selection, string $data): voidWrite clipboard data (decodes base64 and stores).
read(string $selection): ?stringRead clipboard data for a selection.
has(string $selection): boolCheck if a selection has content.
clear(string $selection): voidClear a clipboard selection.
pendingEvents(): arrayGet all pending clipboard events.
buildReadResponse(string $selection, string $data): stringGenerate an OSC 52 response string for a clipboard read.
onChange(callable $listener): voidRegister a listener for clipboard changes.
offChange(callable $listener): boolRemove 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(): arrayGet 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.

MethodSummary
__construct(Config $config)
setStats(Stats $stats): voidInject 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): voidRegister a subscription for cleanup on graceful shutdown.
clearSubscriptions(): voidUnregister all subscriptions (used after shutdown).
serve(string $pidFile = ''): intStart the daemon in blocking mode.
serveAsync(?LoopInterface $loop = null, string $pidFile = ''): PromiseInterfaceStart 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(): voidRequest 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(): ?stringActual 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.

MethodSummary
static encode(string $payload): stringFrame one payload as a spec pkt-line.
static flush(): stringThe flush-pkt.
static isServiceHeader(string $payload, string $service): boolTrue 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.

MethodSummary
__construct(Repo $repo, ?User $user = null)
repo(): Repo
serve($in = null, $out = null): intServe 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.

MethodSummary
static binaryFor(string $service): ?stringThe 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): stringRun 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): arrayRun 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.

MethodSummary
static run($in, $out, array $argv, string $cwd, string $seed = '', ?float $idleSeconds = null, ?float $hardSeconds = null): intPump one request between the client pair and the spawned child.

UploadPack final class

Handles git-upload-pack requests (clone / fetch) over the SSH transport.

MethodSummary
__construct(Repo $repo, ?User $user = null)
repo(): Repo
serve($in = null, $out = null): intServe 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).

MethodSummary
__construct(private readonly string $stateFile, private readonly int $capacity, private readonly int $refillSeconds, ?callable $clock = null)
charge(string $peer, string $username): ?intCharge 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): voidGive 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.

MethodSummary
__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.

MethodSummary
__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(): voidBind 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(): voidStop accepting, drop the watches, end every worker, and drop every client; idempotent.
listenAddress(): ?stringBound address as "host:port" (with the concrete ephemeral port), or null when stopped.
activeConnectionCount(): intSeats currently held (accepted, request unfinished), worker-owned included.

PasswordVerifyCache final class

Small capped LRU of bcrypt results (finding 048).

MethodSummary
__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): boolpassword_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(): intLive entries (tests + introspection).

Server final class

HTTP server that speaks the Git smart protocol.

MethodSummary
__construct(Config $config, ?AccessControl $accessControl = null)
setAllowAnonymousRead(bool $allowed): voidRuntime 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(): AccessControlThe 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): voidArm 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): voidInject a stats collector (default: the shared Stats instance).
maxRequestBodyBytes(): intEffective 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): arrayHandle an incoming HTTP request.
static mintUserToken(string $username, int $expiry, string $secret): stringMint 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.

MethodSummary
__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): ?intWhen the last pull of a repo was attempted (null = never).
effectiveLastPull(Repo $repo): ?intThe 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(): floatWall-clock budget one runOnce() batch may spend (S05, finding 005).
runOnce(?int $now = null, ?float $budgetSeconds = null): intPull 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): boolPull 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): ?stringWhy 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): voidSchedule the job on a ReactPHP loop: runOnce() fires every schedule interval (the async-daemon counterpart of calling runOnce() from blocking housekeeping).
detach(): voidCancel the loop timer. Idempotent.
isAttached(): bool

Schedule final class

Background-job schedule parsed from config.

MethodSummary
static parse(string $expression): self
isDue(?int $lastRun, int $now): boolWhether 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/.

MethodSummary
__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): selfCreate 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): selfCreate with concurrent transfer limit.
static isValidOid(string $oid): boolAn 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): arrayHandle an LFS batch request.
handleBatchAsync(array $request, ?LoopInterface $loop = null): PromiseInterfaceHandle 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(): LFSStorageBackendInterfaceGet the storage backend being used.
concurrentTransfers(): intGet the concurrent transfer limit.
maxObjectBytes(): intThe configured per-object size ceiling.

LFSStorageBackendInterface interface

Interface for LFS storage backends.

MethodSummary
exists(string $oid): boolCheck if an object exists in storage.
size(string $oid): intGet the size of an object in storage.
read(string $oid)Get a readable stream for an object.
write(string $oid, $stream): voidWrite a file to storage from a stream.
delete(string $oid): voidDelete an object from storage.
path(string $oid): ?stringGet the path for an object (if applicable). This is used for generating download URLs.

LocalStorageBackend final class

Local filesystem storage backend for LFS objects.

MethodSummary
__construct(private readonly string $lfsPath)
static isValidOid(string $oid): bool
exists(string $oid): bool
size(string $oid): int
read(string $oid)
readAll(string $oid): stringRead an object fully into memory and close the handle.
write(string $oid, $stream): voidPublish 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): voidPublish 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): voidRemove 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.

MethodSummary
__construct(Config $config)
registerUser(User $user): void
registerRepo(Repo $repo): void
setUsers(iterable $users): void
handleConnection($stream, string $username, string $command, ?string $publicKey = null): intHandle 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.

MethodSummary
static write(string $path, string $contents, int $mode = 0600): voidPublish $contents at $path atomically.
static ensureDir(string $path, int $mode): voidCreate (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): intSweep 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.

MethodSummary
static reapPending(): intCollect 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(): intNumber of handles parked awaiting a non-blocking reap.
static run(array $argv, float $timeoutSeconds = self::DEFAULT_TIMEOUT_SECONDS, array $extraEnv = [], ?int $maxOutputBytes = null): arrayLine-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): arrayByte-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.

MethodSummary
static writeAll($stream, string $bytes, ?float $stallSeconds = null, ?float $absoluteSeconds = null): intPush $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).

MethodSummary
static token(string $token): stringNeutralize 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.

MethodSummary
static resolve(string $archive, string $fallback): stringResolve the version for the current run.
static fromPharMetadata(string $archivePath): ?stringRead 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): boolWhether $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): stringThe 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).

MethodSummary
__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 = []): boolSpawn 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(): intNon-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(): intLive workers right now (sweeps first).
terminateAll(): voidOrderly end for every worker: TERM, bounded poll, KILL the stragglers. Idempotent; safe on an empty pool.
peakCount(): intMaximum simultaneous workers any run of this pool has held.
totalSpawned(): intTotal 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

KeyDefaultEffect
git.allow_anonymous_readfalseTurns on anonymous reads of public repos, over HTTP and through the daemon.
git.max_timeout0Deadline for a stateless git child on the smart-HTTP path.
git.listen_addr:9418The daemon's bind address.
git.idle_timeout3The daemon's idle timer.
git.max_connections32The daemon's connection cap. Newcomers are refused past the cap, and an established transfer is never evicted.
git.mirror_allow_git_protocolfalseLets mirror pulls reach their upstream over the unauthenticated git:// protocol. Each such pull is logged.
http.max_pack_bytes268435456The one request-body cap, shared by pack POSTs and LFS object PUTs. Larger bodies answer 413.
http.public_urlhttp://localhost:23232The origin used in LFS batch hrefs. Set it to the https:// origin behind a proxy.
http.user_trust_modeoffSelects one of off, proxy or token for the identity headers.
http.trusted_proxiesemptyFor proxy mode. Exact IPv4 or IPv6 addresses, or CIDR ranges, as a YAML list or a comma-separated string.
http.auth_secretemptyThe HMAC key for token mode. Generate it with php -r "echo bin2hex(random_bytes(32));".
http.token_max_ttl2592000The ceiling on the lifetime of a minted proxy token, in seconds. Values above one year are refused at load.
http.worker_per_requesttrueForks one worker per connection when ext-pcntl is present. Set it to false to serve connections one at a time.
http.auth_max_attempts10The failed Basic-auth budget per peer and per username. An exhausted budget refuses the attempt before any bcrypt work.
http.auth_refill_seconds60The window over which the failed-attempt budget refills.
lfs.enabledtrueGates the LFS routes.
jobs.mirror_pull@every 10mThe mirror-pull schedule. Cron expressions are refused.
stats.listen_addr:23233The stats endpoint bind. A hostless value resolves to loopback.
stats.persist_pathemptyKeeps counter history across restarts. Empty means the counters reset on each start.
stats.flush_interval_seconds60How often to flush the counters, as an integer from 1 to 86400.

Keys that are read by nothing

KeyWhat happens
http.listen_addrParsed, but serve --http binds from its --http-host and --http-port flags only.
http.tls_key_path, http.tls_cert_pathValidated only. Setting either refuses the config at load, with config.tls_not_supported.
ssh.*, lfs.ssh_enabled, log_formatParsed and held, and used by no shipped code path.
nameReaches only the example script.
dbNot 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

VariableEffect
CANDY_GIT_SERVER_DATA_PATHThe data path. The explicit command-line argument outranks it.
CANDY_GIT_SERVER_LANGThe CLI message locale. An unknown value falls back to English.
CANDY_GIT_SERVER_BOOTSTRAP_ADMINDoes 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.

FlagMeaningDefault
--repo-root DIRThe directory whose subdirectories are served. Required.none
--http-port NThe listen port. --port is a deprecated alias.23232
--http-host HThe listen host.127.0.0.1
--config FThe YAML config, whose directory is the data path.defaults applied
--daemon, --pid-file, --verboseRefused 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.php prints the default configuration and the values from a sample YAML file, using Config::fromDefaults() and Config::load().
  • examples/repo.php builds 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.

FileRole
src/Config.phpThe YAML loader and its typed accessors.
src/Repo.php, src/Visibility.phpThe bare-repository model and its visibility enum.
src/User.php, src/UserStore.phpThe account model and the atomic users.json store.
src/AccessControl.phpRead, write and admin decisions.
src/HttpSmartProtocol/Server.php, HttpListener.phpThe smart-HTTP and LFS router, and the socket listener that hosts it.
src/Git/StatelessRpc.php, PktLine.php, StdioPipe.phpThe stateless-rpc children, the pkt-line codec and the bounded stdio pump.
src/Git/GitDaemon.php, UploadPack.php, ReceivePack.phpThe git:// daemon class and the daemon-shape handlers.
src/SSH/SSHServer.phpThe ForceCommand gate for host sshd.
src/LFS/LFSHandler.php, LocalStorageBackend.phpThe LFS batch API and the default object store.
src/Jobs/Schedule.php, MirrorPuller.phpThe schedule grammar and the mirror-pull job.
src/Stats.php, StatsServer.phpThe counters and their JSON endpoint.
src/Support/BoundedCommand.php, PromisePool.php, Version.phpThe 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

UpstreamWhere 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 8080Not 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.

  • 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 Subscriptions machinery that the daemon uses for shutdown.
  • sugar-core: the runtime and the Util\Proc helpers that the bounded runner builds on.

Try the quickstart →

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.