SPB Git

Repository Public

API_CONTRACT.md 25.9 KB

# SPB Git API contract for the iOS client (server 3.3.0)

Status: design contract written from the audit of spbgit 3.2.0 (src/api/v1.mjs, src/server.mjs, src/lib/shield.mjs, src/git/repo.mjs). Section 1 lists what exists and stays unchanged. Section 2 lists the additions the iOS client needs; they are implemented in the spbgit repository (target version 3.3.0) and are strictly additive: no existing route, field or status code changes, so the website and the spbgit CLI keep working.

Base URL: https://git.spboucher.ai. All JSON is UTF-8. Dates are ISO 8601 strings. Errors use the existing envelope {"error": {"code": "<snake_case>", "message": "<human text>"}} with a coherent HTTP status.

# 1. Existing routes (3.2.0, unchanged)

Route Notes
GET /healthz status, version, repos, shield mode, features
GET /api/v1/repos {repos: [Overview]}, every repository, about 780 KB uncompressed for 286 repositories
GET /api/v1/repos/:name one Overview
GET /api/v1/repos/:name/languages {languages, totalBytes}
GET /api/v1/repos/:name/commits?ref&page {ref, sha, page, hasNext, commits: [CommitSummary]}
GET /api/v1/repos/:name/tree?ref&path one directory level, strong ETag
GET /api/v1/repos/:name/releases tags with binary assets
GET /api/v1/stats site totals, streaks
GET /api/v1/search?q&scope&repo&limit scopes all, repos, files, commits, branches, readmes
GET /raw/:repo/<ref>/<path> raw bytes, streamed
`GET /archive/:repo/.zip .tar.gz`
GET /feed.atom Atom feed of pushes
POST /api/v1/repos, PATCH/DELETE /api/v1/repos/:name token required
POST/GET /api/v1/tokens, DELETE /api/v1/tokens/:id token required
PUT/DELETE /api/v1/repos/:name/releases/:tag/assets/:asset token required
GET /api/v1/whoami token check
GET/POST /api/v1/admin/shield token required
GET /pass/challenge, POST /pass/redeem proof-of-work visitor pass (cookie spb_pass)

Overview fields: name, description, topics[], homepage, pinned, created, research, researchDetected, defaultBranch, head, stamp, empty, lastPush, commitCount, branchCount, tagCount, sizeBytes, languages[{name, bytes, percent, color}], languageBytes, topLanguage, license, licensePath, spark{counts[26], max, total, path, area, lastX, lastY}, cloneUrl, url, computedAt, cloneCount.

CommitSummary fields: sha, shortSha, authorName, authorEmail, date, subject, body, filesChanged, additions, deletions.

# 2. Additions (3.3.0)

General rules for every new route:

  • Validation with zod; repository names through isValidRepoName, paths through isValidTreePath, refs resolved with resolveRef only. No user string ever reaches a shell: execFile/spawn with argument arrays, and -- before paths. Reject refs or paths starting with -.
  • Pagination: page (1-based) and perPage (default 30, max 100). Responses carry page, perPage, hasNext and, when cheap, total. Exception (as built): GET /repos/:name/commits keeps its 3.2.0 default of 40 per page and only returns perPage when the parameter is sent.
  • Caching: ETag on every GET (strong when keyed by a commit SHA, weak otherwise) with 304 support; Cache-Control: public, max-age=31536000, immutable when the request pins a full SHA, public, max-age=60 otherwise. Authenticated responses: private, no-store.
  • Expensive results are computed server-side and cached with the existing Cache (cache.remember, validated by refStamp), never per request.
  • Shield: new read routes are classified like their existing siblings (deep). As built: readme, blob, blob/lines, commits/:sha, commits/:sha/diff, compare, graph, per-repository metrics and metrics/compare are deep; meta, openapi.json, collections, activity, global metrics, branches and tags are api (never refused by the shield). A request carrying a valid token is exempt from the shield budgets. The iOS client solves the visitor-pass proof of work natively and sends the cookie, exactly like a browser.
  • Body limit for JSON writes: 6 MiB. Per-route rate limits on writes (30/min) and on search (existing).

# 2.1 Discovery

GET /api/v1/meta → {name, version, apiVersion: 1, publicUrl, owner: {name, username}, features: {ai, research, codeSearch, writes, push}, limits: {perPageMax, blobInlineBytes, blobLinesMax, diffLinesBudget, commitActionsMax, commitBytesMax}, shield: {mode, powBits}}

GET /api/v1/openapi.json → OpenAPI 3.1 document covering every /api/v1 route (existing and new).

GET /.well-known/apple-app-site-association (and /apple-app-site-association) → application/json: {"applinks": {"details": [{"appIDs": ["3YM54G49SN.ai.spboucher.git"], "components": [{"/": "/api/*", "exclude": true}, {"/": "/assets/*", "exclude": true}, {"/": "/raw/*", "exclude": true}, {"/": "/archive/*", "exclude": true}, {"/": "/releases/*", "exclude": true}, {"/": "/badge/*", "exclude": true}, {"/": "/og/*", "exclude": true}, {"/": "/pass/*", "exclude": true}, {"/": "/about/*", "exclude": true}, {"/": "/*"}]}]}, "webcredentials": {"apps": ["3YM54G49SN.ai.spboucher.git"]}}. Must be registered before /:repo, classified open by the shield, no redirect, no auth.

GET /about/ios, GET /about/ios/privacy, GET /about/ios/support → HTML pages (site layout) with the app presentation, the privacy policy and the support information (English and French on the same page).

# 2.2 Repository list

GET /api/v1/repos gains optional query parameters; without any, the response is byte-compatible with 3.2.0.

  • compact=1: drops spark.path, spark.area, spark.lastX, spark.lastY, stamp.
  • q, language, topic, collection, sort (name|activity|created|size|commits), order (asc|desc), page, perPage: server-side filtering; when page is present the response adds page, perPage, hasNext, total.
  • Each overview gains fileCount (tracked files at HEAD), releaseCount (tags with at least one asset), collections: [id].

GET /api/v1/collections → {collections: [{id, title: {en, fr}, symbol, count, repos: [name]}]}. Collections are derived from real metadata (topics, top language, name prefixes, research flag): ios-apps, macos-apps, ai, research, working-papers, quant-finance, infrastructure, maclustr, web-apps, orix, zyquo, dev-tools. Rules live in one module (src/lib/collections.mjs) and are documented on /about/metrics. A collection with no repository is returned with count: 0.

# 2.3 Repository content

GET /api/v1/repos/:name/readme?ref → {path, ref, sha, size, markdown, truncated} (raw text; above 1 MiB the first mebibyte is returned with truncated: true; 404 no_readme).

GET /api/v1/repos/:name/blob?ref&path → {repo, ref, sha, path, name, oid, size, mode, binary, mime, language, lineCount|null, inline: bool, content|null, rawUrl, lastCommit: CommitSummary|null} (rawUrl is pinned to the commit; mode is the git file mode). content (UTF-8 text) is present only when the blob is text and size <= limits.blobInlineBytes (1 MiB). Otherwise inline: false and the client pages with:

GET /api/v1/repos/:name/blob/lines?ref&path&start&count → {sha, path, start, count, totalLines|null, eof, lines: [string]}. start is 1-based (default 1), count <= limits.blobLinesMax (2000, default 500); count in the response is the number of lines returned and totalLines is known only when eof is true. Streams the blob and stops reading as soon as the window is filled; lines longer than 4000 characters are cut with a trailing …. Refused (413 too_large) above 64 MiB and for binary blobs (415 binary).

GET /raw/... gains Range support (single range, 206, Accept-Ranges: bytes) for media playback.

GET /api/v1/repos/:name/branches → {defaultBranch, branches: [{name, sha, date, subject, authorName, ahead, behind, isDefault}]} (ahead/behind against the default branch).

GET /api/v1/repos/:name/tags → {tags: [{name, sha, target, date, subject, annotated, taggerName|null, message|null, assetCount}]}. sha is the commit the tag leads to; target is the object the ref points at (the tag object of an annotated tag, the commit otherwise).

GET /api/v1/repos/:name/commits gains perPage, path (history of one file or directory), author, since, until, q (message grep, fixed string, case-insensitive). Each CommitSummary gains parents: [sha].

GET /api/v1/repos/:name/commits/:sha → {...CommitSummary, committerName, committerEmail, commitDate, parents: [{sha, shortSha, subject}], refs: [string], branches: [string] (branches containing the commit, max 20), stats: {files, additions, deletions}, files: [{path, oldPath|null, status: "added|modified|deleted|renamed|copied|typechange", additions, deletions, binary}], filesTruncated}. At most 3000 files are listed. Because refs and branches change with every push, this response is cached 60 s even when :sha is a full id (weak ETag); the diff route below is immutable.

GET /api/v1/repos/:name/commits/:sha/diff?path&context&full → {sha, base|null, truncated, lineBudget, files: [{path, oldPath, status, binary, additions, deletions, truncated, hunks: [{header, oldStart, oldLines, newStart, newLines, lines: [{t: " |+|-", o: int|null, n: int|null, s: string}]}]}]}. First parent as base (root commit: empty tree). path restricts to one file; context 0–20 (default 3); budget limits.diffLinesBudget (1500 lines) unless full=1 (hard cap 20 000). As built: when the budget is spent the stream stops, so the file being read has truncated: true (its additions/deletions then count only the lines returned) and the files after it are absent; take the full file list and exact counts from the commit route and ask for one file with path. A line may carry noNewline: true. As observed by the iOS client on 3.3.0: with path=<new path> a renamed file comes back as status: "added" with its whole content (git cannot pair a rename inside a path-restricted diff); the rename and its real counts are only in the unrestricted diff (full=1 when it is beyond the budget) and in the commit route. /compare returns no hunks. /releases lists every tag, with assets: [] for tags without files. In /tags, sha is the commit and target the tag object of an annotated tag.

GET /api/v1/repos/:name/compare?base&head → {base, head, mergeBase, ahead, behind, commits: [CommitSummary] (max 100), commitsTruncated, files: [...same as commit files], filesTruncated, stats} (files is the change from the merge base to head).

GET /api/v1/repos/:name/graph?limit&page → {commits: [{sha, shortSha, parents: [sha], subject, authorName, date, refs: [{name, type: "branch|tag|head"}]}], hasNext, page, limit} in --date-order over all branches and tags (limit default 200, max 500). Lane layout is computed by the client.

# 2.4 Metrics

Every metric has a written definition, returned in definitions and listed on /about/metrics.

GET /api/v1/metrics → global, cached (recomputed when any repository stamp changes, at most once per 5 min). As built: between two rebuilds the previous aggregate is served; while the very first aggregate is being computed (cache empty) the route answers 503 warming_up with Retry-After, which the client must handle:

text
{ computedAt, timezone: "America/Toronto",
  totals: { repos, commits, languages, activeDays, branches, tags, releases, sizeBytes, files, codeBytes,
            commitsToday, commitsThisWeek, commitsThisMonth, commitsThisYear,
            streak, longestStreak, bestDay: {date, commits} },
  daily:   [{date, commits}]            // every day from the first commit to today (zeros included)
  weekly:  [{week: "2026-W49", start, commits}],
  monthly: [{month: "2026-12", commits, additions, deletions, newRepos, activeRepos}],
  yearly:  [{year, commits}],
  weekday: [7 ints, Monday first], hour: [24 ints],     // author local time of each commit
  languages: [{name, color, bytes, percent, repos}],
  extensions: [{ext, files, bytes}] (top 40),
  repoGrowth: [{month, total}],          // cumulative repositories by creation month
  sizes: [{name, sizeBytes, codeBytes, files, commits}],   // every repository
  topRepos: {last30Days: [{name, commits}], last365Days: [...], allTime: [...]} (top 15),
  collections: [{id, repos, commits, commitsLast30Days}],
  research: [{month, commits, repos}],   // repositories in collections research + working-papers
  apple: [{month, commits, repos}],      // repositories in collections ios-apps + macos-apps
  definitions: {...} }

Commits are counted on the default branch of each repository, merges included, deduplicated by SHA inside one repository only. sizeBytes is the on-disk size of the bare repository (packed history); codeBytes is the sum of blob sizes at HEAD classified as source by the language detector, excluding vendored, generated, binary and build paths (node_modules/, vendor/, Pods/, dist/, build/, .build/, DerivedData/, lock files, minified files, *.pb.*, images, archives, fonts, PDFs). The two are never mixed in one chart.

GET /api/v1/repos/:name/metrics → per repository, cached by HEAD:

text
{ head, computedAt, commits, authors: [{name, commits}], firstCommit, lastCommit,
  daily: [{date, commits}] (last 371 days), weekly (all time), monthly: [{month, commits, additions, deletions}],
  weekday[7], hour[24], files, codeBytes, sizeBytes, lines: {code, total, byLanguage: [{name, lines, files}]},
  extensions: [{ext, files, bytes}], languages, hotPaths: [{path, changes}], largestFiles: [{path, size}] }

Line counts read text blobs at HEAD under 1 MiB each, capped at 20 000 files and 256 MiB read in total; when a cap is hit the response says lines.partial: true. Vendored, generated and binary paths are not read (lines.total excludes them too). The response also carries timezone, lines.files, statsPartial (true when the line statistics of the history could not be computed in time: additions/deletions are then zero) and definitions.

GET /api/v1/metrics/compare?repos=a,b,c (2 to 6 names) → {repos: [{name, monthly, commits, codeBytes, sizeBytes, files, languages, firstCommit, lastCommit}]}.

# 2.5 Activity

GET /api/v1/activity?page&perPage&repo&type&since&until&language&collection → {events: [{id, type: "push|branch_created|branch_deleted|tag_created|tag_deleted|repo_created|release_asset", repo, ref, refType, sha, commits, at, subject|null, authorName|null, readmeChanged: bool|null}], page, perPage, hasNext}. Source: data/activity.jsonl (5 800 push records today: {repo, ref, refType, deleted, commits, sha, at}) read backwards in a bounded way, enriched with the head commit subject (cached). From 3.3.0 on, the post-receive handler also records whether a ref was created and whether the push touched a README, and repo creation and release uploads append their own events. Events for repositories that no longer exist are dropped. As built: at most the last 8 MiB of the file are read per request (about 60 000 events); release_asset events carry an extra asset field; readmeChanged is null for records written before 3.3.0, for tags and deletions.

GET /api/v1/search gains:

  • scope=code: content search with git grep -I -n -F (or -E when regex=1, -w when word=1, -i unless case=1) at the default branch HEAD. With repo, one repository; without, repositories are searched in order of last push under a global budget (time 2.5 s, max 40 repositories per request, concurrency 4) and the response carries partial: true and cursor to continue. Results: code: [{repo, ref, sha, path, line, column, preview, language}], limit 50, at most 5 matches per file; the response also has searched (repositories searched by this request). scope=all does not run a code search. An invalid regular expression answers 400 invalid_pattern.
  • scope=tags, and tags included in all.
  • lang=<Language> filter for repos, files, code; exact=1 for whole-string match on names.
  • suggest=1: fast prefix suggestions {suggestions: [{type, repo, text}], ready} from the in-memory index only (no git process), for instant completion. type is repo|topic|branch|tag|file; ready: false means the index is still being built (first request after a start or a push) and the list may be empty: ask again.
  • Every hit that points into a file carries path and line so the client can open the code viewer on it.

# 2.7 Authentication and owner mode

Tokens keep the spbgit_<id>_<secret> format. Records gain scopes: [string] and expiresAt|null. A record without scopes (existing bootstrap token) is treated as ["*"]. Scopes: repo:write (metadata, contents, branches, tags, releases), repo:admin (create and delete repositories), tokens (list, create, revoke), admin (audit log, shield, admin overview). An expired token answers 401 token_expired; a missing scope answers 403 insufficient_scope.

  • POST /api/v1/tokens accepts {label, scopes?, expiresInDays?}; a token can only grant scopes its creator holds. Without scopes the new token inherits its creator's scopes.
  • GET /api/v1/tokens lists {id, label, created, lastUsed, scopes, expiresAt, current: bool}.
  • GET /api/v1/whoami adds scopes, expiresAt, username.
  • GET /api/v1/admin/overview → {version, uptimeSeconds, memory, cache, disk: {gitRootBytes, freeBytes}, shield, tokens: {count}, clones: {total, last30Days}, repos, trash: [{name, deletedAt}]}.
  • GET /api/v1/admin/audit?page&perPage → {entries: [{at, tokenId, tokenLabel, ip, action, repo|null, detail}]} from the new append-only data/audit.jsonl. Every authenticated write appends one entry (no secret, no file content). As built each entry also has status (HTTP status of the write, refused writes included) and the response has page, perPage, hasNext.

# 2.8 Git writes (owner)

All require a token with the listed scope, append an audit entry, bust the repository caches, append an activity event and run the same bookkeeping as a push. They operate on the bare repository with plumbing (hash-object -w --stdin, a temporary GIT_INDEX_FILE, read-tree, update-index --cacheinfo, write-tree, commit-tree, update-ref <ref> <new> <old>), never a shell, never a working tree. update-ref is given the expected old value, so a concurrent push makes the write fail instead of being overwritten.

POST /api/v1/repos/:name/commits (repo:write) body:

text
{ branch, expectedHead, message, author?: {name, email},
  actions: [{action: "create|update|delete|move", path, previousPath?, content?, contentBase64?,
             expectedOid?, executable?}] }
  • expectedHead is mandatory (null only for an empty repository). If the branch tip differs: 409 head_moved with {error, currentHead}.
  • create fails with 409 path_exists if the path exists; update, delete, move fail with 404 path_not_found if it does not; expectedOid (blob id the editor loaded) mismatch gives 409 blob_changed. Other refusals as built: 409 path_conflict (a parent of the path is a file), 400 is_directory, 400 no_changes (the tree is unchanged), 400 unsupported_entry (symbolic link or submodule), 404 branch_not_found, 400 invalid_branch, 400 invalid_path, 413 too_large. The first commit of an empty repository must target its default branch. .gitmodules cannot be written.
  • Limits: 50 actions, 5 MiB of content in total, message 1 to 5 000 characters. Paths validated (no .., no leading /, no .git component, no control characters).
  • Author and committer default to the configured owner. Response 201 {commit: CommitSummary, branch, previousHead}.

POST /api/v1/repos/:name/branches {name, from} (repo:write) → 201 {name, sha}; 409 already_exists; 409 ref_conflict when the name collides with an existing branch path (a versus a/b). DELETE /api/v1/repos/:name/branches/:branch?expectedSha= (repo:write) → 200 {deleted, sha}: refuses the default branch (400 default_branch) and a moved tip (409 head_moved). expectedSha (full 40-character id) is mandatory; the branch name may contain slashes, raw or encoded as %2F. POST /api/v1/repos/:name/tags {name, sha, message?} (annotated when message is given) → 201 {name, sha, target, annotated}; sha is 4 to 40 hexadecimal characters. DELETE /api/v1/repos/:name/tags/:tag?expectedSha= → 200 {deleted, sha, target}; expectedSha is mandatory and may be the commit the tag leads to or the tag object. DELETE /api/v1/repos/:name keeps its behaviour (soft delete, 30 days in the trash) and additionally accepts X-Confirm-Name; when the header is present and differs from :name the request is refused (400 confirmation_mismatch).

As observed by the iOS client on 3.3.0 (owner routes, read from the server code and a local instance):

  • POST /api/v1/tokens answers 201 {token, id, label, created, lastUsed, scopes, expiresAt}: the record with the secret next to it. scopes accepts *; expiresInDays is 1 to 3650. A token cannot grant a scope its creator lacks (403 insufficient_scope, message cannot grant scopes the current token lacks: …). DELETE /api/v1/tokens/:id answers {revoked}.
  • 403 insufficient_scope carries the scope in its message only (This token lacks the scope repo:admin.).
  • PATCH /api/v1/repos/:name is strict (an unknown field, name included, is refused) and also accepts defaultBranch (400 unknown_branch when it does not exist). POST /api/v1/repos accepts defaultBranch (default main) and names matching ^[a-z0-9][a-z0-9._-]{0,63}$; topics match ^[a-z0-9][a-z0-9-]{0,34}$, at most 10; description at most 350 characters; homepage empty or a URL of at most 300 characters.
  • DELETE /api/v1/repos/:name answers {deleted, recoverable, note}.
  • 409 blob_changed carries path and currentOid, and no currentHead. 409 head_moved carries currentHead for commits, branch deletions and tag deletions.
  • Audit entries: detail is a JSON object ({branch, commit, actions, bytes, paths} for a commit, {refused: "<code>"} for a refused Git write, {} otherwise), and a write refused before its handler ran is recorded with the route as action (POST /api/v1/tokens, status 403). The log has no server-side filter.
  • GET /api/v1/admin/overview: shield is {mode: normal|attack, forced: on|off|auto, since, powBits}. POST /api/v1/admin/shield {mode: on|off|auto} answers the same object. The server evaluates its mode at most every five seconds: a switch made within a few seconds of another one is stored at once but reported later, so the client reads the overview again for a few seconds before it calls a switch unconfirmed. Both shield routes are open without a token to requests coming from the server's own machine, and a switch of the shield is not recorded in the audit log.
  • Release assets: PUT …/releases/:tag/assets/:asset takes the raw bytes (application/octet-stream, up to 4 GiB) and answers 201 {name, size, sha256, tag, url}; 400 unknown_tag when the tag does not exist; names match ^[A-Za-z0-9][A-Za-z0-9._-]{0,120}$. DELETE answers {deleted, tag}.
  • Public reads made right after a write are fresh on the server (its caches are busted by the write), but carry Cache-Control: public, max-age=60: a client with an HTTP cache must bypass it to read its own write.

# 2.9 Push notifications (proprietary, optional)

POST /api/v1/devices {deviceToken, environment: "sandbox|production", repos: [name] | "*", locale} → 201 {id}; DELETE /api/v1/devices/:deviceToken. No account: the device token is the identity. Stored in data/devices.json (token, environment, followed repositories, locale, dates; nothing else). deviceToken is 64 to 200 hexadecimal characters; repos holds at most 400 names; DELETE answers 200 {deleted: true} whether or not the token was registered; 503 registry_full above 5000 devices. When SPBGIT_APNS_KEY_FILE, SPBGIT_APNS_KEY_ID, SPBGIT_APNS_TEAM_ID are set, a push to a followed repository sends one APNs alert (HTTP/2, ES256 JWT, topic ai.spboucher.git), coalesced per repository per minute; tokens rejected with 410, or with 400 BadDeviceToken / DeviceTokenNotForTopic, are deleted. The payload carries repo, ref, refType, sha next to aps (alert title = repository name, body localized in English or French, thread-id = repository). Without the key the routes answer 501 push_disabled and meta.features.push is false; the app then relies on background refresh and local notifications only.

# 3. As observed by the offline and platform features (2026-12-02, server 3.3.0)

  • /.well-known/apple-app-site-association is live and matches section 2.1 byte for byte.
  • POST /api/v1/devices and DELETE /api/v1/devices/:token answer 501 {"error":{"code":"push_disabled"}}; meta.features.push is false. The client maps 501 to APIError.unsupported and stays on local notifications.
  • tree has no recursive form: an offline download lists one directory per request. tree and blob pinned to a full SHA answer Cache-Control: immutable with a strong ETag, and sha equals the requested id.
  • blob.content of a text file hashes to blob.oid as a git blob (SHA-1("blob <size>\0" + content)), and size is its UTF-8 byte count: that is the integrity check of offline copies.
  • Web pages exist for /:repo, tree, blob, commit/:sha, commits[/:ref], branches, tags, releases, insights and /search?q=&repo=. There is none for a file history, a diff alone, a comparison, the graph or a collection: the app addresses those with query parameters on the nearest page, which the website ignores (commits/<ref>?path=, commit/<sha>?view=diff&path=, branches?base=&head=, commits?view=graph, /?collection=<id>).
  • Widgets read /api/v1/metrics (totals.repos, commits, commitsToday, streak, longestStreak, daily), /api/v1/stats as a fallback (no daily figure), /api/v1/activity?perPage=1&type=push and /api/v1/repos/:name.
Files main
Menu

Theme