Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .github/workflows/threatcrush.yml
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,10 @@ jobs:
- name: Scan the dbbackup plugin
run: threatcrush scan packages/plugin-dbbackup --deps --fail-on critical,high,medium

# The cleaner deletes files and runs shell on servers: the same bar.
- name: Scan the cleaner plugin
run: threatcrush scan packages/plugin-cleaner --deps --fail-on critical,high,medium

# The S3 engine signs requests and holds credentials: the same bar.
- name: Scan the S3 engine
run: threatcrush scan packages/s3-core --deps --fail-on critical,high,medium
Expand Down
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,10 @@ diskpush dbbackup discover --save # every database on every server yo
diskpush dbbackup add shop --kind postgres --push backup@nas:/srv/db
diskpush dbbackup run --tags nightly
diskpush dbbackup restore shop --to-env STAGING_DATABASE_URL

# Disk full? See what fills and grows it, then free space safely (dry run unless --apply)
diskpush clean report web-1 # biggest dirs, live writers, growth, ranked plan with reasons
diskpush clean web-1 --apply # caches, docker build cache, idle build output, stale partials
```

## Safety
Expand Down Expand Up @@ -155,6 +159,7 @@ to make that flag hard to trigger by accident.
| [docs/file-browser.md](docs/file-browser.md) | Why browsing is SFTP and transfers are rsync |
| [docs/profiles.md](docs/profiles.md) | Saved, repeatable directory pairs |
| [docs/fleet.md](docs/fleet.md) | Running one command, or an upgrade, across many servers |
| [docs/cleaner.md](docs/cleaner.md) | Free disk space safely: the analysis, the three classes, the guards, MCP |
| [docs/s3.md](docs/s3.md) | S3-compatible buckets: saving, credentials, how transfers behave |
| [docs/plugins.md](docs/plugins.md) | Plugins, MediaAnalyzer, database backups, writing one, and the security model |
| [docs/threatcrush-scan.md](docs/threatcrush-scan.md) | What the ThreatCrush badge enforces, and every finding below it |
Expand All @@ -178,6 +183,7 @@ packages/database the local store shared by desktop and CLI
packages/plugin-api the plugin contract, registry and external loader
packages/plugin-mediaanalyzer the built-in MediaAnalyzer plugin
packages/plugin-dbbackup the built-in database backup plugin (Postgres, Supabase, MySQL, SQLite)
packages/plugin-cleaner the built-in Cleaner plugin (free disk space safely, local or over ssh)
```

`rsync-core` deliberately has no dependency on Electron or on the CLI, so the
Expand Down
1 change: 1 addition & 0 deletions apps/cli/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
"@diskpush/database": "workspace:*",
"@diskpush/fleet-core": "workspace:*",
"@diskpush/plugin-api": "workspace:*",
"@diskpush/plugin-cleaner": "workspace:*",
"@diskpush/plugin-dbbackup": "workspace:*",
"@diskpush/plugin-mediaanalyzer": "workspace:*",
"@diskpush/rsync-core": "workspace:*",
Expand Down
2 changes: 1 addition & 1 deletion apps/cli/src/bin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ async function runPlugin(argv: readonly string[]): Promise<number | null> {
})
for (const { name, error } of failures) output.warn(`plugin ${name} did not load: ${error}`)
if (await autoUpdate(call.pluginId, output) === 'updated') reexec()
return await runPluginCommand(registry, call.pluginId, call.args, output, serverDirectory(store))
return await runPluginCommand(registry, call.pluginId, call.args, output, serverDirectory(store), call.defaultCommand)
} catch (error) {
if (error instanceof PluginError) {
process.stderr.write(`${error.message}\n`)
Expand Down
22 changes: 22 additions & 0 deletions apps/cli/src/commands/plugins.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,28 @@ describe('dispatch to a plugin', () => {
expect(stripGlobalFlags(['--json', 'say', '-q', 'x'])).toEqual(['say', 'x'])
})

it('`diskpush clean` is the cleaner, and a missing command means run', async () => {
const { registry: r } = await loadPlugins(memoryBackend(), { external: false })
expect(await r.isEnabled('cleaner')).toBe(true)
expect(findPluginCall(['clean', 'web-1', '--apply'], r)).toEqual({ pluginId: 'cleaner', args: ['web-1', '--apply'], defaultCommand: 'run' })
expect(findPluginCall(['cleaner', 'report'], r)).toEqual({ pluginId: 'cleaner', args: ['report'] })
const said: string[][] = []
const fake = new PluginRegistry(memoryBackend())
fake.register(
definePlugin({
id: 'cleaner',
name: 'Cleaner',
version: '1',
description: 'x',
commands: ['run', 'report'].map((name) => ({ name, summary: name, usage: name, async run(args: string[]) { said.push([name, ...args]); return 0 } })),
}),
)
await runPluginCommand(fake, 'cleaner', ['web-1', '--apply'], output(), undefined, 'run')
await runPluginCommand(fake, 'cleaner', ['report', 'web-1'], output(), undefined, 'run')
await runPluginCommand(fake, 'cleaner', [], output(), undefined, 'run')
expect(said).toEqual([['run', 'web-1', '--apply'], ['report', 'web-1'], ['run']])
})

it('runs the command with its own arguments and a context bound to the plugin', async () => {
const r = registry()
const code = await runPluginCommand(r, 'echo', ['say', 'hello', 'world', '--loud'], output())
Expand Down
30 changes: 26 additions & 4 deletions apps/cli/src/commands/plugins.ts
Original file line number Diff line number Diff line change
Expand Up @@ -149,12 +149,27 @@ async function ask(question: string): Promise<string | null> {
export function findPluginCall(
argv: readonly string[],
registry: Pick<PluginRegistry, 'has'>,
): { pluginId: string; args: string[] } | null {
): { pluginId: string; args: string[]; defaultCommand?: string } | null {
const at = argv.findIndex((token) => !token.startsWith('-'))
if (at === -1) return null
const head = argv[at]!
const word = argv[at]!
const alias = PLUGIN_ALIASES[word]
const head = alias?.pluginId ?? word
if (!registry.has(head)) return null
return { pluginId: head, args: [...argv.slice(0, at), ...argv.slice(at + 1)] }
return {
pluginId: head,
args: [...argv.slice(0, at), ...argv.slice(at + 1)],
...(alias?.defaultCommand ? { defaultCommand: alias.defaultCommand } : {}),
}
}

/**
* Short names for built-in plugins. `diskpush clean` is the cleaner, and
* `diskpush clean [TARGET] [--apply]` with no command means `run`. The alias
* words are reserved plugin ids, so an external plugin cannot take them.
*/
export const PLUGIN_ALIASES: Record<string, { pluginId: string; defaultCommand?: string }> = {
clean: { pluginId: 'cleaner', defaultCommand: 'run' },
}

/** Global flags the CLI owns; everything else belongs to the plugin. */
Expand All @@ -176,9 +191,16 @@ export async function runPluginCommand(
argv: readonly string[],
output: Output,
servers?: ServerDirectory,
defaultCommand?: string,
): Promise<number> {
const plugin = await registry.require(pluginId)
const args = stripGlobalFlags(argv)
let args = stripGlobalFlags(argv)
// An alias with a default command: `diskpush clean web-1 --apply` is `diskpush cleaner run web-1 --apply`.
if (defaultCommand) {
const first = args[0]
const isHelp = first === 'help' || first === '--help' || first === '-h'
if (!isHelp && (first === undefined || !(plugin.commands ?? []).some((command) => command.name === first))) args = [defaultCommand, ...args]
}
const [name, ...rest] = args
if (!name || name === 'help' || name === '--help' || name === '-h') {
process.stdout.write(pluginUsage(plugin))
Expand Down
3 changes: 2 additions & 1 deletion apps/cli/src/plugins.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,12 +24,13 @@ import {
type SettingsBackend,
} from '@diskpush/plugin-api'
import { toServerRef } from '@diskpush/ssh-core'
import { cleanerPlugin } from '@diskpush/plugin-cleaner'
import { dbBackupPlugin } from '@diskpush/plugin-dbbackup'
import { mediaAnalyzerPlugin } from '@diskpush/plugin-mediaanalyzer'
import { sshConfigHosts } from './resolve.js'

/** Plugins that ship with DiskPush. */
export const BUILTIN_PLUGINS = [mediaAnalyzerPlugin, dbBackupPlugin]
export const BUILTIN_PLUGINS = [mediaAnalyzerPlugin, dbBackupPlugin, cleanerPlugin]

export type LoadedRegistry = { registry: PluginRegistry; failures: LoadFailure[] }

Expand Down
15 changes: 15 additions & 0 deletions apps/desktop/electron/main/ipc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ import {
ExternalUrlSchema,
FleetCheckRequestSchema,
FleetSyncRequestSchema,
CleanerScanRequestSchema,
CleanerApplyRequestSchema,
FleetSyncIdSchema,
FleetCommandSaveSchema,
FleetListRenameSchema,
Expand Down Expand Up @@ -53,6 +55,7 @@ import {
startFleet,
} from './services/fleet.js'
import { startFleetSync, cancelFleetSync } from './services/fleet-sync.js'
import { cleanerApply, cleanerCancel, cleanerScan, cleanerTargets } from './services/cleaner.js'
import { browserFor, dropSession, sessionFor, type RemoteBrowser } from './services/sessions.js'
import { store } from './services/store.js'
import { advanceSeries, handlersFor, openSeries, openWith, stopSeries } from './services/open-with.js'
Expand Down Expand Up @@ -472,6 +475,18 @@ export function registerIpc(): void {
setPluginEnabled(pluginId, enabled),
)

// --- cleaner -------------------------------------------------------------
// The renderer names a target and, to apply, a report id plus item ids from
// that report. Paths only ever come from the main process's own scan.

handle(IPC.cleanerTargets, z.undefined(), async () => cleanerTargets())

handle(IPC.cleanerScan, CleanerScanRequestSchema, async (request, event) => cleanerScan(request, event.sender))

handle(IPC.cleanerApply, CleanerApplyRequestSchema, async (request, event) => cleanerApply(request, event.sender))

handle(IPC.cleanerCancel, z.object({ jobId: JobIdSchema }), async ({ jobId }) => cleanerCancel(jobId))

// --- shell ---------------------------------------------------------------

handle(IPC.shellOpenExternal, z.object({ url: ExternalUrlSchema }), async ({ url }) => {
Expand Down
81 changes: 81 additions & 0 deletions apps/desktop/electron/main/services/cleaner.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
/**
* The Cleaner tab, in the main process.
*
* Scans and applies run here through the cleaner plugin's own core (the same
* code the CLI and MCP use), with the plugin's settings and the Fleet tab's
* servers. A scan's report is kept here under an id; an apply names that id
* and item ids from it, so the renderer can choose among findings but can
* never name a path of its own. Progress goes out on `plugins:progress`.
*/
import { randomUUID } from 'node:crypto'
import type { WebContents } from 'electron'
import { PluginError } from '@diskpush/plugin-api'
import { applyClean, listTargets, scanTarget, CLEANER_ID, type ApplyResult, type Report, type Target } from '@diskpush/plugin-cleaner'
import { IPC, type CleanerApplyRequest, type CleanerScanRequest } from '../../shared/contract.js'
import { pluginHostContext, pluginRegistry } from './plugins.js'

const reports = new Map<string, Report>()
const running = new Map<string, AbortController>()

async function requireEnabled(): Promise<void> {
const { registry } = await pluginRegistry()
if (!registry.has(CLEANER_ID)) throw new PluginError('The Cleaner plugin is not installed.')
if (!(await registry.isEnabled(CLEANER_ID))) throw new PluginError('The Cleaner plugin is disabled. Turn it on under Plugins….')
}

export async function cleanerTargets(): Promise<Target[]> {
await requireEnabled()
return listTargets(await pluginHostContext(CLEANER_ID, 'cleaner-targets', null, new AbortController().signal))
}

async function track<T>(jobId: string, work: (signal: AbortSignal) => Promise<T>): Promise<T> {
if (running.has(jobId)) throw new PluginError('That job id is already running.')
const controller = new AbortController()
running.set(jobId, controller)
try {
return await work(controller.signal)
} finally {
running.delete(jobId)
}
}

export type CleanerScanResult = { reportId: string; report: Report }

export async function cleanerScan(request: CleanerScanRequest, sender: WebContents): Promise<CleanerScanResult> {
await requireEnabled()
return track(request.jobId, async (signal) => {
const ctx = await pluginHostContext(CLEANER_ID, request.jobId, sender, signal)
const report = await scanTarget(ctx, request.target, {
...(request.only.length ? { only: request.only } : {}),
...(request.idleDays ? { idleDays: request.idleDays } : {}),
})
const reportId = randomUUID()
// One report per target is enough to apply from; older ones go.
for (const [id, old] of reports) if (old.target === report.target) reports.delete(id)
reports.set(reportId, report)
return { reportId, report }
})
}

export async function cleanerApply(request: CleanerApplyRequest, sender: WebContents): Promise<ApplyResult> {
await requireEnabled()
const report = reports.get(request.reportId)
if (!report) throw new PluginError('That report is gone; scan again first.')
return track(request.jobId, async (signal) => {
const ctx = await pluginHostContext(CLEANER_ID, request.jobId, sender, signal)
const result = await applyClean(ctx, report, { apply: true, ids: request.ids })
// What was removed is no longer in the report; a re-scan shows the new state.
reports.delete(request.reportId)
if (!sender.isDestroyed()) {
sender.send(IPC.eventPlugin, { jobId: request.jobId, event: { type: 'exit', ok: true, message: 'done', changed: true, cancelled: signal.aborted } })
}
return result
})
}

export function cleanerCancel(jobId: string): boolean {
const controller = running.get(jobId)
if (!controller) return false
controller.abort()
return true
}
23 changes: 22 additions & 1 deletion apps/desktop/electron/main/services/plugins.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import {
runAction,
runTask,
type ActionResult,
type BaseContext,
type HostContext,
type LoadFailure,
type LogLevel,
Expand All @@ -28,6 +29,7 @@ import {
type SettingDef,
} from '@diskpush/plugin-api'
import { toServerRef } from '@diskpush/ssh-core'
import { cleanerPlugin } from '@diskpush/plugin-cleaner'
import { dbBackupPlugin } from '@diskpush/plugin-dbbackup'
import { mediaAnalyzerPlugin } from '@diskpush/plugin-mediaanalyzer'
import { ExternalUrlSchema, IPC, type PluginActionRequest } from '../../shared/contract.js'
Expand All @@ -36,7 +38,7 @@ import { isLocalConnectionId } from './local-session.js'
import { store } from './store.js'

/** The same built-in list as the CLI's (apps/cli/src/plugins.ts). */
const BUILTIN_PLUGINS = [mediaAnalyzerPlugin, dbBackupPlugin]
const BUILTIN_PLUGINS = [mediaAnalyzerPlugin, dbBackupPlugin, cleanerPlugin]

let loaded: Promise<{ registry: PluginRegistry; failures: LoadFailure[] }> | null = null

Expand Down Expand Up @@ -138,6 +140,25 @@ const servers: ServerDirectory = {
sshConfigFile: process.env.DISKPUSH_SSH_CONFIG ?? null,
}

/**
* A plugin's full context for host-owned screens (the Cleaner tab) that call
* a built-in plugin's core directly instead of through an action. Progress
* goes out on `plugins:progress` under `jobId` when there is a window to send it to.
*/
export async function pluginHostContext(pluginId: string, jobId: string, sender: WebContents | null, signal: AbortSignal): Promise<BaseContext> {
const { registry } = await pluginRegistry()
return {
settings: registry.settingsFor(pluginId),
secrets: registry.secretsFor(pluginId),
progress: sender ? sink(jobId, sender) : { start() {}, update() {}, log() {} },
openUrl,
signal,
surface: 'desktop',
env: process.env,
servers,
}
}

/** Starts `work` under a fresh AbortController, reports its outcome, and returns at once. */
function launch(jobId: string, sender: WebContents, work: (host: HostContext) => Promise<ActionResult>): { jobId: string } {
if (running.has(jobId)) throw new PluginError('That job id is already running.')
Expand Down
8 changes: 8 additions & 0 deletions apps/desktop/electron/preload/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,14 @@ const api = {
call<boolean>(IPC.pluginsSetSettings, { pluginId, values }),
setEnabled: (pluginId: string, enabled: boolean) => call<boolean>(IPC.pluginsSetEnabled, { pluginId, enabled }),
},
// The Cleaner tab: targets by name, applies by report id + item ids. Never a path.
cleaner: {
targets: () => call(IPC.cleanerTargets),
scan: (jobId: string, target: string, only: string[] = [], idleDays?: number) =>
call(IPC.cleanerScan, { jobId, target, only, ...(idleDays ? { idleDays } : {}) }),
apply: (jobId: string, reportId: string, ids: string[]) => call(IPC.cleanerApply, { jobId, reportId, ids }),
cancel: (jobId: string) => call<boolean>(IPC.cleanerCancel, { jobId }),
},
events: {
/**
* Returns an unsubscribe function. The listener is wrapped so the
Expand Down
30 changes: 30 additions & 0 deletions apps/desktop/electron/shared/contract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,12 @@ export const IPC = {
pluginsSetSettings: 'plugins:set-settings',
pluginsSetEnabled: 'plugins:set-enabled',

/** The Cleaner tab: free disk space on this machine or a server (plugin `cleaner`). */
cleanerTargets: 'cleaner:targets',
cleanerScan: 'cleaner:scan',
cleanerApply: 'cleaner:apply',
cleanerCancel: 'cleaner:cancel',

/** Main -> renderer, progress and the outcome of a plugin action or task. */
eventPlugin: 'plugins:progress',

Expand Down Expand Up @@ -529,6 +535,30 @@ export const PluginSettingsSetSchema = z.object({
.refine((values) => Object.keys(values).length <= 64, { message: 'Too many settings at once.' }),
})

/**
* The Cleaner tab. The renderer names a target (`local` or a server name the
* main process looks up) and, to apply, the id of a report the main process
* produced plus item ids from it. It never sends a path: what is removed is
* whatever the main process's own scan found, re-checked on the target.
*/
export const CleanerTargetSchema = z.string().regex(/^[A-Za-z0-9_.@:-]{1,128}$/, 'That is not a target name.')
export const CleanerCategorySchema = z.enum(['caches', 'docker', 'logs', 'build', 'partials'])

export const CleanerScanRequestSchema = z.object({
jobId: JobIdSchema,
target: CleanerTargetSchema,
only: z.array(CleanerCategorySchema).max(5).default([]),
idleDays: z.number().int().min(1).max(3650).optional(),
})
export type CleanerScanRequest = z.infer<typeof CleanerScanRequestSchema>

export const CleanerApplyRequestSchema = z.object({
jobId: JobIdSchema,
reportId: z.string().regex(/^[a-z0-9-]{1,64}$/),
ids: z.array(z.string().min(1).max(8192)).min(1).max(50000),
})
export type CleanerApplyRequest = z.infer<typeof CleanerApplyRequestSchema>

/** Only http(s) may be handed to the system browser. */
export const ExternalUrlSchema = z.string().url().refine((value) => /^https?:\/\//i.test(value), {
message: 'Only http and https URLs can be opened externally.',
Expand Down
Loading
Loading