@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
@@ -0,0 +1,510 @@
1
+ /**
2
+ * Administering one repository over HTTP — create it (optionally with a first
3
+ * commit), delete it, read what it holds — for a server that has the admin
4
+ * credential and nothing else.
5
+ *
6
+ * The three already existed as operator commands (`walgit delete`, `walgit
7
+ * usage`) that need the object store's own credentials. A host minting one
8
+ * repository per tenant (docs/adr/0021) wants them without holding those, so
9
+ * they are answered here, by the one process that already holds the store.
10
+ * Nothing in this file is a second implementation: delete is `deleteRepo` with
11
+ * its grace semantics, usage is `usageOfIndex`, and a seed is an ordinary push.
12
+ *
13
+ * **A seed is a push, not a write.** The first commit is built in a scratch
14
+ * repository and pushed into the repository's cache over git's local
15
+ * transport, so `pre-receive` and `reference-transaction` judge it exactly as
16
+ * they judge a client's push: the size caps, a Signer List, the WAL publish
17
+ * that makes it durable. Writing the Index and the pack directly would be a
18
+ * second push path, and the one this file must never become is a door around
19
+ * the rules a push is held to.
20
+ *
21
+ * The routing and the credential are `src/http.ts`'s; this is what the routes
22
+ * do once they have been reached.
23
+ */
24
+
25
+ import * as fs from 'node:fs'
26
+ import * as os from 'node:os'
27
+ import * as path from 'node:path'
28
+
29
+ import { indexKey } from '../shared/keys'
30
+ import type { ObjectStore } from '../shared/store'
31
+ import { emptyIndex, loadIndex } from '../shared/wal-index'
32
+ import { deleteRepo, type DeleteResult } from './delete-repo'
33
+ import { git, gitAsync, type GitOptions } from './git'
34
+ import type { ResolvedRepo } from './repo'
35
+ import { usageOfIndex, type RepoUsage } from './usage'
36
+ import { commitIndex } from './wal-index'
37
+
38
+ /**
39
+ * The largest seed body walgit will read.
40
+ *
41
+ * A seed is a scaffold — a README, a config file, a starter tree — and it
42
+ * arrives as JSON held in memory, so it is bounded here before it is parsed.
43
+ * Anything larger is a real push, which streams.
44
+ */
45
+ export const MAX_SEED_BYTES = 1024 * 1024
46
+
47
+ /** How many files one seed may name. A bound on the work one request does. */
48
+ export const MAX_SEED_FILES = 1000
49
+
50
+ /** The first commit a created repository holds, as the request names it. */
51
+ export interface Seed {
52
+ /** Repository path → file content (UTF-8). Every file is mode `100644`. */
53
+ files: Record<string, string>
54
+ message: string
55
+ author: { name: string; email: string }
56
+ /** A branch name, not a ref: `main` becomes `refs/heads/main`. */
57
+ branch: string
58
+ }
59
+
60
+ export type SeedParse = { ok: true; seed: Seed | null } | { ok: false; message: string }
61
+
62
+ /**
63
+ * Read a create request's body: empty means an empty repository, and anything
64
+ * else must be a well-formed seed.
65
+ *
66
+ * Strict rather than forgiving, because every field ends up in a git object
67
+ * that cannot be edited afterwards — a path git would refuse, an ident with a
68
+ * `<` in it, a branch name that is not one. Each is refused here with what was
69
+ * wrong, before a repository is created at all.
70
+ */
71
+ export function parseSeed(text: string): SeedParse {
72
+ if (text.trim() === '') return { ok: true, seed: null }
73
+ let body: unknown
74
+ try {
75
+ body = JSON.parse(text)
76
+ } catch {
77
+ return { ok: false, message: 'the body is not JSON' }
78
+ }
79
+ if (!isRecord(body)) return { ok: false, message: 'the body must be a JSON object' }
80
+
81
+ const files = body.files
82
+ if (!isRecord(files)) {
83
+ return { ok: false, message: '"files" must be an object of path → content' }
84
+ }
85
+ const entries = Object.entries(files)
86
+ if (entries.length === 0) return { ok: false, message: '"files" names no file' }
87
+ if (entries.length > MAX_SEED_FILES) {
88
+ return { ok: false, message: `"files" names more than ${MAX_SEED_FILES} files` }
89
+ }
90
+ const paths = new Set<string>()
91
+ for (const [name, content] of entries) {
92
+ if (typeof content !== 'string') {
93
+ return { ok: false, message: `the content of ${JSON.stringify(name)} must be a string` }
94
+ }
95
+ const why = badPath(name)
96
+ if (why) return { ok: false, message: `${JSON.stringify(name)} ${why}` }
97
+ paths.add(name)
98
+ }
99
+ // A file and a directory of the same name cannot both be in one tree.
100
+ for (const name of paths) {
101
+ const segments = name.split('/')
102
+ for (let i = 1; i < segments.length; i++) {
103
+ const parent = segments.slice(0, i).join('/')
104
+ if (paths.has(parent)) {
105
+ return { ok: false, message: `${JSON.stringify(parent)} is both a file and a directory` }
106
+ }
107
+ }
108
+ }
109
+
110
+ const message = body.message
111
+ if (typeof message !== 'string' || message.trim() === '') {
112
+ return { ok: false, message: '"message" must be a non-empty string' }
113
+ }
114
+
115
+ const author = body.author
116
+ if (!isRecord(author)) return { ok: false, message: '"author" must be { name, email }' }
117
+ const name = author.name
118
+ const email = author.email
119
+ if (!identPart(name)) {
120
+ return {
121
+ ok: false,
122
+ message: '"author.name" must be a non-empty string without <, > or a newline',
123
+ }
124
+ }
125
+ if (!identPart(email)) {
126
+ return {
127
+ ok: false,
128
+ message: '"author.email" must be a non-empty string without <, > or a newline',
129
+ }
130
+ }
131
+
132
+ const branch = body.branch ?? 'main'
133
+ if (typeof branch !== 'string' || !branchNameOk(branch)) {
134
+ return { ok: false, message: '"branch" must be a valid git branch name' }
135
+ }
136
+
137
+ return {
138
+ ok: true,
139
+ seed: { files: files as Record<string, string>, message, author: { name, email }, branch },
140
+ }
141
+ }
142
+
143
+ function isRecord(value: unknown): value is Record<string, unknown> {
144
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
145
+ }
146
+
147
+ /**
148
+ * A git ident half: what `commit-tree` would otherwise strip or choke on.
149
+ * Shared with `src/merge.ts`, whose squash commit takes an author too.
150
+ */
151
+ export function identPart(value: unknown): value is string {
152
+ return (
153
+ typeof value === 'string' && value.trim() !== '' && !/[<>]/.test(value) && !hasControl(value)
154
+ )
155
+ }
156
+
157
+ /**
158
+ * Why git would refuse this path in a tree, or `null` when it would not.
159
+ *
160
+ * `.git` in any case is refused as git's own `verify_path` refuses it: a tree
161
+ * entry by that name is how a clone gets its hooks overwritten.
162
+ */
163
+ function badPath(name: string): string | null {
164
+ if (name === '') return 'is empty'
165
+ // Control characters have no business in a scaffold's file names, and NUL
166
+ // is the record separator the path is written to git with.
167
+ if (hasControl(name)) return 'contains a control character'
168
+ if (name.startsWith('/') || name.endsWith('/')) return 'must be relative, with no trailing slash'
169
+ for (const segment of name.split('/')) {
170
+ if (segment === '' || segment === '.' || segment === '..') {
171
+ return 'has an empty, "." or ".." segment'
172
+ }
173
+ // `.git` as git's `verify_path` spells it on every platform a clone may
174
+ // land on: any case, NTFS's trailing dots and spaces, and its 8.3 alias.
175
+ const folded = segment.toLowerCase().replace(/[. ]+$/, '')
176
+ if (folded === '.git' || folded === 'git~1') return 'names a .git directory'
177
+ }
178
+ return null
179
+ }
180
+
181
+ /** A C0 control character or DEL — NUL, tab, CR and LF among them. */
182
+ function hasControl(value: string): boolean {
183
+ for (let i = 0; i < value.length; i++) {
184
+ const code = value.charCodeAt(i)
185
+ if (code < 0x20 || code === 0x7f) return true
186
+ }
187
+ return false
188
+ }
189
+
190
+ function branchNameOk(branch: string): boolean {
191
+ if (branch === '' || branch.startsWith('-')) return false
192
+ return git(['check-ref-format', `refs/heads/${branch}`]).status === 0
193
+ }
194
+
195
+ // ── The operations ──────────────────────────────────────────────────────────
196
+
197
+ export type CreateResult =
198
+ | { kind: 'created'; repo: string; commit?: string; ref?: string }
199
+ /**
200
+ * The name already has an Index — a repository, or one being deleted, in
201
+ * which case `collectAfter` is when the name frees up.
202
+ */
203
+ | { kind: 'exists'; repo: string; collectAfter?: string }
204
+ /** The seed push was refused; nothing was left behind. */
205
+ | { kind: 'refused'; repo: string; message: string }
206
+
207
+ /**
208
+ * A seed git itself refused — the hooks turning the push down, or a tree that
209
+ * would not hold the files asked for. The caller's to fix, so a 422; anything
210
+ * else that goes wrong while seeding is walgit's, and is thrown as itself.
211
+ */
212
+ export class SeedRefused extends Error {}
213
+
214
+ /** What `src/http.ts` is given to answer the admin routes with. */
215
+ export interface AdminOps {
216
+ create(repo: ResolvedRepo, seed: Seed | null): Promise<CreateResult>
217
+ delete(repo: ResolvedRepo): Promise<DeleteResult>
218
+ /** `null` when the log holds no Index for this name. */
219
+ usage(repoId: string): Promise<AdminUsage | null>
220
+ /**
221
+ * Revoke the repository's scoped tokens issued before `since` (default now)
222
+ * by moving its `tokens_valid_since` forward. `null` when the log holds no
223
+ * Index for this name; `'later-than-now'` for a `since` in the future, which
224
+ * would revoke tokens not minted yet — a different request from this one.
225
+ */
226
+ revokeTokens(repoId: string, since: Date | null): Promise<RevokeResult | 'later-than-now' | null>
227
+ }
228
+
229
+ /** The usage row, with what only the admin surface reports beside it. */
230
+ export type AdminUsage = RepoUsage & {
231
+ /** The repository's tokens-valid-since instant, or `null` when none. */
232
+ tokensValidSince: string | null
233
+ }
234
+
235
+ export interface RevokeResult {
236
+ repo: string
237
+ /**
238
+ * The instant in force after this request. Never earlier than it was: an
239
+ * older `since` than the one already stored leaves the stored one standing,
240
+ * because moving it back would quietly make revoked tokens valid again.
241
+ */
242
+ tokensValidSince: string
243
+ /**
244
+ * Whether the event fan-out acknowledged the revocation, so sockets already
245
+ * open were closed. `false` when it did not, or no stream is configured:
246
+ * the revocation still holds for every request, and a held socket is
247
+ * re-judged before the next event it would be sent.
248
+ */
249
+ announced: boolean
250
+ }
251
+
252
+ /**
253
+ * How far ahead of this clock a supplied `since` may be and still mean "now":
254
+ * a client sending its own now from a slightly fast clock. Clamped to now.
255
+ */
256
+ export const REVOKE_SKEW_MS = 60_000
257
+
258
+ /** An ISO 8601 instant with a date, a time and a zone — what the docs promise. */
259
+ const ISO_INSTANT = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:\d{2})$/
260
+
261
+ export type RevokeParse = { ok: true; since: Date | null } | { ok: false; message: string }
262
+
263
+ /**
264
+ * Read a revoke request's body: empty means now, and otherwise
265
+ * `{"since": "<ISO instant>"}`. Whether it is later than now is the admin
266
+ * operation's question, asked on its own clock.
267
+ */
268
+ export function parseRevoke(text: string): RevokeParse {
269
+ if (text.trim() === '') return { ok: true, since: null }
270
+ let body: unknown
271
+ try {
272
+ body = JSON.parse(text)
273
+ } catch {
274
+ return { ok: false, message: 'the body is not JSON' }
275
+ }
276
+ if (!isRecord(body)) return { ok: false, message: 'the body must be a JSON object' }
277
+ const since = body.since
278
+ if (since === undefined) return { ok: true, since: null }
279
+ if (typeof since !== 'string') {
280
+ return { ok: false, message: '"since" must be an ISO 8601 instant' }
281
+ }
282
+ const ms = ISO_INSTANT.test(since) ? Date.parse(since) : Number.NaN
283
+ if (!Number.isFinite(ms)) return { ok: false, message: '"since" must be an ISO 8601 instant' }
284
+ return { ok: true, since: new Date(ms) }
285
+ }
286
+
287
+ export interface AdminDeps {
288
+ store: ObjectStore
289
+ ensureRepo: (repo: ResolvedRepo) => ResolvedRepo
290
+ syncRepo: (repo: ResolvedRepo) => Promise<unknown>
291
+ /** `WALGIT_DELETE_GRACE_MS`, read once by the caller. */
292
+ graceMs: number
293
+ /**
294
+ * Tell the event fan-out a repository's tokens were revoked, so sockets
295
+ * already open on one of them are closed rather than served until `exp`.
296
+ * Absent where no event stream is configured; must never throw.
297
+ */
298
+ announceRevoked?: (repoId: string, since: string) => Promise<boolean>
299
+ now?: () => Date
300
+ }
301
+
302
+ export function createAdminOps(deps: AdminDeps): AdminOps {
303
+ const now = () => (deps.now ?? (() => new Date()))()
304
+ return {
305
+ async create(repo, seed) {
306
+ // The name is claimed by the Index, under an if-absent write: of two
307
+ // creates racing for one name exactly one wins, and the other is the
308
+ // same 409 a create of an existing repository gets. Nothing before this
309
+ // line writes anything. `created_at` is what expiry dates the
310
+ // repository by until its first push.
311
+ const claimed = await commitIndex(
312
+ deps.store,
313
+ { ...emptyIndex(repo.repoId), created_at: now().toISOString() },
314
+ null,
315
+ )
316
+ if (!claimed.ok) {
317
+ const { index } = await loadIndex(deps.store, repo.repoId)
318
+ return {
319
+ kind: 'exists',
320
+ repo: repo.repoId,
321
+ ...(index.deletion ? { collectAfter: index.deletion.collect_after } : {}),
322
+ }
323
+ }
324
+ if (!seed) return { kind: 'created', repo: repo.repoId }
325
+
326
+ try {
327
+ const ensured = deps.ensureRepo(repo)
328
+ await deps.syncRepo(ensured)
329
+ const commit = await pushSeed(ensured.dir, seed, now())
330
+ return { kind: 'created', repo: repo.repoId, commit, ref: `refs/heads/${seed.branch}` }
331
+ } catch (err) {
332
+ // A failed seed leaves no repository behind, so the caller can fix the
333
+ // body (or wait out the outage) and ask again instead of meeting its
334
+ // own 409. Only the Index this request wrote is removed, and only
335
+ // while it is still the object this request wrote: a push that
336
+ // published since changed its etag, and that is somebody's work.
337
+ //
338
+ // The store has no conditional delete, so a push landing between this
339
+ // read and the delete is not excluded — a window of one round trip, on
340
+ // a name created a moment ago by this very request. The cache
341
+ // directory is left alone: it is disposable, holds nothing the hooks
342
+ // published, and another request may be reading it.
343
+ try {
344
+ const current = await deps.store.get(indexKey(repo.repoId))
345
+ if (current?.etag === claimed.etag) await deps.store.delete(indexKey(repo.repoId))
346
+ } catch {
347
+ // The rollback failing leaves an empty repository behind, which is
348
+ // a 409 on retry and an ordinary delete away; the seed's own failure
349
+ // is the thing to report.
350
+ }
351
+ if (err instanceof SeedRefused) {
352
+ return { kind: 'refused', repo: repo.repoId, message: err.message }
353
+ }
354
+ throw err
355
+ }
356
+ },
357
+
358
+ delete(repo) {
359
+ // Not a dry run: an HTTP DELETE is the asking, as the scheduled sweep is.
360
+ // The grace is the one `walgit delete` and expiry use, so the first call
361
+ // tombstones and a call once it has elapsed collects.
362
+ return deleteRepo(deps.store, repo.repoId, {
363
+ dryRun: false,
364
+ graceMs: deps.graceMs,
365
+ dir: repo.dir,
366
+ ...(deps.now ? { now: deps.now } : {}),
367
+ })
368
+ },
369
+
370
+ async usage(repoId) {
371
+ const { index, etag } = await loadIndex(deps.store, repoId)
372
+ if (etag === null) return null
373
+ return { ...usageOfIndex(index), tokensValidSince: index.tokens_valid_since ?? null }
374
+ },
375
+
376
+ async revokeTokens(repoId, since) {
377
+ const at = now()
378
+ if (since && since.getTime() > at.getTime() + REVOKE_SKEW_MS) return 'later-than-now'
379
+ const asked = (since && since.getTime() < at.getTime() ? since : at).toISOString()
380
+ // A compare-and-swap loop rather than `updateIndex`, because an absent
381
+ // Index must stay absent: revoking a name nobody holds would claim it,
382
+ // and creating is the create route's job. To revoke for a name a write
383
+ // token could still create, create it first.
384
+ for (let attempt = 0; attempt < 8; attempt += 1) {
385
+ const { index, etag } = await loadIndex(deps.store, repoId)
386
+ if (etag === null) return null
387
+ const existing = index.tokens_valid_since
388
+ const effective =
389
+ existing !== undefined && Date.parse(existing) >= Date.parse(asked) ? existing : asked
390
+ if (effective !== existing) {
391
+ const written = await commitIndex(
392
+ deps.store,
393
+ { ...index, tokens_valid_since: effective },
394
+ etag,
395
+ )
396
+ if (!written.ok) continue
397
+ }
398
+ const announced = deps.announceRevoked
399
+ ? await deps.announceRevoked(repoId, effective)
400
+ : false
401
+ return { repo: repoId, tokensValidSince: effective, announced }
402
+ }
403
+ throw new Error('the Index is contended; try again')
404
+ },
405
+ }
406
+ }
407
+
408
+ /**
409
+ * Build the seed's one commit in a scratch repository and push it into `dir`.
410
+ * Returns the commit id; throws `SeedRefused` with git's own words when the
411
+ * push is refused.
412
+ *
413
+ * The scratch repository is a separate object database on purpose: nothing is
414
+ * written into the served repository except by `git-receive-pack`, so the
415
+ * hooks see the commit arrive in quarantine exactly as a client's would.
416
+ *
417
+ * Every git call is asynchronous and the blobs are written by one process, not
418
+ * one per file: this runs on the request path of the container that is also
419
+ * serving every clone and push, and the push's hooks make network round trips.
420
+ */
421
+ async function pushSeed(dir: string, seed: Seed, now: Date): Promise<string> {
422
+ const scratch = fs.mkdtempSync(path.join(os.tmpdir(), 'walgit-seed-'))
423
+ // No message leaving here names the scratch directory.
424
+ const scrub = (text: string) => text.trim().replaceAll(scratch, '<seed>')
425
+ const run = async (args: string[], opts: GitOptions = {}) => {
426
+ const res = await gitAsync(args, opts)
427
+ if (res.status !== 0) {
428
+ throw new Error(`walgit seed: git ${args[0]} failed: ${scrub(res.stderr)}`)
429
+ }
430
+ return res.stdout
431
+ }
432
+ try {
433
+ const gitDir = path.join(scratch, 'seed.git')
434
+ await run(['init', '--bare', '--quiet'], { operands: [gitDir] })
435
+
436
+ // The content goes to git through files named by index, so no requested
437
+ // path is ever a file name here or an argument anywhere.
438
+ const names = Object.keys(seed.files)
439
+ const blobs = path.join(scratch, 'blobs')
440
+ fs.mkdirSync(blobs)
441
+ const blobPaths = names.map((name, i) => {
442
+ const file = path.join(blobs, String(i))
443
+ fs.writeFileSync(file, seed.files[name]!)
444
+ return file
445
+ })
446
+ const oids = (
447
+ await run(['hash-object', '-w', '--stdin-paths'], {
448
+ gitDir,
449
+ input: `${blobPaths.join('\n')}\n`,
450
+ })
451
+ )
452
+ .trim()
453
+ .split('\n')
454
+ if (oids.length !== names.length)
455
+ throw new Error('walgit seed: git hashed the wrong number of files')
456
+
457
+ // NUL-terminated records: with `-z` git reads each path verbatim, with no
458
+ // C-unquoting of a path that begins with a double quote.
459
+ const indexEnv = { GIT_INDEX_FILE: path.join(scratch, 'index') }
460
+ await run(['update-index', '-z', '--index-info'], {
461
+ gitDir,
462
+ input: names.map((name, i) => `100644 blob ${oids[i]}\t${name}\0`).join(''),
463
+ env: indexEnv,
464
+ })
465
+ const tree = (await run(['write-tree'], { gitDir, env: indexEnv })).trim()
466
+
467
+ // `update-index` IGNORES a path it will not carry — a name only some
468
+ // filesystem treats as `.git` — and still exits 0. So the tree is read
469
+ // back, and a seed whose tree is not exactly the files asked for is
470
+ // refused rather than committed short.
471
+ const listed = (await run(['ls-tree', '-r', '-z', '--name-only', tree], { gitDir }))
472
+ .split('\0')
473
+ .filter(Boolean)
474
+ const missing = names.filter((name) => !listed.includes(name))
475
+ if (missing.length > 0 || listed.length !== names.length) {
476
+ throw new SeedRefused(
477
+ `git would not carry ${missing.length > 0 ? missing.map((name) => JSON.stringify(name)).join(', ') : 'these paths as named'} in a tree`,
478
+ )
479
+ }
480
+
481
+ // Author and committer are the one ident the request named: walgit did not
482
+ // write this commit, the caller did, and the commit should say so.
483
+ const date = `${Math.floor(now.getTime() / 1000)} +0000`
484
+ const commit = (
485
+ await run(['commit-tree', tree, '-F', '-'], {
486
+ gitDir,
487
+ input: seed.message.endsWith('\n') ? seed.message : `${seed.message}\n`,
488
+ env: {
489
+ GIT_AUTHOR_NAME: seed.author.name,
490
+ GIT_AUTHOR_EMAIL: seed.author.email,
491
+ GIT_AUTHOR_DATE: date,
492
+ GIT_COMMITTER_NAME: seed.author.name,
493
+ GIT_COMMITTER_EMAIL: seed.author.email,
494
+ GIT_COMMITTER_DATE: date,
495
+ },
496
+ })
497
+ ).trim()
498
+
499
+ const pushed = await gitAsync(
500
+ ['push', '--quiet', '--porcelain', dir, `${commit}:refs/heads/${seed.branch}`],
501
+ { gitDir },
502
+ )
503
+ if (pushed.status !== 0) {
504
+ throw new SeedRefused(`the seed push was refused: ${scrub(pushed.stderr || pushed.stdout)}`)
505
+ }
506
+ return commit
507
+ } finally {
508
+ fs.rmSync(scratch, { recursive: true, force: true })
509
+ }
510
+ }
@@ -10,14 +10,18 @@
10
10
  * the one path this project promises to keep fast, for a feature whose entire
11
11
  * purpose is to stop clients spending time on staleness.
12
12
  *
13
- * Failures are logged and swallowed, and there is nothing to retry: the push is
14
- * already durable and `index.json` already carries the refs this would have
15
- * announced, so a subscriber's next handshake reads the truth from there
16
- * regardless. A dropped announcement costs one subscriber one push of
17
- * freshness, never correctness.
13
+ * Failures are logged and swallowed, and the stream's announcement is not
14
+ * retried: the push is already durable and `index.json` already carries the
15
+ * refs this would have announced, so a subscriber's next handshake reads the
16
+ * truth from there regardless. A dropped announcement costs one subscriber one
17
+ * push of freshness, never correctness.
18
+ *
19
+ * The push webhook is the exception, because a receiver behind a URL has no
20
+ * handshake to catch up through: its delivery is retried with backoff here
21
+ * (shared/webhook.ts), in this process, which nobody is waiting on.
18
22
  */
19
23
 
20
- import { announce, announceConfigFromEnv } from './announce'
24
+ import { publish, publishConfigFromEnv } from './announce'
21
25
  import type { RefChange } from '../shared/wal-index'
22
26
 
23
27
  const repoId = process.argv[2]
@@ -32,12 +36,16 @@ const mergedPayload = process.argv[4]
32
36
  async function main(): Promise<void> {
33
37
  if (!repoId || !payload)
34
38
  throw new Error('usage: announce-main <repo-id> <changes-json> [merged-json]')
35
- const config = announceConfigFromEnv()
39
+ const config = publishConfigFromEnv()
36
40
  // Not an error: the environment can change between the spawn and the start,
37
- // and a deployment with no stream configured simply has nothing to tell.
41
+ // and a deployment with neither the stream nor the webhook configured simply
42
+ // has nothing to tell.
38
43
  if (!config) return
39
44
  const merged = mergedPayload ? (JSON.parse(mergedPayload) as Record<string, string[]>) : {}
40
- await announce(config, repoId, JSON.parse(payload) as RefChange[], fetch, merged)
45
+ // The stream and the push webhook (shared/webhook.ts) together. The
46
+ // webhook's retries are why this process can outlive the push by seconds,
47
+ // and why that costs the pusher nothing: nobody is waiting on it.
48
+ await publish(config, repoId, JSON.parse(payload) as RefChange[], merged)
41
49
  }
42
50
 
43
51
  main().catch((err) => {
@@ -24,6 +24,13 @@
24
24
  import { eventsFromChanges } from '../shared/events'
25
25
  import { ANNOUNCE_PATH, SIGNERS_REF } from '../shared/protocol'
26
26
  import type { RefChange } from '../shared/wal-index'
27
+ import {
28
+ type DeliverOptions,
29
+ type WebhookConfig,
30
+ deliverWebhooks,
31
+ webhookConfigFromEnv,
32
+ webhookEventsFromChanges,
33
+ } from '../shared/webhook'
27
34
 
28
35
  export interface AnnounceConfig {
29
36
  /** The deployment's own public origin — the Worker in front of this container. */
@@ -108,3 +115,82 @@ export async function announce(
108
115
  return false
109
116
  }
110
117
  }
118
+
119
+ /**
120
+ * Tell the fan-out a repository's scoped tokens were revoked (docs/adr/0021),
121
+ * so a socket already open on one of them is closed now rather than served
122
+ * until its `exp`. Never throws, for the reason `announce` never does: the
123
+ * revocation is already in the Index, and every new request reads it there.
124
+ * Returns whether the fan-out acknowledged it.
125
+ */
126
+ export async function announceTokensRevoked(
127
+ config: AnnounceConfig,
128
+ repoId: string,
129
+ since: string,
130
+ fetchImpl: typeof fetch = fetch,
131
+ ): Promise<boolean> {
132
+ try {
133
+ const response = await fetchImpl(`${config.url}${ANNOUNCE_PATH}`, {
134
+ method: 'POST',
135
+ headers: {
136
+ 'content-type': 'application/json',
137
+ authorization: `Bearer ${config.token}`,
138
+ },
139
+ body: JSON.stringify({ events: [], tokensRevoked: [{ repo: repoId, since }] }),
140
+ signal: AbortSignal.timeout(ANNOUNCE_TIMEOUT_MS),
141
+ })
142
+ await response.body?.cancel()
143
+ if (!response.ok) {
144
+ process.stderr.write(`walgit: token revocation announce refused (${response.status})\n`)
145
+ return false
146
+ }
147
+ return true
148
+ } catch (err) {
149
+ process.stderr.write(`walgit: token revocation announce failed: ${(err as Error).message}\n`)
150
+ return false
151
+ }
152
+ }
153
+
154
+ /** Everything a push can be announced to. Either half may be absent. */
155
+ export interface PublishConfig {
156
+ events: AnnounceConfig | null
157
+ webhook: WebhookConfig | null
158
+ }
159
+
160
+ /** What this environment announces to, or null when it announces to nothing. */
161
+ export function publishConfigFromEnv(
162
+ env: Record<string, string | undefined> = process.env,
163
+ ): PublishConfig | null {
164
+ const config = { events: announceConfigFromEnv(env), webhook: webhookConfigFromEnv(env) }
165
+ return config.events || config.webhook ? config : null
166
+ }
167
+
168
+ /**
169
+ * The one place a moved ref is announced: to the ref-event stream and to the
170
+ * push webhook (shared/webhook.ts), from the same changes. Anything that moves
171
+ * a ref and calls this fires both, so a new way of moving one cannot forget
172
+ * the webhook. Never throws.
173
+ *
174
+ * The webhook's retries are awaited here, which is why this runs in the
175
+ * detached announcer (src/announce-main.ts) and never on the push path.
176
+ */
177
+ export async function publish(
178
+ config: PublishConfig,
179
+ repoId: string,
180
+ changes: readonly RefChange[],
181
+ merged: Readonly<Record<string, string[]>> = {},
182
+ options: { fetchImpl?: typeof fetch; webhook?: DeliverOptions } = {},
183
+ ): Promise<void> {
184
+ const fetchImpl = options.fetchImpl ?? fetch
185
+ const work: Promise<unknown>[] = []
186
+ if (config.events) work.push(announce(config.events, repoId, changes, fetchImpl, merged))
187
+ if (config.webhook) {
188
+ work.push(
189
+ deliverWebhooks(config.webhook, webhookEventsFromChanges(repoId, changes, merged), {
190
+ fetchImpl,
191
+ ...options.webhook,
192
+ }),
193
+ )
194
+ }
195
+ await Promise.allSettled(work)
196
+ }