@myrialabs/clopen 0.4.33 → 0.4.35
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/backend/auth/permissions.ts +10 -0
- package/backend/auth/rate-limiter.test.ts +115 -0
- package/backend/auth/rate-limiter.ts +25 -12
- package/backend/containers/actions.ts +316 -0
- package/backend/containers/disk-usage.test.ts +68 -0
- package/backend/containers/disk-usage.ts +170 -0
- package/backend/containers/logs.ts +335 -0
- package/backend/containers/monitor.ts +410 -0
- package/backend/containers/parse.test.ts +599 -0
- package/backend/containers/parse.ts +905 -0
- package/backend/containers/port-index.test.ts +91 -0
- package/backend/containers/port-index.ts +198 -0
- package/backend/containers/prune-job.test.ts +148 -0
- package/backend/containers/prune-job.ts +129 -0
- package/backend/containers/pty-backend.ts +337 -0
- package/backend/containers/pty.ts +114 -0
- package/backend/containers/runtime.ts +218 -0
- package/backend/containers/scan.ts +293 -0
- package/backend/db-client/connection-manager.ts +13 -0
- package/backend/files/file-watcher.test.ts +105 -0
- package/backend/files/file-watcher.ts +45 -1
- package/backend/git/git-service.test.ts +33 -0
- package/backend/git/git-service.ts +7 -3
- package/backend/git/nested-repos.test.ts +292 -1
- package/backend/git/nested-repos.ts +330 -17
- package/backend/host/runner.ts +204 -0
- package/backend/index.ts +20 -2
- package/backend/middleware/security.test.ts +95 -0
- package/backend/middleware/security.ts +114 -0
- package/backend/ports/attribute.test.ts +231 -0
- package/backend/ports/attribute.ts +444 -0
- package/backend/ports/kill.ts +203 -0
- package/backend/ports/monitor.ts +365 -0
- package/backend/ports/processes.test.ts +98 -0
- package/backend/ports/processes.ts +374 -0
- package/backend/ports/registry.ts +165 -0
- package/backend/ports/scan-host.ts +329 -0
- package/backend/ports/scan.test.ts +341 -0
- package/backend/ports/scan.ts +687 -0
- package/backend/ports/ssh-lineage.ts +318 -0
- package/backend/preview/browser/browser-video-capture.ts +84 -31
- package/backend/ssh/forwards.ts +31 -0
- package/backend/ws/auth/device.ts +1 -1
- package/backend/ws/auth/login.ts +8 -4
- package/backend/ws/containers/actions.ts +156 -0
- package/backend/ws/containers/index.ts +43 -0
- package/backend/ws/containers/list.ts +146 -0
- package/backend/ws/containers/logs.ts +43 -0
- package/backend/ws/containers/tunnel.ts +101 -0
- package/backend/ws/git/log.ts +3 -1
- package/backend/ws/git/status.ts +37 -27
- package/backend/ws/index.ts +4 -0
- package/backend/ws/message-rate-limiter.test.ts +45 -0
- package/backend/ws/message-rate-limiter.ts +34 -3
- package/backend/ws/ports/index.ts +19 -0
- package/backend/ws/ports/kill.ts +80 -0
- package/backend/ws/ports/list.ts +60 -0
- package/backend/ws/ssh/connections.ts +8 -0
- package/backend/ws/system/device-info.ts +99 -43
- package/dist/assets/{index-BF4buYmI.js → index-B0iIhSO9.js} +1 -1
- package/dist/assets/{index-BW0DA8NV.js → index-BRJqss6F.js} +1 -1
- package/dist/assets/main-Buko4D0t.css +1 -0
- package/dist/assets/{main-BbwWLJRN.js → main-C_iGUZyL.js} +468 -447
- package/dist/index.html +2 -2
- package/dist/manifest.json +9 -2
- package/package.json +1 -1
- package/shared/types/containers/container.ts +366 -0
- package/shared/types/containers/index.ts +5 -0
- package/shared/types/host/index.ts +18 -0
- package/shared/types/ports/index.ts +5 -0
- package/shared/types/ports/port.ts +230 -0
- package/shared/utils/logger.ts +3 -0
- package/shared/utils/ws-client.ts +67 -12
- package/shared/utils/ws-server.ts +64 -13
- package/dist/assets/main-CCvRMXlP.css +0 -1
|
@@ -43,6 +43,16 @@ export const ADMIN_ONLY_ROUTES = new Set([
|
|
|
43
43
|
'settings:update-batch',
|
|
44
44
|
'system:run-update',
|
|
45
45
|
'system:clear-data',
|
|
46
|
+
// Port manager — anyone signed in may see what is listening, but ending a
|
|
47
|
+
// process can take down another member's work, so stopping is admin-only.
|
|
48
|
+
'ports:kill',
|
|
49
|
+
// Containers — anyone signed in may see what is running, but starting or
|
|
50
|
+
// stopping one takes down whatever it serves for everyone else. Opening a
|
|
51
|
+
// shell inside a container is gated separately, in the PtyKit authorize.
|
|
52
|
+
'containers:action',
|
|
53
|
+
'containers:remove',
|
|
54
|
+
'containers:prune',
|
|
55
|
+
'containers:prune-dismiss',
|
|
46
56
|
// Stack — binary installation is an admin-only operation.
|
|
47
57
|
'stack:status',
|
|
48
58
|
'stack:status-all',
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Behavior-based tests for AuthRateLimiter.
|
|
3
|
+
*
|
|
4
|
+
* Validates:
|
|
5
|
+
* - Failure-based lockout tiers (5/10/20 → 30s/2m/10m) still trigger.
|
|
6
|
+
* - Lockout state is per-route and per-identifier, so a lockout on one
|
|
7
|
+
* endpoint neither blocks nor is cleared by another.
|
|
8
|
+
* - `recordSuccess` clears only its own route's record.
|
|
9
|
+
*
|
|
10
|
+
* Each test uses a unique identifier so the singleton's in-memory state does
|
|
11
|
+
* not bleed across tests.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import { describe, expect, test } from 'bun:test';
|
|
15
|
+
import { authRateLimiter } from './rate-limiter';
|
|
16
|
+
|
|
17
|
+
let seq = 0;
|
|
18
|
+
function uniqueId(label: string): string {
|
|
19
|
+
// IPv4-shaped string the rate limiter treats as opaque.
|
|
20
|
+
return `203.0.113.${++seq}-${label}`;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** Read the remaining lockout out of `check()`'s message. */
|
|
24
|
+
function remainingMs(result: string | null): number | null {
|
|
25
|
+
if (result === null) return null;
|
|
26
|
+
const match = result.match(/Try again in (\d+) seconds/);
|
|
27
|
+
return match ? Number(match[1]) * 1000 : 0;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** Drive an identifier to `count` failures on one route. */
|
|
31
|
+
function fail(id: string, action: string, count: number): void {
|
|
32
|
+
for (let i = 0; i < count; i++) authRateLimiter.recordFailure(id, action);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
describe('failure-based lockout tiers', () => {
|
|
36
|
+
test('four failures stay below the first threshold', () => {
|
|
37
|
+
const id = uniqueId('4fail');
|
|
38
|
+
fail(id, 'auth:login', 4);
|
|
39
|
+
expect(authRateLimiter.check(id, 'auth:login')).toBeNull();
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
test('five failures lock for 30s', () => {
|
|
43
|
+
const id = uniqueId('5fail');
|
|
44
|
+
fail(id, 'auth:login', 5);
|
|
45
|
+
expect(remainingMs(authRateLimiter.check(id, 'auth:login'))).toBeGreaterThanOrEqual(25_000);
|
|
46
|
+
expect(remainingMs(authRateLimiter.check(id, 'auth:login'))).toBeLessThanOrEqual(30_500);
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
test('ten failures escalate to a 2-minute lockout', () => {
|
|
50
|
+
const id = uniqueId('10fail');
|
|
51
|
+
fail(id, 'auth:login', 10);
|
|
52
|
+
expect(remainingMs(authRateLimiter.check(id, 'auth:login'))).toBeGreaterThanOrEqual(115_000);
|
|
53
|
+
expect(remainingMs(authRateLimiter.check(id, 'auth:login'))).toBeLessThanOrEqual(120_500);
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
test('twenty failures escalate to a 10-minute lockout', () => {
|
|
57
|
+
const id = uniqueId('20fail');
|
|
58
|
+
fail(id, 'auth:login', 20);
|
|
59
|
+
expect(remainingMs(authRateLimiter.check(id, 'auth:login'))).toBeGreaterThanOrEqual(595_000);
|
|
60
|
+
expect(remainingMs(authRateLimiter.check(id, 'auth:login'))).toBeLessThanOrEqual(600_500);
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
test('routes outside the rate-limited set are ignored', () => {
|
|
64
|
+
const id = uniqueId('unlimited');
|
|
65
|
+
fail(id, 'auth:logout', 5);
|
|
66
|
+
expect(authRateLimiter.check(id, 'auth:logout')).toBeNull();
|
|
67
|
+
});
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
describe('per-route isolation', () => {
|
|
71
|
+
test('a lockout on auth:login does not block auth:validate-invite', () => {
|
|
72
|
+
const id = uniqueId('route-iso');
|
|
73
|
+
fail(id, 'auth:login', 5);
|
|
74
|
+
|
|
75
|
+
expect(authRateLimiter.check(id, 'auth:login')).not.toBeNull();
|
|
76
|
+
expect(authRateLimiter.check(id, 'auth:validate-invite')).toBeNull();
|
|
77
|
+
expect(authRateLimiter.check(id, 'auth:claim-device-code')).toBeNull();
|
|
78
|
+
});
|
|
79
|
+
|
|
80
|
+
test('success on one route does not clear another route\'s failures', () => {
|
|
81
|
+
const id = uniqueId('no-cross-clear');
|
|
82
|
+
fail(id, 'auth:login', 5);
|
|
83
|
+
authRateLimiter.recordSuccess(id, 'auth:validate-invite');
|
|
84
|
+
|
|
85
|
+
expect(authRateLimiter.check(id, 'auth:login')).not.toBeNull();
|
|
86
|
+
});
|
|
87
|
+
|
|
88
|
+
test('success clears the lockout for its own route', () => {
|
|
89
|
+
const id = uniqueId('self-clear');
|
|
90
|
+
fail(id, 'auth:login', 5);
|
|
91
|
+
authRateLimiter.recordSuccess(id, 'auth:login');
|
|
92
|
+
|
|
93
|
+
expect(authRateLimiter.check(id, 'auth:login')).toBeNull();
|
|
94
|
+
});
|
|
95
|
+
|
|
96
|
+
test('a valid invite clears the failures from earlier mistyped ones', () => {
|
|
97
|
+
const id = uniqueId('invite-retry');
|
|
98
|
+
fail(id, 'auth:validate-invite', 2);
|
|
99
|
+
authRateLimiter.recordSuccess(id, 'auth:validate-invite');
|
|
100
|
+
fail(id, 'auth:validate-invite', 4);
|
|
101
|
+
|
|
102
|
+
expect(authRateLimiter.check(id, 'auth:validate-invite')).toBeNull();
|
|
103
|
+
});
|
|
104
|
+
});
|
|
105
|
+
|
|
106
|
+
describe('per-identifier isolation', () => {
|
|
107
|
+
test('one identifier locking out does not affect another', () => {
|
|
108
|
+
const idA = uniqueId('ipA');
|
|
109
|
+
const idB = uniqueId('ipB');
|
|
110
|
+
fail(idA, 'auth:login', 5);
|
|
111
|
+
|
|
112
|
+
expect(authRateLimiter.check(idA, 'auth:login')).not.toBeNull();
|
|
113
|
+
expect(authRateLimiter.check(idB, 'auth:login')).toBeNull();
|
|
114
|
+
});
|
|
115
|
+
});
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
* Auth Rate Limiter
|
|
3
3
|
*
|
|
4
4
|
* Protects auth endpoints against brute-force and credential stuffing attacks.
|
|
5
|
-
* Tracks failed attempts per IP with progressive lockout.
|
|
5
|
+
* Tracks failed attempts per (IP, route) with progressive lockout.
|
|
6
6
|
*
|
|
7
7
|
* Thresholds:
|
|
8
8
|
* 5 failures → 30 second lockout
|
|
@@ -10,11 +10,15 @@
|
|
|
10
10
|
* 20 failures → 10 minute lockout
|
|
11
11
|
*
|
|
12
12
|
* Attempts decay after the lockout window expires.
|
|
13
|
+
*
|
|
14
|
+
* Records are keyed by IP *and* route: a lockout earned on one endpoint must
|
|
15
|
+
* not block an unrelated one, and clearing one route's record on success must
|
|
16
|
+
* not wipe another route's accumulated failures.
|
|
13
17
|
*/
|
|
14
18
|
|
|
15
19
|
import { debug } from '$shared/utils/logger';
|
|
16
20
|
|
|
17
|
-
/** Routes that should be rate-limited */
|
|
21
|
+
/** Routes that should be rate-limited. */
|
|
18
22
|
const RATE_LIMITED_ROUTES = new Set([
|
|
19
23
|
'auth:login',
|
|
20
24
|
'auth:accept-invite',
|
|
@@ -43,6 +47,7 @@ const STALE_AFTER_MS = 15 * 60_000; // 15 minutes
|
|
|
43
47
|
const CLEANUP_INTERVAL_MS = 5 * 60_000; // 5 minutes
|
|
44
48
|
|
|
45
49
|
class AuthRateLimiter {
|
|
50
|
+
/** Keyed by `${identifier}::${action}` — see the note on the module doc. */
|
|
46
51
|
private attempts = new Map<string, AttemptRecord>();
|
|
47
52
|
private cleanupTimer: ReturnType<typeof setInterval> | null = null;
|
|
48
53
|
|
|
@@ -51,6 +56,10 @@ class AuthRateLimiter {
|
|
|
51
56
|
this.cleanupTimer = setInterval(() => this.cleanup(), CLEANUP_INTERVAL_MS);
|
|
52
57
|
}
|
|
53
58
|
|
|
59
|
+
private static recordKey(identifier: string, action: string): string {
|
|
60
|
+
return `${identifier}::${action}`;
|
|
61
|
+
}
|
|
62
|
+
|
|
54
63
|
/**
|
|
55
64
|
* Check if an action is rate-limited for the given identifier.
|
|
56
65
|
* Returns null if allowed, or an error message if blocked.
|
|
@@ -60,9 +69,9 @@ class AuthRateLimiter {
|
|
|
60
69
|
return null; // Not a rate-limited route
|
|
61
70
|
}
|
|
62
71
|
|
|
63
|
-
const record = this.attempts.get(identifier);
|
|
72
|
+
const record = this.attempts.get(AuthRateLimiter.recordKey(identifier, action));
|
|
64
73
|
if (!record) {
|
|
65
|
-
return null; // No previous
|
|
74
|
+
return null; // No previous activity
|
|
66
75
|
}
|
|
67
76
|
|
|
68
77
|
const now = Date.now();
|
|
@@ -70,7 +79,7 @@ class AuthRateLimiter {
|
|
|
70
79
|
// Check if currently locked out
|
|
71
80
|
if (record.lockedUntil > now) {
|
|
72
81
|
const remainingSec = Math.ceil((record.lockedUntil - now) / 1000);
|
|
73
|
-
debug.warn('auth', `Rate limited: ${identifier} (${remainingSec}s remaining, ${record.failures} failures)`);
|
|
82
|
+
debug.warn('auth', `Rate limited: ${identifier} on ${action} (${remainingSec}s remaining, ${record.failures} failures)`);
|
|
74
83
|
return `Too many failed attempts. Try again in ${remainingSec} seconds.`;
|
|
75
84
|
}
|
|
76
85
|
|
|
@@ -78,13 +87,15 @@ class AuthRateLimiter {
|
|
|
78
87
|
}
|
|
79
88
|
|
|
80
89
|
/**
|
|
81
|
-
* Record a failed auth attempt for the given identifier.
|
|
90
|
+
* Record a failed auth attempt for the given identifier + action.
|
|
91
|
+
* Escalates the failure-tier lockout when a new threshold is crossed.
|
|
82
92
|
*/
|
|
83
93
|
recordFailure(identifier: string, action: string): void {
|
|
84
94
|
if (!RATE_LIMITED_ROUTES.has(action)) return;
|
|
85
95
|
|
|
86
96
|
const now = Date.now();
|
|
87
|
-
const
|
|
97
|
+
const key = AuthRateLimiter.recordKey(identifier, action);
|
|
98
|
+
const record = this.attempts.get(key) ?? { failures: 0, lastFailure: 0, lockedUntil: 0 };
|
|
88
99
|
|
|
89
100
|
record.failures += 1;
|
|
90
101
|
record.lastFailure = now;
|
|
@@ -99,17 +110,19 @@ class AuthRateLimiter {
|
|
|
99
110
|
|
|
100
111
|
if (lockoutMs > 0) {
|
|
101
112
|
record.lockedUntil = now + lockoutMs;
|
|
102
|
-
debug.warn('auth', `Lockout triggered: ${identifier} — ${record.failures} failures, locked for ${lockoutMs / 1000}s`);
|
|
113
|
+
debug.warn('auth', `Lockout triggered: ${identifier} on ${action} — ${record.failures} failures, locked for ${lockoutMs / 1000}s`);
|
|
103
114
|
}
|
|
104
115
|
|
|
105
|
-
this.attempts.set(
|
|
116
|
+
this.attempts.set(key, record);
|
|
106
117
|
}
|
|
107
118
|
|
|
108
119
|
/**
|
|
109
|
-
* Clear failure record on successful auth (e.g., successful
|
|
120
|
+
* Clear the failure record for this route on successful auth (e.g., successful
|
|
121
|
+
* login). Other routes keep whatever they had accumulated.
|
|
110
122
|
*/
|
|
111
|
-
recordSuccess(identifier: string): void {
|
|
112
|
-
|
|
123
|
+
recordSuccess(identifier: string, action: string): void {
|
|
124
|
+
if (!RATE_LIMITED_ROUTES.has(action)) return;
|
|
125
|
+
this.attempts.delete(AuthRateLimiter.recordKey(identifier, action));
|
|
113
126
|
}
|
|
114
127
|
|
|
115
128
|
/**
|
|
@@ -0,0 +1,316 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Containers — starting, stopping, removing, and clearing up after.
|
|
3
|
+
*
|
|
4
|
+
* Every action addresses a container or an image by its full id, and a volume
|
|
5
|
+
* or a network by its name, and every one of those is checked against a
|
|
6
|
+
* pattern before it reaches a command line. Names arrive over a socket, and an
|
|
7
|
+
* argument that begins with a dash is a flag; `assertContainerId` and
|
|
8
|
+
* `assertResourceName` are the gate that stops one becoming the other. Nothing
|
|
9
|
+
* here ever runs through `sudo`: an account that may not talk to the runtime is
|
|
10
|
+
* told so.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import type {
|
|
14
|
+
ContainerAction,
|
|
15
|
+
ContainerActionResult,
|
|
16
|
+
ContainerDetail,
|
|
17
|
+
ContainerResourceKind,
|
|
18
|
+
ContainerRuntime,
|
|
19
|
+
ContainerStats,
|
|
20
|
+
PruneKind,
|
|
21
|
+
PruneOutcome
|
|
22
|
+
} from '$shared/types/containers';
|
|
23
|
+
import { CONTAINER_TIMEOUTS } from '$shared/types/containers';
|
|
24
|
+
import { containerMonitor } from './monitor';
|
|
25
|
+
import { invalidateDiskUsage } from './disk-usage';
|
|
26
|
+
import { containerArgv, detectRuntime, firstProblem, tryRun } from './runtime';
|
|
27
|
+
import { parseInspect, parsePruneOutput, parseStats } from './parse';
|
|
28
|
+
import { debug } from '$shared/utils/logger';
|
|
29
|
+
|
|
30
|
+
/** Both runtimes identify a container or an image with hex. */
|
|
31
|
+
const CONTAINER_ID = /^[a-f0-9]{12,64}$/i;
|
|
32
|
+
/** An image id may carry the digest algorithm that produced it. */
|
|
33
|
+
const IMAGE_ID = /^(sha256:)?[a-f0-9]{12,64}$/i;
|
|
34
|
+
/**
|
|
35
|
+
* The character set both runtimes allow in a volume or network name. Anchored
|
|
36
|
+
* at both ends and required to start with an alphanumeric, so nothing that
|
|
37
|
+
* could be read as a flag or a path ever gets through.
|
|
38
|
+
*/
|
|
39
|
+
const RESOURCE_NAME = /^[a-zA-Z0-9][a-zA-Z0-9_.-]{0,127}$/;
|
|
40
|
+
|
|
41
|
+
export function isContainerId(value: string): boolean {
|
|
42
|
+
return CONTAINER_ID.test(value);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export function assertContainerId(value: string): string {
|
|
46
|
+
if (!isContainerId(value)) throw new Error('That is not a container id.');
|
|
47
|
+
return value;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** Validate whatever identifies a resource of this kind, or refuse it. */
|
|
51
|
+
export function assertResourceId(kind: ContainerResourceKind, value: string): string {
|
|
52
|
+
const ok =
|
|
53
|
+
kind === 'container'
|
|
54
|
+
? CONTAINER_ID.test(value)
|
|
55
|
+
: kind === 'image'
|
|
56
|
+
? IMAGE_ID.test(value)
|
|
57
|
+
: RESOURCE_NAME.test(value);
|
|
58
|
+
if (!ok) throw new Error(`That is not a ${kind} Clopen can address.`);
|
|
59
|
+
return value;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
/** The argv for each action, which is where `remove` stops being one word. */
|
|
64
|
+
function actionArgv(action: ContainerAction, containerId: string): string[] {
|
|
65
|
+
switch (action) {
|
|
66
|
+
case 'remove':
|
|
67
|
+
return ['rm', containerId];
|
|
68
|
+
case 'force-remove':
|
|
69
|
+
// The runtime stops it first. Offered separately from `remove` so the
|
|
70
|
+
// confirmation can say that outright rather than surprising anyone.
|
|
71
|
+
return ['rm', '--force', containerId];
|
|
72
|
+
default:
|
|
73
|
+
return [action, containerId];
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export async function runContainerAction(
|
|
78
|
+
hostId: string,
|
|
79
|
+
containerId: string,
|
|
80
|
+
action: ContainerAction
|
|
81
|
+
): Promise<ContainerActionResult> {
|
|
82
|
+
assertContainerId(containerId);
|
|
83
|
+
|
|
84
|
+
const result = await containerMonitor.withHost(hostId, async (runner, platform) => {
|
|
85
|
+
const info = await detectRuntime(hostId, runner, platform);
|
|
86
|
+
if (info.problem !== 'none' || !info.runtime) {
|
|
87
|
+
return { ok: false, error: 'This host has no container runtime available right now.' };
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
const outcome = await tryRun(
|
|
91
|
+
runner,
|
|
92
|
+
containerArgv(info.runtime, platform, actionArgv(action, containerId)),
|
|
93
|
+
CONTAINER_TIMEOUTS.action
|
|
94
|
+
);
|
|
95
|
+
if (outcome.code === 0) return { ok: true, error: null };
|
|
96
|
+
|
|
97
|
+
const reason = firstProblem(outcome.stderr, outcome.stdout, outcome.code);
|
|
98
|
+
debug.warn('containers', `${action} failed for ${containerId} on ${hostId}: ${reason}`);
|
|
99
|
+
return { ok: false, error: reason };
|
|
100
|
+
});
|
|
101
|
+
|
|
102
|
+
// The table is a second or two old at most, but an action is the one moment
|
|
103
|
+
// a user expects it to be instant.
|
|
104
|
+
containerMonitor.invalidate(hostId);
|
|
105
|
+
// Starting and stopping do not move the disk figures enough to be worth
|
|
106
|
+
// re-measuring for; removing a container does.
|
|
107
|
+
if (action === 'remove' || action === 'force-remove') invalidateDiskUsage(hostId);
|
|
108
|
+
return result;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** The argv that removes one resource of each kind. */
|
|
112
|
+
function removeArgv(kind: ContainerResourceKind, id: string, force: boolean): string[] {
|
|
113
|
+
switch (kind) {
|
|
114
|
+
case 'container':
|
|
115
|
+
return force ? ['rm', '--force', id] : ['rm', id];
|
|
116
|
+
case 'image':
|
|
117
|
+
return force ? ['image', 'rm', '--force', id] : ['image', 'rm', id];
|
|
118
|
+
case 'volume':
|
|
119
|
+
return force ? ['volume', 'rm', '--force', id] : ['volume', 'rm', id];
|
|
120
|
+
case 'network':
|
|
121
|
+
return ['network', 'rm', id];
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* Remove one image, volume or network.
|
|
127
|
+
*
|
|
128
|
+
* Deliberately not forgiving: the runtime refuses to remove anything still in
|
|
129
|
+
* use, and that refusal is passed straight through rather than being retried
|
|
130
|
+
* with `--force`. A volume a running container has mounted is not a volume the
|
|
131
|
+
* user meant to delete, whatever the button said.
|
|
132
|
+
*/
|
|
133
|
+
export async function removeResource(
|
|
134
|
+
hostId: string,
|
|
135
|
+
kind: ContainerResourceKind,
|
|
136
|
+
id: string,
|
|
137
|
+
force = false
|
|
138
|
+
): Promise<ContainerActionResult> {
|
|
139
|
+
assertResourceId(kind, id);
|
|
140
|
+
|
|
141
|
+
const result = await containerMonitor.withHost(hostId, async (runner, platform) => {
|
|
142
|
+
const info = await detectRuntime(hostId, runner, platform);
|
|
143
|
+
if (info.problem !== 'none' || !info.runtime) {
|
|
144
|
+
return { ok: false, error: 'This host has no container runtime available right now.' };
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
const outcome = await tryRun(
|
|
148
|
+
runner,
|
|
149
|
+
containerArgv(info.runtime, platform, removeArgv(kind, id, force)),
|
|
150
|
+
CONTAINER_TIMEOUTS.action
|
|
151
|
+
);
|
|
152
|
+
if (outcome.code === 0) return { ok: true, error: null };
|
|
153
|
+
|
|
154
|
+
const reason = firstProblem(outcome.stderr, outcome.stdout, outcome.code);
|
|
155
|
+
debug.warn('containers', `could not remove ${kind} ${id} on ${hostId}: ${reason}`);
|
|
156
|
+
return { ok: false, error: reason };
|
|
157
|
+
});
|
|
158
|
+
|
|
159
|
+
containerMonitor.invalidate(hostId);
|
|
160
|
+
invalidateDiskUsage(hostId);
|
|
161
|
+
return result;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/**
|
|
165
|
+
* The argv for a sweep.
|
|
166
|
+
*
|
|
167
|
+
* `volumes` is the one place the two runtimes had to be reconciled rather than
|
|
168
|
+
* passed through. Podman's `volume prune` removes every unused volume; Docker's
|
|
169
|
+
* removes only the anonymous ones unless it is given `--all`, which older
|
|
170
|
+
* Docker does not have. So Docker is asked with `--all` and falls back without
|
|
171
|
+
* it, and both runtimes end up meaning the same thing — which is what the
|
|
172
|
+
* confirmation says they mean.
|
|
173
|
+
*/
|
|
174
|
+
function pruneArgv(kind: PruneKind, runtime: ContainerRuntime): string[] {
|
|
175
|
+
switch (kind) {
|
|
176
|
+
case 'containers':
|
|
177
|
+
return ['container', 'prune', '--force'];
|
|
178
|
+
case 'dangling-images':
|
|
179
|
+
return ['image', 'prune', '--force'];
|
|
180
|
+
case 'images':
|
|
181
|
+
return ['image', 'prune', '--all', '--force'];
|
|
182
|
+
case 'volumes':
|
|
183
|
+
return runtime === 'docker'
|
|
184
|
+
? ['volume', 'prune', '--all', '--force']
|
|
185
|
+
: ['volume', 'prune', '--force'];
|
|
186
|
+
case 'networks':
|
|
187
|
+
return ['network', 'prune', '--force'];
|
|
188
|
+
case 'build-cache':
|
|
189
|
+
return ['builder', 'prune', '--force'];
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/** True when a command failed because the runtime is too old for a flag. */
|
|
194
|
+
function unknownFlag(stderr: string): boolean {
|
|
195
|
+
return /unknown flag|unknown shorthand|flag provided but not defined|unrecognized option/i.test(
|
|
196
|
+
stderr
|
|
197
|
+
);
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/**
|
|
201
|
+
* Run a set of sweeps, one after another.
|
|
202
|
+
*
|
|
203
|
+
* Sequential rather than parallel: both runtimes serialise this work behind
|
|
204
|
+
* their own lock anyway, and on an SSH host every one of these is a command on
|
|
205
|
+
* a shared connection. A failure in one kind does not stop the rest — a host
|
|
206
|
+
* with no build cache should not cost the user their volume sweep.
|
|
207
|
+
*/
|
|
208
|
+
export async function pruneResources(hostId: string, kinds: PruneKind[]): Promise<PruneOutcome[]> {
|
|
209
|
+
const outcomes = await containerMonitor.withHost(hostId, async (runner, platform) => {
|
|
210
|
+
const info = await detectRuntime(hostId, runner, platform);
|
|
211
|
+
if (info.problem !== 'none' || !info.runtime) {
|
|
212
|
+
return kinds.map((kind) => ({
|
|
213
|
+
kind,
|
|
214
|
+
ok: false,
|
|
215
|
+
removed: 0,
|
|
216
|
+
reclaimed: null,
|
|
217
|
+
error: 'This host has no container runtime available right now.'
|
|
218
|
+
}));
|
|
219
|
+
}
|
|
220
|
+
const runtime = info.runtime;
|
|
221
|
+
|
|
222
|
+
const results: PruneOutcome[] = [];
|
|
223
|
+
for (const kind of kinds) {
|
|
224
|
+
let outcome = await tryRun(
|
|
225
|
+
runner,
|
|
226
|
+
containerArgv(runtime, platform, pruneArgv(kind, runtime)),
|
|
227
|
+
CONTAINER_TIMEOUTS.prune
|
|
228
|
+
);
|
|
229
|
+
|
|
230
|
+
// Docker before 23 has no `volume prune --all`, and removed every unused
|
|
231
|
+
// volume without it. Dropping the flag there keeps the meaning identical.
|
|
232
|
+
if (outcome.code !== 0 && kind === 'volumes' && unknownFlag(outcome.stderr)) {
|
|
233
|
+
outcome = await tryRun(
|
|
234
|
+
runner,
|
|
235
|
+
containerArgv(runtime, platform, ['volume', 'prune', '--force']),
|
|
236
|
+
CONTAINER_TIMEOUTS.prune
|
|
237
|
+
);
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
if (outcome.code !== 0) {
|
|
241
|
+
const error = firstProblem(outcome.stderr, outcome.stdout, outcome.code);
|
|
242
|
+
debug.warn('containers', `prune ${kind} failed on ${hostId}: ${error}`);
|
|
243
|
+
results.push({ kind, ok: false, removed: 0, reclaimed: null, error });
|
|
244
|
+
continue;
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
const { removed, reclaimed } = parsePruneOutput(outcome.stdout);
|
|
248
|
+
results.push({ kind, ok: true, removed, reclaimed, error: null });
|
|
249
|
+
}
|
|
250
|
+
return results;
|
|
251
|
+
});
|
|
252
|
+
|
|
253
|
+
containerMonitor.invalidate(hostId);
|
|
254
|
+
// A sweep is exactly when these numbers move, and showing the figures it was
|
|
255
|
+
// meant to fix would read as the sweep having done nothing.
|
|
256
|
+
invalidateDiskUsage(hostId);
|
|
257
|
+
return outcomes;
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
/**
|
|
261
|
+
* One sample of what a container is consuming, read when asked for.
|
|
262
|
+
*
|
|
263
|
+
* Not polled and not part of the listing: `stats` samples over a window and
|
|
264
|
+
* takes a second or more even with `--no-stream`, which is fine for a question
|
|
265
|
+
* someone asked and far too expensive for a table that ticks.
|
|
266
|
+
*/
|
|
267
|
+
export async function readStats(hostId: string, containerId: string): Promise<ContainerStats | null> {
|
|
268
|
+
assertContainerId(containerId);
|
|
269
|
+
|
|
270
|
+
return containerMonitor.withHost(hostId, async (runner, platform) => {
|
|
271
|
+
const info = await detectRuntime(hostId, runner, platform);
|
|
272
|
+
if (info.problem !== 'none' || !info.runtime) return null;
|
|
273
|
+
|
|
274
|
+
const result = await tryRun(
|
|
275
|
+
runner,
|
|
276
|
+
containerArgv(info.runtime, platform, [
|
|
277
|
+
'stats',
|
|
278
|
+
'--no-stream',
|
|
279
|
+
'--format',
|
|
280
|
+
info.runtime === 'docker' ? '{{json .}}' : 'json',
|
|
281
|
+
containerId
|
|
282
|
+
]),
|
|
283
|
+
CONTAINER_TIMEOUTS.stats
|
|
284
|
+
);
|
|
285
|
+
if (result.code !== 0) {
|
|
286
|
+
debug.log('containers', `stats failed for ${containerId}:`, result.stderr);
|
|
287
|
+
return null;
|
|
288
|
+
}
|
|
289
|
+
return parseStats(result.stdout);
|
|
290
|
+
});
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
/** Everything `inspect` knows, read only when a detail pane asks for it. */
|
|
294
|
+
export async function inspectContainer(
|
|
295
|
+
hostId: string,
|
|
296
|
+
containerId: string
|
|
297
|
+
): Promise<ContainerDetail | null> {
|
|
298
|
+
assertContainerId(containerId);
|
|
299
|
+
|
|
300
|
+
return containerMonitor.withHost(hostId, async (runner, platform) => {
|
|
301
|
+
const info = await detectRuntime(hostId, runner, platform);
|
|
302
|
+
if (info.problem !== 'none' || !info.runtime) return null;
|
|
303
|
+
|
|
304
|
+
const result = await tryRun(
|
|
305
|
+
runner,
|
|
306
|
+
containerArgv(info.runtime, platform, ['inspect', '--format', '{{json .}}', containerId]),
|
|
307
|
+
CONTAINER_TIMEOUTS.inspect
|
|
308
|
+
);
|
|
309
|
+
if (result.code !== 0) {
|
|
310
|
+
debug.log('containers', `inspect failed for ${containerId}:`, result.stderr);
|
|
311
|
+
return null;
|
|
312
|
+
}
|
|
313
|
+
return parseInspect(result.stdout);
|
|
314
|
+
});
|
|
315
|
+
}
|
|
316
|
+
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import { describe, expect, test } from 'bun:test';
|
|
2
|
+
import { isDiskUsageStale } from './disk-usage';
|
|
3
|
+
import {
|
|
4
|
+
CONTAINER_TIMEOUTS,
|
|
5
|
+
DISK_USAGE_STALE_MS,
|
|
6
|
+
TRANSPORT_GRACE_MS,
|
|
7
|
+
type ContainerDiskUsage
|
|
8
|
+
} from '$shared/types/containers';
|
|
9
|
+
|
|
10
|
+
const NOW = Date.parse('2026-09-01T12:00:00.000Z');
|
|
11
|
+
|
|
12
|
+
function reading(measuredAt: string | null): ContainerDiskUsage {
|
|
13
|
+
return { rows: [], error: null, measuredAt };
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
describe('isDiskUsageStale', () => {
|
|
17
|
+
test('a reading taken just now is still good', () => {
|
|
18
|
+
expect(isDiskUsageStale(reading(new Date(NOW - 1_000).toISOString()), NOW)).toBe(false);
|
|
19
|
+
});
|
|
20
|
+
|
|
21
|
+
test('a reading goes stale once it passes the window', () => {
|
|
22
|
+
const justInside = new Date(NOW - DISK_USAGE_STALE_MS + 1_000).toISOString();
|
|
23
|
+
const justOutside = new Date(NOW - DISK_USAGE_STALE_MS - 1_000).toISOString();
|
|
24
|
+
expect(isDiskUsageStale(reading(justInside), NOW)).toBe(false);
|
|
25
|
+
expect(isDiskUsageStale(reading(justOutside), NOW)).toBe(true);
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
test('having no reading at all is stale', () => {
|
|
29
|
+
expect(isDiskUsageStale(null, NOW)).toBe(true);
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
test('a reading that did not say when it was taken is stale', () => {
|
|
33
|
+
// Rather than being treated as current, which would pin a number that
|
|
34
|
+
// nothing would ever replace.
|
|
35
|
+
expect(isDiskUsageStale(reading(null), NOW)).toBe(true);
|
|
36
|
+
expect(isDiskUsageStale(reading('not a date'), NOW)).toBe(true);
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
test('a reading stamped in the future is not treated as stale', () => {
|
|
40
|
+
// A host whose clock runs ahead should not make the panel re-measure on
|
|
41
|
+
// every open — the invalidation after a prune is what keeps it honest.
|
|
42
|
+
expect(isDiskUsageStale(reading(new Date(NOW + 60_000).toISOString()), NOW)).toBe(false);
|
|
43
|
+
});
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
describe('command budgets', () => {
|
|
47
|
+
// The bug this guards against: the transport gave up at 30s while the backend
|
|
48
|
+
// was still allowed 300s for a prune, so a sweep that was still deleting came
|
|
49
|
+
// back as six failures and the user was invited to run it again.
|
|
50
|
+
test('every command budget leaves room for the transport to outlast it', () => {
|
|
51
|
+
for (const [name, budget] of Object.entries(CONTAINER_TIMEOUTS)) {
|
|
52
|
+
expect(budget + TRANSPORT_GRACE_MS, `${name} must outlast its command`).toBeGreaterThan(
|
|
53
|
+
budget
|
|
54
|
+
);
|
|
55
|
+
}
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
test('a full scan is allowed more than any single listing it runs', () => {
|
|
59
|
+
expect(CONTAINER_TIMEOUTS.scan).toBeGreaterThan(CONTAINER_TIMEOUTS.list);
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
test('a prune is allowed the longest, because it walks what it deletes', () => {
|
|
63
|
+
const others = Object.entries(CONTAINER_TIMEOUTS)
|
|
64
|
+
.filter(([name]) => name !== 'prune')
|
|
65
|
+
.map(([, budget]) => budget);
|
|
66
|
+
expect(CONTAINER_TIMEOUTS.prune).toBeGreaterThan(Math.max(...others));
|
|
67
|
+
});
|
|
68
|
+
});
|