@zabaca/zbc 0.16.4 → 0.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -52,6 +52,21 @@ export const COLD_HEADER = 'x-walgit-cold'
52
52
  */
53
53
  export const INTERNAL_HEADER = 'x-walgit-internal'
54
54
 
55
+ /**
56
+ * The environment variable a per-request refusal travels down in — from the
57
+ * smart-HTTP handler, through `git http-backend`, to `pre-receive`, which
58
+ * prints it and exits non-zero (`src/rate-limit.ts`).
59
+ *
60
+ * A contract between three files, so it is named once here beside the headers
61
+ * rather than spelled out in each of them. It is per-REQUEST and never part of
62
+ * the container's own environment: it is set by the handler that judged this
63
+ * push, and `src/git-backend.ts` refuses to carry a process-level one, which
64
+ * would refuse every push on the instance with a message written for one
65
+ * client. It reaches the hook as a variable rather than a header because a hook
66
+ * is a process git spawns three levels down, where a request does not reach.
67
+ */
68
+ export const REFUSE_ENV = 'WALGIT_REFUSE'
69
+
55
70
  /** Stripped before the response leaves the Worker — internal, not protocol. */
56
71
  export const INTERNAL_HEADERS = [SERVED_HEADER, REJECT_HEADER, COLD_HEADER] as const
57
72
 
@@ -156,6 +171,18 @@ export const ANNOUNCE_PATH = '/_walgit/announce'
156
171
  */
157
172
  export const SMART_HTTP = /^\/([^/]+)\.git\/(info\/refs|git-upload-pack|git-receive-pack)$/
158
173
 
174
+ /**
175
+ * The Proposal read surface: `GET /<name>.git/proposals` (docs/adr/0018).
176
+ *
177
+ * Group 1 is the repository. Beside `SMART_HTTP` rather than inside it,
178
+ * deliberately: that regex is the git protocol and the Worker CLASSIFIES on it,
179
+ * so a fourth endpoint added there would change what the edge counts as a
180
+ * clone. This is a walgit endpoint that happens to live under the repository's
181
+ * own name, which is what ADR-0018 named it and what makes it discoverable from
182
+ * the URL an agent already has.
183
+ */
184
+ export const PROPOSALS_HTTP = /^\/([^/]+)\.git\/proposals$/
185
+
159
186
  /**
160
187
  * A repo id is one flat segment.
161
188
  *
@@ -171,6 +198,17 @@ export const REPO_ID = /^[A-Za-z0-9][A-Za-z0-9._-]*$/
171
198
  /** A ref name, as git writes it. Full name only: `main` is not a ref. */
172
199
  export const REF_NAME = /^refs\/[A-Za-z0-9._\-/]+$/
173
200
 
201
+ /**
202
+ * A Proposal id: the LAST segment of `refs/walgit/proposals/<target>/<id>`
203
+ * (docs/adr/0018), and therefore one ref segment — no slash, since the split
204
+ * that gives a target its own slashes is what makes the last segment the id.
205
+ *
206
+ * Here beside `REF_NAME` rather than in `src/proposals.ts` because both ends
207
+ * validate it: the container names ids on the announce wire, and the Fan-out
208
+ * has to judge them without importing the container's half of the program.
209
+ */
210
+ export const PROPOSAL_ID = /^[A-Za-z0-9._-]+$/
211
+
174
212
  /** The all-zeroes oid: creation when it is `oldOid`, deletion when `newOid`. */
175
213
  export const ZERO_OID = '0'.repeat(40)
176
214
 
@@ -22,14 +22,22 @@ import type { RefChange } from './wal-index'
22
22
 
23
23
  const repoId = process.argv[2]
24
24
  const payload = process.argv[3]
25
+ /**
26
+ * What each moved branch merged (docs/adr/0018), computed by `post-receive`
27
+ * where the Cache is and passed down as a third JSON argument. Omitted by a
28
+ * deployment not taking Proposals, and by any caller from before this existed.
29
+ */
30
+ const mergedPayload = process.argv[4]
25
31
 
26
32
  async function main(): Promise<void> {
27
- if (!repoId || !payload) throw new Error('usage: announce-main <repo-id> <changes-json>')
33
+ if (!repoId || !payload)
34
+ throw new Error('usage: announce-main <repo-id> <changes-json> [merged-json]')
28
35
  const config = announceConfigFromEnv()
29
36
  // Not an error: the environment can change between the spawn and the start,
30
37
  // and a deployment with no stream configured simply has nothing to tell.
31
38
  if (!config) return
32
- await announce(config, repoId, JSON.parse(payload) as RefChange[])
39
+ const merged = mergedPayload ? (JSON.parse(mergedPayload) as Record<string, string[]>) : {}
40
+ await announce(config, repoId, JSON.parse(payload) as RefChange[], fetch, merged)
33
41
  }
34
42
 
35
43
  main().catch((err) => {
@@ -70,8 +70,15 @@ export async function announce(
70
70
  repoId: string,
71
71
  changes: readonly RefChange[],
72
72
  fetchImpl: typeof fetch = fetch,
73
+ /**
74
+ * What each moved branch MERGED, by ref name (docs/adr/0018) — computed on
75
+ * the push path, where the Cache and the Index both are, and carried here
76
+ * rather than derived, because this file knows about a fetch and nothing
77
+ * about ancestry. Empty on every deployment not taking Proposals.
78
+ */
79
+ merged: Readonly<Record<string, string[]>> = {},
73
80
  ): Promise<boolean> {
74
- const events = eventsFromChanges(repoId, changes)
81
+ const events = eventsFromChanges(repoId, changes, merged)
75
82
  if (events.length === 0) return false
76
83
  // A Reader List lives on the Signer List's ref (docs/adr/0013), so a push
77
84
  // that moved it may have revoked a reader whose socket is open right now.
@@ -12,6 +12,7 @@
12
12
 
13
13
  import * as path from 'node:path'
14
14
 
15
+ import { REFUSE_ENV } from '../shared/protocol'
15
16
  import type { BackendRequest } from './http'
16
17
 
17
18
  export async function runGitHttpBackend(req: BackendRequest): Promise<Response> {
@@ -45,9 +46,20 @@ export async function runGitHttpBackend(req: BackendRequest): Promise<Response>
45
46
  // chain can be broken. A hook that cannot see the store configuration
46
47
  // refuses the push — correct, but a confusing way to discover a typo here.
47
48
  for (const [key, value] of Object.entries(process.env)) {
49
+ // `WALGIT_REFUSE` is per-request and never the process's (see below). One
50
+ // left in the container's own environment would refuse EVERY push on this
51
+ // instance, with a message written for one client, so the process copy is
52
+ // not a source for it.
53
+ if (key === REFUSE_ENV) continue
48
54
  if (key.startsWith('WALGIT_') && value !== undefined) env[key] = value
49
55
  }
50
56
 
57
+ // What the handler decided about THIS request, over what the process was
58
+ // started with — `WALGIT_REFUSE`, the per-source refusal `pre-receive` speaks
59
+ // (`src/rate-limit.ts`). Last, so a per-request verdict is never shadowed by
60
+ // a variable of the same name in the container's own environment.
61
+ Object.assign(env, req.env ?? {})
62
+
51
63
  const child = Bun.spawn(['git', 'http-backend'], {
52
64
  env,
53
65
  stdin: request.body ?? 'ignore',
@@ -18,12 +18,20 @@ import * as fs from 'node:fs'
18
18
  import * as path from 'node:path'
19
19
 
20
20
  import { capabilitiesFrom } from '../shared/capabilities'
21
+ import { REFUSE_ENV, ZERO_OID } from '../shared/protocol'
21
22
  import { announceConfigFromEnv } from './announce'
22
23
  import { appendOnlyEnabled, checkAppendOnly } from './append-only'
23
24
  import { configuredThreshold, isCompactionDue } from './compact'
24
25
  import { checkSize, limitsEnforced, limitsOf, liveBytes } from './limits'
25
26
  import { clearPending, invocationId, markConsumed, readPending, sweepPending } from './pending'
26
27
  import { privateReposEnabled } from './private'
28
+ import {
29
+ checkProposalRefs,
30
+ gitAncestry,
31
+ gitObjectType,
32
+ mergedProposals,
33
+ proposalsEnabled,
34
+ } from './proposals'
27
35
  import {
28
36
  establishSigner,
29
37
  parseRefChanges,
@@ -75,6 +83,25 @@ async function main(): Promise<number> {
75
83
  const stdin = await Bun.stdin.text()
76
84
 
77
85
  if (hook === 'pre-receive') {
86
+ // A refusal the front door already reached, spoken here (`src/rate-limit.ts`).
87
+ //
88
+ // FIRST, above every verdict below it, because it is the only one not about
89
+ // this push's contents: the per-source window was judged before a byte of
90
+ // the pack was read, and re-deciding anything under a verdict that has
91
+ // already been taken would be work spent on a push that is not happening.
92
+ //
93
+ // It arrives as an environment variable rather than as a header because
94
+ // this is a process git spawned three levels down, where a request does not
95
+ // reach — and it is spoken HERE rather than answered as an HTTP status
96
+ // because git reports a status on this route as `RPC failed; HTTP …`, which
97
+ // reads as a transport fault and is retried. On stderr, so git puts it on
98
+ // the sideband as `remote:` lines, exactly as a size cap's refusal arrives.
99
+ const handed = (process.env[REFUSE_ENV] ?? '').trim()
100
+ if (handed !== '') {
101
+ process.stderr.write(`${handed}\n`)
102
+ return 1
103
+ }
104
+
78
105
  // Who signed this push, settled here and handed down. It is read in this
79
106
  // hook because this is the only one git shows the certificate to — the
80
107
  // blob lives in the push's quarantine and is gone by the time the refs
@@ -123,11 +150,23 @@ async function main(): Promise<number> {
123
150
  // the push lands. Here is where a refusal is free; there is where it is
124
151
  // true. See `publishPush`.
125
152
  if (signerListsEnabled()) {
153
+ const claim = (await index()).claim
154
+ // Proposals widen this one verdict and nothing else (docs/adr/0018): a
155
+ // push whose refs are ALL under `refs/walgit/proposals/` is judged by who
156
+ // may READ this name rather than by who may write it. The Reader List
157
+ // comes off the same Claim the Signer List does, so both halves of the
158
+ // question are answered from one reading of the Index.
126
159
  const verdict = checkSignerAllowed(
127
160
  repoId,
128
161
  signer,
129
- (await index()).claim?.signers ?? null,
162
+ claim?.signers ?? null,
130
163
  changes,
164
+ 'pre-receive',
165
+ {
166
+ enabled: proposalsEnabled(),
167
+ privateRepos: privateReposEnabled(process.env),
168
+ readers: claim?.readers ?? null,
169
+ },
131
170
  )
132
171
  if (!verdict.ok) {
133
172
  process.stderr.write(`${verdict.message}\n`)
@@ -135,6 +174,26 @@ async function main(): Promise<number> {
135
174
  }
136
175
  }
137
176
 
177
+ // Is what was pushed into the Proposal namespace a Proposal this host will
178
+ // hold — an existing branch as its target, a target that IS a branch, and a
179
+ // commit at its tip (docs/adr/0018)? Judged on the flag alone and for every
180
+ // pusher, the owner included: append-only means a ref written here can
181
+ // never be removed, so junk is refused before it is stored or never.
182
+ //
183
+ // Above append-only and below the gate for the same reason each of those
184
+ // sits where it does: a stranger who may not push here at all is told that
185
+ // first, and everything after it is about WHAT was pushed.
186
+ if (proposalsEnabled()) {
187
+ const verdict = checkProposalRefs(repoId, changes, {
188
+ refs: (await index()).refs,
189
+ objectType: gitObjectType(gitDir),
190
+ })
191
+ if (!verdict.ok) {
192
+ process.stderr.write(`${verdict.message}\n`)
193
+ return 1
194
+ }
195
+ }
196
+
138
197
  // Append-only, for the same reason at the same moment: a push that will be
139
198
  // refused must not cost an object-store write. git's own deny rules run
140
199
  // after this hook, so leaving it to them would upload a pack nothing will
@@ -267,6 +326,10 @@ async function main(): Promise<number> {
267
326
  : pending
268
327
  const result = await publishPush(store, repoId, toPublish, changes, {
269
328
  signerLists: signerListsEnabled(),
329
+ proposals: {
330
+ enabled: proposalsEnabled(),
331
+ privateRepos: privateReposEnabled(process.env),
332
+ },
270
333
  })
271
334
  if (!result.ok) {
272
335
  process.stderr.write(`${publishRefusal(result)}\n`)
@@ -293,7 +356,14 @@ async function main(): Promise<number> {
293
356
  const events = announceConfigFromEnv()
294
357
  if (events) {
295
358
  const changes = parseRefChanges(stdin).filter((c) => c.ref.startsWith('refs/'))
296
- if (changes.length > 0) spawnAnnounce(repoId, changes)
359
+ // What this push MERGED rides the same announcement (docs/adr/0018), so a
360
+ // Watcher on `main` learns a Proposal landed from the move rather than by
361
+ // reading the Proposal list again. Computed HERE and not in the detached
362
+ // announcer because this is where the Cache and the repository's own
363
+ // environment are — and computed at all only when a branch moved on a
364
+ // deployment taking Proposals, so a push on every other deployment pays
365
+ // nothing.
366
+ if (changes.length > 0) spawnAnnounce(repoId, changes, await mergedForAnnounce(changes))
297
367
  }
298
368
  try {
299
369
  const store = storeFromEnv()
@@ -351,6 +421,35 @@ function publishRefusal(result: Extract<PublishResult, { ok: false }>): string {
351
421
  }
352
422
  }
353
423
 
424
+ /**
425
+ * The Proposals this push merged, per branch it moved — or nothing.
426
+ *
427
+ * Best-effort like everything else in `post-receive`: a failure here costs one
428
+ * announcement its `merged` field, never the push and never the announcement.
429
+ * The refs come from the Index (a Proposal pushed to another node is still this
430
+ * repository's) and ancestry from the Cache, which is the split
431
+ * `GET /<name>.git/proposals` already reads Merged through — a commit this disk
432
+ * does not hold reads as NOT merged, never as merged.
433
+ */
434
+ async function mergedForAnnounce(changes: readonly RefChange[]): Promise<Record<string, string[]>> {
435
+ if (!proposalsEnabled()) return {}
436
+ // A push that moved no branch merged nothing, whatever this repository holds,
437
+ // so the Index is not read at all for a Proposal push or a deletion.
438
+ const moved = changes.some(
439
+ (change) => change.ref.startsWith('refs/heads/') && change.newOid !== ZERO_OID,
440
+ )
441
+ if (!moved) return {}
442
+ try {
443
+ const store = storeFromEnv()
444
+ if (!store) return {}
445
+ const { index } = await loadIndex(store, repoId)
446
+ return mergedProposals(changes, index.refs, gitAncestry(gitDir))
447
+ } catch (err) {
448
+ process.stderr.write(`walgit: merged Proposals not computed: ${(err as Error).message}\n`)
449
+ return {}
450
+ }
451
+ }
452
+
354
453
  /**
355
454
  * Hand the announcement to a detached process and return.
356
455
  *
@@ -366,11 +465,20 @@ function publishRefusal(result: Extract<PublishResult, { ok: false }>): string {
366
465
  * what this would have announced, so a subscriber's next handshake reads it
367
466
  * there anyway.
368
467
  */
369
- function spawnAnnounce(repo: string, changes: readonly RefChange[]): void {
468
+ function spawnAnnounce(
469
+ repo: string,
470
+ changes: readonly RefChange[],
471
+ merged: Readonly<Record<string, string[]>>,
472
+ ): void {
370
473
  try {
371
474
  const child = spawn(
372
475
  process.execPath,
373
- [path.join(import.meta.dir, 'announce-main.ts'), repo, JSON.stringify(changes)],
476
+ [
477
+ path.join(import.meta.dir, 'announce-main.ts'),
478
+ repo,
479
+ JSON.stringify(changes),
480
+ JSON.stringify(merged),
481
+ ],
374
482
  { detached: true, stdio: 'ignore' },
375
483
  )
376
484
  child.unref()
@@ -17,10 +17,12 @@ import {
17
17
  EXPIRE_PATH,
18
18
  HEALTH_PATH,
19
19
  INTERNAL_HEADER,
20
+ PROPOSALS_HTTP,
20
21
  PROVENANCE_PATH,
21
22
  READ_CHALLENGE_SCHEME,
22
23
  READ_VERDICT_PATH,
23
24
  REFS_PATH,
25
+ REFUSE_ENV,
24
26
  REJECT_HEADER,
25
27
  SERVED_HEADER,
26
28
  SMART_HTTP,
@@ -29,6 +31,8 @@ import {
29
31
  import { emptyReadResponse } from './empty-read'
30
32
  import { renderInstructions } from './instructions'
31
33
  import { acceptedNonces, readAllowed, readChallengeNonce, renderReadChallenge } from './private'
34
+ import type { ProposalListing } from './proposals'
35
+ import { countsNewRepos, createSourceLimiter, rateLimitsEnforced, rateLimitsOf } from './rate-limit'
32
36
  import type { ResolvedRepo } from './repo'
33
37
  import { resolveRepo } from './repo'
34
38
  import type { Claim, Provenance } from './wal-index'
@@ -38,6 +42,16 @@ export type BackendRequest = {
38
42
  /** The path git http-backend sees, e.g. `/alpha.git/info/refs`. */
39
43
  pathInfo: string
40
44
  request: Request
45
+ /**
46
+ * Extra environment for THIS request's backend, over the process's own.
47
+ *
48
+ * One thing travels this way today: `WALGIT_REFUSE`, the per-source refusal
49
+ * `pre-receive` speaks (`src/rate-limit.ts`). It is a per-request channel
50
+ * because the verdict is per-request — the handler is the only layer that
51
+ * sees the source the edge attributed the push to, and a hook is a process
52
+ * git spawns three levels down, where a header does not reach.
53
+ */
54
+ env?: Record<string, string>
41
55
  }
42
56
 
43
57
  export type HttpHandlerDeps = {
@@ -112,6 +126,21 @@ export type HttpHandlerDeps = {
112
126
  * a missing log is the one wrong answer this feature can give.
113
127
  */
114
128
  readProvenance?: (repoId: string) => Promise<ProvenanceRead>
129
+ /**
130
+ * The Proposals one repository holds, with `merged` already derived
131
+ * (docs/adr/0018).
132
+ *
133
+ * The derivation is the caller's because it needs two things this module
134
+ * deliberately has none of: the Index, and a synced Cache to ask
135
+ * `merge-base --is-ancestor` of. `src/server.ts` is where those meet, and
136
+ * `listProposals` (`src/proposals.ts`) is the pure part of it.
137
+ *
138
+ * Optional like every other reader here, and absent means the endpoint does
139
+ * not exist rather than answering an empty list — an instance with no store
140
+ * has no authoritative answer, and "this repository has no Proposals" is
141
+ * exactly the wrong thing to invent out of a missing log.
142
+ */
143
+ readProposals?: (repoId: string) => Promise<ProposalListing[]>
115
144
  /**
116
145
  * Read gating for Private repositories (docs/adr/0013), or `undefined` for a
117
146
  * deployment that does none — which is every deployment until an operator
@@ -123,6 +152,11 @@ export type HttpHandlerDeps = {
123
152
  * a gate is the failure this shape makes unrepresentable.
124
153
  */
125
154
  privateReads?: PrivateReads
155
+ /**
156
+ * The clock the per-source window is measured on, injectable so a test can
157
+ * stand still inside one or step over its edge (`src/rate-limit.ts`).
158
+ */
159
+ now?: () => number
126
160
  }
127
161
 
128
162
  /** Everything the Private gate needs, present or absent as a whole. */
@@ -251,6 +285,41 @@ export function createHttpHandler(deps: HttpHandlerDeps): (req: Request) => Prom
251
285
  function createRouter(deps: HttpHandlerDeps): (req: Request) => Promise<Response> {
252
286
  const priv = deps.privateReads
253
287
 
288
+ /**
289
+ * What one source may spend in a window, or `null` on the deployments that
290
+ * bound nothing — which is every deployment until an operator sets a limit.
291
+ *
292
+ * Built ONCE per handler rather than per request: the window is the state,
293
+ * and a limiter constructed per request would remember nothing and refuse
294
+ * nobody. The capabilities are the ones this instance advertises, so the page
295
+ * cannot state a rate limit the push path does not hold.
296
+ */
297
+ const rateLimits = rateLimitsOf(deps.capabilities ?? ADVERTISES_NOTHING)
298
+ const limiter = rateLimitsEnforced(rateLimits) ? createSourceLimiter(rateLimits, deps.now) : null
299
+
300
+ /**
301
+ * Does this push bring a name into existence?
302
+ *
303
+ * From the INDEX, for the reason every other question here is: the disk is a
304
+ * cache and a cold node's empty directory is not evidence. A repository that
305
+ * holds no ref is a name being created, which is the same reading
306
+ * `emptyReadResponse` makes one branch below — pushing is what brings a name
307
+ * into existence, so "holds a ref" is the question and "the directory exists"
308
+ * is not.
309
+ *
310
+ * Asked only where a limit needs the answer, and an Index that cannot be read
311
+ * answers `false`: a store outage must not invent a creation refusal for a
312
+ * repository that has existed for a month.
313
+ */
314
+ async function creatingName(repoId: string): Promise<boolean> {
315
+ if (!countsNewRepos(rateLimits) || !deps.readRefs) return false
316
+ try {
317
+ return Object.keys(await deps.readRefs(repoId)).length === 0
318
+ } catch {
319
+ return false
320
+ }
321
+ }
322
+
254
323
  /**
255
324
  * Refuse this read, or don't — the Private gate, for all three reads
256
325
  * (docs/adr/0013).
@@ -440,6 +509,61 @@ function createRouter(deps: HttpHandlerDeps): (req: Request) => Promise<Response
440
509
  })
441
510
  }
442
511
 
512
+ // What Proposals a repository holds (docs/adr/0018). Beside the provenance
513
+ // read and gated identically — the deployment credential above, then the
514
+ // Read Challenge below — because it answers the same kind of question about
515
+ // the same repository: on a Private name, who proposed what is part of what
516
+ // the Reader List is protecting.
517
+ //
518
+ // It exists only where the deployment OFFERS Proposals. That is the derived
519
+ // capability rather than the raw flag (`shared/capabilities.ts`): a Proposal
520
+ // is a signed push to a name holding a Signer List, so on a deployment
521
+ // without those the namespace is an ordinary one and there is no Proposal to
522
+ // report. An instance that advertises none answers 404 here, which is what
523
+ // "with the flag off it does not exist" means.
524
+ const proposalRoute = PROPOSALS_HTTP.exec(url.pathname)
525
+ if (proposalRoute) {
526
+ const offered = (deps.capabilities ?? ADVERTISES_NOTHING).proposals
527
+ if (!offered || !deps.readProposals || request.method !== 'GET') return NOT_FOUND()
528
+ let repoId: string
529
+ try {
530
+ repoId = resolveRepo(deps.reposDir, proposalRoute[1]!).repoId
531
+ } catch {
532
+ // A bad name is a 404 rather than a challenge for a repository that
533
+ // could not exist, exactly as it is on the git path below.
534
+ return NOT_FOUND()
535
+ }
536
+ if (priv) {
537
+ let claim: Claim | undefined
538
+ try {
539
+ claim = await priv.readClaim(repoId)
540
+ } catch {
541
+ claim = LOCKED
542
+ }
543
+ const refused = await refuseRead(request, url, claim)
544
+ if (refused) return refused
545
+ }
546
+ let proposals: ProposalListing[]
547
+ try {
548
+ proposals = await deps.readProposals(repoId)
549
+ } catch (err) {
550
+ // Refused rather than answered empty. Every other absence here is an
551
+ // ordinary answer, but "this repository has no Proposals" read out of an
552
+ // Index we could not reach is a wrong answer a client cannot tell from a
553
+ // right one — and one an agent would act on by pushing a duplicate.
554
+ return reject(503, 'unavailable', `walgit: ${(err as Error).message}\n`)
555
+ }
556
+ return new Response(`${JSON.stringify({ repo: repoId, proposals })}\n`, {
557
+ headers: {
558
+ 'content-type': 'application/json; charset=utf-8',
559
+ // Every field in it is derived from where refs point right now, and
560
+ // `merged` flips the moment somebody pushes the target. A cached copy
561
+ // is a Proposal reported open after it was accepted.
562
+ 'cache-control': 'no-store',
563
+ },
564
+ })
565
+ }
566
+
443
567
  const route = SMART_HTTP.exec(url.pathname)
444
568
  if (!route) return NOT_FOUND()
445
569
 
@@ -518,6 +642,46 @@ function createRouter(deps: HttpHandlerDeps): (req: Request) => Promise<Response
518
642
  }
519
643
  }
520
644
 
645
+ // What this source has spent in the window, and whether this push fits in
646
+ // what is left (`src/rate-limit.ts`).
647
+ //
648
+ // Only the POST, because only the POST is a push: the advertisement that
649
+ // precedes it hands over nothing and charging it would make every push cost
650
+ // two. Only here, because this is the one layer that sees both the source
651
+ // the edge attributed the request to and the repository it names.
652
+ //
653
+ // The verdict does not become a status code. git reports a 4xx on this
654
+ // route as `RPC failed; HTTP …`, which reads as a transport fault and gets
655
+ // retried — the exact failure the size caps were written to stop being. So
656
+ // the refusal rides down to `pre-receive`, which speaks it as a reject line
657
+ // before a single object is stored.
658
+ let refusal: string | undefined
659
+ if (limiter && route[2] === 'git-receive-pack' && request.method === 'POST') {
660
+ const source = sourceOf(request)
661
+ // Unattributable: a request that reached the container without passing
662
+ // the edge, or a local deployment. Pooling everything walgit cannot name
663
+ // into one bucket would let the first such request throttle every other.
664
+ if (source) {
665
+ let repoId: string | null = null
666
+ try {
667
+ repoId = resolveRepo(deps.reposDir, route[1]!).repoId
668
+ } catch {
669
+ // A name walgit would not serve is a 404 below; nothing is charged
670
+ // for a push that is about to be refused for a different reason.
671
+ repoId = null
672
+ }
673
+ if (repoId !== null) {
674
+ const verdict = limiter.admit({
675
+ source,
676
+ repoId,
677
+ creating: await creatingName(repoId),
678
+ bytes: declaredBytes(request),
679
+ })
680
+ if (!verdict.ok) refusal = verdict.message
681
+ }
682
+ }
683
+ }
684
+
521
685
  let repo
522
686
  try {
523
687
  repo = deps.ensureRepo(resolveRepo(deps.reposDir, route[1]!))
@@ -537,10 +701,47 @@ function createRouter(deps: HttpHandlerDeps): (req: Request) => Promise<Response
537
701
  }
538
702
  }
539
703
 
540
- return deps.runBackend({ repo, pathInfo: url.pathname, request })
704
+ return deps.runBackend({
705
+ repo,
706
+ pathInfo: url.pathname,
707
+ request,
708
+ ...(refusal ? { env: { [REFUSE_ENV]: refusal } } : {}),
709
+ })
541
710
  }
542
711
  }
543
712
 
713
+ /**
714
+ * The client this request is attributed to, or `null` when walgit cannot
715
+ * attribute it.
716
+ *
717
+ * `cf-connecting-ip` first: the container is reachable only through the Worker,
718
+ * and Cloudflare sets that header at the edge over whatever the client sent, so
719
+ * it is the one address here a client cannot choose for itself.
720
+ * `x-forwarded-for` is the fallback for a deployment fronted by something else,
721
+ * and its FIRST entry is the client — the rest are proxies.
722
+ */
723
+ function sourceOf(request: Request): string | null {
724
+ const direct = request.headers.get('cf-connecting-ip')?.trim()
725
+ if (direct) return direct
726
+ const forwarded = request.headers.get('x-forwarded-for')?.split(',')[0]?.trim()
727
+ return forwarded ? forwarded : null
728
+ }
729
+
730
+ /**
731
+ * What this push says it weighs.
732
+ *
733
+ * `content-length`, and a chunked push declares none — which reads as 0 and is
734
+ * charged as 0, deliberately. The exact size of a chunked push is known only
735
+ * once it has been uploaded, and by then the bytes have already been spent;
736
+ * the cap that bounds THAT is the per-push size cap, refused in `pre-receive`
737
+ * on the quarantine pack (`src/limits.ts`). This one bounds the volume a source
738
+ * declares, and a client under-declaring it is refused by the other.
739
+ */
740
+ function declaredBytes(request: Request): number {
741
+ const declared = Number(request.headers.get('content-length') ?? '0')
742
+ return Number.isFinite(declared) && declared > 0 ? declared : 0
743
+ }
744
+
544
745
  /**
545
746
  * The fingerprint this request PROVED, or `null`.
546
747
  *
@@ -16,7 +16,7 @@
16
16
  */
17
17
 
18
18
  import type { Capabilities } from '../shared/capabilities'
19
- import { describeBytes } from '../shared/policy'
19
+ import { describeBytes, describeWindow } from '../shared/policy'
20
20
  import { EVENTS_PATH, PROVENANCE_PATH } from '../shared/protocol'
21
21
 
22
22
  /**
@@ -121,6 +121,22 @@ function facts(caps: Capabilities): string[] {
121
121
  if (caps.maxRepoBytes !== null) {
122
122
  facts.push(`One repository may not exceed ${describeBytes(caps.maxRepoBytes)} in total.`)
123
123
  }
124
+ // What one client may spend, per window (`src/rate-limit.ts`). One line for
125
+ // all three halves rather than one each, because this document is the terse
126
+ // one and pays for every sentence out of a byte budget — the long form is
127
+ // `/llms.txt`.
128
+ if (caps.sourceLimited) {
129
+ const per = `per client per ${describeWindow(caps.rateWindowSeconds)}`
130
+ const parts: string[] = []
131
+ if (caps.maxNewReposPerSource !== null) {
132
+ parts.push(`${caps.maxNewReposPerSource} new repositories`)
133
+ }
134
+ if (caps.maxPushesPerSource !== null) parts.push(`${caps.maxPushesPerSource} pushes`)
135
+ if (caps.maxPushBytesPerSource !== null) {
136
+ parts.push(describeBytes(caps.maxPushBytesPerSource))
137
+ }
138
+ facts.push(`Rate limited: ${parts.join(', ')} ${per}. Waiting it out is the remedy.`)
139
+ }
124
140
 
125
141
  facts.push(
126
142
  'Put a random suffix on the name. Many agents run near-identical prompts at the same time; a plain name is probably taken already, and a taken name means your push is refused.',