@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
@@ -20,48 +20,29 @@
20
20
  import * as fs from 'node:fs'
21
21
  import * as path from 'node:path'
22
22
 
23
+ import { ZERO_OID } from '../shared/protocol'
24
+ import { walKey } from './keys'
25
+ import { writePending, type PendingPush } from './pending'
26
+ import { certSigner } from './push-cert'
27
+ import { checkSignerAllowed, describeSigner, type GateRefusal, type PushSigner } from './signers'
23
28
  import type { ObjectStore } from './store'
24
29
  import { ulid } from './ulid'
25
30
  import {
26
- ZERO_OID,
31
+ applyClaim,
32
+ applyProvenance,
27
33
  applyRefChanges,
28
34
  commitIndex,
29
35
  loadIndex,
30
36
  nextIndex,
31
- walKey,
37
+ sha256,
38
+ type Claim,
39
+ type Provenance,
40
+ type PushRecord,
32
41
  type RefChange,
33
42
  type WalEntry,
34
43
  type WalIndex,
35
44
  } from './wal-index'
36
45
 
37
- /**
38
- * What `pre-receive` hands to `reference-transaction`.
39
- *
40
- * The two hooks are separate processes with no channel between them, so the
41
- * uploaded entry is written into the repo directory. It is deliberately NOT a
42
- * WAL object: it is local scratch describing an upload nobody can see yet.
43
- */
44
- export interface PendingPush {
45
- /** Absent for a push that carried no objects, e.g. a branch deletion. */
46
- entry: Omit<WalEntry, 'seq'> | null
47
- }
48
-
49
- const PENDING = 'walgit-pending.json'
50
-
51
- export function pendingPath(gitDir: string): string {
52
- return path.join(gitDir, PENDING)
53
- }
54
-
55
- export function readPending(gitDir: string): PendingPush | null {
56
- const file = pendingPath(gitDir)
57
- if (!fs.existsSync(file)) return null
58
- return JSON.parse(fs.readFileSync(file, 'utf8')) as PendingPush
59
- }
60
-
61
- export function clearPending(gitDir: string): void {
62
- fs.rmSync(pendingPath(gitDir), { force: true })
63
- }
64
-
65
46
  /**
66
47
  * Parse the `<old-oid> SP <new-oid> SP <refname>` lines both hooks are fed.
67
48
  * The refname is taken verbatim to the end of the line: it may contain spaces.
@@ -97,8 +78,28 @@ export function quarantinePack(quarantineDir: string): { pack: string; idx: stri
97
78
  }
98
79
  }
99
80
 
100
- export function sha256(body: Uint8Array): string {
101
- return new Bun.CryptoHasher('sha256').update(body).digest('hex')
81
+ /**
82
+ * The Signer this push establishes, or `null` for "nobody, as far as walgit can
83
+ * tell" — computed once, by the caller, before anything is written.
84
+ *
85
+ * The reader is injected the way `announce`'s `fetchImpl` is: the default reads
86
+ * git's own environment and shells out to `ssh-keygen`, so every decision
87
+ * downstream of this stays testable without a keypair, a subprocess or a
88
+ * running git.
89
+ *
90
+ * The catch is unconditional and it is the fail-open rule itself: a reader that
91
+ * throws is a push with no Signer, not a push with an error (docs/adr/0011).
92
+ * `certSigner` already swallows its own failures, so today this guards the seam
93
+ * rather than the default — but the guarantee belongs to the seam, not to
94
+ * whoever happens to be plugged into it, and the caller is `hook-main`, where an
95
+ * escaping throw is fatal to the push.
96
+ */
97
+ export function establishSigner(signer: () => string | null = certSigner): string | null {
98
+ try {
99
+ return signer()
100
+ } catch {
101
+ return null
102
+ }
102
103
  }
103
104
 
104
105
  export interface PreReceiveContext {
@@ -107,6 +108,37 @@ export interface PreReceiveContext {
107
108
  gitDir: string
108
109
  quarantineDir: string | undefined
109
110
  now?: () => Date
111
+ /**
112
+ * Who made this push, as `describeSigner(establishSigner())` already answered
113
+ * it — a value and not a thunk. The hook settles the question above this call
114
+ * because a verdict that turns on the Signer has to be able to run before the
115
+ * upload; by the time this function runs there is nothing left to ask.
116
+ *
117
+ * The three-way `PushSigner` rather than the fingerprint alone, because the
118
+ * fingerprint is only what the Index records. The other two answers — no
119
+ * certificate, and a certificate that did not verify — are what a REFUSAL has
120
+ * to be able to tell apart, and the certificate itself is gone by the time
121
+ * the publish runs: it lives in the push's quarantine, and `pre-receive` is
122
+ * the only hook git shows it to. So it is read once here and written down.
123
+ *
124
+ * Required. Optional, it would read as "unsigned" to the compiler and as
125
+ * "forgotten" to nobody — a call site that dropped it would record no
126
+ * Provenance for a push that carried a perfectly good certificate, and
127
+ * typecheck.
128
+ */
129
+ signer: PushSigner
130
+ /**
131
+ * The Signer List this push writes, already resolved by the hook, or `null`
132
+ * when it writes none (docs/adr/0012).
133
+ *
134
+ * Optional, where `signer` beside it is required, and the asymmetry is real
135
+ * rather than an oversight: every push has an answer to "who signed this", so
136
+ * a forgotten argument there would silently discard a good one. Nearly no
137
+ * push has an answer to "what list does this write", so the default IS the
138
+ * answer for every caller that has nothing to say — and the one caller that
139
+ * does is the hook, which had to resolve it before the upload anyway.
140
+ */
141
+ signerList?: readonly string[] | null
110
142
  }
111
143
 
112
144
  /**
@@ -117,28 +149,56 @@ export interface PreReceiveContext {
117
149
  * is right in the common case and merely cosmetic when it is wrong: the ULID
118
150
  * keeps the key unique, and `index.json` carries the authoritative key for
119
151
  * every entry, so a mis-numbered key is never followed by anything.
152
+ *
153
+ * The Signer arrives already established (`ctx.signer`) rather than being read
154
+ * here: the hook has to hold it before it reaches this function, because a
155
+ * verdict that needs it and is reached after the upload would leave an Orphan
156
+ * behind every push it refused.
120
157
  */
121
158
  export async function preReceive(ctx: PreReceiveContext): Promise<void> {
122
159
  const now = ctx.now ?? (() => new Date())
160
+ const signer = ctx.signer
161
+ // One reading of the clock for the whole function, because all of it
162
+ // describes one push: the WAL entry, the Signer and the list that push wrote
163
+ // would otherwise be stamped milliseconds apart for no reason anyone reading
164
+ // them back could account for.
165
+ const at = now()
166
+ const ts = at.toISOString()
167
+ // Only a VERIFIED key becomes Provenance. The other two answers are things
168
+ // walgit could not establish, and the Index states what it knows.
169
+ const provenance: Provenance | null =
170
+ signer.kind === 'signed' ? { signer: signer.fingerprint, ts } : null
171
+ // `length` and not truthiness: an empty array is truthy, and recording an
172
+ // empty list is the state `src/signers.ts` refuses a push for reaching.
173
+ const claim: Claim | null = ctx.signerList?.length ? { signers: [...ctx.signerList], ts } : null
174
+ // `signer` unconditionally, unlike the two beside it: the publish re-asks the
175
+ // ownership question and needs the answer whatever it was, including the two
176
+ // shapes that record nothing.
177
+ const recorded = { signer, ...(provenance ? { provenance } : {}), ...(claim ? { claim } : {}) }
123
178
  const found = ctx.quarantineDir ? quarantinePack(ctx.quarantineDir) : null
124
179
  if (!found) {
125
180
  // A ref-only push (a delete, or a branch pointed at an object the server
126
- // already has) is legitimate and still has to publish its ref change.
127
- fs.writeFileSync(pendingPath(ctx.gitDir), JSON.stringify({ entry: null }))
181
+ // already has) is legitimate and still has to publish its ref change — and
182
+ // its provenance: a branch pointed at objects the repository already has
183
+ // moves a ref, and is signed like any other push. A list ref pointed at a
184
+ // commit the repository already holds is the same case.
185
+ writePending(ctx.gitDir, { entry: null, ...recorded })
128
186
  return
129
187
  }
130
188
 
131
189
  const { index } = await loadIndex(ctx.store, ctx.repoId)
132
- const id = ulid(now().getTime())
133
- const packBody = new Uint8Array(fs.readFileSync(found.pack))
190
+ const id = ulid(at.getTime())
191
+ // The `Buffer` goes to the store as it is. A Node `Buffer` already IS a
192
+ // `Uint8Array`, so wrapping it in `new Uint8Array(…)` would change nothing
193
+ // about the value and allocate a second full copy of the pack — up to
194
+ // `WALGIT_MAX_PUSH_BYTES` of it, per in-flight push, which is what sized the
195
+ // container.
196
+ const packBody = fs.readFileSync(found.pack)
134
197
  const key = walKey(ctx.repoId, index.seq + 1, id, 'pack')
135
198
 
136
199
  await ctx.store.put(key, packBody)
137
200
  if (found.idx) {
138
- await ctx.store.put(
139
- walKey(ctx.repoId, index.seq + 1, id, 'idx'),
140
- new Uint8Array(fs.readFileSync(found.idx)),
141
- )
201
+ await ctx.store.put(walKey(ctx.repoId, index.seq + 1, id, 'idx'), fs.readFileSync(found.idx))
142
202
  }
143
203
 
144
204
  const entry: Omit<WalEntry, 'seq'> = {
@@ -146,9 +206,9 @@ export async function preReceive(ctx: PreReceiveContext): Promise<void> {
146
206
  kind: 'push',
147
207
  size: packBody.byteLength,
148
208
  sha256: sha256(packBody),
149
- ts: now().toISOString(),
209
+ ts,
150
210
  }
151
- fs.writeFileSync(pendingPath(ctx.gitDir), JSON.stringify({ entry } satisfies PendingPush))
211
+ writePending(ctx.gitDir, { entry, ...recorded })
152
212
  }
153
213
 
154
214
  export type PublishResult =
@@ -157,6 +217,66 @@ export type PublishResult =
157
217
  | { ok: false; reason: 'ref-conflict'; ref: string; expected: string; actual: string }
158
218
  /** Lost every compare-and-swap attempt against an index that kept moving. */
159
219
  | { ok: false; reason: 'contended' }
220
+ /**
221
+ * The name was claimed while this push uploaded, and the list that now stands
222
+ * does not name the key that signed it. Carries the gate's own message,
223
+ * because a refusal reached here is the same refusal `pre-receive` makes and
224
+ * has to read like one.
225
+ */
226
+ | { ok: false; reason: 'not-allowed'; kind: GateRefusal; message: string }
227
+
228
+ export interface PublishOptions {
229
+ /** How many compare-and-swap attempts before giving up. */
230
+ attempts?: number
231
+ /**
232
+ * Re-ask the ownership question at the compare-and-swap, against the Index
233
+ * this attempt is publishing onto. On exactly when the deployment has Signer
234
+ * Lists on — the caller passes `signerListsEnabled()` rather than this file
235
+ * reading the environment, so the gate and the flag that governs it are
236
+ * settled in one place (`hook-main`), for both askings.
237
+ */
238
+ signerLists?: boolean
239
+ }
240
+
241
+ /**
242
+ * Who made this push, as the pending record can still describe them.
243
+ *
244
+ * `pre-receive` writes the full three-way answer down, because the certificate
245
+ * is gone by the time this runs and *sign your push* and *your signature did
246
+ * not verify* are different things to go and do. A record written without one
247
+ * is read back from the Provenance it did record: that recovers a listed key
248
+ * exactly — which is the only answer that lets a push LAND — and collapses the
249
+ * two failures into whichever of them the environment still shows.
250
+ */
251
+ function pendingSigner(pending: PendingPush): PushSigner {
252
+ return pending.signer ?? describeSigner(pending.provenance?.signer ?? null)
253
+ }
254
+
255
+ /**
256
+ * Is the list the Index holds the one THIS push installed?
257
+ *
258
+ * git updates refs one transaction at a time unless the client asked for
259
+ * `--atomic`, so a push moving the list and a branch together publishes across
260
+ * several compare-and-swaps — and once the first has landed, the Index holds
261
+ * this push's own list. Re-asking the gate against it would break the grant
262
+ * rule for the one shape that rule exists for: a push may move the list and a
263
+ * branch together, and the list it installs applies from the FOLLOWING push.
264
+ * The founding push that lists somebody else's key would refuse its own branch,
265
+ * and a revocation that removes the pusher would refuse the rest of itself.
266
+ *
267
+ * The whole `Claim` is the identity, timestamp and all: `pre-receive` reads the
268
+ * clock once for a push, so no other push can have written this exact value,
269
+ * and one that raced this one for a free name lost the list ref outright — the
270
+ * ref-conflict check above is what refused it, before this could be asked.
271
+ */
272
+ function claimIsThisPush(index: WalIndex, pending: PendingPush): boolean {
273
+ const own = pending.claim
274
+ const held = index.claim
275
+ if (!own || !held || own.ts !== held.ts) return false
276
+ return (
277
+ own.signers.length === held.signers.length && own.signers.every((s, i) => s === held.signers[i])
278
+ )
279
+ }
160
280
 
161
281
  /**
162
282
  * Publish the pending entry with the push's ref changes, under CAS.
@@ -170,30 +290,97 @@ export type PublishResult =
170
290
  *
171
291
  * `index.json` is the source of truth for that check, not the local ref: a
172
292
  * local ref disagreeing with the index is a stale cache, and reconcile's job.
293
+ *
294
+ * Ownership is re-asked here too, and it is the one verdict that is. See the
295
+ * comment on the call below for why that is not a general rule.
173
296
  */
174
297
  export async function publishPush(
175
298
  store: ObjectStore,
176
299
  repoId: string,
177
300
  pending: PendingPush,
178
301
  changes: readonly RefChange[],
179
- attempts = 5,
302
+ options: PublishOptions = {},
180
303
  ): Promise<PublishResult> {
304
+ const attempts = options.attempts ?? 5
181
305
  for (let i = 0; i < attempts; i += 1) {
182
306
  const { index, etag } = await loadIndex(store, repoId)
183
307
 
184
308
  for (const change of changes) {
185
309
  const actual = index.refs[change.ref] ?? ZERO_OID
186
310
  if (actual !== change.oldOid) {
187
- return { ok: false, reason: 'ref-conflict', ref: change.ref, expected: change.oldOid, actual }
311
+ return {
312
+ ok: false,
313
+ reason: 'ref-conflict',
314
+ ref: change.ref,
315
+ expected: change.oldOid,
316
+ actual,
317
+ }
318
+ }
319
+ }
320
+
321
+ // Ownership, asked a SECOND time — the gate already ran in `pre-receive`,
322
+ // and it ran there against an Index read before the pack uploaded. For a
323
+ // real repository that upload is seconds, not microseconds, and a name that
324
+ // was free when the push was judged can be claimed before it publishes.
325
+ // Landing it anyway is a permanent stranger-write, because agentgit is
326
+ // append-only: exactly the thing docs/adr/0012 exists to prevent, arriving
327
+ // in the one moment that design says needs no exception.
328
+ //
329
+ // `index.claim` is the list as it stood BEFORE this push applies its own —
330
+ // `applyClaim` installs that in `next`, below — which is both the gate's
331
+ // own rule (a grant governs the NEXT push) and what lets the founding push
332
+ // through its own re-check. Written against the post-apply value this would
333
+ // refuse every claim ever made — and `claimIsThisPush` is the same rule for
334
+ // the LATER transactions of one push, whose earlier one already applied it.
335
+ //
336
+ // BELOW the ref-conflict check, the opposite order to `pre-receive`'s, and
337
+ // deliberately: a second claim racing this one moves the same ref and is
338
+ // already answered above, in the words any contended ref gets. What reaches
339
+ // this line is a push with no ref conflict to catch it, which is the whole
340
+ // of the exposure.
341
+ //
342
+ // This is a refusal AFTER the upload, which the `pre-receive` placement
343
+ // exists to avoid — and it cannot be moved earlier, because the race is
344
+ // precisely that the earlier answer went stale. The orphaned pack is the
345
+ // accepted cost: `findOrphans` reclaims exactly this shape, and the
346
+ // `aborted` branch in `hook-main` names the key it left behind.
347
+ //
348
+ // Narrow on purpose, and not the start of a rule that every verdict is
349
+ // re-run here. Append-only and the size caps judge what was PUSHED, which
350
+ // cannot change underneath the push. Ownership judges the REPOSITORY, which
351
+ // can.
352
+ if (options.signerLists && !claimIsThisPush(index, pending)) {
353
+ const verdict = checkSignerAllowed(
354
+ repoId,
355
+ pendingSigner(pending),
356
+ index.claim?.signers ?? null,
357
+ changes,
358
+ 'publish',
359
+ )
360
+ if (!verdict.ok) {
361
+ return { ok: false, reason: 'not-allowed', kind: verdict.kind, message: verdict.message }
188
362
  }
189
363
  }
190
364
 
191
365
  // A ref-only push bumps no sequence number and appends no entry: there is
192
366
  // no log record to append, only new ref state. Keeping seq contiguous with
193
367
  // the entry list is what lets a restore trust `entries` by itself.
368
+ //
369
+ // Both records ride on BOTH branches, which is why they are fields on the
370
+ // Index and not on a WAL entry: a ref-only push has no entry to hang them
371
+ // from and is exactly as signed, and exactly as much a claim, as any other.
372
+ const record: PushRecord = {
373
+ provenance: pending.provenance ?? null,
374
+ claim: pending.claim ?? null,
375
+ }
194
376
  const next = pending.entry
195
- ? nextIndex(index, pending.entry, changes)
196
- : { ...index, refs: applyRefChanges(index.refs, changes) }
377
+ ? nextIndex(index, pending.entry, changes, record)
378
+ : {
379
+ ...index,
380
+ refs: applyRefChanges(index.refs, changes),
381
+ provenance: applyProvenance(index.provenance, changes, record.provenance),
382
+ claim: applyClaim(index.claim, changes, record.claim),
383
+ }
197
384
 
198
385
  const result = await commitIndex(store, next, etag)
199
386
  if (result.ok) return { ok: true, index: next }
@@ -15,10 +15,10 @@
15
15
  * publish the truth it was just told.
16
16
  */
17
17
 
18
- import { spawnSync } from 'node:child_process'
19
18
  import * as fs from 'node:fs'
20
19
  import * as path from 'node:path'
21
20
 
21
+ import { git } from './git'
22
22
  import type { WalIndex } from './wal-index'
23
23
 
24
24
  export interface ReconcileResult {
@@ -37,10 +37,8 @@ export interface ReconcileResult {
37
37
  }
38
38
 
39
39
  export function localRefs(gitDir: string): Record<string, string> {
40
- const res = spawnSync('git', ['--git-dir', gitDir, 'for-each-ref', '--format=%(objectname) %(refname)'], {
41
- encoding: 'utf8',
42
- })
43
- if (res.status !== 0) throw new Error(`for-each-ref failed: ${res.stderr?.trim()}`)
40
+ const res = git(['--git-dir', gitDir, 'for-each-ref', '--format=%(objectname) %(refname)'])
41
+ if (res.status !== 0) throw new Error(`for-each-ref failed: ${res.stderr.trim()}`)
44
42
  const refs: Record<string, string> = {}
45
43
  for (const line of res.stdout.split('\n')) {
46
44
  const match = /^(\S+) (.+)$/.exec(line)
@@ -52,12 +50,11 @@ export function localRefs(gitDir: string): Record<string, string> {
52
50
  /** Which of these oids the local object store actually has. One process. */
53
51
  export function presentObjects(gitDir: string, oids: readonly string[]): Set<string> {
54
52
  if (oids.length === 0) return new Set()
55
- const res = spawnSync('git', ['--git-dir', gitDir, 'cat-file', '--batch-check'], {
53
+ const res = git(['--git-dir', gitDir, 'cat-file', '--batch-check'], {
56
54
  input: `${oids.join('\n')}\n`,
57
- encoding: 'utf8',
58
55
  })
59
56
  const present = new Set<string>()
60
- for (const line of (res.stdout ?? '').split('\n')) {
57
+ for (const line of res.stdout.split('\n')) {
61
58
  const match = /^(\S+) (\S+) \d+$/.exec(line)
62
59
  if (match && match[2] !== 'missing') present.add(match[1]!)
63
60
  }
@@ -1,98 +1,43 @@
1
1
  /**
2
2
  * The repo-addressing seam.
3
3
  *
4
- * SSH has no SNI: one front door serves every repository, and the repository is
5
- * named in the client's own command (`git@host:<repo_id>.git`) or in the
6
- * smart-HTTP URL path. That makes the repo name attacker-controlled on every
7
- * entry point, so exactly one function turns it into a path — this one — and
8
- * both entry points funnel through it.
4
+ * The repository a request means is named in the smart-HTTP URL path, so the
5
+ * repo name is attacker-controlled on the way in. Exactly one function turns it
6
+ * into a path — this one — and every entry point funnels through it.
7
+ *
8
+ * Nothing here touches the disk or the log: it is string in, path out. The
9
+ * grammar itself is `shared/protocol.ts`'s, because a repository name arriving
10
+ * over the event socket is attacker-controlled in exactly the way one arriving
11
+ * in a path is, and one gate that both transports apply is the only way they
12
+ * cannot disagree. Provisioning the bare repo that path names is `cache.ts`.
9
13
  */
10
14
 
11
- import { spawnSync } from 'node:child_process'
12
- import * as fs from 'node:fs'
13
15
  import * as path from 'node:path'
14
16
 
15
- import { installHooks } from './hooks'
17
+ import { REPO_ID } from '../shared/protocol'
16
18
 
17
19
  export type ResolvedRepo = { repoId: string; dir: string }
18
20
 
19
21
  /**
20
- * A repo id is one flat segment. Flat because the WAL keys repositories by id
21
- * (docs/adr/0007), not by a directory tree, and a hierarchy on disk that the
22
- * log cannot express would drift the moment a repo is rebuilt from the log.
22
+ * The repo id a request names, validated. Split out from `resolveRepo` because
23
+ * the operator CLI materializes into a path the operator chose rather than into
24
+ * `reposDir` — the id still has to pass the same gate, and there must not be a
25
+ * second copy of it to drift.
23
26
  */
24
- const REPO_ID = /^[A-Za-z0-9][A-Za-z0-9._-]*$/
25
-
26
- export function resolveRepo(reposDir: string, requested: string): ResolvedRepo {
27
- // Strip the address forms a client can send: ssh://host/alpha.git yields a
28
- // leading slash, and OpenSSH passes `~/alpha.git` through unexpanded.
29
- const repoId = requested
30
- .replace(/^~\//, '')
31
- .replace(/^\//, '')
32
- .replace(/\.git$/, '')
27
+ export function normalizeRepoId(requested: string): string {
28
+ // Strip the address forms a client can send: a URL path yields a leading
29
+ // slash, and `.git` is a suffix the client chooses, not part of the id.
30
+ const repoId = requested.replace(/^\//, '').replace(/\.git$/, '')
33
31
  // A trailing newline is not a formality: JavaScript's `$` matches before one,
34
32
  // so `alpha\n` would otherwise pass validation and reach a shell-free but
35
33
  // still surprising path.
36
34
  if (/[\r\n]/.test(repoId) || !REPO_ID.test(repoId)) {
37
35
  throw new Error(`invalid repository name: ${JSON.stringify(requested)}`)
38
36
  }
39
- return { repoId, dir: path.join(reposDir, `${repoId}.git`) }
40
- }
41
-
42
- /**
43
- * Create the bare repo if it is missing, and return it either way.
44
- *
45
- * Auto-creation on first contact is deliberate: a walgit repository has no
46
- * lifecycle of its own on this machine — the disk is a cache, and a push to a
47
- * name nobody has used yet is how a repo comes into existence.
48
- *
49
- * "Empty" is the right starting point even for a repo the log already knows
50
- * about: `syncRepo` runs on every access, and an empty repo is one whose refs
51
- * are all missing, which is precisely the signal that materializes it. Creating
52
- * and restoring are therefore the same code path with different amounts of log.
53
- */
54
- export function ensureBareRepo(repo: ResolvedRepo): ResolvedRepo {
55
- if (!fs.existsSync(path.join(repo.dir, 'HEAD'))) {
56
- fs.mkdirSync(repo.dir, { recursive: true })
57
- // `main` as the default HEAD, because HEAD on a bare repo is what a clone
58
- // checks out: created as `master` and pushed to as `main`, a clone succeeds
59
- // and leaves an empty working tree, which reads as data loss.
60
- run('git', ['init', '--bare', '--quiet', '--initial-branch=main', repo.dir])
61
- }
62
- // Re-applied on every call, not just at creation: `receive.unpackLimit=0`
63
- // is what makes a small push arrive as a packfile rather than exploding into
64
- // loose objects, and there is no packfile to upload if it does.
65
- run('git', ['--git-dir', repo.dir, 'config', 'receive.unpackLimit', '0'])
66
- // The hooks ARE the push path. Re-installed on every access for the same
67
- // reason as the config above: a repo that arrived here by any other route
68
- // would otherwise accept pushes that never reach the write-ahead log.
69
- installHooks(repo.dir, repo.repoId)
70
- return repo
37
+ return repoId
71
38
  }
72
39
 
73
- function run(cmd: string, args: string[]): void {
74
- const res = spawnSync(cmd, args, { stdio: ['ignore', 'ignore', 'pipe'] })
75
- if (res.status !== 0) {
76
- throw new Error(`${cmd} ${args.join(' ')} failed: ${res.stderr?.toString().trim()}`)
77
- }
78
- }
79
-
80
- export type GitService = 'git-upload-pack' | 'git-receive-pack'
81
- export type SshRequest = { service: GitService; requested: string }
82
-
83
- /**
84
- * Parse `SSH_ORIGINAL_COMMAND` under the forced command.
85
- *
86
- * This is the whole of the SSH attack surface: the key's `command=` option
87
- * means the client's command line is never executed, only read here, so the
88
- * grammar is a strict allow-list of the two transport verbs and one
89
- * single-quoted argument. `git-upload-archive` is excluded on purpose — it is
90
- * a third verb clients rarely need and one more code path to reason about.
91
- */
92
- export function parseSshCommand(original: string | undefined): SshRequest {
93
- const match = /^git[- ](upload-pack|receive-pack) '([^']*)'$/.exec(original ?? '')
94
- if (!match) {
95
- throw new Error(`refused: only git-upload-pack and git-receive-pack are permitted`)
96
- }
97
- return { service: `git-${match[1]}` as GitService, requested: match[2]! }
40
+ export function resolveRepo(reposDir: string, requested: string): ResolvedRepo {
41
+ const repoId = normalizeRepoId(requested)
42
+ return { repoId, dir: path.join(reposDir, `${repoId}.git`) }
98
43
  }