@myrialabs/clopen 0.4.31 → 0.4.33

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.
Files changed (114) hide show
  1. package/backend/auth/permissions.test.ts +0 -1
  2. package/backend/auth/permissions.ts +0 -4
  3. package/backend/chat/stream-manager.ts +31 -12
  4. package/backend/database/migrations/068_create_engine_config_revision.test.ts +121 -0
  5. package/backend/database/migrations/068_create_engine_config_revision.ts +117 -0
  6. package/backend/database/migrations/069_create_ssh_client_tables.ts +116 -0
  7. package/backend/database/migrations/index.ts +14 -0
  8. package/backend/database/queries/db-client-connection-queries.ts +7 -2
  9. package/backend/database/queries/file-audit-log-queries.ts +1 -0
  10. package/backend/database/queries/index.ts +3 -0
  11. package/backend/database/queries/ssh-connection-queries.ts +244 -0
  12. package/backend/database/queries/ssh-known-host-queries.ts +67 -0
  13. package/backend/database/queries/ssh-port-forward-queries.ts +113 -0
  14. package/backend/db-client/connection-manager.ts +8 -1
  15. package/backend/engine/README.md +16 -0
  16. package/backend/engine/adapters/claude/stream.ts +89 -49
  17. package/backend/engine/adapters/cline/stream.ts +62 -24
  18. package/backend/engine/adapters/codex/message-converter.ts +18 -12
  19. package/backend/engine/adapters/codex/patch-rollout.test.ts +88 -0
  20. package/backend/engine/adapters/codex/patch-rollout.ts +120 -109
  21. package/backend/engine/adapters/codex/stream.ts +78 -22
  22. package/backend/engine/adapters/copilot/stream.ts +97 -53
  23. package/backend/engine/adapters/cursor/stream.ts +75 -35
  24. package/backend/engine/adapters/opencode/server.ts +511 -134
  25. package/backend/engine/adapters/opencode/stream.ts +131 -79
  26. package/backend/engine/adapters/pi/stream.ts +63 -24
  27. package/backend/engine/adapters/qwen/stream.ts +92 -59
  28. package/backend/engine/adapters/run-registry.test.ts +75 -0
  29. package/backend/engine/adapters/run-registry.ts +63 -0
  30. package/backend/engine/config-revision.ts +150 -0
  31. package/backend/engine/docs/adapter-contract.md +47 -9
  32. package/backend/engine/docs/adding-an-engine.md +8 -0
  33. package/backend/engine/docs/frontend-and-chat.md +39 -0
  34. package/backend/engine/docs/lessons-learned.md +70 -0
  35. package/backend/engine/docs/quick-reference.md +3 -1
  36. package/backend/engine/hot-reload.ts +99 -0
  37. package/backend/engine/index.ts +96 -24
  38. package/backend/engine/types.ts +17 -5
  39. package/backend/files/file-watcher.ts +283 -51
  40. package/backend/files/git-events.test.ts +110 -0
  41. package/backend/git/git-dirs.test.ts +132 -0
  42. package/backend/git/git-dirs.ts +0 -0
  43. package/backend/git/git-executor.ts +22 -3
  44. package/backend/git/git-service.ts +1 -1
  45. package/backend/git/nested-repos.test.ts +224 -0
  46. package/backend/git/nested-repos.ts +386 -0
  47. package/backend/http/audio.ts +5 -32
  48. package/backend/http/bearer-auth.ts +47 -0
  49. package/backend/http/files-download.test.ts +146 -0
  50. package/backend/http/files-download.ts +109 -0
  51. package/backend/http/files-upload.ts +3 -29
  52. package/backend/http/ssh-sftp.ts +133 -0
  53. package/backend/index.ts +23 -2
  54. package/backend/mcp/README.md +34 -6
  55. package/backend/mcp/index.ts +8 -8
  56. package/backend/mcp/internal/config.ts +69 -19
  57. package/backend/mcp/internal/project-context.test.ts +40 -0
  58. package/backend/mcp/internal/project-context.ts +80 -7
  59. package/backend/mcp/internal/remote-server.test.ts +17 -2
  60. package/backend/mcp/internal/remote-server.ts +36 -3
  61. package/backend/mcp/internal/servers/helper.ts +48 -18
  62. package/backend/preview/browser/browser-video-capture.ts +51 -4
  63. package/backend/snapshot/gitignore.ts +10 -174
  64. package/backend/ssh/client-pool.ts +196 -0
  65. package/backend/ssh/connect.ts +375 -0
  66. package/backend/ssh/disk-usage.test.ts +134 -0
  67. package/backend/ssh/disk-usage.ts +214 -0
  68. package/backend/ssh/forwards.ts +309 -0
  69. package/backend/ssh/health.ts +141 -0
  70. package/backend/ssh/known-hosts.ts +96 -0
  71. package/backend/ssh/pty-backend.ts +215 -0
  72. package/backend/ssh/ptykit.ts +66 -0
  73. package/backend/ssh/sftp.test.ts +242 -0
  74. package/backend/ssh/sftp.ts +967 -0
  75. package/backend/ssh/socks5.test.ts +167 -0
  76. package/backend/ssh/socks5.ts +164 -0
  77. package/backend/ssh/tunnel.ts +87 -0
  78. package/backend/ws/chat/stream.ts +24 -0
  79. package/backend/ws/db-client/connections.ts +1 -0
  80. package/backend/ws/engine/codex/accounts.ts +0 -12
  81. package/backend/ws/engine/copilot/accounts.ts +0 -10
  82. package/backend/ws/engine/cursor/accounts.ts +0 -10
  83. package/backend/ws/engine/index.ts +17 -2
  84. package/backend/ws/engine/opencode/providers.ts +0 -52
  85. package/backend/ws/files/read.ts +1 -1
  86. package/backend/ws/files/watch.ts +5 -1
  87. package/backend/ws/git/conflict.ts +1 -1
  88. package/backend/ws/git/diff.ts +1 -1
  89. package/backend/ws/git/staging.ts +1 -1
  90. package/backend/ws/git/status.ts +1 -1
  91. package/backend/ws/index.ts +4 -0
  92. package/backend/ws/ssh/access.ts +31 -0
  93. package/backend/ws/ssh/connections.ts +224 -0
  94. package/backend/ws/ssh/forwards.ts +109 -0
  95. package/backend/ws/ssh/index.ts +18 -0
  96. package/backend/ws/ssh/sftp.ts +259 -0
  97. package/backend/ws/ssh/tunnel.ts +93 -0
  98. package/dist/assets/{index-DYwQ5bP8.js → index-BF4buYmI.js} +1 -1
  99. package/dist/assets/{index-DUc5T21e.js → index-BW0DA8NV.js} +1 -1
  100. package/dist/assets/main-BbwWLJRN.js +1057 -0
  101. package/dist/assets/main-CCvRMXlP.css +1 -0
  102. package/dist/index.html +2 -2
  103. package/package.json +1 -1
  104. package/shared/types/database/schema.ts +49 -0
  105. package/shared/types/db-client/connection.ts +6 -0
  106. package/shared/types/ssh/connection.ts +80 -0
  107. package/shared/types/ssh/forward.ts +46 -0
  108. package/shared/types/ssh/index.ts +8 -0
  109. package/shared/types/ssh/known-host.ts +19 -0
  110. package/shared/types/ssh/sftp.ts +141 -0
  111. package/shared/utils/logger.ts +1 -0
  112. package/backend/ws/engine/restart.ts +0 -54
  113. package/dist/assets/main-VgdjTBLR.css +0 -1
  114. package/dist/assets/main-r0iv2PDz.js +0 -1044
@@ -0,0 +1,375 @@
1
+ /**
2
+ * ssh-client — turning a saved connection into a live `ssh2.Client`.
3
+ *
4
+ * One place builds the ssh2 `ConnectConfig` for all four auth methods, walks
5
+ * the ProxyJump chain, and runs the host-key check, so the terminal, SFTP,
6
+ * port forwarding and the db-client tunnel all authenticate identically.
7
+ */
8
+
9
+ import { readFile } from 'node:fs/promises';
10
+ import { homedir } from 'node:os';
11
+ import { isAbsolute, resolve } from 'node:path';
12
+ import { Client as SshClient, type ConnectConfig } from 'ssh2';
13
+ import { sshConnectionQueries } from '../database/queries';
14
+ import { evaluateHostKey, hostKeyChangedMessage, type HostKeyVerdict } from './known-hosts';
15
+ import type { SshConnection } from '$shared/types/ssh';
16
+ import { debug } from '$shared/utils/logger';
17
+
18
+ /**
19
+ * Raised when the host presented a key that differs from the trusted one. Typed
20
+ * so callers can report *why* the dial failed — Test shows a "trust new key"
21
+ * action instead of a generic connection error.
22
+ */
23
+ export class HostKeyChangedError extends Error {
24
+ constructor(
25
+ message: string,
26
+ readonly verdict: Extract<HostKeyVerdict, { outcome: 'changed' }>
27
+ ) {
28
+ super(message);
29
+ this.name = 'HostKeyChangedError';
30
+ }
31
+ }
32
+
33
+ /** Guards a malformed jump chain that slipped past the save-time cycle check. */
34
+ const MAX_JUMP_DEPTH = 8;
35
+
36
+ const HANDSHAKE_TIMEOUT_MS = 20_000;
37
+
38
+ export interface DialResult {
39
+ client: SshClient;
40
+ /** What the host-key check concluded — surfaced in Test and in the terminal. */
41
+ hostKey: HostKeyVerdict;
42
+ /** The remote SSH identification string, when ssh2 reported one. */
43
+ serverBanner: string | null;
44
+ /** Every client opened for this dial, outermost host last. Close in reverse. */
45
+ chain: SshClient[];
46
+ }
47
+
48
+ function expandHome(path: string): string {
49
+ if (path === '~') return homedir();
50
+ if (path.startsWith('~/')) return resolve(homedir(), path.slice(2));
51
+ return isAbsolute(path) ? path : resolve(path);
52
+ }
53
+
54
+ async function readPrivateKeyFile(path: string): Promise<Buffer> {
55
+ try {
56
+ return await readFile(expandHome(path));
57
+ } catch (error) {
58
+ const reason = error instanceof Error ? error.message : String(error);
59
+ throw new Error(`Could not read private key at ${path}: ${reason}`);
60
+ }
61
+ }
62
+
63
+ /**
64
+ * The agent socket to hand ssh2. Windows has no unix socket for this — Pageant
65
+ * is addressed by the literal string 'pageant', which ssh2 special-cases.
66
+ */
67
+ function resolveAgentSocket(connection: SshConnection): string {
68
+ if (connection.agentSocket) return expandHome(connection.agentSocket);
69
+ if (process.platform === 'win32') return 'pageant';
70
+ const fromEnv = process.env.SSH_AUTH_SOCK;
71
+ if (!fromEnv) {
72
+ throw new Error('No ssh-agent found — SSH_AUTH_SOCK is not set on the Clopen server');
73
+ }
74
+ return fromEnv;
75
+ }
76
+
77
+ async function applyAuth(connection: SshConnection, config: ConnectConfig): Promise<void> {
78
+ switch (connection.authMethod) {
79
+ case 'password': {
80
+ if (!connection.password) throw new Error('Password auth needs a password');
81
+ config.password = connection.password;
82
+ // Many hardened hosts turn off `PasswordAuthentication` but keep
83
+ // `KbdInteractiveAuthentication`, which is the same secret over a
84
+ // different exchange. Offer both rather than failing on the first.
85
+ config.tryKeyboard = true;
86
+ break;
87
+ }
88
+ case 'key': {
89
+ if (!connection.privateKey) throw new Error('Key auth needs a private key');
90
+ config.privateKey = connection.privateKey;
91
+ if (connection.passphrase) config.passphrase = connection.passphrase;
92
+ break;
93
+ }
94
+ case 'key-file': {
95
+ if (!connection.privateKeyPath) throw new Error('Key-file auth needs a key path');
96
+ config.privateKey = await readPrivateKeyFile(connection.privateKeyPath);
97
+ if (connection.passphrase) config.passphrase = connection.passphrase;
98
+ break;
99
+ }
100
+ case 'agent': {
101
+ config.agent = resolveAgentSocket(connection);
102
+ break;
103
+ }
104
+ default: {
105
+ const exhaustive: never = connection.authMethod;
106
+ throw new Error(`Unsupported SSH auth method: ${exhaustive}`);
107
+ }
108
+ }
109
+ }
110
+
111
+ interface HandshakeOutcome {
112
+ hostKey: HostKeyVerdict | null;
113
+ serverBanner: string | null;
114
+ }
115
+
116
+ /**
117
+ * Connect one hop. `sock` carries the stream from the previous hop when this
118
+ * host is reached through a bastion.
119
+ */
120
+ async function connectOne(
121
+ connection: SshConnection,
122
+ sock?: NodeJS.ReadableStream
123
+ ): Promise<{ client: SshClient; outcome: HandshakeOutcome }> {
124
+ const config: ConnectConfig = {
125
+ host: connection.host,
126
+ port: connection.port || 22,
127
+ username: connection.username,
128
+ readyTimeout: HANDSHAKE_TIMEOUT_MS,
129
+ keepaliveInterval: Math.max(0, connection.keepaliveSeconds) * 1000
130
+ };
131
+
132
+ if (sock) config.sock = sock as ConnectConfig['sock'];
133
+
134
+ await applyAuth(connection, config);
135
+
136
+ const outcome: HandshakeOutcome = { hostKey: null, serverBanner: null };
137
+
138
+ // ssh2 exposes the remote identification string only through its debug sink.
139
+ // It is display-only (shown as the server banner in Test), so reading it here
140
+ // costs nothing and keeps the rest of the module off ssh2's internals.
141
+ config.debug = (message: string): void => {
142
+ const match = /^Remote ident: '(.+)'$/.exec(message);
143
+ if (match) outcome.serverBanner = match[1];
144
+ };
145
+
146
+ config.hostVerifier = (keyBlob: Buffer): boolean => {
147
+ const verdict = evaluateHostKey(
148
+ connection.host,
149
+ connection.port || 22,
150
+ keyBlob,
151
+ connection.strictHostKey
152
+ );
153
+ outcome.hostKey = verdict;
154
+ return verdict.outcome !== 'changed';
155
+ };
156
+
157
+ const client = new SshClient();
158
+
159
+ if (connection.authMethod === 'password' && connection.password) {
160
+ const password = connection.password;
161
+ client.on('keyboard-interactive', (_name, _instructions, _lang, prompts, finish) => {
162
+ // Answer every prompt with the stored password; a host that asks for
163
+ // more than that (a real second factor) will simply reject it.
164
+ finish(prompts.map(() => password));
165
+ });
166
+ }
167
+
168
+ await new Promise<void>((resolvePromise, rejectPromise) => {
169
+ const onReady = (): void => {
170
+ client.removeListener('error', onError);
171
+ resolvePromise();
172
+ };
173
+ const onError = (error: Error): void => {
174
+ client.removeListener('ready', onReady);
175
+ // ssh2 reports a rejected host key as a generic handshake failure.
176
+ // Replace it with the message that says what actually happened.
177
+ if (outcome.hostKey?.outcome === 'changed') {
178
+ const changed = outcome.hostKey;
179
+ rejectPromise(
180
+ new HostKeyChangedError(
181
+ hostKeyChangedMessage(connection.host, connection.port || 22, changed),
182
+ changed
183
+ )
184
+ );
185
+ return;
186
+ }
187
+ rejectPromise(error);
188
+ };
189
+ client.once('ready', onReady);
190
+ client.once('error', onError);
191
+ try {
192
+ client.connect(config);
193
+ } catch (error) {
194
+ rejectPromise(error instanceof Error ? error : new Error(String(error)));
195
+ }
196
+ });
197
+
198
+ return { client, outcome };
199
+ }
200
+
201
+ /** Open the stream that reaches `target` from an already-connected bastion. */
202
+ function openJumpChannel(
203
+ bastion: SshClient,
204
+ targetHost: string,
205
+ targetPort: number
206
+ ): Promise<NodeJS.ReadableStream> {
207
+ return new Promise((resolvePromise, rejectPromise) => {
208
+ bastion.forwardOut('127.0.0.1', 0, targetHost, targetPort, (error, stream) => {
209
+ if (error) {
210
+ rejectPromise(new Error(`Jump host could not reach ${targetHost}:${targetPort} — ${error.message}`));
211
+ return;
212
+ }
213
+ resolvePromise(stream);
214
+ });
215
+ });
216
+ }
217
+
218
+ /** Resolve the saved hosts to hop through, bastion-first. */
219
+ function resolveJumpChain(connection: SshConnection): SshConnection[] {
220
+ const chain: SshConnection[] = [];
221
+ let cursor = connection.jumpConnectionId;
222
+ const visited = new Set<string>([connection.id]);
223
+ while (cursor) {
224
+ if (visited.has(cursor)) {
225
+ throw new Error('The jump host chain loops back on itself');
226
+ }
227
+ visited.add(cursor);
228
+ const hop = sshConnectionQueries.get(cursor);
229
+ if (!hop) throw new Error('A jump host in this chain no longer exists');
230
+ chain.unshift(hop);
231
+ if (chain.length > MAX_JUMP_DEPTH) {
232
+ throw new Error(`Jump host chain is deeper than ${MAX_JUMP_DEPTH} hops`);
233
+ }
234
+ cursor = hop.jumpConnectionId;
235
+ }
236
+ return chain;
237
+ }
238
+
239
+ /** Close a dial's clients, innermost hop first. Never throws. */
240
+ export function closeChain(chain: SshClient[]): void {
241
+ for (const client of [...chain].reverse()) {
242
+ try {
243
+ client.end();
244
+ } catch {
245
+ // Already gone — nothing to do.
246
+ }
247
+ }
248
+ }
249
+
250
+ /**
251
+ * Connect to `connection`, hopping through its jump chain if it has one.
252
+ * Every client opened along the way is returned so the caller can close them
253
+ * all; on failure they are closed here.
254
+ */
255
+ export async function dial(connection: SshConnection): Promise<DialResult> {
256
+ const hops = resolveJumpChain(connection);
257
+ const chain: SshClient[] = [];
258
+
259
+ try {
260
+ let sock: NodeJS.ReadableStream | undefined;
261
+
262
+ // Each hop opens a channel to the next one, and the last opens a channel to
263
+ // the destination itself — so the chain arrives as a single stream.
264
+ for (const [index, hop] of hops.entries()) {
265
+ const { client } = await connectOne(hop, sock);
266
+ chain.push(client);
267
+ const following = hops[index + 1];
268
+ const destinationHost = following ? following.host : connection.host;
269
+ const destinationPort = following ? following.port || 22 : connection.port || 22;
270
+ sock = await openJumpChannel(client, destinationHost, destinationPort);
271
+ }
272
+
273
+ const { client, outcome } = await connectOne(connection, sock);
274
+ chain.push(client);
275
+
276
+ if (!outcome.hostKey) {
277
+ throw new Error('The host key check did not run — refusing the connection');
278
+ }
279
+
280
+ debug.log(
281
+ 'ssh',
282
+ `connected ${connection.username}@${connection.host}:${connection.port || 22}` +
283
+ (hops.length > 0 ? ` via ${hops.length} jump host(s)` : '')
284
+ );
285
+
286
+ return {
287
+ client,
288
+ hostKey: outcome.hostKey,
289
+ serverBanner: outcome.serverBanner,
290
+ chain
291
+ };
292
+ } catch (error) {
293
+ closeChain(chain);
294
+ throw error;
295
+ }
296
+ }
297
+
298
+ export interface CommandResult {
299
+ stdout: string;
300
+ stderr: string;
301
+ /** The remote exit status. 0 means success. */
302
+ code: number;
303
+ }
304
+
305
+ /**
306
+ * Run a short command over an exec channel and collect its output. Never
307
+ * throws on a non-zero exit — the caller decides whether that is a failure,
308
+ * because several probes treat "command not found" as simply "not this host".
309
+ */
310
+ export function runCommandDetailed(
311
+ client: SshClient,
312
+ command: string,
313
+ timeoutMs = 15_000
314
+ ): Promise<CommandResult> {
315
+ return new Promise((resolvePromise, rejectPromise) => {
316
+ const timer = setTimeout(() => rejectPromise(new Error(`Command timed out: ${command}`)), timeoutMs);
317
+ client.exec(command, (error, stream) => {
318
+ if (error) {
319
+ clearTimeout(timer);
320
+ rejectPromise(error);
321
+ return;
322
+ }
323
+ let stdout = '';
324
+ let stderr = '';
325
+ let code = 0;
326
+ stream.on('data', (chunk: Buffer) => {
327
+ stdout += chunk.toString('utf8');
328
+ });
329
+ stream.stderr.on('data', (chunk: Buffer) => {
330
+ stderr += chunk.toString('utf8');
331
+ });
332
+ stream.on('exit', (exitCode: number | null) => {
333
+ if (typeof exitCode === 'number') code = exitCode;
334
+ });
335
+ stream.on('close', () => {
336
+ clearTimeout(timer);
337
+ resolvePromise({ stdout: stdout.trim(), stderr: stderr.trim(), code });
338
+ });
339
+ stream.on('error', (streamError: Error) => {
340
+ clearTimeout(timer);
341
+ rejectPromise(streamError);
342
+ });
343
+ });
344
+ });
345
+ }
346
+
347
+ /** Run a short command and return its stdout. Used for the remote OS probe. */
348
+ export async function runCommand(client: SshClient, command: string, timeoutMs = 5_000): Promise<string> {
349
+ const result = await runCommandDetailed(client, command, timeoutMs);
350
+ return result.stdout;
351
+ }
352
+
353
+ /**
354
+ * Run a command and throw if it failed. The thrown message carries the remote
355
+ * stderr, which is what actually tells the user why (permission denied, no such
356
+ * file, `zip` not installed).
357
+ */
358
+ export async function runCommandOrThrow(
359
+ client: SshClient,
360
+ command: string,
361
+ whatItWasDoing: string,
362
+ timeoutMs = 60_000
363
+ ): Promise<string> {
364
+ const result = await runCommandDetailed(client, command, timeoutMs);
365
+ if (result.code !== 0) {
366
+ const reason = result.stderr || result.stdout || `exit status ${result.code}`;
367
+ throw new Error(`${whatItWasDoing}: ${reason}`);
368
+ }
369
+ return result.stdout;
370
+ }
371
+
372
+ /** Single-quote a POSIX shell argument, escaping any embedded quote. */
373
+ export function shellQuote(value: string): string {
374
+ return `'${value.replace(/'/g, `'\\''`)}'`;
375
+ }
@@ -0,0 +1,134 @@
1
+ import { describe, expect, test } from 'bun:test';
2
+ import { parseCpanelQuota, parseFilesystemUsage, parsePosixQuota } from './disk-usage';
3
+
4
+ const GIGABYTE = 1024 ** 3;
5
+
6
+ describe('parseCpanelQuota', () => {
7
+ // Captured verbatim from `uapi --output=json Quota get_quota_info` on a real
8
+ // cPanel account — the one whose control panel reads "3.71 GB / 5 GB (74.16%)".
9
+ const REAL_OUTPUT = JSON.stringify({
10
+ apiversion: 3,
11
+ module: 'Quota',
12
+ func: 'get_quota_info',
13
+ result: {
14
+ errors: null,
15
+ data: {
16
+ inodes_used: 243990,
17
+ inodes_remain: '0',
18
+ megabyte_limit: 5120,
19
+ megabytes_used: 3796.91,
20
+ megabytes_remain: 1323.09,
21
+ inode_limit: '0'
22
+ },
23
+ warnings: null,
24
+ messages: null,
25
+ status: 1,
26
+ metadata: {}
27
+ }
28
+ });
29
+
30
+ test('reports the account limit, not the filesystem', () => {
31
+ const usage = parseCpanelQuota(REAL_OUTPUT, '/home/user');
32
+ expect(usage).not.toBeNull();
33
+ expect(usage?.source).toBe('account-quota');
34
+ expect(usage?.totalBytes).toBe(5 * GIGABYTE);
35
+ });
36
+
37
+ test('the rendered percentage matches what cPanel shows', () => {
38
+ const usage = parseCpanelQuota(REAL_OUTPUT, '/home/user');
39
+ const ratio = (usage!.usedBytes! / usage!.totalBytes!) * 100;
40
+ expect(ratio.toFixed(2)).toBe('74.16');
41
+ expect((usage!.usedBytes! / GIGABYTE).toFixed(2)).toBe('3.71');
42
+ });
43
+
44
+ test('carries the inode count', () => {
45
+ const usage = parseCpanelQuota(REAL_OUTPUT, '/home/user');
46
+ expect(usage?.inodesUsed).toBe(243990);
47
+ // cPanel spells "no limit" as 0, which is not a total to divide by.
48
+ expect(usage?.inodeLimit).toBeNull();
49
+ });
50
+
51
+ test('an unlimited account reports usage without a total', () => {
52
+ const output = JSON.stringify({
53
+ result: { status: 1, data: { megabytes_used: 120, megabyte_limit: 0 } }
54
+ });
55
+ const usage = parseCpanelQuota(output, '/home/user');
56
+ expect(usage?.totalBytes).toBeNull();
57
+ expect(usage?.usedBytes).toBe(120 * 1024 * 1024);
58
+ });
59
+
60
+ test('a failed UAPI call is not an answer', () => {
61
+ const output = JSON.stringify({ result: { status: 0, errors: ['nope'], data: null } });
62
+ expect(parseCpanelQuota(output, '/home/user')).toBeNull();
63
+ });
64
+
65
+ test('non-JSON output is not an answer', () => {
66
+ expect(parseCpanelQuota('bash: uapi: command not found', '/home/user')).toBeNull();
67
+ expect(parseCpanelQuota('', '/home/user')).toBeNull();
68
+ });
69
+ });
70
+
71
+ describe('parsePosixQuota', () => {
72
+ const OUTPUT = [
73
+ 'Disk quotas for user deploy (uid 1001):',
74
+ ' Filesystem blocks quota limit grace files quota limit grace',
75
+ ' /dev/sda1 512000 921600 1048576 4200 0 0'
76
+ ].join('\n');
77
+
78
+ test('reads the hard limit as the total', () => {
79
+ const usage = parsePosixQuota(OUTPUT, '/home/deploy');
80
+ expect(usage?.source).toBe('user-quota');
81
+ expect(usage?.usedBytes).toBe(512000 * 1024);
82
+ expect(usage?.totalBytes).toBe(1048576 * 1024);
83
+ expect(usage?.availableBytes).toBe((1048576 - 512000) * 1024);
84
+ });
85
+
86
+ test('does not guess the file count', () => {
87
+ // `quota -w` prints its grace columns only while over quota, so everything
88
+ // after `limit` shifts position. Reporting nothing beats reporting a number
89
+ // that is silently the wrong column.
90
+ expect(parsePosixQuota(OUTPUT, '/home/deploy')?.inodesUsed).toBeNull();
91
+ });
92
+
93
+ test('falls back to the soft limit when there is no hard one', () => {
94
+ const output = OUTPUT.replace('1048576', '0');
95
+ const usage = parsePosixQuota(output, '/home/deploy');
96
+ expect(usage?.totalBytes).toBe(921600 * 1024);
97
+ });
98
+
99
+ test('an over-quota asterisk does not break the columns', () => {
100
+ const output = OUTPUT.replace('512000', '999999*');
101
+ const usage = parsePosixQuota(output, '/home/deploy');
102
+ expect(usage?.usedBytes).toBe(999999 * 1024);
103
+ });
104
+
105
+ test('no quota set at all is not an answer', () => {
106
+ const output = OUTPUT.replace('921600 1048576', '0 0');
107
+ expect(parsePosixQuota(output, '/home/deploy')).toBeNull();
108
+ });
109
+
110
+ test('a host without the quota tool is not an answer', () => {
111
+ expect(parsePosixQuota('', '/home/deploy')).toBeNull();
112
+ });
113
+ });
114
+
115
+ describe('parseFilesystemUsage', () => {
116
+ // The `df` output from the same shared host — 195 GB free on the volume, and
117
+ // the reason `df` alone was the wrong number to show.
118
+ const OUTPUT = [
119
+ 'Filesystem 1024-blocks Used Available Capacity Mounted on',
120
+ '/dev/sdd 762647808 556975748 204879732 74% /home/themeco1'
121
+ ].join('\n');
122
+
123
+ test('reports the volume, labelled as the volume', () => {
124
+ const usage = parseFilesystemUsage(OUTPUT, '/home/themeco1');
125
+ expect(usage?.source).toBe('filesystem');
126
+ expect(usage?.totalBytes).toBe(762647808 * 1024);
127
+ expect(usage?.availableBytes).toBe(204879732 * 1024);
128
+ });
129
+
130
+ test('output with no data line is not an answer', () => {
131
+ expect(parseFilesystemUsage('Filesystem 1024-blocks Used Available', '/')).toBeNull();
132
+ expect(parseFilesystemUsage('', '/')).toBeNull();
133
+ });
134
+ });