rvlib-shipkit 2.11.0 → 2.13.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 +56 -12
- package/README.md +1 -1
- package/package.json +4 -2
- package/src/agent-time/store.ts +2 -2
- package/src/check.ts +1 -1
- package/src/checks/SK001-package-json-shape.check.ts +4 -0
- package/src/checks/SK003-claude-md-shape.check.ts +1 -1
- package/src/checks/SK004-gitignore-policy.check.ts +27 -2
- package/src/checks/SK005-rvlib-versions.check.ts +1 -1
- package/src/checks/SK008-reviewer-agent.check.ts +2 -2
- package/src/checks/SK012-config-barrel-import.check.ts +1 -1
- package/src/checks/SK015-nested-repo.check.ts +1 -1
- package/src/checks/SK035-public-clean.check.ts +46 -0
- package/src/checks/SK036-draft-media-size.check.ts +28 -0
- package/src/cli/cmd_Backup.ts +152 -0
- package/src/cli/cmd_Ci.ts +8 -11
- package/src/cli/cmd_Drill.ts +145 -0
- package/src/cli/cmd_Home.ts +50 -3
- package/src/cli/cmd_Media.ts +96 -5
- package/src/cli/cmd_Review.ts +8 -2
- package/src/cli/cmd_Shot.ts +5 -2
- package/src/cli/cmd_Smoke.ts +4 -1
- package/src/cli/cmd_Social.ts +226 -0
- package/src/cli/cmd_Start.ts +1 -1
- package/src/cli/cmd_Time.ts +1 -1
- package/src/cli/cmd_Trailer.ts +9 -2
- package/src/cli/cmd_Veille.ts +173 -0
- package/src/cli/family-pages.ts +3 -0
- package/src/cli/registry.ts +13 -2
- package/src/cli.ts +5 -2
- package/src/collections/actions.ts +1 -49
- package/src/collections/checks.ts +2 -1
- package/src/collections/collection-types.ts +11 -2
- package/src/collections/providers.ts +4 -4
- package/src/collections/review.ts +2 -1
- package/src/collections/tests.ts +19 -8
- package/src/contracts/apply-contracts.ts +1 -3
- package/src/contracts/contract-manifests.ts +2 -3
- package/src/contracts/contract-types.ts +0 -1
- package/src/contracts/contracts-engine.ts +0 -3
- package/src/core/app-icon.ts +9 -3
- package/src/core/bun-builtins.ts +2 -2
- package/src/core/discover-checks.ts +37 -5
- package/src/core/fix-scope.ts +4 -2
- package/src/core/floor-resolve.ts +68 -48
- package/src/core/floor.ts +9 -0
- package/src/core/git-root.ts +24 -0
- package/src/core/last-good.ts +3 -1
- package/src/core/layout.ts +8 -0
- package/src/core/log-stamp.ts +36 -0
- package/src/core/loop-watch.ts +93 -0
- package/src/core/machine-link.ts +134 -0
- package/src/core/memory-watch.ts +41 -0
- package/src/core/one-way-in-policy.ts +27 -19
- package/src/core/run-ci.ts +6 -8
- package/src/core/run-fixers.ts +9 -9
- package/src/core/slots.ts +21 -0
- package/src/core/tree-rev.ts +60 -0
- package/src/core/unit-files.ts +42 -0
- package/src/drill/render.ts +140 -0
- package/src/drill/run.ts +269 -0
- package/src/fleet/scan-fleet.ts +6 -5
- package/src/home/daemon-jobs.ts +201 -0
- package/src/home/global-context.ts +34 -1
- package/src/home/home-routes.ts +22 -15
- package/src/home/hubs.ts +10 -3
- package/src/home/inbox-shape.ts +61 -6
- package/src/home/inbox.ts +75 -4
- package/src/home/lib-watch.ts +10 -3
- package/src/home/machine-stores.ts +15 -29
- package/src/home/run-daemon.ts +15 -18
- package/src/home/run-pm.ts +2 -0
- package/src/home/serve-daemon.ts +4 -3
- package/src/home/serve-web.ts +110 -1
- package/src/hooks/commit-message.ts +28 -19
- package/src/hooks/leak-guard.ts +10 -3
- package/src/hooks/run-hooks.ts +2 -6
- package/src/identities/identities.ts +334 -0
- package/src/identities/machine-route.ts +126 -0
- package/src/identities/machine.ts +62 -0
- package/src/init-repo.ts +1 -1
- package/src/ledger/check-stats.ts +10 -9
- package/src/ledger/gate-checks.ts +32 -1
- package/src/ledger/record-kept.ts +112 -0
- package/src/ledger/repo-view.ts +10 -0
- package/src/ledger/run-log.ts +17 -12
- package/src/ledger/run-timeline.ts +8 -4
- package/src/ledger/store.ts +7 -0
- package/src/ledger/suite-log.ts +17 -13
- package/src/media-kinds.ts +9 -1
- package/src/media-store/backup/daemon.ts +73 -0
- package/src/media-store/backup/keys.ts +25 -0
- package/src/media-store/backup/manifest.ts +193 -0
- package/src/media-store/backup/restore.ts +192 -0
- package/src/media-store/backup/run.ts +278 -0
- package/src/media-store/backup/secret.ts +86 -0
- package/src/media-store/backup/snapshot.ts +64 -0
- package/src/media-store/backup/sources.ts +199 -0
- package/src/media-store/content.ts +11 -1
- package/src/media-store/daemon.ts +56 -70
- package/src/media-store/hand.ts +58 -0
- package/src/media-store/put.ts +122 -0
- package/src/media-store/space.ts +73 -11
- package/src/pages/forward.ts +35 -0
- package/src/pages/frame-client.ts +118 -0
- package/src/pages/routes.ts +29 -0
- package/src/pages/unit.ts +92 -0
- package/src/plan/planner.ts +12 -0
- package/src/plan/repo-source.ts +19 -5
- package/src/reflect/transcript.ts +35 -10
- package/src/release/public-clean.ts +301 -0
- package/src/release/published-here.ts +22 -0
- package/src/release/run-bump.ts +2 -1
- package/src/release/run-release.ts +4 -1
- package/src/repo-config.ts +53 -2
- package/src/review/http.ts +16 -2
- package/src/review/media-kind.ts +3 -3
- package/src/review/media-read.ts +3 -3
- package/src/review/model.ts +24 -5
- package/src/review/notes.ts +77 -0
- package/src/review/project.ts +6 -38
- package/src/review/routes.ts +8 -13
- package/src/review/store.ts +46 -4
- package/src/review/trailer-media.ts +24 -3
- package/src/review/trailer-shots.ts +106 -0
- package/src/review/unit.ts +1 -1
- package/src/scaffold/files/agent-handoff.md +3 -0
- package/src/scaffold/files/agent-index.md +4 -12
- package/src/scaffold/project-scaffold.ts +5 -4
- package/src/serve/embed.ts +1 -1
- package/src/serve/hub-app/col-card.tsx +3 -17
- package/src/serve/hub-app/col-tables-view.tsx +2 -1
- package/src/serve/hub-app/cols-svc.ts +12 -14
- package/src/serve/hub-app/dock-st.ts +4 -2
- package/src/serve/hub-app/dock-view.tsx +2 -0
- package/src/serve/hub-app/frames-st.ts +35 -0
- package/src/serve/hub-app/hash-route.ts +64 -1
- package/src/serve/hub-app/home-st.ts +31 -7
- package/src/serve/hub-app/home-strip.css +9 -1
- package/src/serve/hub-app/home-strip.tsx +7 -6
- package/src/serve/hub-app/home.html +5 -0
- package/src/serve/hub-app/hub-app.tsx +49 -5
- package/src/serve/hub-app/hub.css +29 -11
- package/src/serve/hub-app/icons.tsx +16 -1
- package/src/serve/hub-app/identities-st.ts +210 -0
- package/src/serve/hub-app/identities-view.tsx +352 -0
- package/src/serve/hub-app/identities.css +48 -0
- package/src/serve/hub-app/identity-address.ts +52 -0
- package/src/serve/hub-app/inbox-st.ts +59 -6
- package/src/serve/hub-app/inbox-view.tsx +48 -6
- package/src/serve/hub-app/inbox.css +12 -1
- package/src/serve/hub-app/index.html +3 -0
- package/src/serve/hub-app/keys.ts +10 -2
- package/src/serve/hub-app/list-walk.ts +89 -0
- package/src/serve/hub-app/machine-st.ts +12 -0
- package/src/serve/hub-app/media-view.tsx +2 -1
- package/src/serve/hub-app/pages-frames.tsx +134 -0
- package/src/serve/hub-app/pages-svc.ts +111 -0
- package/src/serve/hub-app/palette-st.ts +18 -3
- package/src/serve/hub-app/palette-view.tsx +9 -2
- package/src/serve/hub-app/planned-view.tsx +2 -1
- package/src/serve/hub-app/project-list.css +18 -14
- package/src/serve/hub-app/project-list.tsx +88 -49
- package/src/serve/hub-app/projects-svc.ts +33 -3
- package/src/serve/hub-app/repo-sections.ts +19 -2
- package/src/serve/hub-app/repo-st.ts +75 -19
- package/src/serve/hub-app/review/review-cells.tsx +3 -3
- package/src/serve/hub-app/review/review-kit.ts +30 -7
- package/src/serve/hub-app/review/review-page.tsx +1 -1
- package/src/serve/hub-app/review/review-st.ts +33 -11
- package/src/serve/hub-app/review/review-thread.tsx +11 -9
- package/src/serve/hub-app/review/review-views.tsx +84 -19
- package/src/serve/hub-app/review/thread-st.ts +1 -10
- package/src/serve/hub-app/review/trailer-page.tsx +2 -1
- package/src/serve/hub-app/review.css +17 -8
- package/src/serve/hub-app/site/site-part.tsx +173 -0
- package/src/serve/hub-app/site/site-st.ts +157 -0
- package/src/serve/hub-app/site.css +35 -0
- package/src/serve/hub-app/social/calendar.tsx +182 -0
- package/src/serve/hub-app/social/comms-page.tsx +306 -0
- package/src/serve/hub-app/social/kit.tsx +244 -0
- package/src/serve/hub-app/social/post-card.tsx +456 -0
- package/src/serve/hub-app/social/problems.tsx +60 -0
- package/src/serve/hub-app/social/social-model.ts +154 -0
- package/src/serve/hub-app/social/social-page.tsx +674 -0
- package/src/serve/hub-app/social/social-st.ts +986 -0
- package/src/serve/hub-app/social.css +289 -0
- package/src/serve/hub-app/stores/stores-page.tsx +311 -0
- package/src/serve/hub-app/stores/stores-st.ts +286 -0
- package/src/serve/hub-app/stores.css +54 -0
- package/src/serve/hub-app/test-view.tsx +9 -2
- package/src/serve/hub-app/tests-svc.ts +16 -1
- package/src/serve/hub-app/timeline-geometry.ts +1 -1
- package/src/serve/hub-app/timeline-view.tsx +3 -2
- package/src/serve/hub-app/tree-build.ts +6 -0
- package/src/serve/hub-app/tree-row.tsx +27 -4
- package/src/serve/hub-app/tree-svc.ts +18 -49
- package/src/serve/hub-app/veille/veille-page.tsx +514 -0
- package/src/serve/hub-app/veille/veille-st.ts +443 -0
- package/src/serve/hub-app/veille.css +84 -0
- package/src/serve/hub-runtime.ts +14 -9
- package/src/serve/project-gutter-route.ts +44 -12
- package/src/serve/resources-wire.ts +48 -0
- package/src/serve/run-lanes.ts +7 -4
- package/src/serve/same-origin.ts +1 -1
- package/src/serve/serve-hub.ts +27 -18
- package/src/serve/tracked-watch.ts +24 -3
- package/src/serve/warm-cell.ts +5 -1
- package/src/shipkit-files.ts +15 -4
- package/src/shipkit.ts +0 -1
- package/src/shot/box.ts +162 -0
- package/src/shot/browser-slot.ts +62 -0
- package/src/shot/client.ts +43 -7
- package/src/shot/clip-encoder.ts +93 -12
- package/src/shot/film-box.ts +188 -0
- package/src/shot/shooter.ts +50 -15
- package/src/shot/shot-ask.ts +10 -2
- package/src/shot/stepped-clip.ts +5 -4
- package/src/site/desk.ts +242 -0
- package/src/site/routes.ts +66 -0
- package/src/site/unit.ts +62 -0
- package/src/social/brands.ts +22 -0
- package/src/social/compose.ts +97 -0
- package/src/social/desk-index.ts +123 -0
- package/src/social/desk-wire.ts +64 -0
- package/src/social/drafts.ts +183 -0
- package/src/social/house.ts +24 -0
- package/src/social/load.ts +319 -0
- package/src/social/md.ts +70 -0
- package/src/social/media-facts.ts +53 -0
- package/src/social/media-kind.ts +189 -0
- package/src/social/media-limit.ts +42 -0
- package/src/social/media-of.ts +30 -0
- package/src/social/migrate.ts +123 -0
- package/src/social/open.ts +17 -0
- package/src/social/post-url.ts +158 -0
- package/src/social/presence.ts +332 -0
- package/src/social/public-read.ts +53 -0
- package/src/social/publish/bluesky.ts +168 -0
- package/src/social/publish/discord.ts +76 -0
- package/src/social/publish/index.ts +24 -0
- package/src/social/publish/secret.ts +13 -0
- package/src/social/push.ts +31 -0
- package/src/social/richtext.ts +37 -0
- package/src/social/routes.ts +180 -0
- package/src/social/stats.ts +134 -0
- package/src/social/text.ts +267 -0
- package/src/social/tracker-route.ts +39 -0
- package/src/social/tracker.ts +255 -0
- package/src/social/unit.ts +53 -0
- package/src/social/writes.ts +130 -0
- package/src/start-repo.ts +14 -9
- package/src/stores/collection.ts +27 -0
- package/src/stores/desk.ts +336 -0
- package/src/stores/model.ts +187 -0
- package/src/stores/routes.ts +126 -0
- package/src/stores/unit.ts +57 -0
- package/src/suite/calibrate.ts +127 -0
- package/src/suite/core-counters.ts +91 -0
- package/src/suite/judge-suites.ts +94 -34
- package/src/suite/suite-cli.ts +44 -10
- package/src/suite/suite-cpu-preload.ts +34 -9
- package/src/trailer/adapter.ts +4 -0
- package/src/trailer/build.ts +42 -11
- package/src/trailer/ffmpeg.ts +11 -0
- package/src/trailer/footage.ts +30 -13
- package/src/trailer/grammar.ts +18 -2
- package/src/trailer/graph.ts +28 -6
- package/src/trailer/passage.ts +21 -6
- package/src/trailer/plan.ts +74 -3
- package/src/trailer/shelf.ts +16 -0
- package/src/trailer/stitch.ts +67 -26
- package/src/trailer/url.ts +1 -1
- package/src/trailer/versions.ts +24 -0
- package/src/ts/gate-typecheck.ts +32 -0
- package/src/ts/typecheck-cli.ts +9 -11
- package/src/tui/tui-app.tsx +0 -1
- package/src/veille/asks.ts +155 -0
- package/src/veille/auto.ts +31 -0
- package/src/veille/batch.ts +27 -0
- package/src/veille/chrome.ts +127 -0
- package/src/veille/collection.ts +28 -0
- package/src/veille/desk.ts +242 -0
- package/src/veille/identity.ts +80 -0
- package/src/veille/import.ts +68 -0
- package/src/veille/log.ts +183 -0
- package/src/veille/platforms.ts +118 -0
- package/src/veille/reads.ts +66 -0
- package/src/veille/replied.ts +110 -0
- package/src/veille/routes.ts +185 -0
- package/src/veille/service.ts +81 -0
- package/src/veille/watch.ts +116 -0
- package/src/veille/worth.ts +46 -0
- package/src/wiki/scan-md.ts +18 -0
- package/src/collections/posts.ts +0 -142
- package/src/contracts/manifests/social.contract.ts +0 -20
- package/src/scaffold/files/agent-coding.md +0 -35
- package/src/ts/typecheck-cache.ts +0 -11
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
// A RESTORE (wiki build/shipkit/media-store.md, Backup, Restore): a run's files written back from the Space, each one
|
|
2
|
+
// checked by its sha before it lands. Into a folder that is empty or new, by default. In place only when asked, and
|
|
3
|
+
// then a live file that differs is copied aside first, and a sqlite lands beside its live file (`.restored`): a live
|
|
4
|
+
// db is never swapped under the process that writes it. The DRILL restores into a scratch folder and compares every
|
|
5
|
+
// sha against the live files
|
|
6
|
+
import { copyFileSync, existsSync, mkdirSync, mkdtempSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs'
|
|
7
|
+
import { tmpdir } from 'node:os'
|
|
8
|
+
import { dirname, join, resolve } from 'node:path'
|
|
9
|
+
import { gunzipSync } from 'node:zlib'
|
|
10
|
+
import { shaOf } from '../content.ts'
|
|
11
|
+
import type { Space } from '../space.ts'
|
|
12
|
+
import { stampOf } from './keys.ts'
|
|
13
|
+
import { readManifest, runAt, type Entry, type Manifest } from './manifest.ts'
|
|
14
|
+
import { rowsOf } from './snapshot.ts'
|
|
15
|
+
|
|
16
|
+
export interface RestoreResult {
|
|
17
|
+
run: string
|
|
18
|
+
at: string
|
|
19
|
+
files: number
|
|
20
|
+
bytes: number
|
|
21
|
+
written: number
|
|
22
|
+
/** in place: the live file already held these bytes */
|
|
23
|
+
same: number
|
|
24
|
+
/** in place: live files copied aside before they were replaced, and where */
|
|
25
|
+
aside: { n: number; dir: string | null }
|
|
26
|
+
/** in place: sqlite files written beside the live one */
|
|
27
|
+
beside: string[]
|
|
28
|
+
failed: { path: string; error: string }[]
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
const RESTORE_JOBS = 8
|
|
32
|
+
let fetched = 0
|
|
33
|
+
|
|
34
|
+
/** an entry's bytes from the Space into a file of the scratch folder, checked by its sha (an archive of hundreds of MB
|
|
35
|
+
* is hashed as a stream, never held in memory) */
|
|
36
|
+
async function fetchEntry(space: Space, e: Entry, scratch: string): Promise<string> {
|
|
37
|
+
const tmp = join(scratch, `${++fetched}-${e.key.replace(/\//g, '_')}`)
|
|
38
|
+
await space.get(e.key, tmp)
|
|
39
|
+
if (e.sqlite) {
|
|
40
|
+
const bytes = new Uint8Array(gunzipSync(new Uint8Array(await Bun.file(tmp).arrayBuffer())))
|
|
41
|
+
writeFileSync(tmp, bytes)
|
|
42
|
+
}
|
|
43
|
+
const sha = await shaOf(tmp)
|
|
44
|
+
const size = statSync(tmp).size
|
|
45
|
+
if (sha !== e.sha || size !== e.size) {
|
|
46
|
+
rmSync(tmp, { force: true })
|
|
47
|
+
throw new Error(`${e.key}: the bytes hash to ${sha.slice(0, 12)} (${size} B), the manifest says ${e.sha.slice(0, 12)} (${e.size} B)`)
|
|
48
|
+
}
|
|
49
|
+
return tmp
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** a checked file moved into its place through a file beside it renamed: no reader sees half of it */
|
|
53
|
+
function land(path: string, from: string): void {
|
|
54
|
+
mkdirSync(dirname(path), { recursive: true })
|
|
55
|
+
const tmp = `${path}.${process.pid}.restore`
|
|
56
|
+
try {
|
|
57
|
+
renameSync(from, tmp)
|
|
58
|
+
} catch {
|
|
59
|
+
copyFileSync(from, tmp)
|
|
60
|
+
rmSync(from, { force: true })
|
|
61
|
+
}
|
|
62
|
+
renameSync(tmp, path)
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export interface RestoreOptions {
|
|
66
|
+
/** the live home folder: where `--in-place` writes, and what a manifest's paths are under */
|
|
67
|
+
home: string
|
|
68
|
+
/** a folder that is empty or new; the paths land under it */
|
|
69
|
+
to?: string
|
|
70
|
+
inPlace?: boolean
|
|
71
|
+
at?: Date
|
|
72
|
+
/** only the paths under this prefix */
|
|
73
|
+
only?: string
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** the run a restore or a drill reads: the last at or before `at` */
|
|
77
|
+
async function runFor(space: Space, at?: Date): Promise<{ key: string; at: Date }> {
|
|
78
|
+
const run = await runAt(space, at)
|
|
79
|
+
if (!run) throw new Error(at ? `no backup run at or before ${at.toISOString()}` : 'the Space holds no backup run yet: sk backup')
|
|
80
|
+
return run
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export async function restore(space: Space, o: RestoreOptions): Promise<RestoreResult & { manifest: Manifest }> {
|
|
84
|
+
if ((o.inPlace === true) === (o.to !== undefined)) throw new Error('a restore goes --to <dir> (a folder that is empty or new) or --in-place, one of the two')
|
|
85
|
+
const to = o.to === undefined ? null : resolve(o.to)
|
|
86
|
+
if (to && existsSync(to) && readdirSync(to).length > 0) throw new Error(`${to} is not empty: a restore writes into an empty or new folder, never over files`)
|
|
87
|
+
const run = await runFor(space, o.at)
|
|
88
|
+
const scratch = mkdtempSync(join(tmpdir(), 'shipkit-restore-'))
|
|
89
|
+
const stamp = stampOf(new Date())
|
|
90
|
+
const aside = join(o.home, '.shipkit', 'backup-replaced', stamp)
|
|
91
|
+
try {
|
|
92
|
+
const m = await readManifest(space, run.key, join(scratch, 'run'))
|
|
93
|
+
const files = m.files.filter((f) => !o.only || f.path === o.only || f.path.startsWith(o.only.endsWith('/') ? o.only : `${o.only}/`))
|
|
94
|
+
const out: RestoreResult & { manifest: Manifest } = { run: run.key, at: m.at, files: files.length, bytes: 0, written: 0, same: 0, aside: { n: 0, dir: null }, beside: [], failed: [], manifest: m }
|
|
95
|
+
let next = 0
|
|
96
|
+
const one = async (e: Entry): Promise<void> => {
|
|
97
|
+
try {
|
|
98
|
+
if (to) {
|
|
99
|
+
land(join(to, e.path), await fetchEntry(space, e, scratch))
|
|
100
|
+
out.written++
|
|
101
|
+
out.bytes += e.size
|
|
102
|
+
return
|
|
103
|
+
}
|
|
104
|
+
const live = join(o.home, e.path)
|
|
105
|
+
if (e.sqlite) {
|
|
106
|
+
land(`${live}.restored`, await fetchEntry(space, e, scratch))
|
|
107
|
+
out.beside.push(`${live}.restored`)
|
|
108
|
+
out.written++
|
|
109
|
+
out.bytes += e.size
|
|
110
|
+
return
|
|
111
|
+
}
|
|
112
|
+
if (existsSync(live) && statSync(live).size === e.size && (await shaOf(live)) === e.sha) {
|
|
113
|
+
out.same++
|
|
114
|
+
return
|
|
115
|
+
}
|
|
116
|
+
const file = await fetchEntry(space, e, scratch)
|
|
117
|
+
if (existsSync(live)) {
|
|
118
|
+
mkdirSync(dirname(join(aside, e.path)), { recursive: true })
|
|
119
|
+
copyFileSync(live, join(aside, e.path))
|
|
120
|
+
out.aside.n++
|
|
121
|
+
out.aside.dir = aside
|
|
122
|
+
}
|
|
123
|
+
land(live, file)
|
|
124
|
+
out.written++
|
|
125
|
+
out.bytes += e.size
|
|
126
|
+
} catch (err) {
|
|
127
|
+
out.failed.push({ path: e.path, error: (err as Error).message })
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
// a GET waits on the network: eight at a time
|
|
131
|
+
const work = async (): Promise<void> => {
|
|
132
|
+
for (let e = files[next++]; e; e = files[next++]) await one(e)
|
|
133
|
+
}
|
|
134
|
+
await Promise.all(Array.from({ length: RESTORE_JOBS }, work))
|
|
135
|
+
return out
|
|
136
|
+
} finally {
|
|
137
|
+
rmSync(scratch, { recursive: true, force: true })
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
export interface DrillResult {
|
|
142
|
+
run: string
|
|
143
|
+
at: string
|
|
144
|
+
files: number
|
|
145
|
+
bytes: number
|
|
146
|
+
/** restored, and its sha read again from the disk matches the manifest */
|
|
147
|
+
restored: number
|
|
148
|
+
/** the live file holds the same bytes now */
|
|
149
|
+
sameAsLive: number
|
|
150
|
+
/** the live file moved since the run: newer bytes, the next run takes them */
|
|
151
|
+
liveMoved: string[]
|
|
152
|
+
liveGone: string[]
|
|
153
|
+
/** sqlite: the restored snapshot's rows against the live db's rows now */
|
|
154
|
+
sqlite: { path: string; restored: Record<string, number>; live: Record<string, number> }[]
|
|
155
|
+
failed: { path: string; error: string }[]
|
|
156
|
+
dir: string
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/** a run (the last, or the last at or before `at`) restored into a scratch folder (or `to`), every sha read again and
|
|
160
|
+
* compared to the live files */
|
|
161
|
+
export async function drill(space: Space, o: { home: string; to?: string; keep?: boolean; at?: Date }): Promise<DrillResult & { v: number }> {
|
|
162
|
+
const dir = o.to ? resolve(o.to) : mkdtempSync(join(tmpdir(), 'shipkit-drill-'))
|
|
163
|
+
try {
|
|
164
|
+
const r = await restore(space, { home: o.home, to: dir, ...(o.at ? { at: o.at } : {}) })
|
|
165
|
+
const out: DrillResult & { v: number } = { v: r.manifest.v, run: r.run, at: r.at, files: r.files, bytes: r.bytes, restored: 0, sameAsLive: 0, liveMoved: [], liveGone: [], sqlite: [], failed: [...r.failed], dir }
|
|
166
|
+
const bad = new Set(r.failed.map((f) => f.path))
|
|
167
|
+
for (const e of r.manifest.files) {
|
|
168
|
+
if (bad.has(e.path)) continue
|
|
169
|
+
const back = join(dir, e.path)
|
|
170
|
+
const sha = await shaOf(back)
|
|
171
|
+
if (sha !== e.sha) {
|
|
172
|
+
out.failed.push({ path: e.path, error: `restored bytes hash to ${sha.slice(0, 12)}, the manifest says ${e.sha.slice(0, 12)}` })
|
|
173
|
+
continue
|
|
174
|
+
}
|
|
175
|
+
out.restored++
|
|
176
|
+
const live = join(o.home, e.path)
|
|
177
|
+
if (!existsSync(live)) {
|
|
178
|
+
out.liveGone.push(e.path)
|
|
179
|
+
continue
|
|
180
|
+
}
|
|
181
|
+
if (e.sqlite) {
|
|
182
|
+
out.sqlite.push({ path: e.path, restored: rowsOf(back, e.sqlite), live: rowsOf(live, e.sqlite) })
|
|
183
|
+
continue
|
|
184
|
+
}
|
|
185
|
+
if ((await shaOf(live)) === e.sha) out.sameAsLive++
|
|
186
|
+
else out.liveMoved.push(e.path)
|
|
187
|
+
}
|
|
188
|
+
return out
|
|
189
|
+
} finally {
|
|
190
|
+
if (!o.to && !o.keep) rmSync(dir, { recursive: true, force: true })
|
|
191
|
+
}
|
|
192
|
+
}
|
|
@@ -0,0 +1,278 @@
|
|
|
1
|
+
// A BACKUP RUN (wiki build/shipkit/media-store.md, Backup): every source read once, refused or hashed (a sqlite
|
|
2
|
+
// snapshotted first), each object the Space lacks sent from the bytes that were hashed (never
|
|
3
|
+
// the live file again: it may have moved), then the run's parts the Space lacks, then the run itself, last, so a run
|
|
4
|
+
// never names an object the Space lacks. A run whose state equals the last one writes nothing. The objects are never
|
|
5
|
+
// deleted: every version stays
|
|
6
|
+
import { constants, copyFileSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs'
|
|
7
|
+
import { hostname, tmpdir } from 'node:os'
|
|
8
|
+
import { basename, dirname, join, relative } from 'node:path'
|
|
9
|
+
import { homeDir } from '../../home/home-paths.ts'
|
|
10
|
+
import { gzipSync } from 'node:zlib'
|
|
11
|
+
import { machineGet, machineSet } from '../../core/machine-db.ts'
|
|
12
|
+
import { mediaKey } from '../content.ts'
|
|
13
|
+
import { isUp } from '../remote.ts'
|
|
14
|
+
import type { Space } from '../space.ts'
|
|
15
|
+
import { uploadOne } from '../upload.ts'
|
|
16
|
+
import { BACKUP_LABEL, runKey } from './keys.ts'
|
|
17
|
+
import { digestOf, encodeRun, readManifest, readRunHead, runAt, type Entry, type Refused } from './manifest.ts'
|
|
18
|
+
import { fileRefusal, refusal } from './secret.ts'
|
|
19
|
+
import { snapshotSqlite } from './snapshot.ts'
|
|
20
|
+
import { collect, type Collect, type Source } from './sources.ts'
|
|
21
|
+
|
|
22
|
+
const LAST = 'backup-last'
|
|
23
|
+
/** the files named whole, by path: their size, time, sha and key, so an unchanged archive is never read again */
|
|
24
|
+
const SEEN = 'backup-seen'
|
|
25
|
+
|
|
26
|
+
export interface Last {
|
|
27
|
+
key: string
|
|
28
|
+
digest: string
|
|
29
|
+
at: string
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
type Seen = Record<string, { size: number; mtime: number; sha: string; key: string }>
|
|
33
|
+
|
|
34
|
+
export const lastRun = (): Last | null => machineGet<Last>(LAST)
|
|
35
|
+
|
|
36
|
+
const sha256 = (b: Uint8Array): string => new Bun.CryptoHasher('sha256').update(b).digest('hex')
|
|
37
|
+
|
|
38
|
+
/** one source made ready: its entry and where the object's bytes are (in memory, a frozen copy, or already up) */
|
|
39
|
+
export interface Ready {
|
|
40
|
+
entry: Entry
|
|
41
|
+
bytes?: Uint8Array
|
|
42
|
+
/** a copy in the scratch folder (an APFS clone): the bytes that were hashed, whatever the live file does next */
|
|
43
|
+
file?: string
|
|
44
|
+
/** the object's size: a sqlite's is its gzip */
|
|
45
|
+
size: number
|
|
46
|
+
/** a path the repo names whole: its sha kept by its size and time */
|
|
47
|
+
whole?: true
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** every source read: hashed, snapshotted, or refused */
|
|
51
|
+
export async function prepare(sources: readonly Source[], scratch: string, seen: Seen = machineGet<Seen>(SEEN) ?? {}): Promise<{ ready: Ready[]; refused: Refused[] }> {
|
|
52
|
+
const ready: Ready[] = []
|
|
53
|
+
const refused: Refused[] = []
|
|
54
|
+
for (const s of sources) {
|
|
55
|
+
try {
|
|
56
|
+
if (s.broken) {
|
|
57
|
+
refused.push({ path: s.rel, why: s.broken })
|
|
58
|
+
continue
|
|
59
|
+
}
|
|
60
|
+
if (s.sqlite) {
|
|
61
|
+
const to = join(scratch, `${ready.length}-${basename(s.abs)}`)
|
|
62
|
+
const snap = snapshotSqlite(s.abs, to, s.sqlite)
|
|
63
|
+
const raw = new Uint8Array(await Bun.file(to).arrayBuffer())
|
|
64
|
+
rmSync(to, { force: true })
|
|
65
|
+
const why = refusal(basename(s.rel), raw)
|
|
66
|
+
if (why) {
|
|
67
|
+
refused.push({ path: s.rel, why })
|
|
68
|
+
continue
|
|
69
|
+
}
|
|
70
|
+
const gz = new Uint8Array(gzipSync(raw))
|
|
71
|
+
// a snapshot is a new file each run: its live file's time would move the part with no change
|
|
72
|
+
const entry: Entry = { path: s.rel, sha: sha256(raw), size: raw.length, mtime: 0, key: `${BACKUP_LABEL}/${sha256(gz)}.gz`, sqlite: { ...s.sqlite, rows: snap.rows } }
|
|
73
|
+
ready.push({ entry, bytes: gz, size: gz.length })
|
|
74
|
+
continue
|
|
75
|
+
}
|
|
76
|
+
if (s.whole) {
|
|
77
|
+
const was = seen[s.rel]
|
|
78
|
+
if (was && was.size === s.size && was.mtime === s.mtime && isUp(was.key)) {
|
|
79
|
+
ready.push({ entry: { path: s.rel, sha: was.sha, size: was.size, mtime: s.mtime, key: was.key }, size: was.size, whole: true })
|
|
80
|
+
continue
|
|
81
|
+
}
|
|
82
|
+
const copy = join(scratch, `${ready.length}-whole${extname(s.abs)}`)
|
|
83
|
+
copyFileSync(s.abs, copy, constants.COPYFILE_FICLONE)
|
|
84
|
+
const r = await fileRefusal(copy, basename(s.abs))
|
|
85
|
+
if (r.why) {
|
|
86
|
+
rmSync(copy, { force: true })
|
|
87
|
+
refused.push({ path: s.rel, why: r.why })
|
|
88
|
+
continue
|
|
89
|
+
}
|
|
90
|
+
ready.push({ entry: { path: s.rel, sha: r.sha, size: r.size, mtime: s.mtime, key: mediaKey(BACKUP_LABEL, { sha: r.sha }, s.abs) }, file: copy, size: r.size, whole: true })
|
|
91
|
+
continue
|
|
92
|
+
}
|
|
93
|
+
const bytes = new Uint8Array(await Bun.file(s.abs).arrayBuffer())
|
|
94
|
+
const why = refusal(basename(s.abs), bytes)
|
|
95
|
+
if (why) {
|
|
96
|
+
refused.push({ path: s.rel, why })
|
|
97
|
+
continue
|
|
98
|
+
}
|
|
99
|
+
const sha = sha256(bytes)
|
|
100
|
+
ready.push({ entry: { path: s.rel, sha, size: bytes.length, mtime: s.mtime, key: mediaKey(BACKUP_LABEL, { sha }, s.abs) }, bytes, size: bytes.length })
|
|
101
|
+
} catch (e) {
|
|
102
|
+
refused.push({ path: s.rel, why: `not read: ${(e as Error).message}` })
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
return { ready, refused }
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
const extname = (p: string): string => /(\.[^./]+)$/.exec(basename(p))?.[1]?.toLowerCase() ?? ''
|
|
109
|
+
|
|
110
|
+
export interface RunResult {
|
|
111
|
+
files: number
|
|
112
|
+
bytes: number
|
|
113
|
+
sent: number
|
|
114
|
+
sentBytes: number
|
|
115
|
+
/** objects the Space already held */
|
|
116
|
+
there: number
|
|
117
|
+
refused: Refused[]
|
|
118
|
+
failed: { key: string; error: string }[]
|
|
119
|
+
/** the run written, null when nothing changed since `last` or an upload failed */
|
|
120
|
+
manifest: string | null
|
|
121
|
+
/** what the record of the run cost: its parts sent (of all), their bytes, and the run's own bytes */
|
|
122
|
+
record: { parts: number; partsSent: number; partsBytes: number; runBytes: number }
|
|
123
|
+
last: Last | null
|
|
124
|
+
digest: string
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/** one object up from the bytes that were hashed, checked by a HEAD of its size: true when it was sent */
|
|
128
|
+
async function sendOne(space: Space, key: string, size: number, from: { bytes?: Uint8Array; file?: string }, scratch: string, n: number): Promise<boolean> {
|
|
129
|
+
if (from.file) return uploadOne(space, { key, size, path: from.file })
|
|
130
|
+
const path = join(scratch, `${n}.obj`)
|
|
131
|
+
try {
|
|
132
|
+
writeFileSync(path, from.bytes ?? new Uint8Array(0))
|
|
133
|
+
return await uploadOne(space, { key, size, path })
|
|
134
|
+
} finally {
|
|
135
|
+
rmSync(path, { force: true })
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/** the objects of `ready` up, `jobs` at a time */
|
|
140
|
+
async function sendAll(space: Space, ready: readonly Ready[], scratch: string, jobs: number, out: RunResult): Promise<void> {
|
|
141
|
+
const byKey = new Map<string, Ready>()
|
|
142
|
+
for (const r of ready) byKey.set(r.entry.key, r)
|
|
143
|
+
const list = [...byKey.values()].filter((r) => !isUp(r.entry.key))
|
|
144
|
+
out.there += byKey.size - list.length
|
|
145
|
+
let next = 0
|
|
146
|
+
const work = async (): Promise<void> => {
|
|
147
|
+
for (;;) {
|
|
148
|
+
const i = next++
|
|
149
|
+
const r = list[i]
|
|
150
|
+
if (!r) return
|
|
151
|
+
try {
|
|
152
|
+
if (!r.bytes && !r.file) throw new Error(`${r.entry.path}: no bytes held for ${r.entry.key}, and the index does not see it up`)
|
|
153
|
+
if (await sendOne(space, r.entry.key, r.size, r, scratch, i)) {
|
|
154
|
+
out.sent++
|
|
155
|
+
out.sentBytes += r.size
|
|
156
|
+
} else out.there++
|
|
157
|
+
} catch (e) {
|
|
158
|
+
out.failed.push({ key: r.entry.key, error: (e as Error).message })
|
|
159
|
+
} finally {
|
|
160
|
+
if (r.file) rmSync(r.file, { force: true })
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
await Promise.all(Array.from({ length: Math.max(1, jobs) }, work))
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/** the last run's digest: the machine db's record, else the Space's last run */
|
|
168
|
+
async function lastOf(space: Space, scratch: string): Promise<Last | null> {
|
|
169
|
+
const held = lastRun()
|
|
170
|
+
if (held) return held
|
|
171
|
+
const run = await runAt(space)
|
|
172
|
+
if (!run) return null
|
|
173
|
+
const m = await readRunHead(space, run.key, join(scratch, 'last.json.gz'))
|
|
174
|
+
return { key: run.key, digest: m.digest, at: m.at }
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/** a lock this old is taken over even when its pid runs: a restart in place keeps the pid of the process that held it
|
|
178
|
+
* (a daemon that ran a backup in process), and a job child is killed at an hour */
|
|
179
|
+
export const LOCK_STALE_MS = 2 * 3600_000
|
|
180
|
+
|
|
181
|
+
/** one run at a time on the machine (the daemon's job and a hand run): a lock file with its pid, taken over once its
|
|
182
|
+
* process is gone or the lock is older than LOCK_STALE_MS */
|
|
183
|
+
function lock(): () => void {
|
|
184
|
+
const path = join(homeDir(), 'backup.lock')
|
|
185
|
+
mkdirSync(dirname(path), { recursive: true })
|
|
186
|
+
for (let i = 0; i < 2; i++) {
|
|
187
|
+
try {
|
|
188
|
+
writeFileSync(path, String(process.pid), { flag: 'wx' })
|
|
189
|
+
return () => rmSync(path, { force: true })
|
|
190
|
+
} catch {
|
|
191
|
+
const pid = Number(readFileSync(path, 'utf8').trim())
|
|
192
|
+
let alive = false
|
|
193
|
+
try {
|
|
194
|
+
alive = pid > 0 && process.kill(pid, 0)
|
|
195
|
+
} catch {
|
|
196
|
+
alive = false
|
|
197
|
+
}
|
|
198
|
+
const age = Date.now() - (statSync(path, { throwIfNoEntry: false })?.mtimeMs ?? 0)
|
|
199
|
+
if (alive && age < LOCK_STALE_MS) throw new Error(`another backup runs (pid ${pid}): it holds ${path}`)
|
|
200
|
+
if (alive) console.error(`WARN backup: ${path} held by pid ${pid} for ${Math.round(age / 60_000)} min, past ${LOCK_STALE_MS / 3600_000} h: taken over`)
|
|
201
|
+
rmSync(path, { force: true })
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
throw new Error(`${path}: the lock did not take`)
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/** one run: every source to the Space, then the run's parts the Space lacks, then the run itself, last */
|
|
208
|
+
export async function backupRun(space: Space, o: Collect & { now?: Date; jobs?: number }): Promise<RunResult> {
|
|
209
|
+
const unlock = lock()
|
|
210
|
+
const scratch = mkdtempSync(join(tmpdir(), 'shipkit-backup-'))
|
|
211
|
+
try {
|
|
212
|
+
const now = o.now ?? new Date()
|
|
213
|
+
const { ready, refused } = await prepare(await collect(o), scratch)
|
|
214
|
+
const files = ready.map((r) => r.entry)
|
|
215
|
+
const digest = digestOf(files, refused)
|
|
216
|
+
const last = await lastOf(space, scratch)
|
|
217
|
+
const out: RunResult = { files: files.length, bytes: ready.reduce((n, r) => n + r.entry.size, 0), sent: 0, sentBytes: 0, there: 0, refused, failed: [], manifest: null, record: { parts: 0, partsSent: 0, partsBytes: 0, runBytes: 0 }, last, digest }
|
|
218
|
+
await sendAll(space, ready, scratch, o.jobs ?? 8, out)
|
|
219
|
+
if (out.failed.length > 0) return out
|
|
220
|
+
const seen: Seen = {}
|
|
221
|
+
for (const r of ready) if (r.whole) seen[r.entry.path] = { size: r.entry.size, mtime: r.entry.mtime, sha: r.entry.sha, key: r.entry.key }
|
|
222
|
+
machineSet(SEEN, seen)
|
|
223
|
+
if (last?.digest === digest) return out
|
|
224
|
+
const enc = encodeRun({ at: now.toISOString(), host: hostname(), home: o.home, digest, files, refused }, o.repos.map((r) => relative(o.home, r)))
|
|
225
|
+
out.record.parts = enc.parts.length
|
|
226
|
+
for (const [i, p] of enc.parts.entries()) {
|
|
227
|
+
if (isUp(p.ref.key)) continue
|
|
228
|
+
try {
|
|
229
|
+
if (await sendOne(space, p.ref.key, p.bytes.length, p, scratch, -1 - i)) {
|
|
230
|
+
out.record.partsSent++
|
|
231
|
+
out.record.partsBytes += p.bytes.length
|
|
232
|
+
}
|
|
233
|
+
} catch (e) {
|
|
234
|
+
out.failed.push({ key: p.ref.key, error: (e as Error).message })
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
if (out.failed.length > 0) return out
|
|
238
|
+
const key = runKey(now, digest)
|
|
239
|
+
await sendOne(space, key, enc.run.length, { bytes: enc.run }, scratch, -1 - enc.parts.length)
|
|
240
|
+
out.record.runBytes = enc.run.length
|
|
241
|
+
machineSet(LAST, { key, digest, at: now.toISOString() } satisfies Last)
|
|
242
|
+
out.manifest = key
|
|
243
|
+
return out
|
|
244
|
+
} finally {
|
|
245
|
+
rmSync(scratch, { recursive: true, force: true })
|
|
246
|
+
unlock()
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
export interface CheckResult {
|
|
251
|
+
files: number
|
|
252
|
+
/** sources whose object the Space lacks */
|
|
253
|
+
waiting: { path: string; size: number }[]
|
|
254
|
+
/** sources the last run holds another content of, or none */
|
|
255
|
+
changed: string[]
|
|
256
|
+
refused: Refused[]
|
|
257
|
+
last: Last | null
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
/** what is not backed up yet: each source read and hashed, nothing sent */
|
|
261
|
+
export async function backupCheck(space: Space, o: Collect): Promise<CheckResult> {
|
|
262
|
+
const scratch = mkdtempSync(join(tmpdir(), 'shipkit-backup-'))
|
|
263
|
+
try {
|
|
264
|
+
const { ready, refused } = await prepare(await collect(o), scratch)
|
|
265
|
+
const last = await lastOf(space, scratch)
|
|
266
|
+
const held = last ? new Map((await readManifest(space, last.key, join(scratch, 'last'))).files.map((f) => [f.path, f.sha])) : new Map<string, string>()
|
|
267
|
+
const waiting: CheckResult['waiting'] = []
|
|
268
|
+
for (const r of ready) {
|
|
269
|
+
if (isUp(r.entry.key)) continue
|
|
270
|
+
const h = await space.head(r.entry.key)
|
|
271
|
+
if (h?.size !== r.size) waiting.push({ path: r.entry.path, size: r.size })
|
|
272
|
+
}
|
|
273
|
+
const changed = ready.filter((r) => held.get(r.entry.path) !== r.entry.sha && !r.entry.sqlite).map((r) => r.entry.path)
|
|
274
|
+
return { files: ready.length, waiting, changed, refused, last }
|
|
275
|
+
} finally {
|
|
276
|
+
rmSync(scratch, { recursive: true, force: true })
|
|
277
|
+
}
|
|
278
|
+
}
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
// what the backup never sends (wiki build/shipkit/media-store.md, Backup): a secret's home is the keychain, never the
|
|
2
|
+
// Space. A file is refused by its name (an env file, a key file, a name that says secret, token, password, api key), by
|
|
3
|
+
// the leak guard's secret shapes in its bytes, by a credential line whose value is no keychain pointer, or by its
|
|
4
|
+
// size (over 50 MB is a question for the owner first, unless his repo names the path whole: `backup.paths`). The
|
|
5
|
+
// reason is printed, the content never
|
|
6
|
+
import { parsePatterns, SECRET_ROWS } from '../../hooks/leak-guard.ts'
|
|
7
|
+
|
|
8
|
+
export const MAX_BYTES = 50e6
|
|
9
|
+
|
|
10
|
+
const SHAPES = parsePatterns(SECRET_ROWS.join('\n')).regexes
|
|
11
|
+
|
|
12
|
+
/** a token word counts only at the end of a name (`github-token`, `token.txt`): `lane-token-budget.md` is prose */
|
|
13
|
+
const SECRET_NAME = /^\.env(?:\..*)?$|\.(?:pem|key|p12|pfx|jks|keystore)$|^id_(?:rsa|dsa|ecdsa|ed25519)$|(?:^|[-_.])(?:secrets?|api-?keys?|passwords?|passwd|credentials?|creds)(?:[-_.]|$)|(?:^|[-_.])tokens?(?:\.[a-z]+)?$/i
|
|
14
|
+
|
|
15
|
+
const KEY = '(?:password|passwd|pwd|mot de passe|api[ _-]?key|secret|token|bearer)'
|
|
16
|
+
/** a line that sets a credential to a value: a bare key at the start of a line, or a quoted key with its closing quote
|
|
17
|
+
* (`"secret:cave"` is a value, « 3. Secret : la grotte » inside a note is prose). A value that points at the keychain
|
|
18
|
+
* (a `secret get` command, the word keychain, an `rv/<name>` secret name) passes */
|
|
19
|
+
const CREDENTIAL_LINE = new RegExp(`(?:^[ \\t>*#-]*${KEY}|"${KEY}"|'${KEY}')[ \\t]*[:=][ \\t]*(?![ \\t]*$)(?!.*(?:\\bsecret get\\b|keychain|\\brv/[\\w/-]+))`, 'im')
|
|
20
|
+
|
|
21
|
+
/** why these bytes never go up, null when they may */
|
|
22
|
+
function textRefusal(bytes: Uint8Array): string | null {
|
|
23
|
+
const text = Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString('latin1')
|
|
24
|
+
const shape = SHAPES.find((s) => s.re.test(text))
|
|
25
|
+
if (shape) return `it holds a secret shape (${shape.row.slice(3, 24)}…): the keychain keeps those`
|
|
26
|
+
if (CREDENTIAL_LINE.test(text)) return 'a line sets a credential to a value (not a keychain pointer): the keychain keeps those'
|
|
27
|
+
return null
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
const nameRefusal = (name: string): string | null => (SECRET_NAME.test(name) ? 'its name says it holds a secret: the keychain keeps those' : null)
|
|
31
|
+
|
|
32
|
+
/** why the file never goes up, null when it may */
|
|
33
|
+
export function refusal(name: string, bytes: Uint8Array): string | null {
|
|
34
|
+
if (bytes.length > MAX_BYTES) return `over 50 MB (${(bytes.length / 1e6).toFixed(0)} MB): asked before it goes`
|
|
35
|
+
return nameRefusal(name) ?? textRefusal(bytes)
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** a window of a stream, its end carried into the next so a shape cut by a window's edge is still seen */
|
|
39
|
+
const WINDOW = 8 << 20
|
|
40
|
+
const CARRY = 4096
|
|
41
|
+
|
|
42
|
+
async function streamRefusal(stream: ReadableStream<Uint8Array>, each?: (chunk: Uint8Array) => void): Promise<string | null> {
|
|
43
|
+
let held = new Uint8Array(0)
|
|
44
|
+
let why: string | null = null
|
|
45
|
+
for await (const chunk of stream) {
|
|
46
|
+
each?.(chunk)
|
|
47
|
+
if (why) continue
|
|
48
|
+
const joined = new Uint8Array(held.length + chunk.length)
|
|
49
|
+
joined.set(held)
|
|
50
|
+
joined.set(chunk, held.length)
|
|
51
|
+
held = joined
|
|
52
|
+
if (held.length < WINDOW) continue
|
|
53
|
+
why = textRefusal(held)
|
|
54
|
+
held = held.slice(held.length - CARRY)
|
|
55
|
+
}
|
|
56
|
+
return why ?? (held.length > 0 ? textRefusal(held) : null)
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** the names and the bytes inside a zip (`unzip`), never only its compressed bytes: a secret packed in an archive is
|
|
60
|
+
* still a secret */
|
|
61
|
+
async function zipRefusal(path: string): Promise<string | null> {
|
|
62
|
+
const list = Bun.spawn(['unzip', '-Z1', path], { stdout: 'pipe', stderr: 'pipe' })
|
|
63
|
+
const names = (await new Response(list.stdout).text()).split('\n').filter(Boolean)
|
|
64
|
+
if ((await list.exited) !== 0) return `not read: unzip could not list it: ${(await new Response(list.stderr).text()).trim().slice(0, 200)}`
|
|
65
|
+
for (const n of names) {
|
|
66
|
+
const why = nameRefusal(n.split('/').pop() ?? n)
|
|
67
|
+
if (why) return `${n} inside: ${why}`
|
|
68
|
+
}
|
|
69
|
+
const all = Bun.spawn(['unzip', '-p', path], { stdout: 'pipe', stderr: 'ignore' })
|
|
70
|
+
const why = await streamRefusal(all.stdout)
|
|
71
|
+
if ((await all.exited) > 1) return 'not read: unzip could not read every entry'
|
|
72
|
+
return why ? `inside: ${why}` : null
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** a file the owner named whole (an archive, a dump): no size bound, its bytes read as a stream, its sha read on the
|
|
76
|
+
* way. A zip is read inside */
|
|
77
|
+
export async function fileRefusal(path: string, name: string): Promise<{ why: string | null; sha: string; size: number }> {
|
|
78
|
+
const h = new Bun.CryptoHasher('sha256')
|
|
79
|
+
let size = 0
|
|
80
|
+
const scan = await streamRefusal(Bun.file(path).stream(), (c) => {
|
|
81
|
+
h.update(c)
|
|
82
|
+
size += c.length
|
|
83
|
+
})
|
|
84
|
+
const why = nameRefusal(name) ?? scan ?? (/\.zip$/i.test(name) ? await zipRefusal(path) : null)
|
|
85
|
+
return { why, sha: h.digest('hex'), size }
|
|
86
|
+
}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
// a live sqlite copied consistently (wiki build/shipkit/media-store.md, Backup): the live file attached read only into
|
|
2
|
+
// a fresh database, the tables kept copied inside ONE transaction (one read snapshot of the WAL), then vacuumed. Never a
|
|
3
|
+
// copy of the file while a process writes it. The same rows give the same bytes, so an unchanged db is one object.
|
|
4
|
+
// A cut leaves out the rows that move by themselves (a pid, the backup's own records): else every run differs
|
|
5
|
+
import { Database } from 'bun:sqlite'
|
|
6
|
+
|
|
7
|
+
export interface SqliteCut {
|
|
8
|
+
/** the tables kept, null: every table */
|
|
9
|
+
tables: string[] | null
|
|
10
|
+
/** per table, a where clause of the rows left out */
|
|
11
|
+
except?: Record<string, string>
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export interface Snapshot {
|
|
15
|
+
/** the tables copied and their rows */
|
|
16
|
+
rows: Record<string, number>
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
const quote = (name: string): string => `"${name.replace(/"/g, '""')}"`
|
|
20
|
+
const kept = (cut: SqliteCut, table: string): string => (cut.except?.[table] ? ` where not (${cut.except[table]})` : '')
|
|
21
|
+
|
|
22
|
+
/** the live db at `live` copied into the new file `to` */
|
|
23
|
+
export function snapshotSqlite(live: string, to: string, cut: SqliteCut): Snapshot {
|
|
24
|
+
const db = new Database(to, { create: true, readwrite: true })
|
|
25
|
+
try {
|
|
26
|
+
db.exec('pragma journal_mode = delete')
|
|
27
|
+
db.query('attach database ? as live').run(`file:${encodeURI(live)}?mode=ro`)
|
|
28
|
+
db.exec('begin')
|
|
29
|
+
const all = db.query(`select name, sql from live.sqlite_schema where type = 'table' and name not like 'sqlite_%' order by name`).all() as { name: string; sql: string }[]
|
|
30
|
+
const keep = cut.tables === null ? all : all.filter((t) => cut.tables!.includes(t.name))
|
|
31
|
+
const missing = (cut.tables ?? []).filter((t) => !all.some((a) => a.name === t))
|
|
32
|
+
if (missing.length > 0) throw new Error(`${live}: no table ${missing.join(', ')}`)
|
|
33
|
+
const rows: Record<string, number> = {}
|
|
34
|
+
for (const t of keep) {
|
|
35
|
+
db.exec(t.sql)
|
|
36
|
+
db.exec(`insert into main.${quote(t.name)} select * from live.${quote(t.name)}${kept(cut, t.name)}`)
|
|
37
|
+
rows[t.name] = (db.query(`select count(*) as n from main.${quote(t.name)}`).get() as { n: number }).n
|
|
38
|
+
}
|
|
39
|
+
const names = keep.map((t) => t.name)
|
|
40
|
+
const idx = db.query(`select sql from live.sqlite_schema where type = 'index' and sql is not null and tbl_name in (${names.map(() => '?').join(',') || "''"}) order by name`).all(...names) as { sql: string }[]
|
|
41
|
+
for (const i of idx) db.exec(i.sql)
|
|
42
|
+
db.exec('commit')
|
|
43
|
+
db.exec('detach database live')
|
|
44
|
+
db.exec('vacuum')
|
|
45
|
+
return { rows }
|
|
46
|
+
} finally {
|
|
47
|
+
db.close()
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** the rows of each table a cut keeps, read through one read transaction */
|
|
52
|
+
export function rowsOf(file: string, cut: SqliteCut): Record<string, number> {
|
|
53
|
+
const db = new Database(file, { readonly: true })
|
|
54
|
+
try {
|
|
55
|
+
db.exec('begin')
|
|
56
|
+
const names = (db.query(`select name from sqlite_schema where type = 'table' and name not like 'sqlite_%' order by name`).all() as { name: string }[]).map((r) => r.name).filter((n) => cut.tables === null || cut.tables.includes(n))
|
|
57
|
+
const out: Record<string, number> = {}
|
|
58
|
+
for (const n of names) out[n] = (db.query(`select count(*) as n from ${quote(n)}${kept(cut, n)}`).get() as { n: number }).n
|
|
59
|
+
db.exec('commit')
|
|
60
|
+
return out
|
|
61
|
+
} finally {
|
|
62
|
+
db.close()
|
|
63
|
+
}
|
|
64
|
+
}
|