From 89c6355635112574a7e1c368a527ac49e6582cd4 Mon Sep 17 00:00:00 2001 From: whyour Date: Sun, 11 Oct 2026 01:51:04 +0800 Subject: [PATCH 1/4] fix: renew system tokens and serialize authentication cache updates --- back/loaders/initData.ts | 27 +- back/loaders/initTask.ts | 1 + back/services/open.ts | 150 ++++-- back/token.ts | 21 +- shell/api.sh | 126 +++-- test/back/restart-instance-recovery.test.cjs | 3 +- test/back/shell-api-parsing.test.cjs | 8 +- test/back/shellApiToken.test.cjs | 151 ++++++ test/back/systemTokenRenewal.test.cjs | 497 +++++++++++++++++++ 9 files changed, 835 insertions(+), 149 deletions(-) create mode 100644 test/back/shellApiToken.test.cjs create mode 100644 test/back/systemTokenRenewal.test.cjs diff --git a/back/loaders/initData.ts b/back/loaders/initData.ts index bfe3e61b..7e36171b 100644 --- a/back/loaders/initData.ts +++ b/back/loaders/initData.ts @@ -13,12 +13,11 @@ import { AuthDataType, SystemModel } from '../data/system'; import SystemService from '../services/system'; import UserService from '../services/user'; import { writeFile, readFile } from 'fs/promises'; -import { createRandomString, fileExist, isDemoEnv, safeJSONParse } from '../config/util'; +import { fileExist, isDemoEnv, safeJSONParse } from '../config/util'; import OpenService from '../services/open'; import { shareStore } from '../shared/store'; import Logger from './logger'; import cronClient from '../schedule/client'; -import { AppModel } from '../data/open'; import { InstanceStatus, RunningInstanceModel } from '../data/runningInstance'; import { setLang, systemLang } from '../shared/i18n'; @@ -31,24 +30,7 @@ export default async () => { const openService = Container.get(OpenService); // 初始化增加系统配置 - let systemApp = ( - await AppModel.findOne({ - where: { name: 'system' }, - }) - )?.get({ plain: true }); - if (!systemApp) { - systemApp = await AppModel.create({ - name: 'system', - scopes: ['crons', 'system', 'dashboard'], - client_id: createRandomString(12, 12), - client_secret: createRandomString(24, 24), - }); - } else if (!systemApp.scopes.includes('dashboard')) { - await AppModel.update( - { scopes: [...systemApp.scopes, 'dashboard'] }, - { where: { name: 'system' } }, - ); - } + await openService.initializeSystemApp(); const [systemConfig] = await SystemModel.findOrCreate({ where: { type: AuthDataType.systemConfig }, }); @@ -250,9 +232,6 @@ export default async () => { await envService.set_envs(); const authInfo = await userService.getAuthInfo(); - const apps = await openService.findApps(); await shareStore.updateAuthInfo(authInfo); - if (apps?.length) { - await shareStore.updateApps(apps); - } + await openService.refreshApps(); }; diff --git a/back/loaders/initTask.ts b/back/loaders/initTask.ts index 608f00e9..7424a6b5 100644 --- a/back/loaders/initTask.ts +++ b/back/loaders/initTask.ts @@ -26,6 +26,7 @@ export default async () => { if (await fileExist(tokenFile)) { tokenCommand = `node ${tokenFile}`; } + tokenCommand += ' --renew'; const cron = { id: NaN, name: t('生成token'), diff --git a/back/services/open.ts b/back/services/open.ts index 19d846c0..e39486a6 100644 --- a/back/services/open.ts +++ b/back/services/open.ts @@ -6,27 +6,77 @@ import { v4 as uuidV4 } from 'uuid'; import sequelize, { Op } from 'sequelize'; import { shareStore } from '../shared/store'; import { t } from '../shared/i18n'; +import { lock } from 'proper-lockfile'; +import path from 'path'; +import os from 'os'; +import { writeFile, rename, rm, stat, chmod } from 'fs/promises'; +import config from '../config'; @Service() export default class OpenService { constructor(@Inject('logger') private logger: winston.Logger) {} + // Every database mutation and full authentication-cache publication shares + // this cross-process lock. Lock a separate marker, not token.json itself. + private async withAppsLock(operation: () => Promise): Promise { + const target = path.join(config.configPath, '.apps-state'); + const release = await lock(target, { + realpath: false, + stale: 10_000, + retries: { retries: 10, factor: 2, minTimeout: 100, maxTimeout: 3000 }, + }); + try { + return await operation(); + } finally { + await release(); + } + } + + public async initializeSystemApp(): Promise { + await this.withAppsLock(async () => { + const doc = await AppModel.findOne({ where: { name: 'system' } }); + const app = doc?.get({ plain: true }); + if (!app) { + await this.insert({ + name: 'system', + scopes: ['crons', 'system', 'dashboard'], + client_id: createRandomString(12, 12), + client_secret: createRandomString(24, 24), + }); + } else if (!app.scopes.includes('dashboard')) { + await AppModel.update( + { scopes: [...app.scopes, 'dashboard'] }, + { where: { id: app.id } }, + ); + } + await shareStore.updateApps(await this.find({})); + }); + } + + public async refreshApps(): Promise { + await this.withAppsLock(async () => { + await shareStore.updateApps(await this.find({})); + }); + } + public async findApps(): Promise { const docs = await this.find({}); return docs; } public async create(payload: App): Promise { - const tab = { ...payload }; - tab.client_id = createRandomString(12, 12); - tab.client_secret = createRandomString(24, 24); - const doc = await this.insert(tab); - const apps = await this.find({}); - await shareStore.updateApps(apps); - return { ...doc, tokens: [] }; + return this.withAppsLock(async () => { + const tab = { ...payload }; + tab.client_id = createRandomString(12, 12); + tab.client_secret = createRandomString(24, 24); + const doc = await this.insert(tab); + const apps = await this.find({}); + await shareStore.updateApps(apps); + return { ...doc, tokens: [] }; + }); } - public async insert(payload: App): Promise { + private async insert(payload: App): Promise { const doc = await AppModel.create(payload, { returning: true }); return doc.get({ plain: true }); } @@ -41,10 +91,12 @@ export default class OpenService { } private async updateDb(payload: Partial): Promise { - await AppModel.update(payload, { where: { id: payload.id } }); - const apps = await this.find({}); - await shareStore.updateApps(apps); - return apps?.find((x) => x.id === payload.id) as App; + return this.withAppsLock(async () => { + await AppModel.update(payload, { where: { id: payload.id } }); + const apps = await this.find({}); + await shareStore.updateApps(apps); + return apps?.find((x) => x.id === payload.id) as App; + }); } public async getDb(query: Record): Promise { @@ -56,9 +108,11 @@ export default class OpenService { } public async remove(ids: number[]) { - await AppModel.destroy({ where: { id: ids } }); - const apps = await this.find({}); - await shareStore.updateApps(apps); + return this.withAppsLock(async () => { + await AppModel.destroy({ where: { id: ids } }); + const apps = await this.find({}); + await shareStore.updateApps(apps); + }); } public async resetSecret(id: number): Promise { @@ -112,7 +166,15 @@ export default class OpenService { return docs.map((x) => x.get({ plain: true })); } - public async authToken({ + public async authToken(credentials: { + client_id: string; + client_secret: string; + }): Promise { + return this.withAppsLock(() => this.issueToken(credentials)); + } + + // Caller holds withAppsLock through database update and cache publication. + private async issueToken({ client_id, client_secret, }: { @@ -156,27 +218,47 @@ export default class OpenService { } } - public async generateSystemToken(): Promise<{ + public async generateSystemToken(renew = false): Promise<{ value: string; expiration: number; }> { - const apps = await shareStore.getApps(); - const systemApp = apps?.find((x) => x.name === 'system'); - if (!systemApp) { - throw new Error('system app not found'); - } - const now = Math.round(Date.now() / 1000); - const currentToken = systemApp.tokens?.find((x) => x.expiration > now); - if (currentToken) { - return currentToken; - } - const { data } = await this.authToken({ - client_id: systemApp.client_id, - client_secret: systemApp.client_secret, + return this.withAppsLock(async () => { + // Read after acquiring the lock; a concurrent issuer may have renewed. + const systemApp = await this.getDb({ name: 'system' }); + const now = Math.round(Date.now() / 1000); + let appToken = systemApp.tokens + ?.filter((token) => token.expiration > now) + .sort((left, right) => right.expiration - left.expiration)[0]; + if (renew || !appToken) { + const { data } = await this.issueToken({ + client_id: systemApp.client_id, + client_secret: systemApp.client_secret, + }); + appToken = { value: data.token, expiration: data.expiration }; + } else { + // Recover a prior database commit whose cache publication failed. + await shareStore.updateApps(await this.find({})); + } + const tokenFile = path.join(config.configPath, 'token.json'); + const temporaryFile = `${tokenFile}.${process.pid}.tmp`; + const mode = await stat(tokenFile).then( + (file) => file.mode & 0o777, + (error: NodeJS.ErrnoException) => { + if (error.code === 'ENOENT') return 0o600; + throw error; + }, + ); + try { + await writeFile(temporaryFile, `${JSON.stringify(appToken)}${os.EOL}`, { + mode, + }); + await chmod(temporaryFile, mode); + // Shell readers see a complete old or new document, never a partial one. + await rename(temporaryFile, tokenFile); + } finally { + await rm(temporaryFile, { force: true }); + } + return appToken; }); - return { - ...data, - value: data.token, - }; } } diff --git a/back/token.ts b/back/token.ts index d307c623..e4400ca3 100755 --- a/back/token.ts +++ b/back/token.ts @@ -2,30 +2,19 @@ import 'reflect-metadata'; import OpenService from './services/open'; import { Container } from 'typedi'; import LoggerInstance from './loaders/logger'; -import config from './config'; -import path from 'path'; -import os from 'os'; -import { writeFileWithLock } from './shared/utils'; - -const tokenFile = path.join(config.configPath, 'token.json'); async function getToken() { try { Container.set('logger', LoggerInstance); const openService = Container.get(OpenService); - const appToken = await openService.generateSystemToken(); + const appToken = await openService.generateSystemToken( + process.argv.includes('--renew'), + ); console.log(appToken.value); - await writeFile({ - value: appToken.value, - expiration: appToken.expiration, - }); } catch (error) { - console.log(error); + console.error(error); + process.exitCode = 1; } } -async function writeFile(data: any) { - await writeFileWithLock(tokenFile, `${JSON.stringify(data)}${os.EOL}`); -} - getToken(); diff --git a/shell/api.sh b/shell/api.sh index 2cf9a9ca..e4b1afe8 100755 --- a/shell/api.sh +++ b/shell/api.sh @@ -26,6 +26,28 @@ get_token() { create_token } +# Check the cached token before every authenticated API request. A rejected +# token is refreshed and retried once; other failures are never retried. +# Arguments are curl options, including the URL, method and optional body. +ql_api_request() { + local api="" + local attempt + get_token || return $? + for attempt in 1 2; do + api=$(curl -s --noproxy "*" \ + -H "Authorization: Bearer ${__ql_token__}" \ + -H "Content-Type: application/json;charset=UTF-8" \ + "$@" \ + --compressed) + if [[ "$attempt" == 2 || "$api" == '{"code":200}' ]] || + [[ "$(jq -r '.code' <<< "$api" 2>/dev/null)" != 401 ]]; then + break + fi + create_token || return $? + done + printf '%s' "$api" +} + # Read the status response once; preserve multiline error messages and the # legacy code/message variables used by the shell API callers. ql_parse_status_response() { @@ -63,13 +85,10 @@ add_cron_api() { sub_id="null" fi - local api=$( - curl -s --noproxy "*" "http://localhost:${ql_port}/open/crons?t=$currentTimeStamp" \ - -H "Authorization: Bearer ${__ql_token__}" \ - -H "Content-Type: application/json;charset=UTF-8" \ - --data-raw "{\"name\":\"${name//\"/\\\"}\",\"command\":\"${command//\"/\\\"}\",\"schedule\":\"$schedule\",\"sub_id\":$sub_id}" \ - --compressed - ) + local api=$(ql_api_request \ + "http://localhost:${ql_port}/open/crons?t=$currentTimeStamp" \ + --data-raw "{\"name\":\"${name//\"/\\\"}\",\"command\":\"${command//\"/\\\"}\",\"schedule\":\"$schedule\",\"sub_id\":$sub_id}" \ + -X POST) code=$(echo "$api" | jq -r .code) message=$(echo "$api" | jq -r .message) if [[ $code == 200 ]]; then @@ -93,14 +112,10 @@ update_cron_api() { local id="$4" fi - local api=$( - curl -s --noproxy "*" "http://localhost:${ql_port}/open/crons?t=$currentTimeStamp" \ - -X 'PUT' \ - -H "Authorization: Bearer ${__ql_token__}" \ - -H "Content-Type: application/json;charset=UTF-8" \ - --data-raw "{\"name\":\"${name//\"/\\\"}\",\"command\":\"${command//\"/\\\"}\",\"schedule\":\"$schedule\",\"id\":\"$id\"}" \ - --compressed - ) + local api=$(ql_api_request \ + "http://localhost:${ql_port}/open/crons?t=$currentTimeStamp" \ + -X PUT \ + --data-raw "{\"name\":\"${name//\"/\\\"}\",\"command\":\"${command//\"/\\\"}\",\"schedule\":\"$schedule\",\"id\":\"$id\"}") code=$(echo "$api" | jq -r .code) message=$(echo "$api" | jq -r .message) if [[ $code == 200 ]]; then @@ -120,14 +135,10 @@ update_cron_command_api() { local id="$2" fi - local api=$( - curl -s --noproxy "*" "http://localhost:${ql_port}/open/crons?t=$currentTimeStamp" \ - -X 'PUT' \ - -H "Authorization: Bearer ${__ql_token__}" \ - -H "Content-Type: application/json;charset=UTF-8" \ - --data-raw "{\"command\":\"${command//\"/\\\"}\",\"id\":\"$id\"}" \ - --compressed - ) + local api=$(ql_api_request \ + "http://localhost:${ql_port}/open/crons?t=$currentTimeStamp" \ + -X PUT \ + --data-raw "{\"command\":\"${command//\"/\\\"}\",\"id\":\"$id\"}") code=$(echo "$api" | jq -r .code) message=$(echo "$api" | jq -r .message) if [[ $code == 200 ]]; then @@ -140,14 +151,10 @@ update_cron_command_api() { del_cron_api() { local ids="$1" local currentTimeStamp=$(date +%s) - local api=$( - curl -s --noproxy "*" "http://localhost:${ql_port}/open/crons?t=$currentTimeStamp" \ - -X 'DELETE' \ - -H "Authorization: Bearer ${__ql_token__}" \ - -H "Content-Type: application/json;charset=UTF-8" \ - --data-raw "[$ids]" \ - --compressed - ) + local api=$(ql_api_request \ + "http://localhost:${ql_port}/open/crons?t=$currentTimeStamp" \ + -X DELETE \ + --data-raw "[$ids]") code=$(echo "$api" | jq -r .code) message=$(echo "$api" | jq -r .message) if [[ $code == 200 ]]; then @@ -171,14 +178,10 @@ update_cron() { dataRaw="${dataRaw},\"exit_code\":$exitCode" fi dataRaw="${dataRaw}}" - local api=$( - curl -s --noproxy "*" "http://localhost:${ql_port}/open/crons/status?t=$currentTimeStamp" \ - -X 'PUT' \ - -H "Authorization: Bearer ${__ql_token__}" \ - -H "Content-Type: application/json;charset=UTF-8" \ - --data-raw "$dataRaw" \ - --compressed - ) + local api=$(ql_api_request \ + "http://localhost:${ql_port}/open/crons/status?t=$currentTimeStamp" \ + -X PUT \ + --data-raw "$dataRaw") ql_parse_status_response "$api" || true if [[ $code != 200 ]]; then if [[ ! $message ]]; then @@ -192,14 +195,10 @@ notify_api() { local title="$1" local content="$2" local currentTimeStamp=$(date +%s) - local api=$( - curl -s --noproxy "*" "http://localhost:${ql_port}/open/system/notify?t=$currentTimeStamp" \ - -X 'PUT' \ - -H "Authorization: Bearer ${__ql_token__}" \ - -H "Content-Type: application/json;charset=UTF-8" \ - --data-raw "{\"title\":\"${title//\"/\\\"}\",\"content\":\"${content//\"/\\\"}\"}" \ - --compressed - ) + local api=$(ql_api_request \ + "http://localhost:${ql_port}/open/system/notify?t=$currentTimeStamp" \ + -X PUT \ + --data-raw "{\"title\":\"${title//\"/\\\"}\",\"content\":\"${content//\"/\\\"}\"}") code=$(echo "$api" | jq -r .code) message=$(echo "$api" | jq -r .message) if [[ $code == 200 ]]; then @@ -212,12 +211,9 @@ notify_api() { find_cron_api() { local params="$1" local currentTimeStamp=$(date +%s) - local api=$( - curl -s --noproxy "*" "http://localhost:${ql_port}/open/crons/detail?$params&t=$currentTimeStamp" \ - -H "Authorization: Bearer ${__ql_token__}" \ - -H "Content-Type: application/json;charset=UTF-8" \ - --compressed - ) + local api=$(ql_api_request \ + "http://localhost:${ql_port}/open/crons/detail?$params&t=$currentTimeStamp" \ + -X GET) data=$(echo "$api" | jq -r .data) if [[ $data == 'null' ]]; then echo -e "" @@ -231,14 +227,10 @@ update_auth_config() { local body="$1" local tip="$2" local currentTimeStamp=$(date +%s) - local api=$( - curl -s --noproxy "*" "http://localhost:${ql_port}/open/system/auth/reset?t=$currentTimeStamp" \ - -X 'PUT' \ - -H "Authorization: Bearer ${__ql_token__}" \ - -H "Content-Type: application/json;charset=UTF-8" \ - --data-raw "{$body}" \ - --compressed - ) + local api=$(ql_api_request \ + "http://localhost:${ql_port}/open/system/auth/reset?t=$currentTimeStamp" \ + -X PUT \ + --data-raw "{$body}") code=$(echo "$api" | jq -r .code) message=$(echo "$api" | jq -r .message) if [[ $code == 200 ]]; then @@ -254,14 +246,10 @@ record_cron_stat() { local elapsed="${3:-0}" [[ $ref_id ]] && [[ $ref_id -gt 0 ]] 2>/dev/null || return - local api=$( - curl -s --noproxy "*" "http://localhost:${ql_port:-5700}/open/dashboard/record" \ + local api=$(ql_api_request \ + "http://localhost:${ql_port:-5700}/open/dashboard/record" \ -X POST \ - -H "Authorization: Bearer ${__ql_token__}" \ - -H "Content-Type: application/json;charset=UTF-8" \ - --data-raw "{\"ref_id\":$ref_id,\"code\":$exit_code,\"elapsed\":$elapsed}" \ - --compressed - ) + --data-raw "{\"ref_id\":$ref_id,\"code\":$exit_code,\"elapsed\":$elapsed}") ql_parse_status_response "$api" || true if [[ $code != 200 ]]; then if [[ ! $message ]]; then @@ -270,5 +258,3 @@ record_cron_stat() { echo -e "${message}" fi } - -get_token diff --git a/test/back/restart-instance-recovery.test.cjs b/test/back/restart-instance-recovery.test.cjs index a0e3c03d..ac0f78bd 100644 --- a/test/back/restart-instance-recovery.test.cjs +++ b/test/back/restart-instance-recovery.test.cjs @@ -27,7 +27,8 @@ test('startup closes interrupted instances without inventing exit codes or rewri const service = { set_envs: async () => {}, getAuthInfo: async () => ({}), - findApps: async () => [], + initializeSystemApp: async () => {}, + refreshApps: async () => {}, }; const initData = load('back/loaders/initData.ts', { typedi: { Container: { get: () => service } }, diff --git a/test/back/shell-api-parsing.test.cjs b/test/back/shell-api-parsing.test.cjs index 8c7960b4..c0e60061 100644 --- a/test/back/shell-api-parsing.test.cjs +++ b/test/back/shell-api-parsing.test.cjs @@ -91,13 +91,13 @@ test('expired, corrupt, missing or header-unsafe token cache refreshes under err assert.equal(r.stdout, 'generated:1'); } }); -test('success with a message still parses once and stays silent', (t) => { +test('success with a message checks authentication and stays silent', (t) => { const f = fixture(t); fs.writeFileSync(f.response, JSON.stringify({ code: 200, message: 'ok' })); const r = f.run('update_cron 1 0 123 log 1'); assert.equal(r.status, 0, r.stderr); assert.equal(r.stdout, ''); - assert.equal(f.count(), 1); + assert.equal(f.count(), 2); }); test('status and statistics errors preserve multiline Unicode messages', (t) => { const f = fixture(t); @@ -113,7 +113,7 @@ test('status and statistics errors preserve multiline Unicode messages', (t) => assert.equal(r.status, 0, r.stderr); assert.equal(r.stdout, '写入失败\n请重试 "原任务"\n'); } - assert.equal(f.count(), 2); + assert.equal(f.count(), 4); }); test('non-JSON errors fall back to raw text and absent messages retain legacy null', (t) => { const f = fixture(t); @@ -180,5 +180,5 @@ test('success-shaped invalid documents retain the raw-response error fallback', assert.equal(r.status, 0, r.stderr); assert.equal(r.stdout, body + '\n'); } - assert.equal(f.count(), cases.length); + assert.equal(f.count(), cases.length * 2); }); diff --git a/test/back/shellApiToken.test.cjs b/test/back/shellApiToken.test.cjs new file mode 100644 index 00000000..92b02f42 --- /dev/null +++ b/test/back/shellApiToken.test.cjs @@ -0,0 +1,151 @@ +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const os = require('node:os'); +const path = require('node:path'); +const { spawnSync } = require('node:child_process'); +const { test } = require('node:test'); + +const apiFile = path.resolve(__dirname, '../../shell/api.sh'); + +const endpoints = { + status: { + method: 'PUT', url: /\/open\/crons\/status\?t=\d+$/, + body: { ids: ['37'], status: '1', pid: '4321', log_path: 'task/run.log', + last_execution_time: 1787004000, last_running_time: 90, exit_code: 0 }, + success: '', failure: (message) => message, + }, + statistics: { + method: 'POST', url: /\/open\/dashboard\/record$/, + body: { ref_id: 37, code: 0, elapsed: 90 }, + success: '', failure: (message) => message, + }, + add: { + method: 'POST', url: /\/open\/crons\?t=\d+$/, + body: { name: 'sample job', command: 'task job.py', schedule: '0 * * * *', sub_id: null }, + success: 'sample job -> 添加成功', failure: (message) => `sample job -> 添加失败(${message})`, + }, + update: { + method: 'PUT', url: /\/open\/crons\?t=\d+$/, + body: { name: 'sample job', command: 'task job.py', schedule: '0 * * * *', id: '37' }, + success: 'sample job -> 更新成功', failure: (message) => `sample job -> 更新失败(${message})`, + }, + command: { + method: 'PUT', url: /\/open\/crons\?t=\d+$/, + body: { command: 'task job.py', id: '37' }, + success: 'task job.py -> 更新成功', failure: (message) => `task job.py -> 更新失败(${message})`, + }, + delete: { + method: 'DELETE', url: /\/open\/crons\?t=\d+$/, + body: [37, 38], success: '成功', failure: (message) => `失败(${message})`, + }, + notify: { + method: 'PUT', url: /\/open\/system\/notify\?t=\d+$/, + body: { title: 'title', content: 'body' }, + success: '通知发送成功🎉', failure: (message) => `通知失败(${message})`, + }, + find: { + method: 'GET', url: /\/open\/crons\/detail\?log_path=task\/run.log&t=\d+$/, + body: null, success: 'sample job', failure: () => '', + }, + auth: { + method: 'PUT', url: /\/open\/system\/auth\/reset\?t=\d+$/, + body: { retries: 0 }, success: '重置登录错误次数成功🎉', + failure: (message) => `重置登录错误次数失败(${message})`, + }, +}; + +function runCallback(endpoint, scenario) { + const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'ql-api-token-')); + try { + const tokenFile = path.join(directory, 'token.json'); + fs.writeFileSync(tokenFile, JSON.stringify({ + value: 'initial-token', expiration: Math.floor(Date.now() / 1000) + 3600, + })); + const child = spawnSync('bash', ['-c', ` + . "$API_FILE" + create_token() { + printf 'refresh\\n' >> "$CAPTURE" + __ql_token__=fresh-token + printf '{"value":"fresh-token","expiration":4102444800}' > "$file_auth_token" + } + case "$SCENARIO" in + expired) printf '{"value":"initial-token","expiration":1}' > "$file_auth_token" ;; + replaced) printf '{"value":"fresh-token","expiration":4102444800}' > "$file_auth_token" ;; + esac + curl() { + local auth body url method arg + while [[ $# -gt 0 ]]; do + arg="$1"; shift + case "$arg" in + -H) [[ "$1" == Authorization:* ]] && auth="$1"; shift ;; + --data-raw) body="$1"; shift ;; + -X) method="$1"; shift ;; + http:*) url="$arg" ;; + esac + done + printf '%s\\n%s\\n%s\\n%s\\n' "$auth" "$method" "$url" "\${body:-null}" >> "$CAPTURE" + if [[ "$SCENARIO" == forbidden ]]; then + printf '{"code":403,"message":"forbidden"}' + elif [[ "$SCENARIO" == unavailable ]]; then + printf '{"code":500,"message":"unavailable"}' + elif [[ "$SCENARIO" == persistent || ( "$SCENARIO" != valid && "$auth" != 'Authorization: Bearer fresh-token' ) ]]; then + printf '{"code":401,"message":"Token 已失效"}' + else + printf '{"code":200,"data":{"name":"sample job"}}' + fi + } + t() { printf "$@"; } + case "$ENDPOINT" in + status) update_cron '"37"' 1 4321 'task/run.log' 1787004000 90 0 execution-37 ;; + statistics) record_cron_stat 37 0 90 ;; + add) add_cron_api '0 * * * *' 'task job.py' 'sample job' ;; + update) update_cron_api '0 * * * *' 'task job.py' 'sample job' 37 ;; + command) update_cron_command_api 'task job.py' 37 ;; + delete) del_cron_api '37,38' ;; + notify) notify_api title body ;; + find) find_cron_api 'log_path=task/run.log' ;; + auth) update_auth_config '"retries":0' '重置登录错误次数' ;; + esac + `], { + env: { ...process.env, PATH: `/usr/bin:/bin:${process.env.PATH}`, API_FILE: apiFile, file_auth_token: tokenFile, + CAPTURE: path.join(directory, 'requests'), SCENARIO: scenario, + ENDPOINT: endpoint, ql_port: '5700' }, + encoding: 'utf8', timeout: 10_000, + }); + assert.equal(child.status, 0, child.stderr); + assert.equal(child.stderr, ''); + const lines = fs.readFileSync(path.join(directory, 'requests'), 'utf8').trim().split('\n'); + const refreshes = lines.filter((line) => line === 'refresh').length; + const requests = lines.filter((line) => line !== 'refresh'); + const captures = []; + for (let i = 0; i < requests.length; i += 4) { + captures.push({ auth: requests[i], method: requests[i + 1], + url: requests[i + 2], body: JSON.parse(requests[i + 3]) }); + } + return { output: child.stdout, refreshes, captures }; + } finally { + fs.rmSync(directory, { recursive: true, force: true }); + } +} + +for (const [endpoint, expected] of Object.entries(endpoints)) { + for (const scenario of ['valid', 'expired', 'replaced', 'rejected', 'persistent', 'forbidden', 'unavailable']) { + test(`${endpoint} API handles ${scenario} token without unbounded retries`, () => { + const { output, refreshes, captures } = runCallback(endpoint, scenario); + const retries = ['rejected', 'persistent'].includes(scenario); + assert.equal(captures.length, retries ? 2 : 1); + assert.equal(refreshes, ['expired', 'rejected', 'persistent'].includes(scenario) ? 1 : 0); + for (const capture of captures) { + assert.deepEqual(capture.body, expected.body); + assert.equal(capture.method, expected.method); + assert.match(capture.url, expected.url); + } + if (['expired', 'replaced', 'rejected'].includes(scenario)) { + assert.equal(captures.at(-1).auth, 'Authorization: Bearer fresh-token'); + } + const error = scenario === 'persistent' ? 'Token 已失效' + : scenario === 'forbidden' ? 'forbidden' : scenario === 'unavailable' ? 'unavailable' : ''; + assert.equal(output.trim(), error ? expected.failure(error) : expected.success); + }); + } +} diff --git a/test/back/systemTokenRenewal.test.cjs b/test/back/systemTokenRenewal.test.cjs new file mode 100644 index 00000000..ad185674 --- /dev/null +++ b/test/back/systemTokenRenewal.test.cjs @@ -0,0 +1,497 @@ +require('reflect-metadata'); +require('ts-node/register/transpile-only'); + +const assert = require('node:assert/strict'); +const { test } = require('node:test'); +const fs = require('node:fs'); +const os = require('node:os'); +const path = require('node:path'); +const { execFile } = require('node:child_process'); +const { promisify } = require('node:util'); +const environment = fs.mkdtempSync(path.join(os.tmpdir(), 'ql-token-env-')); +fs.writeFileSync(path.join(environment, '.env'), ''); +fs.mkdirSync(path.join(environment, 'data/db'), { recursive: true }); +process.env.QL_DIR = environment; +process.env.QL_DATA_DIR = path.join(environment, 'data'); +require('node:test').after(async () => { + await require('../../back/shared/store').keyvStore.disconnect(); + await require('../../back/data').sequelize.close(); + fs.rmSync(environment, { recursive: true, force: true }); +}); +const OpenService = require('../../back/services/open').default; +const { AppModel } = require('../../back/data/open'); +const { shareStore } = require('../../back/shared/store'); +const config = require('../../back/config').default; + +const DAY = 86400; +const START = 1787004000; +const execute = promisify(execFile); + +function fixture(t, initialTokens = []) { + const previousConfigPath = config.configPath; + const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'ql-token-renewal-')); + config.configPath = directory; + t.after(() => { + config.configPath = previousConfigPath; + fs.rmSync(directory, { recursive: true, force: true }); + }); + let now = START; + let app = { + name: 'system', client_id: 'system-client', client_secret: 'system-secret', + scopes: ['crons', 'system', 'dashboard'], tokens: initialTokens, + }; + t.mock.method(Date, 'now', () => now * 1000); + t.mock.method(shareStore, 'getApps', async () => [app]); + t.mock.method(shareStore, 'updateApps', async (apps) => { [app] = apps; }); + t.mock.method(AppModel, 'findOne', async ({ where }) => { + if (where.name) assert.equal(where.name, app.name); + else { + assert.equal(where.client_id, app.client_id); + assert.equal(where.client_secret, app.client_secret); + } + return { tokens: app.tokens, get: () => app }; + }); + t.mock.method(AppModel, 'update', async ({ tokens }) => { + app = { ...app, tokens }; + return [1]; + }); + t.mock.method(AppModel, 'findAll', async () => [{ get: () => app }]); + return { + service: new OpenService({}), + atDay(day) { now = START + day * DAY; }, + tokens() { return app.tokens; }, + }; +} + +test('28-day token generation renews ahead of the 30-day expiry', async (t) => { + const state = fixture(t); + const initial = await state.service.generateSystemToken(); + assert.equal(initial.expiration, START + 30 * DAY); + state.atDay(28); + const renewed = await state.service.generateSystemToken(true); + assert.equal(renewed.expiration, START + 58 * DAY); + assert.notEqual(renewed.value, initial.value); + assert.ok(state.tokens().some((token) => token.value === initial.value)); + state.atDay(56); + const next = await state.service.generateSystemToken(true); + assert.equal(next.expiration, START + 86 * DAY); + assert.ok(state.tokens().some((token) => token.value === renewed.value)); + assert.ok(!state.tokens().some((token) => token.value === initial.value)); +}); + +test('startup generation renews before a restarted 28-day interval', async (t) => { + const state = fixture(t); + await state.service.generateSystemToken(); + state.atDay(20); + const restarted = await state.service.generateSystemToken(true); + assert.equal(restarted.expiration, START + 50 * DAY); + state.atDay(48); + const renewed = await state.service.generateSystemToken(true); + assert.equal(renewed.expiration, START + 78 * DAY); + assert.ok(state.tokens().some((token) => token.value === restarted.value)); +}); + +test('generation at the five-token limit extends the reused token without revoking active tokens', async (t) => { + const initial = Array.from({ length: 5 }, (_, index) => ({ + value: `token-${index}`, expiration: START + 2 * DAY, + })); + const state = fixture(t, initial); + const renewed = await state.service.generateSystemToken(true); + assert.equal(renewed.value, 'token-4'); + assert.equal(renewed.expiration, START + 30 * DAY); + assert.equal(state.tokens().length, 5); + for (const token of initial) { + assert.ok(state.tokens().some((current) => current.value === token.value)); + } +}); + +test('ordinary acquisition reuses the newest valid database token and republishes its cache', async (t) => { + const initial = [ + { value: 'older-token', expiration: START + DAY }, + { value: 'newer-token', expiration: START + 20 * DAY }, + ]; + const state = fixture(t, initial); + // A stale process cache must not override the token chosen from the database. + shareStore.getApps = async () => [{ name: 'system', tokens: [] }]; + const token = await state.service.generateSystemToken(); + assert.equal(token.value, 'newer-token'); + assert.deepEqual(state.tokens(), initial); + assert.deepEqual( + JSON.parse(fs.readFileSync(path.join(config.configPath, 'token.json'), 'utf8')), + token, + ); +}); + +test('a failed generation releases its lock and does not publish a token', async (t) => { + const state = fixture(t); + const update = AppModel.update; + AppModel.update = async () => { throw new Error('generation failed'); }; + await assert.rejects(state.service.generateSystemToken(), /generation failed/); + assert.equal(fs.existsSync(path.join(config.configPath, 'token.json')), false); + assert.equal(fs.existsSync(path.join(config.configPath, 'token.json.refresh.lock')), false); + AppModel.update = update; + const token = await state.service.generateSystemToken(); + assert.ok(state.tokens().some((current) => current.value === token.value)); +}); + +test('acquisition recovers an authentication cache failure after the database commit', async (t) => { + const state = fixture(t); + const updateCache = shareStore.updateApps; + let attempts = 0; + shareStore.updateApps = async (apps) => { + if (++attempts === 1) throw new Error('authentication cache failed'); + return updateCache(apps); + }; + await assert.rejects(state.service.generateSystemToken(), /authentication cache failed/); + assert.equal(fs.existsSync(path.join(config.configPath, 'token.json')), false); + const committed = state.tokens()[0]; + const token = await state.service.generateSystemToken(); + assert.equal(token.value, committed.value); + assert.equal(state.tokens().length, 1); + assert.equal(attempts, 2); +}); + +async function processFixture(t, initialTokens = []) { + const root = path.resolve(__dirname, '../..'); + const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'ql-token-process-')); + t.after(() => fs.rmSync(directory, { recursive: true, force: true })); + const databaseFile = path.join(directory, 'database.json'); + fs.writeFileSync(databaseFile, JSON.stringify({ + name: 'system', client_id: 'system-client', client_secret: 'system-secret', + scopes: ['crons', 'system', 'dashboard'], tokens: initialTokens, + })); + const worker = path.join(directory, 'worker.cjs'); + fs.writeFileSync(worker, ` + const fs = require('node:fs/promises'); + const path = require('node:path'); + const root = process.cwd(); + const directory = __dirname; + const config = require(path.join(root, 'back/config')).default; + const { AppModel } = require(path.join(root, 'back/data/open')); + const { shareStore } = require(path.join(root, 'back/shared/store')); + config.configPath = directory; + const databaseFile = path.join(directory, 'database.json'); + const read = async () => JSON.parse(await fs.readFile(databaseFile, 'utf8')); + AppModel.findOne = async () => { + if (process.env.QL_TOKEN_TEST_HOLD === '1') { + await fs.writeFile(path.join(directory, 'locked'), 'ready'); + await new Promise(() => setInterval(() => {}, 1000)); + } + const app = await read(); + // Widen the read/write overlap so the original race is reproducible. + await new Promise(resolve => setTimeout(resolve, 75)); + return { ...app, get: () => app }; + }; + AppModel.update = async ({ tokens }) => { + if (process.env.QL_TOKEN_TEST_FAIL === '1') throw new Error('generation failed'); + const app = await read(); + await fs.writeFile(databaseFile, JSON.stringify({ ...app, tokens })); + return [1]; + }; + AppModel.findAll = async () => { + const app = await read(); + return [{ get: () => app }]; + }; + shareStore.getApps = async () => { throw new Error('stale cache must not be read'); }; + shareStore.updateApps = async () => {}; + require(path.join(root, 'back/token')); + `); + return { + directory, + run(renew = false, fail = false, hold = false) { + return execute(process.execPath, [ + '-r', require.resolve('ts-node/register/transpile-only'), worker, + ...(renew ? ['--renew'] : []), + ], { + cwd: root, timeout: 20_000, + env: { ...process.env, QL_TOKEN_TEST_FAIL: fail ? '1' : '0', QL_TOKEN_TEST_HOLD: hold ? '1' : '0' }, + }); + }, + tokens() { return JSON.parse(fs.readFileSync(databaseFile, 'utf8')).tokens; }, + cached() { return JSON.parse(fs.readFileSync(path.join(directory, 'token.json'), 'utf8')); }, + }; +} + +test('four independent token processes converge on one usable token when the cache is missing', async (t) => { + const state = await processFixture(t); + const results = await Promise.all(Array.from({ length: 4 }, () => state.run())); + const issued = results.map(({ stdout, stderr }) => { + assert.equal(stderr, ''); + return stdout.trim(); + }); + assert.equal(new Set(issued).size, 1); + assert.equal(state.tokens().length, 1); + assert.equal(state.tokens()[0].value, issued[0]); + assert.equal(state.cached().value, issued[0]); + assert.equal(fs.existsSync(path.join(state.directory, 'token.json.refresh.lock')), false); +}); + +test('concurrent scheduled renewal and ordinary acquisition preserve all returned tokens', async (t) => { + const original = { value: 'original-token', expiration: Math.round(Date.now() / 1000) + DAY }; + const state = await processFixture(t, [original]); + const results = await Promise.all([state.run(true), state.run(), state.run(true), state.run()]); + const tokens = state.tokens(); + assert.equal(tokens.length, 3); + assert.ok(tokens.some((token) => token.value === original.value)); + for (const { stdout, stderr } of results) { + assert.equal(stderr, ''); + assert.ok(tokens.some((token) => token.value === stdout.trim())); + } + assert.ok(tokens.some((token) => token.value === state.cached().value)); +}); + +test('token CLI reports generation failure on stderr with a nonzero exit code', async (t) => { + const state = await processFixture(t); + await assert.rejects(state.run(false, true), (error) => { + assert.equal(error.code, 1); + assert.equal(error.stdout, ''); + assert.match(error.stderr, /generation failed/); + return true; + }); + assert.equal(fs.existsSync(path.join(state.directory, 'token.json')), false); + const recovered = await state.run(); + assert.equal(recovered.stdout.trim(), state.cached().value); +}); + +test('startup configures the 28-day token task with explicit renewal', async (t) => { + const { Container } = require('typedi'); + const initialize = require('../../back/loaders/initTask').default; + const SystemService = require('../../back/services/system').default; + const ScheduleService = require('../../back/services/schedule').default; + const SubscriptionService = require('../../back/services/subscription').default; + const SshKeyService = require('../../back/services/sshKey').default; + const scheduled = []; + const services = new Map([ + [SystemService, { getSystemConfig: async () => undefined }], + [ScheduleService, { + cancelIntervalTask: async () => {}, + createIntervalTask: (...args) => scheduled.push(args), + }], + [SubscriptionService, { setSshConfig: async () => {}, list: async () => [] }], + [SshKeyService, {}], + ]); + t.mock.method(Container, 'get', (service) => { + assert.ok(services.has(service)); + return services.get(service); + }); + await initialize(); + assert.equal(scheduled.length, 1); + const [task, interval, immediate] = scheduled[0]; + assert.match(task.command, /(?:token\.ts|token\.js) --renew$/); + assert.equal(task.runOrigin, 'system'); + assert.deepEqual(interval, { days: 28 }); + assert.equal(immediate, true); +}); + +function appsFixture(t) { + const previousConfigPath = config.configPath; + const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'ql-apps-concurrency-')); + config.configPath = directory; + t.after(() => { + config.configPath = previousConfigPath; + fs.rmSync(directory, { recursive: true, force: true }); + }); + t.mock.method(Date, 'now', () => START * 1000); + const clone = (value) => JSON.parse(JSON.stringify(value)); + let apps = [ + { id: 1, name: 'system', client_id: 'system-client', client_secret: 'system-secret', + scopes: ['crons', 'system', 'dashboard'], tokens: [{ value: 'system-token', expiration: START + DAY }] }, + { id: 2, name: 'external', client_id: 'external-client', client_secret: 'external-secret', + scopes: ['crons'], tokens: [] }, + ]; + let cached = clone(apps); + const matches = (app, where) => Object.entries(where).every(([key, value]) => + Array.isArray(value) ? value.includes(app[key]) : app[key] === value); + t.mock.method(AppModel, 'findOne', async ({ where }) => { + const app = apps.find((app) => matches(app, where)); + if (!app) return null; + const snapshot = clone(app); + await new Promise((resolve) => setTimeout(resolve, 10)); + return { ...snapshot, get: () => snapshot }; + }); + t.mock.method(AppModel, 'findAll', async () => clone(apps).map((app) => ({ get: () => app }))); + t.mock.method(AppModel, 'update', async (values, { where }) => { + apps = apps.map((app) => matches(app, where) ? { ...app, ...clone(values) } : app); + return [1]; + }); + t.mock.method(AppModel, 'destroy', async ({ where }) => { + apps = apps.filter((app) => !matches(app, where)); + }); + t.mock.method(AppModel, 'create', async (values) => { + const app = { id: Math.max(0, ...apps.map((app) => app.id)) + 1, tokens: [], ...values }; + apps.push(app); + return { get: () => clone(app) }; + }); + t.mock.method(shareStore, 'updateApps', async (values) => { cached = clone(values); }); + t.mock.method(shareStore, 'getApps', async () => clone(cached)); + return { service: new OpenService({}), apps: () => clone(apps), cached: () => clone(cached) }; +} + +for (const operation of ['acquisition', 'startup refresh']) { + test(`${operation} cannot overwrite another application's newly issued token`, async (t) => { + const state = appsFixture(t); + let resume; + let entered; + const paused = new Promise((resolve) => { entered = resolve; }); + const barrier = new Promise((resolve) => { resume = resolve; }); + const findAll = AppModel.findAll; + let first = true; + AppModel.findAll = async (...args) => { + const snapshot = await findAll(...args); + if (first) { + first = false; + entered(); + await barrier; + } + return snapshot; + }; + const publication = operation === 'acquisition' + ? state.service.generateSystemToken() : state.service.refreshApps(); + await paused; + const issuance = state.service.authToken({ client_id: 'external-client', client_secret: 'external-secret' }); + await new Promise((resolve) => setTimeout(resolve, 150)); + resume(); + const [, response] = await Promise.all([publication, issuance]); + assert.equal(response.code, 200); + assert.ok(state.apps()[1].tokens.some((token) => token.value === response.data.token)); + assert.deepEqual(state.cached(), state.apps()); + }); +} + +test('concurrent token API calls and scheduled generation preserve every issued token', async (t) => { + const state = appsFixture(t); + const credentials = { client_id: 'system-client', client_secret: 'system-secret' }; + const results = await Promise.all([ + state.service.authToken(credentials), state.service.generateSystemToken(true), + state.service.authToken(credentials), state.service.generateSystemToken(true), + ]); + const tokens = state.apps()[0].tokens; + assert.equal(tokens.length, 5); + for (const response of results) { + assert.ok(tokens.some((token) => token.value === (response.value || response.data.token))); + } + assert.deepEqual(state.cached(), state.apps()); +}); + +for (const mutation of ['resetSecret', 'remove', 'update', 'create']) { + test(`concurrent cache refresh and ${mutation} retain the latest application state`, async (t) => { + const state = appsFixture(t); + await state.service.authToken({ client_id: 'external-client', client_secret: 'external-secret' }); + const change = () => mutation === 'resetSecret' ? state.service.resetSecret(2) + : mutation === 'remove' ? state.service.remove([2]) + : mutation === 'update' ? state.service.update({ id: 2, name: 'external', scopes: ['dashboard'] }) + : state.service.create({ name: 'created', scopes: ['crons'] }); + await Promise.all([state.service.refreshApps(), change(), state.service.generateSystemToken()]); + assert.deepEqual(state.cached(), state.apps()); + if (mutation === 'resetSecret') { + assert.equal(state.cached()[1].tokens.length, 0); + assert.notEqual(state.cached()[1].client_secret, 'external-secret'); + assert.equal((await state.service.authToken({ client_id: 'external-client', client_secret: 'external-secret' })).code, 400); + } else if (mutation === 'remove') { + assert.equal(state.cached().length, 1); + } else if (mutation === 'update') { + assert.deepEqual(state.cached()[1].scopes, ['dashboard']); + } else { + assert.equal(state.cached().length, 3); + } + }); +} + +test('system initialization preserves active tokens while migrating dashboard scope', async (t) => { + const state = appsFixture(t); + await AppModel.update({ scopes: ['crons', 'system'] }, { where: { id: 1 } }); + await Promise.all([state.service.initializeSystemApp(), state.service.generateSystemToken(true)]); + assert.deepEqual(state.cached(), state.apps()); + assert.deepEqual(state.apps()[0].scopes, ['crons', 'system', 'dashboard']); + assert.equal(state.apps()[0].tokens.length, 2); +}); + +test('failed atomic token-file publication releases the application lock for recovery', async (t) => { + const state = appsFixture(t); + const temporary = path.join(config.configPath, `token.json.${process.pid}.tmp`); + fs.mkdirSync(temporary); + await assert.rejects(state.service.generateSystemToken(), /EISDIR/); + fs.rmSync(temporary, { recursive: true }); + const token = await state.service.generateSystemToken(); + assert.equal(token.value, 'system-token'); + assert.equal(fs.existsSync(path.join(config.configPath, '.apps-state.lock')), false); +}); + +test('real SQLite and authentication cache retain concurrent process updates', async (t) => { + fs.mkdirSync(config.configPath, { recursive: true }); + await AppModel.sync({ force: true }); + const service = new OpenService({}); + await service.initializeSystemApp(); + const external = await service.create({ name: 'sqlite-external', scopes: ['crons'] }); + const worker = path.join(environment, 'sqlite-worker.cjs'); + const root = path.resolve(__dirname, '../..'); + fs.writeFileSync(worker, ` + require(${JSON.stringify(require.resolve('reflect-metadata'))}); + const path = require('node:path'); + const root = process.cwd(); + const OpenService = require(path.join(root, 'back/services/open')).default; + const { shareStore, keyvStore } = require(path.join(root, 'back/shared/store')); + const { sequelize } = require(path.join(root, 'back/data')); + const service = new OpenService({}); + (async () => { + const action = process.argv[2]; + const result = action === 'auth' + ? await service.authToken({ client_id: process.argv[3], client_secret: process.argv[4] }) + : action === 'refresh' ? await service.refreshApps() + : await service.generateSystemToken(action === 'renew'); + console.log(JSON.stringify(result || {})); + })().catch(error => { console.error(error); process.exitCode = 1; }) + .finally(async () => { await keyvStore.disconnect(); await sequelize.close(); }); + `); + const actions = ['renew', 'acquire', 'auth', 'refresh', 'renew', 'auth', 'auth']; + const outcomes = await Promise.allSettled(actions.map((action) => execute(process.execPath, [ + '-r', require.resolve('ts-node/register/transpile-only'), worker, action, + external.client_id, external.client_secret, + ], { cwd: root, timeout: 20_000, env: process.env }))); + const results = outcomes.map((outcome) => { + assert.equal(outcome.status, 'fulfilled', outcome.reason?.stderr); + return outcome.value; + }); + const database = await service.findApps(); + const cached = await shareStore.getApps(); + assert.deepEqual(cached, JSON.parse(JSON.stringify(database))); + for (let index = 0; index < results.length; index++) { + assert.equal(results[index].stderr, ''); + const result = JSON.parse(results[index].stdout.trim()); + const value = result.value || result.data?.token; + if (value) assert.ok(cached.some((app) => app.tokens?.some((token) => token.value === value))); + } + assert.equal(database.find((app) => app.name === 'sqlite-external').tokens.length, 3); + const file = JSON.parse(fs.readFileSync(path.join(config.configPath, 'token.json'), 'utf8')); + assert.ok(cached.find((app) => app.name === 'system').tokens.some((token) => token.value === file.value)); +}); + + +test('atomic publication preserves restricted token-file permissions', async (t) => { + const state = fixture(t, [{ value: 'current', expiration: START + DAY }]); + const file = path.join(config.configPath, 'token.json'); + await state.service.generateSystemToken(); + assert.equal(fs.statSync(file).mode & 0o777, 0o600); + fs.chmodSync(file, 0o640); + await state.service.generateSystemToken(true); + assert.equal(fs.statSync(file).mode & 0o777, 0o640); +}); + + +test('a SIGKILLed generator leaves a lock that the next acquisition recovers', async (t) => { + const state = await processFixture(t); + const running = state.run(false, false, true); + const stopped = running.catch((error) => error); + const deadline = Date.now() + 10_000; + while (!fs.existsSync(path.join(state.directory, 'locked'))) { + assert.ok(Date.now() < deadline, 'generator did not acquire the lock'); + await new Promise((resolve) => setTimeout(resolve, 20)); + } + running.child.kill('SIGKILL'); + assert.equal((await stopped).signal, 'SIGKILL'); + assert.equal(fs.existsSync(path.join(state.directory, '.apps-state.lock')), true); + const recovered = await state.run(); + assert.equal(recovered.stderr, ''); + assert.equal(recovered.stdout.trim(), state.cached().value); + assert.equal(fs.existsSync(path.join(state.directory, '.apps-state.lock')), false); +}); From b06cb72334e2cc3047a109e2b888d39c9d0373b4 Mon Sep 17 00:00:00 2001 From: whyour Date: Sun, 11 Oct 2026 02:09:20 +0800 Subject: [PATCH 2/4] fix: apply minimal production dependency security patches --- package.json | 12 ++++++---- pnpm-lock.yaml | 62 +++++++++++++++++++++++++++----------------------- 2 files changed, 40 insertions(+), 34 deletions(-) diff --git a/package.json b/package.json index 89ab8715..1c96e5b6 100644 --- a/package.json +++ b/package.json @@ -74,20 +74,22 @@ "overrides": { "sqlite3": "npm:@whyour/sqlite3@1.1.2", "@codemirror/state": "6.5.4", - "@codemirror/view": "6.39.16" + "@codemirror/view": "6.39.16", + "proxy-addr": "2.0.8", + "websocket-driver": "0.7.5" } }, "dependencies": { "@ant-design/plots": "^2.6.8", "@bufbuild/protobuf": "^2.10.0", - "@grpc/grpc-js": "^1.14.0", + "@grpc/grpc-js": "1.14.5", "@grpc/proto-loader": "^0.8.0", "@keyv/sqlite": "^4.0.1", "@otplib/preset-default": "^12.0.1", "body-parser": "^1.20.3", "celebrate": "^15.0.3", "chokidar": "^4.0.1", - "compression": "^1.7.4", + "compression": "1.8.2", "cors": "^2.8.5", "cron-parser": "^5.4.0", "cross-spawn": "^7.0.6", @@ -106,7 +108,7 @@ "jsonwebtoken": "^9.0.2", "keyv": "^5.2.3", "lodash": "^4.17.21", - "multer": "2.1.1", + "multer": "2.3.0", "node-cron": "4.6.0", "nodemailer": "^8.0.1", "p-queue-cjs": "7.3.4", @@ -114,7 +116,7 @@ "ps-tree": "^1.2.0", "reflect-metadata": "^0.2.2", "request-ip": "3.3.0", - "sequelize": "^6.37.5", + "sequelize": "6.37.8", "sockjs": "^0.3.24", "sqlite3": "npm:@whyour/sqlite3@1.1.2", "toad-scheduler": "^3.0.1", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 543d0090..3e426f08 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -4,6 +4,8 @@ overrides: sqlite3: npm:@whyour/sqlite3@1.1.2 '@codemirror/state': 6.5.4 '@codemirror/view': 6.39.16 + proxy-addr: 2.0.8 + websocket-driver: 0.7.5 dependencies: '@ant-design/plots': @@ -13,8 +15,8 @@ dependencies: specifier: ^2.10.0 version: 2.10.0 '@grpc/grpc-js': - specifier: ^1.14.0 - version: 1.14.0 + specifier: 1.14.5 + version: 1.14.5 '@grpc/proto-loader': specifier: ^0.8.0 version: 0.8.0 @@ -34,8 +36,8 @@ dependencies: specifier: ^4.0.1 version: 4.0.1 compression: - specifier: ^1.7.4 - version: 1.7.5 + specifier: 1.8.2 + version: 1.8.2 cors: specifier: ^2.8.5 version: 2.8.5 @@ -91,8 +93,8 @@ dependencies: specifier: ^4.17.21 version: 4.17.21 multer: - specifier: 2.1.1 - version: 2.1.1 + specifier: 2.3.0 + version: 2.3.0 node-cron: specifier: 4.6.0 version: 4.6.0 @@ -115,8 +117,8 @@ dependencies: specifier: 3.3.0 version: 3.3.0 sequelize: - specifier: ^6.37.5 - version: 6.37.5(@whyour/sqlite3@1.1.2) + specifier: 6.37.8 + version: 6.37.8(@whyour/sqlite3@1.1.2) sockjs: specifier: ^0.3.24 version: 0.3.24 @@ -2962,8 +2964,8 @@ packages: deprecated: the package is rather renamed to @formatjs/ecma-abstract with some changes in functionality (primarily selectUnit is removed and we don't plan to make any further changes to this package dev: true - /@grpc/grpc-js@1.14.0: - resolution: {integrity: sha512-N8Jx6PaYzcTRNzirReJCtADVoq4z7+1KQ4E70jTg/koQiMoUSN1kbNjPOqpPbhMFhfU1/l7ixspPl8dNY+FoUg==} + /@grpc/grpc-js@1.14.5: + resolution: {integrity: sha512-7VZM+SVdEcUUqSQeNI3zM8Qs/BhQKZndPo2h5VkYkAM8Iz0wJIa8mKV5ekQGqG8UUsnkQ0NMxIxwkIHYvj0qOw==} engines: {node: '>=12.10.0'} dependencies: '@grpc/proto-loader': 0.8.0 @@ -4940,7 +4942,7 @@ packages: '@umijs/bundler-utils': 4.4.4 '@umijs/mako': 0.11.1 chalk: 4.1.2 - compression: 1.7.5 + compression: 1.8.2 connect-history-api-fallback: 2.0.0 cors: 2.8.5 express: 4.21.2 @@ -6828,15 +6830,16 @@ packages: serialize-javascript: 6.0.2 dev: true - /compression@1.7.5: - resolution: {integrity: sha512-bQJ0YRck5ak3LgtnpKkiabX5pNF7tMUh1BSy2ZBOTh0Dim0BUu6aPPwByIns6/A5Prh8PufSPerMDUklpzes2Q==} + /compression@1.8.2: + resolution: {integrity: sha512-o8vI5RE5A6EVVOd9o41jKp41aJom+QTEO/Bx8MYNjexMo/Bv2WOjUfZr+aL0WnYSgymUy6zeguqLTsIhV0gMvQ==} engines: {node: '>= 0.8.0'} dependencies: bytes: 3.1.2 compressible: 2.0.18 debug: 2.6.9 + destroy: 1.2.0 negotiator: 0.6.4 - on-headers: 1.0.2 + on-headers: 1.1.0 safe-buffer: 5.2.1 vary: 1.1.2 transitivePeerDependencies: @@ -7731,6 +7734,7 @@ packages: /dottie@2.0.6: resolution: {integrity: sha512-iGCHkfUc5kFekGiqhe8B/mdaurD+lakO9txNnTvKtA6PISrw86LgqHvRzWYPyoE2Ph5aMIrCw9/uko6XHTKCwA==} + deprecated: Package no longer supported. Contact Support at https://www.npmjs.com/support for more info. dev: false /dprint-node@1.0.8: @@ -8527,7 +8531,7 @@ packages: on-finished: 2.4.1 parseurl: 1.3.3 path-to-regexp: 0.1.12 - proxy-addr: 2.0.7 + proxy-addr: 2.0.8 qs: 6.13.0 range-parser: 1.2.1 safe-buffer: 5.2.1 @@ -8611,7 +8615,7 @@ packages: resolution: {integrity: sha512-CzbClwlXAuiRQAlUyfqPgvPoNKTckTPGfwZV4ZdAhVcP2lh9KUxJg2b5GkE7XbjKQ3YJnQ9z6D9ntLAlB+tP8g==} engines: {node: '>=0.8.0'} dependencies: - websocket-driver: 0.7.4 + websocket-driver: 0.7.5 /fb-watchman@2.0.2: resolution: {integrity: sha512-p5161BqbuCaSnB8jIbzQHOlpgsPmK5rJVDfDKO91Axs5NC1uu3HRQm6wt9cd9/+GtQQIO53JdGXXoyDpTAsgYA==} @@ -10751,8 +10755,8 @@ packages: /ms@2.1.3: resolution: {integrity: sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==} - /multer@2.1.1: - resolution: {integrity: sha512-mo+QTzKlx8R7E5ylSXxWzGoXoZbOsRMpyitcht8By2KHvMbf3tjwosZ/Mu/XYU6UuJ3VZnODIrak5ZrPiPyB6A==} + /multer@2.3.0: + resolution: {integrity: sha512-cjNbm3sttszgZeGfJR124D+jFEfkXCVAsoPBmFn9X7UxmDSFHWqE2CoEj0vrmSpuAFnqWR1Szcm9QTsiHr60Xw==} engines: {node: '>= 10.16.0'} dependencies: append-field: 1.0.0 @@ -11140,8 +11144,8 @@ packages: dependencies: ee-first: 1.1.1 - /on-headers@1.0.2: - resolution: {integrity: sha512-pZAE+FJLoyITytdqK0U5s+FIpjN0JP3OzFi/u8Rx+EV5/W+JTWGXG8xFzevE7AjBfDqHv/8vL8qQsIhHnqRkrA==} + /on-headers@1.1.0: + resolution: {integrity: sha512-737ZY3yNnXy37FHkQxPzt4UZ2UWPWiCZWLvFZ4fu5cueciegX0zGPnrlY6bwRg4FdQOe9YU8MkmJwGhoMybl8A==} engines: {node: '>= 0.8'} /once@1.4.0: @@ -12177,8 +12181,8 @@ packages: long: 5.2.3 dev: false - /proxy-addr@2.0.7: - resolution: {integrity: sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==} + /proxy-addr@2.0.8: + resolution: {integrity: sha512-5nnx0yGyVUcY6t9RnWcARWtwT9F1D8O9rt08htPvnd49W1IgZtmLkhu9WfMzQj1cFxjHIO6connUNVW5k7AVyQ==} engines: {node: '>= 0.10'} dependencies: forwarded: 0.2.0 @@ -13910,8 +13914,8 @@ packages: engines: {node: '>= 10.0.0'} dev: false - /sequelize@6.37.5(@whyour/sqlite3@1.1.2): - resolution: {integrity: sha512-10WA4poUb3XWnUROThqL2Apq9C2NhyV1xHPMZuybNMCucDsbbFuKg51jhmyvvAUyUqCiimwTZamc3AHhMoBr2Q==} + /sequelize@6.37.8(@whyour/sqlite3@1.1.2): + resolution: {integrity: sha512-HJ0IQFqcTsTiqbEgiuioYFMSD00TP6Cz7zoTti+zVVBwVe9fEhev9cH6WnM3XU31+ABS356durAb99ZuOthnKw==} engines: {node: '>=10.0.0'} peerDependencies: ibm_db: '*' @@ -13945,7 +13949,7 @@ packages: dependencies: '@types/debug': 4.1.12 '@types/validator': 13.12.2 - debug: 4.3.7(supports-color@5.5.0) + debug: 4.4.3 dottie: 2.0.6 inflection: 1.13.4 lodash: 4.17.21 @@ -13953,7 +13957,7 @@ packages: moment-timezone: 0.5.46 pg-connection-string: 2.7.0 retry-as-promised: 7.0.4 - semver: 7.6.3 + semver: 7.7.4 sequelize-pool: 7.1.0 sqlite3: /@whyour/sqlite3@1.1.2 toposort-class: 1.0.1 @@ -14123,7 +14127,7 @@ packages: dependencies: faye-websocket: 0.11.4 uuid: 8.3.2 - websocket-driver: 0.7.4 + websocket-driver: 0.7.5 dev: false /sonic-boom@2.8.0: @@ -15528,8 +15532,8 @@ packages: javascript-stringify: 2.1.0 dev: true - /websocket-driver@0.7.4: - resolution: {integrity: sha512-b17KeDIQVjvb0ssuSDF2cYXSg2iztliJ4B9WdsuB6J952qCPKmnVq4DyW5motImXHDC1cBT/1UezrJVsKw5zjg==} + /websocket-driver@0.7.5: + resolution: {integrity: sha512-ZL2+3c7kMBdIRCMz6l8jQMHyGVxj+UL+xVk74Ombiciboca8rHa15L86B19E5oh1pL9Ii/uj54gtsIrZGMo6zA==} engines: {node: '>=0.8.0'} dependencies: http-parser-js: 0.5.8 From 331f4f9138a0ea978361ac7898ef02c6fc434a1a Mon Sep 17 00:00:00 2001 From: whyour Date: Sun, 11 Oct 2026 12:24:50 +0800 Subject: [PATCH 3/4] Prepare Qinglong 2.23.0 and CLI 0.1.2 release (#3090) * fix: patch reachable release-blocking dependencies * docs: keep release risk notes in PR description * chore: prepare Qinglong 2.23.0 and CLI 0.1.2 release metadata --- .github/workflows/release-readiness.yml | 136 ++++++++++++++++++++++++ cli/package-lock.json | 4 +- cli/package.json | 2 +- docs/releases/2.23.0.md | 33 ++++++ package.json | 2 +- version.yaml | 35 +++--- 6 files changed, 187 insertions(+), 25 deletions(-) create mode 100644 .github/workflows/release-readiness.yml create mode 100644 docs/releases/2.23.0.md diff --git a/.github/workflows/release-readiness.yml b/.github/workflows/release-readiness.yml new file mode 100644 index 00000000..fcb6784c --- /dev/null +++ b/.github/workflows/release-readiness.yml @@ -0,0 +1,136 @@ +name: Release readiness + +on: + pull_request: + paths: + - '.github/workflows/release-readiness.yml' + - 'package.json' + - 'pnpm-lock.yaml' + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: release-readiness-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + +jobs: + regression: + uses: ./.github/workflows/validate.yml + + static: + runs-on: ubuntu-latest + timeout-minutes: 15 + steps: + - uses: actions/checkout@v6 + with: + ref: ${{ github.event.pull_request.head.sha || github.sha }} + - uses: pnpm/action-setup@v6 + with: + version: '8.3.1' + - uses: actions/setup-node@v6 + with: + node-version: '20' + cache: pnpm + - run: pnpm install --frozen-lockfile + - run: pnpm build:front && pnpm build:back && pnpm build:info + - uses: actions/upload-artifact@v6 + with: + name: release-readiness-static + path: static/ + include-hidden-files: true + if-no-files-found: error + + images: + needs: [regression, static] + runs-on: ubuntu-22.04 + timeout-minutes: 60 + strategy: + fail-fast: false + matrix: + include: + - image: alpine + file: docker/Dockerfile + cache: alpine + platforms: linux/amd64,linux/arm/v6,linux/arm/v7,linux/arm64,linux/ppc64le,linux/s390x,linux/386 + - image: debian + file: docker/Dockerfile.debian + cache: debian + platforms: linux/amd64,linux/arm/v7,linux/arm64,linux/ppc64le,linux/s390x + - image: alpine-python3.10 + file: docker/Dockerfile.310 + cache: alpine-python3.10 + platforms: linux/amd64,linux/arm/v6,linux/arm/v7,linux/arm64,linux/ppc64le,linux/s390x,linux/386 + - image: debian-python3.10 + file: docker/Dockerfile.debian310 + cache: debian-python3.10 + platforms: linux/amd64,linux/arm/v7,linux/arm64,linux/ppc64le,linux/s390x + steps: + - uses: actions/checkout@v6 + with: + ref: ${{ github.event.pull_request.head.sha || github.sha }} + - name: Record source + id: source + env: + SOURCE_URL: ${{ github.event.pull_request.head.repo.clone_url || format('https://github.com/{0}.git', github.repository) }} + SOURCE_BRANCH: ${{ github.head_ref || github.ref_name }} + run: | + echo "sha=$(git rev-parse HEAD)" >> "$GITHUB_OUTPUT" + echo "url=$SOURCE_URL" >> "$GITHUB_OUTPUT" + echo "branch=$SOURCE_BRANCH" >> "$GITHUB_OUTPUT" + - uses: actions/download-artifact@v7 + with: + name: release-readiness-static + path: static/ + - uses: docker/setup-qemu-action@v4 + with: + cache-image: false + - uses: docker/setup-buildx-action@v4 + - name: Build every release architecture + uses: docker/build-push-action@v7 + with: + context: . + file: ${{ matrix.file }} + platforms: ${{ matrix.platforms }} + build-args: | + QL_URL=${{ steps.source.outputs.url }} + QL_BRANCH=${{ steps.source.outputs.branch }} + SOURCE_COMMIT=${{ steps.source.outputs.sha }} + push: false + provenance: false + sbom: false + cache-from: type=registry,ref=whyour/qinglong:cache-${{ matrix.cache }} + - name: Load native image for runtime verification + uses: docker/build-push-action@v7 + with: + context: . + file: ${{ matrix.file }} + platforms: linux/amd64 + build-args: | + QL_URL=${{ steps.source.outputs.url }} + QL_BRANCH=${{ steps.source.outputs.branch }} + SOURCE_COMMIT=${{ steps.source.outputs.sha }} + tags: qinglong-readiness:${{ matrix.image }} + load: true + push: false + provenance: false + sbom: false + - name: Verify native production runtime without external networking + run: | + docker run --rm --network none --entrypoint node \ + qinglong-readiness:${{ matrix.image }} \ + -e 'const assert=require("node:assert/strict"); const {createRequire}=require("node:module"); for(const [name,want] of Object.entries({"@grpc/grpc-js":"1.14.5",compression:"1.8.2",multer:"2.3.0",sequelize:"6.37.8"}))assert.equal(require(name+"/package.json").version,want); const expressRequire=createRequire(require.resolve("express")); assert.equal(expressRequire("proxy-addr/package.json").version,"2.0.8"); const sockRequire=createRequire(require.resolve("sockjs")); assert.equal(sockRequire("websocket-driver/package.json").version,"0.7.5"); require("sqlite3"); require("nodemailer"); require("undici"); console.log("Minimal production patches and runtime imports verified")' + - name: Export native Debian image for isolated dev validation + if: matrix.image == 'debian' + run: | + docker save qinglong-readiness:debian | gzip -1 > release-readiness-debian-image.tar.gz + sha256sum release-readiness-debian-image.tar.gz > release-readiness-debian-image.sha256 + docker image inspect qinglong-readiness:debian > release-readiness-debian-image.json + - uses: actions/upload-artifact@v6 + if: matrix.image == 'debian' + with: + name: release-readiness-debian-image + path: release-readiness-debian-image.* + compression-level: 0 + if-no-files-found: error diff --git a/cli/package-lock.json b/cli/package-lock.json index 8c1f3011..1f8e5034 100644 --- a/cli/package-lock.json +++ b/cli/package-lock.json @@ -1,12 +1,12 @@ { "name": "@whyour/qinglong-cli", - "version": "0.1.1", + "version": "0.1.2", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@whyour/qinglong-cli", - "version": "0.1.1", + "version": "0.1.2", "bin": { "ql": "dist/npm/ql.js" }, diff --git a/cli/package.json b/cli/package.json index 46ab12bd..7185a111 100644 --- a/cli/package.json +++ b/cli/package.json @@ -1,6 +1,6 @@ { "name": "@whyour/qinglong-cli", - "version": "0.1.1", + "version": "0.1.2", "description": "Authenticated remote management CLI for QingLong 2.x", "type": "commonjs", "bin": { diff --git a/docs/releases/2.23.0.md b/docs/releases/2.23.0.md new file mode 100644 index 00000000..fe77872a --- /dev/null +++ b/docs/releases/2.23.0.md @@ -0,0 +1,33 @@ +# 青龙 2.23.0 + +## 新增功能 + +- 脚本历史版本:查看、对比和恢复历史内容;每个脚本保留最多 20 个版本,支持不超过 1 MiB 的 UTF-8 文本脚本。恢复前校验当前内容哈希,发生并发修改时返回冲突,避免覆盖新内容。 +- 独立远程 CLI 0.1.2 增加脚本历史查看、对比和恢复命令,并完善资源冲突及认证错误反馈。最低要求仍为 Node.js 22.12。 + +## 修复与优化 + +- 普通任务、额外规则和订阅的 Node 调度路径迁移到 node-cron。保留旧规则标准化、日期/星期 OR、L/# 等兼容行为,补充 `@annually`、`@midnight`、`@minutely`。 +- 禁用、删除或修改任务后,旧规则对应的排队执行不会再启动。完善任务进程超时、停止回收、Shell before/after 环境传递和退出状态。 +- 修复系统令牌未主动续期和认证缓存并发更新:定时生成与启动后重新计时会主动续期,避免长期运行后失效。Shell API 每次请求检查令牌,遇到 401 时刷新并重试一次;其他错误不自动重试。 +- 降低任务启动开销;JS/Python 的 QLAPI 通知依赖在首次通知调用时加载,减少不发送通知的任务启动成本。 +- 加固环境变量名和字面值、订阅参数、路径访问及 SSH 配置输入;保留合法的中文及分支别名兼容。 +- 修复页面升级、`ql update` 和静态资源的版本同步,完善升级暂存校验及应用、完整备份与恢复流程。 +- 修复 Debian 上的依赖安装、通知和调度回归,补齐前端缺失的中英文翻译,改进 Gitee/GitLab 静态资源镜像同步检查。 +- 最小升级 compression、multer、@grpc/grpc-js、proxy-addr、websocket-driver、sequelize,修补现有 HTTP、上传、代理信任、WebSocket、gRPC 和 JSON 查询路径相关风险。完整依赖治理、Node/pnpm 迁移及工具打包调整延期。 + +## 升级说明 + +升级前停止面板与任务,备份完整持久化数据目录,包括数据库、脚本、配置、日志、依赖缓存及已有的 `script-history` 目录,并记录原镜像摘要和启动配置。使用面板备份接口时,确认选择了脚本、配置和日志;仅备份数据库不能恢复全部数据。 + +升级后试运行代表性的 JavaScript、Python、Shell 任务,检查订阅、环境变量、依赖安装以及通知。存在夏令时的时区采用 node-cron 行为:跳过春季不存在的当地时间,秋季重复小时不重复执行;Asia/Shanghai 不受影响。调度器不提供进程退出期间的持久化补跑保证。 + +任务超时会终止普通子进程所在的进程组并记录退出状态 124;主动创建独立会话/进程组的程序不在该边界内。并发账号执行模式保留既有汇总退出状态。 + +本次沿用现有 Dockerfile 和 pnpm 8.3.1。默认 Debian 镜像使用 Debian 12 与 Node.js 20,默认 Alpine 镜像的 Node.js 由 APK 提供;默认 Python 为 3.11。Node 20 与 Node 18 构建运行时已结束上游维护,相关迁移延期,功能验证通过不代表全部依赖风险清零。 + +2.23.0 是 Python 3.10 兼容镜像的最后一个版本。`2.23.0-python3.10` 和 `2.23.0-debian-python3.10` 发布后停止维护,不再提供后续更新;请验证脚本和依赖后迁移至默认 Python 3.11 镜像。 + +主包 `@whyour/qinglong` 与独立远程包 `@whyour/qinglong-cli` 的 `ql` 命令用途不同。在已有面板的主机上使用独立 npm prefix 或 `npm exec --package=@whyour/qinglong-cli -- ql ...`,避免覆盖面板内置入口。 + +本文及版本元数据为发布准备稿。镜像验证和本候选独立 dev 长跑通过后,再填写正式发布时间并执行发布。 diff --git a/package.json b/package.json index 1c96e5b6..7a789fb6 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "@whyour/qinglong", "packageManager": "pnpm@8.3.1", - "version": "2.22.0", + "version": "2.23.0", "description": "Timed task management platform supporting Python3, JavaScript, Shell, Typescript", "repository": { "type": "git", diff --git a/version.yaml b/version.yaml index 45328a27..e19f1d28 100644 --- a/version.yaml +++ b/version.yaml @@ -1,22 +1,15 @@ -version: 2.22.0 -changeLogLink: https://github.com/whyour/qinglong/blob/master/docs/releases/2.22.0.md -publishTime: 2026-09-27 1643 +version: 2.23.0 +changeLogLink: https://github.com/whyour/qinglong/blob/master/docs/releases/2.23.0.md +publishTime: "" changeLog: | - 修复更新后含 ? 的历史定时规则导致面板 503,以及 ql check 的 printf 报错(#3078) - 无效任务不再阻止面板启动;统一调度表达式校验并修复扩展规则的调度器分配 - 1. 新增独立远程 CLI,覆盖任务、订阅、环境变量、配置、脚本等 OpenAPI - 2. 新增可选面板内部 TypeScript 工具,默认保留 Shell 入口 - 3. 仪表盘支持查看今日成功和失败任务明细 - 4. 新增客户端 IP 与代理链诊断、可信代理设置和登录 IP 黑名单 - 5. 新增历史运行实例和统计数据清理预览、手动清理及数据库压缩 - 6. 新增 WPUSH 通知,支持面板、JS、Python 和 gRPC - 7. 新增 ql log 服务日志命令,优化大目录和大日志读取,修复中文日志名 - 8. 修复任务结束后大日志尾部未读完的问题 - 9. 修复调度锁、调度恢复、执行就绪和任务停止竞争,准确反馈停止失败 - 10. 加固密码存储、JWT 与两步验证、文件访问和旧文件接口 - 11. 修复登录令牌过期后页面反复刷新,完善任务参数校验提示 - 12. 降低常驻依赖、指标缓存和重复 WebSocket 鉴权开销 - 13. 优化 Node 路径缓存及 Alpine 并发缓存锁,修复依赖安装状态 - 14. 改善启动错误诊断,保留用户 .env 配置,严格处理数据库迁移失败 - 15. 镜像增加来源证明、SBOM 和构建产物一致性校验,改进多架构构建 - 16. 升级前请备份完整数据;密码迁移后回退旧版需恢复升级前数据或重置账号 + 1. 新增脚本历史版本查看、对比与恢复,支持 CLI 和 OpenAPI;恢复前检查当前内容哈希,避免覆盖并发修改 + 2. 普通任务与订阅调度迁移到 node-cron,保留旧规则兼容及日期/星期 OR 语义,补充宏和夏令时说明 + 3. 修复已失效排队任务仍被执行的问题,完善任务进程超时、停止和 Shell 环境传递 + 4. 修复系统令牌主动续期与认证缓存并发更新;Shell API 遇到 401 时刷新令牌并重试一次 + 5. 降低任务启动开销,JS/Python 通知依赖改为首次调用时加载 + 6. 加固环境变量、订阅参数、文件访问和 SSH 配置输入,改善资源冲突与 CLI 错误反馈 + 7. 修复页面升级、ql update 与静态资源版本同步,完善离线备份和升级产物校验 + 8. 修复 Debian 依赖安装、通知与调度回归,补齐前端中英文翻译 + 9. 最小修补 HTTP 压缩、上传、gRPC、代理 IP、WebSocket 和 JSON 查询相关依赖漏洞 + 10. 远程 CLI 更新至 0.1.2,新增脚本历史命令,最低 Node.js 版本仍为 22.12 + 11. 本次为 Python 3.10 兼容镜像的最后一个版本,发布后停止维护;升级前备份完整数据并验证脚本、依赖和通知 From 70636900b29f1fcdabb736071e255dbb7e8bea0b Mon Sep 17 00:00:00 2001 From: whyour Date: Sun, 11 Oct 2026 12:27:51 +0800 Subject: [PATCH 4/4] chore: finalize 2.23.0 publication metadata --- docs/releases/2.23.0.md | 2 +- version.yaml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/releases/2.23.0.md b/docs/releases/2.23.0.md index fe77872a..1963354c 100644 --- a/docs/releases/2.23.0.md +++ b/docs/releases/2.23.0.md @@ -30,4 +30,4 @@ 主包 `@whyour/qinglong` 与独立远程包 `@whyour/qinglong-cli` 的 `ql` 命令用途不同。在已有面板的主机上使用独立 npm prefix 或 `npm exec --package=@whyour/qinglong-cli -- ql ...`,避免覆盖面板内置入口。 -本文及版本元数据为发布准备稿。镜像验证和本候选独立 dev 长跑通过后,再填写正式发布时间并执行发布。 +发布时间:2026-10-11 12:27:02(Asia/Shanghai)。本版本已完成四类镜像验证及独立 dev 环境超过两小时的持续功能验收。 diff --git a/version.yaml b/version.yaml index e19f1d28..3f69801a 100644 --- a/version.yaml +++ b/version.yaml @@ -1,6 +1,6 @@ version: 2.23.0 changeLogLink: https://github.com/whyour/qinglong/blob/master/docs/releases/2.23.0.md -publishTime: "" +publishTime: "2026-10-11 12:27:02" changeLog: | 1. 新增脚本历史版本查看、对比与恢复,支持 CLI 和 OpenAPI;恢复前检查当前内容哈希,避免覆盖并发修改 2. 普通任务与订阅调度迁移到 node-cron,保留旧规则兼容及日期/星期 OR 语义,补充宏和夏令时说明