@zabaca/zbc 0.12.0 → 0.13.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.
Files changed (73) hide show
  1. package/CHANGELOG.md +63 -0
  2. package/package.json +2 -1
  3. package/templates/apps/inbox/package.json +1 -1
  4. package/templates/apps/walgit/CONTEXT.md +135 -0
  5. package/templates/apps/walgit/Dockerfile +40 -18
  6. package/templates/apps/walgit/README.md +518 -55
  7. package/templates/apps/walgit/e2e/README.md +100 -6
  8. package/templates/apps/walgit/e2e/harness.ts +262 -1
  9. package/templates/apps/walgit/e2e/live.ts +588 -0
  10. package/templates/apps/walgit/e2e/scenarios.ts +367 -5
  11. package/templates/apps/walgit/e2e/suite.ts +5 -5
  12. package/templates/apps/walgit/examples/watch.ts +209 -0
  13. package/templates/apps/walgit/package.json +12 -3
  14. package/templates/apps/walgit/registry.json +6 -11
  15. package/templates/apps/walgit/shared/capabilities.ts +189 -0
  16. package/templates/apps/walgit/shared/container-env.ts +114 -0
  17. package/templates/apps/walgit/shared/credentials.ts +81 -0
  18. package/templates/apps/walgit/shared/events.ts +277 -0
  19. package/templates/apps/walgit/shared/landing.ts +1241 -0
  20. package/templates/apps/walgit/shared/llms.ts +463 -0
  21. package/templates/apps/walgit/shared/outbox.ts +266 -0
  22. package/templates/apps/walgit/shared/policy.ts +59 -0
  23. package/templates/apps/walgit/shared/protocol.ts +197 -0
  24. package/templates/apps/walgit/shared/provenance.ts +154 -0
  25. package/templates/apps/walgit/shared/ref-cache.ts +181 -0
  26. package/templates/apps/walgit/shared/telemetry.ts +219 -0
  27. package/templates/apps/walgit/src/announce-main.ts +37 -0
  28. package/templates/apps/walgit/src/announce.ts +98 -0
  29. package/templates/apps/walgit/src/append-only.ts +112 -0
  30. package/templates/apps/walgit/src/cache.ts +172 -0
  31. package/templates/apps/walgit/src/cli.ts +493 -0
  32. package/templates/apps/walgit/src/compact.ts +25 -23
  33. package/templates/apps/walgit/src/delete-repo.ts +237 -0
  34. package/templates/apps/walgit/src/expire.ts +248 -0
  35. package/templates/apps/walgit/src/gc.ts +8 -16
  36. package/templates/apps/walgit/src/git-backend.ts +29 -0
  37. package/templates/apps/walgit/src/git.ts +78 -0
  38. package/templates/apps/walgit/src/hook-main.ts +259 -17
  39. package/templates/apps/walgit/src/hooks.ts +4 -3
  40. package/templates/apps/walgit/src/http.ts +237 -45
  41. package/templates/apps/walgit/src/instructions.ts +240 -0
  42. package/templates/apps/walgit/src/keys.ts +126 -0
  43. package/templates/apps/walgit/src/limits.ts +158 -0
  44. package/templates/apps/walgit/src/materialize.bench.ts +10 -10
  45. package/templates/apps/walgit/src/materialize.ts +48 -40
  46. package/templates/apps/walgit/src/mkdir-lock.ts +66 -0
  47. package/templates/apps/walgit/src/orphans.ts +2 -5
  48. package/templates/apps/walgit/src/pending.ts +201 -0
  49. package/templates/apps/walgit/src/push-cert.ts +254 -0
  50. package/templates/apps/walgit/src/push.ts +233 -46
  51. package/templates/apps/walgit/src/reconcile.ts +5 -8
  52. package/templates/apps/walgit/src/repo.ts +22 -77
  53. package/templates/apps/walgit/src/server.ts +148 -26
  54. package/templates/apps/walgit/src/signers.ts +577 -0
  55. package/templates/apps/walgit/src/store-env.ts +5 -4
  56. package/templates/apps/walgit/src/store.ts +47 -24
  57. package/templates/apps/walgit/src/usage.ts +404 -0
  58. package/templates/apps/walgit/src/verify.ts +171 -0
  59. package/templates/apps/walgit/src/wal-index.ts +189 -11
  60. package/templates/apps/walgit/tsconfig.json +8 -2
  61. package/templates/apps/walgit/tsconfig.worker.json +24 -0
  62. package/templates/apps/walgit/worker/events-do.ts +259 -0
  63. package/templates/apps/walgit/worker/index.ts +572 -0
  64. package/templates/apps/walgit/wrangler.jsonc +95 -0
  65. package/templates/apps/warehouse/package.json +1 -1
  66. package/templates/infra/modules/cloudflare/index.ts +77 -6
  67. package/templates/infra/modules/fly/index.ts +150 -10
  68. package/templates/infra/modules/turso/index.ts +43 -3
  69. package/templates/infra/package.json +1 -1
  70. package/templates/apps/walgit/entrypoint.sh +0 -59
  71. package/templates/apps/walgit/fly.toml +0 -52
  72. package/templates/apps/walgit/src/ssh-shell.ts +0 -36
  73. package/templates/apps/walgit/sshd_config +0 -38
@@ -0,0 +1,266 @@
1
+ /**
2
+ * What happens when a subscriber stops keeping up.
3
+ *
4
+ * The fan-out is one message per socket per moved ref, and the sockets belong
5
+ * to clients walgit does not control: an agent that suspended its sandbox, a
6
+ * laptop that closed, a process wedged on something else. TCP keeps such a
7
+ * connection open and the send buffer keeps growing, so without a policy the
8
+ * cost of one dead reader is paid by the Durable Object's memory, and then by
9
+ * every other subscriber in it.
10
+ *
11
+ * The policy is a RATE, not an observation: at most one message per repository
12
+ * and ref per window, per socket. Nothing here asks the socket how it is
13
+ * doing, because on Workers nothing can — see `Sink` below. What a slow reader
14
+ * gets is therefore the same as what a fast one gets, only fewer messages of
15
+ * it, and the queue behind either is bounded by the refs it watches rather than
16
+ * by how hard anyone is pushing.
17
+ *
18
+ * That works only because events are LATEST STATE (docs/adr/0009), never a log:
19
+ * a ref that moves twice inside one window has no reader for the intermediate
20
+ * sha, so the queued entry is REPLACED rather than joined. By the time the
21
+ * window elapses the only sha that answers "is my main current?" is the newest
22
+ * one, which is exactly the one that goes out.
23
+ *
24
+ * Pure, and deliberately so: the only things it touches are a `Sink` — two
25
+ * members of `WebSocket` — and an injected clock and timer. So it lives in
26
+ * `shared/` rather than beside the Durable Object that uses it, and the tests
27
+ * drive the window by hand without a Workers runtime.
28
+ */
29
+
30
+ import { type RefEvent, encode } from './events'
31
+
32
+ /**
33
+ * The part of a WebSocket this file needs.
34
+ *
35
+ * Two members, and that is the whole surface the Workers runtime offers for
36
+ * writing to a socket. There is deliberately no `bufferedAmount`: the runtime's
37
+ * `WebSocket` does not have one. Confirmed against workerd 1.20260828.1 rather
38
+ * than inferred from the types — `'bufferedAmount' in server` is `false` on a
39
+ * `WebSocketPair` socket, and it stays `undefined` after `accept()` and after
40
+ * sending 64 KiB. An earlier version of this file read it anyway, through an
41
+ * optional field, which meant the policy compiled, passed its tests against a
42
+ * fake that set the field, and did nothing at all in production.
43
+ */
44
+ export interface Sink {
45
+ send(data: string): void
46
+ close(code: number, reason: string): void
47
+ }
48
+
49
+ /**
50
+ * At most one message per repository-and-ref per this many milliseconds, per
51
+ * socket.
52
+ *
53
+ * Short enough that a person watching a push does not notice it, long enough
54
+ * that a burst of pushes to one branch collapses. It only ever delays the
55
+ * SECOND event in a window — the first is written the moment it arrives, which
56
+ * is the case that matters for "my main just moved".
57
+ */
58
+ export const COALESCE_WINDOW_MS = 250
59
+
60
+ /** The close code a socket that will not take writes sees. 1013 — try again later. */
61
+ export const DEAD_SOCKET_CLOSE_CODE = 1013
62
+ export const DEAD_SOCKET_CLOSE_REASON = 'walgit: send failed; reconnect to resync'
63
+
64
+ /** What one `offer` did, for the caller's counters and for the tests. */
65
+ export interface OfferResult {
66
+ /** Messages actually written to the sink. */
67
+ sent: number
68
+ /** Events that replaced a queued event for the same repository and ref. */
69
+ coalesced: number
70
+ /** Events still queued, waiting for their ref's window to elapse. */
71
+ pending: number
72
+ /** True if this offer gave up on the sink. */
73
+ closed: boolean
74
+ }
75
+
76
+ /**
77
+ * The clock and timer the outbox runs on — injected so tests can drive them.
78
+ *
79
+ * Only these two, and no window override: a second window length would be a
80
+ * knob with no caller, and a test controls everything that matters by winding
81
+ * the clock past `COALESCE_WINDOW_MS`.
82
+ */
83
+ export interface OutboxOptions {
84
+ /** Current time in milliseconds. */
85
+ now?: () => number
86
+ /** Run `fn` after at least `ms` milliseconds. */
87
+ schedule?: (fn: () => void, ms: number) => void
88
+ }
89
+
90
+ /**
91
+ * One socket's outbound queue.
92
+ *
93
+ * State is two `Map`s keyed by repository and ref: what is queued, and when that
94
+ * key last went out. Coalescing is then a property of the data structure rather
95
+ * than a scan — an event for a ref already queued overwrites it — and insertion
96
+ * order keeps the drain fair across refs.
97
+ */
98
+ export class Outbox {
99
+ private readonly pending = new Map<string, RefEvent>()
100
+ private readonly lastSentAt = new Map<string, number>()
101
+ private readonly windowMs = COALESCE_WINDOW_MS
102
+ private readonly now: () => number
103
+ private readonly schedule: (fn: () => void, ms: number) => void
104
+ /** When the armed timer will fire, or null if none is armed. */
105
+ private armedFor: number | null = null
106
+ private closed = false
107
+
108
+ constructor(
109
+ private readonly sink: Sink,
110
+ options: OutboxOptions = {},
111
+ ) {
112
+ this.now = options.now ?? (() => Date.now())
113
+ this.schedule =
114
+ options.schedule ??
115
+ ((fn, ms) => {
116
+ setTimeout(fn, ms)
117
+ })
118
+ }
119
+
120
+ /** Has this outbox given up on its sink? */
121
+ get isClosed(): boolean {
122
+ return this.closed
123
+ }
124
+
125
+ /** How many events are queued, waiting for their ref's window to elapse. */
126
+ get size(): number {
127
+ return this.pending.size
128
+ }
129
+
130
+ /**
131
+ * Hand this socket some events.
132
+ *
133
+ * Queue first, then drain, rather than send-and-queue-the-rest: an event that
134
+ * arrives while an earlier one for the same ref is still queued has to be able
135
+ * to supersede it, and it can only do that if everything goes through the same
136
+ * map.
137
+ */
138
+ offer(events: readonly RefEvent[]): OfferResult {
139
+ if (this.closed) return { sent: 0, coalesced: 0, pending: 0, closed: true }
140
+
141
+ let coalesced = 0
142
+ for (const event of events) {
143
+ // NUL, because it is the one byte neither half can contain: git forbids
144
+ // control characters in a ref name and `repo.ts` forbids them in a
145
+ // repository name. Written as an escape rather than as a raw byte —
146
+ // HEAD's version had the literal, which made git call this file binary
147
+ // and print "Binary files differ" for every review of it.
148
+ const key = `${event.repo}\u0000${event.ref}`
149
+ if (this.pending.has(key)) coalesced += 1
150
+ this.pending.set(key, event)
151
+ }
152
+ const flushed = this.flush()
153
+ return {
154
+ sent: flushed.sent,
155
+ coalesced,
156
+ pending: this.pending.size,
157
+ closed: flushed.closed,
158
+ }
159
+ }
160
+
161
+ /**
162
+ * Write every queued event whose ref's window has elapsed, and arm a timer
163
+ * for the rest.
164
+ *
165
+ * Also the resume path, and the timer's own callback: what a socket receives
166
+ * when its window comes up is one message per ref at its newest sha — never
167
+ * the backlog, because there is no backlog to have.
168
+ */
169
+ flush(): { sent: number; closed: boolean } {
170
+ if (this.closed) return { sent: 0, closed: true }
171
+ const now = this.now()
172
+ let sent = 0
173
+ // The soonest a held event comes due, gathered on the way through so the
174
+ // timer needs no second pass over the queue.
175
+ let earliest = Number.POSITIVE_INFINITY
176
+
177
+ // Deleting the current key mid-iteration is well-defined for a Map, and
178
+ // nothing here adds to `pending`, so this needs no snapshot.
179
+ for (const [key, event] of this.pending) {
180
+ const last = this.lastSentAt.get(key)
181
+ if (last !== undefined && now - last < this.windowMs) {
182
+ earliest = Math.min(earliest, last + this.windowMs)
183
+ continue
184
+ }
185
+ this.pending.delete(key)
186
+ try {
187
+ this.sink.send(encode(event))
188
+ } catch {
189
+ // A socket that throws on send is already gone. Nothing here needs to
190
+ // survive it — the client's next handshake is the whole recovery.
191
+ this.drop()
192
+ return { sent, closed: true }
193
+ }
194
+ this.lastSentAt.set(key, now)
195
+ sent += 1
196
+ }
197
+
198
+ this.forgetIdleRefs(now)
199
+ if (earliest !== Number.POSITIVE_INFINITY) this.arm(earliest, now)
200
+ return { sent, closed: false }
201
+ }
202
+
203
+ /**
204
+ * Make sure ONE timer is pending, and never more.
205
+ *
206
+ * An armed timer is never replaced, not even by an event that comes due
207
+ * sooner: `schedule` hands back no canceller, so re-arming would leave the
208
+ * old timer alive, and a burst across many refs would then accumulate one
209
+ * timer per ref — the unbounded memory inside the Durable Object that this
210
+ * file exists to prevent. Letting the pending timer stand caps a socket at
211
+ * one live timer for as long as it is subscribed.
212
+ *
213
+ * What that costs is bounded and small. An armed deadline is always within
214
+ * one window of when it was set, because the key it was set for was last sent
215
+ * at or before that moment. So an event coming due before an already-armed
216
+ * timer still leaves on that timer, and one coming due after it is re-armed
217
+ * for by the flush the timer runs. Worst case an event waits two windows
218
+ * rather than one.
219
+ */
220
+ private arm(deadline: number, now: number): void {
221
+ if (this.armedFor !== null) return
222
+ this.armedFor = deadline
223
+ this.schedule(
224
+ () => {
225
+ this.armedFor = null
226
+ this.flush()
227
+ },
228
+ Math.max(1, deadline - now),
229
+ )
230
+ }
231
+
232
+ /**
233
+ * Drop the send times of refs that have gone quiet.
234
+ *
235
+ * A ref whose window has elapsed and which has nothing queued is
236
+ * indistinguishable from one never seen — the next event for it goes out
237
+ * immediately either way — so remembering it is pure growth. Running it on
238
+ * every flush keeps the map to the refs that moved inside the last window,
239
+ * which is also what keeps the scan cheap. Nothing else bounds it: a watch
240
+ * entry with no `refs` list covers a whole repository, so the Watch cap
241
+ * limits repositories rather than refs, and a long-lived subscriber would
242
+ * otherwise hold an entry for every ref that has ever moved.
243
+ */
244
+ private forgetIdleRefs(now: number): void {
245
+ for (const [key, at] of this.lastSentAt) {
246
+ if (now - at >= this.windowMs && !this.pending.has(key)) this.lastSentAt.delete(key)
247
+ }
248
+ }
249
+
250
+ /**
251
+ * Give up: close the socket and forget everything queued for it.
252
+ *
253
+ * Forgetting is the point — a closed sink whose queue stayed behind would be
254
+ * exactly the leak this file exists to prevent.
255
+ */
256
+ private drop(): void {
257
+ this.closed = true
258
+ this.pending.clear()
259
+ this.lastSentAt.clear()
260
+ try {
261
+ this.sink.close(DEAD_SOCKET_CLOSE_CODE, DEAD_SOCKET_CLOSE_REASON)
262
+ } catch {
263
+ // Already closed by the runtime; the queue is cleared either way.
264
+ }
265
+ }
266
+ }
@@ -0,0 +1,59 @@
1
+ /**
2
+ * Reading a limit, and saying what it is.
3
+ *
4
+ * Both halves state walgit's limits and only one of them enforces them: the
5
+ * container refuses an oversized push in `pre-receive` (`src/limits.ts`), while
6
+ * `GET /` (`src/instructions.ts`) and the landing page (`shared/landing.ts`)
7
+ * describe the caps to whoever is about to push. A page that promised a number
8
+ * the hook does not hold would be a lie told at the top of the funnel, and the
9
+ * only reliable way not to tell it is for the statement and the enforcement to
10
+ * read the same variable through the same function.
11
+ *
12
+ * That is why these two live here rather than in either half. `positiveNumber`
13
+ * existed three times with two different return types, and `describeBytes`
14
+ * twice with a comment promising they were kept identical.
15
+ */
16
+
17
+ /**
18
+ * A configured limit, or `null` for "this deployment enforces nothing here".
19
+ *
20
+ * Unset, blank, unparseable and non-positive all read as unset. Zero would
21
+ * refuse every push, and a typo in a deployment variable must not silently
22
+ * become "this host accepts nothing" — nor, on the page, a stated cap of `NaN`.
23
+ */
24
+ export function positiveNumber(raw: string | undefined): number | null {
25
+ if (raw === undefined || raw.trim() === '') return null
26
+ const value = Number(raw)
27
+ return Number.isFinite(value) && value > 0 ? value : null
28
+ }
29
+
30
+ /**
31
+ * Both a unit and the raw byte count, so an agent comparing its own pack size
32
+ * against this number never has to guess our rounding.
33
+ *
34
+ * `GET /`, the landing page and the refusal message all print a cap through
35
+ * this one function: an agent reads the limit in one place and the refusal in
36
+ * another, and two roundings would look like two different limits.
37
+ */
38
+ export function describeBytes(bytes: number): string {
39
+ const gib = bytes / 1024 ** 3
40
+ const mib = bytes / 1024 ** 2
41
+ if (gib >= 1) return `${round(gib)} GiB (${bytes} bytes)`
42
+ if (mib >= 1) return `${round(mib)} MiB (${bytes} bytes)`
43
+ return `${bytes} bytes`
44
+ }
45
+
46
+ const round = (n: number) => String(Math.round(n * 100) / 100)
47
+
48
+ /**
49
+ * Is a boolean-ish walgit variable on?
50
+ *
51
+ * `1` or `true`, and nothing else. It lives here because BOTH halves have to
52
+ * agree on it exactly: the container enforces append-only from this answer and
53
+ * the Worker tells agents about it from the same one, and a Worker that read
54
+ * only `1` would quietly stop mentioning a rule the push path was still
55
+ * enforcing for `true` (docs/adr/0010).
56
+ */
57
+ export function flagEnabled(raw: string | undefined): boolean {
58
+ return raw === '1' || raw === 'true'
59
+ }
@@ -0,0 +1,197 @@
1
+ /**
2
+ * The wire contract walgit's two halves speak.
3
+ *
4
+ * walgit is one service in two processes: a container running git behind
5
+ * `src/`, and a Cloudflare Worker in front of it (`worker/`). They cannot share
6
+ * a bundle — `@types/bun` and `@cloudflare/workers-types` are contradictory
7
+ * ambient declarations, so each half gets its own tsconfig — but every fact in
8
+ * this file is a fact BOTH halves have to agree on exactly: a header one sets
9
+ * and the other reads, a path one strips and the other trusts, a grammar one
10
+ * validates a name against and the other validates the same name against on a
11
+ * different transport.
12
+ *
13
+ * Those facts used to be written twice, once on each side, with a comment
14
+ * explaining that the copy was deliberate. Two of them had already drifted by
15
+ * the time anyone looked (docs/adr/0010). What is actually true is narrower
16
+ * than "the halves cannot share code": a module that imports NO runtime is
17
+ * valid under both type systems, and `shared/` is exactly that category —
18
+ * compiled by `tsconfig.json` and `tsconfig.worker.json` both, so "this is
19
+ * runtime-neutral" is something the build fails on rather than a comment.
20
+ *
21
+ * The rule for this directory is one sentence: **`shared/` imports no runtime,
22
+ * and both halves may import it.**
23
+ */
24
+
25
+ // ── Headers ─────────────────────────────────────────────────────────────────
26
+
27
+ /**
28
+ * Headers that make a response countable in front of the container.
29
+ *
30
+ * The Worker counts refusals BY KIND, and it cannot derive the kind from a
31
+ * status code several refusals share. So whichever layer refuses names the kind
32
+ * here, and every response the container produces carries the `served` stamp —
33
+ * its absence is precisely what lets the Worker see that something in FRONT of
34
+ * walgit refused a request walgit should have refused itself.
35
+ */
36
+ export const SERVED_HEADER = 'x-walgit-served'
37
+ export const REJECT_HEADER = 'x-walgit-reject'
38
+
39
+ /** Header the container sets on the first response after it started. */
40
+ export const COLD_HEADER = 'x-walgit-cold'
41
+
42
+ /**
43
+ * The header that marks a REQUEST as coming from the Worker's own handlers
44
+ * rather than from the internet.
45
+ *
46
+ * Expiry DELETES repositories and the container is world-reachable by design,
47
+ * so the endpoints that run it must not be. The Worker strips this header from
48
+ * every request it proxies from a client and sets it only on the ones it
49
+ * originates itself, which makes "the Worker asked" unforgeable from outside
50
+ * without inventing a second credential for a service whose whole point is not
51
+ * having one.
52
+ */
53
+ export const INTERNAL_HEADER = 'x-walgit-internal'
54
+
55
+ /** Stripped before the response leaves the Worker — internal, not protocol. */
56
+ export const INTERNAL_HEADERS = [SERVED_HEADER, REJECT_HEADER, COLD_HEADER] as const
57
+
58
+ // ── Paths ───────────────────────────────────────────────────────────────────
59
+
60
+ /** Liveness. Unauthenticated: it reveals nothing but that the container is up. */
61
+ export const HEALTH_PATH = '/_walgit/health'
62
+
63
+ /** The sweeper's front door. `INTERNAL_HEADER` only — see above. */
64
+ export const EXPIRE_PATH = '/_walgit/expire'
65
+
66
+ /** One repository's ref state, for the event stream's handshake. Internal. */
67
+ export const REFS_PATH = '/_walgit/refs'
68
+
69
+ /**
70
+ * One repository's push provenance: ref → the Signer that moved it, and when
71
+ * (docs/adr/0011).
72
+ *
73
+ * Unlike `REFS_PATH` beside it, this one is for CLIENTS — an agent asking the
74
+ * host who pushed — so it is gated by the ordinary read credential rather than
75
+ * by `INTERNAL_HEADER`. Deliberately not on the ref-event stream: ADR-0009
76
+ * froze that wire to "a ref moved, and to what", and provenance is separate
77
+ * state with a different lifetime and a different reader.
78
+ *
79
+ * The repository is a query parameter rather than a path segment because
80
+ * `SMART_HTTP` is the three git endpoints and no more; widening that grammar
81
+ * to carry a fourth would change what the Worker counts as a clone.
82
+ */
83
+ export const PROVENANCE_PATH = '/_walgit/provenance'
84
+
85
+ /** Where a subscriber connects. A WebSocket upgrade, and nothing else. */
86
+ export const EVENTS_PATH = '/_walgit/events'
87
+
88
+ /**
89
+ * Where the container publishes a push it has already made durable.
90
+ *
91
+ * The container reaches the Worker over the public internet, so unlike the
92
+ * expiry sweep this cannot ride on a stripped header — it carries a shared
93
+ * secret instead (`WALGIT_EVENTS_TOKEN`).
94
+ */
95
+ export const ANNOUNCE_PATH = '/_walgit/announce'
96
+
97
+ // ── Grammar ─────────────────────────────────────────────────────────────────
98
+
99
+ /**
100
+ * The smart-HTTP protocol is three endpoints and no more.
101
+ *
102
+ * Everything else a bare repo exposes over HTTP is DUMB http — raw objects,
103
+ * packs, HEAD — which would read the on-disk cache directly and bypass the WAL
104
+ * the cache is derived from. Not routed, so not served.
105
+ *
106
+ * Group 1 is the repository; group 2 is the endpoint. The container routes on
107
+ * the first and the Worker classifies on both, which is why there is one regex
108
+ * and not one per reader: a path the Worker counts as a clone and the container
109
+ * declines to route would be a metric describing traffic that never happened.
110
+ */
111
+ export const SMART_HTTP = /^\/([^/]+)\.git\/(info\/refs|git-upload-pack|git-receive-pack)$/
112
+
113
+ /**
114
+ * A repo id is one flat segment.
115
+ *
116
+ * Flat because the WAL keys repositories by id (docs/adr/0007), not by a
117
+ * directory tree, and a hierarchy on disk that the log cannot express would
118
+ * drift the moment a repo is rebuilt from the log. The same gate applies to a
119
+ * name arriving in a URL path (`src/repo.ts`) and to one arriving over the
120
+ * event socket (`shared/events.ts`) — both are attacker-controlled, and a name
121
+ * one accepts and the other rejects is a repository half the service can see.
122
+ */
123
+ export const REPO_ID = /^[A-Za-z0-9][A-Za-z0-9._-]*$/
124
+
125
+ /** A ref name, as git writes it. Full name only: `main` is not a ref. */
126
+ export const REF_NAME = /^refs\/[A-Za-z0-9._\-/]+$/
127
+
128
+ /** The all-zeroes oid: creation when it is `oldOid`, deletion when `newOid`. */
129
+ export const ZERO_OID = '0'.repeat(40)
130
+
131
+ /**
132
+ * Where a repository's Signer List lives (docs/adr/0012).
133
+ *
134
+ * A ref, and that is the whole mechanism: claiming a free name is pushing it,
135
+ * granting is a commit that adds a line, revoking is a commit that removes one,
136
+ * and reading it is `git ls-remote`. It is protocol rather than implementation
137
+ * — a client types this name — so it lives here beside the paths, and so the
138
+ * Index writer and the push path cannot spell it two ways.
139
+ *
140
+ * Under `refs/walgit/` rather than `refs/heads/`: it is not a branch, and a
141
+ * clone should not check it out.
142
+ */
143
+ export const SIGNERS_REF = 'refs/walgit/signers'
144
+
145
+ // ── Refusals ────────────────────────────────────────────────────────────────
146
+
147
+ /**
148
+ * Every refusal walgit distinguishes. Aligned with the messages it emits.
149
+ *
150
+ * Counted by kind, never as an aggregate error rate, because the kinds mean
151
+ * different things to whoever is reading:
152
+ *
153
+ * - `size-cap` a client pushing more than the instance allows — abuse, or
154
+ * a misconfigured client
155
+ * - `collision` a name already taken — a product signal about naming
156
+ * - `unauthorized` a bad or missing credential
157
+ * - `edge` walgit did not refuse; something in front of it did. This
158
+ * one is a BUG SIGNAL: every refusal walgit means to make it
159
+ * should make itself, with an explanation. Absorbing it into
160
+ * a general error count is how it would stay invisible.
161
+ */
162
+ export type RejectKind =
163
+ | 'size-cap'
164
+ | 'collision'
165
+ | 'unauthorized'
166
+ | 'not-found'
167
+ | 'unavailable'
168
+ | 'edge'
169
+ | 'other'
170
+
171
+ /**
172
+ * The kinds the container itself can name in `REJECT_HEADER`.
173
+ *
174
+ * `edge` is excluded by construction — it means "something in front of walgit
175
+ * refused", which the thing in front is the only one able to observe — and
176
+ * `other` is the Worker's fallback for a kind it does not recognise, never a
177
+ * kind anything sets deliberately. Stating the subset as a type is the point:
178
+ * it used to be a second, shorter hand-maintained union in `src/http.ts`, and
179
+ * nothing checked that the two lists stayed related.
180
+ */
181
+ export type ContainerRejectKind = Exclude<RejectKind, 'edge' | 'other'>
182
+
183
+ /** An unrecognised kind becomes `other` rather than a new column nobody reads. */
184
+ const KINDS = new Set<RejectKind>([
185
+ 'size-cap',
186
+ 'collision',
187
+ 'unauthorized',
188
+ 'not-found',
189
+ 'unavailable',
190
+ 'edge',
191
+ 'other',
192
+ ])
193
+
194
+ export function normalizeReject(value: string): RejectKind {
195
+ const kind = value.trim().toLowerCase()
196
+ return KINDS.has(kind as RejectKind) ? (kind as RejectKind) : 'other'
197
+ }
@@ -0,0 +1,154 @@
1
+ /**
2
+ * Push provenance: the decidable half.
3
+ *
4
+ * A signed push arrives with a **push certificate** — a small text document
5
+ * naming the pusher, the pushee, the nonce this server issued and every ref the
6
+ * push moves, followed by an armoured SSH signature over everything above it
7
+ * (docs/adr/0011 in the zbc repository). walgit reads it, records the key that
8
+ * signed it as that ref's **Signer**, and refuses nothing on the strength of it
9
+ * — except where the repository holds a Signer List and the instance enforces
10
+ * one, which is the gate in `src/signers.ts` and nothing this module decides.
11
+ *
12
+ * Verification cannot use git's own verdict. `git-receive-pack` checks a
13
+ * certificate with GPG unless told otherwise, so an SSH signature reaches the
14
+ * hook as `GIT_PUSH_CERT_STATUS=N` — "no signature" — with `GIT_PUSH_CERT_KEY`
15
+ * and `GIT_PUSH_CERT_SIGNER` both empty. Configuring git for SSH instead does
16
+ * not help: it then demands `gpg.ssh.allowedSignersFile`, a registry of keys
17
+ * allowed to sign, which is precisely the thing this design refuses to have.
18
+ * `ssh-keygen -Y check-novalidate` answers the only question walgit asks — *is
19
+ * this signature good, and which key made it* — with no registry of any kind.
20
+ *
21
+ * What lives here is what is decidable without a keypair, a subprocess or a
22
+ * running git: where the signed bytes end and the signature begins, and which
23
+ * key a verifier's output names. Running the verifier is `src/push-cert.ts`'s,
24
+ * because a subprocess is a runtime and `shared/` has none (ADR-0010).
25
+ */
26
+
27
+ /**
28
+ * The signature namespace, and it is load-bearing rather than decorative.
29
+ *
30
+ * `ssh-keygen -Y` binds every signature to a namespace and refuses to verify it
31
+ * under any other one ("namespace does not match"). git signs a push
32
+ * certificate under `git`; an SSH authentication handshake is signed under a
33
+ * different namespace entirely. Verifying under `git` is therefore what stops a
34
+ * push signature being replayable as a login, and a verifier that omitted the
35
+ * namespace would silently accept signatures made for something else.
36
+ */
37
+ export const PUSH_CERT_NAMESPACE = 'git'
38
+
39
+ const BEGIN_SIGNATURE = '-----BEGIN SSH SIGNATURE-----'
40
+ const END_SIGNATURE = '-----END SSH SIGNATURE-----'
41
+
42
+ export interface SplitCertificate {
43
+ /**
44
+ * Exactly the bytes the pusher signed: the certificate up to, and not
45
+ * including, the signature block. Byte-exact matters — a stripped trailing
46
+ * newline or a normalized line ending verifies as a forgery.
47
+ */
48
+ body: string
49
+ /** The armoured signature block, as `ssh-keygen -Y … -s <file>` takes it. */
50
+ signature: string
51
+ }
52
+
53
+ /**
54
+ * Split a push certificate into the bytes that were signed and the signature
55
+ * over them, or `null` when the text is not one.
56
+ *
57
+ * git appends the armour to the payload it signed, so the split is positional
58
+ * and needs no parse of the certificate's fields: everything before the BEGIN
59
+ * line is the message, everything from it is the signature. Nothing above the
60
+ * line is interpreted here on purpose — the `pusher` field carries a
61
+ * fingerprint, but it is the *claim* being verified, so believing it would make
62
+ * the signature ornamental.
63
+ *
64
+ * `null` for anything malformed: no armour, no terminator, or a signature with
65
+ * no message under it. The caller records no Signer and accepts the push.
66
+ */
67
+ export function splitPushCertificate(text: string): SplitCertificate | null {
68
+ const begin = text.indexOf(BEGIN_SIGNATURE)
69
+ if (begin === -1) return null
70
+ const end = text.indexOf(END_SIGNATURE, begin)
71
+ if (end === -1) return null
72
+ const body = text.slice(0, begin)
73
+ if (body.trim() === '') return null
74
+ // Re-terminated rather than sliced to the end of the text: whatever follows
75
+ // the armour is not signature, and `ssh-keygen` wants the file newline-ended.
76
+ return { body, signature: `${text.slice(begin, end + END_SIGNATURE.length)}\n` }
77
+ }
78
+
79
+ /**
80
+ * An SSH key fingerprint as `ssh-keygen` prints it: `SHA256:` and 43 characters
81
+ * of unpadded base64 (a 256-bit digest). Anchored on neither side, because the
82
+ * verifier writes it inside a sentence:
83
+ *
84
+ * Good "git" signature with ED25519 key SHA256:BMBEMXbMBsnj…
85
+ *
86
+ * and the wording around it differs between OpenSSH releases while the
87
+ * fingerprint's spelling has not.
88
+ */
89
+ const FINGERPRINT = /SHA256:[A-Za-z0-9+/]{43}/
90
+
91
+ /** The same spelling, anchored — for text that must be nothing else. */
92
+ const FINGERPRINT_ONLY = new RegExp(`^${FINGERPRINT.source}$`)
93
+
94
+ /**
95
+ * Is this text a fingerprint and nothing but one?
96
+ *
97
+ * The Signer List is a file of these, one per line (docs/adr/0012), and it is
98
+ * read strictly: a line that is not exactly a fingerprint makes the whole list
99
+ * unreadable rather than being skipped. Dropping it silently would let a typo
100
+ * cost an agent a key it believes is listed, which is the failure that decision
101
+ * exists to prevent — so this asks the whole-string question, and it is built
102
+ * from the same source as `fingerprintIn` so the two can never disagree about
103
+ * what a fingerprint looks like.
104
+ */
105
+ export function isFingerprint(text: string): boolean {
106
+ return FINGERPRINT_ONLY.test(text)
107
+ }
108
+
109
+ /**
110
+ * The key a verifier's output names, or `null` when it names none.
111
+ *
112
+ * Deliberately not a verdict: whether the signature was *good* is the
113
+ * verifier's exit status, which the caller checks before it gets here. This
114
+ * answers only "which key", and answering `null` is how output that verified
115
+ * something but named nothing recognisable records no Signer instead of
116
+ * recording something wrong.
117
+ */
118
+ export function fingerprintIn(verifierOutput: string): string | null {
119
+ return FINGERPRINT.exec(verifierOutput)?.[0] ?? null
120
+ }
121
+
122
+ /**
123
+ * The configured seed, or `null` for "this deployment does not take signed
124
+ * pushes".
125
+ *
126
+ * Blank reads as unset, the same collapse `containerEnv` makes at the seam and
127
+ * `positiveNumber` makes for the size caps: a variable cleared to an empty
128
+ * string is a capability turned off, not a capability seeded with nothing. git
129
+ * would take `""` as a seed and derive perfectly usable nonces from it, so the
130
+ * two spellings have to collapse here rather than at the config write.
131
+ *
132
+ * It takes the raw variable rather than an environment, like `flagEnabled` and
133
+ * `positiveNumber` beside it, because the two halves do not have the same
134
+ * environment to hand it: the container has `process.env` and the Worker has a
135
+ * binding object. What they must share is the reading, and that is this.
136
+ */
137
+ export function pushCertSeed(raw: string | undefined): string | null {
138
+ if (raw === undefined) return null
139
+ const seed = raw.trim()
140
+ return seed === '' ? null : seed
141
+ }
142
+
143
+ /**
144
+ * Does this deployment take signed pushes? The seed, read as a yes/no.
145
+ *
146
+ * This is what both agent-facing documents render from, and rendering from it
147
+ * is the whole discipline: with no seed, `git-receive-pack` never advertises
148
+ * `push-cert` and a client asking to sign is refused by its own git — so a
149
+ * page that offered signing there would send an agent to a flag that cannot
150
+ * work, which is the same defect as a stated cap nothing enforces.
151
+ */
152
+ export function signedPushEnabled(raw: string | undefined): boolean {
153
+ return pushCertSeed(raw) !== null
154
+ }