@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
@@ -16,9 +16,16 @@ import * as fs from 'node:fs'
16
16
  import { capabilitiesFrom } from '../shared/capabilities'
17
17
  import { BOOT_MARKER } from '../shared/container-snapshot'
18
18
  import { parseTokens } from '../shared/credentials'
19
- import { listCommits, listTree, readBlob, statBlob } from './browse'
19
+ import { tokenPublicKeysConfigError } from '../shared/scoped-token'
20
+ import { createAdminOps } from './admin'
21
+ import { createMergeOps } from './merge'
22
+ import { signerListsEnabled } from './signers'
23
+ import { announceConfigFromEnv, announceTokensRevoked } from './announce'
24
+ import { TokenRevocationReader } from '../shared/token-revocation'
25
+ import { compareRevs, listCommits, listTree, readBlob, statBlob } from './browse'
20
26
  import { clearBootResidue } from './boot-residue'
21
27
  import { ensureBareRepo } from './cache'
28
+ import { configuredDeleteGraceMs } from './delete-repo'
22
29
  import { publishUploadPackAtBoot } from './edge-refs'
23
30
  import { configuredClaimedExpiryMs, configuredExpiryMs, expireRepos } from './expire'
24
31
  import { createHttpHandler, type SweepOptions } from './http'
@@ -97,6 +104,16 @@ if (privateConfigError) {
97
104
  */
98
105
  const privateSeed = privateReposEnabled(process.env) ? privateReposSeed(process.env) : null
99
106
 
107
+ /**
108
+ * A malformed scoped-token key list (docs/adr/0021) is reported at boot and NOT
109
+ * fatal: what it breaks is scoped tokens, which are then refused with a 503
110
+ * naming the entry, while the admin credential keeps working. Taking every
111
+ * clone down for a typo in a key the operator is only adding would be the
112
+ * wrong blast radius.
113
+ */
114
+ const tokenKeysError = tokenPublicKeysConfigError(process.env.WALGIT_TOKEN_PUBLIC_KEYS)
115
+ if (tokenKeysError) console.error(tokenKeysError)
116
+
100
117
  const store = storeFromEnv()
101
118
  if (!store) {
102
119
  // Warned, not fatal: reads still work off the local cache, and a push is
@@ -166,6 +183,12 @@ console.log(
166
183
  `store=${store ? 'configured' : 'MISSING'}`,
167
184
  )
168
185
 
186
+ /** One reader for the process's life, so an unchanged Index costs a 304. */
187
+ function revocationLookup(logStore: ObjectStore): (repoId: string) => Promise<string | null> {
188
+ const reader = new TokenRevocationReader()
189
+ return (repoId) => reader.validSince(logStore, repoId)
190
+ }
191
+
169
192
  /**
170
193
  * One sweep, for real. `--yes` is the CLI's opt-in because a human at a
171
194
  * terminal should have to ask; a scheduled sweep IS the asking, and a dry run
@@ -196,16 +219,56 @@ async function runSweep(logStore: ObjectStore, windowMs: number, opts: SweepOpti
196
219
  }
197
220
  }
198
221
 
222
+ // The ref-event stream, when configured: a token revocation is announced to
223
+ // it so held sockets close (`src/admin.ts`). Pushes announce from the hooks.
224
+ const announceTo = announceConfigFromEnv()
225
+
199
226
  let handler
200
227
  try {
201
228
  handler = createHttpHandler({
202
229
  reposDir,
203
230
  tokens,
204
231
  public: isPublic,
232
+ scopedTokenKeys: process.env.WALGIT_TOKEN_PUBLIC_KEYS,
233
+ // A scoped token is refused once its repository's tokens are revoked
234
+ // (`shared/token-revocation.ts`), read from the Index on every request.
235
+ ...(store ? { tokensValidSince: revocationLookup(store) } : {}),
205
236
  ensureRepo: ensureBareRepo,
206
237
  syncRepo: (repo) => syncRepo(store, repo),
207
238
  runBackend: runGitHttpBackend,
208
239
  capabilities: caps,
240
+ // Create, delete and measure one repository for a server holding the admin
241
+ // credential (`src/admin.ts`). Absent without a store, where there is no
242
+ // Index to claim a name in; the handler also withholds the routes from a
243
+ // deployment with no admin credential configured.
244
+ admin: store
245
+ ? createAdminOps({
246
+ store,
247
+ ensureRepo: ensureBareRepo,
248
+ syncRepo: (repo) => syncRepo(store, repo),
249
+ graceMs: configuredDeleteGraceMs(),
250
+ ...(announceTo
251
+ ? {
252
+ announceRevoked: (repoId: string, since: string) =>
253
+ announceTokensRevoked(announceTo, repoId, since),
254
+ }
255
+ : {}),
256
+ })
257
+ : undefined,
258
+ // Merge one branch into another on request (`src/merge.ts`,
259
+ // docs/adr/0022). Only where the deployment opted in AND there is a store:
260
+ // the merge is a compare-and-swap on the Index, and the push it makes is
261
+ // published there. The handler checks the same capability again, so the
262
+ // route and the documents cannot disagree about whether it exists.
263
+ merge:
264
+ store && caps.merge
265
+ ? createMergeOps({
266
+ store,
267
+ ensureRepo: ensureBareRepo,
268
+ syncRepo: (repo) => syncRepo(store, repo),
269
+ signerLists: signerListsEnabled(),
270
+ })
271
+ : undefined,
209
272
  // Only when there is both a log to sweep and a window to sweep by. An
210
273
  // instance with no retention configured has expiry off entirely, and the
211
274
  // endpoint should not exist for it — `expireRepos` would return an empty
@@ -288,6 +351,7 @@ try {
288
351
  statBlob: (repo, rev, path) => statBlob(repo.dir, rev, path),
289
352
  readBlob: (repo, rev, path) => readBlob(repo.dir, rev, path),
290
353
  listCommits: (repo, rev, before, limit) => listCommits(repo.dir, rev, before, limit),
354
+ compare: (repo, base, head, limits) => compareRevs(repo.dir, base, head, limits),
291
355
  }
292
356
  : undefined,
293
357
  // Read gating, and only where all three halves exist (docs/adr/0013): the
@@ -25,6 +25,7 @@ import { DurableObject } from 'cloudflare:workers'
25
25
  import { capabilitiesFrom } from '../shared/capabilities'
26
26
  import {
27
27
  type RefEvent,
28
+ type TokensRevoked,
28
29
  type WatchEntry,
29
30
  authorizeSubscribe,
30
31
  encode,
@@ -35,8 +36,13 @@ import {
35
36
  watchedRepos,
36
37
  } from '../shared/events'
37
38
  import { Outbox } from '../shared/outbox'
39
+ import { parseTokens } from '../shared/credentials'
40
+ import { scopedAccessOf, scopedTokenExpired, scopedWatchRefusal } from '../shared/scoped-token'
38
41
  import { INTERNAL_HEADER, READ_VERDICT_PATH, REFS_PATH } from '../shared/protocol'
39
42
  import { RefCache } from '../shared/ref-cache'
43
+ import { s3StoreFrom } from '../shared/store'
44
+ import { revocationOf, TokenRevocationReader, tokenRevoked } from '../shared/token-revocation'
45
+ import { AwsClient } from 'aws4fetch'
40
46
  import { type ContainerBindings, containerFor } from './container-binding'
41
47
 
42
48
  /** Only the bindings this object touches — the Worker's Env is a superset. */
@@ -55,6 +61,22 @@ export interface EventsEnv extends ContainerBindings {
55
61
  WALGIT_PRIVATE_REPOS?: string
56
62
  WALGIT_SIGNER_LISTS?: string
57
63
  WALGIT_PUSH_CERT_SEED?: string
64
+ /**
65
+ * Scoped tokens (docs/adr/0021): the keys a watch's credential is verified
66
+ * against, and the deployment's own secrets, which are never judged as one.
67
+ */
68
+ WALGIT_TOKEN_PUBLIC_KEYS?: string
69
+ WALGIT_HTTP_TOKENS?: string
70
+ /**
71
+ * The object store, read for one thing only: whether a scoped token's
72
+ * repository has revoked its tokens since it was issued
73
+ * (`shared/token-revocation.ts`). The same variables the Worker reads it by.
74
+ */
75
+ WALGIT_S3_ENDPOINT?: string
76
+ WALGIT_S3_BUCKET?: string
77
+ WALGIT_S3_ACCESS_KEY_ID?: string
78
+ WALGIT_S3_SECRET_ACCESS_KEY?: string
79
+ WALGIT_S3_REGION?: string
58
80
  }
59
81
 
60
82
  /** The Worker's internal call to fan an announcement out. Never client-reachable. */
@@ -92,6 +114,18 @@ export class WalgitEvents extends DurableObject<EventsEnv> {
92
114
  */
93
115
  private readonly outboxes = new WeakMap<WebSocket, Outbox>()
94
116
 
117
+ /** Revocation reads for watches on scoped tokens (`shared/token-revocation.ts`). */
118
+ private readonly revocations = new TokenRevocationReader()
119
+
120
+ /**
121
+ * The newest revocation announced per repository, in memory. A watch judged
122
+ * against the Index in flight while a revoke was announced read the old
123
+ * Index and was skipped by `revokeTokens` (it had no watch yet); this is
124
+ * checked, with no await between it and the attachment, to close that gap.
125
+ * Losing it on hibernation is harmless: no watch is in flight then.
126
+ */
127
+ private readonly announcedRevocations = new Map<string, string>()
128
+
95
129
  async fetch(request: Request): Promise<Response> {
96
130
  const url = new URL(request.url)
97
131
 
@@ -102,6 +136,11 @@ export class WalgitEvents extends DurableObject<EventsEnv> {
102
136
  // a ref that has already been made durable, which is exactly what a later
103
137
  // handshake would go and read.
104
138
  this.refs.apply(parsed.value.events)
139
+ // A scoped socket is re-judged against its repository's Index before it
140
+ // is sent anything (docs/adr/0021), so a revocation whose announcement
141
+ // was lost still stops delivery: a socket is never served an event after
142
+ // its token was revoked, whichever way the news arrived.
143
+ await this.closeRevokedWatching(parsed.value.events)
105
144
  const delivered = this.broadcast(parsed.value.events)
106
145
  // A socket that outlives a revocation is a leak (docs/adr/0013), so the
107
146
  // sockets reading on the strength of the Reader List this push replaced
@@ -109,6 +148,16 @@ export class WalgitEvents extends DurableObject<EventsEnv> {
109
148
  // bounds its own wait, and a revocation deferred to a timer is one that
110
149
  // may never run on an object about to hibernate.
111
150
  await this.revoke(parsed.value.readersChanged)
151
+ // The same, for a repository whose scoped tokens an admin just revoked
152
+ // (docs/adr/0021): the sockets watching on one issued before it close
153
+ // now, rather than at the token's `exp`.
154
+ for (const { repo, since } of parsed.value.tokensRevoked) {
155
+ const known = this.announcedRevocations.get(repo)
156
+ if (known === undefined || Date.parse(since) > Date.parse(known)) {
157
+ this.announcedRevocations.set(repo, since)
158
+ }
159
+ }
160
+ this.revokeTokens(parsed.value.tokensRevoked)
112
161
  return Response.json({ ok: true, delivered })
113
162
  }
114
163
 
@@ -168,6 +217,53 @@ export class WalgitEvents extends DurableObject<EventsEnv> {
168
217
 
169
218
  const credential = readSubscription(ws).credential
170
219
 
220
+ // A scoped token (docs/adr/0021) may watch its own repository and nothing
221
+ // else. Judged here, on the message that names the repositories, with the
222
+ // same verifier the edge ran at the upgrade — and refused whole, like the
223
+ // Private gate below, because a subscriber silently narrowed waits forever.
224
+ const scoped = await scopedAccessOf(credential, {
225
+ keys: this.env.WALGIT_TOKEN_PUBLIC_KEYS,
226
+ known: [
227
+ ...parseTokens(this.env.WALGIT_HTTP_TOKENS),
228
+ ...(this.env.WALGIT_EVENTS_TOKEN ? [this.env.WALGIT_EVENTS_TOKEN] : []),
229
+ ],
230
+ })
231
+ let scopeRefused = scopedWatchRefusal(scoped, watchedRepos(parsed.value))
232
+ // Revoked since it was issued (`shared/token-revocation.ts`): read from
233
+ // the Index here too, because the watch can arrive long after the upgrade
234
+ // the Worker judged. Unreadable is refused, never read as valid.
235
+ if (!scopeRefused && scoped.kind === 'scoped') {
236
+ const verdict = await revocationOf(
237
+ scoped.claims,
238
+ s3StoreFrom(this.env, (credentials) => new AwsClient(credentials)),
239
+ this.revocations,
240
+ )
241
+ if (verdict.kind === 'unknown') {
242
+ // Not a verdict on the token: the client may retry, so the socket
243
+ // stays open, and nothing is attached or served.
244
+ ws.send(encode({ error: verdict.reason.replace(/^walgit: /, '') }))
245
+ return
246
+ }
247
+ if (verdict.kind === 'revoked') {
248
+ ws.send(encode({ error: 'unauthorized' }))
249
+ try {
250
+ ws.close(1008, 'walgit: token revoked')
251
+ } catch {
252
+ // Already gone.
253
+ }
254
+ return
255
+ }
256
+ }
257
+ if (scopeRefused) {
258
+ ws.send(encode({ error: scopeRefused }))
259
+ try {
260
+ ws.close(1008, "walgit: outside this token's scope")
261
+ } catch {
262
+ // Already gone.
263
+ }
264
+ return
265
+ }
266
+
171
267
  // The Private gate, on the only transport that can ask it here: the
172
268
  // container verifies the signature and answers per repository, and
173
269
  // `authorizeSubscribe` turns that into one verdict for the whole watch.
@@ -207,7 +303,31 @@ export class WalgitEvents extends DurableObject<EventsEnv> {
207
303
  }
208
304
  }
209
305
 
210
- ws.serializeAttachment({ credential, watch: parsed.value } satisfies Subscription)
306
+ // A revoke announced while this watch was being judged: the Index read
307
+ // above may predate it, and `revokeTokens` skipped this socket because it
308
+ // had no watch yet. Checked with no await before the attachment below.
309
+ if (scoped.kind === 'scoped') {
310
+ const announced = this.announcedRevocations.get(scoped.claims.repo)
311
+ if (announced !== undefined && tokenRevoked(scoped.claims.iat, announced)) {
312
+ ws.send(encode({ error: 'unauthorized' }))
313
+ try {
314
+ ws.close(1008, 'walgit: token revoked')
315
+ } catch {
316
+ // Already gone.
317
+ }
318
+ return
319
+ }
320
+ }
321
+
322
+ // A scoped token's `exp` rides on the socket, so the fan-out below stops
323
+ // serving it when the token would have stopped being accepted anywhere else.
324
+ ws.serializeAttachment({
325
+ credential,
326
+ watch: parsed.value,
327
+ ...(scoped.kind === 'scoped'
328
+ ? { expires: scoped.claims.exp, issued: scoped.claims.iat, scopedRepo: scoped.claims.repo }
329
+ : {}),
330
+ } satisfies Subscription)
211
331
 
212
332
  let refsByRepo: Record<string, Record<string, string>>
213
333
  try {
@@ -280,6 +400,80 @@ export class WalgitEvents extends DurableObject<EventsEnv> {
280
400
  }
281
401
  }
282
402
 
403
+ /**
404
+ * Before a fan-out: close every scoped socket an event is about to reach
405
+ * whose token its repository's Index now revokes. One conditional read per
406
+ * repository, and only on a deployment with scoped sockets watching it. An
407
+ * Index that cannot be read closes the socket too — the client reconnects
408
+ * and is judged afresh — because delivering on an unknown verdict would be
409
+ * the fail-open this whole check exists to avoid.
410
+ */
411
+ private async closeRevokedWatching(events: readonly RefEvent[]): Promise<void> {
412
+ if (events.length === 0) return
413
+ const verdicts = new Map<string, string | null | 'unknown'>()
414
+ for (const ws of this.ctx.getWebSockets()) {
415
+ const { watch, expires, issued, scopedRepo } = readSubscription(ws)
416
+ if (!watch || expires === undefined) continue
417
+ if (!events.some((event) => watchCovers(watch, event))) continue
418
+ // A socket attached before `issued` was recorded cannot be judged here;
419
+ // the announcement path closes it on any revocation.
420
+ if (issued === undefined || scopedRepo === undefined) continue
421
+ if (!verdicts.has(scopedRepo)) {
422
+ const store = s3StoreFrom(this.env, (credentials) => new AwsClient(credentials))
423
+ let since: string | null | 'unknown' = 'unknown'
424
+ if (store) {
425
+ try {
426
+ since = await this.revocations.validSince(store, scopedRepo)
427
+ } catch {
428
+ since = 'unknown'
429
+ }
430
+ }
431
+ verdicts.set(scopedRepo, since)
432
+ }
433
+ const since = verdicts.get(scopedRepo)!
434
+ if (since === null) continue
435
+ if (since !== 'unknown' && !tokenRevoked(issued, since)) continue
436
+ try {
437
+ ws.send(
438
+ encode({
439
+ error: since === 'unknown' ? 'could not check token revocation' : 'unauthorized',
440
+ }),
441
+ )
442
+ ws.close(1008, since === 'unknown' ? 'walgit: try again' : 'walgit: token revoked')
443
+ } catch {
444
+ // Already gone.
445
+ }
446
+ }
447
+ }
448
+
449
+ /**
450
+ * Close every socket watching on a scoped token that one of these
451
+ * revocations covers: issued before `since`, for that repository. A scoped
452
+ * socket accepted before this code shipped carries neither field, and is
453
+ * closed by any revocation — the client reconnects and is judged afresh,
454
+ * which costs it a reconnect and never lets it outlive one.
455
+ */
456
+ private revokeTokens(revoked: readonly TokensRevoked[]): void {
457
+ if (revoked.length === 0) return
458
+ for (const ws of this.ctx.getWebSockets()) {
459
+ const { watch, expires, issued, scopedRepo } = readSubscription(ws)
460
+ // Unscoped sockets carry no `expires`; a scoped one always does.
461
+ if (!watch || expires === undefined) continue
462
+ const hit = revoked.some(
463
+ (r) =>
464
+ (scopedRepo === undefined || scopedRepo === r.repo) &&
465
+ (issued === undefined || tokenRevoked(issued, r.since)),
466
+ )
467
+ if (!hit) continue
468
+ try {
469
+ ws.send(encode({ error: 'unauthorized' }))
470
+ ws.close(1008, 'walgit: token revoked')
471
+ } catch {
472
+ // Already gone.
473
+ }
474
+ }
475
+ }
476
+
283
477
  /**
284
478
  * Which of these repositories the presented credential may read, from the
285
479
  * container — the only half that can verify an SSH signature.
@@ -318,8 +512,20 @@ export class WalgitEvents extends DurableObject<EventsEnv> {
318
512
  private broadcast(events: readonly RefEvent[]): number {
319
513
  let delivered = 0
320
514
  for (const ws of this.ctx.getWebSockets()) {
321
- const { watch } = readSubscription(ws)
515
+ const { watch, expires } = readSubscription(ws)
322
516
  if (!watch) continue
517
+ // A scoped token that has expired since its watch was accepted
518
+ // (docs/adr/0021): told, closed, and sent nothing. The client
519
+ // reconnects with a fresh token and is judged again.
520
+ if (expires !== undefined && scopedTokenExpired(expires)) {
521
+ try {
522
+ ws.send(encode({ error: 'token expired' }))
523
+ ws.close(1008, 'walgit: token expired')
524
+ } catch {
525
+ // Already gone.
526
+ }
527
+ continue
528
+ }
323
529
  const wanted = events.filter((event) => watchCovers(watch, event))
324
530
  if (wanted.length === 0) continue
325
531
  // Through the outbox rather than straight to the socket: it holds each
@@ -405,6 +611,12 @@ interface Subscription {
405
611
  credential: string | null
406
612
  /** Null until the client sends a valid `watch`. */
407
613
  watch: WatchEntry[] | null
614
+ /** A scoped token's `exp`, in seconds, when the watch was accepted on one. */
615
+ expires?: number
616
+ /** Its `iat`, in seconds — what a revocation is compared with. */
617
+ issued?: number
618
+ /** Its claimed repository — the one Index whose revocation applies to it. */
619
+ scopedRepo?: string
408
620
  }
409
621
 
410
622
  /** What this socket carries, whatever vintage of this code attached it. */
@@ -416,10 +628,13 @@ function readSubscription(ws: WebSocket): Subscription {
416
628
  // credential — which, on a Private deployment, is an unproven reader.
417
629
  if (Array.isArray(attachment)) return { credential: null, watch: attachment as WatchEntry[] }
418
630
  if (attachment && typeof attachment === 'object') {
419
- const { credential, watch } = attachment as Partial<Subscription>
631
+ const { credential, watch, expires, issued, scopedRepo } = attachment as Partial<Subscription>
420
632
  return {
421
633
  credential: typeof credential === 'string' ? credential : null,
422
634
  watch: Array.isArray(watch) ? watch : null,
635
+ ...(typeof expires === 'number' ? { expires } : {}),
636
+ ...(typeof issued === 'number' ? { issued } : {}),
637
+ ...(typeof scopedRepo === 'string' ? { scopedRepo } : {}),
423
638
  }
424
639
  }
425
640
  } catch {
@@ -34,6 +34,12 @@ import { Container } from '@cloudflare/containers'
34
34
  import { capabilitiesFrom, type Capabilities } from '../shared/capabilities'
35
35
  import { containerEnv, fingerprintEnv, reconcileContainerEnv } from '../shared/container-env'
36
36
  import { parseTokens } from '../shared/credentials'
37
+ import {
38
+ type ScopedClaims,
39
+ scopeTargetOf,
40
+ scopedAccessOf,
41
+ scopedEdgeAnswer,
42
+ } from '../shared/scoped-token'
37
43
  import { authorizeAnnounce, authorizeSubscribe } from '../shared/events'
38
44
  import { renderLanding, wantsLanding } from '../shared/landing'
39
45
  import { renderLlms, wantsLlms } from '../shared/llms'
@@ -81,6 +87,7 @@ import { browseResponse } from '../shared/browse'
81
87
  import { type ContainerBindings, containerFor } from './container-binding'
82
88
  import { WalgitDurableContainer } from './durable-container'
83
89
  import { refsAtEdge, uploadPackKeyFor } from '../shared/edge-refs'
90
+ import { revocationOf, revokedMessage, TokenRevocationReader } from '../shared/token-revocation'
84
91
  import { BROADCAST_PATH, EVENTS_OBJECT_NAME, WalgitEvents } from './events-do'
85
92
  import { handleMcp } from './mcp'
86
93
  // The card's picture, as bytes in the bundle (wrangler.jsonc's `Data` rule).
@@ -163,6 +170,14 @@ export interface Env extends ContainerBindings {
163
170
  */
164
171
  WALGIT_EVENTS_TOKEN?: string
165
172
  WALGIT_EVENTS_URL?: string
173
+ /**
174
+ * The push webhook (shared/webhook.ts): one HMAC-signed POST per moved ref
175
+ * to `WALGIT_WEBHOOK_URL`. Off unless BOTH are set. The Worker only forwards
176
+ * them — the container's `post-receive` announcer delivers — and the secret
177
+ * belongs in `workerSecrets`, never `workerVars`.
178
+ */
179
+ WALGIT_WEBHOOK_URL?: string
180
+ WALGIT_WEBHOOK_SECRET?: string
166
181
  /**
167
182
  * The nonce seed that makes signed pushes possible (src/push-cert.ts). Unset
168
183
  * is the default and means the container never advertises the capability, so
@@ -217,6 +232,20 @@ export interface Env extends ContainerBindings {
217
232
  * container never does, so turning it either way restarts nothing.
218
233
  */
219
234
  WALGIT_SNAPSHOTS?: string
235
+ /**
236
+ * Scoped tokens (`shared/scoped-token.ts`, docs/adr/0021): comma-separated
237
+ * Ed25519 public keys, each 32 raw bytes in base64url. Off unless set — and
238
+ * with it unset not one request is judged differently. Public keys only:
239
+ * whoever mints tokens holds the private half, and walgit never does.
240
+ */
241
+ WALGIT_TOKEN_PUBLIC_KEYS?: string
242
+ /**
243
+ * `1` to let the host merge a branch on request — fast-forward or squash, as
244
+ * a compare-and-swap (`src/merge.ts`, docs/adr/0022). Off unless set, and
245
+ * then `POST /_walgit/merge` does not exist. Only forwarded: the route and the
246
+ * push it makes are the container's.
247
+ */
248
+ WALGIT_MERGE?: string
220
249
  WALGIT_EVENTS: DurableObjectNamespace<WalgitEvents>
221
250
  }
222
251
 
@@ -388,6 +417,78 @@ export default {
388
417
  // instance set a key. Read beside the two reads it mirrors.
389
418
  const analytics = analyticsFrom(env)
390
419
 
420
+ // A scoped token (docs/adr/0021), judged FIRST and here, before anything
421
+ // can wake the container: a bad credential must never cost a cold start,
422
+ // and a good one for repository A must never reach anything about B. The
423
+ // container judges it again with the same function on whatever arrives.
424
+ //
425
+ // Everything that is not a scoped token — no credential, an admin token, a
426
+ // Read Challenge signature, a deployment without the keys — comes out
427
+ // `unscoped` and takes exactly the path it took before.
428
+ const access = await scopedAccessOf(request.headers.get('authorization'), {
429
+ keys: env.WALGIT_TOKEN_PUBLIC_KEYS,
430
+ known: [
431
+ ...parseTokens(env.WALGIT_HTTP_TOKENS),
432
+ ...(env.WALGIT_EVENTS_TOKEN ? [env.WALGIT_EVENTS_TOKEN] : []),
433
+ ],
434
+ })
435
+ const scoped: ScopedClaims | null = access.kind === 'scoped' ? access.claims : null
436
+ const scopedRefusal = scopedEdgeAnswer(
437
+ access,
438
+ scopeTargetOf(request.method, url.pathname, url.search),
439
+ )
440
+ if (scopedRefusal) {
441
+ record(env, ctx, {
442
+ ...base(classifyRequest(request.method, url.pathname, url.search), request),
443
+ outcome: 'reject',
444
+ reject: scopedRefusal.status === 503 ? 'unavailable' : 'unauthorized',
445
+ status: scopedRefusal.status,
446
+ served: false,
447
+ cold: false,
448
+ ttfbMs: Date.now() - startedAt,
449
+ totalMs: Date.now() - startedAt,
450
+ bytesServed: 0,
451
+ })
452
+ return scopedRefusal
453
+ }
454
+
455
+ // Revoked (`shared/token-revocation.ts`): the token's own repository's
456
+ // Index says tokens issued before some instant are no longer good. Read
457
+ // here, on every scoped request and before any surface — git, the pages,
458
+ // the list, MCP, the event socket — so a revocation is in force from the
459
+ // next request, and judged again by the container and the fan-out on what
460
+ // reaches them. A store this edge cannot read refuses rather than passes.
461
+ if (scoped) {
462
+ const revocation = await revocationOf(scoped, edgeStore(env), edgeRevocations)
463
+ if (revocation.kind !== 'valid') {
464
+ const revoked = revocation.kind === 'revoked'
465
+ record(env, ctx, {
466
+ ...base(classifyRequest(request.method, url.pathname, url.search), request),
467
+ outcome: 'reject',
468
+ reject: revoked ? 'unauthorized' : 'unavailable',
469
+ status: revoked ? 401 : 503,
470
+ served: false,
471
+ cold: false,
472
+ ttfbMs: Date.now() - startedAt,
473
+ totalMs: Date.now() - startedAt,
474
+ bytesServed: 0,
475
+ })
476
+ return revoked
477
+ ? new Response(revokedMessage(scoped.repo, revocation.since), {
478
+ status: 401,
479
+ headers: {
480
+ 'content-type': 'text/plain; charset=utf-8',
481
+ 'cache-control': 'no-store',
482
+ 'www-authenticate': BASIC_CHALLENGE,
483
+ },
484
+ })
485
+ : new Response(`${revocation.reason}\n`, {
486
+ status: 503,
487
+ headers: { 'content-type': 'text/plain; charset=utf-8', 'cache-control': 'no-store' },
488
+ })
489
+ }
490
+ }
491
+
391
492
  // The browser half of `/`, answered at the edge (shared/landing.ts). Placed
392
493
  // before every other decision on purpose: a link on an aggregator points at
393
494
  // this exact URL, and none of that traffic should wake the container, queue
@@ -655,7 +756,12 @@ export default {
655
756
  authorization: request.headers.get('authorization'),
656
757
  search: url.search,
657
758
  },
658
- { store, caps, tokens: parseTokens(env.WALGIT_HTTP_TOKENS) },
759
+ {
760
+ store,
761
+ caps,
762
+ tokens: parseTokens(env.WALGIT_HTTP_TOKENS),
763
+ ...(scoped ? { scopedTo: scoped.repo } : {}),
764
+ },
659
765
  )
660
766
  const bytes = new TextEncoder().encode(answer.body)
661
767
  record(env, ctx, {
@@ -859,7 +965,7 @@ export default {
859
965
  // current refs, and then deliver nothing forever, because the container's
860
966
  // `post-receive` had no URL to announce to.
861
967
  if ((url.pathname === EVENTS_PATH || url.pathname === ANNOUNCE_PATH) && caps.events) {
862
- return events(request, url, env, caps)
968
+ return events(request, url, env, caps, scoped)
863
969
  }
864
970
 
865
971
  // The MCP endpoint (`shared/mcp.ts`), answered at the edge like the two
@@ -873,7 +979,7 @@ export default {
873
979
  // `/_walgit/` is reserved, and a repository called `mcp` is reached at
874
980
  // `/mcp.git/…`, so this route cannot shadow one.
875
981
  if (url.pathname === MCP_PATH) {
876
- const response = await handleMcp(request, env, caps, operator, url.host)
982
+ const response = await handleMcp(request, env, caps, operator, url.host, scoped)
877
983
  record(env, ctx, {
878
984
  // Classified rather than hand-labelled, so the kind this row carries
879
985
  // and the kind `shared/telemetry.ts` names for this path cannot become
@@ -1097,7 +1203,13 @@ function authorizationOf(request: Request): HeadersInit {
1097
1203
  * cannot reach a different verdict from the route that claimed it or from the
1098
1204
  * documents that advertised it.
1099
1205
  */
1100
- async function events(request: Request, url: URL, env: Env, caps: Capabilities): Promise<Response> {
1206
+ async function events(
1207
+ request: Request,
1208
+ url: URL,
1209
+ env: Env,
1210
+ caps: Capabilities,
1211
+ scoped: ScopedClaims | null,
1212
+ ): Promise<Response> {
1101
1213
  const stub = env.WALGIT_EVENTS.get(env.WALGIT_EVENTS.idFromName(EVENTS_OBJECT_NAME))
1102
1214
 
1103
1215
  if (url.pathname === ANNOUNCE_PATH) {
@@ -1127,11 +1239,18 @@ async function events(request: Request, url: URL, env: Env, caps: Capabilities):
1127
1239
  // git auth. On a deployment spelling it `true` the manual told an agent that
1128
1240
  // reads need no credential while every subscribe answered 401 — the exact
1129
1241
  // hazard `flagEnabled` was written for (`shared/policy.ts`).
1130
- const allowed = authorizeSubscribe({
1131
- authorization: request.headers.get('authorization'),
1132
- tokens: parseTokens(env.WALGIT_HTTP_TOKENS),
1133
- isPublic: caps.publicAccess,
1134
- })
1242
+ //
1243
+ // A verified scoped token (docs/adr/0021) is let through here in place of
1244
+ // the deployment credential: the repositories it may watch are named on the
1245
+ // socket, after the upgrade, and the Durable Object holds every one of them
1246
+ // to the token's claim (`worker/events-do.ts`).
1247
+ const allowed =
1248
+ scoped !== null ||
1249
+ authorizeSubscribe({
1250
+ authorization: request.headers.get('authorization'),
1251
+ tokens: parseTokens(env.WALGIT_HTTP_TOKENS),
1252
+ isPublic: caps.publicAccess,
1253
+ })
1135
1254
  if (!allowed) {
1136
1255
  return new Response('unauthorized\n', {
1137
1256
  status: 401,
@@ -1214,6 +1333,12 @@ async function absentAtEdge(env: Env, caps: Capabilities, repo: string): Promise
1214
1333
  }
1215
1334
  }
1216
1335
 
1336
+ /**
1337
+ * The isolate's revocation reader: it remembers each Index's etag so an
1338
+ * unchanged one costs a 304, and never answers without asking the store.
1339
+ */
1340
+ const edgeRevocations = new TokenRevocationReader()
1341
+
1217
1342
  function edgeStore(env: Env): ObjectStore | null {
1218
1343
  return s3StoreFrom(env, (credentials) => new AwsClient(credentials))
1219
1344
  }