@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
@@ -3,17 +3,26 @@
3
3
  "version": "0.0.1",
4
4
  "private": true,
5
5
  "type": "module",
6
+ "bin": {
7
+ "walgit": "./src/cli.ts"
8
+ },
6
9
  "scripts": {
7
10
  "test": "bun test src",
8
- "typecheck": "tsc --noEmit",
11
+ "typecheck": "tsc --noEmit && tsc --noEmit -p tsconfig.worker.json",
9
12
  "bench:materialize": "bun run src/materialize.bench.ts",
10
- "e2e": "bun run e2e/suite.ts"
13
+ "walgit": "bun run src/cli.ts",
14
+ "e2e": "bun run e2e/suite.ts",
15
+ "e2e:live": "bun run e2e/live.ts",
16
+ "deploy": "wrangler deploy"
11
17
  },
12
18
  "dependencies": {
13
19
  "aws4fetch": "^1.0.20"
14
20
  },
15
21
  "devDependencies": {
22
+ "@cloudflare/containers": "^0.3.7",
23
+ "@cloudflare/workers-types": "^4.20250101.0",
16
24
  "@types/bun": "^1.3.14",
17
- "typescript": "^5.7.0"
25
+ "typescript": "^7.0.2",
26
+ "wrangler": "^4.0.0"
18
27
  }
19
28
  }
@@ -2,25 +2,20 @@
2
2
  "name": "walgit",
3
3
  "kind": "app",
4
4
  "targetDir": "packages/walgit",
5
- "description": "walgit: a git host where object storage holds the write-ahead log and is the source of truth, and the bare repo on local disk is a disposable cache rebuildable from the log (ADR-0007 in the zbc repository, docs/adr/)",
5
+ "description": "walgit: a git host where object storage holds the write-ahead log and is the source of truth, and the bare repo on local disk is a disposable cache rebuildable from the log (ADR-0007 in the zbc repository, docs/adr/). Serves git smart-HTTP from a Cloudflare Container behind a thin Worker.",
6
6
  "modules": [
7
- "fly",
7
+ "cloudflare",
8
8
  "r2"
9
9
  ],
10
- "dependencies": {
11
- "aws4fetch": "^1.0.20"
12
- },
13
10
  "secrets": [
14
- "FLY_API_TOKEN",
15
- "WALGIT_SSH_HOST_KEY",
16
- "WALGIT_SSH_AUTHORIZED_KEYS",
11
+ "CLOUDFLARE_API_TOKEN",
17
12
  "WALGIT_HTTP_TOKENS",
18
13
  "WALGIT_S3_ENDPOINT",
19
14
  "WALGIT_S3_BUCKET",
20
15
  "WALGIT_S3_ACCESS_KEY_ID",
21
16
  "WALGIT_S3_SECRET_ACCESS_KEY"
22
17
  ],
23
- "signupUrl": "https://fly.io/app/sign-up",
24
- "tokenUrl": "https://fly.io/user/personal_access_tokens",
25
- "instructions": "STATUS: the front door and the push path are deployable \u2014 a Fly machine serving git over SSH (:22, raw TCP) and smart-HTTP (:443), with every push persisted to the write-ahead log in object storage before it is acknowledged and linearized by compare-and-swap on index.json. The bare repos on the machine's filesystem are a cache, reconciled against the log on every access and materialized from it when the objects a ref needs are absent. A repo whose cache is gone is rebuilt from the log on first access \u2014 not disaster recovery but the normal path, since the machine stops whenever it is idle. The log is compacted in the background: once a repo accumulates WALGIT_COMPACTION_THRESHOLD (default 50) un-superseded entries, a post-receive hook hands a detached process a `git repack -adf` whose single pack is published as one WAL entry under a per-repo lease, so a cold restore replays one entry however many pushes the repo has taken. Superseded entries and the packs rejected pushes leave behind are deleted only after WALGIT_GC_GRACE_MS (default one hour), never immediately \u2014 a restore that read index.json a moment before a compaction is still downloading what that compaction superseded, and deleting it out from under that restore fails silently. Both knobs are optional environment variables, not secrets. walgit runs on Fly rather than Cloudflare because it serves git over SSH and no Cloudflare product delivers raw inbound TCP to a Worker or Container (see docs/adr/0006 in the zbc repository). Requires FLY_API_TOKEN (a personal access token, not a deploy token), plus: WALGIT_SSH_HOST_KEY (an ed25519 private key \u2014 `ssh-keygen -t ed25519 -f walgit_host -N ''`; it must be a secret because the container filesystem does not survive a machine stop and a regenerated host key trips every client's man-in-the-middle warning), WALGIT_SSH_AUTHORIZED_KEYS (newline-separated public keys; each is pinned to a forced command server-side), WALGIT_HTTP_TOKENS (comma-separated bearer tokens; git sends them as the Basic-auth password), and the log's home: WALGIT_S3_ENDPOINT, WALGIT_S3_BUCKET, WALGIT_S3_ACCESS_KEY_ID and WALGIT_S3_SECRET_ACCESS_KEY from an r2 module instance's S3-API credentials. Without those four the host still serves reads from its local cache but REFUSES every push \u2014 accepting one it cannot persist is the single failure this app exists to prevent. The fly instance MUST set ipv4: \"dedicated\" \u2014 SSH is on port 22 and shared IPv4 covers 80/443 only, a difference `fly deploy` does not report."
18
+ "signupUrl": "https://dash.cloudflare.com/sign-up",
19
+ "tokenUrl": "https://dash.cloudflare.com/profile/api-tokens",
20
+ "instructions": "STATUS: the front door and the push path are deployable — a Cloudflare Worker proxying to a Durable-Object-bound Container that serves git smart-HTTP, with every push persisted to the write-ahead log in object storage before it is acknowledged and linearized by compare-and-swap on index.json. The bare repos on the container's filesystem are a cache, reconciled against the log on every access and materialized from it when the objects a ref needs are absent. A repo whose cache is gone is rebuilt from the log on first access — not disaster recovery but the normal path, since the container sleeps when idle and its disk is wiped completely on every restart. The log is compacted in the background: once a repo accumulates WALGIT_COMPACTION_THRESHOLD (default 50) un-superseded entries, a post-receive hook hands a detached process a `git repack -adf` whose single pack is published as one WAL entry under a per-repo lease, so a cold restore replays one entry however many pushes the repo has taken. Superseded entries and the packs rejected pushes leave behind are deleted only after WALGIT_GC_GRACE_MS (default one hour), never immediately — a restore that read index.json a moment before a compaction is still downloading what that compaction superseded, and deleting it out from under that restore fails silently. Both knobs are optional environment variables, not secrets.\n\nTRANSPORT: smart-HTTP only. walgit used to also serve SSH, which needed raw inbound TCP and is why it ran on Fly (docs/adr/0006 in the zbc repository); no Cloudflare product delivers raw inbound TCP, so the SSH transport was removed rather than kept on a second host. Clients send the token as the Basic-auth password: `git clone https://walgit:$TOKEN@<worker-host>/myrepo.git`. A repository is created on first push to a name nobody has used.\n\nDEPLOYMENT: through the `cloudflare` module. `wrangler deploy` builds the container image from this package's Dockerfile, so Docker must be running at apply time and the account must be on a Workers Paid plan with Containers enabled. Set `immediateContainerRollout: true` on the instance — wrangler's gradual rollout never drains a single always-warm container, so a redeployed image otherwise never takes effect until it idle-sleeps. That flag covers the IMAGE only; a deploy that changes only forwarded env vars produces no new container version to roll, and the container reads its environment once at start — so the Durable Object fingerprints the environment it would boot with, keeps it in DO storage, and destroys the running container the first time the two differ (reconcileEnv in worker/index.ts). Changing a var therefore costs one container restart on the next request and takes effect immediately. CLOUDFLARE_API_TOKEN needs Workers Scripts: Edit and Containers: Edit. Trap when tearing one down: `wrangler delete` on the Worker does NOT delete its container application — that needs a separate `wrangler containers delete`, or the instances stay live.\n\nCONFIGURATION: the container runs outside the Worker's binding graph, so it reads the store over the S3 API rather than through an r2 binding, and it can only be told about it via environment variables the Worker forwards (CONTAINER_ENV in shared/container-env.ts). Wire these as the cloudflare instance's `workerSecrets`: WALGIT_HTTP_TOKENS (comma-separated bearer tokens, comma-separated so a credential can be rotated without a window where neither works), and the log's home — WALGIT_S3_ENDPOINT, WALGIT_S3_BUCKET, WALGIT_S3_ACCESS_KEY_ID and WALGIT_S3_SECRET_ACCESS_KEY, from an r2 module instance's S3-API credentials. Without those four the host still serves reads from its local cache but REFUSES every push — accepting one it cannot persist is the single failure this app exists to prevent. A secret that is not in that forward list reaches the Worker and stops there.\n\nOPERATOR CLI: src/cli.ts — `bun src/cli.ts <serve|materialize|verify|gc|compact>`, run inside the container so it reads the same credentials the app does; there is no separate config file. `verify` is read-only and exits non-zero when the disk disagrees with index.json; `gc` reclaims superseded and orphaned objects and only reports unless given --yes; `compact` forces a compaction now rather than waiting for the threshold, and `--force=false` asks whether one is due without causing it.\n\nREF EVENTS: optional, off unless configured. Set WALGIT_EVENTS_URL (the deployment's own public origin) and WALGIT_EVENTS_TOKEN (a shared secret, wired as a workerSecret and forwarded to the container) and walgit serves a WebSocket at /_walgit/events: a client sends {\"watch\":[{\"repo\":\"my-thing\",\"refs\":[\"refs/heads/main\"]}]}, is answered with the current sha of each watched ref, and is then sent the new sha every time one moves (sha null is a deletion; an omitted refs list watches every ref in that repository). Subscribing takes exactly the credential a read takes, so a public deployment has a public stream. Events are latest state, not a log — no cursor, no since, no sequence number on the wire; a reconnecting client gets current state in its handshake. The push path announces from post-receive, which git runs only after the compare-and-swap on index.json won, so a push that lost is never announced; the announcement is authenticated, bounded, and can never fail a push. With either variable unset the endpoint does not exist."
26
21
  }
@@ -0,0 +1,189 @@
1
+ /**
2
+ * What this deployment advertises, derived once.
3
+ *
4
+ * Three agent-facing documents describe the same host — the plain-text `GET /`
5
+ * (`src/instructions.ts`), the landing page (`shared/landing.ts`) and
6
+ * `/llms.txt` (`shared/llms.ts`) — and the push path enforces what they
7
+ * describe. Each of them used to read the environment for itself, from three
8
+ * types that disagreed about how to spell "unset" and about which variables a
9
+ * capability was made of. The rule that kept them honest was a paragraph
10
+ * repeated in three doc comments and enforced nowhere; of the nine commits that
11
+ * touched the landing page since July, eight had to touch one of the others.
12
+ *
13
+ * So the derivation lives here, once, and everything that states a capability
14
+ * or enforces one reads the same value. A capability added here is a required
15
+ * field, so every construction site fails to compile until it says what it
16
+ * offers — which is the property a hand-maintained "everything on" test fixture
17
+ * cannot have.
18
+ *
19
+ * ── one predicate per capability, and the renderers combine nothing ─────────
20
+ *
21
+ * A renderer that wrote `signedPushes && signerLists` for itself is a fourth
22
+ * place the rule lives. Both readings of the Signer List flag are fields here
23
+ * (`namesCanRefuse`, `namesCanBeClaimed`), named for what a sentence using them
24
+ * is doing, so a document asks for the reading it needs rather than assembling
25
+ * it.
26
+ *
27
+ * ── the host is not a capability ────────────────────────────────────────────
28
+ *
29
+ * Every document also prints the host it was reached on, and it is deliberately
30
+ * not in here: `GET /` needs a full origin including the scheme (a local test
31
+ * reaches it over plain http and the example has to work verbatim), while the
32
+ * two edge documents take a bare hostname and supply `https://`/`wss://`
33
+ * themselves. One field could not serve both, and the two are passed as
34
+ * arguments beside these facts rather than folded into them.
35
+ */
36
+
37
+ import type { ContainerEnvName } from './container-env'
38
+ import { flagEnabled, positiveNumber } from './policy'
39
+ import { signedPushEnabled } from './provenance'
40
+
41
+ /**
42
+ * The variables a capability may be read from — and only those the container is
43
+ * actually told about.
44
+ *
45
+ * `Extract` rather than a plain union of string literals, deliberately: a
46
+ * capability derived from a variable missing from `CONTAINER_ENV`
47
+ * (`shared/container-env.ts`) would be one the edge advertises and the push
48
+ * path never sees, silently, because every one of these is optional and an
49
+ * unset one just means unenforced. Narrowing through `ContainerEnvName` makes
50
+ * that a compile error instead. If a name here ever stops type-checking, the
51
+ * forward list is the bug — not this type.
52
+ */
53
+ type CapabilityVar = Extract<
54
+ ContainerEnvName,
55
+ | 'WALGIT_PUBLIC'
56
+ | 'WALGIT_APPEND_ONLY'
57
+ | 'WALGIT_RETENTION_HOURS'
58
+ | 'WALGIT_MAX_PUSH_BYTES'
59
+ | 'WALGIT_MAX_REPO_BYTES'
60
+ | 'WALGIT_EVENTS_URL'
61
+ | 'WALGIT_EVENTS_TOKEN'
62
+ | 'WALGIT_PUSH_CERT_SEED'
63
+ | 'WALGIT_SIGNER_LISTS'
64
+ >
65
+
66
+ /**
67
+ * An environment named exactly by the variables a capability is read from.
68
+ *
69
+ * `capabilitiesFrom` accepts something wider (see below), so this is what a
70
+ * caller writing a LITERAL should annotate it with: a misspelled variable in a
71
+ * literal typed as this is a compile error, whereas the same literal handed
72
+ * straight to `capabilitiesFrom` would be accepted and quietly read as unset.
73
+ * That is what every test fixture in this package is typed as.
74
+ */
75
+ export type CapabilityEnv = Partial<Record<CapabilityVar, string>>
76
+
77
+ /**
78
+ * What this deployment offers, as the documents and the push path both read it.
79
+ *
80
+ * Every field is REQUIRED and absence is `null`, never an omitted key. Optional
81
+ * fields would let a new capability be forgotten at a construction site and
82
+ * default to "off" there, which is precisely the drift this module exists to
83
+ * end — and `null` is the spelling `positiveNumber` already returns, so the
84
+ * numbers arrive here without a conversion that could invent a second meaning
85
+ * for a missing limit.
86
+ */
87
+ export type Capabilities = {
88
+ /** Reads and writes take no credential. */
89
+ publicAccess: boolean
90
+ /** Refs only move forward; a rewrite or a deletion is refused. */
91
+ appendOnly: boolean
92
+ /**
93
+ * The ref-event stream is served, and something can publish to it.
94
+ *
95
+ * BOTH halves, because either alone is a stream that never delivers: the
96
+ * token is what claims the socket path at the edge, and the URL is where the
97
+ * container's `post-receive` announces. With only the token, the handshake
98
+ * answers with current refs and then nothing ever arrives, because the push
99
+ * path has nowhere to announce to — which is worse than no stream at all,
100
+ * since an agent writes the client before finding out.
101
+ */
102
+ events: boolean
103
+ /**
104
+ * A signed push is accepted, and who made it is recorded.
105
+ *
106
+ * From the nonce seed, which IS the capability: with none,
107
+ * `git-receive-pack` never advertises `push-cert` and a client asking to
108
+ * sign is refused by its OWN git, before a byte leaves the machine. A
109
+ * document offering it there would hand an agent a flag that cannot work.
110
+ */
111
+ signedPushes: boolean
112
+ /**
113
+ * The gate is on: a claimed name refuses a stranger. Corrects
114
+ * "world-writable".
115
+ *
116
+ * The raw `WALGIT_SIGNER_LISTS` flag, and it is the right strength for any
117
+ * sentence that only states what `pre-receive` refuses — because the hook
118
+ * refuses on this flag by itself (`signerListsEnabled`, `src/signers.ts`).
119
+ * On a deployment that sets it with no nonce seed, a claimed name refuses
120
+ * EVERY push, which makes unconditional writability more wrong rather than
121
+ * less.
122
+ */
123
+ namesCanRefuse: boolean
124
+ /**
125
+ * Safe to send somebody to claim a name: the gate is on AND signing is
126
+ * possible.
127
+ *
128
+ * The strength every sentence that TEACHES claiming needs. With the flag and
129
+ * no seed nothing can sign, so an agent following those instructions would
130
+ * claim the name with an unsigned push and then be refused on every push to
131
+ * it, its own included, with no way to sign out of it.
132
+ */
133
+ namesCanBeClaimed: boolean
134
+ /** A repository is collected this many hours after its last push. */
135
+ retentionHours: number | null
136
+ /** Largest single push, in bytes. */
137
+ maxPushBytes: number | null
138
+ /** Largest total size of one repository, in bytes. */
139
+ maxRepoBytes: number | null
140
+ }
141
+
142
+ /**
143
+ * Read an environment into what it advertises.
144
+ *
145
+ * Takes the environment as an argument rather than reaching for one, because
146
+ * the two halves do not have the same one to hand: the container has
147
+ * `process.env`, read once at boot, and the Worker has a binding object it
148
+ * reads per request. That asymmetry is correct and is why `reconcileEnv`
149
+ * (`worker/index.ts`) exists — what they must share is the reading, and this is
150
+ * it.
151
+ *
152
+ * Every predicate is the one that enforces the thing: `flagEnabled` and
153
+ * `positiveNumber` from `shared/policy.ts`, `signedPushEnabled` from
154
+ * `shared/provenance.ts`. Nothing is parsed a second way here.
155
+ *
156
+ * The second half of the parameter type is what lets the container hand over
157
+ * `process.env` — an all-optional type is "weak" to TypeScript, which refuses a
158
+ * source that declares no property in common with it, and `NodeJS.ProcessEnv`
159
+ * declares only `NODE_ENV` and `TZ`.
160
+ *
161
+ * It does not widen what may be READ here: a property access on a union has to
162
+ * exist on BOTH halves, so a variable outside `CapabilityVar` is a compile
163
+ * error inside this function. It DOES widen what a caller may pass — a literal
164
+ * with a misspelled variable is accepted and read as unset — so a caller
165
+ * writing one annotates it `CapabilityEnv`, which is checked.
166
+ */
167
+ export function capabilitiesFrom(
168
+ env: CapabilityEnv | Record<string, string | undefined>,
169
+ ): Capabilities {
170
+ const namesCanRefuse = flagEnabled(env.WALGIT_SIGNER_LISTS)
171
+ const signedPushes = signedPushEnabled(env.WALGIT_PUSH_CERT_SEED)
172
+
173
+ return {
174
+ publicAccess: flagEnabled(env.WALGIT_PUBLIC),
175
+ appendOnly: flagEnabled(env.WALGIT_APPEND_ONLY),
176
+ // Blank collapses to unset, the same reading `announceConfigFromEnv`
177
+ // (`src/announce.ts`) makes of the same two variables — the config the push
178
+ // path announces with and this advertisement cannot be allowed to disagree.
179
+ events: nonBlank(env.WALGIT_EVENTS_URL) && nonBlank(env.WALGIT_EVENTS_TOKEN),
180
+ signedPushes,
181
+ namesCanRefuse,
182
+ namesCanBeClaimed: namesCanRefuse && signedPushes,
183
+ retentionHours: positiveNumber(env.WALGIT_RETENTION_HOURS),
184
+ maxPushBytes: positiveNumber(env.WALGIT_MAX_PUSH_BYTES),
185
+ maxRepoBytes: positiveNumber(env.WALGIT_MAX_REPO_BYTES),
186
+ }
187
+ }
188
+
189
+ const nonBlank = (raw: string | undefined): boolean => typeof raw === 'string' && raw.trim() !== ''
@@ -0,0 +1,114 @@
1
+ /**
2
+ * The environment the container boots with, and a fingerprint of it.
3
+ *
4
+ * The container is a separate process on a separate machine: it reads its
5
+ * configuration from `process.env` exactly once, at start. That is a deliberate
6
+ * property — `src/server.ts` resolves the policy at boot "so the page and the
7
+ * sweeper can never disagree" — and re-reading `process.env` per request would
8
+ * not make it any fresher, because a running process's environment is fixed.
9
+ * The only way a new value reaches the container is a new container.
10
+ *
11
+ * A `wrangler deploy` that changes only vars produces no new container image,
12
+ * so `--containers-rollout immediate` has nothing to roll: the Worker picks the
13
+ * value up on its next request and the container keeps serving the old one, for
14
+ * as long as traffic keeps it awake. The fingerprint below is what closes that
15
+ * gap — the Durable Object compares it against the one it last booted with and
16
+ * replaces the container when they differ (see `WalgitContainer` in worker/index.ts).
17
+ */
18
+
19
+ /**
20
+ * Every variable the container is allowed to be told about, and no more.
21
+ *
22
+ * A limit that does not reach the container is a limit `GET /` never states and
23
+ * the push path never enforces — silently, since every one of these is optional
24
+ * and an unset one simply means unenforced.
25
+ */
26
+ export const CONTAINER_ENV = [
27
+ 'WALGIT_HTTP_TOKENS',
28
+ 'WALGIT_S3_ENDPOINT',
29
+ 'WALGIT_S3_BUCKET',
30
+ 'WALGIT_S3_ACCESS_KEY_ID',
31
+ 'WALGIT_S3_SECRET_ACCESS_KEY',
32
+ 'WALGIT_S3_REGION',
33
+ 'WALGIT_COMPACTION_THRESHOLD',
34
+ 'WALGIT_GC_GRACE_MS',
35
+ 'WALGIT_DELETE_GRACE_MS',
36
+ 'WALGIT_PUBLIC',
37
+ 'WALGIT_APPEND_ONLY',
38
+ 'WALGIT_RETENTION_HOURS',
39
+ 'WALGIT_MAX_PUSH_BYTES',
40
+ 'WALGIT_MAX_REPO_BYTES',
41
+ // The ref-event stream's two halves. The push path announces from inside the
42
+ // container, so it needs both where to announce (the Worker's own public
43
+ // origin) and the secret that proves it is walgit's push path and not a
44
+ // stranger fabricating events (shared/events.ts).
45
+ 'WALGIT_EVENTS_URL',
46
+ 'WALGIT_EVENTS_TOKEN',
47
+ // Signed pushes. The seed is what `git-receive-pack` derives its nonce from,
48
+ // and receive-pack runs inside the container — so this is the variable that
49
+ // decides whether the capability is advertised at all (src/push-cert.ts).
50
+ 'WALGIT_PUSH_CERT_SEED',
51
+ // Signer Lists (docs/adr/0012). Its own variable rather than a consequence of
52
+ // the seed above: the seed is the flag for SIGNING because a client's own git
53
+ // refuses `--signed` where it is unset, so that capability cannot be asked for
54
+ // where it is not offered. Ownership is a server-side refusal with no such
55
+ // coupling, and riding the seed would turn it on for every deployment that
56
+ // already set one.
57
+ 'WALGIT_SIGNER_LISTS',
58
+ ] as const
59
+
60
+ export type ContainerEnvName = (typeof CONTAINER_ENV)[number]
61
+
62
+ /**
63
+ * The forwarded subset of the Worker's environment.
64
+ *
65
+ * Blank is dropped rather than forwarded as an empty string, because every
66
+ * consumer inside the container reads "unset" and "set to nothing" the same
67
+ * way, and forwarding the difference would make two spellings of one state.
68
+ */
69
+ export function containerEnv(
70
+ source: Partial<Record<ContainerEnvName, string>>,
71
+ ): Record<string, string> {
72
+ const entries: [string, string][] = []
73
+ for (const name of CONTAINER_ENV) {
74
+ const value = source[name]
75
+ if (value !== undefined && value !== '') entries.push([name, value])
76
+ }
77
+ return Object.fromEntries(entries)
78
+ }
79
+
80
+ /**
81
+ * A short, stable digest of an environment — equal exactly when the environment
82
+ * the container would boot with is equal.
83
+ *
84
+ * Hashed rather than stored verbatim on purpose: this value is persisted in
85
+ * Durable Object storage, and half of what it covers is credentials. A digest
86
+ * answers the only question the caller has ("is this the same environment?")
87
+ * without keeping a second copy of the object store's keys anywhere.
88
+ *
89
+ * FNV-1a over a canonical serialization: synchronous (so the constructor and
90
+ * the request path can both use it without a promise), dependency-free, and
91
+ * sufficient here — this is a change detector between values this deployment
92
+ * chose itself, not a defence against a crafted collision.
93
+ */
94
+ export function fingerprintEnv(env: Record<string, string>): string {
95
+ // Sorted so key order — which `containerEnv` fixes but a caller need not —
96
+ // cannot make one environment fingerprint two different ways. NUL separates
97
+ // name from value and entry from entry: it can appear in neither (a POSIX
98
+ // environment string is NUL-terminated), so two distinct environments cannot
99
+ // serialize to the same string.
100
+ const canonical = Object.keys(env)
101
+ .sort()
102
+ .map((key) => `${key}\u0000${env[key]}`)
103
+ .join('\u0000')
104
+
105
+ let hash = 0x811c9dc5
106
+ for (let i = 0; i < canonical.length; i++) {
107
+ hash ^= canonical.charCodeAt(i)
108
+ // The FNV prime, through Math.imul: `hash * 16777619` leaves a double's
109
+ // exact-integer range, which would round and make the digest depend on
110
+ // nothing.
111
+ hash = Math.imul(hash, 0x01000193)
112
+ }
113
+ return (hash >>> 0).toString(16).padStart(8, '0')
114
+ }
@@ -0,0 +1,81 @@
1
+ /**
2
+ * Reading a credential off the wire, once.
3
+ *
4
+ * Three functions, and all three used to exist twice — in `src/http.ts` for the
5
+ * git transport and in `shared/events.ts` for the event socket. They are the
6
+ * same question asked on two transports: a client presents a token, and walgit
7
+ * decides whether it is one of the ones configured. The event stream's answer
8
+ * is deliberately the SAME answer a read gets (an event says a ref moved and
9
+ * what to; that is a strict subset of what a fetch of the repository hands
10
+ * over), so two implementations were never two policies — only two chances to
11
+ * drift.
12
+ *
13
+ * Runtime-neutral, which is what lets both halves import it: `atob` is a
14
+ * standard global in bun and in the Workers runtime alike, and nothing here
15
+ * touches a buffer, a socket or a clock.
16
+ */
17
+
18
+ /**
19
+ * The token a request presents: `Bearer <token>`, or git's
20
+ * `Basic base64(<user>:<token>)`.
21
+ *
22
+ * The user half of Basic is ignored — there is one trust boundary in v0, and a
23
+ * per-user model needs the repo namespace milestone 3 introduces. git sends the
24
+ * credential this way, so accepting it is what makes `git clone https://…`
25
+ * work with a bare token at all.
26
+ */
27
+ export function presentedCredential(header: string): string | null {
28
+ const bearer = /^Bearer (.+)$/i.exec(header)
29
+ if (bearer) return bearer[1]!
30
+ const basic = /^Basic (.+)$/i.exec(header)
31
+ if (basic) {
32
+ // Undecodable base64 is a malformed credential, not a crash: `atob` throws
33
+ // on one, and a header a stranger controls must not be able to do that.
34
+ let decoded: string
35
+ try {
36
+ decoded = atob(basic[1]!)
37
+ } catch {
38
+ return null
39
+ }
40
+ const colon = decoded.indexOf(':')
41
+ return colon === -1 ? decoded : decoded.slice(colon + 1)
42
+ }
43
+ return null
44
+ }
45
+
46
+ /**
47
+ * The credential list.
48
+ *
49
+ * Comma-separated so one deployment can rotate a credential without a window
50
+ * where neither the old nor the new token works. Blank entries are dropped
51
+ * rather than kept as an empty token, which would match an empty credential.
52
+ */
53
+ export function parseTokens(raw: string | undefined): string[] {
54
+ return (raw ?? '')
55
+ .split(',')
56
+ .map((token) => token.trim())
57
+ .filter(Boolean)
58
+ }
59
+
60
+ /** Length-independent comparison, so a wrong token leaks nothing by timing. */
61
+ export function constantTimeEquals(a: string, b: string): boolean {
62
+ let diff = a.length ^ b.length
63
+ for (let i = 0; i < Math.max(a.length, b.length); i++) {
64
+ diff |= (a.charCodeAt(i % a.length || 0) || 0) ^ (b.charCodeAt(i % b.length || 0) || 0)
65
+ }
66
+ return diff === 0
67
+ }
68
+
69
+ /**
70
+ * Does this request carry one of these tokens?
71
+ *
72
+ * The whole check in one place, because the ordering matters and is easy to get
73
+ * subtly wrong: a missing credential is refused before any comparison runs, and
74
+ * every configured token is compared in constant time rather than short-
75
+ * circuiting on the first mismatch.
76
+ */
77
+ export function authorizedBy(authorization: string | null, tokens: readonly string[]): boolean {
78
+ const presented = presentedCredential(authorization ?? '')
79
+ if (!presented) return false
80
+ return tokens.some((token) => constantTimeEquals(token, presented))
81
+ }