@zabaca/zbc 0.17.0 → 0.19.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.
@@ -22,8 +22,9 @@
22
22
  */
23
23
 
24
24
  import type { Capabilities } from './capabilities'
25
+ import type { Operator } from './operator'
25
26
  import { MAX_REFS_PER_ENTRY, MAX_WATCH_ENTRIES } from './events'
26
- import { describeBytes } from './policy'
27
+ import { describeBytes, describeWindow } from './policy'
27
28
  import { CONTENT_SIGNAL } from './robots'
28
29
  import {
29
30
  CHALLENGE_PATH,
@@ -41,7 +42,17 @@ export function wantsLlms(method: string, pathname: string): boolean {
41
42
 
42
43
  const hours = (n: number) => (n === 1 ? '1 hour' : `${n} hours`)
43
44
 
44
- export function renderLlms(host: string, caps: Capabilities): string {
45
+ export function renderLlms(
46
+ host: string,
47
+ caps: Capabilities,
48
+ /**
49
+ * Who runs this deployment (`shared/operator.ts`), passed beside the
50
+ * capabilities for the reason the host is: nothing here branches on it and
51
+ * the push path never sees it. `null` — nobody named — renders the document
52
+ * this host rendered before there was anywhere to name one.
53
+ */
54
+ operator: Operator | null = null,
55
+ ): string {
45
56
  const ws = `wss://${host}${EVENTS_PATH}`
46
57
 
47
58
  const limits: string[] = []
@@ -106,6 +117,33 @@ export function renderLlms(host: string, caps: Capabilities): string {
106
117
  if (caps.maxRepoBytes !== null) {
107
118
  limits.push(`- **One repository may not exceed ${describeBytes(caps.maxRepoBytes)}** in total.`)
108
119
  }
120
+ // What one client may spend, as opposed to how big one thing may be
121
+ // (`src/rate-limit.ts`). Stated here because the reader of this document is
122
+ // exactly the client the limit is about: an agent loop reads it once and then
123
+ // pushes in a pattern it has already decided on, and a limit it learns from a
124
+ // refusal is one it learns halfway through that pattern. Each half is stated
125
+ // only where it is enforced, like every bullet above.
126
+ if (caps.sourceLimited) {
127
+ const window = describeWindow(caps.rateWindowSeconds)
128
+ if (caps.maxNewReposPerSource !== null) {
129
+ limits.push(
130
+ `- **You may create ${caps.maxNewReposPerSource} new repositories per client per ${window}.** Pushing to a name you already created does not count against it.`,
131
+ )
132
+ }
133
+ if (caps.maxPushesPerSource !== null) {
134
+ limits.push(
135
+ `- **You may make ${caps.maxPushesPerSource} pushes per client per ${window}.** Commit locally and push once rather than pushing every commit.`,
136
+ )
137
+ }
138
+ if (caps.maxPushBytesPerSource !== null) {
139
+ limits.push(
140
+ `- **You may push ${describeBytes(caps.maxPushBytesPerSource)} per client per ${window}.**`,
141
+ )
142
+ }
143
+ limits.push(
144
+ `- Each of those is refused in \`pre-receive\`, by a message naming the limit — not a transport failure. Waiting out the ${window} is the remedy; retrying immediately is not.`,
145
+ )
146
+ }
109
147
 
110
148
  /**
111
149
  * The answer to the question the bullet above raises and does not settle: a
@@ -562,13 +600,65 @@ landed — and leaves the field out when it landed none.
562
600
 
563
601
  `
564
602
  : ''
565
- }A Proposal is a push like any other: it is signed, it is append-only, it counts
603
+ }### Ask to be added to a name
604
+
605
+ The Signer List is a target like a branch, and it is the only way to ask for a
606
+ name you are not listed on. Propose the list itself, with your fingerprint line
607
+ added to its \`signers\` file:
608
+
609
+ \`\`\`sh
610
+ git fetch -q https://${host}/$NAME.git refs/walgit/signers
611
+ git checkout -q -B ask FETCH_HEAD
612
+ ssh-keygen -lf $HOME/.ssh/id_ed25519.pub | awk '{print $2}' >> signers
613
+ git add signers && git -c user.email=agent@localhost -c user.name=agent commit -qm ask
614
+ git push --signed=yes https://${host}/$NAME.git HEAD:refs/walgit/proposals/walgit/signers/add-me
615
+ \`\`\`
616
+
617
+ \`walgit/signers\` is the target — the ref with \`refs/\` dropped — and \`add-me\` is
618
+ your own word for the request, as an id always is. It is the one target that is
619
+ not a branch, and every other rule above is unchanged: it is held under
620
+ \`refs/walgit/proposals/\` and moves nothing. \`refs/walgit/signers\` is still
621
+ written only by a key the list already names, so the list changes when a Signer
622
+ accepts your Proposal and not before — and once it has, your next push is judged
623
+ by the list it installed.
624
+
625
+ A Proposal is a push like any other: it is signed, it is append-only, it counts
566
626
  against the name's size caps, and it cannot be deleted or withdrawn. A target
567
- that does not exist, a target that is not a branch, and a tip that is not a
568
- commit are refused before anything is stored.
627
+ that does not exist, a target that is neither a branch nor the Signer List, and
628
+ a tip that is not a commit are refused before anything is stored.
569
629
  `
570
630
  : ''
571
631
 
632
+ /**
633
+ * Who runs this, in the same place and the same order the page states it
634
+ * (`operatorSection`, `shared/landing.ts`): who, then where to write, then
635
+ * what expires on its own.
636
+ *
637
+ * It is the one fact in this document that is not a capability, and an agent
638
+ * asking who is answerable for a host it is about to push somebody else's
639
+ * work to has nowhere else to read it — the page is HTML and this is the
640
+ * document a harness fetches. Absent whole where nothing is configured, like
641
+ * every other section here.
642
+ */
643
+ const whoRuns =
644
+ operator === null
645
+ ? ''
646
+ : `
647
+ ## Who runs this
648
+
649
+ ${[
650
+ operator.name === null ? null : `- **Operator.** ${operator.name} runs this deployment.`,
651
+ operator.contact === null
652
+ ? null
653
+ : `- **Contact.** ${operator.contact} — takedowns, abuse and anything else about this host.`,
654
+ caps.retentionHours === null
655
+ ? null
656
+ : `- **Expiry.** A repository is collected ${hours(caps.retentionHours)} after its last push, whether or not anybody asks. Nothing here is archived.`,
657
+ ]
658
+ .filter((line): line is string => line !== null)
659
+ .join('\n')}
660
+ `
661
+
572
662
  const events = caps.events
573
663
  ? `
574
664
  ## Know when a ref moves, without asking
@@ -668,7 +758,9 @@ the worse failure. Everything else on this host has a public stream.`
668
758
 
669
759
  return `# ${host}
670
760
 
671
- A git host for agents. Push to a name and the repository exists. There is no account to create, no repository to create first, and no API besides git itself.
761
+ agentgit — a git host for AI agents. Push to a name and the repository exists. There is no account to create, no repository to create first, and no API besides git itself.
762
+
763
+ Scratch repositories, and the handoff between two agents: handing work to another agent is the URL, and there is nothing else to send.
672
764
 
673
765
  Smart-HTTP is the only transport.
674
766
 
@@ -725,8 +817,7 @@ the body names the helper, and git prints none of it. Fix it with the one config
725
817
  line from *Keep a name private*, above, and push again.
726
818
  `
727
819
  : ''
728
- }
729
-
820
+ }${whoRuns}
730
821
  ## What this is not
731
822
 
732
823
  Not a forge: no pull requests, no code review, no CI, no issues.${
@@ -0,0 +1,86 @@
1
+ /**
2
+ * Who runs this deployment, and how to reach them.
3
+ *
4
+ * Deliberately NOT a capability (`shared/capabilities.ts`), and the distinction
5
+ * is the same one that keeps the host out of that type: a capability is
6
+ * something the push path enforces and the documents describe, derived from the
7
+ * variables the container is told about. An operator is nobody's capability —
8
+ * it is who is answerable for one — and no code path branches on it. So it is
9
+ * derived here, passed beside the capabilities and the host, and read by the
10
+ * two documents that state it.
11
+ *
12
+ * It is also EDGE-ONLY, and that is why neither variable appears in
13
+ * `CONTAINER_ENV` (`shared/container-env.ts`). Nothing the container serves
14
+ * names an operator, and adding a name there would cost a container restart on
15
+ * every copy edit — `reconcileEnv` replaces the container whenever the
16
+ * forwarded environment's fingerprint changes.
17
+ *
18
+ * Both halves are optional and either may stand alone: a host run by somebody
19
+ * who publishes no address still says who runs it, and an address with no name
20
+ * behind it is still somewhere to send a takedown. What must never happen is a
21
+ * deployment that configured neither printing a placeholder — mail to a name
22
+ * nobody reads is worse than the page admitting there is nobody to write to —
23
+ * which is why nothing configured derives to `null` and the block leaves.
24
+ */
25
+
26
+ /** The variables an operator is read from, and only those. */
27
+ export type OperatorVar = 'WALGIT_OPERATOR' | 'WALGIT_CONTACT'
28
+
29
+ /**
30
+ * An environment named exactly by those variables.
31
+ *
32
+ * What a caller writing a LITERAL should annotate it with — a misspelled name
33
+ * is then a compile error rather than a value quietly read as unset. That is
34
+ * what every fixture in this package is typed as, following `CapabilityEnv`.
35
+ */
36
+ export type OperatorEnv = Partial<Record<OperatorVar, string>>
37
+
38
+ /**
39
+ * Who runs this deployment, with absence spelled `null` on each half rather
40
+ * than as an omitted key — the same rule `Capabilities` follows, for the same
41
+ * reason: an optional field defaults to "off" at a construction site that
42
+ * forgot it.
43
+ */
44
+ export type Operator = {
45
+ /** Who is answerable for this host. */
46
+ name: string | null
47
+ /** Where to write about it — an email address, a URL, or free text. */
48
+ contact: string | null
49
+ }
50
+
51
+ /**
52
+ * Read an environment into who runs it, or `null` for "nobody is named here".
53
+ *
54
+ * Blank collapses to unset, the reading `seedValue` and `containerEnv` already
55
+ * make of a blank variable: a value cleared to an empty string is a line
56
+ * removed from the page, not a line with nothing in it.
57
+ */
58
+ export function operatorFrom(
59
+ env: OperatorEnv | Record<string, string | undefined>,
60
+ ): Operator | null {
61
+ const name = trimmed(env.WALGIT_OPERATOR)
62
+ const contact = trimmed(env.WALGIT_CONTACT)
63
+ if (name === null && contact === null) return null
64
+ return { name, contact }
65
+ }
66
+
67
+ const trimmed = (raw: string | undefined): string | null => {
68
+ if (raw === undefined) return null
69
+ const value = raw.trim()
70
+ return value === '' ? null : value
71
+ }
72
+
73
+ /**
74
+ * Is this contact something a reader can click, and what does it become?
75
+ *
76
+ * Only the two shapes that are unambiguous — an address and an `https`/`http`
77
+ * URL — and anything else stays text. A contact is operator-supplied free text
78
+ * (a Matrix handle, a postal address, "open an issue on GitHub"), and guessing
79
+ * a scheme for it would produce a link that goes nowhere, which is worse than
80
+ * a line somebody has to copy.
81
+ */
82
+ export function contactHref(contact: string): string | null {
83
+ if (/^https?:\/\/\S+$/.test(contact)) return contact
84
+ if (/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(contact)) return `mailto:${contact}`
85
+ return null
86
+ }
@@ -75,3 +75,28 @@ export function seedValue(raw: string | undefined): string | null {
75
75
  const seed = raw.trim()
76
76
  return seed === '' ? null : seed
77
77
  }
78
+
79
+ /**
80
+ * A window in the words both halves state it in.
81
+ *
82
+ * Here for the reason `describeBytes` is: the refusal a push reads
83
+ * (`src/rate-limit.ts`) and the limit the two documents print are the same
84
+ * window, and two spellings of "per hour" would look like two different rules.
85
+ *
86
+ * Whole hours and whole minutes are named as such, because that is how an
87
+ * operator configured it and how a client waits it out. Anything else is stated
88
+ * in seconds rather than rounded into a number somebody would then wait the
89
+ * wrong amount of time on.
90
+ */
91
+ export function describeWindow(seconds: number): string {
92
+ const whole = Math.round(seconds)
93
+ if (whole % 3600 === 0) {
94
+ const hours = whole / 3600
95
+ return hours === 1 ? 'hour' : `${hours} hours`
96
+ }
97
+ if (whole % 60 === 0) {
98
+ const minutes = whole / 60
99
+ return minutes === 1 ? 'minute' : `${minutes} minutes`
100
+ }
101
+ return `${whole} seconds`
102
+ }
@@ -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
 
@@ -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,7 +18,7 @@ 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 { ZERO_OID } from '../shared/protocol'
21
+ import { REFUSE_ENV, ZERO_OID } from '../shared/protocol'
22
22
  import { announceConfigFromEnv } from './announce'
23
23
  import { appendOnlyEnabled, checkAppendOnly } from './append-only'
24
24
  import { configuredThreshold, isCompactionDue } from './compact'
@@ -83,6 +83,25 @@ async function main(): Promise<number> {
83
83
  const stdin = await Bun.stdin.text()
84
84
 
85
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
+
86
105
  // Who signed this push, settled here and handed down. It is read in this
87
106
  // hook because this is the only one git shows the certificate to — the
88
107
  // blob lives in the push's quarantine and is gone by the time the refs
@@ -22,6 +22,7 @@ import {
22
22
  READ_CHALLENGE_SCHEME,
23
23
  READ_VERDICT_PATH,
24
24
  REFS_PATH,
25
+ REFUSE_ENV,
25
26
  REJECT_HEADER,
26
27
  SERVED_HEADER,
27
28
  SMART_HTTP,
@@ -31,6 +32,7 @@ import { emptyReadResponse } from './empty-read'
31
32
  import { renderInstructions } from './instructions'
32
33
  import { acceptedNonces, readAllowed, readChallengeNonce, renderReadChallenge } from './private'
33
34
  import type { ProposalListing } from './proposals'
35
+ import { countsNewRepos, createSourceLimiter, rateLimitsEnforced, rateLimitsOf } from './rate-limit'
34
36
  import type { ResolvedRepo } from './repo'
35
37
  import { resolveRepo } from './repo'
36
38
  import type { Claim, Provenance } from './wal-index'
@@ -40,6 +42,16 @@ export type BackendRequest = {
40
42
  /** The path git http-backend sees, e.g. `/alpha.git/info/refs`. */
41
43
  pathInfo: string
42
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>
43
55
  }
44
56
 
45
57
  export type HttpHandlerDeps = {
@@ -140,6 +152,11 @@ export type HttpHandlerDeps = {
140
152
  * a gate is the failure this shape makes unrepresentable.
141
153
  */
142
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
143
160
  }
144
161
 
145
162
  /** Everything the Private gate needs, present or absent as a whole. */
@@ -268,6 +285,41 @@ export function createHttpHandler(deps: HttpHandlerDeps): (req: Request) => Prom
268
285
  function createRouter(deps: HttpHandlerDeps): (req: Request) => Promise<Response> {
269
286
  const priv = deps.privateReads
270
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
+
271
323
  /**
272
324
  * Refuse this read, or don't — the Private gate, for all three reads
273
325
  * (docs/adr/0013).
@@ -590,6 +642,46 @@ function createRouter(deps: HttpHandlerDeps): (req: Request) => Promise<Response
590
642
  }
591
643
  }
592
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
+
593
685
  let repo
594
686
  try {
595
687
  repo = deps.ensureRepo(resolveRepo(deps.reposDir, route[1]!))
@@ -609,10 +701,47 @@ function createRouter(deps: HttpHandlerDeps): (req: Request) => Promise<Response
609
701
  }
610
702
  }
611
703
 
612
- 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
+ })
613
710
  }
614
711
  }
615
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
+
616
745
  /**
617
746
  * The fingerprint this request PROVED, or `null`.
618
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.',