@zabaca/zbc 0.21.0 → 0.22.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 (52) hide show
  1. package/package.json +6 -1
  2. package/templates/apps/walgit/CONTEXT.md +25 -0
  3. package/templates/apps/walgit/README.md +152 -4
  4. package/templates/apps/walgit/e2e/harness.ts +2 -2
  5. package/templates/apps/walgit/e2e/scenarios.ts +302 -2
  6. package/templates/apps/walgit/shared/browse.ts +733 -0
  7. package/templates/apps/walgit/shared/capabilities.ts +17 -0
  8. package/templates/apps/walgit/shared/container-env.ts +9 -0
  9. package/templates/apps/walgit/shared/landing.ts +8 -27
  10. package/templates/apps/walgit/shared/llms.ts +25 -0
  11. package/templates/apps/walgit/shared/policy.ts +21 -0
  12. package/templates/apps/walgit/shared/pooled.ts +31 -0
  13. package/templates/apps/walgit/shared/protocol.ts +120 -0
  14. package/templates/apps/walgit/shared/repo-list.ts +478 -0
  15. package/templates/apps/walgit/shared/store.ts +307 -0
  16. package/templates/apps/walgit/shared/telemetry.ts +68 -6
  17. package/templates/apps/walgit/shared/wal-index.ts +249 -0
  18. package/templates/apps/walgit/shared/web.ts +46 -0
  19. package/templates/apps/walgit/src/announce-main.ts +1 -1
  20. package/templates/apps/walgit/src/announce.ts +1 -1
  21. package/templates/apps/walgit/src/append-only.ts +5 -8
  22. package/templates/apps/walgit/src/browse.ts +230 -0
  23. package/templates/apps/walgit/src/cache.ts +4 -4
  24. package/templates/apps/walgit/src/compact.ts +6 -12
  25. package/templates/apps/walgit/src/delete-repo.ts +4 -3
  26. package/templates/apps/walgit/src/expire.ts +3 -3
  27. package/templates/apps/walgit/src/gc.ts +4 -3
  28. package/templates/apps/walgit/src/git.ts +127 -10
  29. package/templates/apps/walgit/src/hook-main.ts +1 -1
  30. package/templates/apps/walgit/src/http.ts +386 -3
  31. package/templates/apps/walgit/src/limits.ts +1 -1
  32. package/templates/apps/walgit/src/materialize.bench.ts +4 -10
  33. package/templates/apps/walgit/src/materialize.ts +11 -4
  34. package/templates/apps/walgit/src/orphans.ts +3 -3
  35. package/templates/apps/walgit/src/pending.ts +1 -1
  36. package/templates/apps/walgit/src/private.ts +1 -1
  37. package/templates/apps/walgit/src/proposals.ts +3 -3
  38. package/templates/apps/walgit/src/push-cert.ts +10 -1
  39. package/templates/apps/walgit/src/push.ts +11 -9
  40. package/templates/apps/walgit/src/reconcile.ts +4 -3
  41. package/templates/apps/walgit/src/server.ts +29 -2
  42. package/templates/apps/walgit/src/signers.ts +9 -3
  43. package/templates/apps/walgit/src/store-env.ts +8 -21
  44. package/templates/apps/walgit/src/store.ts +12 -241
  45. package/templates/apps/walgit/src/sync.ts +2 -2
  46. package/templates/apps/walgit/src/usage.ts +4 -18
  47. package/templates/apps/walgit/src/verify.ts +2 -2
  48. package/templates/apps/walgit/src/wal-index.ts +20 -239
  49. package/templates/apps/walgit/worker/index.ts +232 -1
  50. package/templates/infra/modules/cloudflare-zone/index.ts +83 -9
  51. /package/templates/apps/walgit/{src → shared}/keys.ts +0 -0
  52. /package/templates/apps/walgit/{src → shared}/ulid.ts +0 -0
@@ -0,0 +1,46 @@
1
+ /**
2
+ * What the two web-view pages share: the look, and the one cache rule.
3
+ *
4
+ * `shared/repo-list.ts` and `shared/browse.ts` are one product — a reader moves
5
+ * between them by clicking — and they were each carrying their own copy of the
6
+ * stylesheet and of the "cachable only where a read takes no credential" line.
7
+ * A token change then needed two edits, and the second one is the edit nobody
8
+ * makes: the review of the list itself found four such copies (`shortBytes`,
9
+ * `escapeHtml`, the pool, the store reading) and ended them, so a fifth is not
10
+ * a thing to start.
11
+ *
12
+ * Runtime-neutral like everything here (docs/adr/0010): a stylesheet is a
13
+ * string and a cache header is a string.
14
+ */
15
+
16
+ import type { Capabilities } from './capabilities'
17
+
18
+ /**
19
+ * The web view's stylesheet — one inline block, no build step, no request.
20
+ *
21
+ * Every page that uses it carries a CSP that permits `style-src 'unsafe-inline'`
22
+ * and nothing else, which is what makes an inline block the whole of the
23
+ * styling rather than the first of several resources.
24
+ */
25
+ export const WEB_STYLE = ` :root { color-scheme: light dark; --ink: #14100e; --ground: #ede6de; --muted: #6b635c; --accent: #c56a3e; }
26
+ @media (prefers-color-scheme: dark) { :root { --ink: #ede6de; --ground: #14100e; --muted: #9a9088; } }
27
+ body { margin: 0; padding: 2rem 1.25rem 4rem; background: var(--ground); color: var(--ink);
28
+ font: 15px/1.5 ui-monospace, SFMono-Regular, Menlo, monospace; }
29
+ main { max-width: 52rem; margin: 0 auto; }
30
+ h1 { font-size: 1rem; font-weight: 600; margin: 0 0 1rem; }
31
+ table { width: 100%; border-collapse: collapse; }
32
+ th, td { text-align: left; padding: .35rem .5rem; border-bottom: 1px solid color-mix(in srgb, var(--muted) 30%, transparent); }
33
+ th { font-weight: 600; color: var(--muted); }
34
+ td.f, th.f { text-align: right; white-space: nowrap; color: var(--muted); }
35
+ a { color: var(--accent); }
36
+ .tag { font-size: .8em; color: var(--muted); border: 1px solid var(--muted); border-radius: 3px; padding: 0 .3em; }
37
+ .note { color: var(--muted); }`
38
+
39
+ /**
40
+ * A minute where a read takes no credential, nothing otherwise.
41
+ *
42
+ * The second half is the one that matters: a shared cache must not hold a
43
+ * document that exists only because THIS request presented a token.
44
+ */
45
+ export const webCacheControl = (caps: Capabilities): string =>
46
+ caps.publicAccess ? 'public, max-age=60' : 'private, no-store'
@@ -18,7 +18,7 @@
18
18
  */
19
19
 
20
20
  import { announce, announceConfigFromEnv } from './announce'
21
- import type { RefChange } from './wal-index'
21
+ import type { RefChange } from '../shared/wal-index'
22
22
 
23
23
  const repoId = process.argv[2]
24
24
  const payload = process.argv[3]
@@ -23,7 +23,7 @@
23
23
 
24
24
  import { eventsFromChanges } from '../shared/events'
25
25
  import { ANNOUNCE_PATH, SIGNERS_REF } from '../shared/protocol'
26
- import type { RefChange } from './wal-index'
26
+ import type { RefChange } from '../shared/wal-index'
27
27
 
28
28
  export interface AnnounceConfig {
29
29
  /** The deployment's own public origin — the Worker in front of this container. */
@@ -24,7 +24,7 @@ import * as crypto from 'node:crypto'
24
24
  import { git } from './git'
25
25
  import { flagEnabled } from '../shared/policy'
26
26
  import { ZERO_OID } from '../shared/protocol'
27
- import type { RefChange } from './wal-index'
27
+ import type { RefChange } from '../shared/wal-index'
28
28
 
29
29
  /** The env flag an instance sets to make its repositories append-only. */
30
30
  export function appendOnlyEnabled(env: Record<string, string | undefined> = process.env): boolean {
@@ -56,14 +56,11 @@ export type RefVerdict =
56
56
  export function judgeRefChange(gitDir: string, change: RefChange): RefVerdict {
57
57
  if (change.oldOid === ZERO_OID) return { allowed: true }
58
58
  if (change.newOid === ZERO_OID) return { allowed: false, kind: 'delete', ref: change.ref }
59
- const res = git([
60
- '--git-dir',
59
+ const res = git(['merge-base', '--is-ancestor'], {
61
60
  gitDir,
62
- 'merge-base',
63
- '--is-ancestor',
64
- change.oldOid,
65
- change.newOid,
66
- ])
61
+ inheritObjects: true,
62
+ operands: [change.oldOid, change.newOid],
63
+ })
67
64
  if (res.status === 0) return { allowed: true }
68
65
  return { allowed: false, kind: 'rewrite', ref: change.ref }
69
66
  }
@@ -0,0 +1,230 @@
1
+ /**
2
+ * One level of one directory, read off the Cache.
3
+ *
4
+ * This is the whole reason a browse is answered by the container rather than at
5
+ * the edge like the repository list: the Index carries the full ref state and
6
+ * not a single object, so the only thing that can say what is inside a tree is
7
+ * git, on the disk the log was Materialized onto (docs/adr/0007).
8
+ *
9
+ * ── one level, never recursive ──────────────────────────────────────────────
10
+ *
11
+ * `ls-tree` without `-r`. A recursive read of a large repository is unbounded
12
+ * work on the request path, in the one container that is also serving pushes,
13
+ * for a page that shows one directory. Clicking into a directory is another
14
+ * request, which is what pagination looks like when the tree is the index.
15
+ *
16
+ * ── every argument is data ──────────────────────────────────────────────────
17
+ *
18
+ * The revision goes in `operands` and the directory in `paths`, so git's own
19
+ * `--end-of-options` and `--` fences stand between an untrusted URL and a
20
+ * command line (`src/git.ts`). Nothing here concatenates either into `args`.
21
+ */
22
+
23
+ import { OID, type Commit, type TreeEntry } from '../shared/browse'
24
+ import { git, gitBytes } from './git'
25
+
26
+ /** git's modes, as the four kinds a reader can actually see apart. */
27
+ const SYMLINK_MODE = '120000'
28
+ const GITLINK_MODE = '160000'
29
+
30
+ /**
31
+ * One level of the tree at `rev`:`dir`, or `null` when that is not a directory.
32
+ *
33
+ * `null` for a blob, for a path that is not there and for a revision this Cache
34
+ * does not hold — all three are "there is no directory to show", and git has no
35
+ * empty tree, so empty output is the absence rather than an empty listing.
36
+ *
37
+ * Async because the caller is (`src/http.ts` awaits it beside two store reads),
38
+ * not because git is: `spawnSync` is what every other git call here uses, and a
39
+ * browse is one command.
40
+ */
41
+ export async function listTree(
42
+ gitDir: string,
43
+ rev: string,
44
+ dir: string,
45
+ ): Promise<TreeEntry[] | null> {
46
+ // The trailing slash is what makes this list a directory's CONTENTS rather
47
+ // than print the directory's own entry — git's own spelling, and the
48
+ // difference between a page and a one-row page.
49
+ const paths = dir === '' ? [] : [`${dir}/`]
50
+ const res = git(['ls-tree', '--long', '-z'], { gitDir, operands: [rev], paths })
51
+ if (res.status !== 0) return null
52
+
53
+ const records = res.stdout.split('\0').filter((record) => record !== '')
54
+ if (records.length === 0) return null
55
+
56
+ const entries: TreeEntry[] = []
57
+ for (const record of records) {
58
+ const entry = parseRecord(record, dir)
59
+ if (entry) entries.push(entry)
60
+ }
61
+ // Directories first, then by name — the order a reader expects of a file
62
+ // browser, and one `ls-tree` does not make (it is in tree order, which is
63
+ // git's own byte ordering with a trailing slash on directory names).
64
+ entries.sort((a, b) => {
65
+ if ((a.kind === 'tree') !== (b.kind === 'tree')) return a.kind === 'tree' ? -1 : 1
66
+ return a.name < b.name ? -1 : 1
67
+ })
68
+
69
+ for (const entry of entries) {
70
+ if (entry.kind !== 'symlink') continue
71
+ // One `cat-file` per symlink rather than a batch: a symlink's target is its
72
+ // whole content, symlinks are a handful per directory at most, and batching
73
+ // would put an object-id list on a subprocess's stdin to save a spawn on a
74
+ // page that already spawned one.
75
+ const target = git(['cat-file', 'blob'], { gitDir, operands: [entry.oid] })
76
+ if (target.status === 0) entry.target = target.stdout
77
+ }
78
+
79
+ return entries
80
+ }
81
+
82
+ /**
83
+ * One `--long -z` record: `<mode> <type> <oid> <size>\t<path>`.
84
+ *
85
+ * The size column is `-` for everything git does not weigh (a tree, a gitlink),
86
+ * and the path is FULL — relative to the repository root, not to the directory
87
+ * asked for — so the prefix comes back off here rather than at the renderer.
88
+ */
89
+ function parseRecord(record: string, dir: string): TreeEntry | null {
90
+ const tab = record.indexOf('\t')
91
+ if (tab === -1) return null
92
+ const fields = record.slice(0, tab).split(/\s+/)
93
+ const [mode, type, oid, size] = fields
94
+ if (!mode || !type || !oid) return null
95
+
96
+ const full = record.slice(tab + 1)
97
+ const name = dir === '' ? full : full.slice(dir.length + 1)
98
+ if (name === '' || name.includes('/')) return null
99
+
100
+ const kind =
101
+ mode === SYMLINK_MODE
102
+ ? 'symlink'
103
+ : mode === GITLINK_MODE
104
+ ? 'submodule'
105
+ : type === 'tree'
106
+ ? 'tree'
107
+ : 'blob'
108
+ const bytes = Number(size)
109
+ return {
110
+ name,
111
+ kind,
112
+ oid,
113
+ // Only a blob has one. `-` and anything unparseable read as "git did not
114
+ // say", which is what `null` means here and never zero.
115
+ size: kind === 'blob' && Number.isFinite(bytes) ? bytes : null,
116
+ }
117
+ }
118
+
119
+ /**
120
+ * What git knows about `rev`:`path` without reading it — its object id and its
121
+ * size — or `null` when that is not a blob.
122
+ *
123
+ * `--batch-check` rather than `cat-file -s`: one spawn answers both the TYPE
124
+ * and the size, and the type is what makes a directory a `null` here rather
125
+ * than a file of some size. The size is the whole point of asking separately
126
+ * from `readBlob` — it is what the cap is enforced against before any content
127
+ * reaches this process (`BLOB_MAX_BYTES`).
128
+ *
129
+ * The revision goes in on STDIN rather than as an operand, which is where
130
+ * `--batch-check` reads it, so nothing about the reader's spelling reaches a
131
+ * command line at all.
132
+ */
133
+ export async function statBlob(
134
+ gitDir: string,
135
+ rev: string,
136
+ path: string,
137
+ ): Promise<{ oid: string; size: number } | null> {
138
+ if (path === '') return null
139
+ const res = git(['cat-file', '--batch-check'], { gitDir, input: `${rev}:${path}\n` })
140
+ if (res.status !== 0) return null
141
+ // `<oid> <type> <size>`, or `<what was asked> missing`.
142
+ const [oid, type, size] = res.stdout.trim().split(' ')
143
+ if (!oid || type !== 'blob') return null
144
+ const bytes = Number(size)
145
+ return Number.isFinite(bytes) ? { oid, size: bytes } : null
146
+ }
147
+
148
+ /**
149
+ * The bytes of `rev`:`path`, or `null` when there are none to read.
150
+ *
151
+ * Bytes, never a string: see `gitBytes`. The caller has already asked
152
+ * `statBlob` what it is and how big, so this does no checking of its own —
153
+ * `cat-file blob` on a tree fails, and a failure is `null`.
154
+ *
155
+ * One bound the caller does NOT set: a raw read is uncapped by design, but this
156
+ * buffers, so a blob over `MAX_BUFFER` (`src/git.ts`, 64 MiB) fails here and is
157
+ * answered 404. That is above the 250 MiB a deployment lets a whole repository
158
+ * be and well above anything a page offers a link to; a file past it is one to
159
+ * clone. Streaming it would mean handing a subprocess's stdout to a response,
160
+ * which is the shape `git-backend.ts` has and this module deliberately does
161
+ * not.
162
+ */
163
+ export async function readBlob(
164
+ gitDir: string,
165
+ rev: string,
166
+ path: string,
167
+ ): Promise<Uint8Array | null> {
168
+ if (path === '') return null
169
+ const res = gitBytes(['cat-file', 'blob'], { gitDir, operands: [`${rev}:${path}`] })
170
+ return res.status === 0 ? res.stdout : null
171
+ }
172
+
173
+ /**
174
+ * The field separator inside one `git log` record, and the record separator
175
+ * between them.
176
+ *
177
+ * Unit and record separators rather than anything a human types: a commit
178
+ * subject is arbitrary text a pusher chose, and every printable delimiter is
179
+ * one somebody can put in a subject line and split a record with.
180
+ */
181
+ const FIELD = '\x1f'
182
+ const RECORD = '\x1e'
183
+
184
+ /**
185
+ * One page of history walking back from `before` when the reader is paging, or
186
+ * from `rev` when they are not. `null` when git cannot walk it.
187
+ *
188
+ * `--no-walk` is deliberately NOT used: this is the first-parent-and-all
189
+ * history a reader expects of a branch. `limit` is the caller's bound
190
+ * (`LOG_PAGE`), because the bound is on what one request may do.
191
+ *
192
+ * The cursor is the LAST oid the previous page showed rather than the first one
193
+ * it did not, so a next page is built only from commits the reader has actually
194
+ * been shown. That makes it inclusive to git and exclusive to a reader, which
195
+ * is reconciled here: one extra commit is asked for and the cursor itself is
196
+ * dropped. It is validated as a full oid before it ever arrives
197
+ * (`src/http.ts`), which is belt to this module's braces — like every other
198
+ * revision it goes in as an operand.
199
+ */
200
+ export async function listCommits(
201
+ gitDir: string,
202
+ rev: string,
203
+ before: string | null,
204
+ limit: number,
205
+ ): Promise<Commit[] | null> {
206
+ // Defence in depth on the one argument that comes from a query parameter:
207
+ // the handler has refused anything but a full oid already, and this refuses
208
+ // it again rather than trusting that it did.
209
+ if (before !== null && !OID.test(before)) return null
210
+ const res = git(
211
+ [
212
+ 'log',
213
+ `--max-count=${before === null ? limit : limit + 1}`,
214
+ `--format=%H${FIELD}%an <%ae>${FIELD}%aI${FIELD}%s${RECORD}`,
215
+ ],
216
+ { gitDir, operands: [before ?? rev] },
217
+ )
218
+ if (res.status !== 0) return null
219
+ const commits: Commit[] = []
220
+ for (const record of res.stdout.split(RECORD)) {
221
+ const line = record.trim()
222
+ if (line === '') continue
223
+ const [oid, author, date, subject] = line.split(FIELD)
224
+ if (!oid || author === undefined || date === undefined) continue
225
+ // The cursor commit itself: already shown on the page that named it.
226
+ if (oid === before) continue
227
+ commits.push({ oid, author, date, subject: subject ?? '' })
228
+ }
229
+ return commits
230
+ }
@@ -49,7 +49,7 @@ import type { ResolvedRepo } from './repo'
49
49
  */
50
50
  function ensureConfig(gitDir: string, key: string, value: string): void {
51
51
  if (readConfig(gitDir, key) === value) return
52
- const res = git(['--git-dir', gitDir, 'config', key, value])
52
+ const res = git(['config'], { gitDir, operands: [key, value] })
53
53
  if (res.status === 0) return
54
54
  if (readConfig(gitDir, key) === value) return
55
55
  throw new Error(`git config ${key} ${value} failed: ${res.stderr.trim()}`)
@@ -58,12 +58,12 @@ function ensureConfig(gitDir: string, key: string, value: string): void {
58
58
  /** Remove a config key, if it is set. Losing the lock race is not fatal here. */
59
59
  function clearConfig(gitDir: string, key: string): void {
60
60
  if (readConfig(gitDir, key) === undefined) return
61
- git(['--git-dir', gitDir, 'config', '--unset', key])
61
+ git(['config', '--unset'], { gitDir, operands: [key] })
62
62
  }
63
63
 
64
64
  /** The configured value, or undefined when the key is unset. */
65
65
  function readConfig(gitDir: string, key: string): string | undefined {
66
- const res = git(['--git-dir', gitDir, 'config', '--get', key])
66
+ const res = git(['config', '--get'], { gitDir, operands: [key] })
67
67
  return res.status === 0 ? res.stdout.trim() : undefined
68
68
  }
69
69
 
@@ -85,7 +85,7 @@ export function ensureBareRepo(repo: ResolvedRepo): ResolvedRepo {
85
85
  // `main` as the default HEAD, because HEAD on a bare repo is what a clone
86
86
  // checks out: created as `master` and pushed to as `main`, a clone succeeds
87
87
  // and leaves an empty working tree, which reads as data loss.
88
- gitOrThrow(['init', '--bare', '--quiet', '--initial-branch=main', repo.dir])
88
+ gitOrThrow(['init', '--bare', '--quiet', '--initial-branch=main'], { operands: [repo.dir] })
89
89
  }
90
90
  // Re-applied on every call, not just at creation: `receive.unpackLimit=0`
91
91
  // is what makes a small push arrive as a packfile rather than exploding into
@@ -31,19 +31,13 @@ import * as fs from 'node:fs'
31
31
  import * as path from 'node:path'
32
32
 
33
33
  import { gitOrThrow } from './git'
34
- import { leaseKey, walKey } from './keys'
34
+ import { leaseKey, walKey } from '../shared/keys'
35
35
  import { materialize, packBasename, packDirOf } from './materialize'
36
36
  import type { ResolvedRepo } from './repo'
37
- import type { ObjectStore } from './store'
38
- import { ulid } from './ulid'
39
- import {
40
- loadIndex,
41
- sha256,
42
- updateIndex,
43
- type Tombstone,
44
- type WalEntry,
45
- type WalIndex,
46
- } from './wal-index'
37
+ import type { ObjectStore } from '../shared/store'
38
+ import { ulid } from '../shared/ulid'
39
+ import { loadIndex, type Tombstone, type WalEntry, type WalIndex } from '../shared/wal-index'
40
+ import { sha256, updateIndex } from './wal-index'
47
41
 
48
42
  /**
49
43
  * How many un-superseded entries a repository may accumulate before it is
@@ -236,7 +230,7 @@ export async function compact(
236
230
  const supersedesThrough = index.seq
237
231
 
238
232
  const packDir = packDirOf(repo.dir)
239
- gitOrThrow(['--git-dir', repo.dir, 'repack', '-adfq'])
233
+ gitOrThrow(['repack', '-adfq'], { gitDir: repo.dir })
240
234
 
241
235
  const onDisk = fs.readdirSync(packDir)
242
236
  // A cruft pack is not a second copy of the repository — it is git's
@@ -27,9 +27,10 @@
27
27
 
28
28
  import * as fs from 'node:fs'
29
29
 
30
- import type { ObjectStore } from './store'
31
- import { indexKey, repoPrefix } from './keys'
32
- import { loadIndex, updateIndex, type WalIndex } from './wal-index'
30
+ import type { ObjectStore } from '../shared/store'
31
+ import { indexKey, repoPrefix } from '../shared/keys'
32
+ import { loadIndex, type WalIndex } from '../shared/wal-index'
33
+ import { updateIndex } from './wal-index'
33
34
 
34
35
  /**
35
36
  * How long a repository sits tombstoned before its objects may be deleted.
@@ -26,9 +26,9 @@
26
26
  */
27
27
 
28
28
  import { deleteRepo, type DeleteResult } from './delete-repo'
29
- import type { ObjectStore } from './store'
30
- import { listRepoIds } from './keys'
31
- import { loadIndex, type WalIndex } from './wal-index'
29
+ import type { ObjectStore } from '../shared/store'
30
+ import { listRepoIds } from '../shared/keys'
31
+ import { loadIndex, type WalIndex } from '../shared/wal-index'
32
32
 
33
33
  /**
34
34
  * Expiry is off unless a window is configured. Absent means "this instance
@@ -21,10 +21,11 @@
21
21
  */
22
22
 
23
23
  import { configuredGraceMs } from './compact'
24
- import { siblingIdx, walKeyUploadedAt } from './keys'
24
+ import { siblingIdx, walKeyUploadedAt } from '../shared/keys'
25
25
  import { findOrphans } from './orphans'
26
- import type { ObjectStore } from './store'
27
- import { loadIndex, updateIndex, type WalIndex } from './wal-index'
26
+ import type { ObjectStore } from '../shared/store'
27
+ import { loadIndex, type WalIndex } from '../shared/wal-index'
28
+ import { updateIndex } from './wal-index'
28
29
 
29
30
  export interface GcResult {
30
31
  /** Superseded keys whose grace period elapsed, now deleted. */
@@ -13,14 +13,31 @@
13
13
  * with inherited stdio, and `git-backend.ts` streams `git http-backend` as CGI.
14
14
  * Both speak the pack protocol on their own stdio and must never be buffered.
15
15
  *
16
- * One thing belongs here and is deliberately NOT done yet, because this module
17
- * arrived as a pure extraction: **ambient configuration is still inherited.** A
18
- * global or system git config that sets `core.hooksPath` redirects
19
- * `git-receive-pack` away from `$GIT_DIR/hooks`, so walgit's `pre-receive` and
20
- * `reference-transaction` never run and a push is acknowledged with nothing
21
- * written to the log — the one outcome docs/adr/0007 exists to prevent.
22
- * `e2e/harness.ts` already strips it (`GIT_CONFIG_GLOBAL=/dev/null`) for
23
- * exactly this class of reason. This module is where that fix becomes one line.
16
+ * **Hygiene is this module's job, not the caller's.** Two kinds of input reach
17
+ * git here, and neither is safe left as it arrives:
18
+ *
19
+ * - **Arguments.** A ref, an oid or a path is DATA, and git reads an argument
20
+ * beginning with `-` as an option wherever one is allowed. So a caller
21
+ * never concatenates them into `args`: revisions go in `operands` (placed
22
+ * after git's own `--end-of-options` fence) and paths go in `paths` (after
23
+ * `--`). `args` is the subcommand and its flags, which this repository
24
+ * writes and nobody else supplies.
25
+ * - **The environment.** Every inherited `GIT_*` variable is dropped at
26
+ * spawn. A global or system git config that sets `core.hooksPath`
27
+ * redirects `git-receive-pack` away from `$GIT_DIR/hooks`, so walgit's
28
+ * `pre-receive` and `reference-transaction` never run and a push is
29
+ * acknowledged with nothing written to the log — the one outcome
30
+ * docs/adr/0007 exists to prevent. Dropping `GIT_CONFIG_GLOBAL` would
31
+ * RE-OPEN that door (`e2e/harness.ts` sets it to `/dev/null` precisely to
32
+ * close it), so the strip is paired with pinning both config paths at
33
+ * `/dev/null` here. A caller that needs a variable says so in `env`.
34
+ *
35
+ * It covers the commands walgit runs and READS. It deliberately does not cover
36
+ * the two places git is not a subprocess to be read but a transport to be
37
+ * handed the socket: `git-backend.ts` runs `git http-backend` with inherited
38
+ * stdio, and streams it as CGI. Both speak the pack protocol on their own
39
+ * stdio and must never be buffered — and both are given an explicit
40
+ * environment of their own for the same reason this one is.
24
41
  */
25
42
 
26
43
  import { spawnSync } from 'node:child_process'
@@ -35,6 +52,81 @@ export interface GitResult {
35
52
  export interface GitOptions {
36
53
  /** Fed to the command on stdin, e.g. the oid list `cat-file` batches over. */
37
54
  input?: string
55
+ /**
56
+ * The repository, named rather than discovered. git's own discovery walks up
57
+ * from the working directory and would find whichever repository the process
58
+ * happens to sit in — which for a hook or a CLI command is not necessarily
59
+ * the one being operated on.
60
+ */
61
+ gitDir?: string
62
+ /**
63
+ * Revisions, oids and other non-path operands. Placed after
64
+ * `--end-of-options`, so `-p` or `--output=x` arriving as a ref name is read
65
+ * as the ref it is.
66
+ */
67
+ operands?: readonly string[]
68
+ /** Pathspecs. Placed after `--`, which is git's fence for exactly this. */
69
+ paths?: readonly string[]
70
+ /**
71
+ * Variables to set on the child on top of the stripped environment. An
72
+ * `undefined` value removes one. This is the only way a `GIT_*` variable
73
+ * reaches git from here.
74
+ */
75
+ env?: Record<string, string | undefined>
76
+ /**
77
+ * Keep the three variables git itself sets so a hook can see the objects a
78
+ * push is offering (`GIT_OBJECT_DIRECTORY`, `GIT_ALTERNATE_OBJECT_DIRECTORIES`,
79
+ * `GIT_QUARANTINE_PATH`).
80
+ *
81
+ * Only `pre-receive`'s verdicts need it — they ask git about commits that are
82
+ * still in the quarantine and not yet in the repository — and it is opt-in
83
+ * rather than inherited because for every other caller the variable points at
84
+ * an object store that has nothing to do with the command being run.
85
+ */
86
+ inheritObjects?: boolean
87
+ }
88
+
89
+ /** What git sets for a hook so the pushed objects are readable. */
90
+ const QUARANTINE_VARS = [
91
+ 'GIT_OBJECT_DIRECTORY',
92
+ 'GIT_ALTERNATE_OBJECT_DIRECTORIES',
93
+ 'GIT_QUARANTINE_PATH',
94
+ ] as const
95
+
96
+ /**
97
+ * The child's environment: the parent's, minus every `GIT_*`, with ambient
98
+ * config pinned out of the way and the caller's additions last.
99
+ */
100
+ function childEnv(opts: GitOptions): NodeJS.ProcessEnv {
101
+ const env: NodeJS.ProcessEnv = {}
102
+ for (const [key, value] of Object.entries(process.env)) {
103
+ if (!key.startsWith('GIT_')) env[key] = value
104
+ }
105
+ env.GIT_CONFIG_GLOBAL = '/dev/null'
106
+ env.GIT_CONFIG_SYSTEM = '/dev/null'
107
+ if (opts.inheritObjects) {
108
+ for (const name of QUARANTINE_VARS) {
109
+ const value = process.env[name]
110
+ if (value !== undefined) env[name] = value
111
+ }
112
+ }
113
+ for (const [key, value] of Object.entries(opts.env ?? {})) {
114
+ if (value === undefined) delete env[key]
115
+ else env[key] = value
116
+ }
117
+ return env
118
+ }
119
+
120
+ /** The full argument vector, with git's two fences where they belong. */
121
+ function argv(args: readonly string[], opts: GitOptions): string[] {
122
+ const operands = opts.operands ?? []
123
+ const paths = opts.paths ?? []
124
+ return [
125
+ ...(opts.gitDir ? ['--git-dir', opts.gitDir] : []),
126
+ ...args,
127
+ ...(operands.length > 0 ? ['--end-of-options', ...operands] : []),
128
+ ...(paths.length > 0 ? ['--', ...paths] : []),
129
+ ]
38
130
  }
39
131
 
40
132
  /**
@@ -56,10 +148,11 @@ export interface GitOptions {
56
148
  const MAX_BUFFER = 64 * 1024 * 1024
57
149
 
58
150
  export function git(args: readonly string[], opts: GitOptions = {}): GitResult {
59
- const res = spawnSync('git', [...args], {
151
+ const res = spawnSync('git', argv(args, opts), {
60
152
  encoding: 'utf8',
61
153
  input: opts.input,
62
154
  maxBuffer: MAX_BUFFER,
155
+ env: childEnv(opts),
63
156
  })
64
157
  return {
65
158
  status: res.status ?? 1,
@@ -68,11 +161,35 @@ export function git(args: readonly string[], opts: GitOptions = {}): GitResult {
68
161
  }
69
162
  }
70
163
 
164
+ /**
165
+ * git, where the output is BYTES rather than text.
166
+ *
167
+ * One caller: reading a blob (`src/browse.ts`). A repository holds whatever was
168
+ * pushed to it, and decoding a PNG as UTF-8 replaces every byte git actually
169
+ * stored with U+FFFD — which is both the wrong file to hand back and a NUL
170
+ * sniff that says "text". `stderr` stays a string, because a diagnostic is one.
171
+ */
172
+ export function gitBytes(
173
+ args: readonly string[],
174
+ opts: GitOptions = {},
175
+ ): { status: number; stdout: Uint8Array; stderr: string } {
176
+ const res = spawnSync('git', argv(args, opts), {
177
+ input: opts.input,
178
+ maxBuffer: MAX_BUFFER,
179
+ env: childEnv(opts),
180
+ })
181
+ return {
182
+ status: res.status ?? 1,
183
+ stdout: res.stdout ?? new Uint8Array(),
184
+ stderr: res.stderr?.toString('utf8') ?? '',
185
+ }
186
+ }
187
+
71
188
  /** git, where a non-zero exit is a bug rather than an answer. */
72
189
  export function gitOrThrow(args: readonly string[], opts: GitOptions = {}): GitResult {
73
190
  const res = git(args, opts)
74
191
  if (res.status !== 0) {
75
- throw new Error(`git ${args.join(' ')} failed: ${res.stderr.trim()}`)
192
+ throw new Error(`git ${argv(args, opts).join(' ')} failed: ${res.stderr.trim()}`)
76
193
  }
77
194
  return res
78
195
  }
@@ -48,7 +48,7 @@ import {
48
48
  signerListsEnabled,
49
49
  } from './signers'
50
50
  import { requireStore, storeFromEnv } from './store-env'
51
- import { loadIndex, type LoadedIndex, type RefChange } from './wal-index'
51
+ import { loadIndex, type LoadedIndex, type RefChange } from '../shared/wal-index'
52
52
 
53
53
  const hook = process.argv[2]
54
54
  const phase = process.argv[3]