main
ply4 git calls10 ms60 KiB3 cachedprotocol v2
488 lines45 KiBRaw

ply Worker — https://ply.ivar.workers.dev

A Cloudflare Worker that exposes ply as an HTTP API against any smart-HTTP git host. The git client is github:ivarvong/ply#af5cac0372df6caf774d108cbf9229b04af45eb6 (an exact commit of ply main; an operator moves the pin with npm run cd -- bump). The /v1 git API has no storage. GET /view is a public repository viewer, rate-limited by client through a SQLite Durable Object. One Artifacts namespace, public-v0, is served read-only with no token (/r/<repo>, see Public namespace). Feature flags are one R2 object and a service binding (Feature flags). GET / prints the usage text.

Auth

  • Gate: Authorization: Bearer <PLY_TOKEN> on /v1. GET /, GET /view, GET /view.css, GET /r/<repo>, and the /v1 reads of the public namespace are public. The token is a Worker secret (cf workers secrets update PLY_TOKEN --worker ply --type secret_text) and is compared in constant time (SHA-256 of both sides, then crypto.subtle.timingSafeEqual). A missing or wrong token returns 401 {code: "unauthorized"}.
  • Git credential (optional; public repos need none):
    • Git-Authorization: <value> is sent upstream verbatim as Authorization.
    • Git-Token: <token> is mapped by host: github.com → Basic x-access-token:<token>, gitlab.* → Basic oauth2:<token>, anything else (Cloudflare Artifacts included) → Bearer <token>. Artifacts accepts Bearer and Basic; both were checked in the smoke run.
    • Sending both headers is a 400.
    • Neither credential appears in a response, trace, error message or log line. ply never records them, and the Worker scrubs every outgoing string as a second layer (test/worker.test.js greps all of these, including a hostile upstream that echoes the header back).
  • Remote rules: remote must be https:, on the default port, with no userinfo, query, or fragment. The host is canonicalised (lowercase, no trailing dot — github.com. is rejected rather than stripped). IP literals are refused in every encoding the URL parser accepts (dotted, zero-padded, octal, hex, decimal 2130706433, IPv6, IPv4-mapped, IPv4-compatible). So are single-label hosts, localhost/.local/.internal/.lan/.home.arpa/… names, and wildcard-DNS names (nip.io, sslip.io, localtest.me, and the same shape of zone). A path segment of . or .., or an encoded slash, backslash, or dot (%2f, %5c, %2e), is rejected before normalisation. Redirects follow git's http.followRedirects=initial: ply follows a 3xx only on the first GET info/refs (at most three hops, and only when the Location keeps the /info/refs?service=… suffix), and every later request, POSTs included, goes to the rewritten base. ply's allowUrl hook (remoteAllowUrl, src/remote.ts) vets each new base with the same check, on the same origin. A 3xx on a POST, a loop past three hops, or a Location git would not rebase to is a 400 with code http naming the target (git cannot use such a remote either). The Worker's fetch wrapper (createGuardedFetch) re-checks every request and never follows a 3xx itself; a 3xx whose Location is on another origin or fails the check is a 400 bad_request before ply sees it, so a credential never leaves the origin (test/worker.test.js, "redirects"). ALLOW_REMOTE_ORIGINS (comma-separated origins) exempts those origins from the public-host rules (http, an IP, a non-default port). Only the tests use it.

Endpoints

MethodPathInputOutput
GET/v1/refsremote, prefix?{refs: {name: oid}, head, peeled: {tag: commit}}. An empty repository adds {empty:true, unborn:"refs/heads/main"} and leaves head null
GET/v1/discoverremoteprotocol v2 capabilities (agent, fetch, filter, caps, …)
GET/v1/readremote, ref?, paththe blob, streamed. Headers: content-length, x-ply-ref, x-ply-commit, x-ply-blob, x-ply-mode, x-ply-size. A directory is 400 bad_request (list it with GET /v1/tree), not 404
GET/v1/treeremote, ref?, path?{ref, commit, tree, entries: [{name, mode, oid, type}]} (modes as git ls-tree prints them)
GET/v1/commitremote, ref?born: {ref, oid, tree, parents, author, committer, message, signed}. author/committer are {name, email, time, epoch, tz} (time ISO-8601 UTC, epoch the raw seconds, tz as written, e.g. +0530). message is the raw body. signed means a gpgsig header is present (not verified). Fetches the commit only (tree:0, deepen 1; blob:none when the server refuses that). Empty repository (unborn HEAD, or that same branch by name): {empty:true, ref:"refs/heads/main", oid:null, tree:null, parents:[], author:null, committer:null, message:null, signed:false}. A different missing ref stays 404. A born response does not grow an empty field
POST/v1/edit{remote, ref?, base?, author, committer?, message, head?, changes?} or the one-file form {path, find?, replace?, content?, delete?, to?, mode?}{outcome, ref, oid, oldOid, noop, tree, newCommit, oldCommit}. newCommit/oldCommit alias oid/oldOid. A root commit and any newly created ref have oldOid: null
POST/v1/branch{remote, ref, from?}201 {outcome:"created", ref, oid, oldOid:null}. from is a branch or a 40-hex commit. Omit from only when HEAD is born
DELETE/v1/branch{remote, ref, oid?}{outcome:"deleted", ref, deleted}. CAS on oid (default: the oid ls-refs shows now)
POST/v1/tag{remote, name, target, annotated?, message?, tagger?}201 {outcome:"tag", ref, oid, commit, annotated}. Lightweight unless annotated, message, or tagger is set. target is a branch or a commit id
DELETE/v1/tag{remote, name, oid?}same compare-and-swap as DELETE /v1/branch
POST/v1/merge{remote, ref?, from, author?, committer?, message?, fastForwardOnly?, noFastForward?}{outcome, ref, oid, oldOid, noop, …} where outcome is merge, fast_forward, or up_to_date. from is a branch or a 40-hex commit. author and committer are separate stamps, each with its own time and tz
POST/v1/rebase{remote, ref, onto?, committer, author?, squash?, message?}{outcome, ref, oid, oldOid, …} where outcome is rebase, squash, fast_forward, or up_to_date. onto is a branch or a 40-hex commit. author.time and committer.time are independent
POST/v1/cherry-pick, /v1/revert{remote, ref?, commit, committer, message?, allowEmpty?}{outcome, ref, oid, oldOid, noop, tree?}. A patch already applied, and only when both sides added and deleted the same paths, is {outcome:"empty", noop:true, oid:<tip>}. allowEmpty:true writes that empty commit. If the target also has its own adds or deletes, the response is 409 merge_conflict (allowEmpty does not override it)
GET/v1/flagsthe cached flag ruleset {revision, cache, environment, flags}. Writes are not this route
POST/v1/flags/eval{unit, attributes?, keys?}{revision, cache, flags:[{key, variant, reason, bucket}]}. Per-unit; the response is no-store

Flag writes are not HTTP (PUT/POST/PATCH/DELETE /v1/flags are 405). Operators call scripts/flags, which talks to the ply-flag-operator Worker. That Worker checks FLAG_OPERATOR_TOKEN and calls FlagControl (setRollout, setTargeting, getConfig) over a service binding. The design, the basis-point allocation, and the staleness bound are in Feature flags.

  • ref defaults to the remote's HEAD branch. On an empty repository HEAD is an unborn symref (refs/heads/main on Artifacts and on git init -b main). GET /v1/commit reports that as empty: true and names the symref. POST /v1/edit with no ref creates the root commit on that branch. Merge, rebase, cherry-pick, revert, and branch-from cannot use an unborn HEAD: the response is 400 naming the missing field (ref, onto, or from). Naming that unborn ref explicitly is 404 ref refs/heads/main is unborn; create a commit before ….
  • On reads, short names resolve the way git rev-parse does: tags win over branches, and a 40-hex commit oid is also accepted. An abbreviated oid (7–39 hex) resolves only when it matches one advertised ref (a branch tip, a tag tip, or a peeled tag commit); otherwise the response is 400 bad_request asking for the full oid. On writes, short names mean refs/heads/<name>. A 40-hex string is a commit id, never a branch of that name. The zero oid is 400; omit the field to mean "no parent" or "HEAD".
  • author and committer are {name, email, tz?, time?}. tz is +HHMM or -HHMM in the civil range −12:00 through +14:00 (ply's validateIdent; a bad zone is 400 bad_request). time is unix seconds. Omitted tz is +0000. Omitted time is now. Merge and rebase write each stamp with its own time and zone.
  • One edit is {path, find, replace}. An empty or omitted find creates the file (content, or replace, or empty). delete: true deletes it. to renames it. mode is 100644 (default), 100755, or 120000. Several changes go in changes: [{op, path, content?, find?, replace?, to?, mode?}] with op of create, write, edit, delete, or rename, applied in order. Pass changes or a single path, not both. A distinct committer is written on the commit. One find/replace of an existing file still streams through ply.
  • base omitted on a missing ref is a root commit (no parent), pushed with compare-and-swap old oid all zeros. base as another branch, or as a 40-hex commit, starts a new ref whose parent is that commit. base of zeros is 400 and nothing is fetched. On an existing branch, omit base to commit on the tip.
  • Every /v1 response is cache-control: no-store (a credentialed API: nothing it answers is stored, not even a tree/read/commit at a full oid). Every response carries x-ply-version (the Workers version id, which the canary checks) and x-ply-build (ply=<commit> ply-web=<commit>, injected at build time). x-ply-trace is omitted when it would be empty.
  • head on edit is a precondition: if the branch is not at head, the response is 409 cas_conflict and nothing is pushed. head of zeros means the ref must not exist yet. hint is ply's soft head hint for a one-file edit.
  • Every write shares {outcome, ref, oid, oldOid, noop}. newCommit and oldCommit are deprecated aliases of oid and oldOid. onto is a deprecated alias of the commit the write was based on. noop is true for noop, empty, and up_to_date.

Empty repository, in order

This is the whole lifecycle against a brand-new repository. Nothing is seeded with stock git. Replay it against Artifacts after deploy (Git-Token is the Artifacts bearer). Pass oids from responses into later requests.

  1. GET /v1/commit?remote= → 200 {empty:true, ref:"refs/heads/main", oid:null, tree:null, parents:[], author:null, committer:null, message:null, signed:false}. GET /v1/commit?remote=&ref=main is the same body. GET /v1/commit?remote=&ref=nope is 404.
  2. POST /v1/edit {remote, message, author:{name, email, tz, time}, changes:[{op:"create", path, content, mode?}, …]} → 200 {outcome:"commit", ref:"refs/heads/main", oid, oldOid:null, newCommit, oldCommit:null, noop:false, tree}. The ref is created with compare-and-swap old oid 000…0 and the commit has no parent. A 40-hex base is that parent commit. 000…0 is 400.
  3. POST /v1/edit {remote, message, author, committer:{name, email, tz, time}, changes:[{op:"edit", path, find, replace}, {op:"create", …}, {op:"delete", path}, {op:"rename", path, to}]}.
  4. POST /v1/branch {remote, ref, from} → 201 {outcome:"created", ref, oid}. from is a branch or a 40-hex commit. Omit from only when HEAD is born. 000…0 is 400 and nothing is pushed. An existing ref is 409 {code:"ref_exists", retry:"no", oid}.
  5. DELETE /v1/branch {remote, ref, oid} — a stale oid is 409 {code:"stale_expected", retry:"fresh", expected, actual, oid:actual}.
  6. POST /v1/tag {remote, name, target, annotated?, message?, tagger?} and DELETE /v1/tag {remote, name, oid?}.
  7. POST /v1/merge {remote, ref?, from, author, message?}.
  8. POST /v1/rebase {remote, ref, onto?, committer, squash?, message?}.
  9. POST /v1/cherry-pick {remote, ref?, commit, committer, message?, allowEmpty?} — a patch already applied, when both sides added and deleted the same paths, is 200 {outcome:"empty", noop:true, oid:<tip>}. allowEmpty:true writes an empty commit (same tree, new commit). A target branch that also has its own adds or deletes is 409 merge_conflict: ply will not guess which rename git would pair. allowEmpty does not apply to that 409.
  10. POST /v1/revert {remote, ref?, commit, committer, message?, allowEmpty?}.

An empty repository's HEAD is an unborn symref only when the server advertises ls-refs=unborn (git's default, and git's own client sends the argument only then). The first HEAD read against an origin in an isolate pays one info/refs GET so ply can see that bit (git.upload-pack discover in the trace, phase ls-refs in x-artifacts-ray and Server-Timing). The bit is remembered for the isolate and passed back to ply, so later HEAD reads on that origin are the ls-refs alone. A server configured lsrefs.unborn=allow or ignore is reported as an absent HEAD, matching git ls-remote.

GET / prints the same sequence.

  • JSON request bodies are capped at 1 MiB (413 above that). WRITES (a text binding in cloudflare.config.ts) must be on for the POST/DELETE endpoints; otherwise they return 501 unsupported.

Errors

Every failure is JSON {code, message, retry}. code comes from ply's error table (src/errors.ts), and retry is that table's policy: yes, fresh (re-read, then retry), no, or read (the push may have landed; read the ref back first). Merge conflicts add conflicts and reasons. match_count adds matches. auth adds upstreamStatus. cas_conflict adds expected and actual when known (null means the ref was to be, or is, absent). push_partial adds landed and rejected. The table below covers every ply code (src/status.ts is type-checked exhaustive against ply's CODES).

codeHTTPwhy this status
bad_request400input, including a refused remote
auth401 or 403, the upstream's own statusthe caller needs to know whether its credential was missing or not good enough
not_found404ref, path or repo
cas_conflict409the branch moved, so re-read and retry (retry: fresh). git 2.50 and later say incorrect old value provided; ply classifies that string as cas_conflict
ref_exists409creating a branch or tag that already exists (retry: no). The body includes oid, the current target. Checked before the push, so a lost race that Artifacts reports as stale ref is mapped here too
stale_expected409deleting a ref whose oid is not the current target (retry: fresh). The body includes expected, actual, and oid (the actual)
merge_conflict, not_fast_forward, push_rejected, push_partial409conflict with the repository's current state
match_count, lfs_pointer, not_linear, unrelated_histories422the request is well-formed but cannot apply to this content. Retrying it unchanged cannot work, even against a fresh state. That is the difference from 409
limit_exceeded413
rate_limited429
upstream_5xx, network, protocol, pack_corrupt, not_git, remote_error, http, ambiguous502the upstream misbehaved. Check retry before retrying: ambiguous is read
timeout504
aborted499the caller went away
unsupported501including writes when they are disabled
read_only403a write whose remote is in the public namespace, with or without a bearer or git credential
internal500a bug; an error without a known code is reported as this

Tracing

  • ?trace=1 on a JSON endpoint adds trace: [{name, ms, status, attrs, events}] with ply's spans: the spans ply's Tracer hands its onEnd (the plain-value form of the OTLP spans ply emits anywhere; no OTLP is built for a request).

  • /v1/read streams raw bytes and has no JSON to carry spans. Instead, ?trace=1 adds an x-ply-trace header summarising every span that finished before the first byte, as name;dur=ms, …. The blob's own span finishes after the response is sent, so it shows up only in the request's log line (stream: ok|error).

  • Every request writes one structured log line (msg: "ply.request") with id, method, path, upstream host (never the path or the credential), status, ms, round trips, how many fetches used the blob:none fallback, and pack-cache hits. Workers Observability logs and traces are enabled, and redact_query_string keeps remote= out of the platform's request records. Each response carries x-ply-request-id.

  • Every /v1 response that talked to the remote, including 4xx and 5xx, carries x-artifacts-ray and Server-Timing. The ray header is the upstream cf-ray of each git HTTP exchange, in start order:

    ray-header = entry *( ", " entry ) [ ", " overflow ]
    entry      = phase "=" ray ";dur=" duration
    overflow   = "overflow=" 1*DIGIT
    phase      = "ls-refs" / "fetch" / "receive-pack"
    ray        = cf-ray / "-" / "no-response"
    cf-ray     = 16HEX "-" 3ALPHA
    duration   = 1*DIGIT

    ls-refs is info/refs and v2 ls-refs. fetch is each upload-pack fetch, including a blob:none retry. receive-pack is the advertisement and the push. - is a response with no ray id (the raw header is not echoed). no-response is a call that failed before headers. Past 32 entries the rest are overflow=<count>. Server-Timing repeats the same phases and durations, then total for the Worker. The matching spans gain git.upstream.cf_ray, git.upstream.phase, and git.upstream.dur_ms. The viewer sends the same header. It contains no URL, credential, or repository name.

Servers that refuse filter tree:0

Cloudflare Artifacts refuses filter tree:0. ply learns this from the 400 and falls back to blob:none, which brings more trees per fetch (see ply's README). The Worker keeps what it learned per origin for the life of the isolate, so only the first request on an isolate pays for the 400.

Public viewer (/view)

GET /view is a server-rendered browser for a public smart-HTTP repository. It does not use PLY_TOKEN and it never reads Authorization, Git-Token, Git-Authorization, or Cookie. A URL with userinfo is rejected, not turned into a credential. /v1 is unchanged: same gate, same credential headers. /v1 and the viewer share one isolate-wide, per-origin quirks map (src/quirks.ts): a server that rejects filter tree:0 costs that 400 and the blob:none retry once per isolate, and later pages ask for blob:none directly (the waterfall says which). Until 2026-10-31 the viewer re-learned it on every page; on Artifacts that 400 was ~110–150 ms of every page.

The home form accepts an https URL, github.com/owner/repo, owner/repo (github.com), or git@host:path (the ssh user is dropped, then the allowlist runs). Shareable URLs: /view/<host>/<repo path>?ref=&path= (path may use / or %2F). A path segment of . or .., a backslash, or an encoded slash, backslash, or dot in the URL path (and an encoded dot or backslash in ?path=) is rejected on the raw URL, before the URL parser collapses it. ?raw=1 returns the file as text/plain or application/octet-stream (never text/html). ?want=<oid>&filter=tree:0|blob:none&offset= is the pack map. The viewer is ply's showcase, so every page shows the git work behind it. Under the title of a tree or file page, the ply strip sums it up (git calls, wall time, bytes, how many came from Workers Cache, protocol version) with every call drawn on one timeline, and links to #diagnostics. Every HTML page ends with the Diagnostics section, open by default (it was collapsed until 2026-11-06; ?trace=1 still forces it open): the raw remote, a waterfall of the git round trips that produced the page on one shared timeline (call, filter, HTTP status, bytes, cache HIT, duration; tap a row for wants, server agent and pkt-line counters), the protocol the server spoke, pack-map links, and the cf-ray when the platform sends one. The footer links the ply and ply-web commits the deploy was built from. The Workers trace id is not readable inside the isolate. GET / from a browser (Accept containing text/html) is a 302 to /view; curl, fetch and the CD probes (Accept: */*) still get the usage text.

The commit, its first-parent history (Recent commits, 10) and, on a server that refuses tree:0, every tree, come from ONE fetch: want <head> deepen 10 with filter tree:0, or blob:none on Artifacts. Measured on the same graphs on GitHub (2026-10-30): curl tree:0 deepen 10 is 6.1 KB; blob:none deepen 1 is 121.6 KB and deepen 10 is 129.0 KB (+6%). Until 2026-10-30 the log fetched one commit per round trip and stopped after the first on Artifacts.

README and .md files render GitHub-flavoured markdown (tables, task lists, fenced code with a language label, nested lists, quotes, reference and auto links) through src/viewer/markdown.ts: source text is only ever escaped, tags and class names come from fixed sets in safehtml.ts, hrefs pass the scheme allowlist, and repository-relative links resolve to viewer URLs. Images render as links (the CSP is img-src 'none'; a README must not make visitors fetch third-party pixels). The stylesheet is served at a content-hashed URL, /view.<sha1-prefix-12>.css (VIEWER_CSS_PATH), with cache-control: public, max-age=31536000, immutable; HTML is no-store, so a page always links the sheet it was rendered with. /view.css and a previous deploy's hash still answer with the current sheet, no-cache plus an ETag. Icons carry width/height 16 so an unstyled page never draws them large. After every deploy run node scripts/visual-smoke.mjs (headless Chrome over CDP: 375 and 1280 px, light and dark; exits 1 on an SVG wider than 64 px, overflow, an unapplied or unhashed stylesheet, or a tree page without li[data-oid] rows; STALE_CSS=<file> emulates a browser holding an old /view.css). That sheet is Kumo's theme and base plus only the Kumo utilities kumo-classes.ts emits (kumoSubset, 167.9 KB → 67 KB).

Machine-readable markup (stable interface). Styling and layout may change; these attributes do not, and test/viewer.test.ts ("scraping contract") pins them against git ls-tree. Scrapers and monitors should use them, never class names or visible text:

SelectorAttributesMeaning
li[data-oid] (tree page)data-oid full 40-hex oid, data-mode as git ls-tree prints it (100644, 100755, 120000, 040000, 160000), data-type blob/tree/commit, data-nameone row per entry shown; the .. row has none
ul.filesdata-path, data-entries (entries in the tree), data-shown (rows rendered; less than data-entries when capped)the listing
[data-commit]full 40-hex oidthe commit the page shows

Example: curl -s 'https://ply.ivar.workers.dev/view/github.com/ivarvong/ply?path=src' | grep -oE '<li data-oid="[0-9a-f]{40}"' | wc -l matches gh api repos/ivarvong/ply/git/trees/main:src --jq '.tree | length'.

Allowlist. An unauthenticated Worker that will fetch a caller-supplied URL is an SSRF proxy, so the viewer accepts https URLs whose hostname is an exact, case-insensitive match for github.com, gitlab.com, codeberg.org, bitbucket.org, or git.sr.ht. No suffix, no wildcard, no userinfo, default port only. A trailing dot (github.com.) does not match. Lookalikes (github.com.evil.com, evilgithub.com, punycode) do not match. Everything else is rejected before a fetch, and the error lists the supported hosts. VIEWER_EXTRA_HOSTS appends exact hostnames (comma-separated). A token with a scheme, port, userinfo, wildcard, or trailing dot is skipped, not treated as a suffix. Cloudflare Artifacts is off unless that variable names the exact public git host. ALLOW_REMOTE_ORIGINS is a /v1 test hook and does not apply to /view. Redirects follow git's http.followRedirects=initial: ply follows only the first GET info/refs and rebases the repo there, after viewerAllowUrl checks the new base is still that repo's info/refs / git-upload-pack path (plus a .git suffix) on the same host; a 3xx on a POST is an error. createViewerFetch checks every request the same way and never follows a 3xx itself. A redirect whose raw Location contains ., .., %2e, %2f, or %5c, or names any other host, is refused there before ply sees it. Upstream User-Agent is ply-viewer/0.1.0.

Caps (not raised by environment; rate limits can be lowered and are clamped to 1…1000):

CapValue
upstream bytes / page4 MiB
pack bytes mapped2 MiB
pack objects mapped400
inflated bytes / pack4 MiB
one object1 MiB
file shown or returned raw256 KiB
delta chain32
delta result1 MiB
upstream calls / page16
redirects (first info/refs only)2
per-call timeout12 s
page timeout20 s
refs retained2000 (200 branches shown)
tree entries retained / shown2000 / 500
parent commits shown5
page rate60 / minute / client
pack-map rate20 / minute / client

Over any cap the response is an HTML error (413 for a limit, 504 for a timeout), with the trace of the calls that did finish. Rate limiting is keyed by the SHA-256 of CF-Connecting-IP (clients with no header share one key) and stores no addresses. RATE_MODE picks the limiter. batched (the default since 2026-11-06, docs/rate-limit.md): the request reads ONE cached document of blocked clients through the cache-enabled RateCache entrypoint (max-age=1, stale-while-revalidate=30) and never waits on a Durable Object; admitted hits are batched per isolate and flushed every 200 ms from ctx.waitUntil to the single SQLite Durable Object RateCounter with an idempotency key, retried with the same key for up to 5 s. The limit is approximate: a client is refused about 1.5 s after it reaches it. legacy: ViewerRateLimit, one SQLite Durable Object per client called before any git work, storing a short list of timestamps per bucket. Git reads are cached with Workers Caching (see Caching); there is no Cache API anything. HTML is no-store and escaped. CSP is default-src 'none'; style-src 'self'; script-src 'none'; img-src 'none', plus X-Content-Type-Options: nosniff. There is no inline script and unsafe-inline is not allowed.

cloudflare.config.ts declares ViewerRateLimit as a live SQLite class in worker.exports. The namespace already exists (created by migration tag v1-viewer-rate, namespace id 656fdd50f0d6428393eb2d9250ceee67). Declaring it keeps that namespace and its data.

Public namespace (public-v0)

One Cloudflare Artifacts namespace is served publicly and read-only. Its name is one constant, PUBLIC_NAMESPACE in src/public-namespace.ts; cloudflare.config.ts binds that namespace and src/public.ts matches URLs under it, so moving to public-v1 is a one-line change (plus creating the namespace and publishing into it).

  • URLs. GET /r and GET /r/ are the styled index of the namespace. GET /r/<repo> is the canonical viewer page for that repo (ref is the only ref parameter; at and commit redirect to it). A name that is not in the namespace is a styled 404 and is not redirected. The long /view/5ad2236b39de4c8bd8f6270ea63f3ea9.artifacts.cloudflare.net/git/public-v0/<repo>.git form redirects to /r/<repo>. The home page (/view) also lists the namespace (binding list(), cached a minute per isolate). The viewer accepts that Artifacts host without VIEWER_EXTRA_HOSTS, but only for one repo directly under /git/public-v0/; any other path on the host (another namespace, a nested path, .. or an encoded separator) is a 400 before any fetch.
  • /v1 reads. refs, discover, tree, read, and commit need no bearer when the request has no Authorization header at all and remote is exactly https://<that host>/git/public-v0/<repo>(.git). These requests share the viewer's per-client page bucket (60/min, ViewerRateLimit). A caller git credential on such a request is a 400 (send none, or use the bearer). A wrong bearer is still a 401. With a valid bearer nothing changes from the rules above: no rate limit, and the public token is used when the caller sends no git credential of their own. Rationale: the content is public by construction, the remote can only be one of our own repos, the Worker holds only a read credential for it, and the rate limit bounds cost. Every other /v1 request still needs the bearer.
  • Writes. Every write endpoint whose remote is anywhere under /git/public-v0/ on that host (compared case-insensitively, any depth) returns 403 read_only. That holds with a valid bearer and with a caller's own write credential, and nothing is sent upstream. Without a bearer a write is the usual 401.
  • Credential. No stored secret. The Worker has an Artifacts binding PUBLIC_REPOS scoped to public-v0 and calls only get(<repo>).createToken("read", 3600) and list(). Artifacts tokens are per repo; there is no namespace-wide or non-expiring read token (TTL 60 s … 1 year, default 24 h). Tokens are cached per isolate per repo and re-minted with less than 5 minutes left, so rotation is automatic and an isolate holds at most one live token per repo (plus retired ones, kept only so the scrubber still removes them). A read token is refused by git-receive-pack (403, checked 2026-10-30).
  • Where the token goes. withPublicReadCredential (src/public.ts) is the innermost fetch, below createGuardedFetch and createViewerFetch, so it runs on every request, including each hop ply follows. It adds Authorization: Bearer <token> only when the raw URL's origin is exactly https://<that host> (no :443, no uppercase, no trailing dot, no userinfo), the raw path is exactly /git/public-v0/<repo>(.git)/info/refs with query ?service=git-upload-pack and method GET, or …/git-upload-pack with no query and method POST, and the path has no ./.. segment, %, backslash or control character. receive-pack never matches. When the request already carries an Authorization (a caller's Git-Token or Git-Authorization), the caller's credential is used and the Worker's token is not added. The pack cache sits above the guard, so its key has no Authorization and survives rotation.
  • Scrubbing. Every minted token (full, without ?expires=, Basic-encoded, URL-encoded) is scrubbed from every /v1 JSON body, every viewer HTML/text body and header, and every log line. Blob bodies are not rewritten: they are git objects whose hash ply checked. test/public-worker.test.js greps every response and the workerd log for each form, including against a host that echoes the header back.
  • Revocation. Tokens expire within an hour. To cut every Worker token off at once, revoke them per repo (cf artifacts namespaces repos tokens list --namespace public-v0 --name <repo> and cf artifacts namespaces tokens revoke <id> --namespace public-v0 --force); the Worker mints new ones on the next request. To take the namespace offline, remove the binding and deploy.

Mirrors that follow GitHub

public-v0/ply and public-v0/ply-web follow their GitHub main (src/mirror.ts MIRRORS). A Worker cron (* * * * *) compares the two refs; when they differ it fetches only the new objects from GitHub (want <github tip>, have <mirror tip>, anonymous) and pushes them to the mirror as a CAS update from the mirror's tip (a rewritten upstream is followed). The write token is minted through the namespace-scoped binding for that one repo with the minimum TTL (60 s) and revoked as soon as the push returns. No token lives in CI or in the repo. One log line per mirror per minute: {"msg":"ply.mirror", repo, outcome: in-sync|updated|error, from, to, objects, pushBytes, ms}. MIRROR_SYNC="off" stops it. An update over 32 MiB is refused (logged); publish that with the script below.

Publish a repo

sh
env -u CLOUDFLARE_API_TOKEN node scripts/publish.mjs <repo> <source> [--branch main] [--tags]
# e.g. the ply mirror:
env -u CLOUDFLARE_API_TOKEN node scripts/publish.mjs ply https://github.com/ivarvong/ply.git

The script uses your cf login (OAuth). It creates public-v0/<repo> if missing (and revokes the 24 h write token that creation returns), clones the one branch bare, mints a write token for that repo only, with a 10-minute TTL, and force-pushes the branch (and tags with --tags) with stock git. The token reaches git only through GIT_CONFIG_* environment variables, never argv, a file, or stdout. The script revokes it afterwards. The Worker never holds a write token. Re-run the same command to update a mirror. Artifacts limits apply (64 MiB per push, 1 GB per repo).

Caching (Workers Cache)

Workers Caching only, never the Cache API (caches.default): test/gitcache.test.ts fails on any caches. in src/.

eyeball ─▶ default entrypoint (cache OFF: always runs → rate limit, ply.request log, scrub, traces)
             └─ ply ─▶ request guard (createGuardedFetch / createViewerFetch: every request re-validated, no 3xx followed)
                        └─ createLoopbackFetch (src/gitcache.ts)
                             ├─ public + no Authorization + pure function of its request ─▶ ctx.exports.GitCache (cache ON) ─▶ upstream
                             └─ anything else (every caller credential, haves, other hosts) ─────────────────────────▶ upstream
  • What may be cached: an upload-pack exchange with no Authorization header whose URL is exactly a public-v0 repo endpoint, or an upload-pack endpoint on a built-in viewer forge (github.com, gitlab.com, codeberg.org, bitbucket.org, git.sr.ht). A caller's Git-Token / Git-Authorization becomes an Authorization header, so a credentialed read always goes straight upstream and can never populate a key. GitCache re-checks the same rule, and attaches the public-v0 read token itself.

  • Policy (Cache-Control from GitCache):

    kindexchangeCache-Control
    packcommand=fetch with wants only (no have / shallow / want-ref / deepen-since / deepen-not)public, max-age=31536000, immutable: objects are named by their hash
    refscommand=ls-refspublic, max-age=5, stale-while-revalidate=10: a ref change shows within 15 s
    discoverGET info/refs?service=git-upload-packv2 capability list: public, max-age=300, stale-while-revalidate=3600; a v0 advertisement (carries refs): the refs policy
    packa 400 whose text is a partial-clone filter refusal (Artifacts: only blob:none is supported)public, max-age=3600: a fact about the server; uncached, every fresh isolate paid it (11 of 13 GitCache runs in a 20-request cold burst, e021776d)
    —any other non-200, any 3xxno-store (3xx goes back to the guard; GitCache never follows)
  • Keys: /v<CACHE_VERSION>/<kind>/<sha256(kind, url, git-protocol, body)>. The upstream request travels in headers (not part of a Workers Cache key); GitCache recomputes the hash and refuses a mismatch, so no request can store an answer under another's key. crossVersionCache is on (deploys keep packs warm); CACHE_VERSION (src/cache-version.ts) is the only partition: bump it when what GitCache stores changes.

  • Poison: ply re-verifies every object; after a corrupt cached pack it retries with x-ply-cache: bust, which purges that key (ctx.cache.purge({ pathPrefixes }) inside GitCache) before refetching.

  • Observability: the tier (cf-cache-status: HIT, MISS, EXPIRED, …) reaches ply as x-ply-pack-cache, so every span carries git.response.cache, the viewer waterfall shows it, and ply.request logs count cache_hits. A HIT never runs GitCache, so it leaves no GitCache invocation.

  • Whole responses pinned to a commit (src/pinned.ts, cache-enabled Pinned entrypoint): viewer raw files (?raw=1&ref|at=<40-hex>&path=) on /view/… or /r/<repo>, for public-v0 or a built-in forge. The front door rate-limits and logs, then fetches the canonical key /v<CACHE_VERSION>/pinned<path>?<allowed params, sorted> from Pinned. Pinned rebuilds the request from the key alone (it reads no header, so no credential can reach it), runs the same handler, and answers immutable on a 200, no-store otherwise. Responses carry x-ply-pinned-cache (the tier). HTML pages are not cached whole: they render times relative to the request and carry that request's waterfall, cf-ray and id. Their git parts are cached.

  • PACK_CACHE=off sends everything direct.

Develop / deploy

sh
npm test                                 # /v1 + public-namespace workerd suites, then the viewer/security/public unit suites
npm run dev                              # cf dev: Vite + the Cloudflare plugin on local workerd
npm run typecheck                        # tsc for the app, then cf workers types + tsc for cloudflare.config.ts
npm run worker:deploy:dry-run            # cf deploy --dry-run: build and validate, no credentials, no upload
npm run cd                               # operator deploy: bump, 0% canary, smoke, telemetry, ramp (docs/continuous-deployment.md)
npm run cd -- smoke --version <id>       # pinned lifecycle smoke against that Workers version
npm run worker:deploy                    # refuses unless PLY_FORCE_FULL_DEPLOY=1; then cf deploy to 100%

The operator runbook for a gradual ramp (bump, 0% canary, pinned smoke, telemetry, then the policy's steps through 100%, with a rollback at any bad step) is docs/continuous-deployment.md. npm run worker:deploy refuses unless PLY_FORCE_FULL_DEPLOY=1. With that set it still goes to 100% in one shot. Do not run it while a ramp is in progress.

npm run cd deploys only when HEAD is origin/main after a fetch. The full run is npm run cd -- cd --sha <40 hex>, and npm run cd -- --sha <40 hex> is the same. A release is that ply sha paired with the ply-web commit of the checkout. Re-running the pair reads the live deployment and continues from the stage that split is in. A version tagged with only the ply sha is not a match, so a ply-web-only change is uploaded. A dirty checkout is refused before a run starts. --no-bump deploys the checkout without moving the pin. --sha with --no-bump is allowed only when that sha is already the pin. npm run cd -- bump commits the pin on a branch whose parent is origin/main. It uses cf only. A canary is a new version at 0% beside the current one at 100%. Pinned smoke sends Cloudflare-Workers-Version-Overrides: ply="<id>" and requires x-ply-version to match. Telemetry reuses the loss allowance in scripts/canary-verdict.mjs. After the 0% gate the ramp sends unpinned traffic, reads which version served each request from Workers telemetry, and puts the old version back at 100% on a breach.

The smoke creates an empty repo in the Artifacts namespace ply-loadgen. Repo create returns a token; that token is revoked before the smoke starts and must then get 403 from Artifacts. The smoke mints a short-lived write token from PLY_TOKEN_FILE (default ~/.ply-token, mode 0600, the same value as the Worker secret PLY_TOKEN) and drives the git lifecycle through /v1. It does not seed the repo with stock git. The minted token is revoked when the run ends and checked the same way. A pass deletes the repo. A fail leaves the repo name in the verdict. Tokens stay out of argv and the run log.

The Worker is built and deployed with the Cloudflare CLI, cf, pinned as a dev dependency. cloudflare.config.ts is the Worker config (name, compatibility date, bindings, Durable Object exports, observability, limits). vite.config.ts holds build settings only: cf build delegates bundling to Vite and the Cloudflare Vite plugin and writes Build Output to .cloudflare/output. The workerd suites in npm test run that same bundle (test/cf-bundle.js). Nothing here needs Docker: the Vite plugin runs docker image ls after every build even with no containers (execFileSync, no timeout, so a hung daemon hung the build), and vite.config.ts sets WRANGLER_DOCKER_BIN=false so that call fails at once and is skipped.

npm run worker:deploy runs cf deploy only when PLY_FORCE_FULL_DEPLOY=1. Otherwise it exits and uploads nothing. When CLOUDFLARE_API_TOKEN is set, cf uses it. When it is unset, cf uses the OAuth session from cf auth login. The command uploads the Worker named ply: text bindings WRITES and PACK_CACHE, the ViewerRateLimit Durable Object, observability, limits.cpuMs, and workersDev. Worker secrets survive a deploy (the upload sends keep_bindings: ["secret_text", "secret_key"]). PLY_TOKEN stays a secret. Set or rotate it with cf workers secrets update PLY_TOKEN --worker ply --type secret_text. cf prompts for the value, so it never lands in shell history.

cf has no live log stream yet (no equivalent of tail). Use the dashboard's live logs, or Workers Logs, which this Worker sends through observability.logs.

GitHub Actions

GitHub does not bump the ply pin and does not deploy. An operator moves the pin with npm run cd -- bump and ships from the runbook above.

Cloudflare token

cloudflare.config.ts has no accountId. The operator's cf auth login is what uploads. In a non-interactive cf process, cf takes the account from CLOUDFLARE_ACCOUNT_ID. Without it, a token that can see more than one account stops before upload. GitHub Actions does not upload this Worker.

NameWhereWhat it is
CLOUDFLARE_API_TOKENoperator environment, optionalAccount → Workers Scripts: Edit. OAuth from cf auth login is the usual login.
CLOUDFLARE_ACCOUNT_IDoperator environment, when the token can see more than one accountAccount id of the account that owns the ply Worker

Workers Scripts Edit is the user-token permission name. An account-owned token lists the same grant as Workers Scripts Write. The script upload API and GET /accounts/:account_id/workers/subdomain (cf calls that because workersDev is true, and ply.ivar.workers.dev already exists) both accept it. Scope the token to this account. The Worker already exists, so the deploy is an update: Editor on the ply Worker is enough for a per-Worker token. Creating the Worker the first time would need Admin at the Workers product scope.

Nothing else in this config asks for a permission:

  • No routes and no custom domains, so no Zone → Workers Routes → Edit.
  • No KV, R2, D1, Queues, or Secrets Store bindings.
  • The Artifacts binding PUBLIC_REPOS (namespace public-v0). The OAuth deploy of 2026-10-30 uploaded it; whether a scoped CI token needs an Artifacts permission on top of Workers Scripts Edit has not been checked.
  • Durable Objects have no token permission of their own. ViewerRateLimit follows the Worker.
  • Observability, limits.cpuMs, the Worker cache settings (cache, per-entrypoint exports), and the WRITES / PACK_CACHE text bindings travel in the script upload.
  • Workers Tail Read is the permission for live log streaming, which this deploy does not use.

Companion workflow in ivarvong/ply

ply's main should wake ply-web on every push, so the pin updates without waiting for the cron. Add this file as .github/workflows/notify-ply-web.yml in ivarvong/ply. On push to ply main it POSTs repository_dispatch (event_type: ply-main-updated, client_payload.sha set to that commit) to ivarvong/ply-web. When the secret is missing it prints a notice and exits successfully. ply-web resolves ply main itself when it wakes up; the payload sha is the commit that was pushed.

yaml
name: Notify ply-web

on:
  push:
    branches: [main]

permissions:
  contents: read

jobs:
  dispatch:
    runs-on: ubuntu-24.04
    steps:
      - name: Dispatch ply-main-updated
        env:
          PLY_WEB_DISPATCH_TOKEN: ${{ secrets.PLY_WEB_DISPATCH_TOKEN }}
        run: |
          set -euo pipefail
          if [ -z "${PLY_WEB_DISPATCH_TOKEN}" ]; then
            echo "::notice title=ply-web not notified::PLY_WEB_DISPATCH_TOKEN is not set. Add a fine-grained PAT with Contents: Read and write on ivarvong/ply-web. This push did not send repository_dispatch."
            exit 0
          fi
          # GITHUB_SHA is the commit just pushed. ply-web resolves main itself.
          GH_TOKEN="${PLY_WEB_DISPATCH_TOKEN}" gh api --method POST repos/ivarvong/ply-web/dispatches --input - <<EOF
          {"event_type":"ply-main-updated","client_payload":{"sha":"${GITHUB_SHA}"}}
          EOF

Secret, on ivarvong/ply (the sender, not ply-web): PLY_WEB_DISPATCH_TOKEN. A fine-grained personal access token restricted to the ivarvong/ply-web repository, with Contents: Read and write. That is the permission GitHub requires for repository_dispatch.

1# ply Worker — `https://ply.ivar.workers.dev`
3A Cloudflare Worker that exposes [ply](https://github.com/ivarvong/ply) as an HTTP API against any smart-HTTP git host. The git client is `github:ivarvong/ply#af5cac0372df6caf774d108cbf9229b04af45eb6` (an exact commit of ply `main`; an operator moves the pin with `npm run cd -- bump`). The `/v1` git API has no
4storage. `GET /view` is a public repository viewer, rate-limited by client through a SQLite Durable Object. One Artifacts
5namespace, `public-v0`, is served read-only with no token (`/r/<repo>`, see [Public namespace](#public-namespace-public-v0)).
6Feature flags are one R2 object and a service binding ([Feature flags](docs/feature-flags.md)). `GET /` prints the usage text.
8## Auth
10- **Gate**: `Authorization: Bearer <PLY_TOKEN>` on `/v1`. `GET /`, `GET /view`, `GET /view.css`, `GET /r/<repo>`, and the
11 `/v1` reads of the [public namespace](#public-namespace-public-v0) are public. The token is a Worker secret
12 (`cf workers secrets update PLY_TOKEN --worker ply --type secret_text`) and is compared in constant time (SHA-256 of both sides,
13 then `crypto.subtle.timingSafeEqual`). A missing or wrong token returns 401 `{code: "unauthorized"}`.
14- **Git credential** (optional; public repos need none):
15 - `Git-Authorization: <value>` is sent upstream verbatim as `Authorization`.
16 - `Git-Token: <token>` is mapped by host: `github.com` → `Basic x-access-token:<token>`, `gitlab.*` → `Basic
17 oauth2:<token>`, anything else (Cloudflare Artifacts included) → `Bearer <token>`. Artifacts accepts Bearer and
18 Basic; both were checked in the smoke run.
19 - Sending both headers is a 400.
20 - Neither credential appears in a response, trace, error message or log line. ply never records them, and the
21 Worker scrubs every outgoing string as a second layer (`test/worker.test.js` greps all of these, including a
22 hostile upstream that echoes the header back).
23- **Remote rules**: `remote` must be `https:`, on the default port, with no userinfo, query, or fragment. The host is
24 canonicalised (lowercase, no trailing dot — `github.com.` is rejected rather than stripped). IP literals are refused
25 in every encoding the URL parser accepts (dotted, zero-padded, octal, hex, decimal `2130706433`, IPv6, IPv4-mapped,
26 IPv4-compatible). So are single-label hosts, `localhost`/`.local`/`.internal`/`.lan`/`.home.arpa`/… names, and
27 wildcard-DNS names (`nip.io`, `sslip.io`, `localtest.me`, and the same shape of zone). A path segment of `.` or `..`,
28 or an encoded slash, backslash, or dot (`%2f`, `%5c`, `%2e`), is rejected before normalisation. Redirects follow
29 git's `http.followRedirects=initial`: ply follows a 3xx only on the first `GET info/refs` (at most three hops, and only
30 when the `Location` keeps the `/info/refs?service=…` suffix), and every later request, POSTs included, goes to the
31 rewritten base. ply's `allowUrl` hook (`remoteAllowUrl`, `src/remote.ts`) vets each new base with the same check, on
32 the same origin. A 3xx on a POST, a loop past three hops, or a `Location` git would not rebase to is a 400 with
33 code `http` naming the target (git cannot use such a remote either). The Worker's fetch wrapper (`createGuardedFetch`)
34 re-checks every request and never follows a 3xx itself; a 3xx whose `Location` is on another origin or fails the
35 check is a 400 `bad_request` before ply sees it, so a credential never leaves the origin (`test/worker.test.js`,
36 "redirects").
37 `ALLOW_REMOTE_ORIGINS` (comma-separated origins) exempts those origins from the public-host rules (http, an IP, a
38 non-default port). Only the tests use it.
40## Endpoints
42| Method | Path | Input | Output |
43|---|---|---|---|
44| GET | `/v1/refs` | `remote`, `prefix?` | `{refs: {name: oid}, head, peeled: {tag: commit}}`. An empty repository adds `{empty:true, unborn:"refs/heads/main"}` and leaves `head` null |
45| GET | `/v1/discover` | `remote` | protocol v2 capabilities (`agent`, `fetch`, `filter`, `caps`, …) |
46| GET | `/v1/read` | `remote`, `ref?`, `path` | the blob, streamed. Headers: `content-length`, `x-ply-ref`, `x-ply-commit`, `x-ply-blob`, `x-ply-mode`, `x-ply-size`. A directory is `400` `bad_request` (list it with `GET /v1/tree`), not `404` |
47| GET | `/v1/tree` | `remote`, `ref?`, `path?` | `{ref, commit, tree, entries: [{name, mode, oid, type}]}` (modes as `git ls-tree` prints them) |
48| GET | `/v1/commit` | `remote`, `ref?` | born: `{ref, oid, tree, parents, author, committer, message, signed}`. `author`/`committer` are `{name, email, time, epoch, tz}` (`time` ISO-8601 UTC, `epoch` the raw seconds, `tz` as written, e.g. `+0530`). `message` is the raw body. `signed` means a `gpgsig` header is present (not verified). Fetches the commit only (`tree:0`, deepen 1; `blob:none` when the server refuses that). Empty repository (unborn HEAD, or that same branch by name): `{empty:true, ref:"refs/heads/main", oid:null, tree:null, parents:[], author:null, committer:null, message:null, signed:false}`. A different missing ref stays 404. A born response does not grow an `empty` field |
49| POST | `/v1/edit` | `{remote, ref?, base?, author, committer?, message, head?, changes?}` or the one-file form `{path, find?, replace?, content?, delete?, to?, mode?}` | `{outcome, ref, oid, oldOid, noop, tree, newCommit, oldCommit}`. `newCommit`/`oldCommit` alias `oid`/`oldOid`. A root commit and any newly created ref have `oldOid: null` |
50| POST | `/v1/branch` | `{remote, ref, from?}` | 201 `{outcome:"created", ref, oid, oldOid:null}`. `from` is a branch or a 40-hex commit. Omit `from` only when HEAD is born |
51| DELETE | `/v1/branch` | `{remote, ref, oid?}` | `{outcome:"deleted", ref, deleted}`. CAS on `oid` (default: the oid ls-refs shows now) |
52| POST | `/v1/tag` | `{remote, name, target, annotated?, message?, tagger?}` | 201 `{outcome:"tag", ref, oid, commit, annotated}`. Lightweight unless `annotated`, `message`, or `tagger` is set. `target` is a branch or a commit id |
53| DELETE | `/v1/tag` | `{remote, name, oid?}` | same compare-and-swap as `DELETE /v1/branch` |
54| POST | `/v1/merge` | `{remote, ref?, from, author?, committer?, message?, fastForwardOnly?, noFastForward?}` | `{outcome, ref, oid, oldOid, noop, …}` where outcome is `merge`, `fast_forward`, or `up_to_date`. `from` is a branch or a 40-hex commit. `author` and `committer` are separate stamps, each with its own `time` and `tz` |
55| POST | `/v1/rebase` | `{remote, ref, onto?, committer, author?, squash?, message?}` | `{outcome, ref, oid, oldOid, …}` where outcome is `rebase`, `squash`, `fast_forward`, or `up_to_date`. `onto` is a branch or a 40-hex commit. `author.time` and `committer.time` are independent |
56| POST | `/v1/cherry-pick`, `/v1/revert` | `{remote, ref?, commit, committer, message?, allowEmpty?}` | `{outcome, ref, oid, oldOid, noop, tree?}`. A patch already applied, and only when both sides added and deleted the same paths, is `{outcome:"empty", noop:true, oid:<tip>}`. `allowEmpty:true` writes that empty commit. If the target also has its own adds or deletes, the response is 409 `merge_conflict` (`allowEmpty` does not override it) |
57| GET | `/v1/flags` | | the cached flag ruleset `{revision, cache, environment, flags}`. Writes are not this route |
58| POST | `/v1/flags/eval` | `{unit, attributes?, keys?}` | `{revision, cache, flags:[{key, variant, reason, bucket}]}`. Per-unit; the response is `no-store` |
60Flag writes are not HTTP (`PUT`/`POST`/`PATCH`/`DELETE` `/v1/flags` are 405). Operators call `scripts/flags`, which talks to the `ply-flag-operator` Worker. That Worker checks `FLAG_OPERATOR_TOKEN` and calls `FlagControl` (`setRollout`, `setTargeting`, `getConfig`) over a service binding. The design, the basis-point allocation, and the staleness bound are in [Feature flags](docs/feature-flags.md).
62- `ref` defaults to the remote's HEAD branch. On an empty repository HEAD is an unborn symref (`refs/heads/main` on
63 Artifacts and on `git init -b main`). `GET /v1/commit` reports that as `empty: true` and names the symref.
64 `POST /v1/edit` with no `ref` creates the root commit on that branch. Merge, rebase, cherry-pick, revert, and
65 branch-from cannot use an unborn HEAD: the response is 400 naming the missing field (`ref`, `onto`, or `from`).
66 Naming that unborn ref explicitly is 404 `ref refs/heads/main is unborn; create a commit before …`.
67- On reads, short names resolve the way `git rev-parse` does: tags win over branches, and a 40-hex commit oid is also
68 accepted. An abbreviated oid (7–39 hex) resolves only when it matches one advertised ref (a branch tip, a tag tip, or
69 a peeled tag commit); otherwise the response is `400` `bad_request` asking for the full oid. On writes, short names
70 mean `refs/heads/<name>`. A 40-hex string is a commit id, never a branch of that
71 name. The zero oid is 400; omit the field to mean "no parent" or "HEAD".
72- `author` and `committer` are `{name, email, tz?, time?}`. `tz` is `+HHMM` or `-HHMM` in the civil range −12:00
73 through +14:00 (ply's `validateIdent`; a bad zone is 400 `bad_request`). `time` is unix seconds. Omitted `tz` is
74 `+0000`. Omitted `time` is now. Merge and rebase write each stamp with its own time and zone.
75- One edit is `{path, find, replace}`. An empty or omitted `find` creates the file (`content`, or `replace`, or
76 empty). `delete: true` deletes it. `to` renames it. `mode` is `100644` (default), `100755`, or `120000`.
77 Several changes go in `changes: [{op, path, content?, find?, replace?, to?, mode?}]` with `op` of `create`,
78 `write`, `edit`, `delete`, or `rename`, applied in order. Pass `changes` or a single `path`, not both.
79 A distinct `committer` is written on the commit. One find/replace of an existing file still streams through ply.
80- `base` omitted on a missing ref is a root commit (no parent), pushed with compare-and-swap old oid all zeros.
81 `base` as another branch, or as a 40-hex commit, starts a new ref whose parent is that commit. `base` of zeros is
82 400 and nothing is fetched. On an existing branch, omit `base` to commit on the tip.
83- Every `/v1` response is `cache-control: no-store` (a credentialed API: nothing it answers is stored, not even a
84 `tree`/`read`/`commit` at a full oid). Every response carries `x-ply-version` (the Workers version id, which
85 the canary checks) and `x-ply-build` (`ply=<commit> ply-web=<commit>`, injected at build time). `x-ply-trace`
86 is omitted when it would be empty.
87- `head` on edit is a **precondition**: if the branch is not at `head`, the response is 409 `cas_conflict` and nothing
88 is pushed. `head` of zeros means the ref must not exist yet. `hint` is ply's soft head hint for a one-file edit.
89- Every write shares `{outcome, ref, oid, oldOid, noop}`. `newCommit` and `oldCommit` are deprecated aliases of
90 `oid` and `oldOid`. `onto` is a deprecated alias of the commit the write was based on. `noop` is true for
91 `noop`, `empty`, and `up_to_date`.
93### Empty repository, in order
95This is the whole lifecycle against a brand-new repository. Nothing is seeded with stock git. Replay it against
96Artifacts after deploy (`Git-Token` is the Artifacts bearer). Pass oids from responses into later requests.
981. `GET /v1/commit?remote=` → 200 `{empty:true, ref:"refs/heads/main", oid:null, tree:null, parents:[], author:null, committer:null, message:null, signed:false}`.
99 `GET /v1/commit?remote=&ref=main` is the same body. `GET /v1/commit?remote=&ref=nope` is 404.
1002. `POST /v1/edit` `{remote, message, author:{name, email, tz, time}, changes:[{op:"create", path, content, mode?}, …]}`
101 → 200 `{outcome:"commit", ref:"refs/heads/main", oid, oldOid:null, newCommit, oldCommit:null, noop:false, tree}`.
102 The ref is created with compare-and-swap old oid `000…0` and the commit has no parent. A 40-hex `base` is that
103 parent commit. `000…0` is 400.
1043. `POST /v1/edit` `{remote, message, author, committer:{name, email, tz, time}, changes:[{op:"edit", path, find, replace}, {op:"create", …}, {op:"delete", path}, {op:"rename", path, to}]}`.
1054. `POST /v1/branch` `{remote, ref, from}` → 201 `{outcome:"created", ref, oid}`. `from` is a branch or a 40-hex
106 commit. Omit `from` only when HEAD is born. `000…0` is 400 and nothing is pushed. An existing ref is 409
107 `{code:"ref_exists", retry:"no", oid}`.
1085. `DELETE /v1/branch` `{remote, ref, oid}` — a stale oid is 409 `{code:"stale_expected", retry:"fresh", expected, actual, oid:actual}`.
1096. `POST /v1/tag` `{remote, name, target, annotated?, message?, tagger?}` and `DELETE /v1/tag` `{remote, name, oid?}`.
1107. `POST /v1/merge` `{remote, ref?, from, author, message?}`.
1118. `POST /v1/rebase` `{remote, ref, onto?, committer, squash?, message?}`.
1129. `POST /v1/cherry-pick` `{remote, ref?, commit, committer, message?, allowEmpty?}` — a patch already applied, when both
113 sides added and deleted the same paths, is 200 `{outcome:"empty", noop:true, oid:<tip>}`. `allowEmpty:true` writes
114 an empty commit (same tree, new commit). A target branch that also has its own adds or deletes is 409
115 `merge_conflict`: ply will not guess which rename git would pair. `allowEmpty` does not apply to that 409.
11610. `POST /v1/revert` `{remote, ref?, commit, committer, message?, allowEmpty?}`.
118An empty repository's HEAD is an unborn symref only when the server advertises `ls-refs=unborn` (git's default, and
119git's own client sends the argument only then). The first HEAD read against an origin in an isolate pays one
120`info/refs` GET so ply can see that bit (`git.upload-pack discover` in the trace, phase `ls-refs` in `x-artifacts-ray`
121and `Server-Timing`). The bit is remembered for the isolate and passed back to ply, so later HEAD reads on that origin
122are the ls-refs alone. A server configured `lsrefs.unborn=allow` or `ignore` is reported as an absent HEAD, matching
123`git ls-remote`.
125`GET /` prints the same sequence.
126- JSON request bodies are capped at 1 MiB (413 above that). `WRITES` (a text binding in `cloudflare.config.ts`) must be `on` for the
127 POST/DELETE endpoints; otherwise they return 501 `unsupported`.
129## Errors
131Every failure is JSON `{code, message, retry}`. `code` comes from ply's error table (`src/errors.ts`), and `retry` is
132that table's policy: `yes`, `fresh` (re-read, then retry), `no`, or `read` (the push may have landed; read the ref
133back first). Merge conflicts add `conflicts` and `reasons`. `match_count` adds `matches`. `auth` adds
134`upstreamStatus`. `cas_conflict` adds `expected` and `actual` when known (`null` means the ref was to be, or is,
135absent). `push_partial` adds `landed` and `rejected`. The table below covers every ply code (`src/status.ts` is
136type-checked exhaustive against ply's `CODES`).
138| code | HTTP | why this status |
139|---|---|---|
140| `bad_request` | 400 | input, including a refused remote |
141| `auth` | 401 or 403, the upstream's own status | the caller needs to know whether its credential was missing or not good enough |
142| `not_found` | 404 | ref, path or repo |
143| `cas_conflict` | 409 | the branch moved, so re-read and retry (`retry: fresh`). git 2.50 and later say `incorrect old value provided`; ply classifies that string as `cas_conflict` |
144| `ref_exists` | 409 | creating a branch or tag that already exists (`retry: no`). The body includes `oid`, the current target. Checked before the push, so a lost race that Artifacts reports as `stale ref` is mapped here too |
145| `stale_expected` | 409 | deleting a ref whose `oid` is not the current target (`retry: fresh`). The body includes `expected`, `actual`, and `oid` (the actual) |
146| `merge_conflict`, `not_fast_forward`, `push_rejected`, `push_partial` | 409 | conflict with the repository's current state |
147| `match_count`, `lfs_pointer`, `not_linear`, `unrelated_histories` | 422 | the request is well-formed but cannot apply to this content. Retrying it unchanged cannot work, even against a fresh state. That is the difference from 409 |
148| `limit_exceeded` | 413 | |
149| `rate_limited` | 429 | |
150| `upstream_5xx`, `network`, `protocol`, `pack_corrupt`, `not_git`, `remote_error`, `http`, `ambiguous` | 502 | the upstream misbehaved. Check `retry` before retrying: `ambiguous` is `read` |
151| `timeout` | 504 | |
152| `aborted` | 499 | the caller went away |
153| `unsupported` | 501 | including writes when they are disabled |
154| `read_only` | 403 | a write whose remote is in the public namespace, with or without a bearer or git credential |
155| `internal` | 500 | a bug; an error without a known code is reported as this |
157## Tracing
159- `?trace=1` on a JSON endpoint adds `trace: [{name, ms, status, attrs, events}]` with ply's spans: the
160 spans ply's Tracer hands its `onEnd` (the plain-value form of the OTLP spans ply emits anywhere; no OTLP is built
161 for a request).
162- `/v1/read` streams raw bytes and has no JSON to carry spans. Instead, `?trace=1` adds an `x-ply-trace` header
163 summarising every span that finished before the first byte, as `name;dur=ms, …`. The blob's own span finishes after
164 the response is sent, so it shows up only in the request's log line (`stream: ok|error`).
165- Every request writes one structured log line (`msg: "ply.request"`) with id, method, path, upstream **host** (never
166 the path or the credential), status, ms, round trips, how many fetches used the blob:none fallback, and pack-cache
167 hits. Workers Observability logs and traces are enabled, and `redact_query_string` keeps `remote=` out of the
168 platform's request records. Each response carries `x-ply-request-id`.
169- Every `/v1` response that talked to the remote, including 4xx and 5xx, carries `x-artifacts-ray` and `Server-Timing`.
170 The ray header is the upstream `cf-ray` of each git HTTP exchange, in start order:
172 ```
173 ray-header = entry *( ", " entry ) [ ", " overflow ]
174 entry = phase "=" ray ";dur=" duration
175 overflow = "overflow=" 1*DIGIT
176 phase = "ls-refs" / "fetch" / "receive-pack"
177 ray = cf-ray / "-" / "no-response"
178 cf-ray = 16HEX "-" 3ALPHA
179 duration = 1*DIGIT
180 ```
182 `ls-refs` is info/refs and v2 ls-refs. `fetch` is each upload-pack fetch, including a blob:none retry. `receive-pack`
183 is the advertisement and the push. `-` is a response with no ray id (the raw header is not echoed). `no-response` is
184 a call that failed before headers. Past 32 entries the rest are `overflow=<count>`. `Server-Timing` repeats the same
185 phases and durations, then `total` for the Worker. The matching spans gain `git.upstream.cf_ray`,
186 `git.upstream.phase`, and `git.upstream.dur_ms`. The viewer sends the same header. It contains no URL, credential, or
187 repository name.
189## Servers that refuse `filter tree:0`
191Cloudflare Artifacts refuses `filter tree:0`. ply learns this from the 400 and falls back to `blob:none`, which
192brings more trees per fetch (see ply's README). The Worker keeps what it learned per origin for the life of the
193isolate, so only the first request on an isolate pays for the 400.
195## Public viewer (`/view`)
197`GET /view` is a server-rendered browser for a **public** smart-HTTP repository. It does not use `PLY_TOKEN` and it
198never reads `Authorization`, `Git-Token`, `Git-Authorization`, or `Cookie`. A URL with userinfo is rejected, not
199turned into a credential. `/v1` is unchanged: same gate, same credential headers. `/v1` and the viewer share one isolate-wide, per-origin `quirks`
200map (`src/quirks.ts`): a server that rejects `filter tree:0` costs that 400 and the `blob:none` retry once per isolate,
201and later pages ask for `blob:none` directly (the waterfall says which). Until 2026-10-31 the viewer re-learned it on
202every page; on Artifacts that 400 was ~110–150 ms of every page.
204The home form accepts an https URL, `github.com/owner/repo`, `owner/repo` (github.com), or `git@host:path` (the ssh user is dropped, then the allowlist runs). Shareable URLs: `/view/<host>/<repo path>?ref=&path=` (`path` may use `/` or `%2F`). A path segment of `.` or `..`, a backslash, or an encoded slash, backslash, or dot in the URL path (and an encoded dot or backslash in `?path=`) is rejected on the raw URL, before the URL parser collapses it. `?raw=1` returns the file as `text/plain` or
205`application/octet-stream` (never `text/html`). `?want=<oid>&filter=tree:0|blob:none&offset=` is the pack map.
206The viewer is ply's showcase, so every page shows the git work behind it. Under the title of a tree or file page, the
207**ply strip** sums it up (git calls, wall time, bytes, how many came from Workers Cache, protocol version) with every call
208drawn on one timeline, and links to `#diagnostics`. Every HTML page ends with the **Diagnostics** section, open by
209default (it was collapsed until 2026-11-06; `?trace=1` still forces it open): the raw remote, a waterfall of the git
210round trips that produced the page on one shared timeline (call, filter, HTTP status, bytes, cache HIT, duration; tap a
211row for wants, server agent and pkt-line counters), the protocol the server spoke, pack-map links, and the `cf-ray` when
212the platform sends one. The footer links the ply and ply-web commits the deploy was built from. The Workers trace id is
213not readable inside the isolate. `GET /` from a browser (`Accept` containing `text/html`) is a `302` to `/view`; curl,
214fetch and the CD probes (`Accept: */*`) still get the usage text.
216The commit, its first-parent history (Recent commits, 10) and, on a server that refuses `tree:0`, every tree, come from
217ONE fetch: `want <head> deepen 10` with `filter tree:0`, or `blob:none` on Artifacts. Measured on the same graphs on
218GitHub (2026-10-30): curl `tree:0` deepen 10 is 6.1 KB; `blob:none` deepen 1 is 121.6 KB and deepen 10 is 129.0 KB
219(+6%). Until 2026-10-30 the log fetched one commit per round trip and stopped after the first on Artifacts.
221README and `.md` files render GitHub-flavoured markdown (tables, task lists, fenced code with a language label, nested
222lists, quotes, reference and auto links) through `src/viewer/markdown.ts`: source text is only ever escaped, tags and
223class names come from fixed sets in `safehtml.ts`, hrefs pass the scheme allowlist, and repository-relative links
224resolve to viewer URLs. Images render as links (the CSP is `img-src 'none'`; a README must not make visitors fetch
225third-party pixels). The stylesheet is served at a content-hashed URL, `/view.<sha1-prefix-12>.css` (`VIEWER_CSS_PATH`), with `cache-control: public, max-age=31536000, immutable`; HTML is `no-store`, so a page always links the sheet it was rendered with. `/view.css` and a previous deploy's hash still answer with the current sheet, `no-cache` plus an ETag. Icons carry `width`/`height` 16 so an unstyled page never draws them large. After every deploy run `node scripts/visual-smoke.mjs` (headless Chrome over CDP: 375 and 1280 px, light and dark; exits 1 on an SVG wider than 64 px, overflow, an unapplied or unhashed stylesheet, or a tree page without `li[data-oid]` rows; `STALE_CSS=<file>` emulates a browser holding an old `/view.css`). That sheet is Kumo's theme and base plus only the Kumo utilities `kumo-classes.ts` emits
226(`kumoSubset`, 167.9 KB → 67 KB).
228**Machine-readable markup (stable interface).** Styling and layout may change; these attributes do not, and
229`test/viewer.test.ts` ("scraping contract") pins them against `git ls-tree`. Scrapers and monitors should use them, never
230class names or visible text:
232| Selector | Attributes | Meaning |
233|---|---|---|
234| `li[data-oid]` (tree page) | `data-oid` full 40-hex oid, `data-mode` as `git ls-tree` prints it (`100644`, `100755`, `120000`, `040000`, `160000`), `data-type` `blob`/`tree`/`commit`, `data-name` | one row per entry shown; the `..` row has none |
235| `ul.files` | `data-path`, `data-entries` (entries in the tree), `data-shown` (rows rendered; less than `data-entries` when capped) | the listing |
236| `[data-commit]` | full 40-hex oid | the commit the page shows |
238Example: `curl -s 'https://ply.ivar.workers.dev/view/github.com/ivarvong/ply?path=src' | grep -oE '<li data-oid="[0-9a-f]{40}"' | wc -l`
239matches `gh api repos/ivarvong/ply/git/trees/main:src --jq '.tree | length'`.
241**Allowlist.** An unauthenticated Worker that will `fetch` a caller-supplied URL is an SSRF proxy, so the viewer
242accepts https URLs whose hostname is an exact, case-insensitive match for `github.com`, `gitlab.com`,
243`codeberg.org`, `bitbucket.org`, or `git.sr.ht`. No suffix, no wildcard, no userinfo, default port only. A
244trailing dot (`github.com.`) does not match. Lookalikes (`github.com.evil.com`, `evilgithub.com`, punycode)
245do not match. Everything else is rejected before a fetch, and the error lists the supported hosts.
246`VIEWER_EXTRA_HOSTS` appends exact hostnames (comma-separated). A token with a scheme, port, userinfo, wildcard,
247or trailing dot is skipped, not treated as a suffix. Cloudflare Artifacts is off unless that variable names the
248exact public git host. `ALLOW_REMOTE_ORIGINS` is a `/v1` test hook and does not apply to `/view`. Redirects follow
249git's `http.followRedirects=initial`: ply follows only the first `GET info/refs` and rebases the repo there, after
250`viewerAllowUrl` checks the new base is still that repo's `info/refs` / `git-upload-pack` path (plus a `.git` suffix)
251on the same host; a 3xx on a POST is an error. `createViewerFetch` checks every request the same way and never
252follows a 3xx itself. A redirect whose raw `Location` contains `.`, `..`, `%2e`, `%2f`, or `%5c`, or names any other
253host, is refused there before ply sees it. Upstream `User-Agent` is
254`ply-viewer/0.1.0`.
256**Caps** (not raised by environment; rate limits can be lowered and are clamped to 1…1000):
258| Cap | Value |
259|---|---|
260| upstream bytes / page | 4 MiB |
261| pack bytes mapped | 2 MiB |
262| pack objects mapped | 400 |
263| inflated bytes / pack | 4 MiB |
264| one object | 1 MiB |
265| file shown or returned raw | 256 KiB |
266| delta chain | 32 |
267| delta result | 1 MiB |
268| upstream calls / page | 16 |
269| redirects (first info/refs only) | 2 |
270| per-call timeout | 12 s |
271| page timeout | 20 s |
272| refs retained | 2000 (200 branches shown) |
273| tree entries retained / shown | 2000 / 500 |
274| parent commits shown | 5 |
275| page rate | 60 / minute / client |
276| pack-map rate | 20 / minute / client |
278Over any cap the response is an HTML error (413 for a limit, 504 for a timeout), with the trace of the calls that
279did finish. Rate limiting is keyed by the SHA-256 of `CF-Connecting-IP` (clients with no header share one key) and
280stores no addresses. `RATE_MODE` picks the limiter. `batched` (the default since 2026-11-06, [docs/rate-limit.md](docs/rate-limit.md)):
281the request reads ONE cached document of blocked clients through the cache-enabled `RateCache` entrypoint
282(`max-age=1, stale-while-revalidate=30`) and never waits on a Durable Object; admitted hits are batched per isolate and
283flushed every 200 ms from `ctx.waitUntil` to the single SQLite Durable Object `RateCounter` with an idempotency key,
284retried with the same key for up to 5 s. The limit is approximate: a client is refused about 1.5 s after it reaches it.
285`legacy`: `ViewerRateLimit`, one SQLite Durable Object per client called before any git work, storing a short list of
286timestamps per bucket.
287Git reads are cached with Workers Caching (see [Caching](#caching-workers-cache)); there is no Cache API anything. HTML is `no-store` and escaped. CSP is `default-src 'none'; style-src 'self'; script-src 'none'; img-src 'none'`,
288plus `X-Content-Type-Options: nosniff`. There is no inline script and `unsafe-inline` is not allowed.
290`cloudflare.config.ts` declares `ViewerRateLimit` as a live SQLite class in `worker.exports`. The namespace already exists (created by migration tag `v1-viewer-rate`, namespace id `656fdd50f0d6428393eb2d9250ceee67`). Declaring it keeps that namespace and its data.
292## Public namespace (`public-v0`)
294One Cloudflare Artifacts namespace is served publicly and read-only. Its name is one constant,
295`PUBLIC_NAMESPACE` in `src/public-namespace.ts`; `cloudflare.config.ts` binds that namespace and `src/public.ts` matches
296URLs under it, so moving to `public-v1` is a one-line change (plus creating the namespace and publishing into it).
298- **URLs.** `GET /r` and `GET /r/` are the styled index of the namespace. `GET /r/<repo>` is the canonical viewer page
299 for that repo (`ref` is the only ref parameter; `at` and `commit` redirect to it). A name that is not in the namespace
300 is a styled 404 and is not redirected. The long
301 `/view/5ad2236b39de4c8bd8f6270ea63f3ea9.artifacts.cloudflare.net/git/public-v0/<repo>.git` form redirects to `/r/<repo>`.
302 The home page (`/view`) also lists the namespace (binding `list()`, cached a minute per isolate). The viewer
303 accepts that Artifacts host without `VIEWER_EXTRA_HOSTS`, but only for one repo directly under `/git/public-v0/`; any
304 other path on the host (another namespace, a nested path, `..` or an encoded separator) is a 400 before any fetch.
305- **`/v1` reads.** `refs`, `discover`, `tree`, `read`, and `commit` need no bearer when the request has **no
306 `Authorization` header at all** and `remote` is exactly `https://<that host>/git/public-v0/<repo>(.git)`. These requests
307 share the viewer's per-client page bucket (60/min, `ViewerRateLimit`). A caller git credential on such a request is a
308 400 (send none, or use the bearer). A wrong bearer is still a 401. With a valid bearer nothing changes from the
309 rules above: no rate limit, and the public token is used when the caller sends no git credential of their own.
310 Rationale: the content is public by construction, the remote can only be one of our own repos, the Worker holds only
311 a read credential for it, and the rate limit bounds cost. Every other `/v1` request still needs the bearer.
312- **Writes.** Every write endpoint whose `remote` is anywhere under `/git/public-v0/` on that host (compared
313 case-insensitively, any depth) returns 403 `read_only`. That holds with a valid bearer and with a caller's own write
314 credential, and nothing is sent upstream. Without a bearer a write is the usual 401.
315- **Credential.** No stored secret. The Worker has an Artifacts binding `PUBLIC_REPOS` scoped to `public-v0` and calls
316 only `get(<repo>).createToken("read", 3600)` and `list()`. Artifacts tokens are per repo; there is no namespace-wide or
317 non-expiring read token (TTL 60 s … 1 year, default 24 h). Tokens are cached per isolate per repo and re-minted with
318 less than 5 minutes left, so rotation is automatic and an isolate holds at most one live token per repo (plus
319 retired ones, kept only so the scrubber still removes them). A read token is refused by `git-receive-pack` (403,
320 checked 2026-10-30).
321- **Where the token goes.** `withPublicReadCredential` (`src/public.ts`) is the innermost fetch, below
322 `createGuardedFetch` and `createViewerFetch`, so it runs on every request, including each hop ply follows. It adds
323 `Authorization: Bearer <token>` only when the raw URL's origin is exactly `https://<that host>` (no `:443`, no
324 uppercase, no trailing dot, no userinfo), the raw path is exactly `/git/public-v0/<repo>(.git)/info/refs` with query
325 `?service=git-upload-pack` and method GET, or `…/git-upload-pack` with no query and method POST, and the path has no
326 `.`/`..` segment, `%`, backslash or control character. `receive-pack` never matches. When the request already carries
327 an `Authorization` (a caller's `Git-Token` or `Git-Authorization`), the caller's credential is used and the Worker's
328 token is not added. The pack cache sits above the guard, so its key has no Authorization and survives rotation.
329- **Scrubbing.** Every minted token (full, without `?expires=`, Basic-encoded, URL-encoded) is scrubbed from every
330 `/v1` JSON body, every viewer HTML/text body and header, and every log line. Blob bodies are not rewritten: they are
331 git objects whose hash ply checked. `test/public-worker.test.js` greps every response and the workerd log for each
332 form, including against a host that echoes the header back.
333- **Revocation.** Tokens expire within an hour. To cut every Worker token off at once, revoke them per repo
334 (`cf artifacts namespaces repos tokens list --namespace public-v0 --name <repo>` and
335 `cf artifacts namespaces tokens revoke <id> --namespace public-v0 --force`); the Worker mints new ones on the next
336 request. To take the namespace offline, remove the binding and deploy.
338### Mirrors that follow GitHub
340`public-v0/ply` and `public-v0/ply-web` follow their GitHub `main` (`src/mirror.ts` `MIRRORS`). A Worker cron
341(`* * * * *`) compares the two refs; when they differ it fetches only the new objects from GitHub (`want <github tip>`,
342`have <mirror tip>`, anonymous) and pushes them to the mirror as a CAS update from the mirror's tip (a rewritten
343upstream is followed). The write token is minted through the namespace-scoped binding for that one repo with the
344minimum TTL (60 s) and revoked as soon as the push returns. No token lives in CI or in the repo. One log line per mirror
345per minute: `{"msg":"ply.mirror", repo, outcome: in-sync|updated|error, from, to, objects, pushBytes, ms}`.
346`MIRROR_SYNC="off"` stops it. An update over 32 MiB is refused (logged); publish that with the script below.
348### Publish a repo
350```sh
351env -u CLOUDFLARE_API_TOKEN node scripts/publish.mjs <repo> <source> [--branch main] [--tags]
352# e.g. the ply mirror:
353env -u CLOUDFLARE_API_TOKEN node scripts/publish.mjs ply https://github.com/ivarvong/ply.git
354```
356The script uses your `cf` login (OAuth). It creates `public-v0/<repo>` if missing (and revokes the 24 h write token that
357creation returns), clones the one branch bare, mints a **write token for that repo only, with a 10-minute TTL**, and
358force-pushes the branch (and tags with `--tags`) with stock git. The token reaches git only through `GIT_CONFIG_*`
359environment variables, never argv, a file, or stdout. The script revokes it afterwards. The Worker never holds a write
360token. Re-run the same command to update a mirror. Artifacts limits apply (64 MiB per push, 1 GB per repo).
362## Caching (Workers Cache)
364Workers Caching only, never the Cache API (`caches.default`): `test/gitcache.test.ts` fails on any `caches.` in `src/`.
366```
367eyeball ─▶ default entrypoint (cache OFF: always runs → rate limit, ply.request log, scrub, traces)
368 └─ ply ─▶ request guard (createGuardedFetch / createViewerFetch: every request re-validated, no 3xx followed)
369 └─ createLoopbackFetch (src/gitcache.ts)
370 ├─ public + no Authorization + pure function of its request ─▶ ctx.exports.GitCache (cache ON) ─▶ upstream
371 └─ anything else (every caller credential, haves, other hosts) ─────────────────────────▶ upstream
372```
374- **What may be cached:** an upload-pack exchange with **no Authorization header** whose URL is exactly a public-v0 repo
375 endpoint, or an upload-pack endpoint on a built-in viewer forge (github.com, gitlab.com, codeberg.org, bitbucket.org,
376 git.sr.ht). A caller's `Git-Token` / `Git-Authorization` becomes an Authorization header, so a credentialed read always
377 goes straight upstream and can never populate a key. GitCache re-checks the same rule, and attaches the public-v0 read
378 token itself.
379- **Policy** (`Cache-Control` from GitCache):
381 | kind | exchange | Cache-Control |
382 |---|---|---|
383 | `pack` | `command=fetch` with wants only (no have / shallow / want-ref / deepen-since / deepen-not) | `public, max-age=31536000, immutable`: objects are named by their hash |
384 | `refs` | `command=ls-refs` | `public, max-age=5, stale-while-revalidate=10`: a ref change shows within 15 s |
385 | `discover` | `GET info/refs?service=git-upload-pack` | v2 capability list: `public, max-age=300, stale-while-revalidate=3600`; a v0 advertisement (carries refs): the refs policy |
386 | `pack` | a 400 whose text is a partial-clone filter refusal (Artifacts: `only blob:none is supported`) | `public, max-age=3600`: a fact about the server; uncached, every fresh isolate paid it (11 of 13 GitCache runs in a 20-request cold burst, e021776d) |
387 | — | any other non-200, any 3xx | `no-store` (3xx goes back to the guard; GitCache never follows) |
389- **Keys:** `/v<CACHE_VERSION>/<kind>/<sha256(kind, url, git-protocol, body)>`. The upstream request travels in headers
390 (not part of a Workers Cache key); GitCache recomputes the hash and refuses a mismatch, so no request can store an
391 answer under another's key. `crossVersionCache` is on (deploys keep packs warm); `CACHE_VERSION` (`src/cache-version.ts`)
392 is the only partition: bump it when what GitCache stores changes.
393- **Poison:** ply re-verifies every object; after a corrupt cached pack it retries with `x-ply-cache: bust`, which purges
394 that key (`ctx.cache.purge({ pathPrefixes })` inside GitCache) before refetching.
395- **Observability:** the tier (`cf-cache-status`: HIT, MISS, EXPIRED, …) reaches ply as `x-ply-pack-cache`, so every
396 span carries `git.response.cache`, the viewer waterfall shows it, and `ply.request` logs count `cache_hits`. A HIT
397 never runs GitCache, so it leaves no GitCache invocation.
398- **Whole responses pinned to a commit** (`src/pinned.ts`, cache-enabled `Pinned` entrypoint): viewer raw files
399 (`?raw=1&ref|at=<40-hex>&path=`) on `/view/…` or `/r/<repo>`, for public-v0 or a built-in forge. The front door rate-limits and logs, then fetches the
400 canonical key `/v<CACHE_VERSION>/pinned<path>?<allowed params, sorted>` from Pinned. Pinned rebuilds the request from
401 the key alone (it reads no header, so no credential can reach it), runs the same handler, and answers `immutable` on a
402 200, `no-store` otherwise. Responses carry `x-ply-pinned-cache` (the tier). HTML pages are not cached whole: they render
403 times relative to the request and carry that request's waterfall, cf-ray and id. Their git parts are cached.
404- `PACK_CACHE=off` sends everything direct.
406## Develop / deploy
408```sh
409npm test # /v1 + public-namespace workerd suites, then the viewer/security/public unit suites
410npm run dev # cf dev: Vite + the Cloudflare plugin on local workerd
411npm run typecheck # tsc for the app, then cf workers types + tsc for cloudflare.config.ts
412npm run worker:deploy:dry-run # cf deploy --dry-run: build and validate, no credentials, no upload
413npm run cd # operator deploy: bump, 0% canary, smoke, telemetry, ramp (docs/continuous-deployment.md)
414npm run cd -- smoke --version <id> # pinned lifecycle smoke against that Workers version
415npm run worker:deploy # refuses unless PLY_FORCE_FULL_DEPLOY=1; then cf deploy to 100%
416```
418The operator runbook for a gradual ramp (bump, 0% canary, pinned smoke, telemetry, then the policy's steps through 100%, with a rollback at any bad step) is [docs/continuous-deployment.md](docs/continuous-deployment.md). `npm run worker:deploy` refuses unless `PLY_FORCE_FULL_DEPLOY=1`. With that set it still goes to 100% in one shot. Do not run it while a ramp is in progress.
420`npm run cd` deploys only when `HEAD` is `origin/main` after a fetch. The full run is `npm run cd -- cd --sha <40 hex>`, and `npm run cd -- --sha <40 hex>` is the same. A release is that ply sha paired with the ply-web commit of the checkout. Re-running the pair reads the live deployment and continues from the stage that split is in. A version tagged with only the ply sha is not a match, so a ply-web-only change is uploaded. A dirty checkout is refused before a run starts. `--no-bump` deploys the checkout without moving the pin. `--sha` with `--no-bump` is allowed only when that sha is already the pin. `npm run cd -- bump` commits the pin on a branch whose parent is `origin/main`. It uses `cf` only. A canary is a new version at 0% beside the current one at 100%. Pinned smoke sends `Cloudflare-Workers-Version-Overrides: ply="<id>"` and requires `x-ply-version` to match. Telemetry reuses the loss allowance in `scripts/canary-verdict.mjs`. After the 0% gate the ramp sends unpinned traffic, reads which version served each request from Workers telemetry, and puts the old version back at 100% on a breach.
422The smoke creates an empty repo in the Artifacts namespace `ply-loadgen`. Repo create returns a token; that token is revoked before the smoke starts and must then get 403 from Artifacts. The smoke mints a short-lived write token from `PLY_TOKEN_FILE` (default `~/.ply-token`, mode `0600`, the same value as the Worker secret `PLY_TOKEN`) and drives the git lifecycle through `/v1`. It does not seed the repo with stock git. The minted token is revoked when the run ends and checked the same way. A pass deletes the repo. A fail leaves the repo name in the verdict. Tokens stay out of argv and the run log.
424The Worker is built and deployed with the Cloudflare CLI, [`cf`](https://developers.cloudflare.com/cf/), pinned as a dev dependency. `cloudflare.config.ts` is the Worker config (name, compatibility date, bindings, Durable Object exports, observability, limits). `vite.config.ts` holds build settings only: `cf build` delegates bundling to Vite and the Cloudflare Vite plugin and writes Build Output to `.cloudflare/output`. The workerd suites in `npm test` run that same bundle (`test/cf-bundle.js`). Nothing here needs Docker: the Vite plugin runs `docker image ls` after every build even with no containers (execFileSync, no timeout, so a hung daemon hung the build), and `vite.config.ts` sets `WRANGLER_DOCKER_BIN=false` so that call fails at once and is skipped.
426`npm run worker:deploy` runs `cf deploy` only when `PLY_FORCE_FULL_DEPLOY=1`. Otherwise it exits and uploads nothing. When `CLOUDFLARE_API_TOKEN` is set, cf uses it. When it is unset, cf uses the OAuth session from `cf auth login`. The command uploads the Worker named `ply`: text bindings `WRITES` and `PACK_CACHE`, the `ViewerRateLimit` Durable Object, observability, `limits.cpuMs`, and `workersDev`. Worker secrets survive a deploy (the upload sends `keep_bindings: ["secret_text", "secret_key"]`). `PLY_TOKEN` stays a secret. Set or rotate it with `cf workers secrets update PLY_TOKEN --worker ply --type secret_text`. cf prompts for the value, so it never lands in shell history.
428cf has no live log stream yet (no equivalent of `tail`). Use the dashboard's live logs, or Workers Logs, which this Worker sends through `observability.logs`.
430### GitHub Actions
432GitHub does not bump the ply pin and does not deploy. An operator moves the pin with `npm run cd -- bump` and ships from the runbook above.
434### Cloudflare token
436`cloudflare.config.ts` has no `accountId`. The operator's `cf auth login` is what uploads. In a non-interactive `cf` process, cf takes the account from `CLOUDFLARE_ACCOUNT_ID`. Without it, a token that can see more than one account stops before upload. GitHub Actions does not upload this Worker.
438| Name | Where | What it is |
439|---|---|---|
440| `CLOUDFLARE_API_TOKEN` | operator environment, optional | Account → **Workers Scripts: Edit**. OAuth from `cf auth login` is the usual login. |
441| `CLOUDFLARE_ACCOUNT_ID` | operator environment, when the token can see more than one account | Account id of the account that owns the `ply` Worker |
443Workers Scripts Edit is the user-token permission name. An account-owned token lists the same grant as **Workers Scripts Write**. The [script upload API](https://developers.cloudflare.com/api/resources/workers/subresources/scripts/methods/update/) and [`GET /accounts/:account_id/workers/subdomain`](https://developers.cloudflare.com/api/resources/workers/subresources/subdomains/methods/get/) (cf calls that because `workersDev` is true, and `ply.ivar.workers.dev` already exists) both accept it. Scope the token to this account. The Worker already exists, so the deploy is an update: Editor on the `ply` Worker is enough for a per-Worker token. Creating the Worker the first time would need Admin at the Workers product scope.
445Nothing else in this config asks for a permission:
447- No routes and no custom domains, so no Zone → Workers Routes → Edit.
448- No KV, R2, D1, Queues, or Secrets Store bindings.
449- The Artifacts binding `PUBLIC_REPOS` (namespace `public-v0`). The OAuth deploy of 2026-10-30 uploaded it; whether a
450 scoped CI token needs an Artifacts permission on top of Workers Scripts Edit has not been checked.
451- Durable Objects have no token permission of their own. `ViewerRateLimit` follows the Worker.
452- Observability, `limits.cpuMs`, the Worker cache settings (`cache`, per-entrypoint `exports`), and the `WRITES` / `PACK_CACHE` text bindings travel in the script upload.
453- Workers Tail Read is the permission for live log streaming, which this deploy does not use.
455### Companion workflow in ivarvong/ply
457ply's `main` should wake ply-web on every push, so the pin updates without waiting for the cron. Add this file as `.github/workflows/notify-ply-web.yml` in ivarvong/ply. On push to ply `main` it POSTs `repository_dispatch` (`event_type: ply-main-updated`, `client_payload.sha` set to that commit) to `ivarvong/ply-web`. When the secret is missing it prints a notice and exits successfully. ply-web resolves ply `main` itself when it wakes up; the payload sha is the commit that was pushed.
459```yaml
460name: Notify ply-web
462on:
463 push:
464 branches: [main]
466permissions:
467 contents: read
469jobs:
470 dispatch:
471 runs-on: ubuntu-24.04
472 steps:
473 - name: Dispatch ply-main-updated
474 env:
475 PLY_WEB_DISPATCH_TOKEN: ${{ secrets.PLY_WEB_DISPATCH_TOKEN }}
476 run: |
477 set -euo pipefail
478 if [ -z "${PLY_WEB_DISPATCH_TOKEN}" ]; then
479 echo "::notice title=ply-web not notified::PLY_WEB_DISPATCH_TOKEN is not set. Add a fine-grained PAT with Contents: Read and write on ivarvong/ply-web. This push did not send repository_dispatch."
480 exit 0
481 fi
482 # GITHUB_SHA is the commit just pushed. ply-web resolves main itself.
483 GH_TOKEN="${PLY_WEB_DISPATCH_TOKEN}" gh api --method POST repos/ivarvong/ply-web/dispatches --input - <<EOF
484 {"event_type":"ply-main-updated","client_payload":{"sha":"${GITHUB_SHA}"}}
485 EOF
486```
488Secret, on **ivarvong/ply** (the sender, not ply-web): `PLY_WEB_DISPATCH_TOKEN`. A fine-grained personal access token restricted to the `ivarvong/ply-web` repository, with **Contents: Read and write**. That is the permission GitHub requires for `repository_dispatch`.
Diagnostics4 git calls · 10 ms
CallStatusSizeTime010 ms
discover200152 B3 ms
git.upload-pack discover
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=ls-refs
git.upstream.dur_ms=3
git.response.bytes=152
git.server.agent=gitty/1.0
git.server.object_format=sha1
git.server.caps=agent ls-refs fetch object-format
git.server.fetch=shallow filter sideband-all
git.protocol.version=2
git.pkt.frames=8
git.pkt.data=6
git.pkt.flush=2
git.pkt.delim=0
git.pkt.bytes=152
git.pkt.payload.max=34
ls-refs200145 B · hit3 ms
git.upload-pack ls-refs
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=ls-refs
git.upstream.dur_ms=3
git.response.bytes=145
git.response.cache=HIT
git.response.duration_ms=3
git.protocol.version=2
git.pkt.frames=3
git.pkt.data=2
git.pkt.flush=1
git.pkt.delim=0
git.pkt.bytes=145
git.pkt.payload.max=76
git.ls_refs.count=2
git.ls_refs.head=refs/heads/main
fetchblob:none · deepen 1020042 KiB · hit3 ms
git.upload-pack fetch
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=fetch
git.upstream.dur_ms=3
git.response.bytes=42585
git.response.cache=HIT
git.response.duration_ms=3
git.fetch.filter=blob:none
git.fetch.filter.requested=tree:0
git.fetch.filter.fallback=blob:none
git.fetch.filter.learned=false
git.fetch.wants=262b639aa1b258fc1777c3a66ba8f811df3a3da2
git.fetch.haves.count=0
git.fetch.deepen=10
git.fetch.thin_pack=false
git.fetch.ofs_delta=true
git.protocol.version=2
git.pkt.frames=6
git.pkt.data=4
git.pkt.flush=1
git.pkt.delim=1
git.pkt.bytes=42585
git.pkt.payload.max=42490
git.sideband.band1.bytes=42489
git.sideband.band2.bytes=0
git.sideband.band3.bytes=0
git.pack.objects=61
git.pack.bytes=42489
git.pack.ofs_delta=0
git.pack.ref_delta=0
git.pack.chain.max=0
git.pack.trailer=7dbf576d97429022615f79aa46b440d9da603496
git.pack.full=61
Open pack map
fetch20018 KiB · hit4 ms
git.upload-pack fetch
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=fetch
git.upstream.dur_ms=4
git.response.bytes=18392
git.response.cache=HIT
git.response.duration_ms=4
git.fetch.wants=0011567de753332ba7afea098081dffcc62caa2b
git.fetch.haves.count=0
git.fetch.deepen=0
git.fetch.thin_pack=false
git.fetch.ofs_delta=true
git.protocol.version=2
git.pkt.frames=3
git.pkt.data=2
git.pkt.flush=1
git.pkt.delim=0
git.pkt.bytes=18392
git.pkt.payload.max=18371
git.sideband.band1.bytes=18370
git.sideband.band2.bytes=0
git.sideband.band3.bytes=0

Each row is one HTTP round trip ply made to the git server for this page, on one timeline. discover asks what the server speaks, ls-refs lists branch tips, fetch brings objects by id. A hit was served by Workers Cache. Tap a row for its wire details.

Remote
https://5ad2236b39de4c8bd8f6270ea63f3ea9.artifacts.cloudflare.net/git/public-v0/ply-web.git
Ref
refs/heads/main
Commit
262b639aa1b258fc1777c3a66ba8f811df3a3da2
cf-ray
a5e1c67f7cbbc6f8
Request
c45ddc06…
Protocol
v2 · sha1
Agent
gitty/1.0
Filter
advertised
Fetch
shallow filter sideband-all
Capabilities
agent ls-refs fetch object-format