@zabaca/zbc 0.25.0 → 0.27.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 +114 -0
  2. package/package.json +1 -1
  3. package/src/commands/init.ts +105 -10
  4. package/src/commands/secret.ts +1 -66
  5. package/src/commands/update.ts +77 -7
  6. package/src/engine/actions.ts +35 -3
  7. package/src/engine/on-demand.ts +9 -1
  8. package/src/engine/secret-outputs.ts +15 -0
  9. package/src/engine/secrets.ts +81 -1
  10. package/src/utils/copy-refresh.ts +124 -19
  11. package/src/utils/detect-mode.ts +1 -1
  12. package/src/utils/host-workspaces.ts +57 -0
  13. package/src/utils/subtree.ts +54 -15
  14. package/src/utils/template-history.ts +66 -0
  15. package/src/utils/vendor-audit.ts +12 -8
  16. package/src/utils/vendor-stamp.ts +10 -0
  17. package/src/utils/vendored-app.ts +3 -0
  18. package/templates/apps/walgit/CONTEXT.md +45 -4
  19. package/templates/apps/walgit/README.md +394 -11
  20. package/templates/apps/walgit/shared/browse.ts +61 -0
  21. package/templates/apps/walgit/shared/capabilities.ts +26 -0
  22. package/templates/apps/walgit/shared/container-env.ts +12 -0
  23. package/templates/apps/walgit/shared/container-lifecycle.ts +1 -1
  24. package/templates/apps/walgit/shared/credentials.ts +4 -0
  25. package/templates/apps/walgit/shared/events.ts +35 -1
  26. package/templates/apps/walgit/shared/instructions.ts +4 -1
  27. package/templates/apps/walgit/shared/landing.ts +2 -1
  28. package/templates/apps/walgit/shared/llms.ts +73 -5
  29. package/templates/apps/walgit/shared/mcp.ts +19 -3
  30. package/templates/apps/walgit/shared/protocol.ts +40 -3
  31. package/templates/apps/walgit/shared/repo-list.ts +46 -6
  32. package/templates/apps/walgit/shared/scoped-token.ts +500 -0
  33. package/templates/apps/walgit/shared/token-revocation.ts +134 -0
  34. package/templates/apps/walgit/shared/wal-index.ts +19 -0
  35. package/templates/apps/walgit/shared/webhook.ts +281 -0
  36. package/templates/apps/walgit/src/admin.ts +510 -0
  37. package/templates/apps/walgit/src/announce-main.ts +17 -9
  38. package/templates/apps/walgit/src/announce.ts +86 -0
  39. package/templates/apps/walgit/src/browse.ts +255 -2
  40. package/templates/apps/walgit/src/cli.ts +140 -0
  41. package/templates/apps/walgit/src/expire.ts +5 -0
  42. package/templates/apps/walgit/src/git.ts +103 -0
  43. package/templates/apps/walgit/src/hook-main.ts +6 -3
  44. package/templates/apps/walgit/src/http.ts +563 -3
  45. package/templates/apps/walgit/src/limits.ts +3 -0
  46. package/templates/apps/walgit/src/merge.ts +525 -0
  47. package/templates/apps/walgit/src/rate-limit.ts +51 -14
  48. package/templates/apps/walgit/src/server.ts +65 -1
  49. package/templates/apps/walgit/worker/events-do.ts +218 -3
  50. package/templates/apps/walgit/worker/index.ts +134 -9
  51. package/templates/apps/walgit/worker/mcp.ts +17 -2
  52. package/templates/history.json +1 -0
  53. package/templates/infra/modules/cloudflare/index.ts +140 -1
  54. package/templates/infra/modules/cloudflare-access/index.ts +176 -65
  55. package/templates/infra/modules/cloudflare-access/registry.json +1 -1
  56. package/templates/infra/modules/cloudflare-api/index.ts +56 -0
  57. package/templates/infra/modules/cloudflare-email/index.ts +44 -17
  58. package/templates/infra/modules/cloudflare-email/registry.json +1 -1
  59. package/templates/infra/modules/cloudflare-stored-token/index.ts +343 -0
  60. package/templates/infra/modules/cloudflare-stored-token/registry.json +12 -0
  61. package/templates/infra/modules/cloudflare-token/index.ts +46 -17
  62. package/templates/infra/modules/cloudflare-token/registry.json +1 -1
  63. package/templates/infra/modules/cloudflare-tunnel/index.ts +63 -8
  64. package/templates/infra/modules/cloudflare-tunnel/registry.json +1 -1
  65. package/templates/infra/modules/d1/index.ts +37 -35
  66. package/templates/infra/modules/d1/registry.json +1 -1
  67. package/templates/infra/modules/docker-compose-stack/index.ts +3 -1
  68. package/templates/infra/modules/queue/index.ts +28 -18
  69. package/templates/infra/modules/queue/registry.json +1 -1
  70. package/templates/infra/modules/r2/index.ts +20 -11
  71. package/templates/infra/modules/r2/registry.json +1 -1
  72. package/templates/infra/src/context.ts +41 -0
  73. package/templates/infra/src/testing.ts +19 -1
  74. package/templates/infra/src/types.ts +23 -0
@@ -151,6 +151,67 @@ export interface BrowseLogAnswer extends BrowseRefsAnswer {
151
151
  next: string | null
152
152
  }
153
153
 
154
+ /**
155
+ * How many files one compare lists, and diffs: 300.
156
+ *
157
+ * GitHub's own figure for a compare, and a bound on work done on the request
158
+ * path in the one container that is also serving pushes. The totals are still
159
+ * counted over EVERY changed file — the per-file summary is one `git diff
160
+ * --numstat` either way — so a reader is told how much was left out, not merely
161
+ * that something was.
162
+ */
163
+ export const COMPARE_MAX_FILES = 300
164
+
165
+ /**
166
+ * How much unified diff one compare carries: 1 MiB.
167
+ *
168
+ * Enforced on git's OUTPUT as it is read (`gitBounded`, `src/git.ts`), so a
169
+ * diff past it is cut off in the subprocess rather than buffered whole and
170
+ * then trimmed. The cut lands on a line boundary. A reader wanting the rest
171
+ * clones the repository, or compares fewer changes.
172
+ */
173
+ export const COMPARE_MAX_DIFF_BYTES = 1024 * 1024
174
+
175
+ /** What one file did between the merge base and the head. */
176
+ export type CompareStatus = 'added' | 'modified' | 'deleted' | 'renamed'
177
+
178
+ /** One changed file, as `git diff --raw --numstat -M` reports it. */
179
+ export interface CompareFile {
180
+ /** The path at the head; for a deletion, the path that was deleted. */
181
+ path: string
182
+ /** For a rename only: the path at the merge base. */
183
+ previousPath?: string
184
+ status: CompareStatus
185
+ /** Lines added. `0` for a binary file, which has no lines to count. */
186
+ additions: number
187
+ /** Lines deleted. `0` for a binary file. */
188
+ deletions: number
189
+ binary: boolean
190
+ }
191
+
192
+ /** A compare, as the Cache answers it — before the Index facts join it. */
193
+ export interface Comparison {
194
+ /** The commit the head is diffed against: `git merge-base base head`. */
195
+ mergeBase: string
196
+ /** The changed files, in git's path order, capped at `COMPARE_MAX_FILES`. */
197
+ files: CompareFile[]
198
+ /** Counted over every changed file, including any `files` leaves out. */
199
+ totals: { files: number; additions: number; deletions: number }
200
+ /** The unified diff of the listed files, cut at `COMPARE_MAX_DIFF_BYTES`. */
201
+ diff: string
202
+ /** A cap was hit: `files` is not every changed file, or `diff` was cut. */
203
+ truncated: boolean
204
+ }
205
+
206
+ /**
207
+ * What `op=compare` answers: the repository, the two refs as resolved, and the
208
+ * comparison of the head against their merge base (three-dot).
209
+ */
210
+ export interface BrowseCompareAnswer extends BrowseRefsAnswer, Comparison {
211
+ base: { ref: string; oid: string }
212
+ head: { ref: string; oid: string }
213
+ }
214
+
154
215
  /**
155
216
  * The README a directory listing holds, by the fixed preference order.
156
217
  *
@@ -60,11 +60,15 @@ type CapabilityVar = Extract<
60
60
  | 'WALGIT_MAX_REPO_BYTES'
61
61
  | 'WALGIT_EVENTS_URL'
62
62
  | 'WALGIT_EVENTS_TOKEN'
63
+ | 'WALGIT_WEBHOOK_URL'
64
+ | 'WALGIT_WEBHOOK_SECRET'
63
65
  | 'WALGIT_PUSH_CERT_SEED'
64
66
  | 'WALGIT_SIGNER_LISTS'
65
67
  | 'WALGIT_PRIVATE_REPOS'
66
68
  | 'WALGIT_PROPOSALS'
69
+ | 'WALGIT_MERGE'
67
70
  | 'WALGIT_WEB'
71
+ | 'WALGIT_TOKEN_PUBLIC_KEYS'
68
72
  | 'WALGIT_RATE_WINDOW_SECONDS'
69
73
  | 'WALGIT_MAX_NEW_REPOS_PER_SOURCE'
70
74
  | 'WALGIT_MAX_PUSHES_PER_SOURCE'
@@ -108,6 +112,12 @@ export type Capabilities = {
108
112
  * since an agent writes the client before finding out.
109
113
  */
110
114
  events: boolean
115
+ /**
116
+ * Every moved ref is also POSTed, signed, to the operator's webhook
117
+ * (shared/webhook.ts). Both halves, read as `webhookConfigFromEnv` reads
118
+ * them. Says only THAT it is on: the URL is the operator's, never published.
119
+ */
120
+ webhook: boolean
111
121
  /**
112
122
  * A signed push is accepted, and who made it is recorded.
113
123
  *
@@ -197,6 +207,19 @@ export type Capabilities = {
197
207
  * operator opts into rather than acquires on upgrade.
198
208
  */
199
209
  web: boolean
210
+ /**
211
+ * Scoped tokens are accepted (`shared/scoped-token.ts`, docs/adr/0021): an
212
+ * issuer holding the private key mints a short-lived credential for one
213
+ * repository, read or write. Off unless `WALGIT_TOKEN_PUBLIC_KEYS` is set.
214
+ */
215
+ scopedTokens: boolean
216
+ /**
217
+ * The host merges on request (`src/merge.ts`, docs/adr/0022): `POST
218
+ * /_walgit/merge` moves a branch by fast-forward or squash, as a
219
+ * compare-and-swap, through the same push path a client's push takes. Off
220
+ * unless `WALGIT_MERGE` is set, and then the route does not exist.
221
+ */
222
+ merge: boolean
200
223
  /** A repository is collected this many hours after its last push. */
201
224
  retentionHours: number | null
202
225
  /**
@@ -300,6 +323,7 @@ export function capabilitiesFrom(
300
323
  // (`src/announce.ts`) makes of the same two variables — the config the push
301
324
  // path announces with and this advertisement cannot be allowed to disagree.
302
325
  events: nonBlank(env.WALGIT_EVENTS_URL) && nonBlank(env.WALGIT_EVENTS_TOKEN),
326
+ webhook: nonBlank(env.WALGIT_WEBHOOK_URL) && nonBlank(env.WALGIT_WEBHOOK_SECRET),
303
327
  signedPushes,
304
328
  namesCanRefuse,
305
329
  namesCanBeClaimed,
@@ -310,6 +334,8 @@ export function capabilitiesFrom(
310
334
  seedValue(env.WALGIT_PRIVATE_REPOS) !== null,
311
335
  proposals: namesCanRefuse && signedPushes && flagEnabled(env.WALGIT_PROPOSALS),
312
336
  web: flagEnabled(env.WALGIT_WEB),
337
+ scopedTokens: seedValue(env.WALGIT_TOKEN_PUBLIC_KEYS) !== null,
338
+ merge: flagEnabled(env.WALGIT_MERGE),
313
339
  retentionHours,
314
340
  claimedRetentionHours:
315
341
  namesCanBeClaimed &&
@@ -71,6 +71,11 @@ export const CONTAINER_ENV = [
71
71
  // stranger fabricating events (shared/events.ts).
72
72
  'WALGIT_EVENTS_URL',
73
73
  'WALGIT_EVENTS_TOKEN',
74
+ // The push webhook's two halves (shared/webhook.ts). Delivered from the same
75
+ // detached announcer as the stream, inside the container, so the container
76
+ // is the side that needs the URL and the signing secret.
77
+ 'WALGIT_WEBHOOK_URL',
78
+ 'WALGIT_WEBHOOK_SECRET',
74
79
  // Signed pushes. The seed is what `git-receive-pack` derives its nonce from,
75
80
  // and receive-pack runs inside the container — so this is the variable that
76
81
  // decides whether the capability is advertised at all (src/push-cert.ts).
@@ -91,6 +96,9 @@ export const CONTAINER_ENV = [
91
96
  // nonce and mints nothing — it only widens what `pre-receive` accepts on a
92
97
  // claimed name, and the hook that widens runs in the container.
93
98
  'WALGIT_PROPOSALS',
99
+ // Host merges (docs/adr/0022). A plain flag: the merge route and the push it
100
+ // makes are both the container's, so it is the container that must know.
101
+ 'WALGIT_MERGE',
94
102
  // The web view (`shared/repo-list.ts`). The only variable on this list that
95
103
  // nothing inside the container reads: the list is answered at the edge, off
96
104
  // the log, precisely so a browse does not wake the container. It is here
@@ -100,6 +108,10 @@ export const CONTAINER_ENV = [
100
108
  // list buys everywhere else: the deploy that first sets it changes the
101
109
  // fingerprint and replaces the running container once.
102
110
  'WALGIT_WEB',
111
+ // Scoped tokens (docs/adr/0021). The edge verifies before it wakes the
112
+ // container, and the container verifies again on what reaches it, so both
113
+ // halves need the public keys — never a private one; walgit holds none.
114
+ 'WALGIT_TOKEN_PUBLIC_KEYS',
103
115
  // Per-source rate limits (src/rate-limit.ts). The verdict is reached in the
104
116
  // container's own HTTP handler — the only place that sees both the source the
105
117
  // edge attributed the request to and the repository it names — so the numbers
@@ -130,7 +130,7 @@ export function inactivityTimeoutMs(sleepAfterMs: number): number {
130
130
  * drops a response without reading or cancelling its body leaves a stream that
131
131
  * may never finish, and one such request would keep the container up forever:
132
132
  * the alarm sees it in flight and re-arms, every time. An hour is far past any
133
- * clone or push this host takes (the push cap is 99 MiB), so a request still
133
+ * clone or push this host takes (the public push cap is 90 MiB), so a request still
134
134
  * counted after it is let go of, and the idle clock starts.
135
135
  */
136
136
  export const INFLIGHT_MAX_MS = 60 * 60 * 1000
@@ -23,6 +23,10 @@
23
23
  * per-user model needs the repo namespace milestone 3 introduces. git sends the
24
24
  * credential this way, so accepting it is what makes `git clone https://…`
25
25
  * work with a bare token at all.
26
+ *
27
+ * A scoped token (docs/adr/0021) is read here too, and nowhere else: what this
28
+ * returns is what `shared/scoped-token.ts` judges, so the admin token and a
29
+ * scoped one cannot arrive by two parsers that disagree about the header.
26
30
  */
27
31
  export function presentedCredential(header: string): string | null {
28
32
  const bearer = /^Bearer (.+)$/i.exec(header)
@@ -216,6 +216,20 @@ export function parseWatch(raw: string): Parsed<WatchEntry[]> {
216
216
  export interface Announcement {
217
217
  events: RefEvent[]
218
218
  readersChanged: string[]
219
+ /**
220
+ * Repositories whose scoped tokens were revoked (docs/adr/0021), with the
221
+ * tokens-valid-since instant now in force. A socket watching on a scoped
222
+ * token for one of them, issued before it, is closed. Sent by the admin
223
+ * revoke rather than a push, with no events; absent reads as empty.
224
+ */
225
+ tokensRevoked: TokensRevoked[]
226
+ }
227
+
228
+ /** One repository's revocation, as the admin revoke announces it. */
229
+ export interface TokensRevoked {
230
+ repo: string
231
+ /** ISO instant: scoped tokens for `repo` issued before it are refused. */
232
+ since: string
219
233
  }
220
234
 
221
235
  /** The announcement the push path publishes, validated at the door. */
@@ -238,6 +252,23 @@ export function parseAnnounce(body: unknown): Parsed<Announcement> {
238
252
  }
239
253
  }
240
254
 
255
+ const revokedRaw = (body as { tokensRevoked?: unknown }).tokensRevoked ?? []
256
+ if (!Array.isArray(revokedRaw)) return { ok: false, error: '"tokensRevoked" is not an array' }
257
+ const tokensRevoked: TokensRevoked[] = []
258
+ for (const item of revokedRaw) {
259
+ const { repo, since } = (item ?? {}) as { repo?: unknown; since?: unknown }
260
+ if (typeof repo !== 'string' || !REPO_ID.test(repo)) {
261
+ return {
262
+ ok: false,
263
+ error: `invalid repository name in "tokensRevoked": ${JSON.stringify(repo ?? null)}`,
264
+ }
265
+ }
266
+ if (typeof since !== 'string' || !Number.isFinite(Date.parse(since))) {
267
+ return { ok: false, error: `invalid "since" in "tokensRevoked" for ${repo}` }
268
+ }
269
+ tokensRevoked.push({ repo, since })
270
+ }
271
+
241
272
  const parsed: RefEvent[] = []
242
273
  for (const item of events) {
243
274
  if (typeof item !== 'object' || item === null)
@@ -286,7 +317,10 @@ export function parseAnnounce(body: unknown): Parsed<Announcement> {
286
317
  ...(Array.isArray(merged) && merged.length > 0 ? { merged: [...(merged as string[])] } : {}),
287
318
  })
288
319
  }
289
- return { ok: true, value: { events: parsed, readersChanged: [...(changed as string[])] } }
320
+ return {
321
+ ok: true,
322
+ value: { events: parsed, readersChanged: [...(changed as string[])], tokensRevoked },
323
+ }
290
324
  }
291
325
 
292
326
  /**
@@ -130,7 +130,10 @@ function facts(caps: Capabilities): string[] {
130
130
  // one and pays for every sentence out of a byte budget — the long form is
131
131
  // `/llms.txt`.
132
132
  if (caps.sourceLimited) {
133
- const per = `per client per ${describeWindow(caps.rateWindowSeconds)}`
133
+ // Per tenant only where a scoped token can name one; elsewhere a client is
134
+ // its address, and the sentence reads exactly as it always has.
135
+ const who = caps.scopedTokens ? 'tenant or client' : 'client'
136
+ const per = `per ${who} per ${describeWindow(caps.rateWindowSeconds)}`
134
137
  const parts: string[] = []
135
138
  if (caps.maxNewReposPerSource !== null) {
136
139
  parts.push(`${caps.maxNewReposPerSource} new repositories`)
@@ -117,7 +117,8 @@ function sourceLimits(caps: Capabilities): string {
117
117
  if (caps.maxPushBytesPerSource !== null) {
118
118
  parts.push(shortBytes(caps.maxPushBytesPerSource))
119
119
  }
120
- return `${parts.join(', ')} per client per ${window}`
120
+ const who = caps.scopedTokens ? 'tenant or client' : 'client'
121
+ return `${parts.join(', ')} per ${who} per ${window}`
121
122
  }
122
123
 
123
124
  /**
@@ -27,9 +27,11 @@ import { MAX_REFS_PER_ENTRY, MAX_WATCH_ENTRIES } from './events'
27
27
  import { describeBytes, describeWindow } from './policy'
28
28
  import { CONTENT_SIGNAL } from './robots'
29
29
  import {
30
+ BROWSE_PATH,
30
31
  CHALLENGE_PATH,
31
32
  EVENTS_PATH,
32
33
  MCP_PATH,
34
+ MERGE_PATH,
33
35
  PROVENANCE_PATH,
34
36
  READ_CHALLENGE_NAMESPACE,
35
37
  REPOS_PATH,
@@ -89,6 +91,13 @@ export function renderLlms(
89
91
  '/my-thing.git`.',
90
92
  )
91
93
  }
94
+ if (caps.scopedTokens) {
95
+ // Stated only where the keys are configured (docs/adr/0021): a deployment
96
+ // that cannot verify one must not tell an agent a scoped token works.
97
+ limits.push(
98
+ "- **A scoped token opens one repository.** If you were handed one (a JWT, `eyJ…`), send it exactly where a credential goes — the Basic-auth password or `Authorization: Bearer` — and it reads (`mode: read`) or reads and pushes (`mode: write`, which may also create the repository on first push) the one name it was minted for, until it expires. Every other repository refuses it with 403 and the repository list shows only that one name; an expired or unverifiable token is 401, and so is one issued before its repository's tokens were revoked — ask the issuer for a new one. It does not open a Private repository. For the anonymous view of anything else, send no credential at all.",
99
+ )
100
+ }
92
101
  limits.push(
93
102
  '- **A repository is created by its first push.** Names are one segment and first-come. Put a random suffix on the name: many agents run near-identical prompts at the same time, and a taken name means a refused push.',
94
103
  )
@@ -132,19 +141,27 @@ export function renderLlms(
132
141
  // only where it is enforced, like every bullet above.
133
142
  if (caps.sourceLimited) {
134
143
  const window = describeWindow(caps.rateWindowSeconds)
144
+ // Who "per" means. Only a deployment that verifies scoped tokens can tell
145
+ // tenants apart, so only there is the tenant named.
146
+ const who = caps.scopedTokens ? 'tenant or client' : 'client'
135
147
  if (caps.maxNewReposPerSource !== null) {
136
148
  limits.push(
137
- `- **You may create ${caps.maxNewReposPerSource} new repositories per client per ${window}.** Pushing to a name you already created does not count against it.`,
149
+ `- **You may create ${caps.maxNewReposPerSource} new repositories per ${who} per ${window}.** Pushing to a name you already created does not count against it.`,
138
150
  )
139
151
  }
140
152
  if (caps.maxPushesPerSource !== null) {
141
153
  limits.push(
142
- `- **You may make ${caps.maxPushesPerSource} pushes per client per ${window}.** Commit locally and push once rather than pushing every commit.`,
154
+ `- **You may make ${caps.maxPushesPerSource} pushes per ${who} per ${window}.** Commit locally and push once rather than pushing every commit.`,
143
155
  )
144
156
  }
145
157
  if (caps.maxPushBytesPerSource !== null) {
146
158
  limits.push(
147
- `- **You may push ${describeBytes(caps.maxPushBytesPerSource)} per client per ${window}.**`,
159
+ `- **You may push ${describeBytes(caps.maxPushBytesPerSource)} per ${who} per ${window}.**`,
160
+ )
161
+ }
162
+ if (caps.scopedTokens) {
163
+ limits.push(
164
+ "- **A tenant is your scoped token's `sub` claim**, counted across every repository and address it pushes from. A token with no `sub`, or no scoped token at all, is counted per client address.",
148
165
  )
149
166
  }
150
167
  limits.push(
@@ -678,6 +695,36 @@ ${[
678
695
  .join('\n')}
679
696
  `
680
697
 
698
+ /**
699
+ * The push webhook (shared/webhook.ts). Stated because a pusher should know
700
+ * its push is reported beyond this host, and because the receiver's author
701
+ * reads this document too — so it carries the check. Never the URL: that is
702
+ * the operator's, and this document is public.
703
+ */
704
+ const webhook = caps.webhook
705
+ ? `
706
+ ## Every push is also POSTed to the operator
707
+
708
+ This host sends every ref that moves to one URL its operator configured, as a signed HTTP POST — one per ref, after the push is durable, never for a push that was refused. The body uses the event stream's names:
709
+
710
+ \`\`\`json
711
+ {"id":"01JD3Q8X6M2P4R7T9V0WXYZABC","repo":"my-thing","ref":"refs/heads/main","oldSha":"9f2c…","sha":"0ab7…","timestamp":"2026-11-11T12:00:00.000Z"}
712
+ \`\`\`
713
+
714
+ \`oldSha\` is \`null\` for a new ref and \`sha\` is \`null\` for a deleted one; \`merged\` appears when it does on the event stream. Delivery is at least once, retried with backoff on a network failure, a 5xx, a 408 or a 429, so de-duplicate on \`id\` (also sent as \`X-Walgit-Event\`).
715
+
716
+ To verify one, take \`X-Walgit-Timestamp\` (Unix seconds) and the **raw** body, and compare \`X-Walgit-Signature\` with \`sha256=\` plus the hex HMAC-SHA256 of \`<timestamp>.<body>\`, keyed by the shared secret. Refuse a timestamp more than five minutes old — each retry is re-stamped.
717
+
718
+ \`\`\`ts
719
+ import { createHmac, timingSafeEqual } from 'node:crypto'
720
+ const fresh = /^\\d+$/.test(timestamp) && Math.abs(Date.now() / 1000 - Number(timestamp)) <= 300
721
+ const got = Buffer.from(signature)
722
+ const expected = Buffer.from('sha256=' + createHmac('sha256', secret).update(timestamp + '.' + rawBody).digest('hex'))
723
+ const ok = fresh && got.length === expected.length && timingSafeEqual(got, expected)
724
+ \`\`\`
725
+ `
726
+ : ''
727
+
681
728
  const events = caps.events
682
729
  ? `
683
730
  ## Know when a ref moves, without asking
@@ -843,9 +890,30 @@ curl -H 'accept: application/json' https://${host}/$NAME${caps.publicAccess ? ''
843
890
  One repository: its refs, its default branch and one level of the default branch's tree. \`/$NAME/tree/<ref>/<path>\` is any directory at any ref — a branch name containing slashes resolves, because the host splits the ref from the path against its own Index. Same gate as a clone${caps.namesCanBePrivate ? ', so a Private name is refused here exactly as `info/refs` is' : ''}.
844
891
 
845
892
  Three more reads on the same split: \`/$NAME/blob/<ref>/<path>\` is one file (up to 1 MiB, otherwise its size alone), \`/$NAME/raw/<ref>/<path>\` is its bytes — always \`text/plain\` or an \`application/octet-stream\` attachment, chosen by content and never by extension — and \`/$NAME/commits/<ref>\` is fifty commits per page with \`?before=<full oid>\` as the cursor.
893
+
894
+ \`\`\`sh
895
+ curl 'https://${host}${BROWSE_PATH}?repo=$NAME&op=compare&base=main&head=feature/x'${caps.publicAccess ? '' : ' -u walgit:$TOKEN'}
896
+ \`\`\`
897
+
898
+ A review without a checkout: \`head\` against its merge base with \`base\` (three-dot), as JSON — \`mergeBase\`, \`files\` (\`path\`, \`previousPath\` for a rename, \`status\` added/modified/deleted/renamed, \`additions\`, \`deletions\`, \`binary\`), \`totals\` and the unified \`diff\`. Add \`&format=diff\` for the diff alone as text. At most 300 files and 1 MiB of diff; past either, \`truncated\` is true and \`totals\` still counts everything. An unknown ref is 404; two refs with no history in common are 400; a comparison too large to compute in ten seconds is 503 — compare it in a clone.
846
899
  `
847
900
  : ''
848
- }
901
+ }${
902
+ // Host merges (docs/adr/0022), named only where the route exists. A sentence
903
+ // about an endpoint that 404s is an agent sent after nothing.
904
+ caps.merge
905
+ ? `
906
+ ## Merge without a checkout
907
+
908
+ \`\`\`sh
909
+ curl -X POST 'https://${host}${MERGE_PATH}?repo=$NAME'${caps.publicAccess ? '' : ' -u walgit:$TOKEN'} -H 'content-type: application/json' \\
910
+ -d '{"source":"feature/x","target":"main","method":"squash","expected":"<full oid main is at>","message":"Land feature/x","author":{"name":"…","email":"…"}}'
911
+ \`\`\`
912
+
913
+ The host merges \`source\` into the branch \`target\` and answers the new commit with the files it changed. \`method\` is \`fast-forward\` (refused 409 when it is not one) or \`squash\` (one commit on top of \`target\`, the three-way merge of both; \`message\` and \`author\` required). \`expected\` is required: the commit \`target\` stood at when you reviewed it. If it has moved since, the answer is 409 \`stale\` with the \`actual\` commit and nothing changes — read the target again, then decide. A squash that conflicts is 409 \`conflict\` with the paths; resolve those in a clone. It is a push the host makes, so the same size caps and rules apply, and Watchers see the move${caps.sourceLimited ? '; it also counts as one push against your per-source limit (429 once spent)' : ''}. A merge too large to build in twenty seconds is 503 — merge it in a clone.${caps.namesCanRefuse ? ' A name holding a Signer List refuses it (403 `signed`): the host cannot sign, so merge in a clone and push signed.' : ''}${caps.proposals ? ' A squash-merged Proposal does not read as merged — fast-forward it if it should.' : ''}
914
+ `
915
+ : ''
916
+ }
849
917
  ## Ask this host directly
850
918
 
851
919
  This host speaks the Model Context Protocol at \`https://${host}${MCP_PATH}\` (Streamable HTTP). There is nothing to install and nothing to spawn — point a client at the URL:
@@ -860,7 +928,7 @@ It carries what this host can answer without your disk: \`agentgit_status\` (doe
860
928
  // answer and a useless one to send an agent after.
861
929
  caps.signedPushes ? ', `agentgit_provenance` (which key signed the push that moved a ref)' : ''
862
930
  }, and this document as the resource \`agentgit://manual\`. Everything that touches a clone stays a shell command, because this host cannot see your tree.
863
- ${signing}${ownership}${privacy}${proposing}${events}
931
+ ${signing}${ownership}${privacy}${proposing}${events}${webhook}
864
932
  ## If a push is refused
865
933
 
866
934
  Read the message. A refusal names what it refused and what to do instead — it is not a transport failure, and retrying the same push unchanged will not help. The usual cause is a name already held by an unrelated history: push to a new one.
@@ -47,6 +47,7 @@ import type { Capabilities } from './capabilities'
47
47
  import { renderLlms } from './llms'
48
48
  import type { Operator } from './operator'
49
49
  import { REF_NAME, REPO_ID } from './protocol'
50
+ import { nameInScope } from './scoped-token'
50
51
 
51
52
  /** The manual, as a resource a client can read without calling a tool. */
52
53
  export const MANUAL_URI = 'agentgit://manual'
@@ -104,6 +105,12 @@ export interface McpDeps {
104
105
  status(name: string): Promise<Read<StatusFacts>>
105
106
  provenance(name: string): Promise<Read<{ repo: string; provenance: ProvenanceFacts }>>
106
107
  watch(name: string, ref: string | null, timeoutMs: number): Promise<WatchOutcome>
108
+ /**
109
+ * The one repository a verified scoped token names (docs/adr/0021), when the
110
+ * caller presented one. Every tool refuses any other name before `deps` is
111
+ * asked anything, so a name outside the claim never reaches the host.
112
+ */
113
+ scopedTo?: string | null
107
114
  }
108
115
 
109
116
  interface ToolResult {
@@ -129,6 +136,15 @@ const refuse = (message: string): ToolResult => ({
129
136
  * repository half the service can see. Refused here rather than forwarded so a
130
137
  * path-shaped name never becomes a request at all.
131
138
  */
139
+ function outOfScope(deps: McpDeps, name: string): string | null {
140
+ const scope = deps.scopedTo
141
+ if (scope === undefined || scope === null) return null
142
+ // The same comparison the HTTP surfaces make: exact, by the canonical id.
143
+ return nameInScope(scope, name)
144
+ ? null
145
+ : `walgit: this token is scoped to the repository "${scope}", not "${name}"`
146
+ }
147
+
132
148
  function badName(name: string): string | null {
133
149
  return REPO_ID.test(name)
134
150
  ? null
@@ -159,7 +175,7 @@ export function createAgentgitMcp(deps: McpDeps): McpServer {
159
175
  inputSchema: { name },
160
176
  },
161
177
  async (input): Promise<ToolResult> => {
162
- const bad = badName(input.name)
178
+ const bad = badName(input.name) ?? outOfScope(deps, input.name)
163
179
  if (bad) return refuse(bad)
164
180
  const read = await deps.status(input.name)
165
181
  if (!read.ok) return refuse(read.message)
@@ -201,7 +217,7 @@ export function createAgentgitMcp(deps: McpDeps): McpServer {
201
217
  },
202
218
  },
203
219
  async (input): Promise<ToolResult> => {
204
- const bad = badName(input.name)
220
+ const bad = badName(input.name) ?? outOfScope(deps, input.name)
205
221
  if (bad) return refuse(bad)
206
222
  const ref = input.ref ?? null
207
223
  if (ref !== null && !REF_NAME.test(ref)) {
@@ -245,7 +261,7 @@ export function createAgentgitMcp(deps: McpDeps): McpServer {
245
261
  },
246
262
  },
247
263
  async (input): Promise<ToolResult> => {
248
- const bad = badName(input.name)
264
+ const bad = badName(input.name) ?? outOfScope(deps, input.name)
249
265
  if (bad) return refuse(bad)
250
266
  const read = await deps.provenance(input.name)
251
267
  if (!read.ok) return refuse(read.message)
@@ -190,6 +190,27 @@ export const MCP_PATH = '/_walgit/mcp'
190
190
  */
191
191
  export const ANNOUNCE_PATH = '/_walgit/announce'
192
192
 
193
+ /**
194
+ * The admin routes: one repository created (optionally seeded), deleted, or
195
+ * measured, by a server holding the admin credential and no store credentials
196
+ * (`src/admin.ts`).
197
+ *
198
+ * POST /_walgit/admin/repos/<name> create; an optional JSON seed
199
+ * DELETE /_walgit/admin/repos/<name> delete, with the delete grace
200
+ * GET /_walgit/admin/repos/<name>/usage what the log holds for it
201
+ * POST /_walgit/admin/repos/<name>/revoke-tokens
202
+ * revoke its scoped tokens issued
203
+ * before now (or a given time)
204
+ *
205
+ * Group 1 is the repository, group 2 is `/usage`, `/revoke-tokens` or absent. Under the reserved
206
+ * prefix, so no repository name can reach it: a repository id begins with a
207
+ * letter or a digit (`REPO_ID`), never `_`, and a repository is cloned at
208
+ * `/<name>.git/…` anyway. A scoped token is never accepted here — the path is
209
+ * none of the repository surfaces `scopeTargetOf` names, so it is judged
210
+ * `elsewhere` and refused 403 at the edge and again in the container.
211
+ */
212
+ export const ADMIN_REPOS_HTTP = /^\/_walgit\/admin\/repos\/([^/]+)(\/usage|\/revoke-tokens)?$/
213
+
193
214
  /**
194
215
  * The repository list — the web view's one page that is about the deployment
195
216
  * rather than about a name (`shared/repo-list.ts`).
@@ -209,11 +230,13 @@ export const REPOS_PATH = '/repos'
209
230
  /**
210
231
  * One repository's refs and one level of its tree, read on the Cache.
211
232
  *
212
- * `?repo=&op=refs|tree&ref=&path=`, and under `/_walgit/` for the reason every
213
- * endpoint above is: the prefix is reserved and a repository is reached at
233
+ * `?repo=&op=refs|tree|blob|raw|log&ref=&path=`, and `?repo=&op=compare&base=&head=`
234
+ * — the one op a client calls directly rather than through a page, a review of
235
+ * a branch with no checkout (README, *Comparing two refs*). Under `/_walgit/`
236
+ * for the reason every endpoint above is: the prefix is reserved and a repository is reached at
214
237
  * `/<name>.git/…`, so it cannot shadow one.
215
238
  *
216
- * It is for the EDGE rather than for a client — the two browse pages are
239
+ * Every other op is for the EDGE rather than for a client — the browse pages are
217
240
  * rendered from its answer (`shared/browse.ts`) — but it is gated as the
218
241
  * Provenance Read beside it is, by the deployment credential and then the Read
219
242
  * Challenge, rather than by `INTERNAL_HEADER`: it answers a question about one
@@ -226,6 +249,20 @@ export const REPOS_PATH = '/repos'
226
249
  */
227
250
  export const BROWSE_PATH = '/_walgit/browse'
228
251
 
252
+ /**
253
+ * A merge the host performs (docs/adr/0022): `POST ?repo=<name>` with a JSON
254
+ * body naming the source, the target, the method and the commit the target is
255
+ * expected to be at (`src/merge.ts`).
256
+ *
257
+ * Its own path rather than an op of `BROWSE_PATH`, because it is a WRITE: a
258
+ * browse is a read a `read` token may make and the web view's flag governs,
259
+ * and a merge is neither. The name rides the query string as the compare's
260
+ * does, so the scope check reads it the same way. It exists only where the
261
+ * deployment sets `WALGIT_MERGE`; everywhere else it is the 404 any path walgit
262
+ * does not serve is.
263
+ */
264
+ export const MERGE_PATH = '/_walgit/merge'
265
+
229
266
  /**
230
267
  * The browse URLs a person types: `/<name>`, and `/<name>/<kind>/<rest>` for
231
268
  * each of the four GitHub-shaped reads.
@@ -88,6 +88,13 @@ export interface RepoListDeps {
88
88
  caps: Capabilities
89
89
  /** The configured credentials (`parseTokens`). */
90
90
  tokens: readonly string[]
91
+ /**
92
+ * The one repository a verified scoped token names (docs/adr/0021), when the
93
+ * request presented one. The edge has already verified it; here it stands in
94
+ * for the deployment credential and narrows the list to that name, so a
95
+ * scoped token never learns another repository exists.
96
+ */
97
+ scopedTo?: string
91
98
  }
92
99
 
93
100
  /** A response as a value: the Worker turns this into a `Response`. */
@@ -131,11 +138,15 @@ export async function repoListResponse(
131
138
  request: RepoListRequest,
132
139
  deps: RepoListDeps,
133
140
  ): Promise<EdgeResponse> {
134
- const { caps, store, tokens } = deps
141
+ const { caps, store, tokens, scopedTo } = deps
135
142
 
136
143
  // Before the store is touched. A refusal must not be the reason a bucket is
137
144
  // read, and must never be cached: the next request carries a credential.
138
- if (!caps.publicAccess && !authorizedBy(request.authorization, tokens)) {
145
+ if (
146
+ scopedTo === undefined &&
147
+ !caps.publicAccess &&
148
+ !authorizedBy(request.authorization, tokens)
149
+ ) {
139
150
  return {
140
151
  status: 401,
141
152
  headers: {
@@ -150,13 +161,18 @@ export async function repoListResponse(
150
161
  }
151
162
 
152
163
  const page = requestedPage(request.search)
153
- const listing = await collectRepoList(store, page)
164
+ const listing =
165
+ scopedTo === undefined
166
+ ? await collectRepoList(store, page)
167
+ : await collectOneRepo(store, scopedTo)
154
168
 
155
169
  // A minute, and only where a read takes no credential — the same reasoning
156
170
  // the landing page's header carries, plus the one this page adds: a shared
157
171
  // cache must not hold a document that exists because THIS request presented
158
- // a token. One function for both web-view pages (`shared/web.ts`).
159
- const cacheControl = webCacheControl(caps)
172
+ // a token. One function for both web-view pages (`shared/web.ts`). Never
173
+ // shared-cached when it was narrowed for a scoped token: the same URL lists
174
+ // every name to the next, anonymous, request.
175
+ const cacheControl = scopedTo === undefined ? webCacheControl(caps) : 'private, no-store'
160
176
 
161
177
  const wantsHtml = request.accept.toLowerCase().includes('text/html')
162
178
  if (!wantsHtml) {
@@ -263,6 +279,21 @@ export async function collectRepoList(store: ObjectStore, page: number): Promise
263
279
  }
264
280
  }
265
281
 
282
+ /**
283
+ * The list as a scoped token sees it: its own repository, when the log holds
284
+ * one by that name, and nothing else — not even the count of the others.
285
+ */
286
+ export async function collectOneRepo(store: ObjectStore, name: string): Promise<RepoListing> {
287
+ const found = await store.get(indexKey(name)).catch(() => null)
288
+ return {
289
+ repos: found ? [rowFromBytes(name, found.body)] : [],
290
+ page: 1,
291
+ pages: 1,
292
+ total: found ? 1 : 0,
293
+ sortedBy: 'name',
294
+ }
295
+ }
296
+
266
297
  /**
267
298
  * One row, or the bare name.
268
299
  *
@@ -275,7 +306,16 @@ async function rowFor(store: ObjectStore, name: string): Promise<RepoRow> {
275
306
  try {
276
307
  const found = await store.get(indexKey(name))
277
308
  if (!found) return bare(name)
278
- const index = JSON.parse(new TextDecoder().decode(found.body)) as WalIndex
309
+ return rowFromBytes(name, found.body)
310
+ } catch {
311
+ return bare(name)
312
+ }
313
+ }
314
+
315
+ /** One row from an Index's bytes, already read. Never throws. */
316
+ function rowFromBytes(name: string, body: Uint8Array): RepoRow {
317
+ try {
318
+ const index = JSON.parse(new TextDecoder().decode(body)) as WalIndex
279
319
  if (index.version !== 1 || index.repo_id !== name) return bare(name)
280
320
  return foldIndex(name, index)
281
321
  } catch {