feat(cli): cover OpenAPI with a remote npm CLI and internal panel tools (#3074)

* feat(cli): add unified Commander CLI for QingLong 2.x

* fix(cli): publish via npm and address security review feedback

* ci(cli): package npm artifacts and remove evaluation collateral

* test(cli): use a fixed shell fixture for log retention

* refactor(cli): separate remote npm client from panel tools

* feat(cli): cover active panel OpenAPI resources

* docs(cli): unify authentication and skill guidance

* refactor(cli): isolate internal commands and generate Commander help

* refactor(cli): organize remote and internal modules by responsibility

* ci(cli): publish verified npm archives from master

* fix(cli): publish under the whyour npm scope

* ci: use npm trusted publishing for both packages

* docs: introduce the published CLI on the project homepage

* fix(cli): preserve server log truncation and correct login hints

* fix(cli): accept dashboard record request bodies

* fix(cli): preserve stdin for local task execution

* fix(cli): resolve task executables after changing directory

* fix(cli): preserve shell function tasks and sanitize test failures

* fix(cli): preserve shell hook state and resolve workdir after hooks

* fix(cli): preserve cleanup across shared shell task timeouts

* fix(cli): isolate shell control descriptors and reap timed-out descendants
This commit is contained in:
whyour authored and GitHub committed 2026-09-25 23:24:41 +08:00
1 parent f051135fc4
commit 801a71d740
185 files changed
+22412 -6

No files matched your search

+145
View File
@@ -0,0 +1,145 @@
import { saveResponse } from './download';
import { translate } from '../../shared/i18n/index';
import { CliError, fail } from '../../shared/errors';
import type { Credentials, Session, StoredConfig } from '../types';
import { isRecord } from '../../shared/record';
export { isRecord } from '../../shared/record';
interface RequestOptions {
method?: 'GET' | 'PUT' | 'POST' | 'DELETE';
body?: unknown;
output?: string;
text?: boolean;
timeoutMs?: number;
authenticated?: boolean;
}
export async function request(
config: StoredConfig,
endpoint: string,
options: RequestOptions = {},
): Promise<Record<string, unknown>> {
const { method = 'GET', body, authenticated = true } = options;
const scope = endpoint.split(/[/?]/, 1)[0]!;
const subscription = scope === 'subscriptions';
const resource =
scope === 'crons' || subscription
? translate(process.env, subscription ? '订阅' : '任务')
: scope;
const credentialsHint = authenticated
? translate(process.env, '应用凭据和 %s 权限', scope)
: translate(process.env, '应用凭据');
let response: Response;
let result: unknown;
try {
response = await fetch(`${config.url}/open/${endpoint}`, {
method,
redirect: 'error',
signal: AbortSignal.timeout(options.timeoutMs ?? 30000),
headers: {
...(authenticated ? { Authorization: `Bearer ${config.token}` } : {}),
...(body !== undefined && !(body instanceof FormData)
? { 'Content-Type': 'application/json' }
: {}),
},
body:
body instanceof FormData
? body
: body !== undefined
? JSON.stringify(body)
: undefined,
});
// Check HTTP status before decoding (proxies may return HTML on denial).
if (!response.ok) {
await response.body?.cancel();
const suffix =
method !== 'GET' && response.status >= 500
? translate(
process.env,
' 执行结果可能未知,请先检查%s状态再考虑重试。',
resource,
)
: '';
fail(
translate(
process.env,
'API 请求被拒绝(HTTP %s),请检查%s。%s',
response.status,
credentialsHint,
suffix,
),
[401, 403].includes(response.status) ? 3 : 1,
);
}
if (
options.output &&
(response.headers.get('content-disposition')?.startsWith('attachment') ||
!response.headers.get('content-type')?.includes('application/json'))
)
return await saveResponse(response, options.output);
if (
options.text &&
!response.headers.get('content-type')?.includes('application/json')
)
return { code: 200, data: await response.text() };
result = await response.json();
} catch (error) {
// Never expose a fetch error, URL or server error that may include secrets.
if (error instanceof CliError) throw error;
fail(
method !== 'GET'
? translate(
process.env,
'请求失败或响应无效,执行结果未知。请先检查%s状态再考虑重试。',
resource,
)
: translate(
process.env,
'请求失败或返回的 JSON 无效,请检查实例 URL、网络和 TLS 证书。',
),
);
}
if (endpoint.split('?')[0] === 'user/login' && isRecord(result) && result.code === 420)
fail(translate(process.env, '需要双因素验证,请调用 user two-factor-login。'), 3);
if (!isRecord(result) || result.code !== 200) {
const status =
isRecord(result) && typeof result.code === 'number'
? result.code
: undefined;
fail(
translate(
process.env,
'API 请求被拒绝(code %s),请检查%s。',
status ?? translate(process.env, '未知'),
credentialsHint,
),
status === 401 || status === 403 ? 3 : 1,
);
}
if (options.output)
fail(translate(process.env, '接口返回 JSON,未保存下载文件。'));
return result;
}
export async function authenticate(config: Credentials): Promise<Session> {
const query = new URLSearchParams({
client_id: config.clientId,
client_secret: config.clientSecret,
});
const result = await request(config, `auth/token?${query}`, {
authenticated: false,
});
const data = result.data;
if (
!isRecord(data) ||
typeof data.token !== 'string' ||
!data.token ||
typeof data.expiration !== 'number' ||
!Number.isFinite(data.expiration) ||
data.expiration <= Date.now() / 1000
) {
fail(translate(process.env, '认证响应无效。'));
}
return { ...config, token: data.token, expiration: data.expiration };
}
+25
View File
@@ -0,0 +1,25 @@
import { open, unlink } from 'node:fs/promises';
import { pipeline } from 'node:stream/promises';
import { Readable } from 'node:stream';
import type { ReadableStream } from 'node:stream/web';
import { resolve } from 'node:path';
// Never overwrite an existing file; remove only a file created by this call.
export async function saveResponse(
response: Response,
output: string,
): Promise<Record<string, unknown>> {
const path = resolve(output);
const handle = await open(path, 'wx', 0o600);
try {
if (!response.body) throw new Error('Missing response body');
const stream = handle.createWriteStream();
await pipeline(Readable.fromWeb(response.body as ReadableStream<Uint8Array>), stream);
return { code: 200, data: { path, bytes: stream.bytesWritten } };
} catch (error) {
await unlink(path).catch(() => undefined);
throw error;
} finally {
await handle.close();
}
}
+586
View File
@@ -0,0 +1,586 @@
// Reviewed against back/api routes. The coverage test detects route additions/removals.
// All paths are relative to /open; these commands never operate on local panel files.
export interface OpenOperation {
name: string;
method: 'GET' | 'POST' | 'PUT' | 'DELETE';
path: string;
params?: string[];
body?: 'ids' | 'json' | 'object-id';
upload?: string;
download?: boolean;
existing?: boolean;
anonymous?: boolean;
}
export const openOperations: readonly OpenOperation[] = [
{ name: 'task view-list', method: 'GET', path: 'crons/views' },
{
name: 'task view-create',
method: 'POST',
path: 'crons/views',
body: 'json',
},
{
name: 'task view-update',
method: 'PUT',
path: 'crons/views',
params: ['id'],
body: 'object-id',
},
{
name: 'task view-delete',
method: 'DELETE',
path: 'crons/views',
body: 'ids',
},
{
name: 'task view-move',
method: 'PUT',
path: 'crons/views/move',
body: 'json',
},
{
name: 'task view-disable',
method: 'PUT',
path: 'crons/views/disable',
body: 'ids',
},
{
name: 'task view-enable',
method: 'PUT',
path: 'crons/views/enable',
body: 'ids',
},
{ name: 'task list', method: 'GET', path: 'crons', existing: true },
{ name: 'task detail', method: 'GET', path: 'crons/detail' },
{ name: 'task create', method: 'POST', path: 'crons', body: 'json' },
{
name: 'task run',
method: 'PUT',
path: 'crons/run',
body: 'ids',
existing: true,
},
{
name: 'task stop',
method: 'PUT',
path: 'crons/stop',
body: 'ids',
existing: true,
},
{
name: 'task labels-delete',
method: 'DELETE',
path: 'crons/labels',
body: 'json',
},
{
name: 'task labels-create',
method: 'POST',
path: 'crons/labels',
body: 'json',
},
{ name: 'task disable', method: 'PUT', path: 'crons/disable', body: 'ids' },
{ name: 'task enable', method: 'PUT', path: 'crons/enable', body: 'ids' },
{
name: 'task logs',
method: 'GET',
path: 'crons/:id/log',
params: ['id'],
existing: true,
},
{
name: 'task update',
method: 'PUT',
path: 'crons',
params: ['id'],
body: 'object-id',
},
{ name: 'task delete', method: 'DELETE', path: 'crons', body: 'ids' },
{ name: 'task pin', method: 'PUT', path: 'crons/pin', body: 'ids' },
{ name: 'task unpin', method: 'PUT', path: 'crons/unpin', body: 'ids' },
{ name: 'task import', method: 'GET', path: 'crons/import' },
{
name: 'task get',
method: 'GET',
path: 'crons/:id',
params: ['id'],
existing: true,
},
{ name: 'task status', method: 'PUT', path: 'crons/status', body: 'json' },
{
name: 'task instances',
method: 'GET',
path: 'crons/:id/instances',
params: ['id'],
},
{
name: 'task instance-stop',
method: 'POST',
path: 'crons/:id/instances/:instanceId/stop',
params: ['id', 'instanceId'],
},
{
name: 'task log-files',
method: 'GET',
path: 'crons/:id/logs',
params: ['id'],
},
{
name: 'subscription list',
method: 'GET',
path: 'subscriptions',
existing: true,
},
{
name: 'subscription create',
method: 'POST',
path: 'subscriptions',
body: 'json',
},
{
name: 'subscription run',
method: 'PUT',
path: 'subscriptions/run',
body: 'ids',
existing: true,
},
{
name: 'subscription stop',
method: 'PUT',
path: 'subscriptions/stop',
body: 'ids',
existing: true,
},
{
name: 'subscription disable',
method: 'PUT',
path: 'subscriptions/disable',
body: 'ids',
existing: true,
},
{
name: 'subscription enable',
method: 'PUT',
path: 'subscriptions/enable',
body: 'ids',
existing: true,
},
{
name: 'subscription logs',
method: 'GET',
path: 'subscriptions/:id/log',
params: ['id'],
existing: true,
},
{
name: 'subscription update',
method: 'PUT',
path: 'subscriptions',
params: ['id'],
body: 'object-id',
},
{
name: 'subscription delete',
method: 'DELETE',
path: 'subscriptions',
body: 'ids',
},
{
name: 'subscription get',
method: 'GET',
path: 'subscriptions/:id',
params: ['id'],
existing: true,
},
{
name: 'subscription status',
method: 'PUT',
path: 'subscriptions/status',
body: 'json',
},
{
name: 'subscription log-files',
method: 'GET',
path: 'subscriptions/:id/logs',
params: ['id'],
},
{ name: 'app list', method: 'GET', path: 'apps' },
{ name: 'app create', method: 'POST', path: 'apps', body: 'json' },
{
name: 'app update',
method: 'PUT',
path: 'apps',
params: ['id'],
body: 'object-id',
},
{ name: 'app delete', method: 'DELETE', path: 'apps', body: 'ids' },
{
name: 'app reset-secret',
method: 'PUT',
path: 'apps/:id/reset-secret',
params: ['id'],
},
{
name: 'auth login',
method: 'GET',
path: 'auth/token',
existing: true,
anonymous: true,
},
{ name: 'env list', method: 'GET', path: 'envs' },
{ name: 'env create', method: 'POST', path: 'envs', body: 'json' },
{
name: 'env update',
method: 'PUT',
path: 'envs',
params: ['id'],
body: 'object-id',
},
{ name: 'env delete', method: 'DELETE', path: 'envs', body: 'ids' },
{
name: 'env move',
method: 'PUT',
path: 'envs/:id/move',
params: ['id'],
body: 'json',
},
{ name: 'env disable', method: 'PUT', path: 'envs/disable', body: 'ids' },
{ name: 'env enable', method: 'PUT', path: 'envs/enable', body: 'ids' },
{ name: 'env rename', method: 'PUT', path: 'envs/name', body: 'json' },
{ name: 'env get', method: 'GET', path: 'envs/:id', params: ['id'] },
{ name: 'env pin', method: 'PUT', path: 'envs/pin', body: 'ids' },
{ name: 'env unpin', method: 'PUT', path: 'envs/unpin', body: 'ids' },
{
name: 'env labels-create',
method: 'POST',
path: 'envs/labels',
body: 'json',
},
{
name: 'env labels-delete',
method: 'DELETE',
path: 'envs/labels',
body: 'json',
},
{
name: 'env upload',
method: 'POST',
path: 'envs/upload',
body: 'json',
upload: 'env',
},
{ name: 'config samples', method: 'GET', path: 'configs/samples' },
{ name: 'config list', method: 'GET', path: 'configs/files' },
{ name: 'config get', method: 'GET', path: 'configs/detail' },
{ name: 'config save', method: 'POST', path: 'configs/save', body: 'json' },
{ name: 'script list', method: 'GET', path: 'scripts' },
{ name: 'script get', method: 'GET', path: 'scripts/detail' },
{
name: 'script create',
method: 'POST',
path: 'scripts',
body: 'json',
upload: 'file',
},
{
name: 'script update',
method: 'PUT',
path: 'scripts',
body: 'json',
upload: 'file',
},
{ name: 'script delete', method: 'DELETE', path: 'scripts', body: 'json' },
{
name: 'script download',
method: 'POST',
path: 'scripts/download',
body: 'json',
download: true,
},
{ name: 'script run', method: 'PUT', path: 'scripts/run', body: 'json' },
{ name: 'script stop', method: 'PUT', path: 'scripts/stop', body: 'json' },
{
name: 'script rename',
method: 'PUT',
path: 'scripts/rename',
body: 'json',
},
{ name: 'log list', method: 'GET', path: 'logs' },
{ name: 'log get', method: 'GET', path: 'logs/detail' },
{ name: 'log delete', method: 'DELETE', path: 'logs', body: 'json' },
{
name: 'log download',
method: 'POST',
path: 'logs/download',
body: 'json',
download: true,
},
{ name: 'dependency list', method: 'GET', path: 'dependencies' },
{
name: 'dependency create',
method: 'POST',
path: 'dependencies',
body: 'json',
},
{
name: 'dependency update',
method: 'PUT',
path: 'dependencies',
params: ['id'],
body: 'object-id',
},
{
name: 'dependency delete',
method: 'DELETE',
path: 'dependencies',
body: 'ids',
},
{
name: 'dependency force-delete',
method: 'DELETE',
path: 'dependencies/force',
body: 'ids',
},
{
name: 'dependency get',
method: 'GET',
path: 'dependencies/:id',
params: ['id'],
},
{
name: 'dependency reinstall',
method: 'PUT',
path: 'dependencies/reinstall',
body: 'ids',
},
{
name: 'dependency cancel',
method: 'PUT',
path: 'dependencies/cancel',
body: 'ids',
},
{ name: 'system info', method: 'GET', path: 'system' },
{ name: 'system config-get', method: 'GET', path: 'system/config' },
{
name: 'system config-log-remove-frequency',
method: 'PUT',
path: 'system/config/log-remove-frequency',
body: 'json',
},
{
name: 'system config-cron-concurrency',
method: 'PUT',
path: 'system/config/cron-concurrency',
body: 'json',
},
{
name: 'system config-dependence-proxy',
method: 'PUT',
path: 'system/config/dependence-proxy',
body: 'json',
},
{
name: 'system config-node-mirror',
method: 'PUT',
path: 'system/config/node-mirror',
body: 'json',
},
{
name: 'system config-python-mirror',
method: 'PUT',
path: 'system/config/python-mirror',
body: 'json',
},
{
name: 'system config-linux-mirror',
method: 'PUT',
path: 'system/config/linux-mirror',
body: 'json',
},
{ name: 'system update-check', method: 'PUT', path: 'system/update-check' },
{ name: 'system update', method: 'PUT', path: 'system/update' },
{ name: 'system reload', method: 'PUT', path: 'system/reload', body: 'json' },
{ name: 'system notify', method: 'PUT', path: 'system/notify', body: 'json' },
{
name: 'system command-run',
method: 'PUT',
path: 'system/command-run',
body: 'json',
download: true,
},
{
name: 'system command-stop',
method: 'PUT',
path: 'system/command-stop',
body: 'json',
},
{
name: 'system data-export',
method: 'PUT',
path: 'system/data/export',
body: 'json',
download: true,
},
{
name: 'system data-import',
method: 'PUT',
path: 'system/data/import',
body: 'json',
upload: 'data',
},
{ name: 'system logs', method: 'GET', path: 'system/log' },
{ name: 'system logs-delete', method: 'DELETE', path: 'system/log' },
{
name: 'system auth-reset',
method: 'PUT',
path: 'system/auth/reset',
body: 'json',
},
{
name: 'system config-timezone',
method: 'PUT',
path: 'system/config/timezone',
body: 'json',
},
{
name: 'system config-lang',
method: 'PUT',
path: 'system/config/lang',
body: 'json',
},
{
name: 'system config-panel-title',
method: 'PUT',
path: 'system/config/panel-title',
body: 'json',
},
{
name: 'system config-global-ssh-key',
method: 'PUT',
path: 'system/config/global-ssh-key',
body: 'json',
},
{
name: 'system config-dependence-clean',
method: 'PUT',
path: 'system/config/dependence-clean',
body: 'json',
},
{ name: 'dashboard record', method: 'POST', path: 'dashboard/record', body: 'json' },
{ name: 'dashboard overview', method: 'GET', path: 'dashboard/overview' },
{ name: 'dashboard trend', method: 'GET', path: 'dashboard/trend' },
{ name: 'dashboard top-time', method: 'GET', path: 'dashboard/top-time' },
{ name: 'dashboard top-count', method: 'GET', path: 'dashboard/top-count' },
{ name: 'dashboard runtime', method: 'GET', path: 'dashboard/runtime' },
{ name: 'dashboard labels', method: 'GET', path: 'dashboard/labels' },
{ name: 'dashboard system', method: 'GET', path: 'dashboard/system' },
{
name: 'system client-ip-get',
method: 'GET',
path: 'system/client-ip/config',
},
{
name: 'system client-ip-set',
method: 'PUT',
path: 'system/client-ip/config',
body: 'json',
},
{
name: 'system client-ip-diagnose',
method: 'GET',
path: 'system/client-ip/diagnose',
},
{
name: 'system retention-set',
method: 'PUT',
path: 'system/storage-retention/config',
body: 'json',
},
{
name: 'system retention-preview',
method: 'POST',
path: 'system/storage-retention/preview',
body: 'json',
},
{
name: 'system retention-cleanup',
method: 'POST',
path: 'system/storage-retention/cleanup',
body: 'json',
},
{
name: 'user login',
method: 'POST',
path: 'user/login',
body: 'json',
anonymous: true,
},
{ name: 'user logout', method: 'POST', path: 'user/logout' },
{ name: 'user update', method: 'PUT', path: 'user', body: 'json' },
{ name: 'user get', method: 'GET', path: 'user' },
{ name: 'user two-factor-init', method: 'GET', path: 'user/two-factor/init' },
{
name: 'user two-factor-active',
method: 'PUT',
path: 'user/two-factor/active',
body: 'json',
},
{
name: 'user two-factor-deactivate',
method: 'PUT',
path: 'user/two-factor/deactivate',
},
{
name: 'user two-factor-login',
method: 'PUT',
path: 'user/two-factor/login',
body: 'json',
anonymous: true,
},
{ name: 'user login-log', method: 'GET', path: 'user/login-log' },
{ name: 'user ip-blacklist', method: 'GET', path: 'user/ip-blacklist' },
{
name: 'user ip-blacklist-set',
method: 'PUT',
path: 'user/ip-blacklist',
body: 'json',
},
{
name: 'user ip-blacklist-delete',
method: 'DELETE',
path: 'user/ip-blacklist',
body: 'json',
},
{ name: 'user notification-get', method: 'GET', path: 'user/notification' },
{
name: 'user notification-set',
method: 'PUT',
path: 'user/notification',
body: 'json',
},
{
name: 'user init',
method: 'PUT',
path: 'user/init',
body: 'json',
anonymous: true,
},
{
name: 'user notification-init',
method: 'PUT',
path: 'user/notification/init',
body: 'json',
anonymous: true,
},
{
name: 'user avatar',
method: 'PUT',
path: 'user/avatar',
body: 'json',
upload: 'avatar',
},
{ name: 'system apply-reload', method: 'PUT', path: 'update/reload' },
{ name: 'system apply-system', method: 'PUT', path: 'update/system' },
{ name: 'system apply-data', method: 'PUT', path: 'update/data' },
{ name: 'health get', method: 'GET', path: 'health' },
];