Files
qwen-code/scripts/tests/brand-create-safety.test.js
易良andQwen-Coder 73aa65a4b4 chore(desktop): rename packages/desktop-shell to packages/desktop (#12653)
* chore(desktop): rename packages/desktop-shell to packages/desktop

The Electron-era packages/desktop was removed in #9085 and the OpenWork
downstream has forked, so the short name is free and the shell suffix is
the only thing left of the transition. Rename the package directory and
every load-bearing reference: workspace negations (npm + pnpm), the ci.yml
crate filter, desktop-release.yml, the isolation guard, lint/ignore configs,
scripts tests, CLI workspace-fixture tests, and living docs.

User-facing identity is untouched: the crate stays qwen-code-desktop,
productName stays "Qwen Code Desktop", the bundle identifier, updater
feed, release tag scheme, and the legacy electron-bridge asset names are
all unchanged. check-desktop-isolation now guards both path names so the
old one cannot re-enter a workspace set. Dated design docs under
docs/design/ keep their historical paths deliberately.

Refs #8596

* docs(design): follow the rename in the undated notification design notes

The web-shell-browser-notification-details pair is a living doc without a
date prefix, so it falls under the PR's update rule rather than the
historical-record exception.

* docs(desktop): stop citing paths the rename invalidated

Three prose sites and one CI comment still described the pre-rename world,
or contradicted themselves once `packages/desktop` named both the removed
Electron app and the living Tauri shell.

- ci.yml `desktop_shell`: the comment this branch added credited the
  Cargo.toml guard with keeping "branches from either side of the rename"
  green. It does not. A pre-rename head's files sit under
  `packages/desktop-shell`, which the changed-files filter no longer
  matches, so the job skips before the guard ever runs. Say that, and say
  what the guard does cover (a head the filter matched because ci.yml
  itself changed, with no crate at the new path).
- docs/design/web-shell-user-message-links.md: "desktop-shell routing" /
  "desktop-shell clicks" -> "desktop-host", the wording this branch already
  chose in LinkifiedText.tsx for the same rule.
- docs/design/telemetry-runtime-client-attribution-design.md: repoint the
  `runtime.rs` citation. It backs the live `QWEN_CODE_DESKTOP=1` claim, and
  the other document of record for that invariant -- the comment in
  acp-channel-fallback.ts -- was already repointed by this branch, so the
  two disagreed. Only the path token changes; the doc's dated findings are
  untouched.
- brand-create.mjs / SKILL.md / src-tauri/src/main.rs: name the historical
  referent as historical (the Electron `packages/desktop` removed in PR
  9085) instead of letting it read as a self-reference. In main.rs the
  citation `packages/desktop/packages/shared/src/config/storage.ts` now
  looked like a subpath of the file's own package. Rewritten, not deleted:
  the `QWEN_DEFAULT_WORKSPACE_DIR` clause next to it is the only in-code
  documentation of that override and still resolves.

Deliberately not swept: `scripts/check-desktop-isolation.js`'s
`packages/desktop-shell` tripwire, ci.yml's #8132 history comment,
`docs/design/9152-architecture-invariant-classification.md` (names both
spellings and is accurate), and the date-prefixed
`docs/design/2026-07-31-desktop-web-shell-release.md`.

Co-authored-by: Qwen-Coder <[email protected]>
Patrol-Run: qwen-pr-closeout/jmug1iw422v

* test(scripts): pin the desktop crate path and the isolation guard's coverage

Both invariants fail green today, and this rename is the second time the
crate directory has moved.

`scripts/check-desktop-isolation.js` gained `'packages/desktop'` in
`nativePrefixes` -- the only production-logic line in this branch -- and
nothing read it. Deleting that line leaves the guard's output and exit code
byte-identical, because `isNativeLocation('packages/desktop')` then matches
no remaining prefix; a later PR that drops `!packages/desktop` from the root
workspace list would re-admit the package with CI green.

The `desktop_shell` job names the crate directory in five places (the
changed-files filter, the Cargo.toml guard and its `::notice::` text, the
rust-cache `workspaces:`, and two `working-directory:` values). Nothing
asserted they agree with each other or with a directory that exists, so the
next drift reports a skipped job as a passed one.

The new suite parses both instead of re-running them, and is superset-shaped
on purpose: `nativePrefixes` carries a fourth entry (the
`packages/desktop-shell` tripwire) that nothing negates, and an exact-match
assertion would invite deleting it. The npm/pnpm mirror of the negation list
is already pinned by package-scripts.test.js, so this reads package.json only.

Verified by mutation, each applied alone and then restored: reverting the
filter alternative or either `working-directory` to `packages/desktop-shell`,
dropping `'packages/desktop'` from `nativePrefixes`, and dropping
`!packages/desktop` from package.json all turn this suite red. Today no other
test does.

Co-authored-by: Qwen-Coder <[email protected]>
Patrol-Run: qwen-pr-closeout/jmug1iw422v

* test(scripts): pin what the desktop-isolation tests actually claim

Four review findings on scripts/tests/desktop-isolation.test.js, each
verified by mutating the thing it claims to pin, before and after.

- The comment above the local `isNativeLocation` copy claimed a change to
  the script's rule "has to be made here too". Nothing reads the rule back
  from the producer -- `nativePrefixesFromSource` parses the array literal
  only -- and narrowing the script's rule to prefix equality leaves the
  suite green. Describe the copy instead of claiming coupling that does not
  exist.
- `still carries the Cargo.toml existence guard` matched only the guard's
  condition text. Flip the body's `changed=false` to `changed=true`, or move
  it after `fi`, and the suite stayed green at 5/5 while the job runs every
  gated step against a crate that is not there. Assert the assignment sits
  inside the guard's own `if ... fi` body.
- Both on-disk checks keyed on the bare directory, so git-ignored residue
  under `packages/desktop-shell` (`node_modules`, which survives a branch
  switch with an empty `git status`) reddened two tests on a tree with no
  defect and blamed the root workspace set. Key on `package.json`, which is
  what `packages/*` requires to make a directory a workspace member; a real
  re-entry still reddens both.
- The `startsWith(filterAlternative)` assertion compared a path built from
  `crateDir` -- `filterAlternative` with one trailing slash stripped -- back
  against `filterAlternative`, so it could not fail for any input. Dropping
  the trailing slash from the changed-files filter in ci.yml left it green.
  Replace it with the property that makes the alternative a path prefix
  rather than a bare string prefix.

Co-authored-by: Qwen-Coder <[email protected]>
Patrol-Run: qwen-pr-closeout/jmugedurp3j

---------

Co-authored-by: Qwen-Coder <[email protected]>
2026-09-25 05:41:25 +00:00

331 lines
11 KiB
JavaScript

/**
* @license
* Copyright 2026 Qwen Team
* SPDX-License-Identifier: Apache-2.0
*/
import { spawnSync } from 'node:child_process';
import {
mkdtempSync,
mkdirSync,
writeFileSync,
rmSync,
readFileSync,
} from 'node:fs';
import { join } from 'node:path';
import { tmpdir } from 'node:os';
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
const SCRIPT = join(
__dirname,
'..',
'..',
'packages',
'desktop',
'.agents',
'skills',
'desktop-brand-builder',
'scripts',
'brand-create.mjs',
);
/**
* Create a minimal fake shell-root with the files brand-create.mjs expects.
* Pass { withUpdater: false } to model a fork or hand-edited shell-root
* whose tauri.conf.json has no plugins.updater section.
*/
function makeShellRoot({ withUpdater = true } = {}) {
const root = mkdtempSync(join(tmpdir(), 'brand-test-shell-'));
mkdirSync(join(root, 'src-tauri', 'icons'), { recursive: true });
mkdirSync(join(root, 'bootstrap'), { recursive: true });
const tauriConfig = {
productName: 'Qwen Code Desktop',
identifier: 'com.qwen.code.desktop',
bundle: { createUpdaterArtifacts: true, shortDescription: '' },
};
if (withUpdater) {
tauriConfig.plugins = {
updater: {
endpoints: ['https://updater.qwen-code.org'],
pubkey: 'dGVzdA==',
},
};
}
writeFileSync(
join(root, 'src-tauri', 'tauri.conf.json'),
JSON.stringify(tauriConfig),
);
writeFileSync(
join(root, 'package.json'),
JSON.stringify({ name: 'desktop', type: 'module' }),
);
return root;
}
/**
* Seed a minimal @tauri-apps/cli stub so generateIcons resolves and runs it
* locally instead of falling back to a slow, network-dependent `npx --yes`.
*/
function seedTauriCliStub(root) {
const cliDir = join(root, 'node_modules', '@tauri-apps', 'cli');
mkdirSync(cliDir, { recursive: true });
writeFileSync(
join(cliDir, 'package.json'),
JSON.stringify({ name: '@tauri-apps/cli', version: '0.0.0' }),
);
writeFileSync(join(cliDir, 'tauri.js'), 'process.exit(0);\n');
}
function makeLogo(dir) {
const logoPath = join(dir, 'logo.png');
const png = Buffer.from(
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==',
'base64',
);
writeFileSync(logoPath, png);
return logoPath;
}
function runBrand(shellRoot, brandConfig) {
const dir = mkdtempSync(join(tmpdir(), 'brand-test-cfg-'));
const configPath = join(dir, 'brand.json');
writeFileSync(configPath, JSON.stringify(brandConfig));
const result = spawnSync(
process.execPath,
[SCRIPT, '--shell-root', shellRoot, '--config', configPath],
{ encoding: 'utf8', timeout: 10_000 },
);
return { ...result, configDir: dir };
}
let shellRoot;
let logoPath;
const tmpDirs = [];
beforeEach(() => {
shellRoot = makeShellRoot();
logoPath = makeLogo(shellRoot);
});
afterEach(() => {
for (const d of tmpDirs) {
try {
rmSync(d, { recursive: true, force: true });
} catch {
/* best-effort cleanup */
}
}
try {
rmSync(shellRoot, { recursive: true, force: true });
} catch {
/* best-effort cleanup */
}
});
describe('brand-create.mjs safety checks', () => {
// R1-4: Shell injection via logo path
it('does not use shell:true when invoking the icon generator', () => {
const source = readFileSync(SCRIPT, 'utf8');
const fnMatch = source.match(/function generateIcons[\s\S]*?\n\}/);
expect(fnMatch).toBeTruthy();
expect(fnMatch[0]).not.toContain('shell: true');
expect(fnMatch[0]).not.toContain('shell:true');
expect(fnMatch[0]).not.toContain('safeLogo');
});
// R1-1: Missing updaterPubkey for bring-your-own-feed
it('rejects updaterEndpoints without updaterPubkey', () => {
const result = runBrand(shellRoot, {
brandId: 'acme-ai',
logo: logoPath,
updaterEndpoints: ['https://updates.acme.ai'],
});
expect(result.status).not.toBe(0);
expect(result.stderr).toContain('updaterPubkey');
});
// R6-1: a scalar (non-array) updaterEndpoints must fail loudly instead
// of being silently coerced to [], which would ship the brand with
// in-app updates permanently disabled while brand-create exits 0.
it('rejects non-array updaterEndpoints instead of coercing to []', () => {
const confPath = join(shellRoot, 'src-tauri', 'tauri.conf.json');
const scalars = [
'https://updates.acme.ai/feed.json', // typo of the array shape
{ url: 'https://updates.acme.ai/feed.json' },
42,
true,
];
for (const updaterEndpoints of scalars) {
const before = readFileSync(confPath, 'utf8');
const result = runBrand(shellRoot, {
brandId: 'acme-ai',
logo: logoPath,
updaterEndpoints,
});
expect(result.status, result.stderr).not.toBe(0);
expect(result.stderr).toContain('JSON array');
expect(
readFileSync(confPath, 'utf8'),
`value=${JSON.stringify(updaterEndpoints)}`,
).toBe(before);
}
});
it('still accepts omitted or empty-array updaterEndpoints', () => {
for (const extra of [{}, { updaterEndpoints: [] }]) {
const root = makeShellRoot();
tmpDirs.push(root);
seedTauriCliStub(root);
const logo = makeLogo(root);
const result = runBrand(root, {
brandId: 'acme-ai',
logo,
...extra,
});
expect(result.status, result.stderr).toBe(0);
}
});
it('accepts updaterEndpoints when updaterPubkey is provided', () => {
const result = runBrand(shellRoot, {
brandId: 'acme-ai',
logo: logoPath,
updaterEndpoints: ['https://updates.acme.ai'],
updaterPubkey: 'dGVzdHB1YmtleQ==',
});
// May fail later (e.g., tauri icon not installed) but must NOT fail
// on the updaterPubkey validation.
expect(result.stderr).not.toContain('updaterPubkey is missing');
});
// R3-4: Single-use guard bypass when appName === productName
it('rejects appName equal to the pristine default "Qwen Code Desktop"', () => {
const result = runBrand(shellRoot, {
brandId: 'acme-ai',
logo: logoPath,
appName: 'Qwen Code Desktop',
});
expect(result.status).not.toBe(0);
expect(result.stderr).toContain('Qwen Code Desktop');
expect(result.stderr).toContain('re-run guard');
});
it('rejects brandId that derives appName "Qwen Code Desktop"', () => {
// brandId "qwen-code-desktop" → titleWords → "Qwen Code Desktop"
const result = runBrand(shellRoot, {
brandId: 'qwen-code-desktop',
logo: logoPath,
});
expect(result.status).not.toBe(0);
expect(result.stderr).toContain('Qwen Code Desktop');
});
// Hostile appName escaping: appName is a free-form override, and the
// bootstrap.js patcher must not emit invalid JS for it. Previously only
// single quotes were escaped, so a trailing backslash escaped the
// literal's closing quote while brand-create still exited 0.
it('keeps generated bootstrap.js valid JS for hostile appName values', () => {
const hostileNames = [
"Bob's App\\", // trailing backslash (the reported trigger)
'Line1\nLine2', // raw newline is invalid in a single-quoted literal
'Say "hi"', // double quotes
'It\'s "quoted" \\ done', // quotes and backslashes combined
];
for (const appName of hostileNames) {
const root = makeShellRoot();
tmpDirs.push(root);
seedTauriCliStub(root);
const logo = makeLogo(root);
const bootstrapPath = join(root, 'bootstrap', 'bootstrap.js');
writeFileSync(
bootstrapPath,
"const a = 'Starting Qwen Code';\nconst b = 'Restarting Qwen Code';\n",
);
const result = runBrand(root, {
brandId: 'acme-ai',
logo,
appName,
});
expect(result.status, result.stderr).toBe(0);
const check = spawnSync(process.execPath, ['--check', bootstrapPath], {
encoding: 'utf8',
});
expect(check.status, check.stderr).toBe(0);
}
}, 60_000);
// R5-1: appName is also spliced into bootstrap/index.html (<title>,
// alt attribute, <h1>, <h2>), where it must be HTML-escaped so the
// branded startup screen stays well-formed for free-form brand names.
it('HTML-escapes hostile appName values in bootstrap/index.html', () => {
const cases = [
{
appName: 'Acme <Corp>',
expected: [
'<title>Acme &lt;Corp&gt;</title>',
'alt="Acme &lt;Corp&gt;"',
'<h1>Acme &lt;Corp&gt;</h1>',
'<h2 id="title">Starting Acme &lt;Corp&gt;</h2>',
],
hostileFragment: '<Corp>',
},
{
appName: 'Acme "Beta" <Desktop>',
expected: [
'<title>Acme &quot;Beta&quot; &lt;Desktop&gt;</title>',
'alt="Acme &quot;Beta&quot; &lt;Desktop&gt;"',
'<h1>Acme &quot;Beta&quot; &lt;Desktop&gt;</h1>',
'<h2 id="title">Starting Acme &quot;Beta&quot; &lt;Desktop&gt;</h2>',
],
hostileFragment: 'alt="Acme "Beta"',
},
];
for (const { appName, expected, hostileFragment } of cases) {
const root = makeShellRoot();
tmpDirs.push(root);
seedTauriCliStub(root);
const logo = makeLogo(root);
const indexPath = join(root, 'bootstrap', 'index.html');
writeFileSync(
indexPath,
'<!doctype html>\n<html>\n<head>\n<title>Qwen Code</title>\n' +
'</head>\n<body>\n<img src="qwen-code-logo.svg" alt="Qwen Code">\n' +
'<h1>Qwen Code</h1>\n<h2 id="title">Starting Qwen Code</h2>\n' +
'</body>\n</html>\n',
);
const result = runBrand(root, {
brandId: 'acme-ai',
logo,
appName,
});
expect(result.status, result.stderr).toBe(0);
const html = readFileSync(indexPath, 'utf8');
for (const snippet of expected) {
expect(html, `appName=${appName}`).toContain(snippet);
}
expect(html, `appName=${appName}`).not.toContain(hostileFragment);
}
}, 60_000);
// R5-8: the brand's validated updater config must not be silently
// discarded when the target tauri.conf.json has no plugins.updater
// section; fail closed with the config file left unmutated.
it('fails closed when the shell-root has no plugins.updater section', () => {
const root = makeShellRoot({ withUpdater: false });
tmpDirs.push(root);
const logo = makeLogo(root);
const confPath = join(root, 'src-tauri', 'tauri.conf.json');
const before = readFileSync(confPath, 'utf8');
const result = runBrand(root, {
brandId: 'acme-ai',
logo,
updaterEndpoints: ['https://updates.acme.ai'],
updaterPubkey: 'dGVzdHB1YmtleQ==',
});
expect(result.status).not.toBe(0);
expect(result.stderr).toContain('plugins.updater');
expect(readFileSync(confPath, 'utf8')).toBe(before);
}, 60_000);
});