@zabaca/zbc 0.12.0 → 0.14.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 (111) hide show
  1. package/CHANGELOG.md +174 -0
  2. package/package.json +6 -2
  3. package/src/commands/add.ts +13 -0
  4. package/src/commands/init.ts +1 -0
  5. package/src/engine/apply.ts +60 -21
  6. package/src/engine/destroy.ts +183 -14
  7. package/src/engine/discover.ts +1 -1
  8. package/src/engine/resolve.ts +56 -11
  9. package/src/utils/copy-template.ts +10 -0
  10. package/templates/apps/inbox/package.json +4 -2
  11. package/templates/apps/inbox/tsconfig.json +3 -1
  12. package/templates/apps/inbox/worker/api.ts +197 -0
  13. package/templates/apps/inbox/worker/commands.ts +299 -0
  14. package/templates/apps/inbox/worker/inbox-do.ts +53 -10
  15. package/templates/apps/inbox/worker/index.ts +15 -202
  16. package/templates/apps/inbox/worker/mcp.ts +49 -100
  17. package/templates/apps/walgit/CONTEXT.md +135 -0
  18. package/templates/apps/walgit/Dockerfile +40 -18
  19. package/templates/apps/walgit/README.md +518 -55
  20. package/templates/apps/walgit/e2e/README.md +100 -6
  21. package/templates/apps/walgit/e2e/harness.ts +262 -1
  22. package/templates/apps/walgit/e2e/live.ts +588 -0
  23. package/templates/apps/walgit/e2e/scenarios.ts +367 -5
  24. package/templates/apps/walgit/e2e/suite.ts +5 -5
  25. package/templates/apps/walgit/examples/watch.ts +209 -0
  26. package/templates/apps/walgit/package.json +12 -3
  27. package/templates/apps/walgit/registry.json +6 -11
  28. package/templates/apps/walgit/shared/capabilities.ts +189 -0
  29. package/templates/apps/walgit/shared/container-env.ts +114 -0
  30. package/templates/apps/walgit/shared/credentials.ts +81 -0
  31. package/templates/apps/walgit/shared/events.ts +277 -0
  32. package/templates/apps/walgit/shared/landing.ts +1241 -0
  33. package/templates/apps/walgit/shared/llms.ts +463 -0
  34. package/templates/apps/walgit/shared/outbox.ts +266 -0
  35. package/templates/apps/walgit/shared/policy.ts +59 -0
  36. package/templates/apps/walgit/shared/protocol.ts +197 -0
  37. package/templates/apps/walgit/shared/provenance.ts +154 -0
  38. package/templates/apps/walgit/shared/ref-cache.ts +181 -0
  39. package/templates/apps/walgit/shared/telemetry.ts +219 -0
  40. package/templates/apps/walgit/src/announce-main.ts +37 -0
  41. package/templates/apps/walgit/src/announce.ts +98 -0
  42. package/templates/apps/walgit/src/append-only.ts +112 -0
  43. package/templates/apps/walgit/src/cache.ts +172 -0
  44. package/templates/apps/walgit/src/cli.ts +493 -0
  45. package/templates/apps/walgit/src/compact.ts +25 -23
  46. package/templates/apps/walgit/src/delete-repo.ts +237 -0
  47. package/templates/apps/walgit/src/expire.ts +248 -0
  48. package/templates/apps/walgit/src/gc.ts +8 -16
  49. package/templates/apps/walgit/src/git-backend.ts +29 -0
  50. package/templates/apps/walgit/src/git.ts +78 -0
  51. package/templates/apps/walgit/src/hook-main.ts +259 -17
  52. package/templates/apps/walgit/src/hooks.ts +4 -3
  53. package/templates/apps/walgit/src/http.ts +237 -45
  54. package/templates/apps/walgit/src/instructions.ts +240 -0
  55. package/templates/apps/walgit/src/keys.ts +126 -0
  56. package/templates/apps/walgit/src/limits.ts +158 -0
  57. package/templates/apps/walgit/src/materialize.bench.ts +10 -10
  58. package/templates/apps/walgit/src/materialize.ts +48 -40
  59. package/templates/apps/walgit/src/mkdir-lock.ts +66 -0
  60. package/templates/apps/walgit/src/orphans.ts +2 -5
  61. package/templates/apps/walgit/src/pending.ts +201 -0
  62. package/templates/apps/walgit/src/push-cert.ts +254 -0
  63. package/templates/apps/walgit/src/push.ts +233 -46
  64. package/templates/apps/walgit/src/reconcile.ts +5 -8
  65. package/templates/apps/walgit/src/repo.ts +22 -77
  66. package/templates/apps/walgit/src/server.ts +148 -26
  67. package/templates/apps/walgit/src/signers.ts +577 -0
  68. package/templates/apps/walgit/src/store-env.ts +5 -4
  69. package/templates/apps/walgit/src/store.ts +47 -24
  70. package/templates/apps/walgit/src/usage.ts +404 -0
  71. package/templates/apps/walgit/src/verify.ts +171 -0
  72. package/templates/apps/walgit/src/wal-index.ts +189 -11
  73. package/templates/apps/walgit/tsconfig.json +8 -2
  74. package/templates/apps/walgit/tsconfig.worker.json +24 -0
  75. package/templates/apps/walgit/worker/events-do.ts +259 -0
  76. package/templates/apps/walgit/worker/index.ts +572 -0
  77. package/templates/apps/walgit/wrangler.jsonc +95 -0
  78. package/templates/apps/warehouse/package.json +1 -1
  79. package/templates/infra/modules/cloudflare/index.ts +93 -67
  80. package/templates/infra/modules/cloudflare-access/index.ts +3 -3
  81. package/templates/infra/modules/cloudflare-api/index.ts +144 -32
  82. package/templates/infra/modules/cloudflare-api/registry.json +1 -1
  83. package/templates/infra/modules/cloudflare-email/index.ts +103 -144
  84. package/templates/infra/modules/cloudflare-email/registry.json +1 -1
  85. package/templates/infra/modules/cloudflare-token/index.ts +10 -30
  86. package/templates/infra/modules/cloudflare-token/registry.json +1 -1
  87. package/templates/infra/modules/cloudflare-tunnel/index.ts +3 -3
  88. package/templates/infra/modules/cloudflare-zone/index.ts +2 -2
  89. package/templates/infra/modules/fly/index.ts +158 -35
  90. package/templates/infra/modules/host-file/index.ts +6 -7
  91. package/templates/infra/modules/provision-core/index.ts +21 -15
  92. package/templates/infra/modules/r2/index.ts +38 -55
  93. package/templates/infra/modules/r2/registry.json +1 -1
  94. package/templates/infra/modules/remote-provision/index.ts +1 -3
  95. package/templates/infra/modules/turso/index.ts +45 -7
  96. package/templates/infra/modules/vm-provision/index.ts +10 -3
  97. package/templates/infra/package.json +1 -1
  98. package/templates/infra/src/context.ts +115 -0
  99. package/templates/infra/src/define-module.ts +8 -2
  100. package/templates/infra/src/index.ts +11 -1
  101. package/templates/infra/src/types.ts +72 -3
  102. package/src/commands/add-registry.test.ts +0 -92
  103. package/src/commands/secret.test.ts +0 -717
  104. package/src/commands/vendor-mode.test.ts +0 -183
  105. package/src/infra-types.ts +0 -38
  106. package/src/utils/subtree.test.ts +0 -127
  107. package/templates/apps/inbox/worker/send-op.ts +0 -174
  108. package/templates/apps/walgit/entrypoint.sh +0 -59
  109. package/templates/apps/walgit/fly.toml +0 -52
  110. package/templates/apps/walgit/src/ssh-shell.ts +0 -36
  111. package/templates/apps/walgit/sshd_config +0 -38
@@ -0,0 +1,577 @@
1
+ /**
2
+ * Signer Lists: a name can hold the keys allowed to push to it.
3
+ *
4
+ * A repository's list is an ordinary ref — `refs/walgit/signers` — whose tip
5
+ * commit's tree holds a file named `signers`, one `SHA256:…` fingerprint per
6
+ * line. That the mechanism is a ref settles four things with no new machinery
7
+ * (docs/adr/0012): claiming a free name is pushing it, granting is a commit
8
+ * that adds a line, revoking is a commit that removes one, and reading it is
9
+ * `git ls-remote` or a clone.
10
+ *
11
+ * A commit chain rather than a ref pointing straight at a blob, and that was
12
+ * measured rather than assumed: `git merge-base --is-ancestor <blob> <blob>`
13
+ * exits 128 ("is a blob, not a commit"), and the append-only judge next door
14
+ * reads any non-zero exit as a rewrite — so a blob-valued list could be created
15
+ * once and never edited again. No grants, no revocations.
16
+ *
17
+ * There are two decisions here and they are deliberately separate, because they
18
+ * are asked of different bytes and answer different questions:
19
+ *
20
+ * - `checkSignerList` judges the list a push WRITES, and refuses two shapes
21
+ * that are both about LOSING a name rather than defending it — an EMPTY
22
+ * list, which would leave the name claimable by the next stranger, so a
23
+ * compromised key could give a name away rather than merely keep it; and an
24
+ * UNREADABLE one, which would leave an agent believing it holds a name it
25
+ * does not. Both are refused on claimed and unclaimed repositories alike,
26
+ * because both are wrong before ownership means anything.
27
+ * - `checkSignerAllowed` is the gate: while a repository HAS a list, a push
28
+ * not signed by a listed key is refused. It is pure over the Signer this
29
+ * push established, the list as it stood BEFORE this push, and the ref
30
+ * changes — no git, no store, no subprocess.
31
+ *
32
+ * **A grant governs the next push.** The list that judges a push is the one
33
+ * that stood before it, which is what lets a single push move the list and a
34
+ * branch together: the new list applies from the following push. The founding
35
+ * push needs no exception, because an unclaimed name refuses nothing.
36
+ *
37
+ * The gate is fail-open's one exception, and it is confined to a claimed
38
+ * repository (docs/adr/0011, docs/adr/0012). Everywhere else an unestablished
39
+ * Signer is the anonymous push walgit has always accepted; here it refuses,
40
+ * because otherwise breaking verification would be how one bypasses the gate.
41
+ *
42
+ * Off unless the instance turns it on, like append-only beside it: the package
43
+ * ships every capability off, and this one deliberately does not ride
44
+ * `WALGIT_PUSH_CERT_SEED` — a deployment that took signed pushes yesterday must
45
+ * not acquire ownership today as a side effect.
46
+ */
47
+
48
+ import { isFingerprint } from '../shared/provenance'
49
+ import { flagEnabled } from '../shared/policy'
50
+ import { SIGNERS_REF, ZERO_OID } from '../shared/protocol'
51
+ import { suggestName } from './append-only'
52
+ import { git } from './git'
53
+ import { certificatePresented, signedPushEnabled, type PushCertEnv } from './push-cert'
54
+ import type { RefChange } from './wal-index'
55
+
56
+ /**
57
+ * The env flag an instance sets to give its repositories Signer Lists.
58
+ *
59
+ * Turn it on beside `WALGIT_PUSH_CERT_SEED`, never without it. The seed is what
60
+ * makes `git-receive-pack` advertise certificates at all, so with the flag on
61
+ * and no seed every push to a claimed name is refused as unsigned and no client
62
+ * can sign its way out — every claimed name on that deployment is unpushable
63
+ * until the seed is set. Deliberately not enforced here: the gate refuses an
64
+ * unestablished Signer precisely so that breaking verification is not the way
65
+ * around it (docs/adr/0012), and an operator who unset the seed has broken
66
+ * verification for everyone. Failing closed is loud and recoverable; failing
67
+ * open would hand every claimed name back to the next stranger.
68
+ */
69
+ export function signerListsEnabled(env: Record<string, string | undefined> = process.env): boolean {
70
+ return flagEnabled(env.WALGIT_SIGNER_LISTS)
71
+ }
72
+
73
+ // ── The file ────────────────────────────────────────────────────────────────
74
+
75
+ export type ParsedList =
76
+ | { ok: true; signers: string[] }
77
+ /** A line that is neither blank, a comment, nor a fingerprint. */
78
+ | { ok: false; line: string; lineNumber: number }
79
+
80
+ /**
81
+ * Read a `signers` file into the fingerprints it names.
82
+ *
83
+ * Blank lines and `#` comments are ignored, whitespace is trimmed, and
84
+ * duplicates collapse to the first mention — an agent appending a key that is
85
+ * already there has written a list that means what it looks like, not an error.
86
+ *
87
+ * A line that survives all of that and is still not a fingerprint fails the
88
+ * WHOLE list rather than being skipped. Skipping is the tempting reading and it
89
+ * is the dangerous one: a typo'd key would drop out silently, and the agent
90
+ * that pushed it would believe it had granted access it had not. Refusing here
91
+ * costs a retry; the lenient reading costs a name.
92
+ *
93
+ * A comment may trail a fingerprint (`SHA256:… # alice's laptop`), which is
94
+ * free — `#` cannot occur in base64, so the two readings cannot collide.
95
+ */
96
+ export function parseSignerList(text: string): ParsedList {
97
+ const signers: string[] = []
98
+ const seen = new Set<string>()
99
+ const lines = text.split('\n')
100
+ for (let i = 0; i < lines.length; i += 1) {
101
+ const line = lines[i]!
102
+ const entry = line.slice(0, commentAt(line)).trim()
103
+ if (entry === '') continue
104
+ if (!isFingerprint(entry)) return { ok: false, line: entry, lineNumber: i + 1 }
105
+ if (seen.has(entry)) continue
106
+ seen.add(entry)
107
+ signers.push(entry)
108
+ }
109
+ return { ok: true, signers }
110
+ }
111
+
112
+ const commentAt = (line: string) => (line.includes('#') ? line.indexOf('#') : line.length)
113
+
114
+ // ── Finding the file ────────────────────────────────────────────────────────
115
+
116
+ export type SignersFile =
117
+ | { found: true; text: string }
118
+ /** Why not, in the words the refusal message repeats back to the pusher. */
119
+ | { found: false; why: string }
120
+
121
+ /**
122
+ * Read the `signers` file out of the commit a push points the list ref at.
123
+ *
124
+ * Injected rather than called directly so every decision above it is testable
125
+ * without a repository, a subprocess or a running git — the same seam
126
+ * `push-cert.ts` puts in front of its blob reader and `announce.ts` puts in
127
+ * front of `fetch`.
128
+ */
129
+ export type SignersSource = (oid: string) => SignersFile
130
+
131
+ /**
132
+ * The most a `signers` file walgit will read, in bytes — roughly a thousand
133
+ * keys, which is far past any plausible list and far short of a problem.
134
+ *
135
+ * A cap is not optional here, for two reasons that are both about what the file
136
+ * becomes. The resolved list is copied into `index.json`, the hottest object in
137
+ * the system: it is re-read on every push and re-written in full by every
138
+ * compare-and-swap, so a megabyte attached to it by an anonymous pusher is paid
139
+ * for by every later push to that name, forever, with no way to take it off.
140
+ * And reading an unbounded blob through a subprocess buffer is how a file gets
141
+ * silently TRUNCATED into a list that is not the one the ref holds — which is
142
+ * exactly the "a key drops out and nobody notices" failure the strict parser
143
+ * below exists to prevent. Refusing early is the only reading that cannot lie.
144
+ */
145
+ export const MAX_SIGNER_LIST_BYTES = 64 * 1024
146
+
147
+ /**
148
+ * The real source: `git cat-file`, against the repository the hook runs in.
149
+ *
150
+ * The first call is `--batch-check` over BOTH questions at once — is the tip a
151
+ * commit, and what is at `signers` in its tree — because git answers each input
152
+ * line with `<sha> <type> <size>` or `<input> missing`, so one subprocess
153
+ * distinguishes every failure this can have. That matters more than the
154
+ * subprocess it saves: a refusal that could not tell "you pointed the ref at a
155
+ * blob" from "your commit has no such file" from "your file is too big" would
156
+ * send most of its readers looking in the wrong place, and the message is the
157
+ * only documentation the agent being refused has.
158
+ *
159
+ * The size is read BEFORE the content, and nothing over the cap is read at all.
160
+ * `git()` buffers a subprocess's output, and an oversized read there does not
161
+ * reliably fail — it can return truncated bytes with a zero exit, which would
162
+ * resolve a list the ref does not hold.
163
+ *
164
+ * The pushed objects are still in the quarantine when this runs, which needs no
165
+ * special handling: git puts the quarantine on the hook's object path, so
166
+ * `cat-file` sees them exactly as `merge-base` does in `append-only.ts`.
167
+ */
168
+ export function gitSignersSource(gitDir: string): SignersSource {
169
+ return (oid) => {
170
+ const checked = git(['--git-dir', gitDir, 'cat-file', '--batch-check'], {
171
+ input: `${oid}\n${oid}:signers\n`,
172
+ })
173
+ const [tip, file] = checked.stdout.split('\n')
174
+ if (checked.status !== 0 || tip === undefined || file === undefined) {
175
+ return { found: false, why: `git could not read ${SIGNERS_REF} at ${oid}` }
176
+ }
177
+
178
+ const tipType = batchCheckType(tip)
179
+ if (tipType !== 'commit') {
180
+ return { found: false, why: `${SIGNERS_REF} points at ${tipType ?? 'no such object'}` }
181
+ }
182
+
183
+ const fileType = batchCheckType(file)
184
+ if (fileType === null) return { found: false, why: NO_FILE }
185
+ if (fileType !== 'blob') {
186
+ return { found: false, why: '`signers` in that commit is a directory, not a file' }
187
+ }
188
+
189
+ const size = batchCheckSize(file)
190
+ if (size === null) return { found: false, why: NO_FILE }
191
+ if (size > MAX_SIGNER_LIST_BYTES) {
192
+ return {
193
+ found: false,
194
+ why:
195
+ `the \`signers\` file is ${size} bytes, and walgit reads at most ` +
196
+ `${MAX_SIGNER_LIST_BYTES}`,
197
+ }
198
+ }
199
+
200
+ const blob = git(['--git-dir', gitDir, 'cat-file', 'blob', `${oid}:signers`])
201
+ // It was there a moment ago and a git object is immutable, so this is a
202
+ // read that failed rather than a file that is absent — and saying "add a
203
+ // `signers` file" to someone who just pushed one is worse than saying
204
+ // nothing.
205
+ if (blob.status !== 0) {
206
+ return { found: false, why: `git could not read the \`signers\` file at ${oid}` }
207
+ }
208
+ return { found: true, text: blob.stdout }
209
+ }
210
+ }
211
+
212
+ const NO_FILE = 'that commit has no file named `signers` in it'
213
+
214
+ /** `<sha> <type> <size>` → the type; `<input> missing` → `null`. */
215
+ function batchCheckType(line: string): string | null {
216
+ const type = line.trim().split(' ')[1]
217
+ return type === undefined || type === 'missing' ? null : type
218
+ }
219
+
220
+ function batchCheckSize(line: string): number | null {
221
+ const size = Number(line.trim().split(' ')[2])
222
+ return Number.isSafeInteger(size) ? size : null
223
+ }
224
+
225
+ // ── The verdict ─────────────────────────────────────────────────────────────
226
+
227
+ /**
228
+ * Every way a Signer List can refuse a push, across both decisions in this
229
+ * file. One union rather than two so a caller — the hook, a test, a future
230
+ * counter in front of the container — can name a refusal without knowing which
231
+ * of the two questions produced it.
232
+ */
233
+ export type RefusalKind =
234
+ /** The push is signed, by a key the repository's list does not name. */
235
+ | 'not-listed'
236
+ /** The push carried no certificate at all, on a name that requires one. */
237
+ | 'unsigned'
238
+ /** It carried one walgit could not turn into a key. */
239
+ | 'unverified'
240
+ /** The list this push writes names nobody. */
241
+ | 'empty-list'
242
+ /** walgit could not read a list out of what this push wrote. */
243
+ | 'unreadable-list'
244
+
245
+ /** The two halves of it: what `checkSignerList` can say, and what the gate can. */
246
+ export type ListRefusal = Extract<RefusalKind, 'empty-list' | 'unreadable-list'>
247
+ export type GateRefusal = Extract<RefusalKind, 'not-listed' | 'unsigned' | 'unverified'>
248
+
249
+ export type SignerListVerdict =
250
+ | {
251
+ ok: true
252
+ /** The list this push writes, or `null` when it writes none. */
253
+ signers: string[] | null
254
+ }
255
+ | { ok: false; kind: ListRefusal; message: string }
256
+
257
+ /**
258
+ * Judge what a push does to a repository's Signer List, and resolve it.
259
+ *
260
+ * One call answers both questions the caller has — *may this push land* and
261
+ * *what should the Index record* — because they are one reading of one file,
262
+ * and asking twice would let the answer that refuses and the answer that is
263
+ * recorded come from different bytes.
264
+ *
265
+ * A push that does not touch the list ref is `{ ok: true, signers: null }`,
266
+ * which is nearly every push. Deleting the ref is refused as `empty-list`: it
267
+ * leaves the name with no list at all, which is the giving-away this refusal
268
+ * exists to prevent, and is not distinguishable from it by anyone downstream.
269
+ */
270
+ export function checkSignerList(
271
+ repoId: string,
272
+ changes: readonly RefChange[],
273
+ read: SignersSource,
274
+ ): SignerListVerdict {
275
+ // The last one wins, matching what the ref will hold: git applies a push's
276
+ // updates in order, and a push naming one ref twice is a client bug rather
277
+ // than a case with a meaning of its own.
278
+ const moved = changes.filter((c) => c.ref === SIGNERS_REF).at(-1)
279
+ if (!moved) return { ok: true, signers: null }
280
+
281
+ if (moved.newOid === ZERO_OID) {
282
+ return refuse(repoId, 'empty-list', `this push deletes ${SIGNERS_REF}`)
283
+ }
284
+
285
+ const file = read(moved.newOid)
286
+ if (!file.found) return refuse(repoId, 'unreadable-list', file.why)
287
+
288
+ const parsed = parseSignerList(file.text)
289
+ if (!parsed.ok) {
290
+ return refuse(
291
+ repoId,
292
+ 'unreadable-list',
293
+ `line ${parsed.lineNumber} is not a key fingerprint: ${JSON.stringify(parsed.line)}`,
294
+ )
295
+ }
296
+ if (parsed.signers.length === 0) {
297
+ return refuse(repoId, 'empty-list', 'the file you pushed names no keys')
298
+ }
299
+ return { ok: true, signers: parsed.signers }
300
+ }
301
+
302
+ const refuse = (repoId: string, kind: ListRefusal, why: string): SignerListVerdict => ({
303
+ ok: false,
304
+ kind,
305
+ message: rejectionMessage(repoId, kind, why),
306
+ })
307
+
308
+ /**
309
+ * The message a refused list push reads. Product copy, like the append-only
310
+ * one: it states what walgit found, the format it wanted, and the one thing to
311
+ * do next — an agent that cannot act on a refusal has been told nothing.
312
+ */
313
+ function rejectionMessage(repoId: string, kind: ListRefusal, why: string): string {
314
+ const what =
315
+ kind === 'empty-list'
316
+ ? [
317
+ `An empty Signer List would leave ${repoId} claimable by anyone, which is a`,
318
+ 'way to lose the name rather than a way to release it. To hand the name on,',
319
+ 'push a list naming the other key; to stop using it, simply stop pushing.',
320
+ ]
321
+ : [
322
+ `walgit could not read a Signer List out of what you pushed to ${SIGNERS_REF},`,
323
+ `so it will not record one: an unreadable list would leave ${repoId} looking`,
324
+ 'claimed to you and unclaimed to the host.',
325
+ ]
326
+ return [
327
+ `walgit: refused — ${why}.`,
328
+ '',
329
+ ...what,
330
+ '',
331
+ `A Signer List is a COMMIT on ${SIGNERS_REF} whose tree holds a file named`,
332
+ '`signers`, one SSH key fingerprint per line:',
333
+ '',
334
+ ' # laptop',
335
+ ' SHA256:BMBEMXbMBsnjXwgNs+86IiJrPgYlZEsWxaKZW/2/1dw',
336
+ '',
337
+ 'Blank lines and `#` comments are ignored. A fingerprint is what',
338
+ '`ssh-keygen -lf <key>` prints. List at least two keys if you can: there is no',
339
+ 'recovery path for a lost one.',
340
+ '',
341
+ 'Nothing was uploaded; the repository is unchanged.',
342
+ ].join('\n')
343
+ }
344
+
345
+ // ── The gate ────────────────────────────────────────────────────────────────
346
+
347
+ /**
348
+ * What `pre-receive` could establish about who made this push.
349
+ *
350
+ * Three answers where Provenance has two, and the third one is the reason this
351
+ * type exists. `establishSigner` collapses every failure to `null` because a
352
+ * `null` Signer is a push that lands (docs/adr/0011); on a claimed name the two
353
+ * failures need different words, because *sign your push* and *your signature
354
+ * did not verify* are different things to go and do. An agent handed the first
355
+ * when the second is true re-sends the same failing signature.
356
+ */
357
+ export type PushSigner =
358
+ /** A certificate walgit verified, and the key it named. */
359
+ | { kind: 'signed'; fingerprint: string }
360
+ | {
361
+ /** No certificate at all — the anonymous push walgit has always taken. */
362
+ kind: 'unsigned'
363
+ /**
364
+ * Could this push have been signed at all — does the deployment set a
365
+ * nonce seed?
366
+ *
367
+ * It changes no verdict and one sentence. With no seed `git-receive-pack`
368
+ * never advertises the capability, so "push with `--signed=yes`" is
369
+ * advice the pusher's own git refuses, and a claimed name on such a
370
+ * deployment refuses everyone including whoever holds it. The gate still
371
+ * refuses — failing open here is precisely the bypass ADR-0012 closes —
372
+ * but the refusal names the misconfiguration instead of sending an agent
373
+ * to retry something that cannot work.
374
+ */
375
+ signable: boolean
376
+ }
377
+ /**
378
+ * A certificate walgit could not turn into a key: bad nonce, bad signature,
379
+ * missing or throwing verifier.
380
+ */
381
+ | { kind: 'unverified' }
382
+
383
+ /**
384
+ * Read the two answers together: the Signer `establishSigner` settled, and —
385
+ * only when it settled nothing — whether there was a certificate to settle.
386
+ *
387
+ * The env read is deliberately second and deliberately narrow. Who signed is
388
+ * still `establishSigner`'s answer and nothing here revisits it; this only
389
+ * chooses which sentence an unestablished Signer is told.
390
+ */
391
+ export function describeSigner(signer: string | null, env: PushCertEnv = process.env): PushSigner {
392
+ if (signer !== null) return { kind: 'signed', fingerprint: signer }
393
+ if (certificatePresented(env)) return { kind: 'unverified' }
394
+ return { kind: 'unsigned', signable: signedPushEnabled(env) }
395
+ }
396
+
397
+ export type SignerGateVerdict = { ok: true } | { ok: false; kind: GateRefusal; message: string }
398
+
399
+ /**
400
+ * Which of the gate's two askings this is. It changes two sentences and no
401
+ * verdict — the answer is the same function of the same three inputs either
402
+ * way, and only what has already happened to the pusher's objects differs.
403
+ *
404
+ * `pre-receive` runs before the upload, so its refusal can truthfully end
405
+ * "nothing was uploaded; the repository is unchanged". The publish runs after
406
+ * the upload, on a push a moving list overtook mid-flight — and possibly after
407
+ * an earlier transaction of that same push has already published a ref — so
408
+ * both halves of that sentence would be a lie. A refusal that lies about what
409
+ * it did with your objects is worse than one that says nothing.
410
+ */
411
+ export type GateStage = 'pre-receive' | 'publish'
412
+
413
+ /**
414
+ * May this push land, given who signed it and the list this name already holds?
415
+ *
416
+ * Pure over its three inputs, with no git, no store and no subprocess in reach:
417
+ * the list arrives already resolved from the Index (`WalIndex.claim`), which is
418
+ * what keeps ownership from depending on the Cache being materialized.
419
+ *
420
+ * `claimed` is **the list as it stood BEFORE this push**, and that is the whole
421
+ * of the grant rule: a push may move the list and a branch together, and the
422
+ * list it installs applies from the following push. The founding push needs no
423
+ * exception written for it, because an unclaimed name refuses nothing.
424
+ *
425
+ * **Asked twice, of two readings of the Index.** `pre-receive` asks it before
426
+ * the pack uploads, which is where a refusal is free — nothing has been written
427
+ * and no Orphan is left behind. The compare-and-swap that publishes asks it
428
+ * again, against the Index it is committing onto, which is where the answer is
429
+ * TRUE: a name that was free when the push was judged can be claimed while its
430
+ * pack uploads, and under append-only that write would be permanent. Being pure
431
+ * over its three inputs is what lets it be asked in both places without either
432
+ * caller knowing anything about the other. See `publishPush` in `src/push.ts`.
433
+ *
434
+ * **The Index is what enforces, and the ref is what is authoritative** — the
435
+ * gap ADR-0012 leaves to this slice, answered rather than hidden. The derived
436
+ * copy is maintained only while the flag is on, so a list pushed before it was
437
+ * turned on, or a list ref moved while it was off, leaves the two disagreeing:
438
+ * a name the ref says is claimed refuses nothing until its list is pushed
439
+ * again, and a name whose list moved while the flag was off is judged by the
440
+ * one the Index still holds. Neither is re-derived from the other, because
441
+ * re-deriving means reading a git object out of the Cache — and the Cache is
442
+ * disposable, which would make ownership depend on a node having materialized
443
+ * it. The rule for an operator is the short one: turn the flag on before anyone
444
+ * writes a list, and leave it on.
445
+ *
446
+ * An unclaimed name is `null`. An empty array is read as unclaimed too, and the
447
+ * asymmetry with `checkSignerList` — which refuses writing one — is the point:
448
+ * a list naming nobody cannot be written, so reaching one here means the Index
449
+ * disagrees with what this code can produce, and the two readings of that are
450
+ * "the name is open, as it was before anyone claimed it" and "the name is
451
+ * bricked, for everyone, forever". Only one of those has a way back.
452
+ */
453
+ export function checkSignerAllowed(
454
+ repoId: string,
455
+ signer: PushSigner,
456
+ claimed: readonly string[] | null,
457
+ changes: readonly RefChange[],
458
+ stage: GateStage = 'pre-receive',
459
+ ): SignerGateVerdict {
460
+ if (claimed === null || claimed.length === 0) return { ok: true }
461
+ if (signer.kind === 'signed' && claimed.includes(signer.fingerprint)) return { ok: true }
462
+ return {
463
+ ok: false,
464
+ kind: signer.kind === 'signed' ? 'not-listed' : signer.kind,
465
+ message: heldMessage(repoId, signer, changes, stage),
466
+ }
467
+ }
468
+
469
+ /**
470
+ * The message a stranger reads, and the only place most agents will ever learn
471
+ * that Signer Lists exist.
472
+ *
473
+ * Ownership's failure lands on our server, in our words, at the moment it is
474
+ * relevant — which is why the terse front door does not have to carry it
475
+ * (docs/adr/0012). So this says three things and an agent can act on each: the
476
+ * name is held, here is a free one to use instead, and here is how to be added
477
+ * to this one.
478
+ */
479
+ function heldMessage(
480
+ repoId: string,
481
+ signer: PushSigner,
482
+ changes: readonly RefChange[],
483
+ stage: GateStage,
484
+ ): string {
485
+ const why =
486
+ signer.kind === 'signed'
487
+ ? [
488
+ `Your push is signed by ${signer.fingerprint}, and ${repoId}'s Signer List does`,
489
+ 'not name that key.',
490
+ ]
491
+ : signer.kind === 'unsigned'
492
+ ? signer.signable
493
+ ? [
494
+ 'Your push carries no signature, so walgit cannot tell whose it is. A name',
495
+ 'that holds a Signer List takes signed pushes only:',
496
+ '',
497
+ ' git push --signed=yes origin HEAD:refs/heads/<branch>',
498
+ ]
499
+ : [
500
+ 'Your push carries no signature, and this host is not advertising signed',
501
+ 'pushes at all — so no push can satisfy this name, including the one that',
502
+ 'claimed it. That is a misconfiguration here, not something you can fix:',
503
+ 'whoever runs this host has set WALGIT_SIGNER_LISTS without setting',
504
+ 'WALGIT_PUSH_CERT_SEED. Push to a free name, and tell them.',
505
+ ]
506
+ : [
507
+ 'Your push carries a certificate walgit could not verify — a stale nonce, or a',
508
+ 'signature it could not check. A claimed name does not fall back to an',
509
+ 'anonymous push, so re-run the same `git push --signed=yes` to get a fresh',
510
+ 'nonce; if it keeps failing, `ssh-keygen -Y check-novalidate` is what walgit',
511
+ 'runs.',
512
+ ]
513
+ // Why a refusal arrived at the END of a push that was allowed to start. The
514
+ // pusher's own git told them nothing was wrong for as long as the upload
515
+ // took, and an agent handed the ordinary refusal after that would go looking
516
+ // for what it did differently this time. Nothing: the list moved.
517
+ //
518
+ // "moved" and not "was claimed", because both ways of moving reach this: a
519
+ // free name claimed mid-push, and a list that dropped this key mid-push. An
520
+ // agent told it was squatted when it was in fact revoked goes looking for a
521
+ // stranger instead of asking to be re-listed.
522
+ const late =
523
+ stage === 'publish'
524
+ ? [
525
+ `${repoId}'s Signer List moved while this push's objects were uploading, so the`,
526
+ 'refusal arrives at the end of the push rather than at the start. The list that',
527
+ 'judges it is the one standing now.',
528
+ '',
529
+ ]
530
+ : []
531
+ const refs = describeRefs(changes)
532
+ return [
533
+ `walgit: refused — ${repoId} is held by a Signer List.`,
534
+ '',
535
+ ...late,
536
+ ...(refs === null ? [] : [`This push would have written ${refs}.`]),
537
+ ...why,
538
+ '',
539
+ `${repoId} names the keys that may push to it on ${SIGNERS_REF} — anyone can`,
540
+ 'read it, and reads are not gated. Any name nobody has claimed is still free.',
541
+ '',
542
+ 'What you can do instead:',
543
+ ` - push to a free name: git remote set-url origin <same-host>/${suggestName(repoId)}.git`,
544
+ ` - or be added to this one: a listed key pushes a commit on ${SIGNERS_REF}`,
545
+ ' whose `signers` file gains the line `ssh-keygen -lf <your-key>` prints.',
546
+ ' A grant governs the NEXT push, so retry once theirs has landed.',
547
+ '',
548
+ // The publish wording is careful about two things the `pre-receive` one can
549
+ // state flatly. The pack DID upload, so "nothing was uploaded" would be a
550
+ // lie; and git updates refs one at a time unless the client asked for
551
+ // `--atomic`, so an earlier part of this same push may already have
552
+ // published — "the repository is unchanged" would be a lie too.
553
+ ...(stage === 'publish'
554
+ ? [
555
+ 'Nothing named above was written. git updates refs one at a time unless the',
556
+ 'client asked for --atomic, so any ref an earlier part of this push already',
557
+ 'published stays; objects nothing ends up referencing are collected.',
558
+ ]
559
+ : ['Nothing was uploaded; the repository is unchanged.']),
560
+ ].join('\n')
561
+ }
562
+
563
+ /**
564
+ * The refs this push would have written, named rather than counted: an agent
565
+ * pushing several branches at once needs to know the refusal took all of them.
566
+ * Truncated past three, because past three the list stops being read.
567
+ *
568
+ * `null` for a push naming none, which git does not send and which the sentence
569
+ * is therefore left out of entirely — "this push would have written nothing" is
570
+ * a line that can only confuse whoever manages to read it.
571
+ */
572
+ function describeRefs(changes: readonly RefChange[]): string | null {
573
+ const refs = changes.map((c) => c.ref)
574
+ if (refs.length === 0) return null
575
+ if (refs.length <= 3) return refs.join(', ')
576
+ return `${refs.slice(0, 3).join(', ')} and ${refs.length - 3} more`
577
+ }
@@ -1,10 +1,11 @@
1
1
  /**
2
2
  * Build the object store from the environment.
3
3
  *
4
- * Every entry point needs the same store — the smart-HTTP server, the SSH
5
- * forced command, and both hook processes — and the hooks are spawned by git,
6
- * not by us, so configuration can only travel as environment. One reader keeps
7
- * the four in agreement.
4
+ * Every entry point needs the same store — the smart-HTTP server, the operator
5
+ * CLI, and both hook processes — and the hooks are spawned by git, not by us,
6
+ * so configuration can only travel as environment. One reader keeps them in
7
+ * agreement. The container gets that environment from the Worker, which
8
+ * forwards it in worker/index.ts.
8
9
  *
9
10
  * Returning `null` for "not configured" is deliberate: the push path treats
10
11
  * that as fatal (there is nowhere to persist to, so nothing may be