@zabaca/zbc 0.25.0 → 0.26.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.
- package/CHANGELOG.md +17 -0
- package/package.json +1 -1
- package/src/commands/init.ts +105 -10
- package/src/commands/update.ts +33 -6
- package/src/utils/detect-mode.ts +1 -1
- package/src/utils/host-workspaces.ts +57 -0
- package/src/utils/subtree.ts +54 -15
- package/src/utils/vendor-audit.ts +12 -8
- package/src/utils/vendor-stamp.ts +10 -0
- package/src/utils/vendored-app.ts +3 -0
- package/templates/apps/walgit/CONTEXT.md +45 -4
- package/templates/apps/walgit/README.md +394 -11
- package/templates/apps/walgit/shared/browse.ts +61 -0
- package/templates/apps/walgit/shared/capabilities.ts +26 -0
- package/templates/apps/walgit/shared/container-env.ts +12 -0
- package/templates/apps/walgit/shared/container-lifecycle.ts +1 -1
- package/templates/apps/walgit/shared/credentials.ts +4 -0
- package/templates/apps/walgit/shared/events.ts +35 -1
- package/templates/apps/walgit/shared/instructions.ts +4 -1
- package/templates/apps/walgit/shared/landing.ts +2 -1
- package/templates/apps/walgit/shared/llms.ts +73 -5
- package/templates/apps/walgit/shared/mcp.ts +19 -3
- package/templates/apps/walgit/shared/protocol.ts +40 -3
- package/templates/apps/walgit/shared/repo-list.ts +46 -6
- package/templates/apps/walgit/shared/scoped-token.ts +500 -0
- package/templates/apps/walgit/shared/token-revocation.ts +134 -0
- package/templates/apps/walgit/shared/wal-index.ts +19 -0
- package/templates/apps/walgit/shared/webhook.ts +281 -0
- package/templates/apps/walgit/src/admin.ts +510 -0
- package/templates/apps/walgit/src/announce-main.ts +17 -9
- package/templates/apps/walgit/src/announce.ts +86 -0
- package/templates/apps/walgit/src/browse.ts +255 -2
- package/templates/apps/walgit/src/cli.ts +140 -0
- package/templates/apps/walgit/src/expire.ts +5 -0
- package/templates/apps/walgit/src/git.ts +103 -0
- package/templates/apps/walgit/src/hook-main.ts +6 -3
- package/templates/apps/walgit/src/http.ts +563 -3
- package/templates/apps/walgit/src/limits.ts +3 -0
- package/templates/apps/walgit/src/merge.ts +525 -0
- package/templates/apps/walgit/src/rate-limit.ts +51 -14
- package/templates/apps/walgit/src/server.ts +65 -1
- package/templates/apps/walgit/worker/events-do.ts +218 -3
- package/templates/apps/walgit/worker/index.ts +134 -9
- package/templates/apps/walgit/worker/mcp.ts +17 -2
|
@@ -0,0 +1,500 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Scoped tokens: a credential for one repository, minted by somebody else
|
|
3
|
+
* (docs/adr/0021).
|
|
4
|
+
*
|
|
5
|
+
* An issuer holding an Ed25519 private key signs a compact JWT that grants
|
|
6
|
+
* `read` or `write` on exactly one repository name, for a short time. walgit
|
|
7
|
+
* holds only the public half (`WALGIT_TOKEN_PUBLIC_KEYS`), so a walgit that is
|
|
8
|
+
* compromised can refuse and accept tokens but can never make one.
|
|
9
|
+
*
|
|
10
|
+
* Runtime-neutral, like `credentials.ts` beside it, because both halves ask the
|
|
11
|
+
* same question: the edge Worker verifies BEFORE it wakes the container, so a
|
|
12
|
+
* bad credential never costs a cold start, and the container verifies again on
|
|
13
|
+
* what reaches it, so a request that did not come through the edge is held to
|
|
14
|
+
* the same rule. WebCrypto's Ed25519 is a standard global in bun and in the
|
|
15
|
+
* Workers runtime alike; nothing here touches a buffer, a socket or a disk.
|
|
16
|
+
*
|
|
17
|
+
* ── what counts as a scoped token ───────────────────────────────────────────
|
|
18
|
+
*
|
|
19
|
+
* A credential is judged here only when ALL of these hold: the deployment set
|
|
20
|
+
* `WALGIT_TOKEN_PUBLIC_KEYS`, the credential is JWT-shaped (three base64url
|
|
21
|
+
* segments), and it is not one of the deployment's own secrets (the admin
|
|
22
|
+
* tokens, the announce secret). Everything else takes exactly the path it took
|
|
23
|
+
* before this file existed — which is what "off unless set" means, and why an
|
|
24
|
+
* admin token that happens to contain two dots keeps its full reach.
|
|
25
|
+
*/
|
|
26
|
+
|
|
27
|
+
import { constantTimeEquals, presentedCredential } from './credentials'
|
|
28
|
+
import { seedValue } from './policy'
|
|
29
|
+
import {
|
|
30
|
+
BASIC_CHALLENGE,
|
|
31
|
+
BROWSE_PATH,
|
|
32
|
+
MERGE_PATH,
|
|
33
|
+
EVENTS_PATH,
|
|
34
|
+
MCP_PATH,
|
|
35
|
+
PROPOSALS_HTTP,
|
|
36
|
+
PROVENANCE_PATH,
|
|
37
|
+
REPO_ID,
|
|
38
|
+
REPOS_PATH,
|
|
39
|
+
SMART_HTTP,
|
|
40
|
+
wantsBrowse,
|
|
41
|
+
} from './protocol'
|
|
42
|
+
|
|
43
|
+
/** The only `alg` accepted. `none`, `HS256` and everything else are refused. */
|
|
44
|
+
export const SCOPED_TOKEN_ALG = 'EdDSA'
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* How far apart the issuer's clock and this one may be, in seconds.
|
|
48
|
+
*
|
|
49
|
+
* Applied both ways: a token is still honoured this long after `exp`, and one
|
|
50
|
+
* whose `iat` is up to this far in the future is not yet refused for it.
|
|
51
|
+
*/
|
|
52
|
+
export const SCOPED_TOKEN_SKEW_SECONDS = 60
|
|
53
|
+
|
|
54
|
+
export type ScopedMode = 'read' | 'write'
|
|
55
|
+
|
|
56
|
+
/** What a verified token says. */
|
|
57
|
+
export interface ScopedClaims {
|
|
58
|
+
/** The one repository it is for — an exact name, never a prefix or a pattern. */
|
|
59
|
+
repo: string
|
|
60
|
+
mode: ScopedMode
|
|
61
|
+
/** Seconds since the epoch. */
|
|
62
|
+
exp: number
|
|
63
|
+
/** Seconds since the epoch. Kept so a later revocation can cut on it. */
|
|
64
|
+
iat: number
|
|
65
|
+
/** The tenant, when the issuer named one. */
|
|
66
|
+
sub?: string
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export type VerifyResult = { ok: true; claims: ScopedClaims } | { ok: false; reason: string }
|
|
70
|
+
|
|
71
|
+
/** Three base64url segments. The signature segment of a JWT is never empty here. */
|
|
72
|
+
const JWT_SHAPE = /^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/
|
|
73
|
+
|
|
74
|
+
/** An Ed25519 public key, raw, is exactly this long. So is half a signature. */
|
|
75
|
+
const ED25519_KEY_BYTES = 32
|
|
76
|
+
const ED25519_SIGNATURE_BYTES = 64
|
|
77
|
+
|
|
78
|
+
/** Is this deployment configured to accept scoped tokens at all? */
|
|
79
|
+
export function scopedTokensEnabled(raw: string | undefined): boolean {
|
|
80
|
+
return seedValue(raw) !== null
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** Could this credential be a scoped token? Shape only — nothing is verified. */
|
|
84
|
+
export function looksLikeScopedToken(credential: string): boolean {
|
|
85
|
+
return JWT_SHAPE.test(credential)
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* Decode base64url (no padding) to bytes, or `null`.
|
|
90
|
+
*
|
|
91
|
+
* Strict about the alphabet because the shape check upstream already is, and
|
|
92
|
+
* about length because `atob` accepts padding a base64url string never has.
|
|
93
|
+
*/
|
|
94
|
+
export function base64UrlDecode(text: string): Uint8Array<ArrayBuffer> | null {
|
|
95
|
+
if (!/^[A-Za-z0-9_-]*$/.test(text) || text.length % 4 === 1) return null
|
|
96
|
+
const b64 = text.replace(/-/g, '+').replace(/_/g, '/')
|
|
97
|
+
let binary: string
|
|
98
|
+
try {
|
|
99
|
+
binary = atob(b64 + '='.repeat((4 - (b64.length % 4)) % 4))
|
|
100
|
+
} catch {
|
|
101
|
+
return null
|
|
102
|
+
}
|
|
103
|
+
const bytes = new Uint8Array(binary.length)
|
|
104
|
+
for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i)
|
|
105
|
+
// Canonical only. `atob` ignores the spare low bits of the last character,
|
|
106
|
+
// so without this sixteen spellings of one signature would all verify — and
|
|
107
|
+
// anything later keyed on the token string (a cache, a denylist) could be
|
|
108
|
+
// stepped around by re-spelling it.
|
|
109
|
+
return base64UrlEncode(bytes) === text ? bytes : null
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
export function base64UrlEncode(bytes: Uint8Array): string {
|
|
113
|
+
let binary = ''
|
|
114
|
+
for (const byte of bytes) binary += String.fromCharCode(byte)
|
|
115
|
+
return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* The configured public keys, raw.
|
|
120
|
+
*
|
|
121
|
+
* Comma-separated, like `WALGIT_HTTP_TOKENS`, so a key can be rotated without a
|
|
122
|
+
* window where neither the old nor the new one verifies. Each entry is the
|
|
123
|
+
* key's 32 raw bytes in base64url — the `x` of its JWK, and what `walgit token
|
|
124
|
+
* keygen` prints. A malformed entry THROWS rather than being dropped: a key the
|
|
125
|
+
* operator meant to configure and walgit silently ignored is a rotation that
|
|
126
|
+
* did not happen.
|
|
127
|
+
*/
|
|
128
|
+
export function parseTokenPublicKeys(raw: string | undefined): Uint8Array<ArrayBuffer>[] {
|
|
129
|
+
const entries = (raw ?? '')
|
|
130
|
+
.split(',')
|
|
131
|
+
.map((entry) => entry.trim())
|
|
132
|
+
.filter(Boolean)
|
|
133
|
+
return entries.map((entry, i) => {
|
|
134
|
+
const bytes = base64UrlDecode(entry)
|
|
135
|
+
if (!bytes || bytes.length !== ED25519_KEY_BYTES) {
|
|
136
|
+
throw new Error(
|
|
137
|
+
`walgit: WALGIT_TOKEN_PUBLIC_KEYS entry ${i + 1} is not an Ed25519 public key (expected 32 raw bytes, base64url)`,
|
|
138
|
+
)
|
|
139
|
+
}
|
|
140
|
+
return bytes
|
|
141
|
+
})
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** A configuration problem, stated once, or `null`. For boot-time checks. */
|
|
145
|
+
export function tokenPublicKeysConfigError(raw: string | undefined): string | null {
|
|
146
|
+
try {
|
|
147
|
+
parseTokenPublicKeys(raw)
|
|
148
|
+
return null
|
|
149
|
+
} catch (error) {
|
|
150
|
+
return (error as Error).message
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/**
|
|
155
|
+
* Imported keys, per configured value. The environment is fixed for an isolate
|
|
156
|
+
* or a process's life, so this is read once rather than per request.
|
|
157
|
+
*/
|
|
158
|
+
const imported = new Map<string, Promise<CryptoKey[]>>()
|
|
159
|
+
|
|
160
|
+
function importedKeys(raw: string): Promise<CryptoKey[]> {
|
|
161
|
+
let keys = imported.get(raw)
|
|
162
|
+
if (!keys) {
|
|
163
|
+
keys = Promise.all(
|
|
164
|
+
parseTokenPublicKeys(raw).map((bytes) =>
|
|
165
|
+
crypto.subtle.importKey('raw', bytes, { name: 'Ed25519' }, false, ['verify']),
|
|
166
|
+
),
|
|
167
|
+
)
|
|
168
|
+
// A failed import is not cached: the next request reports it again rather
|
|
169
|
+
// than inheriting a rejected promise forever.
|
|
170
|
+
keys.catch(() => imported.delete(raw))
|
|
171
|
+
imported.set(raw, keys)
|
|
172
|
+
}
|
|
173
|
+
return keys
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
function jsonSegment(segment: string): Record<string, unknown> | null {
|
|
177
|
+
const bytes = base64UrlDecode(segment)
|
|
178
|
+
if (!bytes) return null
|
|
179
|
+
try {
|
|
180
|
+
const value = JSON.parse(
|
|
181
|
+
new TextDecoder('utf-8', { fatal: true, ignoreBOM: false }).decode(bytes),
|
|
182
|
+
) as unknown
|
|
183
|
+
return value !== null && typeof value === 'object' && !Array.isArray(value)
|
|
184
|
+
? (value as Record<string, unknown>)
|
|
185
|
+
: null
|
|
186
|
+
} catch {
|
|
187
|
+
return null
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
const isTime = (value: unknown): value is number =>
|
|
192
|
+
typeof value === 'number' && Number.isFinite(value)
|
|
193
|
+
|
|
194
|
+
/**
|
|
195
|
+
* Verify one token against the configured keys.
|
|
196
|
+
*
|
|
197
|
+
* The signature is checked BEFORE any claim, so a forged token is told it is
|
|
198
|
+
* forged and never learns whether its claims would have passed. Every refusal
|
|
199
|
+
* is a reason a client can act on; none of them is a 500.
|
|
200
|
+
*/
|
|
201
|
+
export async function verifyScopedToken(
|
|
202
|
+
token: string,
|
|
203
|
+
keysRaw: string,
|
|
204
|
+
nowMs: number = Date.now(),
|
|
205
|
+
): Promise<VerifyResult> {
|
|
206
|
+
if (!looksLikeScopedToken(token)) return { ok: false, reason: 'malformed token' }
|
|
207
|
+
const [headerPart, payloadPart, signaturePart] = token.split('.') as [string, string, string]
|
|
208
|
+
|
|
209
|
+
const header = jsonSegment(headerPart)
|
|
210
|
+
if (!header) return { ok: false, reason: 'malformed token header' }
|
|
211
|
+
// Exactly one algorithm. A verifier that let the header choose would accept
|
|
212
|
+
// `none`, or an HMAC keyed with the public key — the two classic confusions.
|
|
213
|
+
if (header.alg !== SCOPED_TOKEN_ALG) {
|
|
214
|
+
return { ok: false, reason: `token alg must be ${SCOPED_TOKEN_ALG}` }
|
|
215
|
+
}
|
|
216
|
+
// An extension this verifier does not implement must not be silently
|
|
217
|
+
// ignored (RFC 7515 §4.1.11).
|
|
218
|
+
if (header.crit !== undefined) return { ok: false, reason: 'token header names crit extensions' }
|
|
219
|
+
|
|
220
|
+
const signature = base64UrlDecode(signaturePart)
|
|
221
|
+
if (!signature || signature.length !== ED25519_SIGNATURE_BYTES) {
|
|
222
|
+
return { ok: false, reason: 'malformed token signature' }
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
const keys = await importedKeys(keysRaw)
|
|
226
|
+
const signed = new TextEncoder().encode(`${headerPart}.${payloadPart}`)
|
|
227
|
+
let verified = false
|
|
228
|
+
for (const key of keys) {
|
|
229
|
+
if (await crypto.subtle.verify({ name: 'Ed25519' }, key, signature, signed)) {
|
|
230
|
+
verified = true
|
|
231
|
+
break
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
if (!verified) return { ok: false, reason: 'token signature does not verify' }
|
|
235
|
+
|
|
236
|
+
const payload = jsonSegment(payloadPart)
|
|
237
|
+
if (!payload) return { ok: false, reason: 'malformed token payload' }
|
|
238
|
+
const { repo, mode, exp, iat, nbf, sub } = payload
|
|
239
|
+
// The canonical id only: `.git` is a suffix a client's URL chooses, not part
|
|
240
|
+
// of a name (`src/repo.ts`), so a claim spelled with one would be a second
|
|
241
|
+
// spelling of a different repository.
|
|
242
|
+
if (typeof repo !== 'string' || !REPO_ID.test(repo) || repo.endsWith('.git')) {
|
|
243
|
+
return { ok: false, reason: 'token repo claim is missing or not a repository name' }
|
|
244
|
+
}
|
|
245
|
+
if (mode !== 'read' && mode !== 'write') {
|
|
246
|
+
return { ok: false, reason: 'token mode claim must be read or write' }
|
|
247
|
+
}
|
|
248
|
+
if (!isTime(exp)) return { ok: false, reason: 'token exp claim is missing' }
|
|
249
|
+
if (!isTime(iat)) return { ok: false, reason: 'token iat claim is missing' }
|
|
250
|
+
if (sub !== undefined && typeof sub !== 'string') {
|
|
251
|
+
return { ok: false, reason: 'token sub claim must be a string' }
|
|
252
|
+
}
|
|
253
|
+
if (nbf !== undefined && !isTime(nbf))
|
|
254
|
+
return { ok: false, reason: 'token nbf claim is not a time' }
|
|
255
|
+
|
|
256
|
+
const now = nowMs / 1000
|
|
257
|
+
if (exp + SCOPED_TOKEN_SKEW_SECONDS <= now) return { ok: false, reason: 'token has expired' }
|
|
258
|
+
if (iat - SCOPED_TOKEN_SKEW_SECONDS > now) {
|
|
259
|
+
return { ok: false, reason: 'token iat is in the future' }
|
|
260
|
+
}
|
|
261
|
+
// Optional, but honoured where an issuer sets it (RFC 7519 §4.1.5): a token
|
|
262
|
+
// not valid yet is not valid.
|
|
263
|
+
if (isTime(nbf) && nbf - SCOPED_TOKEN_SKEW_SECONDS > now) {
|
|
264
|
+
return { ok: false, reason: 'token is not valid yet (nbf)' }
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
return {
|
|
268
|
+
ok: true,
|
|
269
|
+
claims: { repo, mode, exp, iat, ...(sub === undefined ? {} : { sub }) },
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
/** What the credential on a request turned out to be. */
|
|
274
|
+
export type ScopedAccess =
|
|
275
|
+
/** Not a scoped token, or scoped tokens are off: today's rules, unchanged. */
|
|
276
|
+
| { kind: 'unscoped' }
|
|
277
|
+
| { kind: 'scoped'; claims: ScopedClaims }
|
|
278
|
+
/** A scoped token that does not verify. 401. */
|
|
279
|
+
| { kind: 'invalid'; reason: string }
|
|
280
|
+
/** The deployment's own key list is malformed. Refused, never accepted. */
|
|
281
|
+
| { kind: 'misconfigured'; reason: string }
|
|
282
|
+
|
|
283
|
+
export interface ScopedConfig {
|
|
284
|
+
/** `WALGIT_TOKEN_PUBLIC_KEYS`, verbatim. */
|
|
285
|
+
keys: string | undefined
|
|
286
|
+
/**
|
|
287
|
+
* The deployment's own secrets — admin tokens, the announce secret. A
|
|
288
|
+
* credential equal to one of them is never judged as a scoped token, whatever
|
|
289
|
+
* it looks like.
|
|
290
|
+
*/
|
|
291
|
+
known: readonly string[]
|
|
292
|
+
now?: () => number
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
/** Classify the credential an `Authorization` header presents. */
|
|
296
|
+
export async function scopedAccessOf(
|
|
297
|
+
authorization: string | null,
|
|
298
|
+
config: ScopedConfig,
|
|
299
|
+
): Promise<ScopedAccess> {
|
|
300
|
+
const keys = seedValue(config.keys)
|
|
301
|
+
if (keys === null) return { kind: 'unscoped' }
|
|
302
|
+
const presented = presentedCredential(authorization ?? '')
|
|
303
|
+
if (!presented || !looksLikeScopedToken(presented)) return { kind: 'unscoped' }
|
|
304
|
+
// Every known secret is compared, so the answer takes the same time whichever
|
|
305
|
+
// (if any) it matched.
|
|
306
|
+
let known = false
|
|
307
|
+
for (const secret of config.known) {
|
|
308
|
+
if (secret !== '' && constantTimeEquals(secret, presented)) known = true
|
|
309
|
+
}
|
|
310
|
+
if (known) return { kind: 'unscoped' }
|
|
311
|
+
let result: VerifyResult
|
|
312
|
+
try {
|
|
313
|
+
result = await verifyScopedToken(presented, keys, config.now?.() ?? Date.now())
|
|
314
|
+
} catch (error) {
|
|
315
|
+
return { kind: 'misconfigured', reason: (error as Error).message }
|
|
316
|
+
}
|
|
317
|
+
return result.ok
|
|
318
|
+
? { kind: 'scoped', claims: result.claims }
|
|
319
|
+
: { kind: 'invalid', reason: result.reason }
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
/**
|
|
323
|
+
* What a request reaches, as far as a scoped token is concerned.
|
|
324
|
+
*
|
|
325
|
+
* - `repo`: one repository, read or written. Allowed only for the claimed
|
|
326
|
+
* name, and a write only for a `write` token.
|
|
327
|
+
* - `list`: the repository list. Allowed, and narrowed to the claimed name.
|
|
328
|
+
* - `per-message`: the MCP endpoint and the event socket, whose repositories
|
|
329
|
+
* are named inside the request rather than in its URL. Let through, and
|
|
330
|
+
* judged on every name there (`scopeRefusal` again, per name).
|
|
331
|
+
* - `elsewhere`: anything else — refused, even where an anonymous request
|
|
332
|
+
* would be served. A client that wants the anonymous view sends no
|
|
333
|
+
* credential.
|
|
334
|
+
*
|
|
335
|
+
* Deny by default: a route added later that is not named here is `elsewhere`,
|
|
336
|
+
* so forgetting it fails closed.
|
|
337
|
+
*/
|
|
338
|
+
export type ScopeTarget =
|
|
339
|
+
| { kind: 'repo'; repo: string; write: boolean }
|
|
340
|
+
| { kind: 'list' }
|
|
341
|
+
| { kind: 'per-message' }
|
|
342
|
+
| { kind: 'elsewhere' }
|
|
343
|
+
|
|
344
|
+
/**
|
|
345
|
+
* The id a requested name resolves to, the way `normalizeRepoId` (`src/repo.ts`)
|
|
346
|
+
* resolves it — so `/alpha.git.git/…` is judged as the `alpha` it would serve.
|
|
347
|
+
* Validity is not decided here: a name the container would refuse is compared
|
|
348
|
+
* as-is and simply fails to match.
|
|
349
|
+
*/
|
|
350
|
+
const canonical = (name: string): string => name.replace(/^\//, '').replace(/\.git$/, '')
|
|
351
|
+
|
|
352
|
+
export function scopeTargetOf(method: string, pathname: string, search: string): ScopeTarget {
|
|
353
|
+
const git = SMART_HTTP.exec(pathname)
|
|
354
|
+
if (git) {
|
|
355
|
+
// EVERY `service` value, not the first: `git http-backend` acts on the
|
|
356
|
+
// last, so a read token appending a second one must still be judged a push.
|
|
357
|
+
const services = new URLSearchParams(search).getAll('service')
|
|
358
|
+
const write =
|
|
359
|
+
git[2] === 'git-receive-pack' ||
|
|
360
|
+
(git[2] === 'info/refs' && services.includes('git-receive-pack'))
|
|
361
|
+
return { kind: 'repo', repo: canonical(git[1]!), write }
|
|
362
|
+
}
|
|
363
|
+
const proposals = PROPOSALS_HTTP.exec(pathname)
|
|
364
|
+
if (proposals) return { kind: 'repo', repo: canonical(proposals[1]!), write: false }
|
|
365
|
+
// The container's own read routes take the name as a query parameter. The
|
|
366
|
+
// edge forwards the provenance read as-is; the browse route is the
|
|
367
|
+
// container-side shape of the web pages below.
|
|
368
|
+
if (pathname === PROVENANCE_PATH || pathname === BROWSE_PATH) {
|
|
369
|
+
const repo = new URLSearchParams(search).get('repo')
|
|
370
|
+
return repo === null
|
|
371
|
+
? { kind: 'elsewhere' }
|
|
372
|
+
: { kind: 'repo', repo: canonical(repo), write: false }
|
|
373
|
+
}
|
|
374
|
+
// A host merge (docs/adr/0022) moves a ref, so it is a write whatever the
|
|
375
|
+
// method: a `read` token is refused it exactly as it is refused a push.
|
|
376
|
+
if (pathname === MERGE_PATH) {
|
|
377
|
+
const repo = new URLSearchParams(search).get('repo')
|
|
378
|
+
return repo === null
|
|
379
|
+
? { kind: 'elsewhere' }
|
|
380
|
+
: { kind: 'repo', repo: canonical(repo), write: true }
|
|
381
|
+
}
|
|
382
|
+
if (pathname === MCP_PATH || pathname === EVENTS_PATH) return { kind: 'per-message' }
|
|
383
|
+
if (pathname === REPOS_PATH) return { kind: 'list' }
|
|
384
|
+
const page = wantsBrowse(method, pathname)
|
|
385
|
+
if (page) return { kind: 'repo', repo: canonical(page.repo), write: false }
|
|
386
|
+
return { kind: 'elsewhere' }
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
/** Why a valid token may not do this, or `null` when it may. Always a 403. */
|
|
390
|
+
export function scopeRefusal(
|
|
391
|
+
claims: ScopedClaims,
|
|
392
|
+
target: ScopeTarget,
|
|
393
|
+
): { status: 403; message: string } | null {
|
|
394
|
+
if (target.kind === 'list' || target.kind === 'per-message') return null
|
|
395
|
+
if (target.kind === 'elsewhere') {
|
|
396
|
+
return {
|
|
397
|
+
status: 403,
|
|
398
|
+
message: `walgit: this token is scoped to the repository "${claims.repo}" and is not accepted here — send no credential for the anonymous view\n`,
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
if (target.repo !== claims.repo) {
|
|
402
|
+
return {
|
|
403
|
+
status: 403,
|
|
404
|
+
message: `walgit: this token is scoped to the repository "${claims.repo}", not "${target.repo}"\n`,
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
if (target.write && claims.mode !== 'write') {
|
|
408
|
+
return {
|
|
409
|
+
status: 403,
|
|
410
|
+
message: `walgit: this token may read "${claims.repo}" but not push to it\n`,
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
return null
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
/** Shorthand for the per-message surfaces: may this token read this name? */
|
|
417
|
+
export function scopeAllowsRead(claims: ScopedClaims, repo: string): boolean {
|
|
418
|
+
return nameInScope(claims.repo, repo)
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
/** Does a requested name resolve to the claimed repository? Exact, by id. */
|
|
422
|
+
export function nameInScope(claimed: string, requested: string): boolean {
|
|
423
|
+
return canonical(requested) === claimed
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
/**
|
|
427
|
+
* Mint one token. For `walgit token mint`, docs and tests — an issuer in
|
|
428
|
+
* production uses whatever JWT library it already has, which is the point of
|
|
429
|
+
* the format.
|
|
430
|
+
*/
|
|
431
|
+
export async function mintScopedToken(
|
|
432
|
+
privateKey: CryptoKey,
|
|
433
|
+
claims: ScopedClaims,
|
|
434
|
+
header: Record<string, unknown> = {},
|
|
435
|
+
): Promise<string> {
|
|
436
|
+
const encode = (value: unknown) =>
|
|
437
|
+
base64UrlEncode(new TextEncoder().encode(JSON.stringify(value)))
|
|
438
|
+
const signingInput = `${encode({ alg: SCOPED_TOKEN_ALG, typ: 'JWT', ...header })}.${encode(claims)}`
|
|
439
|
+
const signature = new Uint8Array(
|
|
440
|
+
await crypto.subtle.sign(
|
|
441
|
+
{ name: 'Ed25519' },
|
|
442
|
+
privateKey,
|
|
443
|
+
new TextEncoder().encode(signingInput),
|
|
444
|
+
),
|
|
445
|
+
)
|
|
446
|
+
return `${signingInput}.${base64UrlEncode(signature)}`
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
/**
|
|
450
|
+
* The edge's answer to a scoped credential, or `null` to carry on.
|
|
451
|
+
*
|
|
452
|
+
* `null` for every unscoped request, so a deployment without
|
|
453
|
+
* `WALGIT_TOKEN_PUBLIC_KEYS` never reaches a line of this file past the
|
|
454
|
+
* classification. The 401 carries the same challenge every other walgit
|
|
455
|
+
* refusal of a credential does, so git's credential helpers behave the same.
|
|
456
|
+
*/
|
|
457
|
+
export function scopedEdgeAnswer(access: ScopedAccess, target: ScopeTarget): Response | null {
|
|
458
|
+
const plain = { 'content-type': 'text/plain; charset=utf-8', 'cache-control': 'no-store' }
|
|
459
|
+
if (access.kind === 'unscoped') return null
|
|
460
|
+
if (access.kind === 'invalid') {
|
|
461
|
+
return new Response(`walgit: ${access.reason}\n`, {
|
|
462
|
+
status: 401,
|
|
463
|
+
headers: { ...plain, 'www-authenticate': BASIC_CHALLENGE },
|
|
464
|
+
})
|
|
465
|
+
}
|
|
466
|
+
if (access.kind === 'misconfigured') {
|
|
467
|
+
return new Response(`${access.reason}\n`, { status: 503, headers: plain })
|
|
468
|
+
}
|
|
469
|
+
const refused = scopeRefusal(access.claims, target)
|
|
470
|
+
return refused ? new Response(refused.message, { status: refused.status, headers: plain }) : null
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
/**
|
|
474
|
+
* Has a token that verified at some earlier moment expired since?
|
|
475
|
+
*
|
|
476
|
+
* For a credential held open — an event-stream socket verified when its
|
|
477
|
+
* `watch` arrived — so it stops being served when the token would have stopped
|
|
478
|
+
* being accepted, with the same skew `verifyScopedToken` allows.
|
|
479
|
+
*/
|
|
480
|
+
export function scopedTokenExpired(exp: number, nowMs: number = Date.now()): boolean {
|
|
481
|
+
return exp + SCOPED_TOKEN_SKEW_SECONDS <= nowMs / 1000
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
/**
|
|
485
|
+
* The event stream's question: may this credential watch these repositories?
|
|
486
|
+
*
|
|
487
|
+
* `null` when it may — every unscoped credential included, which the Reader
|
|
488
|
+
* List gate judges as before. Otherwise the error the socket is told before it
|
|
489
|
+
* is closed: `unauthorized` for a token that does not verify, `forbidden` for
|
|
490
|
+
* one that names anything outside its claim. Whole, never narrowed: a
|
|
491
|
+
* subscriber silently stripped of one repository waits forever.
|
|
492
|
+
*/
|
|
493
|
+
export function scopedWatchRefusal(
|
|
494
|
+
access: ScopedAccess,
|
|
495
|
+
repos: readonly string[],
|
|
496
|
+
): 'unauthorized' | 'forbidden' | null {
|
|
497
|
+
if (access.kind === 'unscoped') return null
|
|
498
|
+
if (access.kind !== 'scoped') return 'unauthorized'
|
|
499
|
+
return repos.every((repo) => scopeAllowsRead(access.claims, repo)) ? null : 'forbidden'
|
|
500
|
+
}
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Revoking a repository's scoped tokens: "tokens valid since" (docs/adr/0021).
|
|
3
|
+
*
|
|
4
|
+
* A scoped token is stateless — nothing about it is stored, so nothing can be
|
|
5
|
+
* deleted to end it, and without this a leaked one is good until `exp`. What is
|
|
6
|
+
* stored instead is one instant per repository, `tokens_valid_since` in its
|
|
7
|
+
* Index: every scoped token for that repository whose `iat` is earlier is
|
|
8
|
+
* refused. One admin write (`POST /_walgit/admin/repos/<name>/revoke-tokens`)
|
|
9
|
+
* revokes every token minted for the name so far, and a token minted after it
|
|
10
|
+
* works.
|
|
11
|
+
*
|
|
12
|
+
* Runtime-neutral, beside `scoped-token.ts`, because all three halves ask it:
|
|
13
|
+
* the edge Worker before anything else is decided, the container on whatever
|
|
14
|
+
* reaches it, and the event fan-out when a watch arrives. Each reads the Index
|
|
15
|
+
* itself, through the same reader, so the answer cannot differ between them.
|
|
16
|
+
*
|
|
17
|
+
* **The propagation bound is the next request.** Nothing here caches the
|
|
18
|
+
* verdict: every scoped request makes one conditional read of the Index, and a
|
|
19
|
+
* memoised copy is used only after the store has said it is still current
|
|
20
|
+
* (`304`). A revocation is therefore in force for the very next request on
|
|
21
|
+
* every surface, and a store that cannot be read refuses the token (503) rather
|
|
22
|
+
* than letting a stale copy — or no copy — pass it. A socket already open when
|
|
23
|
+
* the revocation lands is closed by the announcement the revoke makes
|
|
24
|
+
* (`tokensRevoked`, `shared/events.ts`); where no event stream is configured
|
|
25
|
+
* there is no socket to close.
|
|
26
|
+
*/
|
|
27
|
+
|
|
28
|
+
import type { ObjectStore } from './store'
|
|
29
|
+
import { loadIndex, loadIndexIfChanged } from './wal-index'
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Is a token issued at `iat` (seconds) revoked by `since` (an ISO instant)?
|
|
33
|
+
*
|
|
34
|
+
* Strictly earlier, compared in milliseconds. `iat` is whole seconds, so a
|
|
35
|
+
* token minted in the same second as the revocation but after it reads as
|
|
36
|
+
* earlier and is refused too — the safe direction: rounding the other way
|
|
37
|
+
* would let a token minted a moment BEFORE the revocation through. An issuer
|
|
38
|
+
* that meets this mints again a second later.
|
|
39
|
+
*/
|
|
40
|
+
export function tokenRevoked(iat: number, since: string | null | undefined): boolean {
|
|
41
|
+
if (since === null || since === undefined) return false
|
|
42
|
+
const sinceMs = Date.parse(since)
|
|
43
|
+
// An instant that does not parse is not a revocation anyone could have
|
|
44
|
+
// meant to be lenient about: it was written by an admin, so it fails closed.
|
|
45
|
+
if (!Number.isFinite(sinceMs)) return true
|
|
46
|
+
return iat * 1000 < sinceMs
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** The 401 body for a revoked token. */
|
|
50
|
+
export function revokedMessage(repo: string, since: string): string {
|
|
51
|
+
return `walgit: this token for "${repo}" was issued before ${since}, when the repository's tokens were revoked — ask its issuer for a new one\n`
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* How many repositories one reader remembers. The memo only saves the body of
|
|
56
|
+
* an unchanged Index — every lookup still asks the store — so a bound costs
|
|
57
|
+
* a full read on the next request for an evicted name, and nothing more.
|
|
58
|
+
*/
|
|
59
|
+
export const MAX_REMEMBERED_REPOS = 1024
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Reads a repository's `tokens_valid_since`, one conditional GET per call.
|
|
63
|
+
*
|
|
64
|
+
* Held for an isolate's or a process's life. Never answers from memory alone:
|
|
65
|
+
* the memo is the last Index body's verdict keyed by its etag, and is used only
|
|
66
|
+
* when the store answers `not-modified` for that etag.
|
|
67
|
+
*/
|
|
68
|
+
export class TokenRevocationReader {
|
|
69
|
+
private readonly seen = new Map<string, { etag: string; since: string | null }>()
|
|
70
|
+
|
|
71
|
+
constructor(private readonly maxRepos: number = MAX_REMEMBERED_REPOS) {}
|
|
72
|
+
|
|
73
|
+
/** The repository's revocation instant, or `null` when none. Throws when the store does. */
|
|
74
|
+
async validSince(store: ObjectStore, repo: string): Promise<string | null> {
|
|
75
|
+
const known = this.seen.get(repo)
|
|
76
|
+
if (known) {
|
|
77
|
+
const res = await loadIndexIfChanged(store, repo, known.etag)
|
|
78
|
+
if (res === 'current') return known.since
|
|
79
|
+
return this.remember(repo, res.etag, res.index.tokens_valid_since ?? null)
|
|
80
|
+
}
|
|
81
|
+
const res = await loadIndex(store, repo)
|
|
82
|
+
return this.remember(repo, res.etag, res.index.tokens_valid_since ?? null)
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
private remember(repo: string, etag: string | null, since: string | null): string | null {
|
|
86
|
+
this.seen.delete(repo)
|
|
87
|
+
// An absent Index has no etag to ask about next time, so nothing is kept.
|
|
88
|
+
if (etag === null) return since
|
|
89
|
+
if (this.seen.size >= this.maxRepos) {
|
|
90
|
+
const oldest = this.seen.keys().next().value
|
|
91
|
+
if (oldest !== undefined) this.seen.delete(oldest)
|
|
92
|
+
}
|
|
93
|
+
this.seen.set(repo, { etag, since })
|
|
94
|
+
return since
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
export type RevocationVerdict =
|
|
99
|
+
| { kind: 'valid' }
|
|
100
|
+
| { kind: 'revoked'; since: string }
|
|
101
|
+
/** The Index could not be read, so revocation could not be ruled out. */
|
|
102
|
+
| { kind: 'unknown'; reason: string }
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* Judge one verified token against its repository's revocation instant.
|
|
106
|
+
*
|
|
107
|
+
* The repository is the token's own claim, whatever the request names: a
|
|
108
|
+
* scoped token reaches one repository and nothing else (the scope gate refuses
|
|
109
|
+
* the rest), so its claim is the only Index whose revocation can apply.
|
|
110
|
+
*/
|
|
111
|
+
export async function revocationOf(
|
|
112
|
+
claims: { repo: string; iat: number },
|
|
113
|
+
store: ObjectStore | null,
|
|
114
|
+
reader: TokenRevocationReader,
|
|
115
|
+
): Promise<RevocationVerdict> {
|
|
116
|
+
if (!store) {
|
|
117
|
+
return {
|
|
118
|
+
kind: 'unknown',
|
|
119
|
+
reason: 'walgit: no object store configured here, so token revocation cannot be checked',
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
let since: string | null
|
|
123
|
+
try {
|
|
124
|
+
since = await reader.validSince(store, claims.repo)
|
|
125
|
+
} catch (error) {
|
|
126
|
+
return {
|
|
127
|
+
kind: 'unknown',
|
|
128
|
+
reason: `walgit: could not check token revocation: ${(error as Error).message}`,
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
return since !== null && tokenRevoked(claims.iat, since)
|
|
132
|
+
? { kind: 'revoked', since }
|
|
133
|
+
: { kind: 'valid' }
|
|
134
|
+
}
|
|
@@ -110,6 +110,25 @@ export interface WalIndex {
|
|
|
110
110
|
* second request.
|
|
111
111
|
*/
|
|
112
112
|
deletion?: RepoDeletion
|
|
113
|
+
/**
|
|
114
|
+
* When an admin create claimed this name (`src/admin.ts`), for a repository
|
|
115
|
+
* that may hold no entry yet. Expiry dates a repository by its last push,
|
|
116
|
+
* and one created empty has none — without this it would be kept forever.
|
|
117
|
+
* Absent on every Index a push created.
|
|
118
|
+
*/
|
|
119
|
+
created_at?: string
|
|
120
|
+
/**
|
|
121
|
+
* Tokens valid since: the ISO instant before which no scoped token for this
|
|
122
|
+
* repository is honoured (docs/adr/0021). A token whose `iat` is earlier is
|
|
123
|
+
* refused 401 on every surface, which is how one admin write revokes every
|
|
124
|
+
* token minted for the name so far — scoped tokens are otherwise stateless
|
|
125
|
+
* and stay valid until `exp`.
|
|
126
|
+
*
|
|
127
|
+
* Absent means nothing is revoked, which is every Index until an admin asks
|
|
128
|
+
* (`src/admin.ts`). It only ever moves forward. Carried through every push
|
|
129
|
+
* by `nextIndex`'s spread, like `created_at` above it.
|
|
130
|
+
*/
|
|
131
|
+
tokens_valid_since?: string
|
|
113
132
|
/**
|
|
114
133
|
* Push provenance: ref → who signed the push that moved it to the sha `refs`
|
|
115
134
|
* currently holds, and when (docs/adr/0011).
|