@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.
@@ -3,8 +3,9 @@
3
3
  * List (docs/adr/0018).
4
4
  *
5
5
  * A Proposal is a ref under `refs/walgit/proposals/<target>/<id>` naming a
6
- * commit its pusher wants in `refs/heads/<target>`, plus the Push Certificate
7
- * behind it, and nothing else. There is no record, no row and no file: whether
6
+ * commit its pusher wants in `refs/heads/<target>` — or in `refs/walgit/signers`,
7
+ * the one non-branch target, which is how a stranger asks to be listed — plus
8
+ * the Push Certificate behind it, and nothing else. There is no record, no row and no file: whether
8
9
  * it is Merged is `merge-base --is-ancestor` against the target, computed on
9
10
  * read from the Cache and never written down.
10
11
  *
@@ -36,7 +37,7 @@
36
37
  */
37
38
 
38
39
  import { flagEnabled } from '../shared/policy'
39
- import { ZERO_OID } from '../shared/protocol'
40
+ import { SIGNERS_REF, ZERO_OID } from '../shared/protocol'
40
41
  import { git } from './git'
41
42
  import type { Provenance, RefChange } from './wal-index'
42
43
 
@@ -51,11 +52,40 @@ export function proposalsEnabled(env: Record<string, string | undefined> = proce
51
52
  */
52
53
  export const PROPOSALS_PREFIX = 'refs/walgit/proposals/'
53
54
 
54
- /** The branch a Proposal wants its commit in, spelled as a ref. */
55
- export const targetRef = (target: string): string => `refs/heads/${target}`
55
+ /**
56
+ * The one target that is not a branch: the Signer List itself (docs/adr/0018).
57
+ *
58
+ * A stranger who may read a claimed name has nothing it can DO about not being
59
+ * listed — the refusal could only tell it what somebody else must push. So the
60
+ * list is proposable like a branch: the stranger pushes the `signers` file with
61
+ * its own fingerprint line added, and a Signer accepts it. The invariant is
62
+ * untouched, because a Proposal moves nothing: `refs/walgit/signers` is still
63
+ * only ever written by a listed key's push.
64
+ *
65
+ * The spelling is the ref with `refs/` dropped, which is the cheapest thing it
66
+ * could be: the id is still the last segment, the "no target begins with
67
+ * `refs/`" refusal is untouched, and `ls-remote` still shows the target without
68
+ * anything being fetched.
69
+ */
70
+ export const SIGNERS_TARGET = 'walgit/signers'
71
+
72
+ /**
73
+ * The ref a Proposal wants its commit in.
74
+ *
75
+ * `refs/heads/<target>` for every target but one, and the exception is exact:
76
+ * `walgit/signers/deeper` is an ordinary branch name and is resolved as one, so
77
+ * the Signer List cannot be reached by a target that merely starts with its
78
+ * spelling.
79
+ */
80
+ export const targetRef = (target: string): string =>
81
+ target === SIGNERS_TARGET ? SIGNERS_REF : `refs/heads/${target}`
56
82
 
57
83
  export interface Proposal {
58
- /** The branch this Proposal is for, WITHOUT the `refs/heads/` prefix. */
84
+ /**
85
+ * What this Proposal is for: a branch WITHOUT its `refs/heads/` prefix, or
86
+ * `walgit/signers` for the Signer List. `targetRef` is the one place that
87
+ * knows which.
88
+ */
59
89
  target: string
60
90
  /** The pusher's word. The host assigns nothing and collisions are refused. */
61
91
  id: string
@@ -121,9 +151,11 @@ export function gitObjectType(gitDir: string): (oid: string) => string | null {
121
151
  export type ProposalRefusal =
122
152
  /** The ref is in the namespace and names no `<target>/<id>`. */
123
153
  | 'grammar'
124
- /** `refs/heads/<target>` is not a ref this repository holds. */
154
+ /** The target's ref — `refs/heads/<target>`, or the Signer List — is not one
155
+ * this repository holds. */
125
156
  | 'missing-target'
126
- /** The target is not a branch — it names something outside `refs/heads/`. */
157
+ /** The target is neither a branch nor `walgit/signers`: it names something
158
+ * outside `refs/heads/`. */
127
159
  | 'not-a-branch'
128
160
  /** The tip is a tree, a blob, a tag, or an object the host cannot see. */
129
161
  | 'not-a-commit'
@@ -162,7 +194,7 @@ export function checkProposalRefs(
162
194
  repoId,
163
195
  'not-a-branch',
164
196
  change.ref,
165
- `its target \`${proposal.target}\` is not a branch — a Proposal names one under refs/heads/`,
197
+ `its target \`${proposal.target}\` is not a branch — a Proposal names one under refs/heads/, or \`${SIGNERS_TARGET}\` for the Signer List`,
166
198
  )
167
199
  }
168
200
 
@@ -206,13 +238,17 @@ function rejectionMessage(repoId: string, ref: string, why: string): string {
206
238
  return [
207
239
  `walgit: refused — ${ref} is not a Proposal ${repoId} can hold: ${why}.`,
208
240
  '',
209
- 'A Proposal is a ref naming the commit you want in an existing branch:',
241
+ 'A Proposal is a ref naming the commit you want in a branch that already',
242
+ "exists here — or in this name's Signer List:",
210
243
  '',
211
244
  ` git push --signed=yes origin HEAD:${PROPOSALS_PREFIX}<branch>/<your-id>`,
212
245
  '',
213
246
  'The branch is the one you want it merged into and must already exist here;',
214
247
  'the id is your own word for this change, and a taken one is refused as a',
215
- 'non-fast-forward, so pick another. Refs here are append-only like every',
248
+ 'non-fast-forward, so pick another. To ask to be added to this name instead,',
249
+ `propose its Signer List: the same push with \`${SIGNERS_TARGET}\` where the branch`,
250
+ `goes, carrying ${SIGNERS_REF}'s \`signers\` file with your fingerprint added.`,
251
+ 'Refs here are append-only like every',
216
252
  'other, which is why a Proposal is judged before it is stored rather than',
217
253
  'after.',
218
254
  '',
@@ -0,0 +1,264 @@
1
+ /**
2
+ * Per-source rate limits: bound what one visitor can spend, in a window.
3
+ *
4
+ * The size caps beside this file (`src/limits.ts`) bound how big a push may be.
5
+ * They say nothing about how OFTEN one may arrive, and the two are different
6
+ * failures: a hundred 1 MiB pushes are each individually fine, and a hundred
7
+ * new names are each individually free. One container serves every repository
8
+ * (`wrangler.jsonc`, `max_instances: 1`), so a bored visitor filling the bucket
9
+ * during a traffic spike is not merely storage — it is the queue everyone else
10
+ * is behind.
11
+ *
12
+ * ── where the verdict is reached, and where it is spoken ────────────────────
13
+ *
14
+ * Reached in `src/http.ts`, because that is the only place that sees BOTH the
15
+ * source the edge attributed the request to and the repository it names: the
16
+ * hooks are processes git spawns, three down, and a header does not reach them.
17
+ * Spoken by `pre-receive`, because a refusal at the HTTP layer is a status code
18
+ * git reports as `RPC failed; HTTP …` — a transport fault, which a client
19
+ * retries. The handler therefore hands the backend a refusal and the hook
20
+ * prints it, so an over-limit push reads exactly the way an oversized one does:
21
+ * a `remote:` reject line naming the limit and what to do next.
22
+ *
23
+ * ── what a "source" is ──────────────────────────────────────────────────────
24
+ *
25
+ * Whatever the Worker can see, which is the client IP (`cf-connecting-ip`, set
26
+ * by Cloudflare at the edge and not forgeable by a client, since the container
27
+ * is reachable only through the Worker). A request carrying no such header is
28
+ * unattributable — a direct request to the container, a local deployment — and
29
+ * is NOT limited: pooling everything walgit cannot name into one bucket would
30
+ * make the first unattributable request throttle every other one.
31
+ *
32
+ * ── the counters are in memory, deliberately ────────────────────────────────
33
+ *
34
+ * A window that a container restart forgets. The alternative is a round trip to
35
+ * the object store on every push to enforce a limit whose entire purpose is to
36
+ * make a spike cheap, and the failure direction of forgetting is a visitor
37
+ * getting one more window than it should — against a Durable Object write per
38
+ * push, forever, on every deployment that turned this on. The table is capped
39
+ * so a spike of distinct addresses cannot grow it without bound.
40
+ *
41
+ * Every limit is UNSET by default, and an unset one is not enforced and not
42
+ * advertised — `capabilitiesFrom` (`shared/capabilities.ts`) is the one reading
43
+ * both this file and the three documents take their numbers from.
44
+ */
45
+
46
+ import type { Capabilities } from '../shared/capabilities'
47
+ import { describeBytes, describeWindow } from '../shared/policy'
48
+
49
+ export interface RateLimits {
50
+ /** The window every count below is taken over, in milliseconds. */
51
+ windowMs: number
52
+ /** New repository names one source may create per window. `null` is unlimited. */
53
+ maxNewRepos: number | null
54
+ /** Pushes one source may make per window. `null` is unlimited. */
55
+ maxPushes: number | null
56
+ /** Bytes one source may push per window. `null` is unlimited. */
57
+ maxPushBytes: number | null
58
+ }
59
+
60
+ /**
61
+ * The limits this instance enforces, as the four of the capabilities this file
62
+ * cares about — a projection, exactly as `limitsOf` is, so the number a page
63
+ * prints and the number a push is refused on cannot be arrived at two ways.
64
+ */
65
+ export function rateLimitsOf(caps: Capabilities): RateLimits {
66
+ return {
67
+ windowMs: caps.rateWindowSeconds * 1000,
68
+ maxNewRepos: caps.maxNewReposPerSource,
69
+ maxPushes: caps.maxPushesPerSource,
70
+ maxPushBytes: caps.maxPushBytesPerSource,
71
+ }
72
+ }
73
+
74
+ /** Is there anything to count? Nothing is tracked when there isn't. */
75
+ export function rateLimitsEnforced(limits: RateLimits): boolean {
76
+ return limits.maxNewRepos !== null || limits.maxPushes !== null || limits.maxPushBytes !== null
77
+ }
78
+
79
+ /** Does any configured limit need to know whether the name is a new one? */
80
+ export function countsNewRepos(limits: RateLimits): boolean {
81
+ return limits.maxNewRepos !== null
82
+ }
83
+
84
+ export type RateKind = 'new-repos' | 'pushes' | 'push-bytes'
85
+
86
+ export type RateVerdict = { ok: true } | { ok: false; kind: RateKind; message: string }
87
+
88
+ export interface RateCharge {
89
+ /** The client the edge attributed this request to. */
90
+ source: string
91
+ /** The repository this push names. */
92
+ repoId: string
93
+ /** Does this push bring a name into existence? */
94
+ creating: boolean
95
+ /** Bytes this push declared, or 0 when it declared none. */
96
+ bytes: number
97
+ }
98
+
99
+ /**
100
+ * How many sources one instance remembers at once.
101
+ *
102
+ * A bound rather than a tuning knob: this table is fed by whoever shows up, so
103
+ * an unbounded one is a memory leak an attacker chooses the size of. When it is
104
+ * full the least recently seen source is dropped — which forgives it, the same
105
+ * direction a restart forgives in, and the one that cannot refuse an innocent
106
+ * client because somebody else arrived.
107
+ */
108
+ const MAX_SOURCES = 10_000
109
+
110
+ type Spend = { at: number; bytes: number; creating: boolean }
111
+
112
+ export interface SourceLimiter {
113
+ /** Judge one push and, when it is allowed, charge it to its source. */
114
+ admit(charge: RateCharge): RateVerdict
115
+ }
116
+
117
+ /**
118
+ * The window, as a table of what each source spent in it.
119
+ *
120
+ * Charged only for pushes it ALLOWS. A refused push costs the client nothing
121
+ * further, so a client that keeps retrying is refused on the same spend rather
122
+ * than digging a deeper hole it cannot see the bottom of — and the window
123
+ * therefore always describes traffic walgit actually served.
124
+ */
125
+ export function createSourceLimiter(
126
+ limits: RateLimits,
127
+ now: () => number = Date.now,
128
+ ): SourceLimiter {
129
+ const spends = new Map<string, Spend[]>()
130
+
131
+ return {
132
+ admit(charge) {
133
+ const at = now()
134
+ const since = at - limits.windowMs
135
+
136
+ // Re-inserted on every touch, so Map iteration order is least-recently
137
+ // seen first and the eviction below drops the right one.
138
+ const previous = spends.get(charge.source)
139
+ spends.delete(charge.source)
140
+ const window = (previous ?? []).filter((spend) => spend.at > since)
141
+
142
+ const verdict = judge(limits, window, charge)
143
+ if (verdict.ok) window.push({ at, bytes: charge.bytes, creating: charge.creating })
144
+
145
+ if (window.length > 0) {
146
+ spends.set(charge.source, window)
147
+ if (spends.size > MAX_SOURCES) {
148
+ const oldest = spends.keys().next()
149
+ if (!oldest.done) spends.delete(oldest.value)
150
+ }
151
+ }
152
+ return verdict
153
+ },
154
+ }
155
+ }
156
+
157
+ /**
158
+ * Judge one push against a source's window.
159
+ *
160
+ * Creation is judged FIRST, and the reason is the same one that puts the
161
+ * per-push size cap ahead of the per-repository one: when a push trips both, the
162
+ * actionable message is the one about the thing the client chose to do. "You
163
+ * have created enough new names" tells it to push to a name it already has;
164
+ * "you have pushed enough" would send it away from the host entirely for a
165
+ * push that would have been fine under a name it already owns.
166
+ */
167
+ function judge(limits: RateLimits, window: Spend[], charge: RateCharge): RateVerdict {
168
+ const window_ = describeWindow(limits.windowMs / 1000)
169
+
170
+ if (charge.creating && limits.maxNewRepos !== null) {
171
+ const created = window.filter((spend) => spend.creating).length
172
+ if (created >= limits.maxNewRepos) {
173
+ return {
174
+ ok: false,
175
+ kind: 'new-repos',
176
+ message: tooManyNewRepos(charge.repoId, limits.maxNewRepos, window_),
177
+ }
178
+ }
179
+ }
180
+
181
+ if (limits.maxPushes !== null && window.length >= limits.maxPushes) {
182
+ return { ok: false, kind: 'pushes', message: tooManyPushes(limits.maxPushes, window_) }
183
+ }
184
+
185
+ if (limits.maxPushBytes !== null) {
186
+ const spent = window.reduce((total, spend) => total + spend.bytes, 0)
187
+ if (spent + charge.bytes > limits.maxPushBytes) {
188
+ return {
189
+ ok: false,
190
+ kind: 'push-bytes',
191
+ message: tooManyBytes(spent, charge.bytes, limits.maxPushBytes, window_),
192
+ }
193
+ }
194
+ }
195
+
196
+ return { ok: true }
197
+ }
198
+
199
+ /**
200
+ * Product copy, and the same discipline the size caps are written with: say
201
+ * which limit, say the number, and say the one thing to do next. A rate limit
202
+ * is the refusal most likely to be read by something that will simply try
203
+ * again, so each message states that waiting is the remedy and roughly what
204
+ * for.
205
+ */
206
+ function tooManyNewRepos(repoId: string, cap: number, window: string): string {
207
+ return [
208
+ `walgit: refused — ${repoId} would be your ${cap + 1}${ordinal(cap + 1)} new repository this ${window}.`,
209
+ '',
210
+ `This host lets one client create ${cap} ${plural(cap, 'repository', 'repositories')} per ${window}.`,
211
+ 'This is a walgit limit, not a network failure. Retrying now will be refused',
212
+ 'again in the same way.',
213
+ '',
214
+ 'What you can do instead:',
215
+ ` - push to a name you already created — the limit is on NEW names, not on pushes`,
216
+ ` - or wait out the ${window} and push again`,
217
+ '',
218
+ 'Nothing was uploaded; no repository was created.',
219
+ ].join('\n')
220
+ }
221
+
222
+ function tooManyPushes(cap: number, window: string): string {
223
+ return [
224
+ `walgit: refused — you have already made ${cap} ${plural(cap, 'push', 'pushes')} this ${window}.`,
225
+ '',
226
+ `This host lets one client push ${cap} ${plural(cap, 'time', 'times')} per ${window}.`,
227
+ 'This is a walgit limit, not a network failure. Retrying now will be refused',
228
+ 'again in the same way.',
229
+ '',
230
+ 'What you can do instead:',
231
+ ' - combine your work into fewer pushes: commit locally, then push once',
232
+ ` - or wait out the ${window} and push again`,
233
+ '',
234
+ 'Nothing was uploaded; the repository is unchanged.',
235
+ ].join('\n')
236
+ }
237
+
238
+ function tooManyBytes(spent: number, bytes: number, cap: number, window: string): string {
239
+ return [
240
+ `walgit: refused — this push would take you past ${describeBytes(cap)} pushed this ${window}.`,
241
+ '',
242
+ `You have pushed ${describeBytes(spent)} in the last ${window} and this push adds`,
243
+ `${describeBytes(bytes)}.`,
244
+ 'This is a walgit limit, not a network failure. Retrying now will be refused',
245
+ 'again in the same way.',
246
+ '',
247
+ 'What you can do instead:',
248
+ ' - push less at once, or leave large files out of the repository entirely',
249
+ ` - or wait out the ${window} and push again`,
250
+ '',
251
+ 'Nothing was uploaded; the repository is unchanged.',
252
+ ].join('\n')
253
+ }
254
+
255
+ const plural = (n: number, one: string, many: string) => (n === 1 ? one : many)
256
+
257
+ /** `1st`, `2nd`, `3rd`, `4th` — the suffix only, so the number reads naturally. */
258
+ function ordinal(n: number): string {
259
+ if (n % 100 >= 11 && n % 100 <= 13) return 'th'
260
+ if (n % 10 === 1) return 'st'
261
+ if (n % 10 === 2) return 'nd'
262
+ if (n % 10 === 3) return 'rd'
263
+ return 'th'
264
+ }
@@ -149,6 +149,11 @@ console.log(
149
149
  `retentionHours=${caps.retentionHours ?? 'off'} ` +
150
150
  `maxPush=${caps.maxPushBytes ?? 'unset'} maxRepo=${caps.maxRepoBytes ?? 'unset'} ` +
151
151
  `private=${caps.namesCanBePrivate} ` +
152
+ `perSource=${
153
+ caps.sourceLimited
154
+ ? `${caps.maxNewReposPerSource ?? '-'} repos/${caps.maxPushesPerSource ?? '-'} pushes/${caps.maxPushBytesPerSource ?? '-'} bytes per ${caps.rateWindowSeconds}s`
155
+ : 'off'
156
+ } ` +
152
157
  `store=${store ? 'configured' : 'MISSING'}`,
153
158
  )
154
159
 
@@ -51,7 +51,7 @@ import { SIGNERS_REF, ZERO_OID } from '../shared/protocol'
51
51
  import { suggestName } from './append-only'
52
52
  import { git } from './git'
53
53
  import { readAllowed } from './private'
54
- import { isProposalRef } from './proposals'
54
+ import { PROPOSALS_PREFIX, SIGNERS_TARGET, isProposalRef } from './proposals'
55
55
  import { certificatePresented, signedPushEnabled, type PushCertEnv } from './push-cert'
56
56
  import type { RefChange } from './wal-index'
57
57
 
@@ -602,10 +602,26 @@ function mayPropose(
602
602
  claimed: readonly string[],
603
603
  changes: readonly RefChange[],
604
604
  proposals: ProposalGate,
605
+ ): boolean {
606
+ if (changes.length === 0 || !changes.every((c) => isProposalRef(c.ref))) return false
607
+ return proposalsOpenTo(signer, claimed, proposals)
608
+ }
609
+
610
+ /**
611
+ * The same three conditions minus the refs, so the refusal can ask whether this
612
+ * pusher has the Proposal door at all before offering it one.
613
+ *
614
+ * Split rather than duplicated: a remedy naming a door this deployment does not
615
+ * open, or one this key would be refused at, is worse than the terse remedy it
616
+ * replaces — an agent acts on it and is refused a second time.
617
+ */
618
+ function proposalsOpenTo(
619
+ signer: PushSigner,
620
+ claimed: readonly string[],
621
+ proposals: ProposalGate,
605
622
  ): boolean {
606
623
  if (!proposals.enabled) return false
607
624
  if (signer.kind !== 'signed') return false
608
- if (changes.length === 0 || !changes.every((c) => isProposalRef(c.ref))) return false
609
625
  return readAllowed({
610
626
  enabled: proposals.privateRepos,
611
627
  claim: {
@@ -676,7 +692,13 @@ export function checkSignerAllowed(
676
692
  return {
677
693
  ok: false,
678
694
  kind: signer.kind === 'signed' ? 'not-listed' : signer.kind,
679
- message: heldMessage(repoId, signer, changes, stage),
695
+ message: heldMessage(
696
+ repoId,
697
+ signer,
698
+ changes,
699
+ stage,
700
+ proposalsOpenTo(signer, claimed, proposals),
701
+ ),
680
702
  }
681
703
  }
682
704
 
@@ -689,12 +711,20 @@ export function checkSignerAllowed(
689
711
  * (docs/adr/0012). So this says three things and an agent can act on each: the
690
712
  * name is held, here is a free one to use instead, and here is how to be added
691
713
  * to this one.
714
+ *
715
+ * `canPropose` decides whether the third of those is something the READER can
716
+ * do or only something somebody else can. Where Proposals are open to this key
717
+ * (docs/adr/0018), the remedy leads with proposing the Signer List — the one
718
+ * remedy a stranger can act on alone — and keeps the grant recipe under it,
719
+ * because the grant is still what lands. Where they are not, the line is left
720
+ * out entirely: a door that 404s is worse than the terse remedy it replaces.
692
721
  */
693
722
  function heldMessage(
694
723
  repoId: string,
695
724
  signer: PushSigner,
696
725
  changes: readonly RefChange[],
697
726
  stage: GateStage,
727
+ canPropose: boolean,
698
728
  ): string {
699
729
  const why =
700
730
  signer.kind === 'signed'
@@ -755,6 +785,17 @@ function heldMessage(
755
785
  '',
756
786
  'What you can do instead:',
757
787
  ` - push to a free name: git remote set-url origin <same-host>/${suggestName(repoId)}.git`,
788
+ ...(canPropose
789
+ ? [
790
+ " - or ask to be added, yourself: propose this name's Signer List — commit",
791
+ ` ${SIGNERS_REF}'s \`signers\` file with the line \`ssh-keygen -lf <your-key>\``,
792
+ ' prints added, and push it as a Proposal:',
793
+ '',
794
+ ` git push --signed=yes origin HEAD:${PROPOSALS_PREFIX}${SIGNERS_TARGET}/<your-id>`,
795
+ '',
796
+ ' That moves nothing: it is held until a listed key merges it.',
797
+ ]
798
+ : []),
758
799
  ` - or be added to this one: a listed key pushes a commit on ${SIGNERS_REF}`,
759
800
  ' whose `signers` file gains the line `ssh-keygen -lf <your-key>` prints.',
760
801
  ' A grant governs the NEXT push, so retry once theirs has landed.',
@@ -28,11 +28,12 @@
28
28
  import { Container, getContainer } from '@cloudflare/containers'
29
29
 
30
30
  import { capabilitiesFrom, type Capabilities } from '../shared/capabilities'
31
- import { containerEnv, fingerprintEnv } from '../shared/container-env'
31
+ import { containerEnv, fingerprintEnv, reconcileContainerEnv } from '../shared/container-env'
32
32
  import { parseTokens } from '../shared/credentials'
33
33
  import { authorizeAnnounce, authorizeSubscribe } from '../shared/events'
34
34
  import { renderLanding, wantsLanding } from '../shared/landing'
35
35
  import { renderLlms, wantsLlms } from '../shared/llms'
36
+ import { operatorFrom } from '../shared/operator'
36
37
  import { renderRobots, wantsRobots } from '../shared/robots'
37
38
  import {
38
39
  ANNOUNCE_PATH,
@@ -53,6 +54,15 @@ import { BROADCAST_PATH, EVENTS_OBJECT_NAME, WalgitEvents } from './events-do'
53
54
 
54
55
  export interface Env {
55
56
  WALGIT_CONTAINER: DurableObjectNamespace<WalgitContainer>
57
+ /**
58
+ * The commit this Worker was deployed from, set by the cloudflare module's
59
+ * `deployIdVar`. Nothing reads it: it exists so that a deploy which changes
60
+ * only the container image still changes the environment the container is
61
+ * fingerprinted on, and `reconcileEnv` below replaces the running container
62
+ * (shared/container-env.ts). Absent on a deployment that does not set
63
+ * `deployIdVar`, which then behaves exactly as before.
64
+ */
65
+ WALGIT_BUILD_ID?: string
56
66
  /** Comma-separated bearer tokens; git sends one as the Basic-auth password. */
57
67
  WALGIT_HTTP_TOKENS?: string
58
68
  /** The write-ahead log's home — see src/store-env.ts. */
@@ -75,6 +85,16 @@ export interface Env {
75
85
  WALGIT_RETENTION_HOURS?: string
76
86
  WALGIT_MAX_PUSH_BYTES?: string
77
87
  WALGIT_MAX_REPO_BYTES?: string
88
+ /**
89
+ * What one source may spend in a window (src/rate-limit.ts). All off unless
90
+ * set; the window defaults when a count is set without one. Forwarded to the
91
+ * container, which is where the verdict is reached — this side only states
92
+ * them on the two documents below.
93
+ */
94
+ WALGIT_RATE_WINDOW_SECONDS?: string
95
+ WALGIT_MAX_NEW_REPOS_PER_SOURCE?: string
96
+ WALGIT_MAX_PUSHES_PER_SOURCE?: string
97
+ WALGIT_MAX_PUSH_BYTES_PER_SOURCE?: string
78
98
  /**
79
99
  * Where request-level telemetry goes — the half of observability the log
80
100
  * cannot produce (shared/telemetry.ts). Optional: a deployment without the
@@ -117,6 +137,18 @@ export interface Env {
117
137
  * default, and a secret.
118
138
  */
119
139
  WALGIT_PRIVATE_REPOS?: string
140
+ /**
141
+ * Who runs this deployment, and where to write about it
142
+ * (`shared/operator.ts`). Read ONLY through `operatorFrom`, like the policy
143
+ * above is read only through `capabilitiesFrom`.
144
+ *
145
+ * Deliberately absent from `CONTAINER_ENV`: nothing the container serves
146
+ * names an operator, and a name there would cost a container restart on
147
+ * every copy edit. Unset means the two edge documents carry no operator
148
+ * block at all, rather than a placeholder nobody reads.
149
+ */
150
+ WALGIT_OPERATOR?: string
151
+ WALGIT_CONTACT?: string
120
152
  WALGIT_EVENTS: DurableObjectNamespace<WalgitEvents>
121
153
  }
122
154
 
@@ -167,51 +199,48 @@ export class WalgitContainer extends Container<Env> {
167
199
  }
168
200
 
169
201
  /**
170
- * Replace the container if it is running an environment this deploy changed.
171
- *
172
- * `envVars` above is re-read on every Durable Object construction, and a
173
- * `wrangler deploy` constructs a new one — so this side is never stale. The
174
- * container is: it read `process.env` once at start and cannot be told
175
- * anything afterwards, and a vars-only deploy produces no new container image
176
- * for `--containers-rollout immediate` to roll. Without this, the new value
177
- * takes effect whenever the container next happens to idle out, which under
178
- * sustained traffic is never.
202
+ * Bind this Durable Object to `reconcileContainerEnv`'s rules.
179
203
  *
180
- * The fingerprint is persisted in Durable Object storage because that is the
181
- * only state that survives the very event being detected — a redeploy
182
- * discards every in-memory field, so an in-memory copy would compare the new
183
- * environment against itself and always agree.
204
+ * The decision — and the two orderings that matter, no-record-is-a-mismatch
205
+ * and record-only-after-a-successful-destroy — lives in
206
+ * `shared/container-env.ts`, where it can be tested without a Workers
207
+ * runtime. What is left here is exactly the three things only this side can
208
+ * do: reach the container, reach Durable Object storage, and log.
184
209
  */
185
210
  private async reconcileEnv(): Promise<void> {
186
211
  const current = fingerprintEnv(this.envVars ?? {})
187
- const booted = await this.ctx.storage.get<string>(ENV_FINGERPRINT_KEY)
188
- if (booted === current) return
212
+ let booted: string | undefined
213
+ // Captured so the port's getter below reads `this` Durable Object's state
214
+ // rather than the object literal's.
215
+ const state = this.ctx
216
+
217
+ const outcome = await reconcileContainerEnv(
218
+ {
219
+ // A getter, not a snapshot: it is read after the storage lookup above
220
+ // it, exactly where the original code read it.
221
+ get running() {
222
+ return state.container?.running ?? false
223
+ },
224
+ read: async () => {
225
+ booted = await state.storage.get<string>(ENV_FINGERPRINT_KEY)
226
+ return booted
227
+ },
228
+ // SIGKILL rather than a graceful stop: the container serves git over
229
+ // HTTP and holds nothing worth draining — every durable effect of a
230
+ // push is in the log before it is acknowledged (docs/adr/0007) — and
231
+ // `sleepAfter` already covers the polite path. `destroy` triggers
232
+ // `onStop`; the next `containerFetch` starts a fresh one.
233
+ destroy: () => this.destroy(),
234
+ write: (fingerprint) => state.storage.put(ENV_FINGERPRINT_KEY, fingerprint),
235
+ },
236
+ current,
237
+ )
189
238
 
190
- // Only a RUNNING container can be stale. A stopped one has nothing to
191
- // replace: its next start reads `envVars` as it now is, which is already
192
- // the new environment.
193
- //
194
- // No recorded fingerprint counts as a mismatch rather than as a fresh
195
- // start, deliberately. A running container with no record predates this
196
- // code, so what it booted with is unknowable — and on the deploy that
197
- // ships this, that container is exactly the one already serving a
198
- // superseded policy. Assuming it is current would leave the bug live
199
- // until the next idle. A DO that has never started a container reaches
200
- // here with `running` false and simply records.
201
- if (this.ctx.container?.running) {
202
- // SIGKILL rather than a graceful stop: the container serves git over
203
- // HTTP and holds nothing worth draining — every durable effect of a push
204
- // is in the log before it is acknowledged (docs/adr/0007) — and
205
- // `sleepAfter` already covers the polite path. `destroy` triggers
206
- // `onStop`; the next `containerFetch` starts a fresh one.
207
- await this.destroy()
239
+ if (outcome === 'replaced') {
208
240
  console.log(
209
241
  `walgit container env changed (${booted ?? 'unrecorded'} -> ${current}); container replaced`,
210
242
  )
211
243
  }
212
- // Written last, and only after a successful destroy: recording first would
213
- // make a failed replacement look reconciled forever.
214
- await this.ctx.storage.put(ENV_FINGERPRINT_KEY, current)
215
244
  }
216
245
 
217
246
  async fetch(request: Request): Promise<Response> {
@@ -252,6 +281,10 @@ export default {
252
281
  // and the socket cannot describe three different deployments — they used
253
282
  // to read the environment three times, and only the size caps were shared.
254
283
  const caps = capabilitiesFrom(env)
284
+ // Who is answerable for this deployment (`shared/operator.ts`). Derived
285
+ // beside the capabilities and passed to both documents, so the page and
286
+ // the manual cannot name two different operators.
287
+ const operator = operatorFrom(env)
255
288
 
256
289
  // The browser half of `/`, answered at the edge (shared/landing.ts). Placed
257
290
  // before every other decision on purpose: a link on an aggregator points at
@@ -264,7 +297,7 @@ export default {
264
297
  // them: this document and `/llms.txt` want a bare hostname they prefix
265
298
  // with `https://`/`wss://` themselves, while `GET /` needs a full origin
266
299
  // including the scheme, and one field could not serve both.
267
- const page = renderLanding(url.host, caps)
300
+ const page = renderLanding(url.host, caps, operator)
268
301
  const bytes = new TextEncoder().encode(page)
269
302
  record(env, ctx, {
270
303
  kind: 'landing',
@@ -305,7 +338,7 @@ export default {
305
338
  // `/llms.txt` is not reachable as a repo route even for a repository called
306
339
  // `llms.txt`.
307
340
  if (wantsLlms(request.method, url.pathname)) {
308
- const doc = renderLlms(url.host, caps)
341
+ const doc = renderLlms(url.host, caps, operator)
309
342
  const bytes = new TextEncoder().encode(doc)
310
343
  record(env, ctx, {
311
344
  kind: 'landing',