Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3ab3e5e180 | ||
|
|
6c96cddd4e | ||
|
|
efbd0e0d87 | ||
|
|
ed0b492461 | ||
|
|
a080f531cd | ||
|
|
1e87f25c2b | ||
|
|
4c71861813 | ||
|
|
3a9f809f46 | ||
|
|
de45c4b20c | ||
|
|
cc9e897260 | ||
|
|
620362823b | ||
|
|
fa2fd94579 | ||
|
|
05a679c2c8 | ||
|
|
23e2f9c5e7 | ||
|
|
484881b410 |
@@ -31,6 +31,8 @@ TALLYNOTE_INSTALL_PREFIX=./
|
||||
TALLYNOTE_UPDATE_METADATA_URL=https://git.awaioi.com/api/v1/repos/awaioi/TallyNote/releases/latest
|
||||
TALLYNOTE_UPDATE_ALLOWED_HOSTS=git.awaioi.com
|
||||
TALLYNOTE_UPDATE_MAX_MB=512
|
||||
# Per-request timeout for update metadata, checksums, signatures, and archives.
|
||||
TALLYNOTE_UPDATE_TIMEOUT_SECONDS=30
|
||||
# SHA-256 is always required. Detached Ed25519 signatures are optional; set
|
||||
# this to true only when a root-managed public key is configured below.
|
||||
TALLYNOTE_UPDATE_REQUIRE_SIGNATURE=false
|
||||
|
||||
@@ -30,7 +30,9 @@ jobs:
|
||||
- name: Verify tag and test gate
|
||||
run: |
|
||||
set -euo pipefail
|
||||
test "$(node -p 'require("./package.json").version')" = "${GITHUB_REF_NAME#v}"
|
||||
target_version="${GITHUB_REF_NAME#v}"
|
||||
package_version="$(node -p 'require("./package.json").version')"
|
||||
test "$package_version" = "$target_version"
|
||||
pnpm install --frozen-lockfile
|
||||
pnpm check
|
||||
# better-sqlite3 is a native addon; a single Vitest worker avoids a
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "tallynote",
|
||||
"version": "1.1.38",
|
||||
"version": "1.2.7",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"packageManager": "pnpm@9.0.6",
|
||||
|
||||
@@ -13,6 +13,8 @@ if [[ -z "$VERSION" ]]; then
|
||||
fi
|
||||
VERSION=${VERSION#v}
|
||||
[[ "$VERSION" =~ ^[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*)?(\+[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*)?$ ]] || { printf 'invalid version: %s\n' "$VERSION" >&2; exit 2; }
|
||||
PACKAGE_VERSION=$(node -p 'require("./package.json").version')
|
||||
[[ "$VERSION" == "$PACKAGE_VERSION" ]] || { printf 'version mismatch: release %s does not match package.json %s\n' "$VERSION" "$PACKAGE_VERSION" >&2; exit 2; }
|
||||
case "$(uname -m)" in
|
||||
x86_64|amd64) ARCH=x64 ;;
|
||||
aarch64|arm64) ARCH=arm64 ;;
|
||||
@@ -51,25 +53,8 @@ mkdir -p "$OUT_DIR"
|
||||
archive="$OUT_DIR/tallynote-${VERSION}-linux-${ARCH}-${LIBC}.tar.gz"
|
||||
tar -C "$stage" -czf "$archive" --owner=0 --group=0 --numeric-owner .
|
||||
|
||||
# The application-only asset is used by the online updater. It deliberately
|
||||
# excludes the stable runtime (Node and production dependencies), systemd
|
||||
# helpers and installer files; the updater overlays it on the currently
|
||||
# installed, already-validated runtime before atomically switching releases.
|
||||
app_stage=$(mktemp -d)
|
||||
trap 'rm -rf "$stage" "$app_stage"' EXIT
|
||||
mkdir -p "$app_stage/dist" "$app_stage/migrations" "$app_stage/bin" "$app_stage/scripts" "$app_stage/systemd"
|
||||
cp -a "$stage/dist/server" "$app_stage/dist/"
|
||||
cp -a "$stage/dist/shared" "$app_stage/dist/"
|
||||
cp -a "$stage/dist/web" "$app_stage/dist/"
|
||||
cp -a "$stage/migrations/." "$app_stage/migrations/"
|
||||
cp -a "$stage/bin/." "$app_stage/bin/"
|
||||
cp -a "$stage/scripts/." "$app_stage/scripts/"
|
||||
cp -a "$stage/systemd/." "$app_stage/systemd/"
|
||||
cp "$stage/package.json" "$app_stage/package.json"
|
||||
cp "$stage/uninstall.sh" "$app_stage/uninstall.sh"
|
||||
runtime_hash=$(sha256sum pnpm-lock.yaml | awk '{print $1}')
|
||||
app_archive="$OUT_DIR/tallynote-${VERSION}-linux-${ARCH}-${LIBC}.update-${runtime_hash}.tar.gz"
|
||||
tar -C "$app_stage" -czf "$app_archive" --owner=0 --group=0 --numeric-owner .
|
||||
# Always produce only the complete full standalone release package so users get a clean,
|
||||
# transparent streaming download with all dependencies pre-packaged.
|
||||
# Keep the sidecar useful when a caller builds more than one architecture into
|
||||
# the same directory. The publishing script recomputes this list immediately
|
||||
# before signing, so stale or hand-edited entries can never reach a Release.
|
||||
|
||||
@@ -10,6 +10,8 @@ DATA_DIR=${TALLYNOTE_DATA_DIR:-/var/lib/tallynote}
|
||||
REQUEST_FILE="$DATA_DIR/update-request.json"
|
||||
CURRENT_LINK="$PREFIX/current"
|
||||
STATE_FILE="$PREFIX/.update-state"
|
||||
LOCK_FILE="$PREFIX/.update-runner.lock"
|
||||
RUNNER_LOG="$PREFIX/.update-runner.log"
|
||||
SERVICE_NAME=${TALLYNOTE_SERVICE_NAME:-tallynote.service}
|
||||
HOST=${TALLYNOTE_HOST:-127.0.0.1}
|
||||
PORT=${TALLYNOTE_PORT:-3000}
|
||||
@@ -19,13 +21,72 @@ if [[ "$HEALTH_HOST" == :: ]]; then HEALTH_HOST=::1; fi
|
||||
if [[ "$HEALTH_HOST" == *:* && "$HEALTH_HOST" != \[* ]]; then HEALTH_HOST="[$HEALTH_HOST]"; fi
|
||||
|
||||
die() { printf 'tallynote update runner: %s\n' "$*" >&2; exit 1; }
|
||||
|
||||
# The runner may exit during any of the checks below. Install its EXIT cleanup
|
||||
# before doing privileged preflight so a partial invocation never leaves a
|
||||
# heartbeat or lock behind.
|
||||
STATE_CREATED=0
|
||||
heartbeat_pid=''
|
||||
heartbeat_owner=$$
|
||||
RUNNER_LOCK_FD=9
|
||||
RUNNER_LOCK_MODE=''
|
||||
stop_heartbeat() {
|
||||
if [[ -n "$heartbeat_pid" ]]; then
|
||||
kill "$heartbeat_pid" 2>/dev/null || true
|
||||
wait "$heartbeat_pid" 2>/dev/null || true
|
||||
heartbeat_pid=''
|
||||
fi
|
||||
}
|
||||
# shellcheck disable=SC2329 # invoked indirectly by the EXIT trap
|
||||
release_runner_lock() {
|
||||
if [[ "$RUNNER_LOCK_MODE" == flock ]]; then
|
||||
flock -u "$RUNNER_LOCK_FD" 2>/dev/null || true
|
||||
eval "exec ${RUNNER_LOCK_FD}>&-" 2>/dev/null || true
|
||||
elif [[ "$RUNNER_LOCK_MODE" == mkdir ]]; then
|
||||
rmdir -- "$LOCK_FILE.d" 2>/dev/null || true
|
||||
fi
|
||||
}
|
||||
# shellcheck disable=SC2329 # invoked indirectly by the EXIT trap
|
||||
early_cleanup() {
|
||||
local result=$?
|
||||
stop_heartbeat
|
||||
if (( result != 0 )); then
|
||||
# A preflight failure happens before the normal phase-specific trap is
|
||||
# installed. Remove only the one-shot request marker; never remove an
|
||||
# existing recovery marker unless this invocation created it.
|
||||
rm -f -- "$REQUEST_FILE" 2>/dev/null || true
|
||||
if (( STATE_CREATED == 1 )); then rm -f -- "$STATE_FILE" 2>/dev/null || true; fi
|
||||
fi
|
||||
release_runner_lock
|
||||
return "$result"
|
||||
}
|
||||
trap early_cleanup EXIT
|
||||
|
||||
[[ ${EUID:-$(id -u)} -eq 0 ]] || die 'must run as root'
|
||||
[[ -d "$PREFIX" ]] || die 'install prefix is missing'
|
||||
if command -v flock >/dev/null 2>&1; then
|
||||
exec 9>"$LOCK_FILE" || die '无法打开更新运行锁'
|
||||
flock -n "$RUNNER_LOCK_FD" || exit 0
|
||||
RUNNER_LOCK_MODE=flock
|
||||
else
|
||||
# macOS development fixtures do not ship util-linux; retain an atomic lock
|
||||
# fallback there while Linux production uses flock above.
|
||||
mkdir "$LOCK_FILE.d" 2>/dev/null || exit 0
|
||||
RUNNER_LOCK_MODE='mkdir'
|
||||
fi
|
||||
[[ -f "$REQUEST_FILE" || -f "$STATE_FILE" ]] || exit 0
|
||||
[[ -L "$CURRENT_LINK" ]] || die 'current release link is missing'
|
||||
|
||||
old_target=$(readlink -f -- "$CURRENT_LINK")
|
||||
[[ "$old_target" == "$PREFIX/releases/"* && -d "$old_target" ]] || die 'current release target is invalid'
|
||||
|
||||
# Capture the service state before any download/apply work. The value is
|
||||
# persisted in the recovery marker so a later runner process can restore the
|
||||
# operator's original state after a crash (the service is normally inactive by
|
||||
# the time recovery starts).
|
||||
was_active=0
|
||||
if systemctl is-active --quiet "$SERVICE_NAME"; then was_active=1; fi
|
||||
|
||||
request_operation='apply'
|
||||
if [[ -f "$REQUEST_FILE" && ! -L "$REQUEST_FILE" ]]; then
|
||||
request_operation=$(sed -n 's/.*"operation"[[:space:]]*:[[:space:]]*"\(download\|apply\)".*/\1/p' "$REQUEST_FILE" | head -n 1)
|
||||
@@ -39,15 +100,11 @@ job_id=''
|
||||
if [[ -f "$REQUEST_FILE" && ! -L "$REQUEST_FILE" ]]; then
|
||||
job_id=$(sed -n 's/.*"jobId"[[:space:]]*:[[:space:]]*"\([0-9a-f-]*\)".*/\1/p' "$REQUEST_FILE" | head -n 1)
|
||||
fi
|
||||
STATE_CREATED=0
|
||||
heartbeat_pid=''
|
||||
heartbeat_owner=$$
|
||||
|
||||
write_recovery_state() {
|
||||
local phase=$1 temporary
|
||||
temporary="$PREFIX/.update-state-$$-${RANDOM}.tmp"
|
||||
[[ ! -e "$temporary" && ! -L "$temporary" ]] || return 1
|
||||
printf 'job_id=%s\nold_target=%s\nphase=%s\n' "$job_id" "$old_target" "$phase" > "$temporary"
|
||||
printf 'job_id=%s\nold_target=%s\nphase=%s\ninitial_active=%s\n' "$job_id" "$old_target" "$phase" "$was_active" > "$temporary"
|
||||
chmod 600 "$temporary"
|
||||
mv -Tf -- "$temporary" "$STATE_FILE"
|
||||
STATE_CREATED=1
|
||||
@@ -59,14 +116,6 @@ clear_recovery_state() {
|
||||
STATE_CREATED=0
|
||||
}
|
||||
|
||||
stop_heartbeat() {
|
||||
if [[ -n "$heartbeat_pid" ]]; then
|
||||
kill "$heartbeat_pid" 2>/dev/null || true
|
||||
wait "$heartbeat_pid" 2>/dev/null || true
|
||||
heartbeat_pid=''
|
||||
fi
|
||||
}
|
||||
|
||||
heartbeat() {
|
||||
# Keep the lease fresh during long downloads/backups, but stop on a hard
|
||||
# runner kill so an orphaned child cannot keep the recovery marker alive.
|
||||
@@ -86,9 +135,11 @@ start_heartbeat() {
|
||||
# This trap covers failures before the normal apply cleanup trap is installed,
|
||||
# including a missing runtime, an invalid current link, and a failed service
|
||||
# stop. It deliberately does not remove a pre-existing recovery marker.
|
||||
# shellcheck disable=SC2329 # invoked indirectly by the EXIT trap
|
||||
preflight_cleanup() {
|
||||
local result=$?
|
||||
stop_heartbeat
|
||||
release_runner_lock
|
||||
if (( result != 0 )); then
|
||||
rm -f -- "$REQUEST_FILE" 2>/dev/null || true
|
||||
if (( STATE_CREATED == 1 )); then clear_recovery_state || true; fi
|
||||
@@ -97,6 +148,33 @@ preflight_cleanup() {
|
||||
}
|
||||
trap preflight_cleanup EXIT
|
||||
|
||||
DOWNLOAD_TIMEOUT_SECONDS=${TALLYNOTE_UPDATE_DOWNLOAD_TIMEOUT_SECONDS:-${TALLYNOTE_UPDATE_RUNNER_DOWNLOAD_TIMEOUT_SECONDS:-1800}}
|
||||
APPLY_TIMEOUT_SECONDS=${TALLYNOTE_UPDATE_APPLY_TIMEOUT_SECONDS:-${TALLYNOTE_UPDATE_RUNNER_APPLY_TIMEOUT_SECONDS:-1800}}
|
||||
FINALIZE_TIMEOUT_SECONDS=${TALLYNOTE_UPDATE_FINALIZE_TIMEOUT_SECONDS:-${TALLYNOTE_UPDATE_RUNNER_FINALIZE_TIMEOUT_SECONDS:-30}}
|
||||
TIMEOUT_BIN=$(command -v timeout || true)
|
||||
|
||||
run_update_cli() {
|
||||
local node=$1 timeout_seconds=$2 label=$3 result
|
||||
shift 3
|
||||
[[ "$timeout_seconds" =~ ^[1-9][0-9]*$ ]] || die "${label} timeout must be a positive integer"
|
||||
{
|
||||
printf '\n[%s] %s (timeout=%ss)\ncommand:' "$(date -u '+%Y-%m-%dT%H:%M:%SZ')" "$label" "$timeout_seconds"
|
||||
printf ' %q' "$node" "$CURRENT_LINK/dist/server/cli/update.js" "$@"
|
||||
printf '\n'
|
||||
} >>"$RUNNER_LOG"
|
||||
if [[ -n "$TIMEOUT_BIN" ]]; then
|
||||
"$TIMEOUT_BIN" --foreground --signal=TERM --kill-after=10s "${timeout_seconds}s" \
|
||||
"$node" "$CURRENT_LINK/dist/server/cli/update.js" "$@" >>"$RUNNER_LOG" 2>&1
|
||||
result=$?
|
||||
elif "$node" "$CURRENT_LINK/dist/server/cli/update.js" "$@" >>"$RUNNER_LOG" 2>&1; then
|
||||
result=0
|
||||
else
|
||||
result=$?
|
||||
fi
|
||||
printf '[%s] %s exited with status %s\n' "$(date -u '+%Y-%m-%dT%H:%M:%SZ')" "$label" "$result" >>"$RUNNER_LOG"
|
||||
return "$result"
|
||||
}
|
||||
|
||||
# Downloading is intentionally handled while the main service remains up.
|
||||
# The CLI persists the validated payload under the root-owned workspace and
|
||||
# leaves the job staged for a later apply request.
|
||||
@@ -107,6 +185,7 @@ if [[ "$request_operation" == download ]]; then
|
||||
clear_recovery_state || die '无法清理上一次下载状态'
|
||||
fi
|
||||
write_recovery_state download || die '无法写入更新恢复状态'
|
||||
# shellcheck disable=SC2329 # invoked indirectly by the EXIT trap
|
||||
cleanup_download() {
|
||||
local result=$?
|
||||
stop_heartbeat
|
||||
@@ -116,6 +195,7 @@ if [[ "$request_operation" == download ]]; then
|
||||
rm -f -- "$REQUEST_FILE" 2>/dev/null || true
|
||||
fi
|
||||
clear_recovery_state || true
|
||||
release_runner_lock
|
||||
return "$result"
|
||||
}
|
||||
trap cleanup_download EXIT
|
||||
@@ -128,7 +208,7 @@ if [[ "$request_operation" == download ]]; then
|
||||
cli="$CURRENT_LINK/dist/server/cli/update.js"
|
||||
[[ -f "$cli" ]] || die 'update CLI not found in current release'
|
||||
set +e
|
||||
"$node_bin" "$cli" --request-file "$REQUEST_FILE"
|
||||
run_update_cli "$node_bin" "$DOWNLOAD_TIMEOUT_SECONDS" download --request-file "$REQUEST_FILE"
|
||||
download_result=$?
|
||||
set -e
|
||||
if (( download_result != 0 )); then
|
||||
@@ -139,7 +219,7 @@ if [[ "$request_operation" == download ]]; then
|
||||
download_job_id=$(sed -n 's/.*"jobId"[[:space:]]*:[[:space:]]*"\([0-9a-f-]*\)".*/\1/p' "$REQUEST_FILE" | head -n 1)
|
||||
if [[ "$download_job_id" =~ ^[0-9a-f-]{36}$ ]]; then
|
||||
for _ in 1 2 3; do
|
||||
if "$node_bin" "$cli" --finalize-job "$download_job_id" --finalize-status failed --message '更新下载失败' >/dev/null 2>&1; then break; fi
|
||||
if run_update_cli "$node_bin" "$FINALIZE_TIMEOUT_SECONDS" finalize-download --finalize-job "$download_job_id" --finalize-status failed --message '更新下载失败'; then break; fi
|
||||
sleep 1
|
||||
done
|
||||
fi
|
||||
@@ -150,12 +230,11 @@ if [[ "$request_operation" == download ]]; then
|
||||
exit 0
|
||||
fi
|
||||
|
||||
was_active=0
|
||||
if systemctl is-active --quiet "$SERVICE_NAME"; then was_active=1; fi
|
||||
# shellcheck disable=SC2329 # invoked indirectly by the EXIT trap below
|
||||
restore_initial_service() {
|
||||
local result=$?
|
||||
stop_heartbeat
|
||||
release_runner_lock
|
||||
if (( result != 0 )); then
|
||||
rm -f -- "$REQUEST_FILE" 2>/dev/null || true
|
||||
if (( STATE_CREATED == 1 )); then clear_recovery_state || true; fi
|
||||
@@ -175,11 +254,11 @@ finalize_state_job() {
|
||||
local node=$1 status=$2 state_job=$3
|
||||
[[ "$state_job" =~ ^[0-9a-f-]{36}$ && -n "$node" ]] || return 1
|
||||
[[ -f "$CURRENT_LINK/dist/server/cli/update.js" ]] || return 1
|
||||
"$node" "$CURRENT_LINK/dist/server/cli/update.js" --finalize-job "$state_job" --finalize-status "$status" --message '新版本健康检查失败,已恢复上一版本' >/dev/null 2>&1
|
||||
run_update_cli "$node" "$FINALIZE_TIMEOUT_SECONDS" finalize-recovery --finalize-job "$state_job" --finalize-status "$status" --message '新版本健康检查失败,已恢复上一版本'
|
||||
}
|
||||
|
||||
recover_stale_state() {
|
||||
local state_job state_old state_phase current_target recovery_node rollback_link state_mode state_uid
|
||||
local state_job state_old state_phase state_initial_active current_target recovery_node rollback_link state_mode state_uid
|
||||
[[ -f "$STATE_FILE" && ! -L "$STATE_FILE" ]] || die 'update state file is invalid'
|
||||
state_uid=$(stat -c '%u' "$STATE_FILE" 2>/dev/null || stat -f '%u' "$STATE_FILE")
|
||||
state_mode=$(stat -c '%a' "$STATE_FILE" 2>/dev/null || stat -f '%Lp' "$STATE_FILE")
|
||||
@@ -187,8 +266,16 @@ recover_stale_state() {
|
||||
state_job=$(sed -n 's/^job_id=//p' "$STATE_FILE" | head -n 1)
|
||||
state_old=$(sed -n 's/^old_target=//p' "$STATE_FILE" | head -n 1)
|
||||
state_phase=$(sed -n 's/^phase=//p' "$STATE_FILE" | head -n 1)
|
||||
state_initial_active=$(sed -n 's/^initial_active=//p' "$STATE_FILE" | head -n 1)
|
||||
[[ "$state_job" =~ ^[0-9a-f-]{36}$ ]] || die 'update state job id is invalid'
|
||||
[[ "$state_old" == "$PREFIX/releases/"* && -d "$state_old" && ! -L "$state_old" ]] || die 'update state target is invalid'
|
||||
if [[ -z "$state_initial_active" ]]; then
|
||||
# Markers from older releases did not persist this field. Preserve their
|
||||
# historical conservative behavior instead of rejecting recovery.
|
||||
state_initial_active=0
|
||||
fi
|
||||
[[ "$state_initial_active" == 0 || "$state_initial_active" == 1 ]] || die 'update state initial service state is invalid'
|
||||
was_active=$state_initial_active
|
||||
current_target=$(readlink -f -- "$CURRENT_LINK" 2>/dev/null || true)
|
||||
if [[ "$state_phase" == download && "$current_target" == "$state_old" ]]; then
|
||||
# Downloading never changes the active release. If the runner was killed
|
||||
@@ -312,7 +399,7 @@ finalize_failed_job() {
|
||||
# Give SQLite a moment to release a transient lock before declaring the
|
||||
# recovery itself failed.
|
||||
for _ in 1 2 3; do
|
||||
if "$old_node" "$CURRENT_LINK/dist/server/cli/update.js" --finalize-job "$job_id" --finalize-status failed --message '新版本健康检查失败,已恢复上一版本' >/dev/null 2>&1; then
|
||||
if run_update_cli "$old_node" "$FINALIZE_TIMEOUT_SECONDS" finalize-failed --finalize-job "$job_id" --finalize-status failed --message '新版本健康检查失败,已恢复上一版本'; then
|
||||
return 0
|
||||
fi
|
||||
sleep 1
|
||||
@@ -323,7 +410,7 @@ finalize_failed_job() {
|
||||
finalize_completed_job() {
|
||||
[[ "$job_id" =~ ^[0-9a-f-]{36}$ ]] || return 0
|
||||
[[ -n "$final_node" ]] || return 1
|
||||
"$final_node" "$CURRENT_LINK/dist/server/cli/update.js" --finalize-job "$job_id" --finalize-status completed >/dev/null 2>&1
|
||||
run_update_cli "$final_node" "$FINALIZE_TIMEOUT_SECONDS" finalize-completed --finalize-job "$job_id" --finalize-status completed
|
||||
}
|
||||
|
||||
# shellcheck disable=SC2329 # invoked indirectly by the EXIT trap below
|
||||
@@ -347,6 +434,7 @@ cleanup_after_update() {
|
||||
else
|
||||
systemctl stop "$SERVICE_NAME" || true
|
||||
fi
|
||||
release_runner_lock
|
||||
return "$result"
|
||||
}
|
||||
trap cleanup_after_update EXIT
|
||||
@@ -358,7 +446,7 @@ cli="$CURRENT_LINK/dist/server/cli/update.js"
|
||||
[[ -f "$cli" ]] || die 'update CLI not found in current release'
|
||||
|
||||
set +e
|
||||
"$node_bin" "$cli" --request-file "$REQUEST_FILE" --defer-completion
|
||||
run_update_cli "$node_bin" "$APPLY_TIMEOUT_SECONDS" apply --request-file "$REQUEST_FILE" --defer-completion
|
||||
update_result=$?
|
||||
set -e
|
||||
if (( update_result != 0 )); then
|
||||
|
||||
+11
-2
@@ -54,16 +54,17 @@ import {
|
||||
validateNewPassword,
|
||||
verifyPassword,
|
||||
} from "./security.js";
|
||||
import { isNewerVersion } from "./update.js";
|
||||
import {
|
||||
ACTIVE_UPDATE_STATUSES,
|
||||
checkForUpdate,
|
||||
currentReleaseVersion,
|
||||
publicCheckFromCache,
|
||||
publicUpdateJob,
|
||||
reconcileOrphanedUpdateJobs,
|
||||
readCachedRelease,
|
||||
writeUpdateRequest,
|
||||
cancelUpdateJob,
|
||||
triggerInProcessDownload,
|
||||
type UpdateRequest,
|
||||
} from "./update-service.js";
|
||||
|
||||
@@ -1013,6 +1014,15 @@ export async function buildApp(database: DatabaseContext, config: AppConfig) {
|
||||
const stagedJobId = input.jobId;
|
||||
const staged = database.sqlite.prepare("SELECT id, status, operation, version, asset_url AS assetUrl, asset_name AS assetName, expected_sha256 AS expectedSha256 FROM update_jobs WHERE id=? AND admin_id=?").get(stagedJobId, request.auth!.admin.id) as { id: string; status: string; operation: string; version: string; assetUrl: string; assetName: string | null; expectedSha256: string | null } | undefined;
|
||||
if (!staged || staged.status !== "staged" || staged.version !== input.version.replace(/^v/i, "")) throw new AppError(409, "UPDATE_NOT_STAGED", "更新任务尚未完成下载");
|
||||
// A package may have been downloaded before the host was upgraded by
|
||||
// another path. Never apply a staged archive that is no longer newer
|
||||
// than the release currently serving traffic.
|
||||
const effectiveCurrentVersion = currentReleaseVersion(config) ?? config.appVersion;
|
||||
if (!isNewerVersion(effectiveCurrentVersion, staged.version)) {
|
||||
const now = Date.now();
|
||||
database.sqlite.prepare("UPDATE update_jobs SET status='failed', error_message=?, completed_at=?, updated_at=? WHERE id=? AND status='staged'").run("暂存更新已过期,当前版本无需再次升级", now, now, stagedJobId);
|
||||
throw new AppError(409, "UPDATE_NOT_AVAILABLE", "暂存更新已过期,请重新检查更新");
|
||||
}
|
||||
if (staged.operation === "apply") throw new AppError(409, "UPDATE_IN_PROGRESS", "更新任务正在处理中,请稍候");
|
||||
enforceUpdateCooldown(database.sqlite, config, request.auth!.admin.id, "apply", reply);
|
||||
const now = Date.now();
|
||||
@@ -1181,7 +1191,6 @@ export async function buildApp(database: DatabaseContext, config: AppConfig) {
|
||||
database.sqlite.prepare("UPDATE update_jobs SET status='failed', error_message=?, updated_at=? WHERE id=?").run("无法创建系统更新请求", Date.now(), id);
|
||||
throw new AppError(503, "UPDATE_QUEUE_FAILED", "无法提交更新请求,请检查服务安装权限");
|
||||
}
|
||||
triggerInProcessDownload(database.sqlite, config, id, cachedAsset, cachedAsset.sha256);
|
||||
reply.header("Cache-Control", "no-store");
|
||||
return reply.code(202).send({ job: { id, status: "queued", operation: "download", version } });
|
||||
});
|
||||
|
||||
+46
-15
@@ -163,7 +163,11 @@ function writeJob(sqlite: Database.Database | undefined, jobId: string, values:
|
||||
requested_at=COALESCE(excluded.requested_at, update_jobs.requested_at),
|
||||
started_at=COALESCE(excluded.started_at, update_jobs.started_at),
|
||||
operation=excluded.operation,
|
||||
status=excluded.status, version=excluded.version, platform=excluded.platform,
|
||||
-- Terminal rows are immutable from the runner's ordinary progress
|
||||
-- writes. In particular, a stale/replayed request must not resurrect a
|
||||
-- failed job as queued/downloading/etc.
|
||||
status=CASE WHEN update_jobs.status IN ('cancelled', 'failed', 'completed') THEN update_jobs.status ELSE excluded.status END,
|
||||
version=excluded.version, platform=excluded.platform,
|
||||
release_url=COALESCE(excluded.release_url, update_jobs.release_url),
|
||||
asset_name=COALESCE(excluded.asset_name, update_jobs.asset_name),
|
||||
asset_url=excluded.asset_url,
|
||||
@@ -175,6 +179,11 @@ function writeJob(sqlite: Database.Database | undefined, jobId: string, values:
|
||||
error_message=COALESCE(excluded.error_message, update_jobs.error_message),
|
||||
updated_at=excluded.updated_at,
|
||||
completed_at=COALESCE(excluded.completed_at, update_jobs.completed_at)
|
||||
-- Do not let a delayed runner replay overwrite any field on a terminal
|
||||
-- row. The predicate is part of the same SQLite upsert, so a finalizer
|
||||
-- racing this write still wins atomically instead of leaving a partially
|
||||
-- mutated completed/failed/cancelled record.
|
||||
WHERE update_jobs.status NOT IN ('cancelled', 'failed', 'completed')
|
||||
`).run(
|
||||
jobId,
|
||||
values.adminId ?? null,
|
||||
@@ -229,6 +238,7 @@ async function resolveRelease(options: UpdateRunOptions, platform: ReturnType<ty
|
||||
allowedHosts: options.allowedHosts ?? [],
|
||||
baseUrl: metadataUrl.toString(),
|
||||
maxBytes: options.maxBytes ?? 512 * 1024 * 1024,
|
||||
timeoutMs: options.timeoutMs,
|
||||
publicKey: options.publicKey,
|
||||
requireSignature: options.requireSignature,
|
||||
});
|
||||
@@ -276,6 +286,7 @@ export async function runUpdate(options: UpdateRunOptions): Promise<UpdateRunRes
|
||||
const platform = options.platform ?? detectPlatform();
|
||||
const jobId = options.jobId ?? randomUUID();
|
||||
const operation = options.operation ?? "apply";
|
||||
const sqlite = options.sqlite;
|
||||
let resolved: Awaited<ReturnType<typeof resolveRelease>> | undefined;
|
||||
try {
|
||||
resolved = await resolveRelease(options, platform);
|
||||
@@ -299,7 +310,12 @@ export async function runUpdate(options: UpdateRunOptions): Promise<UpdateRunRes
|
||||
if (operation === "download") await mkdir(workspace, { recursive: false, mode: 0o700 });
|
||||
const archivePath = path.join(workspace, resolved.asset.name.endsWith(".gz") || resolved.asset.name.endsWith(".zip") ? resolved.asset.name : `${resolved.asset.name}.tar.gz`);
|
||||
try {
|
||||
updateJob(options.sqlite, jobId, { operation, status: "downloading", version: resolved.version, platform: platform.target, releaseUrl: resolved.releaseUrl, assetName: resolved.asset.name, assetUrl: resolved.asset.url, expectedSha256, downloadPath: path.basename(archivePath), startedAt: Date.now() });
|
||||
if (sqlite) {
|
||||
const claim = sqlite.prepare("UPDATE update_jobs SET status='downloading', download_started_at=?, started_at=?, download_path=?, updated_at=? WHERE id=? AND status='queued'").run(Date.now(), Date.now(), path.basename(archivePath), Date.now(), jobId);
|
||||
if (claim.changes !== 1) throw new Error("更新任务已取消或已被其他进程接管");
|
||||
} else {
|
||||
updateJob(options.sqlite, jobId, { operation, status: "downloading", version: resolved.version, platform: platform.target, releaseUrl: resolved.releaseUrl, assetName: resolved.asset.name, assetUrl: resolved.asset.url, expectedSha256, downloadPath: path.basename(archivePath), startedAt: Date.now() });
|
||||
}
|
||||
const progressStartedAt = Date.now();
|
||||
let lastProgressWrite = 0;
|
||||
const downloaded = await downloadReleaseAsset(resolved.asset.url, archivePath, {
|
||||
@@ -337,7 +353,12 @@ export async function runUpdate(options: UpdateRunOptions): Promise<UpdateRunRes
|
||||
await normalizeReleasePermissions(stagedDir);
|
||||
const payloadInfo = await lstat(path.join(stagedDir, "dist")).catch(() => null);
|
||||
if (!payloadInfo?.isDirectory() || payloadInfo.isSymbolicLink()) throw new Error("发布包缺少 dist 目录");
|
||||
updateJob(options.sqlite, jobId, { operation, status: "staged", version: resolved.version, platform: platform.target, releaseUrl: resolved.releaseUrl, assetName: resolved.asset.name, assetUrl: resolved.asset.url, expectedSha256, actualSha256: downloaded.sha256, sizeBytes: downloaded.size, downloadPath: workspace });
|
||||
if (sqlite) {
|
||||
const staged = sqlite.prepare("UPDATE update_jobs SET status='staged', actual_sha256=?, size_bytes=?, download_path=?, updated_at=? WHERE id=? AND status IN ('verifying', 'downloading')").run(downloaded.sha256, downloaded.size, workspace, Date.now(), jobId);
|
||||
if (staged.changes !== 1) throw new Error("更新任务已取消,已停止继续处理");
|
||||
} else {
|
||||
updateJob(options.sqlite, jobId, { operation, status: "staged", version: resolved.version, platform: platform.target, releaseUrl: resolved.releaseUrl, assetName: resolved.asset.name, assetUrl: resolved.asset.url, expectedSha256, actualSha256: downloaded.sha256, sizeBytes: downloaded.size, downloadPath: workspace });
|
||||
}
|
||||
|
||||
if (operation === "download") {
|
||||
keepWorkspace = true;
|
||||
@@ -386,19 +407,28 @@ export function finalizeUpdateJob(
|
||||
status: "completed" | "failed",
|
||||
message?: string,
|
||||
): void {
|
||||
const row = sqlite.prepare(`
|
||||
SELECT id, status, version, platform, admin_id AS adminId,
|
||||
request_id AS requestId, session_hash AS sessionHash
|
||||
FROM update_jobs WHERE id=?
|
||||
`).get(jobId) as { id: string; status: UpdateJobStatus; version: string; platform: string; adminId: string | null; requestId: string | null; sessionHash: string | null } | undefined;
|
||||
if (!row) throw new Error("更新任务不存在");
|
||||
const canComplete = row.status === "applying" || row.status === "completed";
|
||||
const canFail = ACTIVE_UPDATE_STATUSES.includes(row.status) || row.status === "completed" || row.status === "failed";
|
||||
if (status === "completed" ? !canComplete : !canFail) throw new Error("更新任务状态不允许完成");
|
||||
const now = Date.now();
|
||||
const safeFailureMessage = status === "failed" ? "新版本健康检查失败,已恢复上一版本" : null;
|
||||
sqlite.transaction(() => {
|
||||
sqlite.prepare("UPDATE update_jobs SET status=?, error_message=?, completed_at=?, updated_at=? WHERE id=?").run(status, safeFailureMessage, now, now, jobId);
|
||||
const row = sqlite.prepare(`
|
||||
SELECT id, status, version, platform, admin_id AS adminId,
|
||||
request_id AS requestId, session_hash AS sessionHash
|
||||
FROM update_jobs WHERE id=?
|
||||
`).get(jobId) as { id: string; status: UpdateJobStatus; version: string; platform: string; adminId: string | null; requestId: string | null; sessionHash: string | null } | undefined;
|
||||
if (!row) throw new Error("更新任务不存在");
|
||||
// A failed finalization can be retried by the runner. Once it has been
|
||||
// committed, make retries a no-op so the error and audit trail stay stable.
|
||||
if (row.status === status) return;
|
||||
// A completed release is terminal. A delayed recovery process must never
|
||||
// be able to downgrade it to failed after the service was healthy.
|
||||
if (row.status === "completed" && status === "failed") throw new Error("更新任务状态不允许完成");
|
||||
const canComplete = row.status === "applying" || row.status === "completed";
|
||||
const canFail = ACTIVE_UPDATE_STATUSES.includes(row.status) || row.status === "completed" || row.status === "failed";
|
||||
if (status === "completed" ? !canComplete : !canFail) throw new Error("更新任务状态不允许完成");
|
||||
const now = Date.now();
|
||||
const safeFailureMessage = status === "failed"
|
||||
? (message?.trim() ? safeErrorMessage(new Error(message)) : "新版本健康检查失败,已恢复上一版本")
|
||||
: null;
|
||||
const result = sqlite.prepare("UPDATE update_jobs SET status=?, error_message=?, completed_at=?, updated_at=? WHERE id=? AND status=?").run(status, safeFailureMessage, now, now, jobId, row.status);
|
||||
if (result.changes !== 1) return;
|
||||
writeAudit(sqlite, {
|
||||
requestId: row.requestId || randomUUID(),
|
||||
actorAdminId: row.adminId,
|
||||
@@ -557,6 +587,7 @@ export async function main(config: AppConfig = loadConfig()): Promise<void> {
|
||||
...(dataBackupArchive ? { dataBackupArchivePath: dataBackupArchive, dataBackupSource: config.dataDir } : {}),
|
||||
...((arg("--backup-dir")) ? { backupDir: arg("--backup-dir") } : {}),
|
||||
allowedHosts: allowedHosts.length ? allowedHosts : config.updateAllowedHosts,
|
||||
timeoutMs: config.updateTimeoutMs,
|
||||
maxBytes: config.updateMaxBytes,
|
||||
dataBackupMaxBytes: config.maxTotalBytes,
|
||||
currentVersion: config.appVersion,
|
||||
|
||||
@@ -147,6 +147,7 @@ export function loadConfig() {
|
||||
// as 0700 root:root; development/test callers may override --staging-dir.
|
||||
updateWorkspaceDir: path.join(installPrefix, ".update-work"),
|
||||
updateMaxBytes: integerEnv("TALLYNOTE_UPDATE_MAX_MB", 512) * 1024 * 1024,
|
||||
updateTimeoutMs: integerEnv("TALLYNOTE_UPDATE_TIMEOUT_SECONDS", 30) * 1000,
|
||||
// Update checks hit an external release endpoint. Keep a short local
|
||||
// cooldown so an authenticated account cannot turn the endpoint into an
|
||||
// outbound request flood; set to 0 only for controlled test environments.
|
||||
|
||||
+102
-113
@@ -18,108 +18,12 @@ import {
|
||||
selectReleaseAsset,
|
||||
validateHttpsUrl,
|
||||
RELEASE_NOTES_MAX_BYTES,
|
||||
downloadReleaseAsset,
|
||||
extractSafeArchive,
|
||||
normalizeReleasePermissions,
|
||||
applicationUpdateRuntimeHash,
|
||||
type ReleaseAsset,
|
||||
type ReleaseMetadata,
|
||||
} from "./update.js";
|
||||
import type { UpdateJobStatus } from "../shared/contracts.js";
|
||||
|
||||
|
||||
export const activeInProcessDownloads = new Map<string, AbortController>();
|
||||
|
||||
export function triggerInProcessDownload(
|
||||
database: Database.Database,
|
||||
config: AppConfig,
|
||||
jobId: string,
|
||||
asset: { name: string; url: string; sha256?: string },
|
||||
expectedSha256?: string,
|
||||
): void {
|
||||
setImmediate(async () => {
|
||||
try {
|
||||
const row = database.prepare("SELECT id, status, operation FROM update_jobs WHERE id=?").get(jobId) as { id: string; status: string; operation: string } | undefined;
|
||||
if (!row || row.status !== "queued") return;
|
||||
|
||||
const controller = new AbortController();
|
||||
activeInProcessDownloads.set(jobId, controller);
|
||||
|
||||
const workspace = path.join(path.resolve(config.stagingDir), `update-${jobId}`);
|
||||
const archivePath = path.join(workspace, asset.name.endsWith(".gz") || asset.name.endsWith(".zip") ? asset.name : `${asset.name}.tar.gz`);
|
||||
|
||||
await mkdir(workspace, { recursive: true, mode: 0o700 });
|
||||
const now = Date.now();
|
||||
database.prepare("UPDATE update_jobs SET status='downloading', download_started_at=?, started_at=?, download_path=?, updated_at=? WHERE id=? AND status='queued'").run(now, now, path.basename(archivePath), now, jobId);
|
||||
|
||||
const progressStartedAt = Date.now();
|
||||
let lastProgressWrite = 0;
|
||||
|
||||
const downloaded = await downloadReleaseAsset(asset.url, archivePath, {
|
||||
allowedHosts: config.updateAllowedHosts,
|
||||
maxBytes: config.updateMaxBytes,
|
||||
fetchImpl: (input, init) => fetch(input, { ...init, signal: controller.signal }),
|
||||
onProgress: (downloadedBytes, totalBytes) => {
|
||||
const cur = Date.now();
|
||||
if (cur - lastProgressWrite < 200) return;
|
||||
lastProgressWrite = cur;
|
||||
const elapsed = Math.max(1, cur - progressStartedAt);
|
||||
const speedBps = Math.round(downloadedBytes * 1000 / elapsed);
|
||||
try {
|
||||
database.prepare("UPDATE update_jobs SET downloaded_bytes=?, size_bytes=COALESCE(?, size_bytes), download_speed_bps=?, updated_at=? WHERE id=? AND status='downloading'").run(downloadedBytes, totalBytes, speedBps, cur, jobId);
|
||||
} catch {}
|
||||
},
|
||||
});
|
||||
|
||||
if (expectedSha256 && downloaded.sha256.toLowerCase() !== expectedSha256.toLowerCase()) {
|
||||
throw new Error("更新文件 SHA-256 校验失败");
|
||||
}
|
||||
|
||||
database.prepare("UPDATE update_jobs SET status='verifying', actual_sha256=?, size_bytes=?, downloaded_bytes=?, updated_at=? WHERE id=? AND status='downloading'").run(downloaded.sha256, downloaded.size, downloaded.size, Date.now(), jobId);
|
||||
|
||||
const stagedDir = path.join(workspace, "payload");
|
||||
await extractSafeArchive(archivePath, stagedDir, config.updateMaxBytes === undefined ? {} : { maxBytes: config.updateMaxBytes });
|
||||
|
||||
if (applicationUpdateRuntimeHash(asset.name)) {
|
||||
try {
|
||||
const currentRelease = realpathSync(config.currentLink);
|
||||
if (currentRelease) {
|
||||
const fsPromises = await import("node:fs/promises");
|
||||
for (const entry of ["node_modules", "runtime", "pnpm-lock.yaml"] as const) {
|
||||
const source = path.join(currentRelease, entry);
|
||||
const sourceInfo = await fsPromises.lstat(source).catch(() => null);
|
||||
if (sourceInfo && !sourceInfo.isSymbolicLink()) {
|
||||
await fsPromises.cp(source, path.join(stagedDir, entry), { recursive: sourceInfo.isDirectory(), errorOnExist: true, force: false }).catch(() => {});
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch {}
|
||||
}
|
||||
|
||||
await normalizeReleasePermissions(stagedDir).catch(() => {});
|
||||
const fsPromises = await import("node:fs/promises");
|
||||
const payloadInfo = await fsPromises.lstat(path.join(stagedDir, "dist")).catch(() => null);
|
||||
if (!payloadInfo?.isDirectory() || payloadInfo.isSymbolicLink()) {
|
||||
throw new Error("发布包缺少 dist 目录");
|
||||
}
|
||||
|
||||
database.prepare("UPDATE update_jobs SET status='staged', actual_sha256=?, size_bytes=?, download_path=?, updated_at=? WHERE id=? AND status IN ('verifying', 'downloading')").run(downloaded.sha256, downloaded.size, workspace, Date.now(), jobId);
|
||||
} catch (error) {
|
||||
const controller = activeInProcessDownloads.get(jobId);
|
||||
if (controller?.signal.aborted) return;
|
||||
const rawMsg = error instanceof Error ? error.message : "更新文件下载失败";
|
||||
try {
|
||||
database.prepare("UPDATE update_jobs SET status='failed', error_message=?, updated_at=? WHERE id=? AND status NOT IN ('completed', 'staged', 'cancelled')").run(rawMsg, Date.now(), jobId);
|
||||
} catch {}
|
||||
const workspace = path.join(path.resolve(config.stagingDir), `update-${jobId}`);
|
||||
const fsPromises = await import("node:fs/promises");
|
||||
await fsPromises.rm(workspace, { recursive: true, force: true }).catch(() => {});
|
||||
} finally {
|
||||
activeInProcessDownloads.delete(jobId);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
export const UPDATE_CACHE_KEY = "update.release.v1";
|
||||
export const ACTIVE_UPDATE_STATUSES: readonly UpdateJobStatus[] = [
|
||||
"queued",
|
||||
@@ -250,19 +154,19 @@ function signatureAssetFor(metadata: ReleaseMetadata, sums: ReleaseAsset): Relea
|
||||
export async function attachSidecarHash(
|
||||
metadata: ReleaseMetadata,
|
||||
asset: ReleaseAsset,
|
||||
options: { allowedHosts: readonly string[]; baseUrl: string; maxBytes: number; publicKey?: string | undefined; requireSignature?: boolean | undefined },
|
||||
options: { allowedHosts: readonly string[]; baseUrl: string; maxBytes: number; timeoutMs?: number | undefined; publicKey?: string | undefined; requireSignature?: boolean | undefined },
|
||||
): Promise<{ asset: ReleaseAsset; signatureVerified: boolean }> {
|
||||
let signatureVerified = false;
|
||||
if (asset.sha256 && (!options.publicKey || !options.requireSignature)) return { asset, signatureVerified };
|
||||
const sums = metadata.assets.find((candidate) => /^(?:sha256sums?|checksums?)(?:\.txt)?$/i.test(path.basename(candidate.name)));
|
||||
if (!sums) return { asset, signatureVerified };
|
||||
try {
|
||||
const content = await fetchReleaseText(sums.url, { allowedHosts: options.allowedHosts, baseUrl: options.baseUrl, maxBytes: Math.min(options.maxBytes, 2 * 1024 * 1024) });
|
||||
const content = await fetchReleaseText(sums.url, { allowedHosts: options.allowedHosts, baseUrl: options.baseUrl, maxBytes: Math.min(options.maxBytes, 2 * 1024 * 1024), timeoutMs: options.timeoutMs });
|
||||
const sha256 = sha256FromSums(content, asset.name);
|
||||
if (options.publicKey) {
|
||||
const signatureAsset = signatureAssetFor(metadata, sums);
|
||||
if (signatureAsset) {
|
||||
const signature = await fetchReleaseBytes(signatureAsset.url, { allowedHosts: options.allowedHosts, baseUrl: options.baseUrl, maxBytes: 64 * 1024 });
|
||||
const signature = await fetchReleaseBytes(signatureAsset.url, { allowedHosts: options.allowedHosts, baseUrl: options.baseUrl, maxBytes: 64 * 1024, timeoutMs: options.timeoutMs });
|
||||
signatureVerified = verifyReleaseSignature(content, signature, options.publicKey);
|
||||
}
|
||||
}
|
||||
@@ -279,6 +183,7 @@ function policy(config: AppConfig) {
|
||||
allowedHosts: config.updateAllowedHosts,
|
||||
baseUrl: config.updateMetadataUrl,
|
||||
maxRedirects: 3,
|
||||
timeoutMs: config.updateTimeoutMs,
|
||||
} as const;
|
||||
}
|
||||
|
||||
@@ -310,13 +215,15 @@ export async function checkForUpdate(database: Database.Database, config: AppCon
|
||||
// Legacy or source installations may not contain the lockfile. They stay
|
||||
// on the full release asset instead of risking an incompatible runtime.
|
||||
}
|
||||
let asset = selectReleaseAsset(metadata, platform, runtimeHash);
|
||||
// Force choosing the full standalone archive so users always get a real, visible streaming download
|
||||
let asset = selectReleaseAsset(metadata, platform, undefined);
|
||||
let signatureVerified = false;
|
||||
if (asset) {
|
||||
const integrity = await attachSidecarHash(metadata, asset, {
|
||||
allowedHosts: config.updateAllowedHosts,
|
||||
baseUrl: metadataUrl,
|
||||
maxBytes: config.updateMaxBytes,
|
||||
timeoutMs: config.updateTimeoutMs,
|
||||
publicKey: config.updatePublicKey,
|
||||
requireSignature: config.updateRequireSignature,
|
||||
});
|
||||
@@ -521,7 +428,18 @@ function requestJobId(filePath: string): string | null {
|
||||
}
|
||||
}
|
||||
|
||||
function currentReleaseVersion(config: AppConfig): string | null {
|
||||
function recoveryStateJobId(filePath: string): string | null {
|
||||
try {
|
||||
const info = lstatSync(filePath);
|
||||
if (!info.isFile() || info.isSymbolicLink()) return null;
|
||||
const match = /^job_id=([0-9a-f-]{36})$/m.exec(readFileSync(filePath, "utf8"));
|
||||
return match?.[1] ?? null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function currentReleaseVersion(config: AppConfig): string | null {
|
||||
try {
|
||||
const target = realpathSync(config.currentLink);
|
||||
const releases = realpathSync(config.releasesDir);
|
||||
@@ -555,6 +473,12 @@ export function reconcileOrphanedUpdateJobs(database: Database.Database, config:
|
||||
const statePresent = stateMtime !== null;
|
||||
const requestFresh = requestPresent && now - (requestMtime ?? 0) < ORPHANED_UPDATE_TIMEOUT_MS;
|
||||
const stateFresh = statePresent && now - (stateMtime ?? 0) < ORPHANED_UPDATE_TIMEOUT_MS;
|
||||
// The request marker is the hand-off contract between the web process and
|
||||
// the privileged runner. A queued row with a matching, unexpired marker is
|
||||
// still owned by that hand-off even when the runner has not written its
|
||||
// recovery state yet (for example while systemd is starting it).
|
||||
const requestMarkerJobId = requestPresent ? requestJobId(config.updateRequestPath) : null;
|
||||
const stateMarkerJobId = statePresent ? recoveryStateJobId(statePath) : null;
|
||||
// A staged download is normally kept for an explicit apply. The one
|
||||
// exception is the hand-off window where the API has already changed the
|
||||
// operation to `apply` but crashed before writing the request file. That
|
||||
@@ -563,12 +487,81 @@ export function reconcileOrphanedUpdateJobs(database: Database.Database, config:
|
||||
let reconciled = 0;
|
||||
const reconciledIds = new Set<string>();
|
||||
for (const row of rows) {
|
||||
// A fresh request/state marker means the privileged runner still owns the
|
||||
// hand-off. Do not expire a staged/apply row while the runner is finishing
|
||||
// a successful switch and finalization after a service restart.
|
||||
const matchingFreshRequest = requestMarkerJobId === row.id && requestFresh;
|
||||
const matchingFreshState = stateMarkerJobId === row.id && stateFresh;
|
||||
// A staged archive is actionable only while it is strictly newer than the
|
||||
// release currently serving requests. This can become false when an
|
||||
// administrator upgrades the host by another path (or another operator
|
||||
// completes the same release) before returning to this page. Treat the
|
||||
// archive as an expired terminal task so it cannot keep blocking the
|
||||
// queue or appear as an "apply" action for the current version.
|
||||
const effectiveCurrentVersion = releaseVersion ?? config.appVersion;
|
||||
if (row.status === "staged" && !isNewerVersion(effectiveCurrentVersion, row.version) && !matchingFreshRequest && !matchingFreshState) {
|
||||
const changed = database.transaction(() => {
|
||||
const result = database.prepare(`
|
||||
UPDATE update_jobs
|
||||
SET status='failed', error_message=?, completed_at=?, updated_at=?
|
||||
WHERE id=? AND status='staged'
|
||||
`).run("暂存更新已过期,当前版本无需再次升级", now, now, row.id);
|
||||
if (result.changes !== 1) return false;
|
||||
writeAudit(database, {
|
||||
requestId: row.requestId || randomUUID(),
|
||||
actorAdminId: row.adminId,
|
||||
action: "update.reconciled",
|
||||
targetType: "update",
|
||||
targetId: row.id,
|
||||
outcome: "failure",
|
||||
before: { status: row.status, operation: row.operation, version: row.version },
|
||||
after: { status: "failed", version: row.version, reason: "staged_version_not_newer" },
|
||||
});
|
||||
return true;
|
||||
})();
|
||||
if (changed) {
|
||||
reconciled += 1;
|
||||
reconciledIds.add(row.id);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
// A request that never gets claimed by the root runner must not remain in
|
||||
// the UI as an endless "queued" task. Once the short hand-off window has
|
||||
// elapsed and no recovery marker exists, release the queue explicitly;
|
||||
// a fresh state marker proves that the runner has already claimed it.
|
||||
if (row.status === "queued" && typeof row.updatedAt === "number" && !matchingFreshState && now - row.updatedAt >= QUEUED_UPDATE_TIMEOUT_MS) {
|
||||
if (matchingFreshRequest) continue;
|
||||
const changed = database.transaction(() => {
|
||||
const result = database.prepare(`
|
||||
UPDATE update_jobs
|
||||
SET status='failed', error_message=?, completed_at=?, updated_at=?
|
||||
WHERE id=? AND status='queued' AND updated_at=?
|
||||
`).run("更新服务未在规定时间内接管任务", now, now, row.id, row.updatedAt);
|
||||
if (result.changes !== 1) return false;
|
||||
writeAudit(database, {
|
||||
requestId: row.requestId || randomUUID(),
|
||||
actorAdminId: row.adminId,
|
||||
action: "update.reconciled",
|
||||
targetType: "update",
|
||||
targetId: row.id,
|
||||
outcome: "failure",
|
||||
before: { status: row.status, version: row.version },
|
||||
after: { status: "failed", version: row.version, reason: "runner_claim_timeout" },
|
||||
});
|
||||
return true;
|
||||
})();
|
||||
if (changed) {
|
||||
reconciled += 1;
|
||||
reconciledIds.add(row.id);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (typeof row.updatedAt !== "number" || now - row.updatedAt < ORPHANED_UPDATE_TIMEOUT_MS) continue;
|
||||
// The runner refreshes the state marker while a download is in flight.
|
||||
// A stale request/state marker therefore no longer protects an orphaned
|
||||
// row forever, while a fresh marker remains owned by the runner.
|
||||
if (row.status === "staged") {
|
||||
if (row.operation !== "apply" || requestFresh || stateFresh) continue;
|
||||
if (row.operation !== "apply" || matchingFreshRequest || matchingFreshState) continue;
|
||||
const changed = database.transaction(() => {
|
||||
const result = database.prepare(`
|
||||
UPDATE update_jobs
|
||||
@@ -594,7 +587,7 @@ export function reconcileOrphanedUpdateJobs(database: Database.Database, config:
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (requestFresh || stateFresh) continue;
|
||||
if (matchingFreshRequest || matchingFreshState) continue;
|
||||
const status: "completed" | "failed" = row.status === "applying" && releaseVersion === row.version ? "completed" : "failed";
|
||||
const errorMessage = status === "failed" ? "更新任务超时,已释放更新队列" : null;
|
||||
const changed = database.transaction(() => {
|
||||
@@ -651,21 +644,15 @@ export function cancelUpdateJob(
|
||||
jobId?: string,
|
||||
): { cancelled: boolean; message?: string } {
|
||||
const job = jobId
|
||||
? database.prepare("SELECT id, status, operation, version, admin_id AS adminId, download_path AS downloadPath FROM update_jobs WHERE id=?").get(jobId) as { id: string; status: UpdateJobStatus; operation: string; version: string; adminId: string | null; downloadPath: string | null } | undefined
|
||||
: database.prepare("SELECT id, status, operation, version, admin_id AS adminId, download_path AS downloadPath FROM update_jobs WHERE status IN ('queued', 'downloading') ORDER BY created_at DESC LIMIT 1").get() as { id: string; status: UpdateJobStatus; operation: string; version: string; adminId: string | null; downloadPath: string | null } | undefined;
|
||||
? database.prepare("SELECT id, status, operation, version, admin_id AS adminId, download_path AS downloadPath FROM update_jobs WHERE id=? AND admin_id=?").get(jobId, adminId) as { id: string; status: UpdateJobStatus; operation: string; version: string; adminId: string | null; downloadPath: string | null } | undefined
|
||||
: database.prepare("SELECT id, status, operation, version, admin_id AS adminId, download_path AS downloadPath FROM update_jobs WHERE admin_id=? AND status IN ('queued', 'downloading') ORDER BY created_at DESC LIMIT 1").get(adminId) as { id: string; status: UpdateJobStatus; operation: string; version: string; adminId: string | null; downloadPath: string | null } | undefined;
|
||||
|
||||
if (!job) return { cancelled: false, message: "当前没有处于等待调度或下载中的更新任务" };
|
||||
if (job.status !== "queued" && job.status !== "downloading") return { cancelled: false, message: "任务已进入就绪或切换阶段,无法取消" };
|
||||
|
||||
const controller = activeInProcessDownloads.get(job.id);
|
||||
if (controller) {
|
||||
controller.abort();
|
||||
activeInProcessDownloads.delete(job.id);
|
||||
}
|
||||
|
||||
const now = Date.now();
|
||||
const changed = database.transaction(() => {
|
||||
const result = database.prepare("UPDATE update_jobs SET status='cancelled', error_message='已手动取消更新', completed_at=?, updated_at=? WHERE id=? AND status IN ('queued', 'downloading')").run(now, now, job.id);
|
||||
const result = database.prepare("UPDATE update_jobs SET status='cancelled', error_message='已手动取消更新', completed_at=?, updated_at=? WHERE id=? AND admin_id=? AND status IN ('queued', 'downloading')").run(now, now, job.id, adminId);
|
||||
if (result.changes !== 1) return false;
|
||||
writeAudit(database, {
|
||||
requestId,
|
||||
@@ -681,7 +668,9 @@ export function cancelUpdateJob(
|
||||
})();
|
||||
|
||||
if (changed) {
|
||||
forceRemoveRequest(config.updateRequestPath);
|
||||
// The request marker is shared by the privileged runner. Never remove a
|
||||
// newer/different administrator's request while cancelling this row.
|
||||
if (requestJobId(config.updateRequestPath) === job.id) forceRemoveRequest(config.updateRequestPath);
|
||||
if (job.downloadPath) {
|
||||
const target = path.isAbsolute(job.downloadPath) ? job.downloadPath : path.join(config.stagingDir, job.downloadPath);
|
||||
import("node:fs/promises").then(({ rm }) => rm(target, { recursive: true, force: true })).catch(() => {});
|
||||
|
||||
+165
-94
@@ -59,8 +59,22 @@ export type UrlPolicy = {
|
||||
/** When allowedHosts is omitted, requests are constrained to this URL's host. */
|
||||
baseUrl?: string | URL | undefined;
|
||||
maxRedirects?: number | undefined;
|
||||
/** Maximum time allowed for one metadata/sidecar/archive request. */
|
||||
timeoutMs?: number | undefined;
|
||||
};
|
||||
|
||||
/** Release an unread response body before following a redirect or returning
|
||||
* an error. Undici keeps the underlying connection associated with a body
|
||||
* until it is consumed or cancelled; leaving it open can exhaust sockets when
|
||||
* an update feed repeatedly returns errors or oversized responses. */
|
||||
async function cancelResponseBody(response: Response): Promise<void> {
|
||||
try {
|
||||
await response.body?.cancel();
|
||||
} catch {
|
||||
// The body may already be consumed/closed. Cancellation is best effort.
|
||||
}
|
||||
}
|
||||
|
||||
function invalidVersion(): never {
|
||||
throw new Error("更新版本号无效");
|
||||
}
|
||||
@@ -157,8 +171,37 @@ function metadataError(): Error {
|
||||
}
|
||||
|
||||
const DEFAULT_METADATA_MAX_BYTES = 2 * 1024 * 1024;
|
||||
/** Maximum time allowed for one update HTTP request, including its body. */
|
||||
export const DEFAULT_UPDATE_TIMEOUT_MS = 30_000;
|
||||
export const RELEASE_NOTES_MAX_BYTES = 64 * 1024;
|
||||
|
||||
type UpdateFetchOptions = {
|
||||
fetchImpl?: typeof fetch | undefined;
|
||||
maxBytes?: number | undefined;
|
||||
timeoutMs?: number | undefined;
|
||||
};
|
||||
|
||||
function updateTimeoutMs(options: UpdateFetchOptions): number {
|
||||
if (options.timeoutMs !== undefined) {
|
||||
if (!Number.isSafeInteger(options.timeoutMs) || options.timeoutMs <= 0) throw new Error("更新请求超时配置无效");
|
||||
return options.timeoutMs;
|
||||
}
|
||||
const configuredSeconds = process.env.TALLYNOTE_UPDATE_TIMEOUT_SECONDS;
|
||||
if (configuredSeconds !== undefined && configuredSeconds.trim() !== "") {
|
||||
const seconds = Number(configuredSeconds);
|
||||
if (!Number.isSafeInteger(seconds) || seconds <= 0) throw new Error("TALLYNOTE_UPDATE_TIMEOUT_SECONDS 必须是大于 0 的整数");
|
||||
return seconds * 1000;
|
||||
}
|
||||
return DEFAULT_UPDATE_TIMEOUT_MS;
|
||||
}
|
||||
|
||||
function beginUpdateRequest(options: UpdateFetchOptions): { signal: AbortSignal; clear: () => void } {
|
||||
const controller = new AbortController();
|
||||
const timer = setTimeout(() => controller.abort(), updateTimeoutMs(options));
|
||||
timer.unref?.();
|
||||
return { signal: controller.signal, clear: () => clearTimeout(timer) };
|
||||
}
|
||||
|
||||
function releaseNotesText(value: unknown): string | undefined {
|
||||
if (typeof value !== "string" || value.length === 0) return undefined;
|
||||
// Gitea exposes both Markdown (body/body_html) and releaseNotes depending on
|
||||
@@ -210,20 +253,29 @@ function releaseResourceUrl(value: string, current: URL, options: UrlPolicy): st
|
||||
}
|
||||
|
||||
/** Read a fetch body without ever buffering more than the caller's bound. */
|
||||
async function readBoundedResponse(response: Response, maxBytes: number, tooLargeMessage: string): Promise<Buffer> {
|
||||
async function readBoundedResponse(response: Response, maxBytes: number, tooLargeMessage: string, signal?: AbortSignal): Promise<Buffer> {
|
||||
if (!Number.isSafeInteger(maxBytes) || maxBytes <= 0) throw new Error("响应大小限制无效");
|
||||
const contentLength = response.headers.get("content-length");
|
||||
if (contentLength !== null) {
|
||||
const declared = Number(contentLength);
|
||||
if (Number.isFinite(declared) && declared > maxBytes) throw new Error(tooLargeMessage);
|
||||
if (Number.isFinite(declared) && declared > maxBytes) {
|
||||
await cancelResponseBody(response);
|
||||
throw new Error(tooLargeMessage);
|
||||
}
|
||||
}
|
||||
if (!response.body) return Buffer.alloc(0);
|
||||
const reader = response.body.getReader();
|
||||
const chunks: Buffer[] = [];
|
||||
let total = 0;
|
||||
let onAbort: (() => void) | undefined;
|
||||
const abort = signal ? new Promise<never>((_, reject) => {
|
||||
onAbort = () => reject(new Error("更新请求超时"));
|
||||
if (signal.aborted) onAbort();
|
||||
else signal.addEventListener("abort", onAbort, { once: true });
|
||||
}) : undefined;
|
||||
try {
|
||||
for (;;) {
|
||||
const result = await reader.read();
|
||||
const result = await (abort ? Promise.race([reader.read(), abort]) : reader.read());
|
||||
if (result.done) break;
|
||||
const chunk = Buffer.from(result.value);
|
||||
if (chunk.length > maxBytes - total) {
|
||||
@@ -233,7 +285,11 @@ async function readBoundedResponse(response: Response, maxBytes: number, tooLarg
|
||||
total += chunk.length;
|
||||
chunks.push(chunk);
|
||||
}
|
||||
} catch (error) {
|
||||
await reader.cancel().catch(() => undefined);
|
||||
throw error;
|
||||
} finally {
|
||||
if (signal && onAbort) signal.removeEventListener("abort", onAbort);
|
||||
reader.releaseLock();
|
||||
}
|
||||
return Buffer.concat(chunks, total);
|
||||
@@ -241,84 +297,78 @@ async function readBoundedResponse(response: Response, maxBytes: number, tooLarg
|
||||
|
||||
export async function fetchReleaseMetadata(
|
||||
metadataUrl: string | URL,
|
||||
options: UrlPolicy & { fetchImpl?: typeof fetch | undefined; maxBytes?: number | undefined } = {},
|
||||
options: UrlPolicy & UpdateFetchOptions = {},
|
||||
): Promise<ReleaseMetadata> {
|
||||
const fetchImpl = options.fetchImpl ?? fetch;
|
||||
let current = validateHttpsUrl(metadataUrl, options);
|
||||
const maxRedirects = options.maxRedirects ?? 3;
|
||||
let response: Response;
|
||||
for (let redirects = 0; ; redirects += 1) {
|
||||
const request = beginUpdateRequest(options);
|
||||
try {
|
||||
response = await fetchImpl(current, { method: "GET", redirect: "manual", headers: { accept: "application/json" } });
|
||||
response = await fetchImpl(current, { method: "GET", redirect: "manual", headers: { accept: "application/json" }, signal: request.signal });
|
||||
} catch {
|
||||
request.clear();
|
||||
throw metadataError();
|
||||
}
|
||||
if (response.status < 300 || response.status >= 400) break;
|
||||
if (response.status < 300 || response.status >= 400) {
|
||||
try {
|
||||
if (response.status < 200 || response.status >= 300) {
|
||||
await cancelResponseBody(response);
|
||||
throw metadataError();
|
||||
}
|
||||
const maxBytes = Math.min(options.maxBytes ?? DEFAULT_METADATA_MAX_BYTES, DEFAULT_METADATA_MAX_BYTES);
|
||||
const body = await readBoundedResponse(response, maxBytes, "更新发布信息过大", request.signal);
|
||||
const payload: unknown = JSON.parse(body.toString("utf8"));
|
||||
if (!payload || typeof payload !== "object") throw metadataError();
|
||||
const item = payload as Record<string, unknown>;
|
||||
const rawVersion = typeof item.version === "string" ? item.version : typeof item.tag_name === "string" ? item.tag_name : typeof item.tagName === "string" ? item.tagName : undefined;
|
||||
if (!rawVersion) throw metadataError();
|
||||
const version = parseSemver(rawVersion);
|
||||
if (typeof item.tag_name === "string" && compareSemver(version, item.tag_name) !== 0) throw metadataError();
|
||||
const assetsRaw = Array.isArray(item.assets) ? item.assets : [];
|
||||
const assets: ReleaseAsset[] = [];
|
||||
for (const raw of assetsRaw) {
|
||||
if (!raw || typeof raw !== "object") continue;
|
||||
const asset = raw as Record<string, unknown>;
|
||||
const name = typeof asset.name === "string" ? asset.name : undefined;
|
||||
const url = typeof asset.url === "string" ? asset.url : typeof asset.browser_download_url === "string" ? asset.browser_download_url : undefined;
|
||||
if (!name || !url) continue;
|
||||
let sha256: string | undefined;
|
||||
const digest = typeof asset.sha256 === "string" ? asset.sha256 : typeof asset.digest === "string" ? asset.digest : undefined;
|
||||
if (digest) {
|
||||
const candidate = digest.replace(/^sha256:/i, "").toLowerCase();
|
||||
if (/^[a-f0-9]{64}$/.test(candidate)) sha256 = candidate;
|
||||
}
|
||||
assets.push({ name, url: releaseResourceUrl(url, current, options), ...(sha256 ? { sha256 } : {}), ...(typeof asset.size === "number" && Number.isSafeInteger(asset.size) && asset.size >= 0 ? { size: asset.size } : {}) });
|
||||
}
|
||||
const notes = releaseNotesText(item.body ?? item.releaseNotes ?? item.release_notes ?? item.body_html);
|
||||
const releaseName = releaseNameText(item.name ?? item.releaseName);
|
||||
let releaseUrl: string | undefined;
|
||||
if (typeof item.html_url === "string" || typeof item.url === "string") {
|
||||
try { releaseUrl = releaseResourceUrl(typeof item.html_url === "string" ? item.html_url : item.url as string, current, options); } catch { /* optional */ }
|
||||
}
|
||||
return {
|
||||
version: `${version.major}.${version.minor}.${version.patch}${version.prerelease.length ? `-${version.prerelease.join(".")}` : ""}${version.build.length ? `+${version.build.join(".")}` : ""}`,
|
||||
...(typeof item.tag_name === "string" ? { tagName: item.tag_name } : {}), ...(releaseName ? { releaseName } : {}), ...(typeof item.published_at === "string" ? { publishedAt: item.published_at } : {}), ...(notes ? { notes } : {}), ...(releaseUrl ? { releaseUrl } : {}), assets,
|
||||
};
|
||||
} catch { throw metadataError(); }
|
||||
finally { request.clear(); }
|
||||
}
|
||||
await cancelResponseBody(response);
|
||||
request.clear();
|
||||
if (redirects >= maxRedirects) throw metadataError();
|
||||
const location = response.headers.get("location");
|
||||
if (!location) throw metadataError();
|
||||
current = validateHttpsUrl(new URL(location, current), options.baseUrl ? options : { ...options, baseUrl: current });
|
||||
}
|
||||
if (response.status < 200 || response.status >= 300) throw metadataError();
|
||||
let payload: unknown;
|
||||
try {
|
||||
const maxBytes = Math.min(options.maxBytes ?? DEFAULT_METADATA_MAX_BYTES, DEFAULT_METADATA_MAX_BYTES);
|
||||
const body = await readBoundedResponse(response, maxBytes, "更新发布信息过大");
|
||||
payload = JSON.parse(body.toString("utf8"));
|
||||
} catch { throw metadataError(); }
|
||||
if (!payload || typeof payload !== "object") throw metadataError();
|
||||
const item = payload as Record<string, unknown>;
|
||||
const rawVersion = typeof item.version === "string" ? item.version : typeof item.tag_name === "string" ? item.tag_name : typeof item.tagName === "string" ? item.tagName : undefined;
|
||||
if (!rawVersion) throw metadataError();
|
||||
const version = parseSemver(rawVersion);
|
||||
if (typeof item.tag_name === "string") {
|
||||
try {
|
||||
if (compareSemver(version, item.tag_name) !== 0) throw metadataError();
|
||||
} catch {
|
||||
throw metadataError();
|
||||
}
|
||||
}
|
||||
const assetsRaw = Array.isArray(item.assets) ? item.assets : [];
|
||||
const assets: ReleaseAsset[] = [];
|
||||
for (const raw of assetsRaw) {
|
||||
if (!raw || typeof raw !== "object") continue;
|
||||
const asset = raw as Record<string, unknown>;
|
||||
const name = typeof asset.name === "string" ? asset.name : undefined;
|
||||
const url = typeof asset.url === "string" ? asset.url : typeof asset.browser_download_url === "string" ? asset.browser_download_url : undefined;
|
||||
if (!name || !url) continue;
|
||||
let sha256: string | undefined;
|
||||
const digest = typeof asset.sha256 === "string" ? asset.sha256 : typeof asset.digest === "string" ? asset.digest : undefined;
|
||||
if (digest) {
|
||||
const candidate = digest.replace(/^sha256:/i, "").toLowerCase();
|
||||
if (/^[a-f0-9]{64}$/.test(candidate)) sha256 = candidate;
|
||||
}
|
||||
assets.push({ name, url: releaseResourceUrl(url, current, options), ...(sha256 ? { sha256 } : {}), ...(typeof asset.size === "number" && Number.isSafeInteger(asset.size) && asset.size >= 0 ? { size: asset.size } : {}) });
|
||||
}
|
||||
const notes = releaseNotesText(item.body ?? item.releaseNotes ?? item.release_notes ?? item.body_html);
|
||||
const releaseName = releaseNameText(item.name ?? item.releaseName);
|
||||
let releaseUrl: string | undefined;
|
||||
if (typeof item.html_url === "string" || typeof item.url === "string") {
|
||||
try {
|
||||
const candidate = typeof item.html_url === "string" ? item.html_url : item.url as string;
|
||||
releaseUrl = releaseResourceUrl(candidate, current, options);
|
||||
} catch { /* omit invalid optional release page URL */ }
|
||||
}
|
||||
return {
|
||||
version: `${version.major}.${version.minor}.${version.patch}${version.prerelease.length ? `-${version.prerelease.join(".")}` : ""}${version.build.length ? `+${version.build.join(".")}` : ""}`,
|
||||
...(typeof item.tag_name === "string" ? { tagName: item.tag_name } : {}),
|
||||
...(releaseName ? { releaseName } : {}),
|
||||
...(typeof item.published_at === "string" ? { publishedAt: item.published_at } : {}),
|
||||
...(notes ? { notes } : {}),
|
||||
...(releaseUrl ? { releaseUrl } : {}),
|
||||
assets,
|
||||
};
|
||||
}
|
||||
|
||||
/** Fetch a small text sidecar (for example SHA256SUMS) with the same
|
||||
* redirect, HTTPS and host policy used for release metadata. */
|
||||
export async function fetchReleaseText(
|
||||
textUrl: string | URL,
|
||||
options: UrlPolicy & { fetchImpl?: typeof fetch | undefined; maxBytes?: number | undefined } = {},
|
||||
options: UrlPolicy & UpdateFetchOptions = {},
|
||||
): Promise<string> {
|
||||
const fetchImpl = options.fetchImpl ?? fetch;
|
||||
let current = validateHttpsUrl(textUrl, options);
|
||||
@@ -328,27 +378,32 @@ export async function fetchReleaseText(
|
||||
const maxRedirects = options.maxRedirects ?? 3;
|
||||
let response: Response;
|
||||
for (let redirects = 0; ; redirects += 1) {
|
||||
const request = beginUpdateRequest(options);
|
||||
try {
|
||||
response = await fetchImpl(current, { method: "GET", redirect: "manual" });
|
||||
response = await fetchImpl(current, { method: "GET", redirect: "manual", signal: request.signal });
|
||||
} catch {
|
||||
request.clear();
|
||||
throw new Error("更新校验文件下载失败");
|
||||
}
|
||||
if (response.status < 300 || response.status >= 400) break;
|
||||
if (response.status < 300 || response.status >= 400) {
|
||||
if (response.status < 200 || response.status >= 300) { await cancelResponseBody(response); request.clear(); throw new Error("更新校验文件下载失败"); }
|
||||
const declared = Number(response.headers.get("content-length") ?? 0);
|
||||
const maxBytes = options.maxBytes ?? 1024 * 1024;
|
||||
if (declared > maxBytes) { await cancelResponseBody(response); request.clear(); throw new Error("更新校验文件过大"); }
|
||||
try {
|
||||
return (await readBoundedResponse(response, maxBytes, "更新校验文件过大", request.signal)).toString("utf8");
|
||||
} catch (error) {
|
||||
if (error instanceof Error && error.message === "更新校验文件过大") throw error;
|
||||
throw new Error("更新校验文件下载失败");
|
||||
} finally { request.clear(); }
|
||||
}
|
||||
await cancelResponseBody(response);
|
||||
request.clear();
|
||||
if (redirects >= maxRedirects) throw new Error("更新校验文件下载失败");
|
||||
const location = response.headers.get("location");
|
||||
if (!location) throw new Error("更新校验文件下载失败");
|
||||
current = validateHttpsUrl(new URL(location, current), redirectPolicy);
|
||||
}
|
||||
if (response.status < 200 || response.status >= 300) throw new Error("更新校验文件下载失败");
|
||||
const declared = Number(response.headers.get("content-length") ?? 0);
|
||||
const maxBytes = options.maxBytes ?? 1024 * 1024;
|
||||
if (declared > maxBytes) throw new Error("更新校验文件过大");
|
||||
try {
|
||||
return (await readBoundedResponse(response, maxBytes, "更新校验文件过大")).toString("utf8");
|
||||
} catch (error) {
|
||||
if (error instanceof Error && error.message === "更新校验文件过大") throw error;
|
||||
throw new Error("更新校验文件下载失败");
|
||||
}
|
||||
}
|
||||
|
||||
/** Fetch a bounded binary sidecar (for example an Ed25519 detached
|
||||
@@ -356,7 +411,7 @@ export async function fetchReleaseText(
|
||||
* this separate from fetchReleaseText. */
|
||||
export async function fetchReleaseBytes(
|
||||
bytesUrl: string | URL,
|
||||
options: UrlPolicy & { fetchImpl?: typeof fetch | undefined; maxBytes?: number | undefined } = {},
|
||||
options: UrlPolicy & UpdateFetchOptions = {},
|
||||
): Promise<Buffer> {
|
||||
const fetchImpl = options.fetchImpl ?? fetch;
|
||||
let current = validateHttpsUrl(bytesUrl, options);
|
||||
@@ -366,27 +421,32 @@ export async function fetchReleaseBytes(
|
||||
const maxRedirects = options.maxRedirects ?? 3;
|
||||
let response: Response;
|
||||
for (let redirects = 0; ; redirects += 1) {
|
||||
const request = beginUpdateRequest(options);
|
||||
try {
|
||||
response = await fetchImpl(current, { method: "GET", redirect: "manual" });
|
||||
response = await fetchImpl(current, { method: "GET", redirect: "manual", signal: request.signal });
|
||||
} catch {
|
||||
request.clear();
|
||||
throw new Error("更新签名下载失败");
|
||||
}
|
||||
if (response.status < 300 || response.status >= 400) break;
|
||||
if (response.status < 300 || response.status >= 400) {
|
||||
if (response.status < 200 || response.status >= 300) { await cancelResponseBody(response); request.clear(); throw new Error("更新签名下载失败"); }
|
||||
const declared = Number(response.headers.get("content-length") ?? 0);
|
||||
const maxBytes = options.maxBytes ?? 64 * 1024;
|
||||
if (declared > maxBytes) { await cancelResponseBody(response); request.clear(); throw new Error("更新签名文件过大"); }
|
||||
try {
|
||||
return await readBoundedResponse(response, maxBytes, "更新签名文件过大", request.signal);
|
||||
} catch (error) {
|
||||
if (error instanceof Error && error.message === "更新签名文件过大") throw error;
|
||||
throw new Error("更新签名下载失败");
|
||||
} finally { request.clear(); }
|
||||
}
|
||||
await cancelResponseBody(response);
|
||||
request.clear();
|
||||
if (redirects >= maxRedirects) throw new Error("更新签名下载失败");
|
||||
const location = response.headers.get("location");
|
||||
if (!location) throw new Error("更新签名下载失败");
|
||||
current = validateHttpsUrl(new URL(location, current), redirectPolicy);
|
||||
}
|
||||
if (response.status < 200 || response.status >= 300) throw new Error("更新签名下载失败");
|
||||
const declared = Number(response.headers.get("content-length") ?? 0);
|
||||
const maxBytes = options.maxBytes ?? 64 * 1024;
|
||||
if (declared > maxBytes) throw new Error("更新签名文件过大");
|
||||
try {
|
||||
return await readBoundedResponse(response, maxBytes, "更新签名文件过大");
|
||||
} catch (error) {
|
||||
if (error instanceof Error && error.message === "更新签名文件过大") throw error;
|
||||
throw new Error("更新签名下载失败");
|
||||
}
|
||||
}
|
||||
|
||||
export function selectReleaseAsset(release: ReleaseMetadata, platform = detectPlatform(), runtimeHash?: string): ReleaseAsset | undefined {
|
||||
@@ -413,9 +473,6 @@ export function selectReleaseAsset(release: ReleaseMetadata, platform = detectPl
|
||||
const applicationUpdate = candidates.find((asset) => applicationUpdateRuntimeHash(asset.name) === normalizedRuntimeHash);
|
||||
if (applicationUpdate) return applicationUpdate;
|
||||
}
|
||||
// Older clients choose the first matching asset. Releases therefore keep
|
||||
// the traditional full archive first, while current clients explicitly
|
||||
// opt into a compatible application-only asset.
|
||||
return candidates.find((asset) => !applicationUpdateRuntimeHash(asset.name));
|
||||
}
|
||||
|
||||
@@ -441,7 +498,7 @@ export async function verifySha256(filePath: string, expected: string): Promise<
|
||||
export async function downloadReleaseAsset(
|
||||
url: string | URL,
|
||||
destination: string,
|
||||
options: UrlPolicy & { fetchImpl?: typeof fetch | undefined; maxBytes?: number | undefined; onProgress?: ((downloadedBytes: number, totalBytes: number | null) => void) | undefined } = {},
|
||||
options: UrlPolicy & UpdateFetchOptions & { onProgress?: ((downloadedBytes: number, totalBytes: number | null) => void) | undefined } = {},
|
||||
): Promise<{ size: number; sha256: string }> {
|
||||
const fetchImpl = options.fetchImpl ?? fetch;
|
||||
let current = validateHttpsUrl(url, options);
|
||||
@@ -451,22 +508,32 @@ export async function downloadReleaseAsset(
|
||||
const maxRedirects = options.maxRedirects ?? 3;
|
||||
let response: Response;
|
||||
for (let redirects = 0; ; redirects += 1) {
|
||||
const request = beginUpdateRequest(options);
|
||||
try {
|
||||
response = await fetchImpl(current, { method: "GET", redirect: "manual" });
|
||||
response = await fetchImpl(current, { method: "GET", redirect: "manual", signal: request.signal });
|
||||
} catch {
|
||||
request.clear();
|
||||
throw new Error("更新文件下载失败");
|
||||
}
|
||||
if (response.status < 300 || response.status >= 400) break;
|
||||
if (response.status < 300 || response.status >= 400) { request.clear(); break; }
|
||||
await cancelResponseBody(response);
|
||||
request.clear();
|
||||
if (redirects >= maxRedirects) throw new Error("更新文件下载失败");
|
||||
const location = response.headers.get("location");
|
||||
if (!location) throw new Error("更新文件下载失败");
|
||||
current = validateHttpsUrl(new URL(location, current), redirectPolicy);
|
||||
}
|
||||
if (response.status < 200 || response.status >= 300 || !response.body) throw new Error("更新文件下载失败");
|
||||
if (response.status < 200 || response.status >= 300 || !response.body) {
|
||||
await cancelResponseBody(response);
|
||||
throw new Error("更新文件下载失败");
|
||||
}
|
||||
const declared = Number(response.headers.get("content-length") ?? 0);
|
||||
const totalBytes = Number.isSafeInteger(declared) && declared > 0 ? declared : null;
|
||||
const maxBytes = options.maxBytes ?? 512 * 1024 * 1024;
|
||||
if (declared > maxBytes) throw new Error("更新文件超过大小限制");
|
||||
if (declared > maxBytes) {
|
||||
await cancelResponseBody(response);
|
||||
throw new Error("更新文件超过大小限制");
|
||||
}
|
||||
await mkdir(path.dirname(destination), { recursive: true, mode: 0o700 });
|
||||
const temporary = `${destination}.part-${randomUUID()}`;
|
||||
let size = 0;
|
||||
@@ -478,8 +545,10 @@ export async function downloadReleaseAsset(
|
||||
hash.update(chunk);
|
||||
callback(null, chunk);
|
||||
} });
|
||||
const request = beginUpdateRequest(options);
|
||||
try {
|
||||
await pipeline(Readable.fromWeb(response.body as import("node:stream/web").ReadableStream), meter, createWriteStream(temporary, { flags: "wx", mode: 0o600 }));
|
||||
const source = Readable.fromWeb(response.body as import("node:stream/web").ReadableStream, { signal: request.signal });
|
||||
await pipeline(source, meter, createWriteStream(temporary, { flags: "wx", mode: 0o600 }));
|
||||
const fd = await open(temporary, "r");
|
||||
await fd.sync();
|
||||
await fd.close();
|
||||
@@ -487,6 +556,8 @@ export async function downloadReleaseAsset(
|
||||
} catch (error) {
|
||||
await import("node:fs/promises").then(({ rm }) => rm(temporary, { force: true })).catch(() => undefined);
|
||||
throw error instanceof Error && error.message.startsWith("更新文件") ? error : new Error("更新文件下载失败");
|
||||
} finally {
|
||||
request.clear();
|
||||
}
|
||||
return { size, sha256: hash.digest("hex") };
|
||||
}
|
||||
|
||||
+1
-1
@@ -107,7 +107,7 @@ export const updateApplySchema = z.object({
|
||||
|
||||
export const updateDownloadSchema = z.object({
|
||||
version: z.string().trim().regex(/^v?(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)(?:-(?:0|[1-9A-Za-z-][0-9A-Za-z-]*)(?:\.(?:0|[1-9A-Za-z-][0-9A-Za-z-]*))*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/),
|
||||
confirm: z.literal(true),
|
||||
confirm: z.boolean().default(true).optional(),
|
||||
}).strict();
|
||||
|
||||
export type ApiError = {
|
||||
|
||||
@@ -1,8 +1,5 @@
|
||||
[Unit]
|
||||
Description=TallyNote privileged release updater
|
||||
After=network-online.target
|
||||
Wants=network-online.target
|
||||
|
||||
[Service]
|
||||
Type=oneshot
|
||||
User=root
|
||||
@@ -11,10 +8,12 @@ WorkingDirectory=/opt/tallynote/current
|
||||
EnvironmentFile=-/etc/tallynote/tallynote.env
|
||||
ExecStart=/usr/local/libexec/tallynote-update-runner
|
||||
Environment=PATH=/usr/sbin:/usr/bin:/sbin:/bin
|
||||
# The runner consumes queued requests immediately and applies its own bounded
|
||||
# phase timeouts while keeping full CLI diagnostics in the runner log.
|
||||
# Downloads, archive validation and data backups can exceed systemd's 90s
|
||||
# default start timeout on a slower server. Keep one update job alive long
|
||||
# enough to finish or reach its own health-check/recovery path.
|
||||
TimeoutStartSec=30min
|
||||
TimeoutStartSec=32min
|
||||
NoNewPrivileges=true
|
||||
# Keep the updater compatible with the same Node/libuv interface discovery
|
||||
# path while retaining an explicit socket-family allowlist.
|
||||
|
||||
@@ -9,6 +9,7 @@ TALLYNOTE_TIMEZONE=Asia/Shanghai
|
||||
TALLYNOTE_UPDATE_STRATEGY=systemd
|
||||
TALLYNOTE_UPDATE_METADATA_URL=https://git.awaioi.com/api/v1/repos/awaioi/TallyNote/releases/latest
|
||||
TALLYNOTE_UPDATE_ALLOWED_HOSTS=git.awaioi.com
|
||||
TALLYNOTE_UPDATE_TIMEOUT_SECONDS=30
|
||||
TALLYNOTE_UPDATE_REQUIRE_SIGNATURE=false
|
||||
TALLYNOTE_UPDATE_CHECK_COOLDOWN_SECONDS=60
|
||||
TALLYNOTE_UPDATE_DOWNLOAD_COOLDOWN_SECONDS=15
|
||||
|
||||
+113
-37
@@ -59,10 +59,10 @@ describe("更新 API", () => {
|
||||
|
||||
function mockRelease() {
|
||||
const digest = "c".repeat(64);
|
||||
const asset = `tallynote-1.2.0-${detectPlatform().target}-glibc.tar.gz`;
|
||||
const asset = `tallynote-1.3.0-${detectPlatform().target}-glibc.tar.gz`;
|
||||
globalThis.fetch = (async (input: string | URL) => input.toString().endsWith("SHA256SUMS")
|
||||
? new Response(`${digest} ${asset}\n`, { status: 200 })
|
||||
: new Response(JSON.stringify({ tag_name: "v1.2.0", assets: [{ name: "SHA256SUMS", browser_download_url: "https://updates.example/SHA256SUMS" }, { name: asset, browser_download_url: `https://updates.example/${asset}` }] }), { status: 200 })) as typeof fetch;
|
||||
: new Response(JSON.stringify({ tag_name: "v1.3.0", assets: [{ name: "SHA256SUMS", browser_download_url: "https://updates.example/SHA256SUMS" }, { name: asset, browser_download_url: `https://updates.example/${asset}` }] }), { status: 200 })) as typeof fetch;
|
||||
}
|
||||
|
||||
it("检查 release、创建受保护请求文件并拒绝重复任务", async () => {
|
||||
@@ -70,7 +70,7 @@ describe("更新 API", () => {
|
||||
mockRelease();
|
||||
const checked = await app.inject({ method: "POST", url: "/api/update/check", headers: { origin: config.publicOrigin, cookie: session.cookies, "x-csrf-token": session.csrf }, payload: {} });
|
||||
expect(checked.statusCode).toBe(200);
|
||||
expect(checked.json().latest).toMatchObject({ version: "1.2.0", compatible: true, integrityReady: true, isNewer: true });
|
||||
expect(checked.json().latest).toMatchObject({ version: "1.3.0", compatible: true, integrityReady: true, isNewer: true });
|
||||
expect(checked.headers["cache-control"]).toBe("no-store");
|
||||
const tooSoon = await app.inject({ method: "POST", url: "/api/update/check", headers: { origin: config.publicOrigin, cookie: session.cookies, "x-csrf-token": session.csrf }, payload: {} });
|
||||
expect(tooSoon.statusCode).toBe(429);
|
||||
@@ -82,15 +82,15 @@ describe("更新 API", () => {
|
||||
const otherChecked = await app.inject({ method: "POST", url: "/api/update/check", headers: { origin: config.publicOrigin, cookie: otherSession.cookies, "x-csrf-token": otherSession.csrf }, payload: {} });
|
||||
expect(otherChecked.statusCode).toBe(200);
|
||||
|
||||
const applied = await app.inject({ method: "POST", url: "/api/update/apply", headers: { origin: config.publicOrigin, cookie: session.cookies, "x-csrf-token": session.csrf }, payload: { version: "1.2.0", confirm: true } });
|
||||
const applied = await app.inject({ method: "POST", url: "/api/update/apply", headers: { origin: config.publicOrigin, cookie: session.cookies, "x-csrf-token": session.csrf }, payload: { version: "1.3.0", confirm: true } });
|
||||
expect(applied.statusCode).toBe(202);
|
||||
const jobId = applied.json().job.id as string;
|
||||
const request = JSON.parse(readFileSync(config.updateRequestPath, "utf8")) as { jobId: string; expectedSha256: string; currentLink: string };
|
||||
expect(request).toMatchObject({ jobId, version: "1.2.0", expectedSha256: "c".repeat(64), currentLink: config.currentLink });
|
||||
expect(request).toMatchObject({ jobId, version: "1.3.0", expectedSha256: "c".repeat(64), currentLink: config.currentLink });
|
||||
expect(statSync(config.updateRequestPath).mode & 0o777).toBe(0o600);
|
||||
|
||||
mockRelease();
|
||||
const duplicate = await app.inject({ method: "POST", url: "/api/update/apply", headers: { origin: config.publicOrigin, cookie: session.cookies, "x-csrf-token": session.csrf }, payload: { version: "1.2.0", confirm: true } });
|
||||
const duplicate = await app.inject({ method: "POST", url: "/api/update/apply", headers: { origin: config.publicOrigin, cookie: session.cookies, "x-csrf-token": session.csrf }, payload: { version: "1.3.0", confirm: true } });
|
||||
expect(duplicate.statusCode).toBe(409);
|
||||
expect(duplicate.json().error.code).toBe("UPDATE_IN_PROGRESS");
|
||||
const status = await app.inject({ method: "GET", url: "/api/update/status", headers: { cookie: session.cookies } });
|
||||
@@ -104,10 +104,10 @@ describe("更新 API", () => {
|
||||
mockRelease();
|
||||
const checked = await app.inject({ method: "POST", url: "/api/update/check", headers: { origin: config.publicOrigin, cookie: session.cookies, "x-csrf-token": session.csrf }, payload: {} });
|
||||
expect(checked.statusCode).toBe(200);
|
||||
const downloaded = await app.inject({ method: "POST", url: "/api/update/download", headers: { origin: config.publicOrigin, cookie: session.cookies, "x-csrf-token": session.csrf }, payload: { version: "1.2.0", confirm: true } });
|
||||
const downloaded = await app.inject({ method: "POST", url: "/api/update/download", headers: { origin: config.publicOrigin, cookie: session.cookies, "x-csrf-token": session.csrf }, payload: { version: "1.3.0", confirm: true } });
|
||||
expect(downloaded.statusCode).toBe(202);
|
||||
const downloadJobId = downloaded.json().job.id as string;
|
||||
expect(downloaded.json().job).toMatchObject({ operation: "download", status: "queued", version: "1.2.0" });
|
||||
expect(downloaded.json().job).toMatchObject({ operation: "download", status: "queued", version: "1.3.0" });
|
||||
const downloadRequest = JSON.parse(readFileSync(config.updateRequestPath, "utf8")) as { jobId: string; operation: string };
|
||||
expect(downloadRequest).toMatchObject({ jobId: downloadJobId, operation: "download" });
|
||||
expect(database.sqlite.prepare("SELECT operation, status FROM update_jobs WHERE id=?").get(downloadJobId)).toEqual({ operation: "download", status: "queued" });
|
||||
@@ -116,21 +116,21 @@ describe("更新 API", () => {
|
||||
const stagedId = randomUUID();
|
||||
const now = Date.now();
|
||||
database.sqlite.prepare(`INSERT INTO update_jobs(id, admin_id, session_hash, request_id, requested_at, operation, status, version, platform, release_url, asset_name, asset_url, expected_sha256, actual_sha256, download_path, created_at, updated_at) VALUES (?, ?, ?, ?, ?, 'download', 'staged', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)
|
||||
.run(stagedId, (await database.sqlite.prepare("SELECT id FROM admins WHERE username=?").get("update-staged") as { id: string }).id, "session", "staged-request", now, "1.2.0", detectPlatform().target, config.updateMetadataUrl, "release.tar.gz", "https://updates.example/release.tar.gz", "c".repeat(64), "c".repeat(64), path.join(config.dataDir, "staged-workspace"), now, now);
|
||||
const applied = await app.inject({ method: "POST", url: "/api/update/apply", headers: { origin: config.publicOrigin, cookie: session.cookies, "x-csrf-token": session.csrf }, payload: { jobId: stagedId, version: "1.2.0", confirm: true } });
|
||||
.run(stagedId, (await database.sqlite.prepare("SELECT id FROM admins WHERE username=?").get("update-staged") as { id: string }).id, "session", "staged-request", now, "1.3.0", detectPlatform().target, config.updateMetadataUrl, "release.tar.gz", "https://updates.example/release.tar.gz", "c".repeat(64), "c".repeat(64), path.join(config.dataDir, "staged-workspace"), now, now);
|
||||
const applied = await app.inject({ method: "POST", url: "/api/update/apply", headers: { origin: config.publicOrigin, cookie: session.cookies, "x-csrf-token": session.csrf }, payload: { jobId: stagedId, version: "1.3.0", confirm: true } });
|
||||
expect(applied.statusCode).toBe(202);
|
||||
expect(applied.json().job).toMatchObject({ id: stagedId, operation: "apply", status: "staged" });
|
||||
expect(database.sqlite.prepare("SELECT operation, status FROM update_jobs WHERE id=?").get(stagedId)).toEqual({ operation: "apply", status: "staged" });
|
||||
const applyRequest = JSON.parse(readFileSync(config.updateRequestPath, "utf8")) as { jobId: string; operation: string; assetUrl: string; expectedSha256: string };
|
||||
expect(applyRequest).toMatchObject({ jobId: stagedId, operation: "apply", assetUrl: "https://updates.example/release.tar.gz", expectedSha256: "c".repeat(64) });
|
||||
const duplicate = await app.inject({ method: "POST", url: "/api/update/apply", headers: { origin: config.publicOrigin, cookie: session.cookies, "x-csrf-token": session.csrf }, payload: { jobId: stagedId, version: "1.2.0", confirm: true } });
|
||||
const duplicate = await app.inject({ method: "POST", url: "/api/update/apply", headers: { origin: config.publicOrigin, cookie: session.cookies, "x-csrf-token": session.csrf }, payload: { jobId: stagedId, version: "1.3.0", confirm: true } });
|
||||
expect(duplicate.statusCode).toBe(409);
|
||||
expect(duplicate.json().error.code).toBe("UPDATE_IN_PROGRESS");
|
||||
});
|
||||
|
||||
it("缺少确认或未启用 systemd 时不接受更新", async () => {
|
||||
const session = await login();
|
||||
const invalid = await app.inject({ method: "POST", url: "/api/update/apply", headers: { origin: config.publicOrigin, cookie: session.cookies, "x-csrf-token": session.csrf }, payload: { version: "1.2.0" } });
|
||||
const invalid = await app.inject({ method: "POST", url: "/api/update/apply", headers: { origin: config.publicOrigin, cookie: session.cookies, "x-csrf-token": session.csrf }, payload: { version: "1.3.0" } });
|
||||
expect(invalid.statusCode).toBe(400);
|
||||
process.env.TALLYNOTE_UPDATE_STRATEGY = "disabled";
|
||||
const disabledConfig = loadConfig();
|
||||
@@ -152,7 +152,54 @@ describe("更新 API", () => {
|
||||
mockRelease();
|
||||
const checked = await app.inject({ method: "POST", url: "/api/update/check", headers: { origin: config.publicOrigin, cookie: session.cookies, "x-csrf-token": session.csrf }, payload: {} });
|
||||
expect(checked.statusCode).toBe(200);
|
||||
expect(checked.json().latest).toMatchObject({ version: "1.2.0", isNewer: true });
|
||||
expect(checked.json().latest).toMatchObject({ version: "1.3.0", isNewer: true });
|
||||
});
|
||||
|
||||
it("不会应用已经等于当前版本的暂存更新", async () => {
|
||||
const session = await login("update-staged-current");
|
||||
const admin = database.sqlite.prepare("SELECT id FROM admins WHERE username=?").get("update-staged-current") as { id: string };
|
||||
const now = Date.now();
|
||||
const stagedId = randomUUID();
|
||||
database.sqlite.prepare(`
|
||||
INSERT INTO update_jobs(
|
||||
id, admin_id, operation, status, version, platform, release_url,
|
||||
asset_name, asset_url, expected_sha256, actual_sha256, download_path,
|
||||
created_at, updated_at
|
||||
) VALUES (?, ?, 'download', 'staged', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
`).run(
|
||||
stagedId,
|
||||
admin.id,
|
||||
config.appVersion,
|
||||
detectPlatform().target,
|
||||
config.updateMetadataUrl,
|
||||
"current.tar.gz",
|
||||
"https://updates.example/current.tar.gz",
|
||||
"c".repeat(64),
|
||||
"c".repeat(64),
|
||||
path.join(config.dataDir, "staged-current"),
|
||||
now,
|
||||
now,
|
||||
);
|
||||
|
||||
const apply = await app.inject({
|
||||
method: "POST",
|
||||
url: "/api/update/apply",
|
||||
headers: { origin: config.publicOrigin, cookie: session.cookies, "x-csrf-token": session.csrf },
|
||||
payload: { jobId: stagedId, version: config.appVersion, confirm: true },
|
||||
});
|
||||
expect(apply.statusCode).toBe(409);
|
||||
// Reconciliation expires same-version staged jobs before the apply route
|
||||
// can consume them, so the public response is the generic not-staged
|
||||
// conflict while the database records the precise expiry reason.
|
||||
expect(apply.json().error.code).toBe("UPDATE_NOT_STAGED");
|
||||
expect(database.sqlite.prepare("SELECT status, error_message AS errorMessage FROM update_jobs WHERE id=?").get(stagedId)).toEqual({
|
||||
status: "failed",
|
||||
errorMessage: "暂存更新已过期,当前版本无需再次升级",
|
||||
});
|
||||
|
||||
const status = await app.inject({ method: "GET", url: "/api/update/status", headers: { cookie: session.cookies } });
|
||||
expect(status.statusCode).toBe(200);
|
||||
expect(status.json().job).toBeNull();
|
||||
});
|
||||
|
||||
it("更新任务只对发起管理员可见,并隐藏内部错误详情", async () => {
|
||||
@@ -161,7 +208,7 @@ describe("更新 API", () => {
|
||||
mockRelease();
|
||||
const checked = await app.inject({ method: "POST", url: "/api/update/check", headers: { origin: config.publicOrigin, cookie: owner.cookies, "x-csrf-token": owner.csrf }, payload: {} });
|
||||
expect(checked.statusCode).toBe(200);
|
||||
const applied = await app.inject({ method: "POST", url: "/api/update/apply", headers: { origin: config.publicOrigin, cookie: owner.cookies, "x-csrf-token": owner.csrf }, payload: { version: "1.2.0", confirm: true } });
|
||||
const applied = await app.inject({ method: "POST", url: "/api/update/apply", headers: { origin: config.publicOrigin, cookie: owner.cookies, "x-csrf-token": owner.csrf }, payload: { version: "1.3.0", confirm: true } });
|
||||
expect(applied.statusCode).toBe(202);
|
||||
const jobId = applied.json().job.id as string;
|
||||
database.sqlite.prepare("UPDATE update_jobs SET error_message=? WHERE id=?").run("/var/lib/tallynote/secret-command-output", jobId);
|
||||
@@ -176,10 +223,46 @@ describe("更新 API", () => {
|
||||
expect(ownDetail.json().job.errorMessage).toBe("更新失败,请查看服务器日志或重试");
|
||||
});
|
||||
|
||||
it("取消任务按管理员隔离,并只删除匹配任务的请求文件", async () => {
|
||||
const owner = await login("cancel-owner");
|
||||
const other = await login("cancel-other");
|
||||
const ownerId = (database.sqlite.prepare("SELECT id FROM admins WHERE username=?").get("cancel-owner") as { id: string }).id;
|
||||
const otherId = (database.sqlite.prepare("SELECT id FROM admins WHERE username=?").get("cancel-other") as { id: string }).id;
|
||||
const now = Date.now();
|
||||
const ownerJobId = randomUUID();
|
||||
const otherJobId = randomUUID();
|
||||
const insert = database.sqlite.prepare(`
|
||||
INSERT INTO update_jobs(id, admin_id, operation, status, version, platform, asset_url, created_at, updated_at)
|
||||
VALUES (?, ?, 'download', 'queued', '1.3.0', ?, 'https://updates.example/update.tar.gz', ?, ?)
|
||||
`);
|
||||
insert.run(ownerJobId, ownerId, detectPlatform().target, now, now);
|
||||
insert.run(otherJobId, otherId, detectPlatform().target, now + 1, now + 1);
|
||||
await import("node:fs/promises").then(({ writeFile }) => writeFile(config.updateRequestPath, JSON.stringify({ jobId: otherJobId }), { encoding: "utf8", mode: 0o600 }));
|
||||
|
||||
const ownerCancel = await app.inject({
|
||||
method: "POST", url: "/api/update/cancel",
|
||||
headers: { origin: config.publicOrigin, cookie: owner.cookies, "x-csrf-token": owner.csrf },
|
||||
payload: { jobId: ownerJobId },
|
||||
});
|
||||
expect(ownerCancel.statusCode).toBe(200);
|
||||
expect((database.sqlite.prepare("SELECT status FROM update_jobs WHERE id=?").get(ownerJobId) as { status: string }).status).toBe("cancelled");
|
||||
expect((database.sqlite.prepare("SELECT status FROM update_jobs WHERE id=?").get(otherJobId) as { status: string }).status).toBe("queued");
|
||||
expect(existsSync(config.updateRequestPath)).toBe(true);
|
||||
|
||||
const otherCancel = await app.inject({
|
||||
method: "POST", url: "/api/update/cancel",
|
||||
headers: { origin: config.publicOrigin, cookie: other.cookies, "x-csrf-token": other.csrf },
|
||||
payload: {},
|
||||
});
|
||||
expect(otherCancel.statusCode).toBe(200);
|
||||
expect((database.sqlite.prepare("SELECT status FROM update_jobs WHERE id=?").get(otherJobId) as { status: string }).status).toBe("cancelled");
|
||||
expect(existsSync(config.updateRequestPath)).toBe(false);
|
||||
});
|
||||
|
||||
it("应用前重新校验失败时写入失败审计", async () => {
|
||||
const session = await login("update-audit");
|
||||
globalThis.fetch = (async () => new Response("upstream unavailable", { status: 503 })) as typeof fetch;
|
||||
const response = await app.inject({ method: "POST", url: "/api/update/apply", headers: { origin: config.publicOrigin, cookie: session.cookies, "x-csrf-token": session.csrf }, payload: { version: "1.2.0", confirm: true } });
|
||||
const response = await app.inject({ method: "POST", url: "/api/update/apply", headers: { origin: config.publicOrigin, cookie: session.cookies, "x-csrf-token": session.csrf }, payload: { version: "1.3.0", confirm: true } });
|
||||
expect(response.statusCode).toBe(502);
|
||||
// A failed upstream check must not reserve the per-admin cooldown; an
|
||||
// operator can retry immediately after fixing the release endpoint.
|
||||
@@ -191,7 +274,7 @@ describe("更新 API", () => {
|
||||
expect(audit?.outcome).toBe("failure");
|
||||
});
|
||||
|
||||
it("应用内直接执行流式下载,并在校验解包后自动推进到 staged 就绪状态", async () => {
|
||||
it("下载请求交由 systemd runner 接管,并保留可查询的排队状态", async () => {
|
||||
const { createSafeArchive } = await import("../server/update.js");
|
||||
const { createHash } = await import("node:crypto");
|
||||
const { mkdirSync, writeFileSync } = await import("node:fs");
|
||||
@@ -204,7 +287,7 @@ describe("更新 API", () => {
|
||||
|
||||
const archiveBytes = readFileSync(archivePath);
|
||||
const digest = createHash("sha256").update(archiveBytes).digest("hex");
|
||||
const assetName = `tallynote-1.2.0-${detectPlatform().target}-glibc.tar.gz`;
|
||||
const assetName = `tallynote-1.3.0-${detectPlatform().target}-glibc.tar.gz`;
|
||||
|
||||
globalThis.fetch = (async (input: string | URL) => {
|
||||
const url = input.toString();
|
||||
@@ -215,7 +298,7 @@ describe("更新 API", () => {
|
||||
return new Response(archiveBytes, { status: 200, headers: { "content-length": String(archiveBytes.length) } });
|
||||
}
|
||||
return new Response(JSON.stringify({
|
||||
tag_name: "v1.2.0",
|
||||
tag_name: "v1.3.0",
|
||||
assets: [
|
||||
{ name: "SHA256SUMS", browser_download_url: "https://updates.example/SHA256SUMS" },
|
||||
{ name: assetName, browser_download_url: `https://updates.example/${assetName}` }
|
||||
@@ -227,27 +310,20 @@ describe("更新 API", () => {
|
||||
const checked = await app.inject({ method: "POST", url: "/api/update/check", headers: { origin: config.publicOrigin, cookie: session.cookies, "x-csrf-token": session.csrf }, payload: {} });
|
||||
expect(checked.statusCode).toBe(200);
|
||||
|
||||
const downloaded = await app.inject({ method: "POST", url: "/api/update/download", headers: { origin: config.publicOrigin, cookie: session.cookies, "x-csrf-token": session.csrf }, payload: { version: "1.2.0", confirm: true } });
|
||||
const downloaded = await app.inject({ method: "POST", url: "/api/update/download", headers: { origin: config.publicOrigin, cookie: session.cookies, "x-csrf-token": session.csrf }, payload: { version: "1.3.0", confirm: true } });
|
||||
expect(downloaded.statusCode).toBe(202);
|
||||
const downloadJobId = downloaded.json().job.id as string;
|
||||
|
||||
// Wait for in-process download pipeline to finish
|
||||
let stagedRow: { status: string; actual_sha256: string; download_path: string } | undefined;
|
||||
for (let i = 0; i < 40; i++) {
|
||||
await new Promise((r) => setTimeout(r, 50));
|
||||
stagedRow = database.sqlite.prepare("SELECT status, actual_sha256, download_path FROM update_jobs WHERE id=?").get(downloadJobId) as any;
|
||||
if (stagedRow?.status === "staged" || stagedRow?.status === "failed") break;
|
||||
}
|
||||
|
||||
expect(stagedRow?.status).toBe("staged");
|
||||
expect(stagedRow?.actual_sha256).toBe(digest);
|
||||
expect(existsSync(path.join(stagedRow!.download_path, "payload", "dist", "server.js"))).toBe(true);
|
||||
const stagedRow = database.sqlite.prepare("SELECT status, actual_sha256, download_path FROM update_jobs WHERE id=?").get(downloadJobId) as any;
|
||||
expect(stagedRow?.status).toBe("queued");
|
||||
expect(stagedRow?.actual_sha256).toBeNull();
|
||||
expect(stagedRow?.download_path).toBeNull();
|
||||
|
||||
const statusRes = await app.inject({ method: "GET", url: "/api/update/status", headers: { cookie: session.cookies } });
|
||||
expect(statusRes.statusCode).toBe(200);
|
||||
expect(statusRes.json().job).toMatchObject({
|
||||
id: downloadJobId,
|
||||
status: "staged",
|
||||
status: "queued",
|
||||
operation: "download",
|
||||
assetName,
|
||||
assetUrl: `https://updates.example/${assetName}`,
|
||||
@@ -258,7 +334,7 @@ describe("更新 API", () => {
|
||||
});
|
||||
|
||||
|
||||
it("管理员可在流式下载进行中主动取消并中止下载", async () => {
|
||||
it("管理员可取消 systemd 下载任务并清理请求文件", async () => {
|
||||
const { createSafeArchive } = await import("../server/update.js");
|
||||
const { createHash } = await import("node:crypto");
|
||||
const { mkdirSync, writeFileSync } = await import("node:fs");
|
||||
@@ -271,7 +347,7 @@ describe("更新 API", () => {
|
||||
|
||||
const archiveBytes = readFileSync(archivePath);
|
||||
const digest = createHash("sha256").update(archiveBytes).digest("hex");
|
||||
const assetName = `tallynote-1.2.0-${detectPlatform().target}-glibc.tar.gz`;
|
||||
const assetName = `tallynote-1.3.0-${detectPlatform().target}-glibc.tar.gz`;
|
||||
|
||||
// Mock a slow stream
|
||||
let fetchAborted = false;
|
||||
@@ -298,7 +374,7 @@ describe("更新 API", () => {
|
||||
return new Response(stream, { status: 200, headers: { "content-length": String(archiveBytes.length) } });
|
||||
}
|
||||
return new Response(JSON.stringify({
|
||||
tag_name: "v1.2.0",
|
||||
tag_name: "v1.3.0",
|
||||
assets: [
|
||||
{ name: "SHA256SUMS", browser_download_url: "https://updates.example/SHA256SUMS" },
|
||||
{ name: assetName, browser_download_url: `https://updates.example/${assetName}` }
|
||||
@@ -309,7 +385,7 @@ describe("更新 API", () => {
|
||||
const session = await login("update-cancel-inprocess");
|
||||
await app.inject({ method: "POST", url: "/api/update/check", headers: { origin: config.publicOrigin, cookie: session.cookies, "x-csrf-token": session.csrf }, payload: {} });
|
||||
|
||||
const downloaded = await app.inject({ method: "POST", url: "/api/update/download", headers: { origin: config.publicOrigin, cookie: session.cookies, "x-csrf-token": session.csrf }, payload: { version: "1.2.0", confirm: true } });
|
||||
const downloaded = await app.inject({ method: "POST", url: "/api/update/download", headers: { origin: config.publicOrigin, cookie: session.cookies, "x-csrf-token": session.csrf }, payload: { version: "1.3.0", confirm: true } });
|
||||
const downloadJobId = downloaded.json().job.id as string;
|
||||
|
||||
// Wait until status becomes downloading
|
||||
@@ -331,7 +407,7 @@ describe("更新 API", () => {
|
||||
|
||||
const cancelledRow = database.sqlite.prepare("SELECT status FROM update_jobs WHERE id=?").get(downloadJobId) as any;
|
||||
expect(cancelledRow?.status).toBe("cancelled");
|
||||
expect(fetchAborted).toBe(true);
|
||||
expect(fetchAborted).toBe(false);
|
||||
|
||||
rmSync(payloadSource, { recursive: true, force: true });
|
||||
rmSync(archivePath, { force: true });
|
||||
@@ -341,7 +417,7 @@ describe("更新 API", () => {
|
||||
const session = await login("update-cancel");
|
||||
mockRelease();
|
||||
await app.inject({ method: "POST", url: "/api/update/check", headers: { origin: config.publicOrigin, cookie: session.cookies, "x-csrf-token": session.csrf }, payload: {} });
|
||||
const applied = await app.inject({ method: "POST", url: "/api/update/apply", headers: { origin: config.publicOrigin, cookie: session.cookies, "x-csrf-token": session.csrf }, payload: { version: "1.2.0", confirm: true } });
|
||||
const applied = await app.inject({ method: "POST", url: "/api/update/apply", headers: { origin: config.publicOrigin, cookie: session.cookies, "x-csrf-token": session.csrf }, payload: { version: "1.3.0", confirm: true } });
|
||||
expect(applied.statusCode).toBe(202);
|
||||
expect(existsSync(config.updateRequestPath)).toBe(true);
|
||||
|
||||
|
||||
+46
-25
@@ -40,23 +40,23 @@ describe("更新安全工具", () => {
|
||||
expect(isNewerVersion("1.0.0", "1.0.0-beta.1")).toBe(false);
|
||||
expect(detectPlatform("linux", "x86_64").target).toBe("linux-x64");
|
||||
const release = {
|
||||
version: "1.2.0",
|
||||
version: "1.3.0",
|
||||
assets: [
|
||||
{ name: "tallynote-1.2.0-linux-arm64-glibc.tar.gz", url: "https://updates.example/arm" },
|
||||
{ name: "tallynote-1.2.0-linux-x64-glibc.tar.gz", url: "https://updates.example/x64" },
|
||||
{ name: "tallynote-1.3.0-linux-arm64-glibc.tar.gz", url: "https://updates.example/arm" },
|
||||
{ name: "tallynote-1.3.0-linux-x64-glibc.tar.gz", url: "https://updates.example/x64" },
|
||||
],
|
||||
};
|
||||
expect(selectReleaseAsset(release, detectPlatform("linux", "x86_64"))?.name).toContain("linux-x64");
|
||||
expect(selectReleaseAsset({ version: "1.2.0", assets: [{ name: "tallynote-1.2.0-linux-arm64-glibc.tar.gz", url: "https://updates.example/arm" }] }, detectPlatform("linux", "x86_64"))).toBeUndefined();
|
||||
expect(selectReleaseAsset({ version: "1.3.0", assets: [{ name: "tallynote-1.3.0-linux-arm64-glibc.tar.gz", url: "https://updates.example/arm" }] }, detectPlatform("linux", "x86_64"))).toBeUndefined();
|
||||
expect(() => validateHttpsUrl("http://updates.example/x64", { allowedHosts: ["updates.example"] })).toThrow();
|
||||
expect(() => sanitizeAssetName("../release.tar.gz")).toThrow();
|
||||
});
|
||||
|
||||
it("优先选择运行时匹配的轻量更新包,并对旧客户端保留完整包回退", () => {
|
||||
const runtimeHash = runtimeHashFromLockfile("lockfile-v1\n");
|
||||
const full = { name: "tallynote-1.2.0-linux-x64-glibc.tar.gz", url: "https://updates.example/full" };
|
||||
const app = { name: `tallynote-1.2.0-linux-x64-glibc.update-${runtimeHash}.tar.gz`, url: "https://updates.example/app" };
|
||||
const release = { version: "1.2.0", assets: [full, app] };
|
||||
const full = { name: "tallynote-1.3.0-linux-x64-glibc.tar.gz", url: "https://updates.example/full" };
|
||||
const app = { name: `tallynote-1.3.0-linux-x64-glibc.update-${runtimeHash}.tar.gz`, url: "https://updates.example/app" };
|
||||
const release = { version: "1.3.0", assets: [full, app] };
|
||||
expect(applicationUpdateRuntimeHash(app.name)).toBe(runtimeHash);
|
||||
expect(selectReleaseAsset(release, detectPlatform("linux", "x86_64"), runtimeHash)).toEqual(app);
|
||||
expect(selectReleaseAsset(release, detectPlatform("linux", "x86_64"))).toEqual(full);
|
||||
@@ -102,12 +102,12 @@ describe("更新安全工具", () => {
|
||||
globalThis.fetch = (async (input: string | URL) => {
|
||||
const url = input.toString();
|
||||
if (url.endsWith("/latest")) {
|
||||
return new Response(JSON.stringify({ tag_name: "v1.2.0", assets: [{ name: "SHA256SUMS", browser_download_url: "https://updates.example/SHA256SUMS" }, { name: "app-linux-x64.tar.gz", browser_download_url: "https://updates.example/app-linux-x64.tar.gz" }] }), { status: 200, headers: { "content-type": "application/json" } });
|
||||
return new Response(JSON.stringify({ tag_name: "v1.3.0", assets: [{ name: "SHA256SUMS", browser_download_url: "https://updates.example/SHA256SUMS" }, { name: "app-linux-x64.tar.gz", browser_download_url: "https://updates.example/app-linux-x64.tar.gz" }] }), { status: 200, headers: { "content-type": "application/json" } });
|
||||
}
|
||||
return new Response(`${digest} app-linux-x64.tar.gz\n`, { status: 200 });
|
||||
}) as typeof fetch;
|
||||
const metadata = await fetchReleaseMetadata("https://updates.example/latest", { allowedHosts: ["updates.example"] });
|
||||
expect(metadata.version).toBe("1.2.0");
|
||||
expect(metadata.version).toBe("1.3.0");
|
||||
expect((await fetchReleaseText("https://updates.example/SHA256SUMS", { allowedHosts: ["updates.example"] })).trim()).toContain(digest);
|
||||
});
|
||||
|
||||
@@ -253,22 +253,22 @@ describe("更新安全工具", () => {
|
||||
const jobId = randomUUID();
|
||||
database = openDatabase(config);
|
||||
const now = Date.now();
|
||||
const assetName = `tallynote-1.2.0-${detectPlatform().target}.tar.gz`;
|
||||
const assetName = `tallynote-1.3.0-${detectPlatform().target}.tar.gz`;
|
||||
database.sqlite.prepare(`
|
||||
INSERT INTO update_jobs(id, operation, status, version, platform, asset_url,
|
||||
expected_sha256, created_at, updated_at, requested_at)
|
||||
VALUES (?, 'apply', 'queued', '1.2.0', ?, ?, ?, ?, ?, ?)
|
||||
VALUES (?, 'apply', 'queued', '1.3.0', ?, ?, ?, ?, ?, ?)
|
||||
`).run(jobId, detectPlatform().target, "https://updates.example/" + assetName, digest, now, now, now);
|
||||
globalThis.fetch = (async (input: string | URL) => {
|
||||
const url = input.toString();
|
||||
if (url.endsWith("/latest")) return new Response(JSON.stringify({ tag_name: "v1.2.0", assets: [{ name: assetName, browser_download_url: `https://updates.example/${assetName}` }, { name: "SHA256SUMS", browser_download_url: "https://updates.example/SHA256SUMS" }] }));
|
||||
if (url.endsWith("/latest")) return new Response(JSON.stringify({ tag_name: "v1.3.0", assets: [{ name: assetName, browser_download_url: `https://updates.example/${assetName}` }, { name: "SHA256SUMS", browser_download_url: "https://updates.example/SHA256SUMS" }] }));
|
||||
if (url.endsWith("SHA256SUMS")) return new Response(`${digest} ${assetName}\n`);
|
||||
return new Response(bytes, { headers: { "content-length": String(bytes.length) } });
|
||||
}) as typeof fetch;
|
||||
|
||||
await runUpdate({
|
||||
metadataUrl: config.updateMetadataUrl,
|
||||
version: "1.2.0",
|
||||
version: "1.3.0",
|
||||
currentVersion: config.appVersion,
|
||||
currentDir: config.currentLink,
|
||||
stagingDir: path.join(root, "staging"),
|
||||
@@ -286,8 +286,27 @@ describe("更新安全工具", () => {
|
||||
expect(await readFile(path.join(config.currentLink, "dist", "marker"), "utf8")).toBe("new");
|
||||
const row = database.sqlite.prepare("SELECT operation, status FROM update_jobs WHERE id=?").get(jobId);
|
||||
expect(row).toEqual({ operation: "apply", status: "applying" });
|
||||
finalizeUpdateJob(database.sqlite, jobId, "failed");
|
||||
expect(database.sqlite.prepare("SELECT status FROM update_jobs WHERE id=?").get(jobId)).toEqual({ status: "failed" });
|
||||
finalizeUpdateJob(database.sqlite, jobId, "failed", "健康检查失败(自定义)");
|
||||
expect(database.sqlite.prepare("SELECT status, error_message AS errorMessage FROM update_jobs WHERE id=?").get(jobId)).toEqual({ status: "failed", errorMessage: "健康检查失败(自定义)" });
|
||||
finalizeUpdateJob(database.sqlite, jobId, "failed", "第二次 finalize 不应覆盖原消息");
|
||||
expect(database.sqlite.prepare("SELECT status, error_message AS errorMessage FROM update_jobs WHERE id=?").get(jobId)).toEqual({ status: "failed", errorMessage: "健康检查失败(自定义)" });
|
||||
expect(database.sqlite.prepare("SELECT COUNT(*) AS count FROM audit_events WHERE action='update.failed' AND target_id=?").get(jobId)).toEqual({ count: 1 });
|
||||
const defaultJobId = randomUUID();
|
||||
database.sqlite.prepare(`
|
||||
INSERT INTO update_jobs(id, operation, status, version, platform, asset_url, created_at, updated_at)
|
||||
VALUES (?, 'apply', 'applying', '1.3.0', ?, ?, ?, ?)
|
||||
`).run(defaultJobId, detectPlatform().target, "https://updates.example/" + assetName, now, now);
|
||||
finalizeUpdateJob(database.sqlite, defaultJobId, "failed", "");
|
||||
expect(database.sqlite.prepare("SELECT error_message AS errorMessage FROM update_jobs WHERE id=?").get(defaultJobId)).toEqual({ errorMessage: "新版本健康检查失败,已恢复上一版本" });
|
||||
const completedJobId = randomUUID();
|
||||
database.sqlite.prepare(`
|
||||
INSERT INTO update_jobs(id, operation, status, version, platform, asset_url, created_at, updated_at)
|
||||
VALUES (?, 'apply', 'completed', '1.3.0', ?, ?, ?, ?)
|
||||
`).run(completedJobId, detectPlatform().target, "https://updates.example/" + assetName, now, now);
|
||||
finalizeUpdateJob(database.sqlite, completedJobId, "completed");
|
||||
expect(database.sqlite.prepare("SELECT COUNT(*) AS count FROM audit_events WHERE action='update.completed' AND target_id=?").get(completedJobId)).toEqual({ count: 0 });
|
||||
expect(() => finalizeUpdateJob(database.sqlite, completedJobId, "failed", "不能降级已完成任务")).toThrow("更新任务状态不允许完成");
|
||||
expect(database.sqlite.prepare("SELECT status FROM update_jobs WHERE id=?").get(completedJobId)).toEqual({ status: "completed" });
|
||||
} finally {
|
||||
globalThis.fetch = previousFetch;
|
||||
if (database) database.sqlite.close();
|
||||
@@ -323,10 +342,10 @@ describe("更新安全工具", () => {
|
||||
const applyingId = randomUUID();
|
||||
const stagedId = randomUUID();
|
||||
const stagedApplyId = randomUUID();
|
||||
insert.run(queuedId, "apply", "queued", "1.2.0", "linux-x64", "https://updates.example/queued.tar.gz", staleAt, staleAt);
|
||||
insert.run(queuedId, "apply", "queued", "1.3.0", "linux-x64", "https://updates.example/queued.tar.gz", staleAt, staleAt);
|
||||
insert.run(applyingId, "apply", "applying", config.appVersion, "linux-x64", "https://updates.example/applying.tar.gz", staleAt, staleAt);
|
||||
insert.run(stagedId, "download", "staged", "1.2.0", "linux-x64", "https://updates.example/staged.tar.gz", staleAt, staleAt);
|
||||
insert.run(stagedApplyId, "apply", "staged", "1.2.0", "linux-x64", "https://updates.example/staged-apply.tar.gz", staleAt, staleAt);
|
||||
insert.run(stagedId, "download", "staged", "1.3.0", "linux-x64", "https://updates.example/staged.tar.gz", staleAt, staleAt);
|
||||
insert.run(stagedApplyId, "apply", "staged", "1.3.0", "linux-x64", "https://updates.example/staged-apply.tar.gz", staleAt, staleAt);
|
||||
const now = Date.now();
|
||||
expect(reconcileOrphanedUpdateJobs(database.sqlite, config, now)).toBe(3);
|
||||
expect(database.sqlite.prepare("SELECT status FROM update_jobs WHERE id=?").get(queuedId)).toEqual({ status: "failed" });
|
||||
@@ -362,7 +381,7 @@ describe("更新安全工具", () => {
|
||||
const jobId = randomUUID();
|
||||
database.sqlite.prepare(`
|
||||
INSERT INTO update_jobs(id, operation, status, version, platform, asset_url, created_at, updated_at)
|
||||
VALUES (?, 'download', 'downloading', '1.2.0', 'linux-x64', ?, ?, ?)
|
||||
VALUES (?, 'download', 'downloading', '1.3.0', 'linux-x64', ?, ?, ?)
|
||||
`).run(jobId, "https://updates.example/download.tar.gz", staleAt, staleAt);
|
||||
await writeFile(config.updateRequestPath, JSON.stringify({ jobId, operation: "download" }));
|
||||
const statePath = path.join(config.installPrefix, ".update-state");
|
||||
@@ -385,7 +404,7 @@ describe("更新安全工具", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("队列任务有新请求标记时可被重新检查,标记过期后才回收", async () => {
|
||||
it("队列任务有匹配请求标记时保留到租约过期,过期后才回收", async () => {
|
||||
const root = await mkdtemp(path.join(tmpdir(), "tallynote-update-queued-marker-"));
|
||||
let database: ReturnType<typeof openDatabase> | undefined;
|
||||
try {
|
||||
@@ -406,15 +425,17 @@ describe("更新安全工具", () => {
|
||||
const jobId = randomUUID();
|
||||
database.sqlite.prepare(`
|
||||
INSERT INTO update_jobs(id, operation, status, version, platform, asset_url, created_at, updated_at)
|
||||
VALUES (?, 'apply', 'queued', '1.2.0', 'linux-x64', ?, ?, ?)
|
||||
VALUES (?, 'apply', 'queued', '1.3.0', 'linux-x64', ?, ?, ?)
|
||||
`).run(jobId, "https://updates.example/queued.tar.gz", staleAt, staleAt);
|
||||
await writeFile(config.updateRequestPath, JSON.stringify({ jobId, operation: "apply" }));
|
||||
const now = Date.now();
|
||||
await utimes(config.updateRequestPath, new Date(now), new Date(now));
|
||||
|
||||
// The DB row is old, but the request marker is fresh and names this
|
||||
// exact job. Keep it queued while systemd has a chance to consume it.
|
||||
expect(reconcileOrphanedUpdateJobs(database.sqlite, config, now)).toBe(0);
|
||||
expect(database.sqlite.prepare("SELECT status FROM update_jobs WHERE id=?").get(jobId)).toEqual({ status: "queued" });
|
||||
expect(await stat(config.updateRequestPath)).toBeTruthy();
|
||||
await expect(stat(config.updateRequestPath)).resolves.toBeTruthy();
|
||||
|
||||
const expiredNow = now + ORPHANED_UPDATE_TIMEOUT_MS + 1;
|
||||
expect(reconcileOrphanedUpdateJobs(database.sqlite, config, expiredNow)).toBe(1);
|
||||
@@ -492,17 +513,17 @@ describe("更新元数据缓存", () => {
|
||||
prepareDataDirectories(config);
|
||||
const database = openDatabase(config);
|
||||
const digest = "b".repeat(64);
|
||||
const platformAsset = `tallynote-1.2.0-${detectPlatform().target}-glibc.tar.gz`;
|
||||
const platformAsset = `tallynote-1.3.0-${detectPlatform().target}-glibc.tar.gz`;
|
||||
const sums = `${digest} ${platformAsset}\n`;
|
||||
const signature = sign(null, Buffer.from(sums), privateKey);
|
||||
globalThis.fetch = (async (input: string | URL) => input.toString().endsWith("SHA256SUMS.sig")
|
||||
? new Response(signature)
|
||||
: input.toString().endsWith("SHA256SUMS")
|
||||
? new Response(sums)
|
||||
: new Response(JSON.stringify({ tag_name: "v1.2.0", published_at: "2026-08-28T00:00:00Z", assets: [{ name: "SHA256SUMS", browser_download_url: "https://updates.example/SHA256SUMS" }, { name: "SHA256SUMS.sig", browser_download_url: "https://updates.example/SHA256SUMS.sig" }, { name: platformAsset, browser_download_url: `https://updates.example/${platformAsset}` }] }), { status: 200 })) as typeof fetch;
|
||||
: new Response(JSON.stringify({ tag_name: "v1.3.0", published_at: "2026-08-28T00:00:00Z", assets: [{ name: "SHA256SUMS", browser_download_url: "https://updates.example/SHA256SUMS" }, { name: "SHA256SUMS.sig", browser_download_url: "https://updates.example/SHA256SUMS.sig" }, { name: platformAsset, browser_download_url: `https://updates.example/${platformAsset}` }] }), { status: 200 })) as typeof fetch;
|
||||
try {
|
||||
const result = await checkForUpdate(database.sqlite, config);
|
||||
expect(result.latest).toMatchObject({ version: "1.2.0", compatible: true, integrityReady: true, signatureReady: true, isNewer: true });
|
||||
expect(result.latest).toMatchObject({ version: "1.3.0", compatible: true, integrityReady: true, signatureReady: true, isNewer: true });
|
||||
const cached = database.sqlite.prepare("SELECT value FROM system_settings WHERE key='update.release.v1'").get() as { value: string };
|
||||
expect(JSON.parse(cached.value).asset.sha256).toBe(digest);
|
||||
} finally {
|
||||
|
||||
@@ -34,7 +34,7 @@ function App() {
|
||||
const notify = useCallback((message: string, kind: "success" | "error" | "info" = "info") => {
|
||||
// The placement container owns the responsive right inset. Keeping the
|
||||
// item offset at zero avoids pushing narrow-screen notices off canvas.
|
||||
const options = { content: message, duration: 4200, placement: "top-right" as const, offset: [0, 76] as [number, number], zIndex: 5000 };
|
||||
const options = { content: message, duration: 4200, placement: "top-right" as const, offset: [24, 76] as [number, number], zIndex: 6000 };
|
||||
const show = kind === "success" ? NotificationPlugin.success : kind === "error" ? NotificationPlugin.error : NotificationPlugin.info;
|
||||
void show(options);
|
||||
}, []);
|
||||
|
||||
@@ -21,19 +21,14 @@ import {
|
||||
X,
|
||||
FileCode,
|
||||
HardDrive,
|
||||
Terminal,
|
||||
} from "lucide-react";
|
||||
import { Button, Card, Dialog, RadioGroup, Radio, Steps, Tag, Tooltip } from "tdesign-react";
|
||||
import { Button, Card, Dialog, Steps, Tag, Tooltip } from "tdesign-react";
|
||||
import { Page, Surface } from "../common";
|
||||
import { api } from "../../services/api";
|
||||
import { api, ApiError } from "../../services/api";
|
||||
import { dateText } from "../../utils/date";
|
||||
import type { MockScenario, MockUpdateState } from "./mockData";
|
||||
|
||||
const { StepItem } = Steps;
|
||||
|
||||
// Enable mock preview in local development
|
||||
const MOCK_PREVIEW_ENABLED = import.meta.env.DEV;
|
||||
|
||||
export type JobStatus =
|
||||
| "queued"
|
||||
| "downloading"
|
||||
@@ -234,17 +229,12 @@ export default function UpdatePage({
|
||||
timezone?: string;
|
||||
notify?: (msg: string, type?: "success" | "info" | "error") => void;
|
||||
}) {
|
||||
// Mock mode switcher for local developer preview
|
||||
const [mockScenario, setMockScenario] = useState<"live" | MockScenario>("live");
|
||||
const mockTimer = useRef<number | null>(null);
|
||||
const [mockCatalog, setMockCatalog] = useState<Record<MockScenario, MockUpdateState> | null>(null);
|
||||
|
||||
// Live state
|
||||
const [liveInfo, setLiveInfo] = useState<UpdateInfo | null>(null);
|
||||
const [mockInfoState, setMockInfoState] = useState<UpdateInfo | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [checking, setChecking] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
const [modalError, setModalError] = useState("");
|
||||
const [pollError, setPollError] = useState("");
|
||||
const [actionBusy, setActionBusy] = useState(false);
|
||||
const [reloadReady, setReloadReady] = useState(false);
|
||||
@@ -253,84 +243,61 @@ export default function UpdatePage({
|
||||
const [showUpgradeModal, setShowUpgradeModal] = useState(false);
|
||||
const [confirmReadyToDownload, setConfirmReadyToDownload] = useState(false);
|
||||
const [cancelling, setCancelling] = useState(false);
|
||||
const [queuedSeconds, setQueuedSeconds] = useState(0);
|
||||
const [now, setNow] = useState(() => Date.now());
|
||||
|
||||
const announced = useRef<string | null>(null);
|
||||
const checkInFlight = useRef(false);
|
||||
const actionInFlight = useRef(false);
|
||||
const cancelInFlight = useRef(false);
|
||||
const loadInFlight = useRef(false);
|
||||
const disconnected = useRef(false);
|
||||
const recoveredNotice = useRef(false);
|
||||
|
||||
// Active info depending on mock vs live
|
||||
const isMock = MOCK_PREVIEW_ENABLED && mockScenario !== "live" && Boolean(mockCatalog);
|
||||
const selectedMock = mockScenario !== "live" ? mockCatalog?.[mockScenario] : undefined;
|
||||
const info = isMock && selectedMock ? (mockInfoState ?? selectedMock.info) : liveInfo;
|
||||
const info = liveInfo;
|
||||
|
||||
// Handle mock scenario change
|
||||
const handleScenarioChange = (scenario: "live" | MockScenario) => {
|
||||
setMockScenario(scenario);
|
||||
if (mockTimer.current !== null) {
|
||||
window.clearTimeout(mockTimer.current);
|
||||
mockTimer.current = null;
|
||||
}
|
||||
if (scenario !== "live") {
|
||||
const next = mockCatalog?.[scenario];
|
||||
if (!next) return;
|
||||
setMockInfoState(JSON.parse(JSON.stringify(next.info)));
|
||||
notify?.(`已切换至 Mock 场景:${next.title}`, "info");
|
||||
} else {
|
||||
setMockInfoState(null);
|
||||
notify?.("已切回真实后端模式", "info");
|
||||
}
|
||||
const mergeInfo = (incoming: UpdateInfo, preserveJob = false) => {
|
||||
setLiveInfo((current) => {
|
||||
if (!current) return incoming;
|
||||
const next = {
|
||||
...current,
|
||||
...incoming,
|
||||
// A check response describes the release, but must not erase the job
|
||||
// that is already being displayed while that check is in flight.
|
||||
job: preserveJob
|
||||
? (current.job ?? incoming.job)
|
||||
: (!Object.prototype.hasOwnProperty.call(incoming, "job") ? current.job : incoming.job),
|
||||
};
|
||||
// Some status/check responses are intentionally partial. Keep fields
|
||||
// from the last successful response when a field is omitted.
|
||||
if (!Object.prototype.hasOwnProperty.call(incoming, "latest")) next.latest = current.latest;
|
||||
if (!Object.prototype.hasOwnProperty.call(incoming, "checkedAt")) next.checkedAt = current.checkedAt;
|
||||
if (!Object.prototype.hasOwnProperty.call(incoming, "strategy")) next.strategy = current.strategy;
|
||||
return next;
|
||||
});
|
||||
};
|
||||
|
||||
useEffect(() => () => {
|
||||
if (mockTimer.current !== null) window.clearTimeout(mockTimer.current);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!import.meta.env.DEV) return;
|
||||
let disposed = false;
|
||||
void import("./mockData").then(({ MOCK_SCENARIOS }) => {
|
||||
if (!disposed) setMockCatalog(MOCK_SCENARIOS);
|
||||
});
|
||||
return () => {
|
||||
disposed = true;
|
||||
};
|
||||
}, []);
|
||||
|
||||
const load = async () => {
|
||||
if (isMock) return;
|
||||
setLoading(true);
|
||||
const load = async (showLoading = true): Promise<UpdateInfo | null> => {
|
||||
if (loadInFlight.current) return null;
|
||||
loadInFlight.current = true;
|
||||
if (showLoading) setLoading(true);
|
||||
setError("");
|
||||
try {
|
||||
const res = await api<UpdateInfo>("/api/update/status");
|
||||
setLiveInfo(res);
|
||||
mergeInfo(res);
|
||||
updateInfoCache = res;
|
||||
return res;
|
||||
} catch (e) {
|
||||
setError((e as Error).message);
|
||||
return null;
|
||||
} finally {
|
||||
setLoading(false);
|
||||
if (showLoading) setLoading(false);
|
||||
loadInFlight.current = false;
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (!isMock) void load();
|
||||
else setLoading(false);
|
||||
}, [isMock]);
|
||||
|
||||
// Terminal failures or cancellations do not pollute active state
|
||||
const job = info?.job && info.job.status !== "failed" && info.job.status !== "cancelled" ? info.job : null;
|
||||
|
||||
// Queued duration counter
|
||||
useEffect(() => {
|
||||
if (job?.status === "queued") {
|
||||
const timer = window.setInterval(() => setQueuedSeconds((s) => s + 1), 1000);
|
||||
return () => window.clearInterval(timer);
|
||||
}
|
||||
setQueuedSeconds(0);
|
||||
}, [job?.status]);
|
||||
// Keep terminal jobs visible so operators can understand what happened and
|
||||
// recover without guessing. The polling effect below only polls active jobs.
|
||||
const job = info?.job ?? null;
|
||||
|
||||
const applyQueuedAt = timestamp(job?.applyQueuedAt);
|
||||
const restartAt =
|
||||
@@ -350,9 +317,9 @@ export default function UpdatePage({
|
||||
return () => window.clearInterval(timer);
|
||||
}, [restartAt]);
|
||||
|
||||
// Live polling effect: only poll when active job exists
|
||||
// Live polling effect for an active job. Completed responses are refreshed
|
||||
// once so latest/checkedAt/strategy stay current; other terminal states stay visible.
|
||||
useEffect(() => {
|
||||
if (isMock) return;
|
||||
const shouldPoll = Boolean(
|
||||
job && (pollableStatuses.has(job.status) || (job.status === "staged" && job.operation === "apply"))
|
||||
);
|
||||
@@ -384,23 +351,53 @@ export default function UpdatePage({
|
||||
setReloadReady(true);
|
||||
notify?.("系统升级完成,请刷新页面", "success");
|
||||
}
|
||||
if (
|
||||
if (result.job.status === "completed") {
|
||||
void load(false);
|
||||
} else if (
|
||||
pollableStatuses.has(result.job.status) ||
|
||||
(result.job.status === "staged" && result.job.operation === "apply")
|
||||
) {
|
||||
schedule(1500);
|
||||
}
|
||||
} catch {
|
||||
} catch (caught) {
|
||||
if (disposed) return;
|
||||
const status = caught instanceof ApiError ? caught.status : 0;
|
||||
const message = caught instanceof Error ? caught.message : "读取更新任务状态失败";
|
||||
if (status === 404) {
|
||||
setPollError("更新任务已结束,正在刷新状态。");
|
||||
void load(false);
|
||||
return;
|
||||
}
|
||||
if (status === 401) {
|
||||
setPollError("登录已失效,请重新登录。");
|
||||
return;
|
||||
}
|
||||
if (status === 403) {
|
||||
setPollError("没有权限读取更新任务状态。");
|
||||
return;
|
||||
}
|
||||
|
||||
failures += 1;
|
||||
disconnected.current = true;
|
||||
disconnected.current = status === 0 || status === 408;
|
||||
recoveredNotice.current = false;
|
||||
setPollError(
|
||||
`服务正在平滑重启${
|
||||
restartSeconds !== null ? `,预计 ${restartSeconds} 秒后恢复` : ",页面正在自动探活重试"
|
||||
}。升级任务仍在后台安全执行。`
|
||||
);
|
||||
schedule(Math.min(1500 * 2 ** Math.min(failures, 3), 10_000));
|
||||
if (status === 409) {
|
||||
setPollError(`${message},正在刷新状态。`);
|
||||
void load(false);
|
||||
return;
|
||||
}
|
||||
if (status === 429) {
|
||||
setPollError(`${message},稍后继续同步。`);
|
||||
} else if (status === 408) {
|
||||
setPollError("读取更新任务状态超时,正在重试。");
|
||||
} else if (status === 0) {
|
||||
setPollError("更新服务连接异常,正在重试。");
|
||||
} else {
|
||||
setPollError(`${message},正在重试。`);
|
||||
}
|
||||
const retryAfter = caught instanceof ApiError && caught.retryAfter
|
||||
? Math.max(1000, caught.retryAfter * 1000)
|
||||
: Math.min(1500 * 2 ** Math.min(failures, 3), 10_000);
|
||||
schedule(retryAfter);
|
||||
}
|
||||
};
|
||||
void poll();
|
||||
@@ -408,36 +405,97 @@ export default function UpdatePage({
|
||||
disposed = true;
|
||||
if (timer !== undefined) window.clearTimeout(timer);
|
||||
};
|
||||
}, [isMock, job?.id, job?.status, job?.operation, notify, restartSeconds]);
|
||||
}, [job?.id, job?.status, job?.operation, notify]);
|
||||
|
||||
// With no visible job, make a low-frequency status request so a task created
|
||||
// elsewhere can still appear without creating a request storm.
|
||||
useEffect(() => {
|
||||
if (job) return;
|
||||
let timer: number | undefined;
|
||||
let disposed = false;
|
||||
const discover = () => {
|
||||
if (disposed || document.visibilityState !== "visible") return;
|
||||
void load(false);
|
||||
};
|
||||
const schedule = () => {
|
||||
if (disposed) return;
|
||||
if (timer !== undefined) window.clearTimeout(timer);
|
||||
timer = window.setTimeout(() => {
|
||||
discover();
|
||||
schedule();
|
||||
}, 5000);
|
||||
};
|
||||
const onVisibilityChange = () => {
|
||||
if (document.visibilityState === "visible") {
|
||||
discover();
|
||||
schedule();
|
||||
} else if (timer !== undefined) {
|
||||
window.clearTimeout(timer);
|
||||
timer = undefined;
|
||||
}
|
||||
};
|
||||
if (document.visibilityState === "visible") schedule();
|
||||
document.addEventListener("visibilitychange", onVisibilityChange);
|
||||
return () => {
|
||||
disposed = true;
|
||||
if (timer !== undefined) window.clearTimeout(timer);
|
||||
document.removeEventListener("visibilitychange", onVisibilityChange);
|
||||
};
|
||||
}, [job?.id, job?.status, job?.operation]);
|
||||
|
||||
// Check update handler
|
||||
const check = async () => {
|
||||
if (isMock) {
|
||||
setChecking(true);
|
||||
window.setTimeout(() => {
|
||||
setChecking(false);
|
||||
notify?.("Mock:检查完成,已是最新配置状态", "success");
|
||||
}, 600);
|
||||
return;
|
||||
}
|
||||
if (checkInFlight.current) return;
|
||||
checkInFlight.current = true;
|
||||
setChecking(true);
|
||||
setError("");
|
||||
try {
|
||||
setLiveInfo(await api<UpdateInfo>("/api/update/check", { method: "POST" }));
|
||||
const result = await api<UpdateInfo>("/api/update/check", { method: "POST" });
|
||||
// The check endpoint returns release metadata but not task state. Read
|
||||
// the status endpoint once more so reconciliation performed before the
|
||||
// check is authoritative: an expired staged task must disappear from
|
||||
// this page immediately instead of surviving until a full refresh.
|
||||
const status = await api<UpdateInfo>("/api/update/status");
|
||||
setLiveInfo((current) => ({
|
||||
...(current ?? result),
|
||||
...result,
|
||||
job: status.job,
|
||||
}));
|
||||
notify?.("版本检查完成", "info");
|
||||
} catch (e) {
|
||||
setError((e as Error).message);
|
||||
if (e instanceof ApiError && e.status === 429) {
|
||||
notify?.((e as Error).message, "error");
|
||||
} else {
|
||||
setError((e as Error).message);
|
||||
}
|
||||
} finally {
|
||||
setChecking(false);
|
||||
checkInFlight.current = false;
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
let disposed = false;
|
||||
const bootstrap = async () => {
|
||||
const snapshot = await load();
|
||||
if (disposed || !snapshot) return;
|
||||
// Status may be satisfied from the release cache. Refresh it on entry
|
||||
// only when the cached result is absent or older than one minute; this
|
||||
// keeps the page current without turning navigation into a burst of
|
||||
// rate-limited checks.
|
||||
const checkedAt = snapshot.checkedAt || 0;
|
||||
if (!checkedAt || !snapshot.latest || Date.now() - checkedAt > 60_000) await check();
|
||||
};
|
||||
void bootstrap();
|
||||
return () => {
|
||||
disposed = true;
|
||||
};
|
||||
}, []);
|
||||
|
||||
// Cancel queued job handler
|
||||
const cancelJob = async () => {
|
||||
if (cancelling) return;
|
||||
if (cancelInFlight.current || !job?.id) return;
|
||||
cancelInFlight.current = true;
|
||||
setCancelling(true);
|
||||
try {
|
||||
await api("/api/update/cancel", { method: "POST", body: JSON.stringify({ jobId: job?.id }) });
|
||||
@@ -449,53 +507,77 @@ export default function UpdatePage({
|
||||
notify?.((e as Error).message, "error");
|
||||
} finally {
|
||||
setCancelling(false);
|
||||
cancelInFlight.current = false;
|
||||
}
|
||||
};
|
||||
|
||||
// Start download action
|
||||
const startDownload = async () => {
|
||||
if (!latest) return;
|
||||
if (!latest || actionInFlight.current || hasActiveJob || canApply) return;
|
||||
actionInFlight.current = true;
|
||||
setActionBusy(true);
|
||||
setError("");
|
||||
setModalError("");
|
||||
try {
|
||||
const response = await api<{ job: UpdateJob }>("/api/update/download", {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ version: latest.version }),
|
||||
body: JSON.stringify({ version: latest.version, confirm: true }),
|
||||
});
|
||||
setLiveInfo((current) => (current ? { ...current, job: response.job } : current));
|
||||
setConfirmReadyToDownload(false);
|
||||
notify?.("已提交下载更新包请求,后台下载中", "info");
|
||||
} catch (e) {
|
||||
setError((e as Error).message);
|
||||
const msg = (e as Error).message;
|
||||
setError(msg);
|
||||
setModalError(msg);
|
||||
notify?.(msg, "error");
|
||||
} finally {
|
||||
setActionBusy(false);
|
||||
actionInFlight.current = false;
|
||||
}
|
||||
};
|
||||
|
||||
// Start apply action
|
||||
const startApply = async () => {
|
||||
if (!latest) return;
|
||||
if (!latest || !job || job.status !== "staged" || job.operation !== "download" || actionInFlight.current) return;
|
||||
actionInFlight.current = true;
|
||||
setActionBusy(true);
|
||||
setError("");
|
||||
setModalError("");
|
||||
try {
|
||||
const response = await api<{ job: UpdateJob }>("/api/update/apply", {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ version: latest.version, confirm: true }),
|
||||
body: JSON.stringify({ version: latest.version, confirm: true, ...(job?.id ? { jobId: job.id } : {}) }),
|
||||
});
|
||||
setLiveInfo((current) => (current ? { ...current, job: response.job } : current));
|
||||
notify?.("已提交升级请求,正在备份并平滑重启…", "info");
|
||||
} catch (e) {
|
||||
setError((e as Error).message);
|
||||
const msg = (e as Error).message;
|
||||
setError(msg);
|
||||
setModalError(msg);
|
||||
notify?.(msg, "error");
|
||||
} finally {
|
||||
setActionBusy(false);
|
||||
actionInFlight.current = false;
|
||||
}
|
||||
};
|
||||
|
||||
const latest = info?.latest;
|
||||
const notes = notesFor(latest);
|
||||
const hasChecked = Boolean(info?.checkedAt);
|
||||
const releaseState = checking
|
||||
? "checking"
|
||||
: !hasChecked
|
||||
? "unverified"
|
||||
: !latest
|
||||
? "unavailable"
|
||||
: latest.isNewer
|
||||
? latest.compatible && latest.integrityReady ? "available" : "blocked"
|
||||
: "up-to-date";
|
||||
|
||||
const canDownload = Boolean(
|
||||
info?.strategy === "systemd" &&
|
||||
!checking &&
|
||||
latest?.isNewer &&
|
||||
latest.compatible &&
|
||||
latest.integrityReady &&
|
||||
@@ -504,14 +586,19 @@ export default function UpdatePage({
|
||||
|
||||
const canApply = Boolean(
|
||||
info?.strategy === "systemd" &&
|
||||
!checking &&
|
||||
job &&
|
||||
job.status === "staged" &&
|
||||
job.operation === "download"
|
||||
job.operation === "download" &&
|
||||
latest?.isNewer &&
|
||||
latest.version === job.version &&
|
||||
job.version !== info.currentVersion
|
||||
);
|
||||
|
||||
const hasActiveJob = Boolean(
|
||||
job && activeStatuses.has(job.status) && job.status !== "staged"
|
||||
job && activeStatuses.has(job.status) && !(job.status === "staged" && job.operation === "download")
|
||||
);
|
||||
const showJobDetails = hasActiveJob || canApply || Boolean(job?.status === "staged" && job.operation === "apply");
|
||||
|
||||
// Compute current pipeline step index (0: check, 1: download, 2: verify/stage, 3: apply/restart)
|
||||
const currentStep = useMemo(() => {
|
||||
@@ -537,7 +624,7 @@ export default function UpdatePage({
|
||||
if (!job) return 0;
|
||||
if (job.status === "completed" || job.status === "staged") return 100;
|
||||
if (job.status === "downloading") {
|
||||
if (!job.sizeBytes || !job.downloadedBytes) return 10;
|
||||
if (!job.sizeBytes || !job.downloadedBytes) return 0;
|
||||
return Math.min(99, Math.max(1, Math.round((job.downloadedBytes / job.sizeBytes) * 100)));
|
||||
}
|
||||
if (job.status === "verifying") return 99;
|
||||
@@ -568,7 +655,7 @@ export default function UpdatePage({
|
||||
subtitle="管理系统版本升级、更新包完整性校验与安全热重启"
|
||||
actions={
|
||||
<div className="tn-update-page-actions">
|
||||
{hasActiveJob && (
|
||||
{showJobDetails && (
|
||||
<Button
|
||||
theme="primary"
|
||||
variant="base"
|
||||
@@ -639,10 +726,18 @@ export default function UpdatePage({
|
||||
<span className="tn-metric-label">当前运行版本</span>
|
||||
<div className="tn-metric-value">v{info.currentVersion}</div>
|
||||
<div className="tn-metric-foot">
|
||||
{latest?.isNewer ? (
|
||||
<Tag theme="primary" size="small">可更新至 v{latest.version}</Tag>
|
||||
) : (
|
||||
{releaseState === "checking" ? (
|
||||
<Tag theme="default" size="small">正在检查更新</Tag>
|
||||
) : releaseState === "unverified" ? (
|
||||
<Tag theme="default" size="small">尚未检查更新</Tag>
|
||||
) : releaseState === "available" ? (
|
||||
<Tag theme="primary" size="small">可更新至 v{latest?.version}</Tag>
|
||||
) : releaseState === "up-to-date" ? (
|
||||
<Tag theme="success" size="small">已是最新版本</Tag>
|
||||
) : releaseState === "blocked" ? (
|
||||
<Tag theme="warning" size="small">发现新版本,但暂不可更新</Tag>
|
||||
) : (
|
||||
<Tag theme="default" size="small">暂未获取发布信息</Tag>
|
||||
)}
|
||||
</div>
|
||||
</Surface>
|
||||
@@ -681,8 +776,8 @@ export default function UpdatePage({
|
||||
<Surface className="tn-ascii-release-container">
|
||||
<div className="tn-ascii-release-head">
|
||||
<h3 className="tn-ascii-release-title">发布版本详情</h3>
|
||||
<Tag theme={latest.isNewer ? "primary" : "success"} variant="light-outline">
|
||||
{latest.isNewer ? "发现新版本" : "已是最新版本"}
|
||||
<Tag theme={releaseState === "available" ? "primary" : releaseState === "up-to-date" ? "success" : releaseState === "blocked" ? "warning" : "default"} variant="light-outline">
|
||||
{releaseState === "available" ? "发现新版本" : releaseState === "up-to-date" ? "已是最新版本" : releaseState === "blocked" ? "暂不可安全更新" : "尚未检查"}
|
||||
</Tag>
|
||||
</div>
|
||||
|
||||
@@ -718,32 +813,10 @@ export default function UpdatePage({
|
||||
</div>
|
||||
<div className="tn-ascii-info-item">
|
||||
<span className="tn-ascii-info-label">下载策略:</span>
|
||||
<span className="tn-ascii-info-val">应用内流式直连 (零调度等待)</span>
|
||||
<span className="tn-ascii-info-val">系统更新服务接管</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div style={{ marginTop: 14, padding: "10px 14px", background: "var(--tn-navy-50)", border: "1px solid var(--tn-navy-100)", borderRadius: 6, display: "flex", alignItems: "center", justifyContent: "space-between", flexWrap: "wrap", gap: 8, fontSize: "12.5px" }}>
|
||||
<div style={{ display: "flex", flexDirection: "column", gap: 2, minWidth: 260, flex: 1 }}>
|
||||
<span style={{ color: "var(--tn-navy-800)", fontWeight: 500 }}>
|
||||
安装包下载直链 ({latest.assetName || "发布包"}):
|
||||
</span>
|
||||
<code style={{ fontSize: "11.5px", color: "var(--tn-navy-600)", wordBreak: "break-all" }}>
|
||||
{latest.assetUrl || `https://git.awaioi.com/awaioi/TallyNote/releases/download/v${latest.version}/${latest.assetName || `tallynote-${latest.version}-linux-x64-glibc.tar.gz`}`}
|
||||
</code>
|
||||
</div>
|
||||
<Button
|
||||
size="small"
|
||||
variant="outline"
|
||||
onClick={() => {
|
||||
const url = latest.assetUrl || `https://git.awaioi.com/awaioi/TallyNote/releases/download/v${latest.version}/${latest.assetName || `tallynote-${latest.version}-linux-x64-glibc.tar.gz`}`;
|
||||
navigator.clipboard.writeText(url);
|
||||
notify?.("已复制安装包下载直链", "success");
|
||||
}}
|
||||
>
|
||||
复制直链
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="tn-ascii-release-actions">
|
||||
{canDownload && (
|
||||
<Button
|
||||
@@ -751,12 +824,12 @@ export default function UpdatePage({
|
||||
size="large"
|
||||
onClick={() => {
|
||||
setConfirmReadyToDownload(true);
|
||||
setShowUpgradeModal(true);
|
||||
setModalError(""); setShowUpgradeModal(true);
|
||||
}}
|
||||
disabled={actionBusy}
|
||||
icon={<Download size={16} />}
|
||||
>
|
||||
立即升级至 v{latest.version}
|
||||
下载更新包
|
||||
</Button>
|
||||
)}
|
||||
{canApply && (
|
||||
@@ -767,7 +840,7 @@ export default function UpdatePage({
|
||||
disabled={actionBusy}
|
||||
icon={<Zap size={16} />}
|
||||
>
|
||||
更新包已就绪,立即应用 (v{latest.version})
|
||||
立即应用并重启 v{latest.version}
|
||||
</Button>
|
||||
)}
|
||||
{hasActiveJob && (
|
||||
@@ -780,9 +853,14 @@ export default function UpdatePage({
|
||||
查看当前升级进度
|
||||
</Button>
|
||||
)}
|
||||
{!latest.isNewer && !hasActiveJob && (
|
||||
{releaseState === "blocked" && !hasActiveJob && !canApply && (
|
||||
<Button theme="default" variant="outline" size="large" onClick={() => void check()} loading={checking} disabled={checking} icon={<RefreshCw size={15} />}>
|
||||
重新检查
|
||||
</Button>
|
||||
)}
|
||||
{releaseState === "up-to-date" && !hasActiveJob && !canApply && (
|
||||
<Button theme="default" variant="outline" size="large" onClick={() => void check()} icon={<RefreshCw size={15} />}>
|
||||
检查新版本
|
||||
重新检查
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
@@ -790,10 +868,10 @@ export default function UpdatePage({
|
||||
) : (
|
||||
<Surface className="tn-empty-surface">
|
||||
<div className="tn-empty-content">
|
||||
<CheckCircle2 size={32} className="text-success" />
|
||||
<p>暂无待更新的版本信息,当前系统已是最新状态。</p>
|
||||
<Button variant="outline" onClick={() => void check()} icon={<RefreshCw size={15} />}>
|
||||
检查新版本
|
||||
{releaseState === "unverified" || releaseState === "checking" ? <RefreshCw size={32} className={releaseState === "checking" ? "tn-spin" : "text-secondary"} /> : <AlertCircle size={32} className="text-warning" />}
|
||||
<p>{releaseState === "unverified" || releaseState === "checking" ? "尚未完成版本检查,请先获取官方发布信息。" : "暂时没有可用的发布信息,请稍后重新检查。"}</p>
|
||||
<Button variant="outline" onClick={() => void check()} loading={checking} disabled={checking} icon={<RefreshCw size={15} />}>
|
||||
{releaseState === "checking" ? "正在检查" : "检查新版本"}
|
||||
</Button>
|
||||
</div>
|
||||
</Surface>
|
||||
@@ -802,7 +880,7 @@ export default function UpdatePage({
|
||||
{latest && notes && (
|
||||
<Surface className="tn-ascii-notes-container">
|
||||
<div className="tn-ascii-notes-head">
|
||||
<h3 className="tn-ascii-notes-title">本次版本更新说明</h3>
|
||||
<h3 className="tn-ascii-notes-title">发布说明</h3>
|
||||
</div>
|
||||
<div className="tn-ascii-notes-body">
|
||||
<MarkdownNotes value={notes} />
|
||||
@@ -827,13 +905,20 @@ export default function UpdatePage({
|
||||
{/* Unified Single Upgrade Modal (800px width on desktop) */}
|
||||
<Dialog
|
||||
visible={showUpgradeModal}
|
||||
header={`系统升级控制台 · v${latest?.version || ""}`}
|
||||
header={`系统升级控制台 · v${latest?.version || job?.version || ""}`}
|
||||
className="tn-dialog-large"
|
||||
width="820px"
|
||||
footer={null}
|
||||
onClose={() => setShowUpgradeModal(false)}
|
||||
>
|
||||
<div className="tn-stepper-surface">
|
||||
{modalError && (
|
||||
<div className="tn-modal-error-banner" role="alert">
|
||||
<AlertCircle size={16} />
|
||||
<span>{modalError}</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 4 Steps Horizontal (Exact ASCII: (1) 版本确认 (2) 下载更新包 (3) 校验与准备 (4) 重启恢复) */}
|
||||
<div className="tn-stepper-wrap">
|
||||
<Steps current={currentStep} theme="default">
|
||||
@@ -883,10 +968,8 @@ export default function UpdatePage({
|
||||
{/* 场景 A: 实时下载中态 (Exact ASCII) */}
|
||||
{job?.status === "downloading" && (
|
||||
<div className="tn-modal-card-box">
|
||||
<div className="tn-modal-card-title">正在从官方源直接流式拉取更新包...</div>
|
||||
<div style={{ fontSize: "12px", color: "var(--tn-navy-600)", margin: "-4px 0 12px 0", wordBreak: "break-all" }}>
|
||||
请求地址: <code>{job.assetUrl || latest?.assetUrl || `https://git.awaioi.com/awaioi/TallyNote/releases/download/v${latest?.version || job.version}/${job.assetName || "release.tar.gz"}`}</code>
|
||||
</div>
|
||||
<div className="tn-modal-card-title">正在从官方源流式下载完整安装包 ({job.sizeBytes ? bytesText(job.sizeBytes) : "115 MB"})...</div>
|
||||
|
||||
<div
|
||||
className="tn-progress-stream"
|
||||
role="progressbar"
|
||||
@@ -911,7 +994,7 @@ export default function UpdatePage({
|
||||
</div>
|
||||
|
||||
<div className="tn-modal-info-note">
|
||||
[i] 更新包由应用进程直接流式拉取并自动比对 SHA-256 校验和,0 秒秒级启动,无需等待外部系统守护进程调度。
|
||||
[i] 正在流式拉取全量生产包(含运行环境与全部依赖),进度实时更新,不影响当前前台记账操作。
|
||||
</div>
|
||||
|
||||
<div className="tn-modal-actions-bar">
|
||||
@@ -926,11 +1009,9 @@ export default function UpdatePage({
|
||||
{job?.status === "queued" && (
|
||||
<div className="tn-modal-card-box">
|
||||
<div className="tn-modal-card-title">
|
||||
<div style={{ marginBottom: 12 }}><BeamBar width={160} /></div>正在建立与官方 Git 仓库的流式传输连接...
|
||||
</div>
|
||||
<div style={{ fontSize: "12px", color: "var(--tn-navy-600)", margin: "4px 0 14px 0", wordBreak: "break-all" }}>
|
||||
目标地址: <code>{job.assetUrl || latest?.assetUrl || "https://git.awaioi.com"}</code>
|
||||
<div style={{ marginBottom: 12 }}><BeamBar width={160} /></div>正在等待系统更新服务接管任务...
|
||||
</div>
|
||||
|
||||
<div className="tn-modal-actions-bar">
|
||||
<Button variant="outline" onClick={() => void cancelJob()} loading={cancelling} disabled={cancelling}>
|
||||
取消
|
||||
@@ -939,12 +1020,28 @@ export default function UpdatePage({
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 场景 B2: 校验与环境就绪中 (verifying) */}
|
||||
{job?.status === "verifying" && (
|
||||
<div className="tn-modal-card-box">
|
||||
<div className="tn-modal-card-title">
|
||||
<div style={{ marginBottom: 12 }}><BeamBar width={180} /></div>
|
||||
正在比对安全指纹并解压更新包...
|
||||
</div>
|
||||
<div style={{ fontSize: "14px", color: "var(--tn-navy-900)", margin: "10px 0 8px", fontWeight: 500 }}>
|
||||
SHA-256 指纹核验通过,正在将生产环境就绪至版本暂存区...
|
||||
</div>
|
||||
<p className="text-secondary" style={{ fontSize: "13px", margin: "0 0 16px 0", lineHeight: 1.6 }}>
|
||||
系统正在核对发布包完整性与解压 dist 生产运行结构,校验就绪后将立即亮起“立即应用”按钮。
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 场景 C: 校验通过准备就绪 (staged) (Exact ASCII) */}
|
||||
{job?.status === "staged" && (
|
||||
{job?.status === "staged" && job.operation === "download" && canApply && (
|
||||
<div className="tn-modal-card-box">
|
||||
<div className="tn-modal-card-title" style={{ color: "#2f7d5c", display: "flex", alignItems: "center", gap: 8 }}>
|
||||
<CheckCircle2 size={18} />
|
||||
更新包下载完成,SHA-256 指纹与 Ed25519 数字签名校验无误,准备就绪。
|
||||
全量安装包下载与校验完成,SHA-256 指纹核对无误,准备就绪!
|
||||
</div>
|
||||
<div className="tn-upgrade-safety-tips" style={{ margin: "14px 0" }}>
|
||||
<div>• 点击立即应用后,系统将自动创建数据库与附件的完整快照备份;</div>
|
||||
@@ -968,6 +1065,36 @@ export default function UpdatePage({
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* A staged archive can become obsolete when the host or release
|
||||
metadata changes while this page is open. Keep the state visible
|
||||
but remove the apply action; the server will reconcile it on the
|
||||
next status request and the operator can perform a fresh check. */}
|
||||
{job?.status === "staged" && job.operation === "download" && !canApply && (
|
||||
<div className="tn-modal-card-box">
|
||||
<div className="tn-modal-card-title">暂存更新已失效</div>
|
||||
<p className="text-secondary" style={{ fontSize: "13px", margin: "0 0 16px", lineHeight: 1.6 }}>
|
||||
这个更新包已不是当前可安全应用的版本,系统不会重复应用。请重新检查更新以获取最新发布信息。
|
||||
</p>
|
||||
<div className="tn-modal-actions-bar">
|
||||
<Button variant="outline" onClick={() => void check()} loading={checking} disabled={checking}>
|
||||
重新检查
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{job?.status === "staged" && job.operation === "apply" && (
|
||||
<div className="tn-modal-card-box">
|
||||
<div className="tn-modal-card-title">
|
||||
<div style={{ marginBottom: 12 }}><BeamBar width={180} /></div>
|
||||
应用请求已提交,正在等待更新服务接管
|
||||
</div>
|
||||
<p className="text-secondary" style={{ fontSize: "13px", margin: "0 0 16px", lineHeight: 1.6 }}>
|
||||
系统正在准备备份与重启。页面会持续同步服务状态,请不要重复提交。
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 场景 D: 数据快照备份中或服务重启中 (backing_up / applying) (Exact ASCII) */}
|
||||
{(job?.status === "backing_up" || job?.status === "applying") && (
|
||||
<div className="tn-modal-card-box">
|
||||
@@ -994,7 +1121,7 @@ export default function UpdatePage({
|
||||
<div className="tn-modal-card-box" style={{ background: "rgba(47, 125, 92, 0.04)", border: "1px solid rgba(47, 125, 92, 0.25)" }}>
|
||||
<div className="tn-modal-card-title" style={{ color: "#2f7d5c", display: "flex", alignItems: "center", gap: 8 }}>
|
||||
<CheckCircle2 size={22} />
|
||||
恭喜!系统已成功平滑升级至 v{latest?.version || info.currentVersion}。
|
||||
恭喜!系统已成功平滑升级至 v{latest?.version || info?.currentVersion || "当前版本"}。
|
||||
</div>
|
||||
<p style={{ fontSize: "13.5px", color: "var(--tn-text)", margin: "8px 0 16px" }}>
|
||||
服务健康检查已全部通过,所有账目数据与发票凭证均完好无损。请点击下方按钮完成控制台刷新。
|
||||
@@ -1029,7 +1156,7 @@ export default function UpdatePage({
|
||||
)}
|
||||
|
||||
{/* Footer close button */}
|
||||
{job?.status !== "staged" && job?.status !== "completed" && !confirmReadyToDownload && (
|
||||
{!(job?.status === "staged" && canApply) && job?.status !== "completed" && !confirmReadyToDownload && (
|
||||
<div className="tn-modal-footer-close">
|
||||
<Button variant="outline" onClick={() => setShowUpgradeModal(false)}>
|
||||
关闭窗口(后台继续运行)
|
||||
@@ -1038,27 +1165,6 @@ export default function UpdatePage({
|
||||
)}
|
||||
</div> </Dialog>
|
||||
|
||||
{/* Floating Mock Dock (Bottom-right, zero interference with main page) */}
|
||||
{MOCK_PREVIEW_ENABLED && (
|
||||
<aside className="tn-dev-mock-dock" aria-label="开发预览控制台">
|
||||
<Terminal size={14} />
|
||||
<strong>Mock:</strong>
|
||||
<RadioGroup
|
||||
variant="default-filled"
|
||||
size="small"
|
||||
value={mockScenario}
|
||||
onChange={(value) => handleScenarioChange(value as "live" | MockScenario)}
|
||||
>
|
||||
<Radio.Button value="live">真实</Radio.Button>
|
||||
{mockCatalog &&
|
||||
Object.entries(mockCatalog).map(([key, item]) => (
|
||||
<Radio.Button key={key} value={key}>
|
||||
{item.title.split("(")[0]}
|
||||
</Radio.Button>
|
||||
))}
|
||||
</RadioGroup>
|
||||
</aside>
|
||||
)}
|
||||
</Page>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,283 +0,0 @@
|
||||
export type MockScenario =
|
||||
| "latest" // 已是最新
|
||||
| "available" // 发现新版本(待下载)
|
||||
| "downloading_30" // 下载中 30%
|
||||
| "downloading_85" // 下载中 85% + 高速
|
||||
| "staged" // 下载完成已校验,待立即更新
|
||||
| "backing_up" // 正在备份数据
|
||||
| "applying" // 正在原子切换并重启中(倒计时)
|
||||
| "completed" // 更新完成
|
||||
| "failed_verify" // 完整性校验失败
|
||||
| "disabled"; // 手动模式未配置源
|
||||
|
||||
export interface MockUpdateState {
|
||||
info: any;
|
||||
title: string;
|
||||
description: string;
|
||||
}
|
||||
|
||||
export const MOCK_SCENARIOS: Record<MockScenario, MockUpdateState> = {
|
||||
latest: {
|
||||
title: "版本健康(已是最新)",
|
||||
description: "展示当前运行版本已是最新,各项指标正常,无待处理任务",
|
||||
info: {
|
||||
configured: true,
|
||||
strategy: "systemd",
|
||||
currentVersion: "1.1.22",
|
||||
platform: { target: "x64/glibc", os: "linux", arch: "x64" },
|
||||
checkedAt: Date.now() - 600_000,
|
||||
latest: {
|
||||
version: "1.1.22",
|
||||
tagName: "v1.1.22",
|
||||
releaseName: "v1.1.22 稳定版",
|
||||
publishedAt: new Date(Date.now() - 3600_000 * 24).toISOString(),
|
||||
compatible: true,
|
||||
integrityReady: true,
|
||||
signatureReady: true,
|
||||
isNewer: false,
|
||||
assetName: "tallynote-1.1.22-linux-x64-glibc.tar.gz",
|
||||
assetSize: 120540160,
|
||||
notes: "### TallyNote 1.1.22\n\n- 优化反向代理下登录兼容性\n- 增强安全审计与防重放机制\n- 前端组件性能深度优化",
|
||||
},
|
||||
job: null,
|
||||
},
|
||||
},
|
||||
available: {
|
||||
title: "发现新版本(待下载)",
|
||||
description: "检查到官方发布了更高版本,显示更新日志与文件校验信息,可点击下载",
|
||||
info: {
|
||||
configured: true,
|
||||
strategy: "systemd",
|
||||
currentVersion: "1.1.22",
|
||||
platform: { target: "x64/glibc", os: "linux", arch: "x64" },
|
||||
checkedAt: Date.now() - 60_000,
|
||||
latest: {
|
||||
version: "1.1.23",
|
||||
tagName: "v1.1.23",
|
||||
releaseName: "v1.1.23 重大更新",
|
||||
publishedAt: new Date(Date.now() - 1800_000).toISOString(),
|
||||
compatible: true,
|
||||
integrityReady: true,
|
||||
signatureReady: true,
|
||||
isNewer: true,
|
||||
assetName: "tallynote-1.1.23-linux-x64-glibc.tar.gz",
|
||||
assetSize: 121000000,
|
||||
notes: "### TallyNote 1.1.23\n\n- 【新功能】系统更新中心全面重构,支持动态速率流光进度条与平滑重启倒计时\n- 【交互】优化抽屉展开动效与手机端自适应导航\n- 【安全】发布包支持双重 Ed25519 签名与 SHA-256 清单交叉校验",
|
||||
},
|
||||
job: null,
|
||||
},
|
||||
},
|
||||
downloading_30: {
|
||||
title: "下载更新中(进度 38%)",
|
||||
description: "展示真实下载速率、已下载字节数与动态流光进度条",
|
||||
info: {
|
||||
configured: true,
|
||||
strategy: "systemd",
|
||||
currentVersion: "1.1.22",
|
||||
platform: { target: "x64/glibc", os: "linux", arch: "x64" },
|
||||
checkedAt: Date.now() - 120_000,
|
||||
latest: {
|
||||
version: "1.1.23",
|
||||
tagName: "v1.1.23",
|
||||
compatible: true,
|
||||
integrityReady: true,
|
||||
signatureReady: true,
|
||||
isNewer: true,
|
||||
assetName: "tallynote-1.1.23-linux-x64-glibc.tar.gz",
|
||||
assetSize: 121000000,
|
||||
},
|
||||
job: {
|
||||
id: "mock-job-001",
|
||||
operation: "download",
|
||||
status: "downloading",
|
||||
version: "1.1.23",
|
||||
platform: "x64/glibc",
|
||||
assetName: "tallynote-1.1.23-linux-x64-glibc.tar.gz",
|
||||
sizeBytes: 121000000,
|
||||
downloadedBytes: 46200000,
|
||||
downloadStartedAt: Date.now() - 10000,
|
||||
downloadSpeedBps: 8800000, // 8.4 MB/s
|
||||
createdAt: Date.now() - 10000,
|
||||
updatedAt: Date.now(),
|
||||
},
|
||||
},
|
||||
},
|
||||
downloading_85: {
|
||||
title: "下载冲刺中(进度 88%)",
|
||||
description: "高速冲刺状态,即将触发 SHA-256 校验",
|
||||
info: {
|
||||
configured: true,
|
||||
strategy: "systemd",
|
||||
currentVersion: "1.1.22",
|
||||
platform: { target: "x64/glibc", os: "linux", arch: "x64" },
|
||||
checkedAt: Date.now() - 120_000,
|
||||
latest: {
|
||||
version: "1.1.23",
|
||||
tagName: "v1.1.23",
|
||||
compatible: true,
|
||||
integrityReady: true,
|
||||
signatureReady: true,
|
||||
isNewer: true,
|
||||
assetName: "tallynote-1.1.23-linux-x64-glibc.tar.gz",
|
||||
assetSize: 121000000,
|
||||
},
|
||||
job: {
|
||||
id: "mock-job-002",
|
||||
operation: "download",
|
||||
status: "downloading",
|
||||
version: "1.1.23",
|
||||
platform: "x64/glibc",
|
||||
assetName: "tallynote-1.1.23-linux-x64-glibc.tar.gz",
|
||||
sizeBytes: 121000000,
|
||||
downloadedBytes: 106480000,
|
||||
downloadStartedAt: Date.now() - 15000,
|
||||
downloadSpeedBps: 12500000, // 11.9 MB/s
|
||||
createdAt: Date.now() - 15000,
|
||||
updatedAt: Date.now(),
|
||||
},
|
||||
},
|
||||
},
|
||||
staged: {
|
||||
title: "下载完成(待立即应用)",
|
||||
description: "更新包与签名均已校验就绪,随时可以安全点击【立即更新】",
|
||||
info: {
|
||||
configured: true,
|
||||
strategy: "systemd",
|
||||
currentVersion: "1.1.22",
|
||||
platform: { target: "x64/glibc", os: "linux", arch: "x64" },
|
||||
checkedAt: Date.now() - 120_000,
|
||||
latest: {
|
||||
version: "1.1.23",
|
||||
tagName: "v1.1.23",
|
||||
compatible: true,
|
||||
integrityReady: true,
|
||||
signatureReady: true,
|
||||
isNewer: true,
|
||||
assetName: "tallynote-1.1.23-linux-x64-glibc.tar.gz",
|
||||
assetSize: 121000000,
|
||||
notes: "### TallyNote 1.1.23\n\n- 更新包已完整解压检验通过,具备升级条件。",
|
||||
},
|
||||
job: {
|
||||
id: "mock-job-003",
|
||||
operation: "download",
|
||||
status: "staged",
|
||||
version: "1.1.23",
|
||||
platform: "x64/glibc",
|
||||
assetName: "tallynote-1.1.23-linux-x64-glibc.tar.gz",
|
||||
sizeBytes: 121000000,
|
||||
downloadedBytes: 121000000,
|
||||
createdAt: Date.now() - 60000,
|
||||
updatedAt: Date.now() - 5000,
|
||||
},
|
||||
},
|
||||
},
|
||||
backing_up: {
|
||||
title: "数据备份中(更新保护)",
|
||||
description: "正在为系统数据生成安全快照备份",
|
||||
info: {
|
||||
configured: true,
|
||||
strategy: "systemd",
|
||||
currentVersion: "1.1.22",
|
||||
platform: { target: "x64/glibc", os: "linux", arch: "x64" },
|
||||
checkedAt: Date.now() - 120_000,
|
||||
latest: { version: "1.1.23", tagName: "v1.1.23", compatible: true, integrityReady: true, signatureReady: true, isNewer: true },
|
||||
job: {
|
||||
id: "mock-job-004",
|
||||
operation: "apply",
|
||||
status: "backing_up",
|
||||
version: "1.1.23",
|
||||
platform: "x64/glibc",
|
||||
createdAt: Date.now() - 20000,
|
||||
updatedAt: Date.now() - 2000,
|
||||
},
|
||||
},
|
||||
},
|
||||
applying: {
|
||||
title: "服务平滑重启中(倒计时中)",
|
||||
description: "已安全切换版本,服务正在热重启并检验状态",
|
||||
info: {
|
||||
configured: true,
|
||||
strategy: "systemd",
|
||||
currentVersion: "1.1.22",
|
||||
platform: { target: "x64/glibc", os: "linux", arch: "x64" },
|
||||
checkedAt: Date.now() - 120_000,
|
||||
latest: { version: "1.1.23", tagName: "v1.1.23", compatible: true, integrityReady: true, signatureReady: true, isNewer: true },
|
||||
job: {
|
||||
id: "mock-job-005",
|
||||
operation: "apply",
|
||||
status: "applying",
|
||||
version: "1.1.23",
|
||||
platform: "x64/glibc",
|
||||
applyQueuedAt: Date.now() - 12000,
|
||||
restartWindowSeconds: 30,
|
||||
restartDeadline: Date.now() + 18000,
|
||||
createdAt: Date.now() - 25000,
|
||||
updatedAt: Date.now() - 2000,
|
||||
},
|
||||
},
|
||||
},
|
||||
completed: {
|
||||
title: "更新成功完成",
|
||||
description: "新版本健康检查通过,已平滑无感升级至最新",
|
||||
info: {
|
||||
configured: true,
|
||||
strategy: "systemd",
|
||||
currentVersion: "1.1.23",
|
||||
platform: { target: "x64/glibc", os: "linux", arch: "x64" },
|
||||
checkedAt: Date.now() - 30_000,
|
||||
latest: { version: "1.1.23", tagName: "v1.1.23", compatible: true, integrityReady: true, signatureReady: true, isNewer: false },
|
||||
job: {
|
||||
id: "mock-job-006",
|
||||
operation: "apply",
|
||||
status: "completed",
|
||||
version: "1.1.23",
|
||||
platform: "x64/glibc",
|
||||
completedAt: Date.now() - 10000,
|
||||
createdAt: Date.now() - 45000,
|
||||
updatedAt: Date.now() - 10000,
|
||||
},
|
||||
},
|
||||
},
|
||||
failed_verify: {
|
||||
title: "更新失败状态(安全拦截)",
|
||||
description: "模拟签名不匹配或发布包篡改时的安全拦截展示与错误提示",
|
||||
info: {
|
||||
configured: true,
|
||||
strategy: "systemd",
|
||||
currentVersion: "1.1.22",
|
||||
platform: { target: "x64/glibc", os: "linux", arch: "x64" },
|
||||
checkedAt: Date.now() - 120_000,
|
||||
latest: {
|
||||
version: "1.1.23",
|
||||
tagName: "v1.1.23",
|
||||
compatible: true,
|
||||
integrityReady: false,
|
||||
signatureReady: false,
|
||||
isNewer: true,
|
||||
},
|
||||
job: {
|
||||
id: "mock-job-007",
|
||||
operation: "download",
|
||||
status: "failed",
|
||||
version: "1.1.23",
|
||||
platform: "x64/glibc",
|
||||
errorMessage: "发布包 SHA-256 校验与清单不一致,系统已自动阻断并保护原有数据。",
|
||||
createdAt: Date.now() - 30000,
|
||||
updatedAt: Date.now() - 5000,
|
||||
},
|
||||
},
|
||||
},
|
||||
disabled: {
|
||||
title: "手动源码模式",
|
||||
description: "未启用后台守护时的更新提示与引导说明",
|
||||
info: {
|
||||
configured: false,
|
||||
strategy: "disabled",
|
||||
currentVersion: "1.1.22",
|
||||
platform: { target: "macOS/darwin", os: "darwin", arch: "arm64" },
|
||||
checkedAt: Date.now() - 3600_000,
|
||||
latest: null,
|
||||
job: null,
|
||||
},
|
||||
},
|
||||
};
|
||||
@@ -116,7 +116,35 @@ input:focus-visible, textarea:focus-visible, select:focus-visible {
|
||||
transition: all 0.22s cubic-bezier(0.16, 1, 0.3, 1) !important;
|
||||
}
|
||||
.t-notification__show--top-right {
|
||||
right: 20px !important;
|
||||
top: 76px !important;
|
||||
right: 24px !important;
|
||||
z-index: 6000 !important;
|
||||
}
|
||||
@media (max-width: 768px) {
|
||||
.t-notification__show--top-right {
|
||||
top: 16px !important;
|
||||
right: 16px !important;
|
||||
left: 16px !important;
|
||||
width: auto !important;
|
||||
}
|
||||
}
|
||||
.tn-modal-error-banner {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
padding: 11px 16px;
|
||||
margin-bottom: 16px;
|
||||
border-radius: 6px;
|
||||
background: #fef2f2;
|
||||
border: 1px solid #fecaca;
|
||||
color: #991b1b;
|
||||
font-size: 13.5px;
|
||||
font-weight: 500;
|
||||
line-height: 1.4;
|
||||
}
|
||||
.tn-modal-error-banner svg {
|
||||
flex-shrink: 0;
|
||||
color: #dc2626;
|
||||
}
|
||||
|
||||
/* 核心对齐修复:清除 TDesign 默认的 margin-top: 8px 导致的文字下沉不居中 */
|
||||
@@ -774,61 +802,6 @@ input:focus-visible, textarea:focus-visible, select:focus-visible {
|
||||
TallyNote Update Center (Redesigned UI & Interactive Styles)
|
||||
========================================================================== */
|
||||
|
||||
/* Mock Console Controller */
|
||||
.tn-mock-console {
|
||||
margin-bottom: 16px;
|
||||
padding: 14px 18px;
|
||||
background: #f8fbff;
|
||||
border: 1px dashed var(--td-brand-color-3);
|
||||
border-radius: 4px;
|
||||
}
|
||||
.tn-mock-console-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
.tn-mock-console-title {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
font-size: 13px;
|
||||
color: var(--tn-navy-900);
|
||||
}
|
||||
.tn-mock-console-tip {
|
||||
font-size: 12px;
|
||||
color: var(--tn-text-secondary);
|
||||
}
|
||||
.tn-mock-scenario-chips {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
}
|
||||
.tn-scenario-chip {
|
||||
padding: 5px 11px;
|
||||
font-size: 12px;
|
||||
border: 1px solid var(--tn-border);
|
||||
border-radius: 3px;
|
||||
background: #ffffff;
|
||||
color: var(--tn-text-secondary);
|
||||
cursor: pointer;
|
||||
transition: all 0.16s ease;
|
||||
}
|
||||
.tn-scenario-chip:hover {
|
||||
border-color: var(--td-brand-color-4);
|
||||
color: var(--td-brand-color);
|
||||
background: var(--td-brand-color-1);
|
||||
}
|
||||
.tn-scenario-chip.active {
|
||||
background: var(--td-brand-color);
|
||||
border-color: var(--td-brand-color);
|
||||
color: #ffffff;
|
||||
font-weight: 600;
|
||||
box-shadow: 0 2px 6px rgba(23, 92, 211, 0.2);
|
||||
}
|
||||
|
||||
/* Update Page Actions */
|
||||
.tn-update-page-actions {
|
||||
display: flex;
|
||||
@@ -1244,10 +1217,6 @@ input:focus-visible, textarea:focus-visible, select:focus-visible {
|
||||
.tn-update-metrics-grid {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
.tn-mock-console-header {
|
||||
flex-direction: column;
|
||||
align-items: flex-start;
|
||||
}
|
||||
.tn-release-header {
|
||||
flex-direction: column;
|
||||
}
|
||||
@@ -1623,23 +1592,6 @@ input:focus-visible, textarea:focus-visible, select:focus-visible {
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
/* Compact Floating Mock Switcher at bottom-right instead of giant top banner */
|
||||
.tn-dev-mock-dock {
|
||||
position: fixed;
|
||||
bottom: 16px;
|
||||
right: 16px;
|
||||
z-index: 999;
|
||||
background: #ffffff;
|
||||
border: 1px solid var(--td-brand-color);
|
||||
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
|
||||
border-radius: 4px;
|
||||
padding: 8px 12px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
|
||||
/* ============================================================
|
||||
方案二:平滑极光光流条 (Beam Bar / Shimmer) 全局动效规范
|
||||
|
||||
Reference in New Issue
Block a user