rvlib-shipkit 2.32.0 → 2.34.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 +42 -0
- package/package.json +1 -1
- package/src/advisors/advisor-view.ts +29 -7
- package/src/advisors/edge/api.ts +1 -30
- package/src/advisors/project.ts +3 -3
- package/src/advisors/sync.ts +11 -4
- package/src/advisors/users-router.ts +13 -11
- package/src/cli/cmd_BackupTargets.ts +49 -8
- package/src/cli/cmd_Capacity.ts +6 -2
- package/src/cli/cmd_Ci.ts +2 -1
- package/src/cli/cmd_Media.ts +1 -1
- package/src/cli/cmd_Shot.ts +26 -4
- package/src/cli/cmd_Start.ts +3 -3
- package/src/cli.ts +13 -2
- package/src/core/admission.ts +268 -0
- package/src/core/code-lines.ts +36 -21
- package/src/core/machine-read.ts +5 -2
- package/src/core/memory-watch.ts +1 -1
- package/src/core/peer-sk.ts +8 -0
- package/src/gate/admit-heavy.ts +150 -0
- package/src/gate/check-runner.ts +6 -0
- package/src/gate/gate-checks.ts +7 -5
- package/src/gate/head-gate.ts +1 -1
- package/src/gate/job-run.ts +2 -1
- package/src/gate/pre-commit-discovery.ts +6 -3
- package/src/gate/run-check.ts +3 -0
- package/src/gate/run-ci.ts +4 -0
- package/src/home/backup-status.ts +41 -13
- package/src/home/backup-verdict.ts +1 -0
- package/src/home/daemon-jobs.ts +5 -0
- package/src/home/home-routes.ts +3 -2
- package/src/home/house-bucket.ts +14 -0
- package/src/home/run-daemon.ts +3 -1
- package/src/home/this-house.ts +68 -0
- package/src/home/via-hub.ts +2 -1
- package/src/hooks/commit-msg-run.ts +61 -0
- package/src/hooks/commit-run.ts +16 -166
- package/src/hooks/gate-outcome.ts +108 -0
- package/src/hooks/git-hook.ts +9 -9
- package/src/hooks/hook-config.ts +2 -1
- package/src/hooks/pre-commit-checks.ts +1 -1
- package/src/hooks/run-hooks.ts +2 -1
- package/src/hooks/shared-file.ts +3 -2
- package/src/hq/backup-targets.ts +58 -5
- package/src/hq/hq-local.ts +1 -1
- package/src/media-store/backup/bucket-target.ts +58 -0
- package/src/media-store/backup/target-send.ts +7 -4
- package/src/media-store/space.ts +2 -0
- package/src/plan/planner.ts +3 -2
- package/src/repo-config.ts +8 -1
- package/src/review/answer-kinds.ts +2 -0
- package/src/review/cells.ts +40 -9
- package/src/review/format.ts +1 -1
- package/src/review/model.ts +3 -3
- package/src/review/routes.ts +2 -28
- package/src/review/store-parties.ts +28 -0
- package/src/review/store.ts +11 -2
- package/src/review/thread-state.ts +9 -3
- package/src/scaffold/project-scaffold.ts +2 -2
- package/src/secrets/copy.ts +4 -4
- package/src/serve/hub-app/auto-text.tsx +3 -1
- package/src/serve/hub-app/dock-st.ts +1 -1
- package/src/serve/hub-app/review/question-views.tsx +28 -17
- package/src/serve/hub-app/review/review-host.ts +6 -2
- package/src/serve/hub-app/review/review-list.tsx +8 -5
- package/src/serve/hub-app/review/review-st.ts +2 -2
- package/src/serve/hub-app/review/review-thread.tsx +2 -1
- package/src/serve/hub-app/review/review-views.tsx +10 -7
- package/src/serve/hub-app/review/thread-st.ts +25 -11
- package/src/serve/hub-app/review/tone-bar.tsx +29 -24
- package/src/serve/hub-app/review/tones.ts +18 -0
- package/src/serve/hub-app/review.css +11 -2
- package/src/setup-house.ts +1 -7
- package/src/shot/client.ts +2 -1
- package/src/shot/on-place.ts +141 -0
- package/src/start-repo.ts +27 -30
package/src/hooks/commit-run.ts
CHANGED
|
@@ -1,27 +1,23 @@
|
|
|
1
|
-
// the commit gates
|
|
2
|
-
//
|
|
1
|
+
// the pre-commit gates, run by the hook in ONE process: what the commit stages is read once (hooks/staged.ts) and
|
|
2
|
+
// every gate reads that, the built-ins and the repo's own module gates alike. The commit-msg gates are
|
|
3
|
+
// hooks/commit-msg-run.ts, what both share hooks/gate-outcome.ts.
|
|
3
4
|
// the one constraint a reader breaks first: the hook has 20 ms from bun's start (hooks/hook-gates.ts), so this
|
|
4
5
|
// module loads only what every commit needs; a gate that needs more imports it inside its own branch
|
|
5
|
-
import {
|
|
6
|
+
import { existsSync } from 'fs'
|
|
6
7
|
import { join } from 'path'
|
|
7
|
-
import {
|
|
8
|
-
import { maskPattern, patternFingerprint, runLeakGuard, type LeakHit, type LeakWaiver } from './leak-guard.ts'
|
|
8
|
+
import { runLeakGuard } from './leak-guard.ts'
|
|
9
9
|
import { runRootIdentity } from './root-identity.ts'
|
|
10
10
|
import { BlobReader, patchesByFile, readStagedAsync, type StagedCommit } from './staged.ts'
|
|
11
11
|
import { ALLOW_MASS_DELETE, runTreeShrink } from './tree-shrink.ts'
|
|
12
|
-
import {
|
|
12
|
+
import { hookGateOff, type HookGateId } from './hook-gates.ts'
|
|
13
|
+
import { commandGate, hitLine, importGate, moduleGate, startTimes, timeRow, waivedLines, type GateOutcome, type Timed } from './gate-outcome.ts'
|
|
13
14
|
import { heavyInCommit } from '../social/media-limit.ts'
|
|
14
15
|
import { LAYOUT } from '../core/layout.ts'
|
|
15
16
|
import { gitRoot } from '../core/git-root.ts'
|
|
16
17
|
import type { HookConfig } from './hook-config.ts'
|
|
17
18
|
import type { RepoConfig } from '../repo-config.ts'
|
|
18
19
|
|
|
19
|
-
|
|
20
|
-
export type GateOutcome = { id: string; ok: boolean; lines: string[]; ms?: number }
|
|
21
|
-
|
|
22
|
-
/** what a repo's module gate answers: `ok` false refuses the commit, and `lines` are printed when it fails or say
|
|
23
|
-
* something other than `ok:` */
|
|
24
|
-
export type GateVerdict = { ok: boolean; lines: string[] }
|
|
20
|
+
export { report, type GateOutcome, type GateVerdict, type Timed } from './gate-outcome.ts'
|
|
25
21
|
|
|
26
22
|
/** what a repo's pre-commit module gate is given: the commit's one staged read, and reads of it that cost no spawn or
|
|
27
23
|
* one for all their blobs */
|
|
@@ -39,35 +35,6 @@ export type PreCommitCtx = {
|
|
|
39
35
|
config: HookConfig
|
|
40
36
|
}
|
|
41
37
|
|
|
42
|
-
/** what a repo's commit-msg module gate is given */
|
|
43
|
-
export type CommitMsgCtx = { root: string; message: string; messageFile: string; config: HookConfig }
|
|
44
|
-
|
|
45
|
-
/** a repo module gate: `module` names a file relative to the repo root that exports `preCommit` (or `commitMsg`) */
|
|
46
|
-
type ModuleGate = { id: string; module: string }
|
|
47
|
-
|
|
48
|
-
/** a hit line: the masked pattern plus its FINGERPRINT, which is the token a
|
|
49
|
-
* waiver is written against, so nobody has to type the private word to
|
|
50
|
-
* exempt it. The file rides along for a content hit; a staged-PATH hit adds
|
|
51
|
-
* nothing, because there the path IS what matched. */
|
|
52
|
-
const hitLine = (x: LeakHit): string =>
|
|
53
|
-
` ${x.where}${x.where === 'staged content' && x.file != null ? ` ${x.file}` : ''}: ${maskPattern(x.pattern)} [${patternFingerprint(x.pattern)}]${x.over == null ? '' : `, ${x.over.found} added where ${x.over.source} allows ${x.over.count}`}`
|
|
54
|
-
|
|
55
|
-
/** what the allowlist let through, one line per waiver. An allowlist that
|
|
56
|
-
* fires invisibly is a silent weakening, so a waived match is as loud as a
|
|
57
|
-
* blocked one and carries the reason its author wrote. */
|
|
58
|
-
function waivedLines(waived: LeakWaiver[]): string[] {
|
|
59
|
-
const rows = new Map<string, { pattern: string; reason: string; source: string; targets: Set<string> }>()
|
|
60
|
-
for (const w of waived) {
|
|
61
|
-
const key = `${w.pattern} ${w.source}`
|
|
62
|
-
const row = rows.get(key) ?? { pattern: w.pattern, reason: w.reason, source: w.source, targets: new Set<string>() }
|
|
63
|
-
row.targets.add(w.file ?? w.where)
|
|
64
|
-
rows.set(key, row)
|
|
65
|
-
}
|
|
66
|
-
return [...rows.values()].map(
|
|
67
|
-
(r) => ` waived ${maskPattern(r.pattern)} [${patternFingerprint(r.pattern)}] in ${r.targets.size} target(s) — ${r.reason} (${r.source})`,
|
|
68
|
-
)
|
|
69
|
-
}
|
|
70
|
-
|
|
71
38
|
export const COMFY_DRAFTS = '.comfy-ts/drafts/'
|
|
72
39
|
|
|
73
40
|
/** the staged files the `blocked-paths` gate refuses. A repo DECLARED private
|
|
@@ -84,65 +51,6 @@ export const draftsOpen = (c: Pick<HookConfig, 'visibility'>): boolean => c.visi
|
|
|
84
51
|
|
|
85
52
|
const REPLAY_MARKERS = ['MERGE_HEAD', 'CHERRY_PICK_HEAD', 'rebase-merge', 'rebase-apply']
|
|
86
53
|
|
|
87
|
-
/** a gate's time, in ms. `owner`: who may make it cheaper or move it out of the hook: the repo (its own gate, a
|
|
88
|
-
* check that declares onPreCommit), `once` for what is read again once after its file changed (the check table,
|
|
89
|
-
* the config), or no one (a built-in commit gate, the process start, the staged read) */
|
|
90
|
-
export type Timed = { id: string; ms: number; owner?: 'repo' | 'once' }
|
|
91
|
-
|
|
92
|
-
/** what ran before the gates, named where the caller timed it (the imports, the config read), the rest as `start` */
|
|
93
|
-
function startTimes(since: number, before: Timed[] = []): Timed[] {
|
|
94
|
-
const rest = performance.now() - since - before.reduce((a, t) => a + t.ms, 0)
|
|
95
|
-
return [...before, ...(rest >= 1 ? [{ id: 'start', ms: rest }] : [])]
|
|
96
|
-
}
|
|
97
|
-
|
|
98
|
-
/** what to do about a hook over its budget, from its slowest items. Only a gate the repo owns is ever sent out of the
|
|
99
|
-
* hook: a built-in (the leak guard first) never leaves it, whatever it costs */
|
|
100
|
-
function overBudget(slowest: readonly Timed[]): string {
|
|
101
|
-
const repo = slowest.find((t) => t.owner === 'repo')
|
|
102
|
-
if (repo != null) return `make ${repo.id} cheaper, or move it to a ci task`
|
|
103
|
-
if (slowest[0]?.owner === 'once') return `${slowest[0].id} was read again after its file changed: once, the next commit is back under it`
|
|
104
|
-
return 'built-in gates never leave the hook: a large commit or a busy machine costs this, nothing is to move'
|
|
105
|
-
}
|
|
106
|
-
|
|
107
|
-
/** set it to print every gate's time on each commit */
|
|
108
|
-
export const HOOK_TIMES = 'SHIPKIT_HOOK_TIMES'
|
|
109
|
-
|
|
110
|
-
/** the hook's own time row: over the budget it WARNs naming the slowest gates, and `SHIPKIT_HOOK_TIMES=1` prints them
|
|
111
|
-
* all. `start` is what ran before the gates: the process start, the imports, the config read */
|
|
112
|
-
function timeRow(hook: string, elapsed: number, times: Timed[]): GateOutcome {
|
|
113
|
-
const words = (ts: Timed[]): string => ts.map((t) => `${t.id} ${Math.round(t.ms)}ms`).join(', ')
|
|
114
|
-
const lines: string[] = []
|
|
115
|
-
if (elapsed > HOOK_BUDGET_MS) {
|
|
116
|
-
const slowest = [...times].sort((a, b) => b.ms - a.ms).slice(0, 3)
|
|
117
|
-
lines.push(`WARN ${hook} took ${Math.round(elapsed)}ms (budget ${HOOK_BUDGET_MS}ms), slowest: ${words(slowest)}: ${overBudget(slowest)} (tools/shipkit/commit-gates.md)`)
|
|
118
|
-
}
|
|
119
|
-
if (process.env[HOOK_TIMES] === '1') lines.push(` ${hook} times: ${words(times)}`)
|
|
120
|
-
return { id: 'hook-time', ok: true, lines, ms: elapsed }
|
|
121
|
-
}
|
|
122
|
-
|
|
123
|
-
const failLines = (e: unknown): string[] => [` ${String(e instanceof Error ? e.message : e).split('\n')[0]!.slice(0, 300)}`]
|
|
124
|
-
|
|
125
|
-
/** a module gate's file, imported; `loading`: its import already started (the hook starts it while git reads) */
|
|
126
|
-
const importGate = (root: string, g: ModuleGate): Promise<Record<string, unknown>> => import(join(root, g.module)) as Promise<Record<string, unknown>>
|
|
127
|
-
|
|
128
|
-
async function moduleGate<C>(root: string, g: ModuleGate, name: 'preCommit' | 'commitMsg', ctx: C, loading = importGate(root, g)): Promise<GateOutcome> {
|
|
129
|
-
try {
|
|
130
|
-
const mod = await loading
|
|
131
|
-
const run = mod[name]
|
|
132
|
-
if (typeof run !== 'function') return { id: g.id, ok: false, lines: [`FAIL: ${g.id}: ${g.module} exports no \`${name}\` function`] }
|
|
133
|
-
const v = (await (run as (c: C) => GateVerdict | Promise<GateVerdict>)(ctx)) as GateVerdict
|
|
134
|
-
return { id: g.id, ok: v.ok, lines: v.ok ? (v.lines.length === 0 ? [`ok: ${g.id}`] : v.lines) : [`FAIL: ${g.id}`, ...v.lines] }
|
|
135
|
-
} catch (e) {
|
|
136
|
-
return { id: g.id, ok: false, lines: [`FAIL: ${g.id} threw, so it judged nothing`, ...failLines(e)] }
|
|
137
|
-
}
|
|
138
|
-
}
|
|
139
|
-
|
|
140
|
-
async function commandGate(root: string, g: { id: string; cmd: string[] }, extra: string[], timeoutMs: number): Promise<GateOutcome> {
|
|
141
|
-
const { spawnWithTimeout } = await import('../core/spawn-timeout.ts')
|
|
142
|
-
const r = await spawnWithTimeout([...g.cmd, ...extra], { cwd: root, timeoutMs })
|
|
143
|
-
return { id: g.id, ok: r.code === 0, lines: r.code === 0 ? [`ok: ${g.id}`] : [`FAIL: ${g.id} (exit ${r.code})`, ...r.out.trim().split('\n').slice(-30).map((l) => ` ${l}`)] }
|
|
144
|
-
}
|
|
145
|
-
|
|
146
54
|
/** a promise whose rejection is seen where it is awaited, never as an unhandled one while other work runs first */
|
|
147
55
|
const later = <T>(p: Promise<T>): Promise<T> => {
|
|
148
56
|
p.catch(() => {})
|
|
@@ -171,7 +79,9 @@ export async function runPreCommitWith(root: string, config: HookConfig, full: (
|
|
|
171
79
|
// only an agent's shell carries CLAUDECODE, and the shared-file gate judges nothing else: its module loads only then
|
|
172
80
|
const agent = !off('shared-file') && process.env['CLAUDECODE'] === '1'
|
|
173
81
|
const sharedModule = agent ? later(import('./shared-file.ts')) : null
|
|
174
|
-
|
|
82
|
+
// the table's module loads while git reads; its answer needs the staged names, and its time is its own
|
|
83
|
+
const discovery = later(import('../gate/pre-commit-discovery.ts'))
|
|
84
|
+
const checks = later(reading.catch(() => null).then((read) => timed('checks at commit', () => runPreCommitChecks(root, config, full, discovery, read?.names))))
|
|
175
85
|
// the shared-file gate's reads that need no staged path, while git reads; an error is the gate's to report
|
|
176
86
|
const prepared = sharedModule == null ? null : await timed('shared-file read', async () => {
|
|
177
87
|
try {
|
|
@@ -339,11 +249,11 @@ export async function runPreCommitWith(root: string, config: HookConfig, full: (
|
|
|
339
249
|
/** every `onPreCommit` check, run RAW on the working tree: no ledger, no
|
|
340
250
|
* cache, no repair. A failure refuses the commit, a pass over its budget
|
|
341
251
|
* warns by name and never blocks on time. The table answers « none » with
|
|
342
|
-
* stats alone (gate/pre-commit-discovery.ts),
|
|
343
|
-
* when one runs */
|
|
344
|
-
async function runPreCommitChecks(root: string, config: HookConfig, full: () => Promise<RepoConfig
|
|
345
|
-
const { declarationsTable, preCommitFromTable } = await
|
|
346
|
-
const known = await preCommitFromTable(root)
|
|
252
|
+
* stats alone (gate/pre-commit-discovery.ts), its walk read again only when the
|
|
253
|
+
* commit stages a unit file, and the check engine loads only when one runs */
|
|
254
|
+
async function runPreCommitChecks(root: string, config: HookConfig, full: () => Promise<RepoConfig>, discovery: Promise<typeof import('../gate/pre-commit-discovery.ts')>, names?: readonly string[]): Promise<{ outcomes: GateOutcome[]; table: TableState }> {
|
|
255
|
+
const { declarationsTable, preCommitFromTable } = await discovery
|
|
256
|
+
const known = await preCommitFromTable(root, names)
|
|
347
257
|
if (known?.length === 0) return { outcomes: [], table: 'answered' }
|
|
348
258
|
const { runPreCommitChecksFull } = await import('./pre-commit-checks.ts')
|
|
349
259
|
const { outcomes, settled } = await runPreCommitChecksFull(root, config, full)
|
|
@@ -358,63 +268,3 @@ async function runPreCommitChecks(root: string, config: HookConfig, full: () =>
|
|
|
358
268
|
/** how the check table answered: from stats alone, rebuilt once and answering the next commit, or rebuilt and still
|
|
359
269
|
* unable to answer it (every commit pays the discovery) */
|
|
360
270
|
type TableState = 'answered' | 'rebuilt' | 'unsettled'
|
|
361
|
-
|
|
362
|
-
/** the commit-msg gate: the shared message predicate, then the repo's own. */
|
|
363
|
-
export async function runCommitMsgWith(root: string, config: HookConfig, messageFile: string, o: { since?: number; before?: Timed[] } = {}): Promise<GateOutcome[]> {
|
|
364
|
-
const since = o.since ?? performance.now()
|
|
365
|
-
const times = startTimes(since, o.before)
|
|
366
|
-
const h = config.hooks ?? {}
|
|
367
|
-
const out: GateOutcome[] = []
|
|
368
|
-
const message = readFileSync(messageFile, 'utf8')
|
|
369
|
-
if (hookGateOff(config, 'commit-message') == null) {
|
|
370
|
-
const languageOff = hookGateOff(config, 'commit-language') != null
|
|
371
|
-
const offenses = commitMessageOffenses(message, { languageAllow: h.languageAllow })
|
|
372
|
-
.filter((o) => o.kind !== 'language' || !languageOff)
|
|
373
|
-
out.push(offenses.length === 0
|
|
374
|
-
? { id: 'commit-message', ok: true, lines: [`ok: commit message clean (no dash punctuation${languageOff ? '' : ', English'})`] }
|
|
375
|
-
: {
|
|
376
|
-
id: 'commit-message',
|
|
377
|
-
ok: false,
|
|
378
|
-
lines: [
|
|
379
|
-
`FAIL: commit message has ${offenses.length} offense(s)`,
|
|
380
|
-
...offenses.map((o) => ` line ${o.line}: ${o.text.slice(0, 100)}\n ${o.why}`),
|
|
381
|
-
],
|
|
382
|
-
})
|
|
383
|
-
}
|
|
384
|
-
// the leak guard also reads the MESSAGE, a private name pasted into a
|
|
385
|
-
// commit body is as public as one pasted into a file
|
|
386
|
-
if (hookGateOff(config, 'leak-guard') == null) {
|
|
387
|
-
const r = runLeakGuard(root, { keywordFile: h.keywordFile, staged: false, allow: h.leakAllow, text: [{ label: 'commit message', content: message }] })
|
|
388
|
-
if (r.status === 'hit')
|
|
389
|
-
out.push({ id: 'leak-guard', ok: false, lines: [`FAIL: leak-guard matched in the commit message`, ...r.hits.map(hitLine), ...waivedLines(r.waived)] })
|
|
390
|
-
else if (r.status === 'clean' && r.waived.length > 0)
|
|
391
|
-
out.push({ id: 'leak-guard', ok: true, lines: [`ok: leak-guard clean in the commit message (${r.waived.length} waived)`, ...waivedLines(r.waived)] })
|
|
392
|
-
}
|
|
393
|
-
if (hookGateOff(config, 'reflection-trailer') == null && /^(Fixes|Declines)-reflection:/im.test(message)) {
|
|
394
|
-
const t = performance.now()
|
|
395
|
-
const { machinePlaces, trailerErrors } = await import('../reflections/reflection-close.ts')
|
|
396
|
-
const places = await machinePlaces(root)
|
|
397
|
-
const errors = places === null ? ['no house repo on this machine: a reflection closes where its house is'] : trailerErrors(stripNonMessage(message), places)
|
|
398
|
-
out.push(errors.length === 0
|
|
399
|
-
? { id: 'reflection-trailer', ok: true, lines: ['ok: reflection trailers name open reflections'] }
|
|
400
|
-
: { id: 'reflection-trailer', ok: false, lines: [`FAIL: reflection-trailer: ${errors.length} trailer(s) name no open reflection`, ...errors.map((e) => ` ${e}`)] })
|
|
401
|
-
times.push({ id: 'reflection-trailer', ms: performance.now() - t })
|
|
402
|
-
}
|
|
403
|
-
for (const g of h.commitMsg ?? []) {
|
|
404
|
-
const t = performance.now()
|
|
405
|
-
out.push('module' in g ? await moduleGate<CommitMsgCtx>(root, g, 'commitMsg', { root, message, messageFile, config }) : await commandGate(root, g, [messageFile], 60_000))
|
|
406
|
-
times.push({ id: g.id, ms: performance.now() - t, owner: 'repo' })
|
|
407
|
-
}
|
|
408
|
-
out.push(timeRow('commit-msg', performance.now() - since, times))
|
|
409
|
-
return out
|
|
410
|
-
}
|
|
411
|
-
|
|
412
|
-
/** a gate that passed prints only what still needs a reader (a WARN, a waived
|
|
413
|
-
* hit), so a clean commit costs one line, not one per gate */
|
|
414
|
-
export const report = (out: GateOutcome[], write: (s: string) => void): number => {
|
|
415
|
-
for (const g of out) for (const l of g.lines) if (!g.ok || !l.startsWith('ok: ')) write(`${l}\n`)
|
|
416
|
-
const ok = out.every((g) => g.ok)
|
|
417
|
-
const time = out.find((g) => g.id === 'hook-time')?.ms
|
|
418
|
-
if (ok) write(`ok: ${out.filter((g) => g.id !== 'hook-time').length} commit gate(s) clean${time == null ? '' : ` in ${Math.round(time)}ms`}\n`)
|
|
419
|
-
return ok ? 0 : 1
|
|
420
|
-
}
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
// what both commit hooks share: a gate's outcome and its lines, the hook's time row, a repo's own gate run, and the
|
|
2
|
+
// report. Its own module so the commit-msg hook loads none of the pre-commit gates (hooks/commit-msg-run.ts).
|
|
3
|
+
// the one constraint a reader breaks first: every import here is paid by both hooks on every commit
|
|
4
|
+
import { join } from 'path'
|
|
5
|
+
import { maskPattern, patternFingerprint, type LeakHit, type LeakWaiver } from './leak-guard.ts'
|
|
6
|
+
import { HOOK_BUDGET_MS } from './hook-gates.ts'
|
|
7
|
+
|
|
8
|
+
/** `ms`: set on the hook's own time row (`hook-time`), which `report` folds into its last line */
|
|
9
|
+
export type GateOutcome = { id: string; ok: boolean; lines: string[]; ms?: number }
|
|
10
|
+
|
|
11
|
+
/** what a repo's module gate answers: `ok` false refuses the commit, and `lines` are printed when it fails or say
|
|
12
|
+
* something other than `ok:` */
|
|
13
|
+
export type GateVerdict = { ok: boolean; lines: string[] }
|
|
14
|
+
|
|
15
|
+
/** a repo module gate: `module` names a file relative to the repo root that exports `preCommit` (or `commitMsg`) */
|
|
16
|
+
export type ModuleGate = { id: string; module: string }
|
|
17
|
+
|
|
18
|
+
/** a gate's time, in ms. `owner`: who may make it cheaper or move it out of the hook: the repo (its own gate, a
|
|
19
|
+
* check that declares onPreCommit), `once` for what is read again once after its file changed (the check table,
|
|
20
|
+
* the config), or no one (a built-in commit gate, the process start, the staged read) */
|
|
21
|
+
export type Timed = { id: string; ms: number; owner?: 'repo' | 'once' }
|
|
22
|
+
|
|
23
|
+
/** a hit line: the masked pattern plus its FINGERPRINT, which is the token a
|
|
24
|
+
* waiver is written against, so nobody has to type the private word to
|
|
25
|
+
* exempt it. The file rides along for a content hit; a staged-PATH hit adds
|
|
26
|
+
* nothing, because there the path IS what matched. */
|
|
27
|
+
export const hitLine = (x: LeakHit): string =>
|
|
28
|
+
` ${x.where}${x.where === 'staged content' && x.file != null ? ` ${x.file}` : ''}: ${maskPattern(x.pattern)} [${patternFingerprint(x.pattern)}]${x.over == null ? '' : `, ${x.over.found} added where ${x.over.source} allows ${x.over.count}`}`
|
|
29
|
+
|
|
30
|
+
/** what the allowlist let through, one line per waiver. An allowlist that
|
|
31
|
+
* fires invisibly is a silent weakening, so a waived match is as loud as a
|
|
32
|
+
* blocked one and carries the reason its author wrote. */
|
|
33
|
+
export function waivedLines(waived: LeakWaiver[]): string[] {
|
|
34
|
+
const rows = new Map<string, { pattern: string; reason: string; source: string; targets: Set<string> }>()
|
|
35
|
+
for (const w of waived) {
|
|
36
|
+
const key = `${w.pattern} ${w.source}`
|
|
37
|
+
const row = rows.get(key) ?? { pattern: w.pattern, reason: w.reason, source: w.source, targets: new Set<string>() }
|
|
38
|
+
row.targets.add(w.file ?? w.where)
|
|
39
|
+
rows.set(key, row)
|
|
40
|
+
}
|
|
41
|
+
return [...rows.values()].map(
|
|
42
|
+
(r) => ` waived ${maskPattern(r.pattern)} [${patternFingerprint(r.pattern)}] in ${r.targets.size} target(s) — ${r.reason} (${r.source})`,
|
|
43
|
+
)
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** what ran before the gates, named where the caller timed it (the imports, the config read), the rest as `start` */
|
|
47
|
+
export function startTimes(since: number, before: Timed[] = []): Timed[] {
|
|
48
|
+
const rest = performance.now() - since - before.reduce((a, t) => a + t.ms, 0)
|
|
49
|
+
return [...before, ...(rest >= 1 ? [{ id: 'start', ms: rest }] : [])]
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** what to do about a hook over its budget, from its slowest items. Only a gate the repo owns is ever sent out of the
|
|
53
|
+
* hook: a built-in (the leak guard first) never leaves it, whatever it costs */
|
|
54
|
+
function overBudget(slowest: readonly Timed[]): string {
|
|
55
|
+
const repo = slowest.find((t) => t.owner === 'repo')
|
|
56
|
+
if (repo != null) return `make ${repo.id} cheaper, or move it to a ci task`
|
|
57
|
+
if (slowest[0]?.owner === 'once') return `${slowest[0].id} was read again after its file changed: once, the next commit is back under it`
|
|
58
|
+
return 'built-in gates never leave the hook: a large commit or a busy machine costs this, nothing is to move'
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** set it to print every gate's time on each commit */
|
|
62
|
+
export const HOOK_TIMES = 'SHIPKIT_HOOK_TIMES'
|
|
63
|
+
|
|
64
|
+
/** the hook's own time row: over the budget it WARNs naming the slowest gates, and `SHIPKIT_HOOK_TIMES=1` prints them
|
|
65
|
+
* all. `start` is what ran before the gates: the process start, the imports, the config read */
|
|
66
|
+
export function timeRow(hook: string, elapsed: number, times: Timed[]): GateOutcome {
|
|
67
|
+
const words = (ts: Timed[]): string => ts.map((t) => `${t.id} ${Math.round(t.ms)}ms`).join(', ')
|
|
68
|
+
const lines: string[] = []
|
|
69
|
+
if (elapsed > HOOK_BUDGET_MS) {
|
|
70
|
+
const slowest = [...times].sort((a, b) => b.ms - a.ms).slice(0, 3)
|
|
71
|
+
lines.push(`WARN ${hook} took ${Math.round(elapsed)}ms (budget ${HOOK_BUDGET_MS}ms), slowest: ${words(slowest)}: ${overBudget(slowest)} (tools/shipkit/commit-gates.md)`)
|
|
72
|
+
}
|
|
73
|
+
if (process.env[HOOK_TIMES] === '1') lines.push(` ${hook} times: ${words(times)}`)
|
|
74
|
+
return { id: 'hook-time', ok: true, lines, ms: elapsed }
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
const failLines = (e: unknown): string[] => [` ${String(e instanceof Error ? e.message : e).split('\n')[0]!.slice(0, 300)}`]
|
|
78
|
+
|
|
79
|
+
/** a module gate's file, imported; the hook starts it while git reads */
|
|
80
|
+
export const importGate = (root: string, g: ModuleGate): Promise<Record<string, unknown>> => import(join(root, g.module)) as Promise<Record<string, unknown>>
|
|
81
|
+
|
|
82
|
+
export async function moduleGate<C>(root: string, g: ModuleGate, name: 'preCommit' | 'commitMsg', ctx: C, loading = importGate(root, g)): Promise<GateOutcome> {
|
|
83
|
+
try {
|
|
84
|
+
const mod = await loading
|
|
85
|
+
const run = mod[name]
|
|
86
|
+
if (typeof run !== 'function') return { id: g.id, ok: false, lines: [`FAIL: ${g.id}: ${g.module} exports no \`${name}\` function`] }
|
|
87
|
+
const v = (await (run as (c: C) => GateVerdict | Promise<GateVerdict>)(ctx)) as GateVerdict
|
|
88
|
+
return { id: g.id, ok: v.ok, lines: v.ok ? (v.lines.length === 0 ? [`ok: ${g.id}`] : v.lines) : [`FAIL: ${g.id}`, ...v.lines] }
|
|
89
|
+
} catch (e) {
|
|
90
|
+
return { id: g.id, ok: false, lines: [`FAIL: ${g.id} threw, so it judged nothing`, ...failLines(e)] }
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export async function commandGate(root: string, g: { id: string; cmd: string[] }, extra: string[], timeoutMs: number): Promise<GateOutcome> {
|
|
95
|
+
const { spawnWithTimeout } = await import('../core/spawn-timeout.ts')
|
|
96
|
+
const r = await spawnWithTimeout([...g.cmd, ...extra], { cwd: root, timeoutMs })
|
|
97
|
+
return { id: g.id, ok: r.code === 0, lines: r.code === 0 ? [`ok: ${g.id}`] : [`FAIL: ${g.id} (exit ${r.code})`, ...r.out.trim().split('\n').slice(-30).map((l) => ` ${l}`)] }
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** a gate that passed prints only what still needs a reader (a WARN, a waived
|
|
101
|
+
* hit), so a clean commit costs one line, not one per gate */
|
|
102
|
+
export const report = (out: GateOutcome[], write: (s: string) => void): number => {
|
|
103
|
+
for (const g of out) for (const l of g.lines) if (!g.ok || !l.startsWith('ok: ')) write(`${l}\n`)
|
|
104
|
+
const ok = out.every((g) => g.ok)
|
|
105
|
+
const time = out.find((g) => g.id === 'hook-time')?.ms
|
|
106
|
+
if (ok) write(`ok: ${out.filter((g) => g.id !== 'hook-time').length} commit gate(s) clean${time == null ? '' : ` in ${Math.round(time)}ms`}\n`)
|
|
107
|
+
return ok ? 0 : 1
|
|
108
|
+
}
|
package/src/hooks/git-hook.ts
CHANGED
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
import { existsSync, realpathSync, writeSync } from 'fs'
|
|
7
7
|
import { join } from 'path'
|
|
8
8
|
import { readStagedAsync, STAGED_STDIN, stagedFromStdin } from './staged.ts'
|
|
9
|
-
import type { Timed } from './
|
|
9
|
+
import type { Timed } from './gate-outcome.ts'
|
|
10
10
|
|
|
11
11
|
// the process start and the static import, before the first line runs
|
|
12
12
|
const loaded = performance.now()
|
|
@@ -24,25 +24,25 @@ async function oneCopy(): Promise<void> {
|
|
|
24
24
|
;(await import('../core/one-lib.ts')).installOneLib()
|
|
25
25
|
}
|
|
26
26
|
|
|
27
|
-
/**
|
|
28
|
-
async function load() {
|
|
27
|
+
/** one hook's gates and the config fields, loaded while git runs; `before`: what that took, for the hook's time line */
|
|
28
|
+
async function load<G>(gates: () => Promise<G>) {
|
|
29
29
|
await oneCopy()
|
|
30
|
-
const [
|
|
30
|
+
const [g, { loadHookConfig }, { report }] = await Promise.all([gates(), import('./hook-config.ts'), import('./gate-outcome.ts')])
|
|
31
31
|
const imported = performance.now()
|
|
32
32
|
const c = await loadHookConfig(root)
|
|
33
33
|
const before: Timed[] = [{ id: 'boot', ms: loaded }, { id: 'imports', ms: imported - loaded }, c.fromCopy ? { id: 'config', ms: performance.now() - imported } : { id: 'config load', ms: performance.now() - imported, ...(c.wrote ? { owner: 'once' as const } : {}) }]
|
|
34
|
-
return { gates, config: c.config, full: c.full, before }
|
|
34
|
+
return { gates: g, report, config: c.config, full: c.full, before }
|
|
35
35
|
}
|
|
36
36
|
|
|
37
37
|
if (hook === 'pre-commit') {
|
|
38
38
|
// the hook body pipes git's read in (hooks/run-hooks.ts): git ran while bun started. Run by hand, it reads git itself
|
|
39
39
|
const staged = file === STAGED_STDIN ? stagedFromStdin(root) : readStagedAsync(root)
|
|
40
40
|
staged.catch(() => {})
|
|
41
|
-
const { gates, config, full, before } = await load()
|
|
42
|
-
process.exitCode =
|
|
41
|
+
const { gates, report, config, full, before } = await load(() => import('./commit-run.ts'))
|
|
42
|
+
process.exitCode = report(await gates.runPreCommitWith(root, config, full, { since: 0, before, staged }), write)
|
|
43
43
|
} else if (hook === 'commit-msg' && file != null) {
|
|
44
|
-
const { gates, config, before } = await load()
|
|
45
|
-
process.exitCode =
|
|
44
|
+
const { gates, report, config, before } = await load(() => import('./commit-msg-run.ts'))
|
|
45
|
+
process.exitCode = report(await gates.runCommitMsgWith(root, config, file, { since: 0, before }), write)
|
|
46
46
|
} else {
|
|
47
47
|
console.error(`usage: bun ${import.meta.path} pre-commit | commit-msg <message file>`)
|
|
48
48
|
process.exitCode = 2
|
package/src/hooks/hook-config.ts
CHANGED
|
@@ -8,7 +8,6 @@
|
|
|
8
8
|
// when repo.config.ts itself changes (or the copy is dropped); a field that is not plain data is never copied, and
|
|
9
9
|
// such a config is loaded whole on every commit
|
|
10
10
|
import { mkdirSync, readFileSync } from 'fs'
|
|
11
|
-
import { atomicWrite } from '../core/atomic-write.ts'
|
|
12
11
|
import { dirname, join } from 'path'
|
|
13
12
|
import { gitRoot } from '../core/git-root.ts'
|
|
14
13
|
import type { RepoConfig } from '../repo-config.ts'
|
|
@@ -93,6 +92,8 @@ export async function loadHookConfig(root: string): Promise<{ config: HookConfig
|
|
|
93
92
|
const keys = Object.keys(copies.copies)
|
|
94
93
|
for (const k of keys.slice(0, Math.max(0, keys.length - COPIES_MAX))) delete copies.copies[k]
|
|
95
94
|
mkdirSync(dirname(copy), { recursive: true })
|
|
95
|
+
// loaded only here: a commit that reads the copy writes nothing
|
|
96
|
+
const { atomicWrite } = await import('../core/atomic-write.ts')
|
|
96
97
|
atomicWrite(copy, JSON.stringify(copies))
|
|
97
98
|
wrote = true
|
|
98
99
|
} catch {
|
|
@@ -9,7 +9,7 @@ import { runCheckBody, type CheckDef } from '../check.ts'
|
|
|
9
9
|
import { repoOff } from '../core/when.ts'
|
|
10
10
|
import { formatLine } from '../core/wire.ts'
|
|
11
11
|
import type { RepoConfig } from '../repo-config.ts'
|
|
12
|
-
import type { GateOutcome } from './
|
|
12
|
+
import type { GateOutcome } from './gate-outcome.ts'
|
|
13
13
|
import type { HookConfig } from './hook-config.ts'
|
|
14
14
|
|
|
15
15
|
/** the checks that declare `onPreCommit` and apply here, with their budget */
|
package/src/hooks/run-hooks.ts
CHANGED
|
@@ -15,7 +15,8 @@ import { FOREIGN_HOOKS, FOREIGN_WHY, isForeign } from '../core/foreign.ts'
|
|
|
15
15
|
import type { RepoConfig } from '../repo-config.ts'
|
|
16
16
|
import { gitBin } from '../core/git-bin.ts'
|
|
17
17
|
import { HOOK_BUDGET_MS, hookGateOff, type HookGateId } from './hook-gates.ts'
|
|
18
|
-
import { blockedStaged, COMFY_DRAFTS, draftsOpen,
|
|
18
|
+
import { blockedStaged, COMFY_DRAFTS, draftsOpen, runPreCommitWith, type GateOutcome } from './commit-run.ts'
|
|
19
|
+
import { runCommitMsgWith } from './commit-msg-run.ts'
|
|
19
20
|
import type { PreCommitCheck } from './pre-commit-checks.ts'
|
|
20
21
|
import { DIFF_FLAGS, STAGED_END, STAGED_STDIN } from './staged.ts'
|
|
21
22
|
|
package/src/hooks/shared-file.ts
CHANGED
|
@@ -10,14 +10,12 @@
|
|
|
10
10
|
import { readFileSync, realpathSync, statSync } from 'fs'
|
|
11
11
|
import { homedir } from 'os'
|
|
12
12
|
import { basename, dirname, join } from 'path'
|
|
13
|
-
import { sessionRecords } from '../agent-time/claude-sessions.ts'
|
|
14
13
|
import { laneNameOf } from '../agent-time/lane-name.ts'
|
|
15
14
|
import { gitBin } from '../core/git-bin.ts'
|
|
16
15
|
import { EDIT_MATCHER, hasEditGuard } from './edit-guard.ts'
|
|
17
16
|
import { heldNow, markJudged, type Committing } from './held-calls.ts'
|
|
18
17
|
import type { Staged } from './staged.ts'
|
|
19
18
|
import { readWrites, seenOf, writerKey, writesByName, type Write, type Writer } from './write-log.ts'
|
|
20
|
-
import { pidAlive } from '../core/pid-alive.ts'
|
|
21
19
|
|
|
22
20
|
/** the joint commit two lanes agreed on: the other writers, by the names the refusal prints */
|
|
23
21
|
export const COMMIT_WITH = 'SHIPKIT_COMMIT_WITH'
|
|
@@ -53,6 +51,9 @@ export function writerState(w: Writer, lastNote = 0): WriterState {
|
|
|
53
51
|
const transcript = w.tp == null ? null : w.a == null ? w.tp : join(w.tp.replace(/\.jsonl$/, ''), 'subagents', `agent-${w.a}.jsonl`)
|
|
54
52
|
let heard = lastNote
|
|
55
53
|
try { if (transcript != null) heard = Math.max(heard, statSync(transcript).mtimeMs) } catch { /* no transcript: its notes date it */ }
|
|
54
|
+
// loaded here, never at the module's import: only a contested file asks it, and a commit with none loads none of it
|
|
55
|
+
const { sessionRecords } = require('../agent-time/claude-sessions.ts') as typeof import('../agent-time/claude-sessions.ts')
|
|
56
|
+
const { pidAlive } = require('../core/pid-alive.ts') as typeof import('../core/pid-alive.ts')
|
|
56
57
|
const records = sessionRecords(config)
|
|
57
58
|
if (records.length === 0) return { state: 'unknown', heard }
|
|
58
59
|
const live = records.filter((r) => r.sessionId === w.s && pidAlive(r.pid))
|
package/src/hq/backup-targets.ts
CHANGED
|
@@ -3,31 +3,72 @@
|
|
|
3
3
|
//
|
|
4
4
|
// The constraint a reader breaks first: a row never holds a secret, and never a second copy of an address the house
|
|
5
5
|
// config already owns. A bucket the config names (the Space, its second place) is a row that names that config key;
|
|
6
|
-
// only a place with no other owner (an ssh machine, a bucket added by hand) holds its own address
|
|
6
|
+
// only a place with no other owner (an ssh machine, a bucket added by hand) holds its own address, and the names of the
|
|
7
|
+
// two secrets of its key
|
|
7
8
|
import type { Database } from 'bun:sqlite'
|
|
9
|
+
import type { KeyPairNames } from '../secrets/key-pair.ts'
|
|
10
|
+
import { SECRET_NAME } from '../secrets/name.ts'
|
|
8
11
|
|
|
9
12
|
/** where a target's address lives: a key of the house config's `serve`, or the row itself */
|
|
10
13
|
export type TargetAddress =
|
|
11
14
|
| { kind: 's3'; config: 'mediaSpace' | 'spaceCopy' }
|
|
15
|
+
| BucketAddress
|
|
12
16
|
| { kind: 'ssh'; host: string; folder: string }
|
|
13
17
|
|
|
18
|
+
/** a bucket added by hand, at any S3 server: its origin, and the names of the two secrets of its key */
|
|
19
|
+
export type BucketAddress = {
|
|
20
|
+
kind: 's3'
|
|
21
|
+
/** the origin, the bucket in its host or in its path (`path`) */
|
|
22
|
+
endpoint: string
|
|
23
|
+
bucket: string
|
|
24
|
+
region: string
|
|
25
|
+
/** the bucket in the path, not the host: MinIO, R2 and any server at one origin want it */
|
|
26
|
+
path?: boolean
|
|
27
|
+
key: KeyPairNames
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** the bucket a row holds itself, null for a machine and for a bucket the house config owns */
|
|
31
|
+
export const ownBucket = (a: TargetAddress): BucketAddress | null => (a.kind === 's3' && !('config' in a) ? a : null)
|
|
32
|
+
/** the config key that owns a row's bucket, null for a machine and for a bucket the row holds itself */
|
|
33
|
+
export const configBucket = (a: TargetAddress): 'mediaSpace' | 'spaceCopy' | null => (a.kind === 's3' && 'config' in a ? a.config : null)
|
|
34
|
+
|
|
14
35
|
export type BackupTarget = { id: string; label: string; on: boolean; at: number; address: TargetAddress }
|
|
15
36
|
|
|
16
37
|
export const TARGETS_SCHEMA = 'create table if not exists backup_targets (id text primary key, label text not null, address text not null, on_ integer not null, at integer not null) without rowid;'
|
|
17
38
|
|
|
18
39
|
const ID = /^[a-z0-9][a-z0-9-]{0,39}$/
|
|
40
|
+
const BUCKET = /^[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]$/
|
|
41
|
+
const REGION = /^[A-Za-z0-9-]{1,40}$/
|
|
19
42
|
const HOST = /^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/
|
|
20
43
|
/** a folder under the target's home: `~/` then plain names, never `..` */
|
|
21
44
|
const FOLDER = /^~\/(?:[A-Za-z0-9._-]+\/)*[A-Za-z0-9._-]+$/
|
|
22
45
|
|
|
23
46
|
/** why an address cannot be stored, null when it can */
|
|
24
47
|
export function addressProblem(a: TargetAddress): string | null {
|
|
25
|
-
if (a.kind === 's3') return a.config === 'mediaSpace' || a.config === 'spaceCopy' ? null : 'an s3 target names serve.mediaSpace or serve.spaceCopy'
|
|
48
|
+
if (a.kind === 's3') return 'config' in a ? (a.config === 'mediaSpace' || a.config === 'spaceCopy' ? null : 'an s3 target names serve.mediaSpace or serve.spaceCopy') : bucketProblemOf(a)
|
|
26
49
|
if (!HOST.test(a.host)) return `${JSON.stringify(a.host)}: an ssh host of letters, digits, dots, dashes`
|
|
27
50
|
if (!FOLDER.test(a.folder) || a.folder.split('/').includes('..')) return `${JSON.stringify(a.folder)}: a folder under the home, ~/a/b`
|
|
28
51
|
return null
|
|
29
52
|
}
|
|
30
53
|
|
|
54
|
+
const LOOPBACK = new Set(['127.0.0.1', 'localhost', '[::1]'])
|
|
55
|
+
/** why a bucket's address cannot be stored, null when it can: a copy of the house's data never goes over plain http */
|
|
56
|
+
function bucketProblemOf(a: BucketAddress): string | null {
|
|
57
|
+
let origin: URL
|
|
58
|
+
try {
|
|
59
|
+
origin = new URL(a.endpoint)
|
|
60
|
+
} catch {
|
|
61
|
+
return `${JSON.stringify(a.endpoint)}: the origin of an S3 server, https://s3.example.com`
|
|
62
|
+
}
|
|
63
|
+
if (origin.protocol !== 'https:' && !(origin.protocol === 'http:' && LOOPBACK.has(origin.hostname))) return `${a.endpoint}: not https`
|
|
64
|
+
if (origin.username !== '' || origin.password !== '') return 'the endpoint carries a password: store it as a secret and name it'
|
|
65
|
+
if (origin.origin !== a.endpoint.replace(/\/$/, '')) return `${a.endpoint}: the origin alone, ${origin.origin}, with no path`
|
|
66
|
+
if (!BUCKET.test(a.bucket)) return `${JSON.stringify(a.bucket)}: a bucket of 3 to 63 lowercase letters, digits, dots, dashes`
|
|
67
|
+
if (!REGION.test(a.region)) return `${JSON.stringify(a.region)}: a region of letters, digits, dashes (auto, us-east-1)`
|
|
68
|
+
for (const n of [a.key?.accessKeyId, a.key?.secretAccessKey]) if (typeof n !== 'string' || !SECRET_NAME.test(n)) return 'a bucket names the two secrets of its key: the access key id and the secret access key'
|
|
69
|
+
return null
|
|
70
|
+
}
|
|
71
|
+
|
|
31
72
|
/** every target, in the order they were added */
|
|
32
73
|
export function listTargets(db: Database): BackupTarget[] {
|
|
33
74
|
const has = db.query("select 1 from sqlite_master where type = 'table' and name = 'backup_targets'").get() != null
|
|
@@ -57,9 +98,21 @@ export function removeTarget(db: Database, id: string): { removed: boolean } {
|
|
|
57
98
|
return { removed: db.query('delete from backup_targets where id = ?').run(id).changes > 0 }
|
|
58
99
|
}
|
|
59
100
|
|
|
101
|
+
/** what the config says of a bucket it names, for the first label of its row; null for a bucket it does not name */
|
|
102
|
+
export type SeedBucket = { endpoint?: string; region: string }
|
|
103
|
+
export type SeedFrom = { mediaSpace: SeedBucket | null; spaceCopy: SeedBucket | null }
|
|
104
|
+
|
|
105
|
+
/** the id and label a provider's bucket starts with, read from its origin; `auto` is the region of R2 alone */
|
|
106
|
+
function seedName(b: SeedBucket, other: { id: string; label: string }): { id: string; label: string } {
|
|
107
|
+
const host = b.endpoint == null || !URL.canParse(b.endpoint) ? '' : new URL(b.endpoint).hostname
|
|
108
|
+
if (host.endsWith('.digitaloceanspaces.com')) return { id: 'do-space', label: 'DigitalOcean Space' }
|
|
109
|
+
if (host.endsWith('.r2.cloudflarestorage.com') || (host === '' && b.region === 'auto')) return { id: 'cf-r2', label: 'Cloudflare R2' }
|
|
110
|
+
return other
|
|
111
|
+
}
|
|
112
|
+
|
|
60
113
|
/** the house's targets the first time: the Space, and its second place when the config names one; a machine is added
|
|
61
114
|
* by hand. Only into an empty table, so a row the owner removed never comes back by itself */
|
|
62
|
-
export function seedTargets(db: Database, o:
|
|
115
|
+
export function seedTargets(db: Database, o: SeedFrom & { now: number }): BackupTarget[] {
|
|
63
116
|
if (listTargets(db).length > 0) return []
|
|
64
117
|
const out: BackupTarget[] = []
|
|
65
118
|
const put = (t: Parameters<typeof putTarget>[1], at: number): void => {
|
|
@@ -67,8 +120,8 @@ export function seedTargets(db: Database, o: { mediaSpace: boolean; spaceCopy: b
|
|
|
67
120
|
if (!('refused' in r)) out.push(r)
|
|
68
121
|
}
|
|
69
122
|
db.transaction(() => {
|
|
70
|
-
if (o.mediaSpace) put({ id: '
|
|
71
|
-
if (o.spaceCopy) put({ id: '
|
|
123
|
+
if (o.mediaSpace) put({ ...seedName(o.mediaSpace, { id: 'space', label: 'the Space' }), address: { kind: 's3', config: 'mediaSpace' } }, o.now)
|
|
124
|
+
if (o.spaceCopy) put({ ...seedName(o.spaceCopy, { id: 'space-copy', label: 'the second place' }), address: { kind: 's3', config: 'spaceCopy' } }, o.now + 1)
|
|
72
125
|
}).immediate()
|
|
73
126
|
return out
|
|
74
127
|
}
|
package/src/hq/hq-local.ts
CHANGED
|
@@ -355,7 +355,7 @@ export function setHqPort(open: boolean): { open: boolean; port: number } | Refu
|
|
|
355
355
|
* writer of its file: the door opened or closed, a join code for another machine, the end of a node, a prompt
|
|
356
356
|
* forgotten, a switch wanted of another machine */
|
|
357
357
|
/** what the first list of backup targets is seeded from, which the daemon reads in the house (backup-targets.ts) */
|
|
358
|
-
export type TargetSeed = () => Promise<
|
|
358
|
+
export type TargetSeed = () => Promise<import('./backup-targets.ts').SeedFrom>
|
|
359
359
|
|
|
360
360
|
export async function hqAdminRoute(req: Request, path: string, now: number = Date.now(), o: { seed?: TargetSeed } = {}): Promise<Response | null> {
|
|
361
361
|
if (!path.startsWith('/api/home/hq/') || req.method !== 'POST') return null
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
// a bucket added by hand as a place for copies (wiki tools/shipkit/media-store-backup.md, Targets): any S3 server, its
|
|
2
|
+
// address in the hq's row, its key pair read through the house store and held in memory only. A copy goes up under
|
|
3
|
+
// `_snapshots/<store>/<machine>/`, its name carrying 12 of its sha, and a copy read back is compared with that name.
|
|
4
|
+
import { mkdirSync } from 'node:fs'
|
|
5
|
+
import { join } from 'node:path'
|
|
6
|
+
import { atomicWrite } from '../../core/atomic-write.ts'
|
|
7
|
+
import type { BucketAddress } from '../../hq/backup-targets.ts'
|
|
8
|
+
import { readKeyPair } from '../../secrets/key-pair.ts'
|
|
9
|
+
import { putStream } from '../copy/stream.ts'
|
|
10
|
+
import { signedFetch, spaceOf, type SpaceConfig } from '../space.ts'
|
|
11
|
+
import { COPY_NAME, SAFE, sha256 } from './ssh-target.ts'
|
|
12
|
+
|
|
13
|
+
/** the bucket as a config the S3 calls sign with, or why it cannot be reached: a key half that is not stored */
|
|
14
|
+
export async function bucketConfig(a: BucketAddress, read: (name: string) => Promise<string>): Promise<SpaceConfig | { why: string }> {
|
|
15
|
+
try {
|
|
16
|
+
return { endpoint: a.endpoint, bucket: a.bucket, region: a.region, ...(a.path === true ? { path: true } : {}), cdn: null, creds: await readKeyPair(a.key, read) }
|
|
17
|
+
} catch (e) {
|
|
18
|
+
return { why: `no key yet: ${(e as Error).message}` }
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export const bucketPut = async (c: SpaceConfig, key: string, bytes: Uint8Array): Promise<void> => void (await putStream(c, key, new Blob([bytes.slice()]).stream(), { max: bytes.length }))
|
|
23
|
+
|
|
24
|
+
/** the folder of one store's copies of one machine */
|
|
25
|
+
export const copiesDir = (store: string, machine: string): string => `_snapshots/${store}/${machine}/`
|
|
26
|
+
|
|
27
|
+
/** what a bucket answers to one small object written and read back: null when it gave the same bytes */
|
|
28
|
+
export async function bucketProblem(c: SpaceConfig, machine: string, now = Date.now()): Promise<string | null> {
|
|
29
|
+
if (!SAFE.test(machine)) return `${machine}: not a safe folder name`
|
|
30
|
+
const key = `${copiesDir('check', machine)}check.txt`
|
|
31
|
+
const bytes = new TextEncoder().encode(`shipkit ${now}\n`)
|
|
32
|
+
try {
|
|
33
|
+
await bucketPut(c, key, bytes)
|
|
34
|
+
const r = await signedFetch(c, 'GET', key, {})
|
|
35
|
+
if (!r.ok) return `it took an object and does not read it back: ${r.status}`
|
|
36
|
+
return sha256(new Uint8Array(await r.arrayBuffer())) === sha256(bytes) ? null : 'it gave other bytes back than the ones written'
|
|
37
|
+
} catch (e) {
|
|
38
|
+
return (e as Error).message
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** the newest copy of a store written back under `to`, its bytes compared with the sha its name carries; an `.gz` one
|
|
43
|
+
* is gunzipped beside it. Throws with its reason, and leaves no file of a copy that did not match */
|
|
44
|
+
export async function getNewest(c: SpaceConfig, o: { store: string; machine: string; to: string }): Promise<{ key: string; file: string; bytes: number }> {
|
|
45
|
+
const names = (await spaceOf(c).list(copiesDir(o.store, o.machine))).map((x) => x.key.slice(copiesDir(o.store, o.machine).length)).filter((n) => COPY_NAME.test(n)).sort()
|
|
46
|
+
const name = names.at(-1)
|
|
47
|
+
if (name == null) throw new Error(`no copy of ${o.store} from ${o.machine} in ${c.bucket}`)
|
|
48
|
+
const key = `${copiesDir(o.store, o.machine)}${name}`
|
|
49
|
+
const r = await signedFetch(c, 'GET', key, {})
|
|
50
|
+
if (!r.ok) throw new Error(`${key} does not read back: ${r.status}`)
|
|
51
|
+
const bytes = new Uint8Array(await r.arrayBuffer())
|
|
52
|
+
if (sha256(bytes).slice(0, 12) !== COPY_NAME.exec(name)![2]) throw new Error(`${key} came back with other bytes than the ones that went up`)
|
|
53
|
+
const out = name.endsWith('.gz') ? Bun.gunzipSync(bytes) : bytes
|
|
54
|
+
const file = join(o.to, `${o.store}-${name.replace(/\.gz$/, '')}`)
|
|
55
|
+
mkdirSync(o.to, { recursive: true })
|
|
56
|
+
atomicWrite(file, out, { mode: 0o600 })
|
|
57
|
+
return { key, file, bytes: out.length }
|
|
58
|
+
}
|