@zabaca/zbc 0.24.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 +45 -0
- package/package.json +3 -2
- package/src/commands/add.ts +78 -5
- package/src/commands/init.ts +105 -10
- package/src/commands/list.ts +6 -3
- package/src/commands/update.ts +75 -6
- package/src/engine/destroy.ts +23 -2
- package/src/engine/resolve.ts +5 -0
- package/src/utils/detect-mode.ts +1 -1
- package/src/utils/host-workspaces.ts +57 -0
- package/src/utils/subtree.ts +78 -9
- package/src/utils/vendor-audit.ts +12 -8
- package/src/utils/vendor-stamp.ts +102 -1
- package/src/utils/vendored-app.ts +356 -0
- package/templates/CLAUDE.md +1 -1
- 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 +18 -4
- package/templates/apps/warehouse/worker/router.ts +1 -2
- package/templates/apps/warehouse/worker/test-setup.ts +1 -2
- package/templates/infra/modules/cloudflare-access/index.ts +245 -28
- package/templates/infra/modules/cloudflare-access/registry.json +1 -1
- package/templates/infra/modules/d1/index.ts +133 -4
- package/templates/infra/modules/d1/registry.json +4 -1
- package/templates/infra/modules/queue/index.ts +313 -0
- package/templates/infra/modules/queue/registry.json +13 -0
- package/templates/infra/modules/r2/registry.json +1 -1
- package/templates/infra/src/define-module.ts +19 -2
- package/templates/infra/src/types.ts +24 -0
- package/templates/apps/inbox/package.json +0 -26
- package/templates/apps/inbox/public/index.html +0 -379
- package/templates/apps/inbox/registry.json +0 -9
- package/templates/apps/inbox/tsconfig.json +0 -19
- package/templates/apps/inbox/worker/api.ts +0 -197
- package/templates/apps/inbox/worker/commands.ts +0 -299
- package/templates/apps/inbox/worker/inbox-do.ts +0 -577
- package/templates/apps/inbox/worker/index.ts +0 -195
- package/templates/apps/inbox/worker/mcp.ts +0 -228
- package/templates/apps/inbox/worker/shared.ts +0 -117
- package/templates/apps/inbox/wrangler.jsonc +0 -48
|
@@ -20,8 +20,15 @@
|
|
|
20
20
|
* command line (`src/git.ts`). Nothing here concatenates either into `args`.
|
|
21
21
|
*/
|
|
22
22
|
|
|
23
|
-
import {
|
|
24
|
-
|
|
23
|
+
import {
|
|
24
|
+
OID,
|
|
25
|
+
type Commit,
|
|
26
|
+
type CompareFile,
|
|
27
|
+
type CompareStatus,
|
|
28
|
+
type Comparison,
|
|
29
|
+
type TreeEntry,
|
|
30
|
+
} from '../shared/browse'
|
|
31
|
+
import { git, gitBounded, gitBytes } from './git'
|
|
25
32
|
|
|
26
33
|
/** git's modes, as the four kinds a reader can actually see apart. */
|
|
27
34
|
const SYMLINK_MODE = '120000'
|
|
@@ -228,3 +235,249 @@ export async function listCommits(
|
|
|
228
235
|
}
|
|
229
236
|
return commits
|
|
230
237
|
}
|
|
238
|
+
|
|
239
|
+
/** The bounds one compare works under. The handler's, like `LOG_PAGE`. */
|
|
240
|
+
export interface CompareLimits {
|
|
241
|
+
maxFiles: number
|
|
242
|
+
/** `0` skips the unified diff: the summary alone (a merge's answer). */
|
|
243
|
+
maxDiffBytes: number
|
|
244
|
+
/** Wall-clock budget for every git command of one compare, together. */
|
|
245
|
+
timeoutMs: number
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
/** A comparison, with the two commits it was read at. */
|
|
249
|
+
export type CompareResult = Comparison & { peeled: { base: string; head: string } }
|
|
250
|
+
|
|
251
|
+
/**
|
|
252
|
+
* How much summary one compare will read: 16 MiB of `--raw --numstat -z`,
|
|
253
|
+
* which is on the order of a hundred thousand changed files. Past it the
|
|
254
|
+
* records cannot be trusted to pair up, so the compare is refused rather than
|
|
255
|
+
* answered with counts that silently stopped.
|
|
256
|
+
*/
|
|
257
|
+
const SUMMARY_MAX_BYTES = 16 * 1024 * 1024
|
|
258
|
+
|
|
259
|
+
/**
|
|
260
|
+
* The flags every diff below runs with, whatever the repository's own config.
|
|
261
|
+
*
|
|
262
|
+
* `-M` because a rename shown as a delete and an add is the wrong review, and
|
|
263
|
+
* git's `diff.renames` default is a config this process should not depend on.
|
|
264
|
+
* No colour, no external diff driver and no textconv: the output is read by a
|
|
265
|
+
* program, and a driver is a command the repository could name.
|
|
266
|
+
*/
|
|
267
|
+
const DIFF_FLAGS = ['-M', '--no-color', '--no-ext-diff', '--no-textconv']
|
|
268
|
+
|
|
269
|
+
const text = (bytes: Uint8Array) => new TextDecoder().decode(bytes)
|
|
270
|
+
|
|
271
|
+
/**
|
|
272
|
+
* The head against its merge base with the base — three-dot, the diff a review
|
|
273
|
+
* reads.
|
|
274
|
+
*
|
|
275
|
+
* `null` when the Cache cannot resolve one of the two to a commit;
|
|
276
|
+
* `'unrelated'` when they share no history and there is no merge base to diff
|
|
277
|
+
* against; `'too-large'` when the comparison cannot be computed inside the
|
|
278
|
+
* bounds at all — the time budget ran out, or the summary alone overran.
|
|
279
|
+
*
|
|
280
|
+
* Four commands, all under one deadline: `rev-parse` to peel each side to its
|
|
281
|
+
* commit (an annotated tag names a tag object), `merge-base`, one `diff --raw
|
|
282
|
+
* --numstat -z` for the whole summary, and one `diff` for the text. The
|
|
283
|
+
* summary line-diffs every changed file to count it, so it is not free — it is
|
|
284
|
+
* read whole so the totals are true when the list is capped, and the deadline
|
|
285
|
+
* is what bounds it. The text is limited to the listed files and cut off in
|
|
286
|
+
* the subprocess at the byte cap. Both revisions are full oids by the time they
|
|
287
|
+
* arrive (`src/http.ts`), and they go in as operands all the same.
|
|
288
|
+
*/
|
|
289
|
+
export async function compareRevs(
|
|
290
|
+
gitDir: string,
|
|
291
|
+
base: string,
|
|
292
|
+
head: string,
|
|
293
|
+
limits: CompareLimits,
|
|
294
|
+
): Promise<CompareResult | 'unrelated' | 'too-large' | null> {
|
|
295
|
+
const deadline = Date.now() + limits.timeoutMs
|
|
296
|
+
const run = (args: string[], limit: number, opts: Parameters<typeof gitBounded>[2] = {}) =>
|
|
297
|
+
gitBounded(args, { limit, timeoutMs: Math.max(1, deadline - Date.now()) }, { gitDir, ...opts })
|
|
298
|
+
|
|
299
|
+
const peeled: string[] = []
|
|
300
|
+
for (const rev of [base, head]) {
|
|
301
|
+
const res = run(['rev-parse', '--verify', '--quiet'], 4096, { operands: [`${rev}^{commit}`] })
|
|
302
|
+
if (res.outcome === 'timed-out') return 'too-large'
|
|
303
|
+
const oid = text(res.stdout).trim()
|
|
304
|
+
if (res.outcome !== 'ok' || !OID.test(oid)) return null
|
|
305
|
+
peeled.push(oid)
|
|
306
|
+
}
|
|
307
|
+
const [baseCommit, headCommit] = peeled as [string, string]
|
|
308
|
+
|
|
309
|
+
const mb = run(['merge-base'], 4096, { operands: [baseCommit, headCommit] })
|
|
310
|
+
if (mb.outcome === 'timed-out') return 'too-large'
|
|
311
|
+
const mergeBase = text(mb.stdout).trim()
|
|
312
|
+
// A failure with no output is "no common ancestor": two histories, both real.
|
|
313
|
+
if (mb.outcome === 'failed' && mergeBase === '') return 'unrelated'
|
|
314
|
+
if (mb.outcome !== 'ok' || !OID.test(mergeBase)) return null
|
|
315
|
+
|
|
316
|
+
const summary = run(['diff', ...DIFF_FLAGS, '--raw', '--numstat', '-z'], SUMMARY_MAX_BYTES, {
|
|
317
|
+
operands: [mergeBase, headCommit],
|
|
318
|
+
})
|
|
319
|
+
if (summary.outcome === 'timed-out' || summary.outcome === 'overflowed') return 'too-large'
|
|
320
|
+
if (summary.outcome !== 'ok') return null
|
|
321
|
+
const all = parseSummary(text(summary.stdout))
|
|
322
|
+
if (all === null) return 'too-large'
|
|
323
|
+
|
|
324
|
+
const totals = { files: all.length, additions: 0, deletions: 0 }
|
|
325
|
+
for (const file of all) {
|
|
326
|
+
totals.additions += file.additions
|
|
327
|
+
totals.deletions += file.deletions
|
|
328
|
+
}
|
|
329
|
+
const files = all.slice(0, limits.maxFiles)
|
|
330
|
+
const capped = files.length < all.length
|
|
331
|
+
let truncated = capped
|
|
332
|
+
|
|
333
|
+
let diff = ''
|
|
334
|
+
if (files.length > 0 && limits.maxDiffBytes > 0) {
|
|
335
|
+
// Only the listed files, when the list was capped — so the diff a reader
|
|
336
|
+
// gets describes exactly the files they were shown. A rename needs both
|
|
337
|
+
// of its paths in the pathspec or git cannot pair them. Literal pathspecs,
|
|
338
|
+
// because a file may be called `*` and that is a name, not a glob.
|
|
339
|
+
const paths = capped
|
|
340
|
+
? files.flatMap((file) => (file.previousPath ? [file.previousPath, file.path] : [file.path]))
|
|
341
|
+
: []
|
|
342
|
+
const res = run(['-c', 'core.quotePath=false', 'diff', ...DIFF_FLAGS], limits.maxDiffBytes, {
|
|
343
|
+
operands: [mergeBase, headCommit],
|
|
344
|
+
paths,
|
|
345
|
+
env: { GIT_LITERAL_PATHSPECS: '1' },
|
|
346
|
+
})
|
|
347
|
+
if (res.outcome === 'timed-out') return 'too-large'
|
|
348
|
+
if (res.outcome === 'failed') return null
|
|
349
|
+
let bytes = res.stdout
|
|
350
|
+
if (res.outcome === 'overflowed') {
|
|
351
|
+
truncated = true
|
|
352
|
+
// On a line boundary, so the last line shown is a whole one and a
|
|
353
|
+
// multi-byte character is never split.
|
|
354
|
+
bytes = bytes.subarray(0, bytes.lastIndexOf(0x0a) + 1)
|
|
355
|
+
}
|
|
356
|
+
diff = text(bytes)
|
|
357
|
+
// A pathspec still matches as a directory PREFIX, so a listed `a` lets an
|
|
358
|
+
// unlisted `a/x` into the diff. Keep only the sections the list names.
|
|
359
|
+
if (capped) diff = onlySections(diff, files)
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
return {
|
|
363
|
+
mergeBase,
|
|
364
|
+
files,
|
|
365
|
+
totals,
|
|
366
|
+
diff,
|
|
367
|
+
truncated,
|
|
368
|
+
peeled: { base: baseCommit, head: headCommit },
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
/**
|
|
373
|
+
* The sections of a unified diff whose `diff --git` header names a listed
|
|
374
|
+
* file, in order. The header is rebuilt the way git writes it — each side
|
|
375
|
+
* C-quoted on its own when it needs to be, with `core.quotePath` off so only
|
|
376
|
+
* control characters, `"` and `\\` do — and compared whole.
|
|
377
|
+
*/
|
|
378
|
+
function onlySections(diff: string, files: CompareFile[]): string {
|
|
379
|
+
const wanted = new Set(
|
|
380
|
+
files.map(
|
|
381
|
+
(file) =>
|
|
382
|
+
`diff --git ${quotePath(`a/${file.previousPath ?? file.path}`)} ${quotePath(`b/${file.path}`)}`,
|
|
383
|
+
),
|
|
384
|
+
)
|
|
385
|
+
const sections = diff.split(/^(?=diff --git )/m)
|
|
386
|
+
return sections
|
|
387
|
+
.filter((section) => {
|
|
388
|
+
const end = section.indexOf('\n')
|
|
389
|
+
return wanted.has(end === -1 ? section : section.slice(0, end))
|
|
390
|
+
})
|
|
391
|
+
.join('')
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
const C_ESCAPES: Record<string, string> = {
|
|
395
|
+
'\x07': 'a',
|
|
396
|
+
'\b': 'b',
|
|
397
|
+
'\t': 't',
|
|
398
|
+
'\n': 'n',
|
|
399
|
+
'\v': 'v',
|
|
400
|
+
'\f': 'f',
|
|
401
|
+
'\r': 'r',
|
|
402
|
+
'"': '"',
|
|
403
|
+
'\\': '\\',
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
/** git's `quote_c_style` with `core.quotePath=false`. */
|
|
407
|
+
function quotePath(name: string): string {
|
|
408
|
+
let quoted = ''
|
|
409
|
+
let needs = false
|
|
410
|
+
for (const ch of name) {
|
|
411
|
+
const code = ch.codePointAt(0)!
|
|
412
|
+
if (C_ESCAPES[ch] !== undefined) {
|
|
413
|
+
quoted += `\\${C_ESCAPES[ch]}`
|
|
414
|
+
needs = true
|
|
415
|
+
} else if (code < 0x20 || code === 0x7f) {
|
|
416
|
+
quoted += `\\${code.toString(8).padStart(3, '0')}`
|
|
417
|
+
needs = true
|
|
418
|
+
} else {
|
|
419
|
+
quoted += ch
|
|
420
|
+
}
|
|
421
|
+
}
|
|
422
|
+
return needs ? `"${quoted}"` : name
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
/**
|
|
426
|
+
* `git diff --raw --numstat -z`: every raw record, then every numstat record,
|
|
427
|
+
* in the same order.
|
|
428
|
+
*
|
|
429
|
+
* A raw record is `:<modes> <oids> <status>` then one path, or two for a
|
|
430
|
+
* rename. A numstat record is `<added>\t<deleted>\t<path>`, or for a rename
|
|
431
|
+
* `<added>\t<deleted>\t` followed by the two paths as their own fields. `-`
|
|
432
|
+
* for both counts is git's word for binary.
|
|
433
|
+
*/
|
|
434
|
+
function parseSummary(out: string): CompareFile[] | null {
|
|
435
|
+
const fields = out.split('\0')
|
|
436
|
+
const raw: { path: string; previousPath?: string; status: CompareStatus }[] = []
|
|
437
|
+
const counts: { additions: number; deletions: number; binary: boolean }[] = []
|
|
438
|
+
let i = 0
|
|
439
|
+
while (i < fields.length) {
|
|
440
|
+
const field = fields[i++]!
|
|
441
|
+
if (field === '') continue
|
|
442
|
+
if (field.startsWith(':')) {
|
|
443
|
+
const letter = field.slice(field.lastIndexOf(' ') + 1)
|
|
444
|
+
if (letter.startsWith('R') || letter.startsWith('C')) {
|
|
445
|
+
const previousPath = fields[i++] ?? ''
|
|
446
|
+
const path = fields[i++] ?? ''
|
|
447
|
+
raw.push(
|
|
448
|
+
letter.startsWith('R')
|
|
449
|
+
? { path, previousPath, status: 'renamed' }
|
|
450
|
+
: // A copy is only reported under `-C`, which is not asked for; were
|
|
451
|
+
// one ever to arrive, the new file is what a reviewer reads.
|
|
452
|
+
{ path, status: 'added' },
|
|
453
|
+
)
|
|
454
|
+
} else {
|
|
455
|
+
const path = fields[i++] ?? ''
|
|
456
|
+
raw.push({ path, status: statusOf(letter) })
|
|
457
|
+
}
|
|
458
|
+
continue
|
|
459
|
+
}
|
|
460
|
+
const [added, deleted, path] = field.split('\t')
|
|
461
|
+
// A rename's numstat names its paths as the next two fields.
|
|
462
|
+
if (path === '') i += 2
|
|
463
|
+
const binary = added === '-' && deleted === '-'
|
|
464
|
+
counts.push({
|
|
465
|
+
additions: binary ? 0 : Number(added) || 0,
|
|
466
|
+
deletions: binary ? 0 : Number(deleted) || 0,
|
|
467
|
+
binary,
|
|
468
|
+
})
|
|
469
|
+
}
|
|
470
|
+
// Every file has one record of each kind. Anything else is output that was
|
|
471
|
+
// not read whole, and counts from it would be wrong without saying so.
|
|
472
|
+
if (raw.length !== counts.length) return null
|
|
473
|
+
return raw.map((file, n) => ({ ...file, ...counts[n]! }))
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
/** git's one-letter status, as the four a reviewer reads apart. */
|
|
477
|
+
function statusOf(letter: string): CompareStatus {
|
|
478
|
+
if (letter === 'A') return 'added'
|
|
479
|
+
if (letter === 'D') return 'deleted'
|
|
480
|
+
// `M`, and `T` — a type change (a file become a symlink) is a modification
|
|
481
|
+
// of the path as far as a review is concerned.
|
|
482
|
+
return 'modified'
|
|
483
|
+
}
|
|
@@ -23,8 +23,11 @@
|
|
|
23
23
|
* missing configuration).
|
|
24
24
|
*/
|
|
25
25
|
|
|
26
|
+
import * as fs from 'node:fs'
|
|
26
27
|
import * as path from 'node:path'
|
|
27
28
|
|
|
29
|
+
import { base64UrlEncode, mintScopedToken, type ScopedMode } from '../shared/scoped-token'
|
|
30
|
+
|
|
28
31
|
import { compact, configuredGraceMs, type CompactResult } from './compact'
|
|
29
32
|
import { configuredDeleteGraceMs, deleteRepo } from './delete-repo'
|
|
30
33
|
import { configuredClaimedExpiryMs, configuredExpiryMs, expireRepos } from './expire'
|
|
@@ -60,6 +63,12 @@ const KNOWN_VALUE_FLAGS = new Set([
|
|
|
60
63
|
'claimed-after',
|
|
61
64
|
'since',
|
|
62
65
|
'top',
|
|
66
|
+
'key',
|
|
67
|
+
'out',
|
|
68
|
+
'repo',
|
|
69
|
+
'mode',
|
|
70
|
+
'ttl',
|
|
71
|
+
'sub',
|
|
63
72
|
])
|
|
64
73
|
|
|
65
74
|
export function parseArgs(argv: readonly string[]): ParsedArgs {
|
|
@@ -95,6 +104,10 @@ const USAGE = `walgit — operator CLI for a WAL-backed git host
|
|
|
95
104
|
walgit delete <repo_id...> remove repositories entirely (dry run)
|
|
96
105
|
walgit usage what the log says this service holds
|
|
97
106
|
walgit expire [repo_id...] collect repos idle past the window (dry run)
|
|
107
|
+
walgit token keygen --out <file> make an Ed25519 keypair for scoped tokens
|
|
108
|
+
walgit token public-key --key <file> print a private key's WALGIT_TOKEN_PUBLIC_KEYS entry
|
|
109
|
+
walgit token mint --key <file> --repo <name> --mode read|write [--ttl 1h] [--sub <tenant>]
|
|
110
|
+
mint a scoped token for one repository
|
|
98
111
|
|
|
99
112
|
Options
|
|
100
113
|
--repos-dir <dir> where bare repos live (default: $WALGIT_REPOS_DIR)
|
|
@@ -110,6 +123,7 @@ Options
|
|
|
110
123
|
--collect-only expire: collect tombstoned repos, tombstone nothing new
|
|
111
124
|
--since <duration> usage: push window, e.g. 24h, 7d, 30m (default 24h)
|
|
112
125
|
--top <n> usage: how many repositories to name (0 = all, default 10)
|
|
126
|
+
--ttl <duration> token mint: lifetime, e.g. 15m, 1h, 7d (default 1h)
|
|
113
127
|
|
|
114
128
|
The object store is read from the environment the app itself uses:
|
|
115
129
|
WALGIT_S3_ENDPOINT / _BUCKET / _ACCESS_KEY_ID / _SECRET_ACCESS_KEY, or
|
|
@@ -478,6 +492,130 @@ async function usageCommand(args: ParsedArgs, env: NodeJS.ProcessEnv): Promise<n
|
|
|
478
492
|
return OK
|
|
479
493
|
}
|
|
480
494
|
|
|
495
|
+
// ── Scoped tokens (docs/adr/0021) ──────────────────────────────────────────
|
|
496
|
+
//
|
|
497
|
+
// An operator's tool for testing and docs. An issuer in production signs with
|
|
498
|
+
// whatever JWT library it already has — EdDSA over Ed25519 is the standard
|
|
499
|
+
// shape, which is why the format was chosen — and walgit itself never holds a
|
|
500
|
+
// private key: these commands run wherever the key is, not in the container.
|
|
501
|
+
|
|
502
|
+
const PEM_LABEL = 'PRIVATE KEY'
|
|
503
|
+
|
|
504
|
+
function pem(der: Uint8Array): string {
|
|
505
|
+
let binary = ''
|
|
506
|
+
for (const byte of der) binary += String.fromCharCode(byte)
|
|
507
|
+
const lines = btoa(binary).match(/.{1,64}/g) ?? []
|
|
508
|
+
return `-----BEGIN ${PEM_LABEL}-----\n${lines.join('\n')}\n-----END ${PEM_LABEL}-----\n`
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
/**
|
|
512
|
+
* Read a PKCS#8 Ed25519 private key — what `token keygen` writes and what
|
|
513
|
+
* `openssl genpkey -algorithm ed25519` writes too.
|
|
514
|
+
*/
|
|
515
|
+
async function readPrivateKey(file: string): Promise<CryptoKey> {
|
|
516
|
+
const text = fs.readFileSync(file, 'utf8')
|
|
517
|
+
const body = new RegExp(
|
|
518
|
+
`-----BEGIN ${PEM_LABEL}-----([\\s\\S]+?)-----END ${PEM_LABEL}-----`,
|
|
519
|
+
).exec(text)
|
|
520
|
+
if (!body) throw new Error(`${file} is not a PEM "${PEM_LABEL}" (PKCS#8) file`)
|
|
521
|
+
const der = Uint8Array.from(atob(body[1]!.replace(/\s+/g, '')), (c) => c.charCodeAt(0))
|
|
522
|
+
try {
|
|
523
|
+
return await crypto.subtle.importKey('pkcs8', der, { name: 'Ed25519' }, true, ['sign'])
|
|
524
|
+
} catch {
|
|
525
|
+
throw new Error(`${file} is not an Ed25519 private key`)
|
|
526
|
+
}
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
/** The public half, as one `WALGIT_TOKEN_PUBLIC_KEYS` entry: the JWK's `x`. */
|
|
530
|
+
async function publicKeyOf(privateKey: CryptoKey): Promise<string> {
|
|
531
|
+
const jwk = await crypto.subtle.exportKey('jwk', privateKey)
|
|
532
|
+
if (typeof jwk.x !== 'string') throw new Error('could not derive the public key')
|
|
533
|
+
return jwk.x
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
function stringFlag(args: ParsedArgs, name: string): string | undefined {
|
|
537
|
+
const value = args.flags[name]
|
|
538
|
+
return typeof value === 'string' && value !== '' ? value : undefined
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
async function tokenCommand(args: ParsedArgs): Promise<number> {
|
|
542
|
+
const sub = args.positional[0]
|
|
543
|
+
if (sub === 'keygen') {
|
|
544
|
+
const out = stringFlag(args, 'out')
|
|
545
|
+
if (!out) {
|
|
546
|
+
console.error('walgit: token keygen needs --out <file> for the private key')
|
|
547
|
+
return MISUSE
|
|
548
|
+
}
|
|
549
|
+
// Never overwrite: replacing a signing key in place is a rotation nobody
|
|
550
|
+
// planned, and every token the old one minted stops verifying.
|
|
551
|
+
if (fs.existsSync(out)) {
|
|
552
|
+
console.error(`walgit: ${out} already exists; refusing to overwrite a key`)
|
|
553
|
+
return MISUSE
|
|
554
|
+
}
|
|
555
|
+
const pair = (await crypto.subtle.generateKey({ name: 'Ed25519' }, true, [
|
|
556
|
+
'sign',
|
|
557
|
+
'verify',
|
|
558
|
+
])) as CryptoKeyPair
|
|
559
|
+
const der = new Uint8Array(await crypto.subtle.exportKey('pkcs8', pair.privateKey))
|
|
560
|
+
fs.writeFileSync(out, pem(der), { mode: 0o600, flag: 'wx' })
|
|
561
|
+
const raw = new Uint8Array(await crypto.subtle.exportKey('raw', pair.publicKey))
|
|
562
|
+
emit(
|
|
563
|
+
args,
|
|
564
|
+
{ privateKey: out, publicKey: base64UrlEncode(raw) },
|
|
565
|
+
`private key written to ${out} (keep it with the issuer, never on walgit)\n` +
|
|
566
|
+
`WALGIT_TOKEN_PUBLIC_KEYS entry: ${base64UrlEncode(raw)}`,
|
|
567
|
+
)
|
|
568
|
+
return OK
|
|
569
|
+
}
|
|
570
|
+
|
|
571
|
+
if (sub === 'public-key') {
|
|
572
|
+
const key = stringFlag(args, 'key')
|
|
573
|
+
if (!key) {
|
|
574
|
+
console.error('walgit: token public-key needs --key <private key file>')
|
|
575
|
+
return MISUSE
|
|
576
|
+
}
|
|
577
|
+
const publicKey = await publicKeyOf(await readPrivateKey(key))
|
|
578
|
+
emit(args, { publicKey }, publicKey)
|
|
579
|
+
return OK
|
|
580
|
+
}
|
|
581
|
+
|
|
582
|
+
if (sub === 'mint') {
|
|
583
|
+
const key = stringFlag(args, 'key')
|
|
584
|
+
const repoFlag = stringFlag(args, 'repo')
|
|
585
|
+
const mode = stringFlag(args, 'mode')
|
|
586
|
+
if (!key || !repoFlag || (mode !== 'read' && mode !== 'write')) {
|
|
587
|
+
console.error(
|
|
588
|
+
'walgit: token mint needs --key <file> --repo <name> --mode read|write [--ttl 1h] [--sub <tenant>]',
|
|
589
|
+
)
|
|
590
|
+
return MISUSE
|
|
591
|
+
}
|
|
592
|
+
// The same grammar every entry point applies, and the canonical spelling:
|
|
593
|
+
// a claim is an exact name, never `name.git`.
|
|
594
|
+
const repo = normalizeRepoId(repoFlag)
|
|
595
|
+
// A claim may not end in `.git` (it would name a different repository than
|
|
596
|
+
// the URL serves), so a name that still does after normalizing would mint
|
|
597
|
+
// a token no deployment accepts. Refused here, where it can be said.
|
|
598
|
+
if (repo.endsWith('.git'))
|
|
599
|
+
throw new Error(`"${repoFlag}" is not a repository id a token can name`)
|
|
600
|
+
const ttlMs = parseDuration(stringFlag(args, 'ttl') ?? '1h')
|
|
601
|
+
if (!(ttlMs > 0)) throw new Error('--ttl must be longer than zero')
|
|
602
|
+
const iat = Math.floor(Date.now() / 1000)
|
|
603
|
+
const tenant = stringFlag(args, 'sub')
|
|
604
|
+
const token = await mintScopedToken(await readPrivateKey(key), {
|
|
605
|
+
repo,
|
|
606
|
+
mode: mode as ScopedMode,
|
|
607
|
+
iat,
|
|
608
|
+
exp: iat + Math.ceil(ttlMs / 1000),
|
|
609
|
+
...(tenant ? { sub: tenant } : {}),
|
|
610
|
+
})
|
|
611
|
+
emit(args, { token, repo, mode, exp: iat + Math.ceil(ttlMs / 1000) }, token)
|
|
612
|
+
return OK
|
|
613
|
+
}
|
|
614
|
+
|
|
615
|
+
console.error(`walgit: token needs keygen, public-key or mint\n\n${USAGE}`)
|
|
616
|
+
return MISUSE
|
|
617
|
+
}
|
|
618
|
+
|
|
481
619
|
// ── Entry point ─────────────────────────────────────────────────────────────
|
|
482
620
|
|
|
483
621
|
export async function main(
|
|
@@ -508,6 +646,8 @@ export async function main(
|
|
|
508
646
|
return await usageCommand(args, env)
|
|
509
647
|
case 'expire':
|
|
510
648
|
return await expireCommand(args, env)
|
|
649
|
+
case 'token':
|
|
650
|
+
return await tokenCommand(args)
|
|
511
651
|
default:
|
|
512
652
|
console.error(`walgit: unknown command "${args.command}"\n\n${USAGE}`)
|
|
513
653
|
return MISUSE
|
|
@@ -87,6 +87,11 @@ export function lastWriteAt(index: WalIndex): string | null {
|
|
|
87
87
|
if (!Number.isFinite(at)) continue
|
|
88
88
|
if (!newest || at > newest.at) newest = { ts: entry.ts, at }
|
|
89
89
|
}
|
|
90
|
+
// A repository an admin created empty is dated by its creation until its
|
|
91
|
+
// first push, so it expires like one pushed to once and then left.
|
|
92
|
+
if (!newest && index.created_at && Number.isFinite(Date.parse(index.created_at))) {
|
|
93
|
+
return index.created_at
|
|
94
|
+
}
|
|
90
95
|
return newest?.ts ?? null
|
|
91
96
|
}
|
|
92
97
|
|
|
@@ -185,6 +185,49 @@ export function gitBytes(
|
|
|
185
185
|
}
|
|
186
186
|
}
|
|
187
187
|
|
|
188
|
+
/**
|
|
189
|
+
* git, where both the output and the time are deliberately BOUNDED rather than
|
|
190
|
+
* merely buffered.
|
|
191
|
+
*
|
|
192
|
+
* One caller: the compare (`src/browse.ts`), whose cost is whatever two refs
|
|
193
|
+
* make it and is not something a request may let grow to `MAX_BUFFER` or hold
|
|
194
|
+
* the process for. Past `limit` bytes of stdout the child is killed and what
|
|
195
|
+
* was read so far comes back cut at `limit` as `overflowed` — the cut is the
|
|
196
|
+
* caller's to present, never a failure. Past `timeoutMs` the child is killed
|
|
197
|
+
* and the answer is `timed-out`. A zero exit is not trusted for completeness:
|
|
198
|
+
* the runtime reports an overrun as `ENOBUFS` with a killed child, and that is
|
|
199
|
+
* the signal read — and only when it was STDOUT that overran, since stderr
|
|
200
|
+
* filling the same buffer raises the same code with nothing on stdout.
|
|
201
|
+
*/
|
|
202
|
+
export function gitBounded(
|
|
203
|
+
args: readonly string[],
|
|
204
|
+
bounds: { limit: number; timeoutMs: number },
|
|
205
|
+
opts: GitOptions = {},
|
|
206
|
+
): {
|
|
207
|
+
outcome: 'ok' | 'overflowed' | 'timed-out' | 'failed'
|
|
208
|
+
stdout: Uint8Array
|
|
209
|
+
stderr: string
|
|
210
|
+
} {
|
|
211
|
+
const res = spawnSync('git', argv(args, opts), {
|
|
212
|
+
input: opts.input,
|
|
213
|
+
maxBuffer: bounds.limit,
|
|
214
|
+
timeout: bounds.timeoutMs,
|
|
215
|
+
env: childEnv(opts),
|
|
216
|
+
})
|
|
217
|
+
const code = (res.error as NodeJS.ErrnoException | undefined)?.code
|
|
218
|
+
const stdout = res.stdout ?? new Uint8Array()
|
|
219
|
+
const stderr = res.stderr?.toString('utf8') ?? ''
|
|
220
|
+
if (code === 'ETIMEDOUT') return { outcome: 'timed-out', stdout: new Uint8Array(), stderr }
|
|
221
|
+
if (
|
|
222
|
+
stdout.byteLength >= bounds.limit &&
|
|
223
|
+
(code === 'ENOBUFS' || stdout.byteLength > bounds.limit)
|
|
224
|
+
) {
|
|
225
|
+
return { outcome: 'overflowed', stdout: stdout.subarray(0, bounds.limit), stderr }
|
|
226
|
+
}
|
|
227
|
+
if (res.error || res.status !== 0) return { outcome: 'failed', stdout, stderr }
|
|
228
|
+
return { outcome: 'ok', stdout, stderr }
|
|
229
|
+
}
|
|
230
|
+
|
|
188
231
|
/** git, where a non-zero exit is a bug rather than an answer. */
|
|
189
232
|
export function gitOrThrow(args: readonly string[], opts: GitOptions = {}): GitResult {
|
|
190
233
|
const res = git(args, opts)
|
|
@@ -193,3 +236,63 @@ export function gitOrThrow(args: readonly string[], opts: GitOptions = {}): GitR
|
|
|
193
236
|
}
|
|
194
237
|
return res
|
|
195
238
|
}
|
|
239
|
+
|
|
240
|
+
/**
|
|
241
|
+
* `git` without blocking the event loop, for the one caller that runs git on
|
|
242
|
+
* the request path of a process also serving pushes: an admin seed
|
|
243
|
+
* (`src/admin.ts`), whose push runs the hooks and their network round trips.
|
|
244
|
+
* Same environment and argv rules as `git`; `input` is written to stdin.
|
|
245
|
+
*/
|
|
246
|
+
/**
|
|
247
|
+
* `gitAsync` under a deadline: the child is killed once `timeoutMs` passes and
|
|
248
|
+
* the answer says so (`timedOut`), with whatever it had written by then.
|
|
249
|
+
*
|
|
250
|
+
* For work on the request path that a caller can make arbitrarily expensive —
|
|
251
|
+
* a merge's three-way merge of two large histories (`src/merge.ts`) — where
|
|
252
|
+
* waiting it out would hold the process that also serves every push.
|
|
253
|
+
*/
|
|
254
|
+
export async function gitAsyncWithin(
|
|
255
|
+
args: readonly string[],
|
|
256
|
+
timeoutMs: number,
|
|
257
|
+
opts: GitOptions = {},
|
|
258
|
+
): Promise<GitResult & { timedOut: boolean }> {
|
|
259
|
+
const child = Bun.spawn(['git', ...argv(args, opts)], {
|
|
260
|
+
env: childEnv(opts),
|
|
261
|
+
stdin: opts.input === undefined ? 'ignore' : new TextEncoder().encode(opts.input),
|
|
262
|
+
stdout: 'pipe',
|
|
263
|
+
stderr: 'pipe',
|
|
264
|
+
})
|
|
265
|
+
let timedOut = false
|
|
266
|
+
const timer = setTimeout(
|
|
267
|
+
() => {
|
|
268
|
+
timedOut = true
|
|
269
|
+
child.kill('SIGKILL')
|
|
270
|
+
},
|
|
271
|
+
Math.max(1, timeoutMs),
|
|
272
|
+
)
|
|
273
|
+
try {
|
|
274
|
+
const [stdout, stderr, status] = await Promise.all([
|
|
275
|
+
new Response(child.stdout).text(),
|
|
276
|
+
new Response(child.stderr).text(),
|
|
277
|
+
child.exited,
|
|
278
|
+
])
|
|
279
|
+
return { status: timedOut ? 1 : status, stdout, stderr, timedOut }
|
|
280
|
+
} finally {
|
|
281
|
+
clearTimeout(timer)
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
export async function gitAsync(args: readonly string[], opts: GitOptions = {}): Promise<GitResult> {
|
|
286
|
+
const child = Bun.spawn(['git', ...argv(args, opts)], {
|
|
287
|
+
env: childEnv(opts),
|
|
288
|
+
stdin: opts.input === undefined ? 'ignore' : new TextEncoder().encode(opts.input),
|
|
289
|
+
stdout: 'pipe',
|
|
290
|
+
stderr: 'pipe',
|
|
291
|
+
})
|
|
292
|
+
const [stdout, stderr, status] = await Promise.all([
|
|
293
|
+
new Response(child.stdout).text(),
|
|
294
|
+
new Response(child.stderr).text(),
|
|
295
|
+
child.exited,
|
|
296
|
+
])
|
|
297
|
+
return { status, stdout, stderr }
|
|
298
|
+
}
|
|
@@ -19,7 +19,7 @@ import * as path from 'node:path'
|
|
|
19
19
|
|
|
20
20
|
import { capabilitiesFrom } from '../shared/capabilities'
|
|
21
21
|
import { REFUSE_ENV, ZERO_OID } from '../shared/protocol'
|
|
22
|
-
import {
|
|
22
|
+
import { publishConfigFromEnv } from './announce'
|
|
23
23
|
import { appendOnlyEnabled, checkAppendOnly } from './append-only'
|
|
24
24
|
import { configuredThreshold, isCompactionDue } from './compact'
|
|
25
25
|
import { checkSize, limitsEnforced, limitsOf, liveBytes } from './limits'
|
|
@@ -353,8 +353,11 @@ async function main(): Promise<number> {
|
|
|
353
353
|
// never reaches this line, so nobody is ever told about one. See
|
|
354
354
|
// src/announce.ts, which swallows every failure for the same reason the
|
|
355
355
|
// rest of this branch does.
|
|
356
|
-
|
|
357
|
-
|
|
356
|
+
// The push webhook (shared/webhook.ts) rides the same detached announcer,
|
|
357
|
+
// so a deployment with either configured spawns it and one with neither
|
|
358
|
+
// pays nothing.
|
|
359
|
+
const announceTo = publishConfigFromEnv()
|
|
360
|
+
if (announceTo) {
|
|
358
361
|
const changes = parseRefChanges(stdin).filter((c) => c.ref.startsWith('refs/'))
|
|
359
362
|
// What this push MERGED rides the same announcement (docs/adr/0018), so a
|
|
360
363
|
// Watcher on `main` learns a Proposal landed from the move rather than by
|