qwen-code/scripts/verify-installation-release.js
jinye a3c8986e59 docs(serve): v0.16-alpha known limits + SDK QWEN_SERVER_TOKEN env fallback (PR 27) (#4473)
* docs(serve): v0.16-alpha known limits + SDK QWEN_SERVER_TOKEN env fallback (PR 27)

First PR in the F5 release chain (PR 27 → 28 → 30a → 31) per the
2026-05-24 v0.16-alpha scope freeze in #4175 (text-only chat / coding
+ local-only deployment).

## SDK ergonomic micro-change (~50 LOC + 4 tests)

`DaemonClient` constructor falls back to `QWEN_SERVER_TOKEN` env
var when `opts.token` is absent — closes the asymmetry where the
daemon side already honors this var (--token CLI flag fallback,
already in main since PR 15) but the SDK forced clients to thread
it through every construction.

Properties:
- Browser-safe via `globalThis.process` indirection (the SDK is
  imported by @qwen-code/webui; literal process.env access would
  explode at module load on browser bundles)
- Whitespace stripped (matches daemon-side trim — handy for
  `export QWEN_SERVER_TOKEN=\"\$(cat token.txt)\"` where cat adds a
  trailing newline)
- Empty / whitespace-only treated as unset (a stale
  `export QWEN_SERVER_TOKEN=\"\"` won't accidentally send
  Authorization: Bearer with no token)
- Resolved at construction, not lazily per-request (later
  process.env mutations don't affect already-built clients)
- Explicit opts.token wins over env

Tests: 4 new in DaemonClient.test.ts `bearer auth` describe
covering env fallback / explicit-wins / empty-treated-unset /
whitespace-stripped. Plus a defensive snapshot/restore on the
existing 'omits Authorization when no token' test so an
inherited test-runner export of QWEN_SERVER_TOKEN doesn't turn
that assertion into a false positive.

This SDK fallback is the entire ergonomic replacement for PR 29's
SDK env/file fallback. PR 29's other features (auto-gen daemon
token, instance-path keying, stale cleanup) remain deferred to
v0.16.x — all are DX improvements over the boot-time security gate
already shipped in PR 15.

## v0.16-alpha docs (~120 LOC markdown)

- docs/users/qwen-serve.md: new "v0.16-alpha known limits" section
  enumerating product surface (text-only ✅, multimodal ❌),
  deployment surface (local launchers ✅, containerized ❌, multi-
  daemon ❌, BYO-token ✅), and hardening posture (boot security
  gate ✅, mutation gate ✅, MCP guardrails ✅, prompt absolute
  deadline ⏸️, rate limiting ⏸️, --max-body-size ⏸️). Adds an
  alpha banner at the top of the file.

- docs/developers/examples/daemon-client-quickstart.md:
  documents the SDK env fallback in both the Hello-daemon
  intro and the Authentication section, with the "export +
  no-token-arg" recommended path called out for local dev.

Verification: 125/125 DaemonClient.test.ts pass (121 existing +
4 new); 4/4 daemon-public-surface.test.ts pass (constructor
signature unchanged); tsc clean on packages/sdk-typescript;
eslint --max-warnings 0 clean on touched .ts files.

Part of #4175.

* fix(sdk): #4473 round 1 fold-in — 2 copilot doc threads adopted

T1 [copilot DaemonClient.ts:144 — stale line refs in readTokenFromEnv
  JSDoc]: removed `runQwenServe.ts:175` (token resolution actually
  lives at line 302-318 today, would drift again on next refactor)
  and `docs/users/qwen-serve.md:173`. Replaced with stable
  symbol/section references ("runQwenServe token-resolution path";
  "qwen-serve user guide CLI flags section").

T2 [copilot daemon-client-quickstart.md:33 — `~/.qwen/server-token`
  implies built-in path that doesn't exist]: PR 27 explicitly defers
  token auto-generation + file-store fallback (PR 29 deferred features).
  The example incorrectly suggested a standard file location.
  Replaced with two explicit user-managed alternatives:
  - `openssl rand -hex 32` one-shot
  - `cat ./my-token-file` user-managed file

Both threads were accurate suggestions caught at the right time
(zero behavior change; pure docstring/example accuracy).

Verification: 125/125 DaemonClient tests pass; tsc + eslint clean
on touched files.
2026-05-27 10:31:34 +08:00

305 lines
8.6 KiB
JavaScript

#!/usr/bin/env node
/**
* @license
* Copyright 2026 Qwen Team
* SPDX-License-Identifier: Apache-2.0
*/
import crypto from 'node:crypto';
import fs from 'node:fs';
import path from 'node:path';
import { Readable } from 'node:stream';
import { pipeline } from 'node:stream/promises';
import { fileURLToPath } from 'node:url';
import { RELEASE_TARGETS } from './build-standalone-release.js';
import {
fail,
isMainModule,
parseArgs,
parseSha256Sums,
sha256File,
} from './release-script-utils.js';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const rootDir = path.resolve(__dirname, '..');
const EXPECTED_STANDALONE_ARCHIVE_NAMES =
standaloneArchiveNamesFromReleaseTargets(RELEASE_TARGETS);
// Release artifacts that the installer chain expects in a GitHub Release.
// Hosted installer scripts are served from a separate endpoint and are
// intentionally not part of this set; they have their own staging path in
// `package:hosted-installation`.
const EXPECTED_RELEASE_ASSET_NAMES = [
...EXPECTED_STANDALONE_ARCHIVE_NAMES,
'SHA256SUMS',
];
const REMOTE_FETCH_TIMEOUT_MS = 30_000;
// Mirrors `build-standalone-release.js`'s archive-name derivation. The two
// must stay aligned: any new platform/extension landing in RELEASE_TARGETS
// has to be reflected here (and there) before a new target ships, otherwise
// the verify and the build will disagree on expected filenames.
function standaloneArchiveNamesFromReleaseTargets(releaseTargets) {
return releaseTargets.map(
({ qwenTarget }) =>
`qwen-code-${qwenTarget}.${qwenTarget === 'win-x64' ? 'zip' : 'tar.gz'}`,
);
}
const ARG_DEFS = {
'--dir': { key: 'dir', type: 'value' },
'--base-url': { key: 'baseUrl', type: 'value' },
'--list-release-asset-paths': {
key: 'listReleaseAssetPaths',
type: 'flag',
},
};
if (isMainModule(import.meta.url)) {
try {
await main();
} catch (error) {
console.error(error instanceof Error ? error.message : error);
process.exitCode = 1;
}
}
async function main() {
const args = parseArgs(process.argv.slice(2), ARG_DEFS);
if (args.help) {
printUsage();
return;
}
if (args.dir && args.baseUrl) {
fail('Pass --dir or --base-url, not both.');
}
if (args.listReleaseAssetPaths && args.baseUrl) {
fail('Pass --list-release-asset-paths with --dir, not --base-url.');
}
if (args.listReleaseAssetPaths) {
const dir = path.resolve(
args.dir || path.join(rootDir, 'dist', 'standalone'),
);
await verifyReleaseDirectory(dir, { silent: true });
for (const assetPath of releaseAssetPaths(dir)) {
console.log(assetPath);
}
return;
}
if (args.baseUrl) {
await verifyReleaseBaseUrl(args.baseUrl);
return;
}
await verifyReleaseDirectory(
path.resolve(args.dir || path.join(rootDir, 'dist', 'standalone')),
);
}
function printUsage() {
console.log(`Usage: npm run verify:installation-release -- [options]
Verifies that an installation release directory contains the expected standalone
archives with matching SHA256SUMS entries. For a release URL, downloads
SHA256SUMS and the expected archives, then verifies each archive hash.
Options:
--dir PATH Verify a local release directory. Defaults to dist/standalone.
--base-url URL Verify a remote release URL (e.g. a GitHub release download
prefix). Cannot be combined with --dir.
--list-release-asset-paths
Verify --dir, then print explicit asset paths for upload.
-h, --help Show this help message.
`);
}
async function verifyReleaseDirectory(dir, options = {}) {
const { silent = false } = options;
const checksums = readReleaseChecksums(dir);
assertExpectedChecksumEntries(checksums);
assertExpectedArchiveFiles(dir);
for (const assetName of EXPECTED_STANDALONE_ARCHIVE_NAMES) {
const assetPath = path.join(dir, assetName);
if (!fs.existsSync(assetPath)) {
fail(`Missing release asset: ${assetName}`);
}
const actual = await sha256File(assetPath);
const expected = checksums.get(assetName);
if (actual !== expected) {
fail(
`Checksum mismatch for ${assetName}: expected ${expected}, got ${actual}`,
);
}
}
if (!silent) {
console.log(
`Verified ${EXPECTED_RELEASE_ASSET_NAMES.length} installation release assets in ${dir}`,
);
}
}
async function verifyReleaseBaseUrl(baseUrl, options = {}) {
const { fetchImpl = fetch } = options;
const normalizedBaseUrl = normalizeHttpsBaseUrl(baseUrl);
const checksumUrl = new URL('SHA256SUMS', normalizedBaseUrl).toString();
const checksums = parseSha256Sums(await fetchText(checksumUrl, fetchImpl));
assertExpectedChecksumEntries(checksums);
await assertRemoteAssetChecksums(normalizedBaseUrl, checksums, fetchImpl);
console.log(
`Verified ${EXPECTED_RELEASE_ASSET_NAMES.length} installation release assets at ${baseUrl}`,
);
}
function readReleaseChecksums(dir) {
const checksumPath = path.join(dir, 'SHA256SUMS');
if (!fs.existsSync(checksumPath)) {
fail(`SHA256SUMS was not found at ${checksumPath}`);
}
return parseSha256Sums(fs.readFileSync(checksumPath, 'utf8'));
}
function assertExpectedChecksumEntries(checksums) {
const expected = new Set(EXPECTED_STANDALONE_ARCHIVE_NAMES);
const missing = EXPECTED_STANDALONE_ARCHIVE_NAMES.filter(
(assetName) => !checksums.has(assetName),
);
const extra = Array.from(checksums.keys()).filter(
(assetName) => !expected.has(assetName),
);
if (missing.length > 0) {
fail(`Missing release asset checksum: ${missing.join(', ')}`);
}
if (extra.length > 0) {
fail(`Unexpected release asset checksum: ${extra.join(', ')}`);
}
}
function assertExpectedArchiveFiles(dir) {
const expected = new Set(EXPECTED_RELEASE_ASSET_NAMES);
const extra = fs
.readdirSync(dir)
.filter((assetName) => !expected.has(assetName))
.sort();
if (extra.length > 0) {
fail(`Unexpected release asset: ${extra.join(', ')}`);
}
}
function releaseAssetPaths(dir) {
return EXPECTED_RELEASE_ASSET_NAMES.map((assetName) =>
path.join(dir, assetName),
);
}
async function assertRemoteAssetChecksums(
normalizedBaseUrl,
checksums,
fetchImpl,
) {
const failures = [];
for (const assetName of EXPECTED_STANDALONE_ARCHIVE_NAMES) {
try {
const assetUrl = new URL(assetName, normalizedBaseUrl).toString();
const actual = await fetchSha256(assetUrl, fetchImpl);
const expected = checksums.get(assetName);
if (actual !== expected) {
fail(
`Checksum mismatch for ${assetName}: expected ${expected}, got ${actual}`,
);
}
} catch (reason) {
failures.push({
assetName,
reason: formatErrorReason(reason),
});
}
}
if (failures.length === 0) {
return;
}
if (failures.length === EXPECTED_STANDALONE_ARCHIVE_NAMES.length) {
fail(
`All ${failures.length} release asset URLs are unavailable; check --base-url: ${normalizedBaseUrl}`,
);
}
fail(
`Unavailable or invalid release asset(s): ${failures
.map(({ assetName, reason }) => `${assetName} (${reason})`)
.join('; ')}`,
);
}
async function fetchSha256(url, fetchImpl) {
const response = await fetchWithTimeout(fetchImpl, url);
if (!response.ok) {
fail(
`Failed to download ${url}: ${response.status} ${response.statusText}`,
);
}
if (!response.body) {
fail(`Downloaded response has no body: ${url}`);
}
const hash = crypto.createHash('sha256');
await pipeline(Readable.fromWeb(response.body), hash);
return hash.digest('hex');
}
function formatErrorReason(reason) {
if (reason instanceof Error) {
return reason.message.replace(/^ERROR:\s*/, '');
}
return String(reason);
}
async function fetchText(url, fetchImpl) {
const response = await fetchWithTimeout(fetchImpl, url);
if (!response.ok) {
fail(
`Failed to download ${url}: ${response.status} ${response.statusText}`,
);
}
return response.text();
}
function fetchWithTimeout(fetchImpl, url, options = {}) {
return fetchImpl(url, {
...options,
signal: AbortSignal.timeout(REMOTE_FETCH_TIMEOUT_MS),
});
}
function normalizeHttpsBaseUrl(baseUrl) {
let parsed;
try {
parsed = new URL(baseUrl);
} catch {
fail(`--base-url must be a valid URL: ${baseUrl}`);
}
if (parsed.protocol !== 'https:') {
fail(`--base-url must use https: ${baseUrl}`);
}
if (!parsed.pathname.endsWith('/')) {
parsed.pathname = `${parsed.pathname}/`;
}
return parsed.toString();
}
export {
EXPECTED_STANDALONE_ARCHIVE_NAMES,
EXPECTED_RELEASE_ASSET_NAMES,
releaseAssetPaths,
verifyReleaseBaseUrl,
verifyReleaseDirectory,
};