@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
@@ -1,207 +1,27 @@
1
1
  /**
2
- * `index.json` — the source of truth for one repository.
2
+ * Writing `index.json` — the compare-and-swap that publishes a push.
3
3
  *
4
- * It carries the full ref state, so there is no database beside it. A push is
5
- * published by writing a new version of this object under a compare-and-swap;
6
- * until that write lands, the packfile already uploaded to the WAL is present
7
- * but unpublished, and nothing can see it.
4
+ * The Index’s types and its reader are in `shared/wal-index.ts`, because both
5
+ * halves of walgit read the log (docs/adr/0010). Everything here belongs to the
6
+ * process that holds the disk: the next-state helpers, the conditional write
7
+ * that makes a push durable, and `sha256`, which is the one piece of this file
8
+ * that could not move — it hashes through `Bun.CryptoHasher`.
8
9
  *
9
- * See this repository's docs/adr/0007-walgit-object-storage-holds-the-log.md.
10
+ * See this repository’s docs/adr/0007-walgit-object-storage-holds-the-log.md.
10
11
  */
11
12
 
12
13
  import { SIGNERS_REF, ZERO_OID } from '../shared/protocol'
13
- import { indexKey } from './keys'
14
- import type { ObjectStore, PutResult } from './store'
15
-
16
- export type WalEntryKind = 'push' | 'compaction'
17
-
18
- export interface WalEntry {
19
- seq: number
20
- /** Object key of the packfile, e.g. `wal/000000000042-01J….pack`. */
21
- key: string
22
- kind: WalEntryKind
23
- size: number
24
- sha256: string
25
- ts: string
26
- /** Compaction only: entries at or below this seq are no longer needed. */
27
- supersedes_through?: number
28
- }
29
-
30
- /**
31
- * A superseded WAL object, scheduled for deletion but not yet deleted.
32
- *
33
- * The delay is the whole point. A compaction's compare-and-swap advances the
34
- * frontier instantly, but a restore that read `index.json` a moment earlier is
35
- * still downloading the entries that CAS just superseded — and deleting them
36
- * out from under it fails the restore with a missing object, which is ranked
37
- * risk #2 in docs/adr/0007 precisely because nothing shouts. So the CAS records
38
- * an intent to delete, and collection happens later, out of band.
39
- */
40
- export interface Tombstone {
41
- /** The object key. Its sibling `.idx` is collected with it. */
42
- key: string
43
- /** The compaction entry whose pack now contains these objects. */
44
- superseded_by: number
45
- /** ISO instant before which this key must not be deleted. */
46
- collect_after: string
47
- }
48
-
49
- /**
50
- * A repository scheduled for deletion.
51
- *
52
- * Deletion is deferred for the same reason a tombstone is: a clone that read
53
- * this index a moment ago is still downloading the packs it names, and pulling
54
- * them out from under it fails the clone with a missing object. The marker is
55
- * written under compare-and-swap like everything else, so an operator asking
56
- * twice does not shorten the wait — the first request's `collect_after` stands.
57
- */
58
- export interface RepoDeletion {
59
- /** ISO instant the operator asked for the repository to go. */
60
- requested_at: string
61
- /** ISO instant before which nothing under the repo prefix may be deleted. */
62
- collect_after: string
63
- }
64
-
65
- export interface WalIndex {
66
- version: 1
67
- repo_id: string
68
- /** Highest WAL entry applied. Monotonic. */
69
- seq: number
70
- entries: WalEntry[]
71
- /** Full ref state after applying every entry. `refs/heads/main` → oid. */
72
- refs: Record<string, string>
73
- /** Entries below this are not needed to restore. */
74
- compaction_frontier: number
75
- /**
76
- * Superseded keys awaiting collection. Optional because an index written
77
- * before compaction existed does not have the field; absent reads as empty.
78
- */
79
- tombstones?: Tombstone[]
80
- /**
81
- * Set when this repository has been scheduled for deletion. Its presence is
82
- * what makes the second run of `walgit delete` a collection rather than a
83
- * second request.
84
- */
85
- deletion?: RepoDeletion
86
- /**
87
- * Push provenance: ref → who signed the push that moved it to the sha `refs`
88
- * currently holds, and when (docs/adr/0011).
89
- *
90
- * A second map beside `refs` rather than a widening of it, for three reasons
91
- * that each rule out the alternatives. It is not hung off a `WalEntry`: a
92
- * ref-only push appends none, so provenance would be blind to a whole class
93
- * of push. It is not kept on the certificate blob: that lives on the Cache,
94
- * which is wiped on restart. And it is not a richer value inside `refs`,
95
- * because every existing reader of the Index — reconcile, materialize, the
96
- * event handshake — would then have to change to keep reading a sha.
97
- *
98
- * Latest-state per ref, like everything else here: there is no provenance
99
- * history, because the audit trail of *content* is the commit graph and a
100
- * second ledger would be a second thing to keep true.
101
- *
102
- * Optional and absent when empty, so an unsigned deployment's index.json is
103
- * byte-for-byte what it was before this field existed.
104
- */
105
- provenance?: Record<string, Provenance>
106
- /**
107
- * The repository's Signer List, as the push that last moved `refs/walgit/signers`
108
- * resolved it (docs/adr/0012). Absent means unclaimed, which is every
109
- * repository until someone writes one.
110
- *
111
- * Repo-level rather than per-ref, unlike `provenance` above it: the list
112
- * governs the name, not a branch.
113
- *
114
- * The ref is authoritative and this is a derived copy, which is safe rather
115
- * than a second source of truth — it is written by the same compare-and-swap
116
- * that publishes the ref move, derived from bytes in that same push, and a
117
- * restore replays the ref and this field together because both live here. The
118
- * copy exists because the refusal that will read it runs in `pre-receive`,
119
- * which already loads the Index; resolving from the Cache instead would make
120
- * ownership depend on the Cache being materialized, and the Cache is
121
- * disposable by definition (ADR-0007).
122
- *
123
- * It cannot be derived from `provenance`, which is latest-state per ref and
124
- * overwritten by every push — by the time it mattered it would name the most
125
- * recent Signer rather than the founding one.
126
- */
127
- claim?: Claim
128
- }
129
-
130
- /** Who moved a ref, and when it landed. */
131
- export interface Provenance {
132
- /**
133
- * The SSH key fingerprint that signed the push, as `ssh-keygen` spells it:
134
- * `SHA256:` and 43 characters of base64. A key, never a user or an account —
135
- * neither exists here, and naming it either would imply a registry walgit
136
- * deliberately does not have.
137
- */
138
- signer: string
139
- /** ISO instant the push was received. */
140
- ts: string
141
- }
142
-
143
- /** The keys a repository's Signer List names, and when that list landed. */
144
- export interface Claim {
145
- /**
146
- * Fingerprints, in the order the file names them and with duplicates already
147
- * collapsed — the list as `parseKeyList` read it, never the raw file. What
148
- * is stored is the resolved answer, so a reader never re-parses and cannot
149
- * reach a different one.
150
- */
151
- signers: string[]
152
- /**
153
- * The keys the repository lets READ it — its Reader List (docs/adr/0013) —
154
- * as `parseKeyList` read the `readers` file beside `signers` in the same
155
- * commit. Absent when that file is absent, which is every repository until
156
- * someone writes one: presence is the switch, so there is no `private`
157
- * marker and no third state.
158
- *
159
- * `[]` is a value rather than an absence, and the difference is the whole
160
- * capability: an empty Reader List is valid and means the Signer List reads
161
- * this repository and nobody else, while no field at all means anyone does.
162
- *
163
- * Maintained only while the Private seed is set, exactly as the Claim around
164
- * it is maintained only under the Signer List flag — the ref is what is
165
- * authoritative and this is a derived copy (see `applyClaim`).
166
- */
167
- readers?: string[]
168
- /** ISO instant the push that wrote this list was received. */
169
- ts: string
170
- }
171
-
172
- /**
173
- * What one push records about who made it — applied by the same compare-and-swap
174
- * that publishes the push, which is why they travel together rather than as two
175
- * nullable tail arguments nobody can keep straight at a call site.
176
- */
177
- export interface PushRecord {
178
- /** The Signer of this push, or `null` for an anonymous one. */
179
- provenance: Provenance | null
180
- /** The Signer List this push writes, or `null` when it writes none. */
181
- claim: Claim | null
182
- }
183
-
184
- /** A push that records neither. The overwhelming majority of them. */
185
- const NO_RECORD: PushRecord = { provenance: null, claim: null }
186
-
187
- /** A ref change as `reference-transaction` reports it on stdin. */
188
- export interface RefChange {
189
- ref: string
190
- oldOid: string
191
- newOid: string
192
- }
193
-
194
- export function emptyIndex(repoId: string): WalIndex {
195
- return {
196
- version: 1,
197
- repo_id: repoId,
198
- seq: 0,
199
- entries: [],
200
- refs: {},
201
- compaction_frontier: 0,
202
- tombstones: [],
203
- }
204
- }
14
+ import { indexKey } from '../shared/keys'
15
+ import type { ObjectStore, PutResult } from '../shared/store'
16
+ import { loadIndex } from '../shared/wal-index'
17
+ import type {
18
+ Claim,
19
+ Provenance,
20
+ PushRecord,
21
+ RefChange,
22
+ WalEntry,
23
+ WalIndex,
24
+ } from '../shared/wal-index'
205
25
 
206
26
  /**
207
27
  * A WAL object's content address, as `WalEntry.sha256` carries it.
@@ -216,47 +36,8 @@ export function sha256(body: Uint8Array): string {
216
36
  return new Bun.CryptoHasher('sha256').update(body).digest('hex')
217
37
  }
218
38
 
219
- // ── Reading ─────────────────────────────────────────────────────────────────
220
-
221
- export interface LoadedIndex {
222
- index: WalIndex
223
- /** ETag to guard the next write with. `null` when the object does not exist. */
224
- etag: string | null
225
- }
226
-
227
- export async function loadIndex(store: ObjectStore, repoId: string): Promise<LoadedIndex> {
228
- const found = await store.get(indexKey(repoId))
229
- if (!found) return { index: emptyIndex(repoId), etag: null }
230
- return { index: parseIndex(found.body, repoId), etag: found.etag }
231
- }
232
-
233
- /**
234
- * Cheap currency check for the read path: `not-modified` costs one metadata
235
- * round trip, which is what lets a node serve from its local cache without
236
- * trusting it blindly.
237
- */
238
- export async function loadIndexIfChanged(
239
- store: ObjectStore,
240
- repoId: string,
241
- knownEtag: string,
242
- ): Promise<LoadedIndex | 'current'> {
243
- const res = await store.getIfNoneMatch(indexKey(repoId), knownEtag)
244
- if (res.status === 'not-modified') return 'current'
245
- if (res.status === 'absent') return { index: emptyIndex(repoId), etag: null }
246
- return { index: parseIndex(res.body, repoId), etag: res.etag }
247
- }
248
-
249
- function parseIndex(body: Uint8Array, repoId: string): WalIndex {
250
- const parsed = JSON.parse(new TextDecoder().decode(body)) as WalIndex
251
- // Guard the two invariants a corrupted or misrouted object would break. A
252
- // wrong repo_id means the key routing is wrong, which silently serving would
253
- // turn into cross-repository data loss.
254
- if (parsed.version !== 1) throw new Error(`index.json: unsupported version ${parsed.version}`)
255
- if (parsed.repo_id !== repoId) {
256
- throw new Error(`index.json at ${repoId} declares repo_id "${parsed.repo_id}"`)
257
- }
258
- return parsed
259
- }
39
+ /** A push that records neither. The overwhelming majority of them. */
40
+ const NO_RECORD: PushRecord = { provenance: null, claim: null }
260
41
 
261
42
  // ── Writing ─────────────────────────────────────────────────────────────────
262
43
 
@@ -25,6 +25,7 @@
25
25
  * deliberately not in this milestone.
26
26
  */
27
27
 
28
+ import { AwsClient } from 'aws4fetch'
28
29
  import { Container, getContainer } from '@cloudflare/containers'
29
30
 
30
31
  import { capabilitiesFrom, type Capabilities } from '../shared/capabilities'
@@ -45,22 +46,30 @@ import { OG_IMAGE_CACHE_CONTROL, OG_IMAGE_CONTENT_TYPE, wantsOgImage } from '../
45
46
  import { analyticsFrom } from '../shared/analytics'
46
47
  import { operatorFrom } from '../shared/operator'
47
48
  import { renderRobots, wantsRobots } from '../shared/robots'
49
+ import { repoListResponse, wantsRepoList } from '../shared/repo-list'
50
+ import { s3StoreFrom, type ObjectStore } from '../shared/store'
48
51
  import {
49
52
  ANNOUNCE_PATH,
53
+ BASIC_CHALLENGE,
50
54
  COLD_HEADER,
51
55
  EVENTS_PATH,
56
+ BROWSE_PATH,
52
57
  EXPIRE_PATH,
53
58
  INTERNAL_HEADER,
54
59
  INTERNAL_HEADERS,
55
60
  MCP_PATH,
61
+ REJECT_HEADER,
56
62
  SERVED_HEADER,
63
+ wantsBrowse,
57
64
  } from '../shared/protocol'
58
65
  import {
59
66
  classifyOutcome,
60
67
  classifyRequest,
68
+ outcomeOf,
61
69
  toDataPoint,
62
70
  type RequestMetric,
63
71
  } from '../shared/telemetry'
72
+ import { browseResponse } from '../shared/browse'
64
73
  import { BROADCAST_PATH, EVENTS_OBJECT_NAME, WalgitEvents } from './events-do'
65
74
  import { handleMcp } from './mcp'
66
75
  // The card's picture, as bytes in the bundle (wrangler.jsonc's `Data` rule).
@@ -98,6 +107,12 @@ export interface Env {
98
107
  */
99
108
  WALGIT_PUBLIC?: string
100
109
  WALGIT_APPEND_ONLY?: string
110
+ /**
111
+ * The web view (`shared/repo-list.ts`). Read ONLY through `capabilitiesFrom`,
112
+ * like the policy above it — the route below and the two documents that
113
+ * advertise it must not be able to disagree about whether it exists.
114
+ */
115
+ WALGIT_WEB?: string
101
116
  WALGIT_RETENTION_HOURS?: string
102
117
  WALGIT_MAX_PUSH_BYTES?: string
103
118
  WALGIT_MAX_REPO_BYTES?: string
@@ -520,6 +535,197 @@ export default {
520
535
  })
521
536
  }
522
537
 
538
+ // `/repos` — the repository list (`shared/repo-list.ts`), answered at the
539
+ // edge off the log. Placed after the icon routes and before anything that
540
+ // could be a repository, so `/robots.txt` and `/favicon.ico` keep being
541
+ // answered by the branches above rather than by a browse route.
542
+ //
543
+ // Claimed from `caps.web` — the same field the two documents advertise it
544
+ // from — so with the capability off the path falls through to the
545
+ // container, which does not route it, and the client gets the 404 it got
546
+ // before this route existed.
547
+ //
548
+ // The store is built here rather than in `shared/`: the reading is shared
549
+ // (`s3StoreFrom`), but the signer belongs to whichever half has
550
+ // `aws4fetch` to hand. A deployment with the view on and no object store
551
+ // configured is answered 503 below rather than proxied.
552
+ if (caps.web && wantsRepoList(request.method, url.pathname)) {
553
+ const store = edgeStore(env)
554
+ // A deployment that turned the view on without configuring an object
555
+ // store has no log to list. Answered here rather than proxied: falling
556
+ // through would wake the container for a path it does not route, which
557
+ // is the one thing this route exists not to do, and a 404 would say the
558
+ // view does not exist when what is missing is the bucket.
559
+ const answer = !store
560
+ ? {
561
+ status: 503,
562
+ headers: { 'content-type': 'text/plain; charset=utf-8', 'cache-control': 'no-store' },
563
+ body: 'walgit: no object store configured, so there is no log to list\n',
564
+ }
565
+ : await repoListResponse(
566
+ {
567
+ method: request.method,
568
+ accept,
569
+ authorization: request.headers.get('authorization'),
570
+ search: url.search,
571
+ },
572
+ { store, caps, tokens: parseTokens(env.WALGIT_HTTP_TOKENS) },
573
+ )
574
+ const bytes = new TextEncoder().encode(answer.body)
575
+ record(env, ctx, {
576
+ kind: 'list',
577
+ repo: '',
578
+ outcome: answer.status < 400 ? 'ok' : 'reject',
579
+ reject: answer.status < 400 ? '' : answer.status === 401 ? 'unauthorized' : 'unavailable',
580
+ status: answer.status,
581
+ // The container was not involved at all, which is the property this
582
+ // branch exists to create — the same claim the landing page makes.
583
+ served: false,
584
+ cold: false,
585
+ ttfbMs: Date.now() - startedAt,
586
+ totalMs: Date.now() - startedAt,
587
+ bytesServed: request.method === 'HEAD' ? 0 : bytes.byteLength,
588
+ bytesReceived: 0,
589
+ })
590
+ return new Response(request.method === 'HEAD' ? null : bytes, {
591
+ status: answer.status,
592
+ headers: answer.headers,
593
+ })
594
+ }
595
+
596
+ // `/<name>` and `/<name>/tree/…` — the two repository pages
597
+ // (`shared/browse.ts`). Placed after the list and before anything that
598
+ // could be a repository, for the same reason the list is: the icon and
599
+ // document routes above keep answering their own paths rather than being
600
+ // claimed as a repository called `robots.txt`.
601
+ //
602
+ // Unlike the list this cannot be answered off the log: a tree is git
603
+ // objects, and only the Cache holds those. So the edge asks the container's
604
+ // `/_walgit/browse` and renders the answer — one round trip, because
605
+ // `op=tree` carries the ref list with it — and a refusal is passed through
606
+ // verbatim, which is what keeps the browse gate the clone gate and not a
607
+ // second one (docs/adr/0013).
608
+ //
609
+ // Claimed from `caps.web`, the same field the list and the two documents
610
+ // read, so with `WALGIT_WEB` off the path falls through to the container
611
+ // exactly as it did before this route existed.
612
+ const browseRoute = caps.web ? wantsBrowse(request.method, url.pathname) : null
613
+
614
+ // `/<name>/raw/…` — the bytes themselves, rather than a page about them.
615
+ //
616
+ // Proxied rather than rendered, and that is the whole difference: a
617
+ // repository holds whatever was pushed to it, and a renderer that turned
618
+ // those bytes into a string would corrupt every file that is not UTF-8. The
619
+ // container has already chosen the `content-type` from the CONTENT — plain
620
+ // text with `nosniff`, or an octet-stream attachment — because it is the
621
+ // half holding the bytes, and nothing here second-guesses that.
622
+ if (browseRoute && browseRoute.kind === 'raw') {
623
+ const query =
624
+ `?repo=${encodeURIComponent(browseRoute.repo)}&op=raw` +
625
+ (browseRoute.rest === '' ? '' : `&ref=${encodeURIComponent(browseRoute.rest)}`)
626
+ const asked = new Request(`https://walgit.internal${BROWSE_PATH}${query}`, {
627
+ // The client's own credential and nothing else, exactly as the page
628
+ // route below: the edge must not open a door the client could not.
629
+ headers: authorizationOf(request),
630
+ })
631
+ const res = await getContainer(env.WALGIT_CONTAINER).fetch(asked)
632
+ const outcome = outcomeOf({
633
+ status: res.status,
634
+ declared: res.headers.get(REJECT_HEADER) ?? '',
635
+ served: res.headers.get(SERVED_HEADER) !== null,
636
+ })
637
+ record(env, ctx, {
638
+ kind: 'browse',
639
+ repo: browseRoute.repo,
640
+ outcome: outcome.outcome,
641
+ reject: outcome.reject,
642
+ status: res.status,
643
+ served: res.headers.get(SERVED_HEADER) !== null,
644
+ cold: res.headers.get(COLD_HEADER) !== null,
645
+ ttfbMs: Date.now() - startedAt,
646
+ totalMs: Date.now() - startedAt,
647
+ // The body is a stream on its way to the client and must not be read
648
+ // to be weighed: `content-length` is what the container already said.
649
+ bytesServed: request.method === 'HEAD' ? 0 : Number(res.headers.get('content-length') ?? 0),
650
+ bytesReceived: 0,
651
+ })
652
+ // The container's own headers, minus the ones that are walgit's internal
653
+ // bookkeeping rather than protocol.
654
+ const headers = new Headers(res.headers)
655
+ for (const name of INTERNAL_HEADERS) headers.delete(name)
656
+ return new Response(request.method === 'HEAD' ? null : res.body, {
657
+ status: res.status,
658
+ statusText: res.statusText,
659
+ headers,
660
+ })
661
+ }
662
+
663
+ if (browseRoute) {
664
+ const answer = await browseResponse(
665
+ browseRoute,
666
+ { accept, before: url.searchParams.get('before') },
667
+ {
668
+ caps,
669
+ ask: async (query) => {
670
+ const asked = new Request(`https://walgit.internal${BROWSE_PATH}${query}`, {
671
+ // The client's own credential, and nothing else: the container
672
+ // answers this behind the deployment token and then the Read
673
+ // Challenge, and the edge must not be able to open a door the
674
+ // client could not.
675
+ headers: authorizationOf(request),
676
+ })
677
+ const res = await getContainer(env.WALGIT_CONTAINER).fetch(asked)
678
+ return {
679
+ status: res.status,
680
+ text: await res.text(),
681
+ contentType: res.headers.get('content-type') ?? '',
682
+ served: res.headers.get(SERVED_HEADER) !== null,
683
+ reject: res.headers.get(REJECT_HEADER) ?? '',
684
+ // One value, already comma-joined by the runtime: a Private
685
+ // repository is refused with two `WWW-Authenticate` lines, and
686
+ // what arrives here is the joined header. Passed on as it came
687
+ // rather than re-split, because the split is what a parser gets
688
+ // wrong on a nonce containing `=`.
689
+ challenges: [res.headers.get('www-authenticate')].filter(
690
+ (value): value is string => value !== null,
691
+ ),
692
+ }
693
+ },
694
+ },
695
+ )
696
+ const bytes = new TextEncoder().encode(answer.body)
697
+ record(env, ctx, {
698
+ kind: 'browse',
699
+ repo: browseRoute.repo,
700
+ outcome: answer.status < 400 ? 'ok' : 'reject',
701
+ // The container's own words for the refusal, so a browse refused by
702
+ // the Private gate is counted as the `unauthorized` it is rather than
703
+ // re-derived from a status several refusals share — and so a refusal
704
+ // the container never made still reads as `edge`.
705
+ reject:
706
+ answer.status < 400
707
+ ? ''
708
+ : outcomeOf({
709
+ status: answer.upstream.status,
710
+ declared: answer.upstream.reject,
711
+ served: answer.upstream.served,
712
+ }).reject || 'other',
713
+ status: answer.status,
714
+ // The CONTAINER answered the question this page was rendered from, and
715
+ // saying otherwise would make the `edge` refusal signal unreadable.
716
+ served: answer.upstream.served,
717
+ cold: false,
718
+ ttfbMs: Date.now() - startedAt,
719
+ totalMs: Date.now() - startedAt,
720
+ bytesServed: request.method === 'HEAD' ? 0 : bytes.byteLength,
721
+ bytesReceived: 0,
722
+ })
723
+ return new Response(request.method === 'HEAD' ? null : bytes, {
724
+ status: answer.status,
725
+ headers: answer.headers,
726
+ })
727
+ }
728
+
523
729
  // The ref-event stream, answered at the edge for the same reason the
524
730
  // landing page is: a subscription is a socket the container has no reason
525
731
  // to hold, and holding one would keep the single container awake for as
@@ -695,6 +901,19 @@ export default {
695
901
  },
696
902
  }
697
903
 
904
+ /**
905
+ * The credential the CLIENT presented, and nothing else.
906
+ *
907
+ * The container answers the browse behind the deployment token and then the
908
+ * Read Challenge, so the edge must forward what the reader sent rather than
909
+ * anything of its own: a browse that opened a door the client could not open
910
+ * for itself would be the second authorization model ADR-0013 refuses.
911
+ */
912
+ function authorizationOf(request: Request): HeadersInit {
913
+ const authorization = request.headers.get('authorization')
914
+ return authorization ? { authorization } : {}
915
+ }
916
+
698
917
  /**
699
918
  * The two ends of the ref-event stream: a subscriber connecting, and the push
700
919
  * path publishing.
@@ -746,7 +965,7 @@ async function events(request: Request, url: URL, env: Env, caps: Capabilities):
746
965
  if (!allowed) {
747
966
  return new Response('unauthorized\n', {
748
967
  status: 401,
749
- headers: { 'www-authenticate': 'Basic realm="walgit"' },
968
+ headers: { 'www-authenticate': BASIC_CHALLENGE },
750
969
  })
751
970
  }
752
971
  return stub.fetch(request)
@@ -769,6 +988,18 @@ async function sweep(event: ScheduledController, env: Env): Promise<void> {
769
988
  }
770
989
  }
771
990
 
991
+ /**
992
+ * The object store, as the edge reads it — or `null` when this deployment has
993
+ * not configured one.
994
+ *
995
+ * The reading itself is the shared one (`s3StoreFrom`, `shared/store.ts`), the
996
+ * same the container makes; what is here is only the dependency it takes, since
997
+ * the signer belongs to whichever half has `aws4fetch` to hand.
998
+ */
999
+ function edgeStore(env: Env): ObjectStore | null {
1000
+ return s3StoreFrom(env, (credentials) => new AwsClient(credentials))
1001
+ }
1002
+
772
1003
  /**
773
1004
  * The same request with any client-supplied INTERNAL_HEADER removed.
774
1005
  *