@zabaca/zbc 0.11.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 (74) 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/cloudflare-access/index.ts +85 -14
  68. package/templates/infra/modules/fly/index.ts +150 -10
  69. package/templates/infra/modules/turso/index.ts +43 -3
  70. package/templates/infra/package.json +1 -1
  71. package/templates/apps/walgit/entrypoint.sh +0 -59
  72. package/templates/apps/walgit/fly.toml +0 -52
  73. package/templates/apps/walgit/src/ssh-shell.ts +0 -36
  74. package/templates/apps/walgit/sshd_config +0 -38
@@ -1,9 +1,9 @@
1
- # The seven-scenario verification suite
1
+ # The verification suite
2
2
 
3
3
  One command runs every guarantee walgit claims:
4
4
 
5
5
  ```bash
6
- bun run e2e # all seven
6
+ bun run e2e # every scenario
7
7
  bun run e2e -- --quick # smaller fixtures — disclosed in the output
8
8
  bun run e2e -- --only 2,7
9
9
  ```
@@ -43,9 +43,9 @@ directory it created, and is wired to the normal exit, to a throw, and to
43
43
 
44
44
  | Code | Meaning |
45
45
  | ---- | ------- |
46
- | 0 | All seven passed |
46
+ | 0 | Everything passed |
47
47
  | 1 | At least one scenario failed |
48
- | 2 | Nothing failed, but the suite ran less than the full seven (`--only`) |
48
+ | 2 | Nothing failed, but the suite ran less than the full set (`--only`) |
49
49
 
50
50
  Code 2 exists so a narrowed sweep cannot be mistaken for a clean one by a
51
51
  script. For the same reason `--quick`, an unbaselined latency size, and a run
@@ -64,8 +64,8 @@ A breach fails the build, and the failure says what to do about it. The knob is
64
64
  different machine — a bucket run should have its own, since a network round trip
65
65
  per entry is not a regression.
66
66
 
67
- Machine wake is deliberately excluded: on Fly a client pays wake (~1.35 s, from
68
- the milestone-0 spike) **plus** replay, and blending the two makes a regression
67
+ Cold start is deliberately excluded: a client pays it (median 1.77 s, from
68
+ the Containers spike) **plus** replay, and blending the two makes a regression
69
69
  unattributable. The suite reports `fetch` and `init+refs` separately for the
70
70
  same reason.
71
71
 
@@ -76,3 +76,97 @@ Scenario 2 enumerates its kill points in `KILL_POINTS` — `after-upload`,
76
76
  (a `SIGKILL` at an arbitrary moment, which is the check on the enumeration being
77
77
  incomplete). The list is enumerated rather than exhaustive, and the suite says
78
78
  so in its output. **Adding a step to the push path means adding it here.**
79
+
80
+ ## Scenario 8 and the events endpoint
81
+
82
+ Scenario 8 is the only one with a stand-in, and it is a narrow one. In
83
+ production the sockets live in a Durable Object behind the Worker; here they
84
+ live in a Bun server inside the suite (`EventsEndpoint` in `harness.ts`), because
85
+ the alternative is a Workers runtime in the test path.
86
+
87
+ What is **not** stood in for is everything that decides anything: the announce
88
+ credential is checked by `authorizeAnnounce`, the `watch` message is parsed by
89
+ `parseWatch`, the fan-out is `watchCovers`, the handshake is `handshake`, the
90
+ backpressure policy is the real `Outbox` — the same modules the Worker calls.
91
+ The handshake's refs are read from the node's `/_walgit/refs`, over the same
92
+ internal endpoint the Durable Object uses, so they come from the Index rather
93
+ than from the suite's own memory.
94
+
95
+ The push side is entirely real, which is the point of the scenario: the hook
96
+ fires, `post-receive` announces over a real socket to a real port, and the
97
+ subscriber is a real WebSocket client. It covers three things a unit test
98
+ cannot see — a push arriving, a **ref-only** push (no pack uploaded at all)
99
+ arriving, and a push that lost the compare-and-swap announcing nothing.
100
+
101
+ ## Scenario 9 and the signing key
102
+
103
+ Scenario 9 is the only end-to-end check on push provenance (`docs/adr/0011`),
104
+ and it is the only place in the suite where a **key** exists. It generates an
105
+ ed25519 keypair with `ssh-keygen`, configures the clone to sign with it, pushes
106
+ `--signed=yes`, and compares the Signer read back from `/_walgit/provenance`
107
+ against `ssh-keygen -lf` on the public half — the one fingerprint in the run
108
+ walgit had no hand in producing.
109
+
110
+ Nothing here is stood in for, deliberately: git's own verdict on an SSH push
111
+ certificate is `GIT_PUSH_CERT_STATUS=N` with no signer at all, so a stubbed
112
+ verifier would have reported success against exactly the mistake this scenario
113
+ exists to catch.
114
+
115
+ The key is generated by the scenario, removed by it, and asserted gone. No
116
+ credential is needed to run it: the nonce seed is a local string, and
117
+ `WALGIT_PUSH_CERT_SEED` on the node is the whole of what turns the capability
118
+ on — with it unset, the client's own git refuses `--signed=yes` before a byte
119
+ reaches the network.
120
+
121
+ One asymmetry worth knowing, because it makes a "no new objects" check by WAL
122
+ entry count wrong: a **signed** ref-only push sends an empty pack (a 32-byte
123
+ header and trailer) where an unsigned one sends none at all. The scenario reads
124
+ the object count out of the pack header instead.
125
+
126
+ # `live.ts` — a separate check, against a deployment
127
+
128
+ Everything above is `suite.ts`, which starts its own node. `live.ts` is not part
129
+ of it and shares none of its machinery beyond `harness.ts`'s `git` helpers: it
130
+ asks whether a **deployment** has ownership turned on, which
131
+ `WALGIT_SIGNER_LISTS` being instance configuration (`docs/adr/0012`) makes
132
+ unanswerable from inside the package.
133
+
134
+ ```bash
135
+ bun run e2e:live -- --origin https://walgit.example.com # …and it enforces
136
+ bun run e2e:live -- --origin https://… --expect-unclaimed
137
+ bun run e2e:live -- --local # boot src/server.ts with ownership on
138
+ ```
139
+
140
+ The mechanism itself is proven by `src/push.e2e.test.ts` — claim, grant, revoke,
141
+ the atomic list-and-branch steal — and this file must not grow into a second
142
+ copy of that. What it adds is a real `git push` over HTTP, with real ed25519
143
+ keys and real push certificates, **against an address**: a free name claimed, the
144
+ list read back from `/_walgit/provenance`, an unlisted key refused, an unsigned
145
+ push refused, and the claimed repository still cloned with no credential.
146
+
147
+ The first two forms are **assertions about an origin**, not verbosity levels, and
148
+ exactly one is true of any deployment that advertises signed pushes: the default
149
+ says *this origin enforces Signer Lists*, `--expect-unclaimed` says *it does
150
+ not*. Each exits 0 only when its own assertion holds, so neither can be mistaken
151
+ for the other by a script — there is deliberately no mode that merely reports
152
+ what it found. `--expect-unclaimed` requires `/llms.txt` to say in its own words
153
+ that the host keeps no list of allowed signers, rather than settling for the
154
+ absence of the opposite: a deployment with ownership on and no
155
+ `WALGIT_PUSH_CERT_SEED` says neither, and that misconfiguration must not pass as
156
+ "ownership is off".
157
+
158
+ `--local` boots the container process alone, so `/llms.txt` — the Worker's
159
+ document — is not there to check, and the run says so in its output rather than
160
+ passing quietly over it. It is a smoke test for this file, not evidence about
161
+ any instance.
162
+
163
+ | Code | Meaning |
164
+ | ---- | ------- |
165
+ | 0 | the assertion holds |
166
+ | 1 | it does not, or the origin could not be reached |
167
+ | 64 | the arguments were wrong |
168
+
169
+ Under `--origin` the run leaves `walgit-live-*` repositories behind on that
170
+ origin — collected by its retention window if it has one, permanent if not, with
171
+ the claimed one claimed forever. It names them on the way out. Under `--local`
172
+ there is nothing to leave: the node and its store go with the scratch directory.
@@ -1,5 +1,5 @@
1
1
  /**
2
- * The machinery the seven scenarios share: a real walgit node they can kill, a
2
+ * The machinery the scenarios share: a real walgit node they can kill, a
3
3
  * real git client, and a real object store with a prefix nobody else is using.
4
4
  *
5
5
  * The one design rule here is that nothing in this file is a double. The
@@ -21,6 +21,21 @@ import * as path from 'node:path'
21
21
  import type { ObjectStore } from '../src/store'
22
22
  import { storeFromEnv } from '../src/store-env'
23
23
  import { ulid } from '../src/ulid'
24
+ import {
25
+ type Handshake,
26
+ type RefEvent,
27
+ type WatchEntry,
28
+ authorizeAnnounce,
29
+ authorizeSubscribe,
30
+ encode,
31
+ handshake,
32
+ parseAnnounce,
33
+ parseWatch,
34
+ watchCovers,
35
+ watchedRepos,
36
+ } from '../shared/events'
37
+ import { Outbox } from '../shared/outbox'
38
+ import { ANNOUNCE_PATH, EVENTS_PATH, INTERNAL_HEADER, REFS_PATH } from '../shared/protocol'
24
39
 
25
40
  export const APP_ROOT = path.resolve(import.meta.dir, '..')
26
41
 
@@ -298,3 +313,249 @@ export async function commit(dir: string, body: string): Promise<string> {
298
313
  await gitOk(dir, 'commit', '--quiet', '-m', body.trim() || 'commit')
299
314
  return (await gitOk(dir, 'rev-parse', 'HEAD')).trim()
300
315
  }
316
+
317
+ // ── The events endpoint ─────────────────────────────────────────────────────
318
+
319
+ interface SocketData {
320
+ watch: WatchEntry[] | null
321
+ outbox: Outbox | null
322
+ }
323
+
324
+ /**
325
+ * The other end of the ref-event stream, for the scenarios that need one.
326
+ *
327
+ * In production this is a Worker holding a Durable Object; here it is a Bun
328
+ * server holding the sockets in memory. That substitution is the one place in
329
+ * this file where something is not the production article, and it is bounded on
330
+ * purpose: everything that DECIDES anything — whether the announce credential
331
+ * is good, what a `watch` message means, which sockets an announcement reaches,
332
+ * what goes on the wire, and what happens to a subscriber that stops draining —
333
+ * is imported from `shared/events.ts` and `shared/outbox.ts`, the same modules
334
+ * the Worker calls. What stands in for the Durable Object is accept, remember,
335
+ * send, forget, which is what `worker/events-do.ts` says it is and no more.
336
+ *
337
+ * The alternative would be a Workers runtime inside the suite, which the
338
+ * scenarios do not need: the wiring they prove — a hook that fires, an
339
+ * announcement that authenticates, a socket that receives — is all on the
340
+ * container's side of that boundary, and every part of it here is real.
341
+ */
342
+ export class EventsEndpoint {
343
+ /** The secret the container's push path presents (`WALGIT_EVENTS_TOKEN`). */
344
+ readonly token = 'walgit-e2e-events'
345
+ port = 0
346
+ /** Every announcement the push path published, in arrival order. */
347
+ readonly announced: RefEvent[] = []
348
+ private server: ReturnType<typeof Bun.serve> | null = null
349
+ private refsNode: WalgitNode | null = null
350
+ private readonly subscribers = new Set<Subscriber>()
351
+ // Bun has no `getWebSockets()`; tracking them is the one piece of bookkeeping
352
+ // the Durable Object gets from its runtime and this does not.
353
+ private readonly live = new Set<Bun.ServerWebSocket<SocketData>>()
354
+
355
+ async start(): Promise<void> {
356
+ this.port = await freePort()
357
+ // Arrow handlers throughout: they close over `this`, which is what lets the
358
+ // decisions stay methods on this class rather than free functions holding a
359
+ // reference to it.
360
+ this.server = Bun.serve<SocketData>({
361
+ port: this.port,
362
+ hostname: '127.0.0.1',
363
+ idleTimeout: 0,
364
+ fetch: async (request, server) => {
365
+ const url = new URL(request.url)
366
+
367
+ if (url.pathname === ANNOUNCE_PATH) {
368
+ if (request.method !== 'POST')
369
+ return new Response('method not allowed\n', { status: 405 })
370
+ if (!authorizeAnnounce(request.headers.get('authorization'), this.token)) {
371
+ return new Response('unauthorized\n', { status: 401 })
372
+ }
373
+ const parsed = parseAnnounce(await request.json().catch(() => null))
374
+ if (!parsed.ok) return new Response(`${parsed.error}\n`, { status: 400 })
375
+ this.announced.push(...parsed.value)
376
+ return Response.json({ ok: true, delivered: this.broadcast(parsed.value) })
377
+ }
378
+
379
+ if (url.pathname !== EVENTS_PATH) return new Response('not found\n', { status: 404 })
380
+ // Exactly the credential a read of the repository needs, checked with
381
+ // the function the Worker checks it with.
382
+ const allowed = authorizeSubscribe({
383
+ authorization: request.headers.get('authorization'),
384
+ tokens: [TOKEN],
385
+ isPublic: false,
386
+ })
387
+ if (!allowed) return new Response('unauthorized\n', { status: 401 })
388
+ if (server.upgrade(request, { data: { watch: null, outbox: null } })) return undefined
389
+ return new Response('expected a websocket upgrade\n', { status: 426 })
390
+ },
391
+ websocket: {
392
+ open: (ws) => {
393
+ this.live.add(ws)
394
+ },
395
+ message: async (ws, raw) => {
396
+ const parsed = parseWatch(typeof raw === 'string' ? raw : new TextDecoder().decode(raw))
397
+ if (!parsed.ok) {
398
+ ws.send(encode({ error: parsed.error }))
399
+ return
400
+ }
401
+ let refsByRepo: Record<string, Record<string, string>>
402
+ try {
403
+ refsByRepo = await this.currentRefs(watchedRepos(parsed.value))
404
+ } catch (err) {
405
+ ws.send(encode({ error: `could not read current refs: ${(err as Error).message}` }))
406
+ return
407
+ }
408
+ // Read, record, answer — the order `events-do.ts` keeps, so a push
409
+ // landing mid-handshake cannot fall between the two.
410
+ ws.data.watch = parsed.value
411
+ ws.send(encode(handshake(parsed.value, refsByRepo)))
412
+ },
413
+ close: (ws) => {
414
+ this.live.delete(ws)
415
+ ws.data.watch = null
416
+ ws.data.outbox = null
417
+ },
418
+ },
419
+ })
420
+ }
421
+
422
+ /** Where the container announces to (`WALGIT_EVENTS_URL`). */
423
+ get url(): string {
424
+ return `http://127.0.0.1:${this.port}`
425
+ }
426
+
427
+ /**
428
+ * The node whose Index answers a handshake.
429
+ *
430
+ * Set after the node starts, because the node needs this endpoint's URL at
431
+ * boot — the same circularity the deployment has, resolved the same way: the
432
+ * container is told where to announce, and the socket layer asks the
433
+ * container for refs when a subscriber arrives.
434
+ */
435
+ refsFrom(node: WalgitNode): void {
436
+ this.refsNode = node
437
+ }
438
+
439
+ /** Connect a subscriber and complete its handshake. */
440
+ async subscribe(watch: WatchEntry[]): Promise<Subscriber> {
441
+ const subscriber = new Subscriber(`ws://127.0.0.1:${this.port}${EVENTS_PATH}`)
442
+ this.subscribers.add(subscriber)
443
+ await subscriber.open(watch)
444
+ return subscriber
445
+ }
446
+
447
+ stop(): void {
448
+ for (const subscriber of this.subscribers) subscriber.close()
449
+ this.subscribers.clear()
450
+ this.server?.stop(true)
451
+ this.server = null
452
+ }
453
+
454
+ /** Fan one announcement out, through the real `Outbox`. */
455
+ private broadcast(events: readonly RefEvent[]): number {
456
+ let delivered = 0
457
+ for (const ws of this.live) {
458
+ const watch = ws.data.watch
459
+ if (!watch) continue
460
+ const wanted = events.filter((event) => watchCovers(watch, event))
461
+ if (wanted.length === 0) continue
462
+ ws.data.outbox ??= new Outbox({
463
+ send: (data) => {
464
+ ws.send(data)
465
+ },
466
+ close: (code, reason) => {
467
+ ws.close(code, reason)
468
+ },
469
+ })
470
+ delivered += ws.data.outbox.offer(wanted).sent
471
+ }
472
+ return delivered
473
+ }
474
+
475
+ /**
476
+ * Ref state from the node's Index, over the container's internal endpoint —
477
+ * the same request `events-do.ts` makes, header and all.
478
+ */
479
+ private async currentRefs(repos: string[]): Promise<Record<string, Record<string, string>>> {
480
+ const node = this.refsNode
481
+ if (!node) throw new Error('e2e: the events endpoint has no node to read refs from')
482
+ const byRepo: Record<string, Record<string, string>> = {}
483
+ for (const repo of repos) {
484
+ const response = await fetch(
485
+ `http://127.0.0.1:${node.port}${REFS_PATH}?repo=${encodeURIComponent(repo)}`,
486
+ { headers: { [INTERNAL_HEADER]: '1' } },
487
+ )
488
+ if (!response.ok) throw new Error(`refs lookup for ${repo}: ${response.status}`)
489
+ const body = (await response.json()) as { refs?: Record<string, string> }
490
+ byRepo[repo] = body.refs ?? {}
491
+ }
492
+ return byRepo
493
+ }
494
+ }
495
+
496
+ /**
497
+ * A client on the stream.
498
+ *
499
+ * A real WebSocket to a real port, so a scenario asserting that a sha arrived
500
+ * is asserting that it crossed a socket — the wiring failure this exists to
501
+ * catch is precisely one a direct call to the fan-out would not see.
502
+ */
503
+ export class Subscriber {
504
+ /** Every event message received after the handshake, in arrival order. */
505
+ readonly events: RefEvent[] = []
506
+ handshake: Handshake | null = null
507
+ private socket: WebSocket | null = null
508
+
509
+ constructor(private readonly url: string) {}
510
+
511
+ async open(watch: WatchEntry[]): Promise<void> {
512
+ const socket = new WebSocket(this.url, {
513
+ headers: { authorization: `Bearer ${TOKEN}` },
514
+ } as never)
515
+ this.socket = socket
516
+ await new Promise<void>((resolve, reject) => {
517
+ socket.addEventListener('open', () => resolve(), { once: true })
518
+ socket.addEventListener('error', () => reject(new Error('subscriber could not connect')), {
519
+ once: true,
520
+ })
521
+ })
522
+ const handshaken = new Promise<void>((resolve, reject) => {
523
+ const timer = setTimeout(() => reject(new Error('no handshake within 10s')), 10_000)
524
+ socket.addEventListener('message', (event: MessageEvent) => {
525
+ const message = JSON.parse(String(event.data)) as Handshake | RefEvent | { error: string }
526
+ if ('error' in message) {
527
+ clearTimeout(timer)
528
+ reject(new Error(`subscriber refused: ${message.error}`))
529
+ return
530
+ }
531
+ if ('ok' in message) {
532
+ clearTimeout(timer)
533
+ this.handshake = message
534
+ resolve()
535
+ return
536
+ }
537
+ this.events.push(message)
538
+ })
539
+ })
540
+ socket.send(JSON.stringify({ watch }))
541
+ await handshaken
542
+ }
543
+
544
+ /** Wait for an event matching `match`, or fail after `timeoutMs`. */
545
+ async next(match: (event: RefEvent) => boolean, timeoutMs = 10_000): Promise<RefEvent> {
546
+ const deadline = Date.now() + timeoutMs
547
+ while (Date.now() < deadline) {
548
+ const found = this.events.find(match)
549
+ if (found) return found
550
+ await sleep(25)
551
+ }
552
+ throw new Error(
553
+ `no matching ref event within ${timeoutMs}ms; saw ${JSON.stringify(this.events)}`,
554
+ )
555
+ }
556
+
557
+ close(): void {
558
+ this.socket?.close()
559
+ this.socket = null
560
+ }
561
+ }