Selaa lähdekoodia

Merge remote-tracking branch 'origin/main' into codex/fix-config-permissions

hetaoBackend 2 kuukautta sitten
vanhempi
sitoutus
d0178d90ef

+ 4 - 2
README.md

@@ -78,7 +78,7 @@ mcode login --region global
 
 
 Complete sign-in in your browser, then open `mcode` and use `/status` to check your account and `/provider` to choose a model. Run `mcode logout` to sign out.
 Complete sign-in in your browser, then open `mcode` and use `/status` to check your account and `/provider` to choose a model. Run `mcode logout` to sign out.
 
 
-Token Plan requires an account with available credits. User data is stored in `~/.minimax-code` by default.
+Token Plan requires an account with available credits. The published npm CLI `@minimax-ai/code@0.4.12` defaults to `~/.minimax` for user data; builds from this repository default to `~/.minimax-code`. `MINIMAX_DATA_DIR` or `MAVIS_DATA_DIR` can override the data directory. The installer's `~/.minimax-code` installation directory is separate from this choice. See [Accounts and data](docs/installation.md#accounts-and-data) before locating or removing configuration and sessions.
 
 
 <details>
 <details>
 <summary>Use your own API key (BYOK)</summary>
 <summary>Use your own API key (BYOK)</summary>
@@ -197,7 +197,9 @@ For now, code and documentation pull requests are accepted only from repository
 
 
 ## Desktop app and support
 ## Desktop app and support
 
 
-<img src="https://filecdn.minimax.chat/public/c3ebbd2e-f55b-48d7-adff-030abb63e06d.png" alt="MiniMax Code desktop app" width="100%" />
+<a href="https://agent.minimax.io/download" title="Download MiniMax Code">
+  <img src="https://filecdn.minimax.chat/public/c3ebbd2e-f55b-48d7-adff-030abb63e06d.png" alt="MiniMax Code desktop app — click to download" width="100%" />
+</a>
 
 
 [Download for macOS or Windows](https://agent.minimax.io/download) · [Report a problem or ask a question](https://github.com/MiniMax-AI/minimax-code/issues/new/choose)
 [Download for macOS or Windows](https://agent.minimax.io/download) · [Report a problem or ask a question](https://github.com/MiniMax-AI/minimax-code/issues/new/choose)
 
 

+ 4 - 2
README_ZH.md

@@ -78,7 +78,7 @@ mcode login --region global
 
 
 在浏览器中完成登录,再启动 `mcode`,通过 `/status` 检查账号、通过 `/provider` 选择模型。退出登录使用 `mcode logout`。
 在浏览器中完成登录,再启动 `mcode`,通过 `/status` 检查账号、通过 `/provider` 选择模型。退出登录使用 `mcode logout`。
 
 
-Token Plan 需要账号与可用额度。默认用户数据保存在 `~/.minimax-code`。
+Token Plan 需要账号与可用额度。已发布的 npm CLI `@minimax-ai/code@0.4.12` 默认将用户数据保存在 `~/.minimax`;从本仓库构建的版本默认为 `~/.minimax-code`。`MINIMAX_DATA_DIR` 或 `MAVIS_DATA_DIR` 可以覆盖数据目录。安装脚本使用的 `~/.minimax-code` 安装目录与数据目录的选择是两回事。查找或删除配置和会话前,请参阅[账号与数据](docs/installation.md#accounts-and-data)。
 
 
 <details>
 <details>
 <summary>使用自己的 API Key(BYOK)</summary>
 <summary>使用自己的 API Key(BYOK)</summary>
@@ -197,7 +197,9 @@ node /absolute/path/to/minimax-code/dist/cli.js
 
 
 ## 桌面版与问题反馈
 ## 桌面版与问题反馈
 
 
-<img src="https://filecdn.minimax.chat/public/c3ebbd2e-f55b-48d7-adff-030abb63e06d.png" alt="MiniMax Code 桌面版" width="100%" />
+<a href="https://agent.minimaxi.com/download" title="下载 MiniMax Code">
+  <img src="https://filecdn.minimax.chat/public/c3ebbd2e-f55b-48d7-adff-030abb63e06d.png" alt="MiniMax Code 桌面版 — 点击下载" width="100%" />
+</a>
 
 
 [下载 macOS 或 Windows 桌面版](https://agent.minimaxi.com/download) · [报告问题或提问](https://github.com/MiniMax-AI/minimax-code/issues/new/choose)
 [下载 macOS 或 Windows 桌面版](https://agent.minimaxi.com/download) · [报告问题或提问](https://github.com/MiniMax-AI/minimax-code/issues/new/choose)
 
 

+ 1 - 1
SECURITY.md

@@ -10,7 +10,7 @@ Include the affected version, operating system and Node.js version, a minimal re
 
 
 ## Data and service boundaries
 ## Data and service boundaries
 
 
-- The default data directory, `~/.minimax-code`, stores login state, provider configuration, and sessions. It is not shareable project configuration. Restrict local access and keep it out of Git.
+- The active data directory stores login state, provider configuration (including API keys in `config.yaml`), and sessions. The published npm CLI `@minimax-ai/code@0.4.12` defaults to `~/.minimax`; builds from this repository default to `~/.minimax-code`. Environment overrides can select another directory. Follow [Accounts and data](docs/installation.md#accounts-and-data) to identify it; the installer location alone does not identify stored credentials. Restrict local access to every data directory you have used and keep them out of Git, including old profiles. They are not shareable project configuration.
 - Models, official plugins, connectors, search, media, feedback, and telemetry may contact external services. Those services continue to control authorization and credits; source access does not grant access to accounts or third-party resources.
 - Models, official plugins, connectors, search, media, feedback, and telemetry may contact external services. Those services continue to control authorization and credits; source access does not grant access to accounts or third-party resources.
 - mcode-tools obtains short-lived access tokens through the host's lease broker. Never pass refresh tokens to tool processes.
 - mcode-tools obtains short-lived access tokens through the host's lease broker. Never pass refresh tokens to tool processes.
 - Permissions and sandboxing do not replace review of untrusted plugins, MCP servers, and shell commands. If automatic permission classification is unavailable, retain user confirmation rather than allowing operations by default.
 - Permissions and sandboxing do not replace review of untrusted plugins, MCP servers, and shell commands. If automatic permission classification is unavailable, retain user confirmation rather than allowing operations by default.

+ 18 - 1
docs/installation.md

@@ -39,7 +39,24 @@ On Windows, also use `node` with the appropriate local absolute path. Do not ove
 
 
 Run `/login` in the TUI or `pnpm mcode login`, choosing the region for your account. Token Plan requires an account and available credits. See the root README for BYOK configuration and testing.
 Run `/login` in the TUI or `pnpm mcode login`, choosing the region for your account. Token Plan requires an account and available credits. See the root README for BYOK configuration and testing.
 
 
-The default data directory is `~/.minimax-code`. For tests, explicitly set `MINIMAX_DATA_DIR` to a temporary directory to keep normal sessions separate. Use `$env:MINIMAX_DATA_DIR = 'C:\path\to\test-profile'` in PowerShell or `export MINIMAX_DATA_DIR=/path/to/test-profile` in a POSIX shell.
+Data-directory defaults depend on the artifact you run:
+
+| CLI artifact | Default user data directory |
+| --- | --- |
+| Published npm `@minimax-ai/code@0.4.12` | `~/.minimax` |
+| Build from this repository | `~/.minimax-code` |
+
+The npm 0.4.12 default was checked against the [public registry artifact](https://registry.npmjs.org/@minimax-ai/code/0.4.12) on 2026-09-19, with its SHA-512 integrity verified. This applies to that published version, including local npm dependencies; do not infer the default of another release from its version label alone. The source default is defined in [`data-dir.ts`](../packages/tui/src/runtime/data-dir.ts). Login state, provider configuration such as `config.yaml`, caches, and sessions belong to the selected data directory.
+
+Both accept a non-empty `MINIMAX_DATA_DIR`, falling back to a non-empty `MAVIS_DATA_DIR`, before the default. The [macOS / Linux / WSL installer](https://filecdn.minimax.chat/public/install.sh) installs the npm package under `~/.minimax-code` by default (`MCODE_INSTALL_DIR` changes the installation location). It does not set either data-directory override. Installation files and user data are separate concerns, even when their directories have the same name.
+
+To locate data safely:
+
+1. Identify the launcher you actually use with `command -v mcode` (POSIX) or `Get-Command mcode -All` (PowerShell), and run that launcher's `--version`. For a local npm dependency, use `node_modules/.bin/mcode --version`; a global npm listing does not identify it. A source build may report the same version as the npm release.
+2. Check whether either data-directory override is set in that launcher's environment. Otherwise use the artifact-specific default above. Inspect directory and file names/permissions locally, without printing `config.yaml`, authentication files, or session contents. For builds from this repository, `mcode telemetry status` also reports the selected `configFile` path without printing credentials; npm 0.4.12 does not provide that command.
+3. If both directories exist, their presence alone does not identify the active one. Keep both protected, and include the launcher, version, installation method, and whether overrides are set when requesting help. Redact personal path components; do not attach configuration or authentication files. Changing an override does not migrate existing data, so do not move or delete either directory merely to match these docs.
+
+For tests, explicitly set `MINIMAX_DATA_DIR` to a temporary directory to keep normal sessions separate. Use `$env:MINIMAX_DATA_DIR = 'C:\path\to\test-profile'` in PowerShell or `export MINIMAX_DATA_DIR=/path/to/test-profile` in a POSIX shell.
 
 
 ## Update or remove
 ## Update or remove
 
 

+ 1 - 1
docs/telemetry.md

@@ -4,7 +4,7 @@ All automatic telemetry uploads are disabled by default and each requires its ow
 
 
 ## Turn it on or off
 ## Turn it on or off
 
 
-Add this to the active profile's `config.yaml`, normally `~/.minimax-code/config.yaml`, then restart MCode:
+Add this to the active profile's `config.yaml`, then restart MCode. Builds from this repository default to `~/.minimax-code/config.yaml`; the published npm CLI `@minimax-ai/code@0.4.12` defaults to `~/.minimax/config.yaml`. Overrides can change this path; see [Accounts and data](installation.md#accounts-and-data) to locate it. The telemetry controls below describe this repository's source build and are not a guarantee of feature parity with that npm release.
 
 
 ```yaml
 ```yaml
 telemetry:
 telemetry:

+ 29 - 1
packages/tui/src/update/install-source.ts

@@ -327,12 +327,40 @@ export function bindMcodeNpmCommandToRuntime(
     path.join(npmDirectory, 'node_modules', 'npm', 'bin', 'npm-cli.js'),
     path.join(npmDirectory, 'node_modules', 'npm', 'bin', 'npm-cli.js'),
     path.join(npmDirectory, '..', 'lib', 'node_modules', 'npm', 'bin', 'npm-cli.js'),
     path.join(npmDirectory, '..', 'lib', 'node_modules', 'npm', 'bin', 'npm-cli.js'),
   ];
   ];
-  const npmCli = candidates.find((file) => existsSync(file) && statSync(file).isFile());
+  const npmCli =
+    candidates.find((file) => existsSync(file) && statSync(file).isFile()) ??
+    resolvePnpmNpmShim(npmExecutable);
   if (!npmCli)
   if (!npmCli)
     throw new Error(`Cannot locate npm-cli.js for the owned npm executable: ${command.executable}`);
     throw new Error(`Cannot locate npm-cli.js for the owned npm executable: ${command.executable}`);
   return { ...command, executable: runtimeExecutable, args: [npmCli, ...command.args] };
   return { ...command, executable: runtimeExecutable, args: [npmCli, ...command.args] };
 }
 }
 
 
+function resolvePnpmNpmShim(npmExecutable: string): string | undefined {
+  // pnpm env places npm behind a shell shim in PNPM_HOME. Read only its literal
+  // versioned CLI target; never execute/source the shim or search other runtimes.
+  try {
+    const metadata = statSync(npmExecutable);
+    if (!metadata.isFile() || metadata.size > 64 * 1024) return undefined;
+    const lines = readFileSync(npmExecutable, 'utf8').split(/\r?\n/u);
+    if (lines[0] !== '#!/bin/sh') return undefined;
+    const commands = lines.map((line) => line.trim()).filter((line) => /^exec\s/u.test(line));
+    if (commands.length === 0) return undefined;
+    const targets = commands.map((line) =>
+      /^exec (?:"\$basedir\/node"|node) "\$basedir\/(nodejs\/\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?\/lib\/node_modules\/npm\/bin\/npm-cli\.js)" "\$@"$/u.exec(line)?.[1],
+    );
+    const target = targets[0];
+    if (!target || targets.some((candidate) => candidate !== target)) return undefined;
+    const npmDirectory = path.dirname(npmExecutable);
+    const versionRoot = path.join(npmDirectory, ...target.split('/').slice(0, 2));
+    const cli = realpathSync(path.join(npmDirectory, target));
+    // Reject symlinks that redirect the target outside this pnpm Node version.
+    if (!isResolvedPathInside(versionRoot, cli, path) || !statSync(cli).isFile()) return undefined;
+    return cli;
+  } catch {
+    return undefined;
+  }
+}
+
 export function createMcodeNpmRuntimeEnvironment(
 export function createMcodeNpmRuntimeEnvironment(
   environment: NodeJS.ProcessEnv,
   environment: NodeJS.ProcessEnv,
   runtimeExecutable: string,
   runtimeExecutable: string,

+ 145 - 1
packages/tui/test/unit/update-application.test.ts

@@ -1,4 +1,4 @@
-import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
+import { existsSync, mkdirSync, mkdtempSync, realpathSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';
 import os from 'node:os';
 import os from 'node:os';
 import path from 'node:path';
 import path from 'node:path';
 import { describe, expect, it, vi } from 'vitest';
 import { describe, expect, it, vi } from 'vitest';
@@ -7,6 +7,7 @@ import {
   type McodeUpdateApplicationDependencies,
   type McodeUpdateApplicationDependencies,
 } from '../../src/update/application.js';
 } from '../../src/update/application.js';
 import {
 import {
+  bindMcodeNpmCommandToRuntime,
   buildMcodePackageManagerCommand,
   buildMcodePackageManagerCommand,
   classifyMcodeInstallPath,
   classifyMcodeInstallPath,
   classifyNpmGlobalInstall,
   classifyNpmGlobalInstall,
@@ -25,6 +26,149 @@ import {
   writeMcodePrefixUpdatePending,
   writeMcodePrefixUpdatePending,
 } from '../../src/update/prefix-update.js';
 } from '../../src/update/prefix-update.js';
 
 
+describe('installer-owned npm runtime binding', () => {
+  const target = 'nodejs/26.3.1/lib/node_modules/npm/bin/npm-cli.js';
+  const shim = (cli = target) =>
+    [
+      '#!/bin/sh',
+      'basedir=$(dirname "$(echo "$0" | sed -e \'s,\\\\,/,g\')")',
+      'if [ -x "$basedir/node" ]; then',
+      `  exec "$basedir/node" "$basedir/${cli}" "$@"`,
+      'else',
+      `  exec node "$basedir/${cli}" "$@"`,
+      'fi',
+    ].join('\n');
+
+  async function withLayout(
+    run: (root: string, write: (file: string, text?: string) => string) => void | Promise<void>,
+  ) {
+    const root = realpathSync(mkdtempSync(path.join(os.tmpdir(), 'mcode-npm-shim-')));
+    const write = (file: string, text = '') => {
+      const fullPath = path.join(root, file);
+      mkdirSync(path.dirname(fullPath), { recursive: true });
+      writeFileSync(fullPath, text);
+      return fullPath;
+    };
+    try {
+      await run(root, write);
+    } finally {
+      rmSync(root, { recursive: true, force: true });
+    }
+  }
+
+  function bind(executable: string) {
+    return bindMcodeNpmCommandToRuntime(
+      { executable, args: ['view', '@minimax-ai/code@latest', '--json'], display: 'owned npm' },
+      process.execPath,
+    );
+  }
+
+  it('resolves the reported pnpm shell shim and runs its CLI with the selected Node', async () => {
+    await withLayout(async (root, write) => {
+      const marker = path.join(root, 'shim-was-executed');
+      const npm = write(
+        'pnpm home/npm',
+        shim().replace('#!/bin/sh', `#!/bin/sh\ntouch "${marker}"`),
+      );
+      const cli = write(`pnpm home/${target}`, 'console.log(JSON.stringify("1.2.4"));');
+      // A different installed pnpm Node version must not influence the selection.
+      write(
+        'pnpm home/nodejs/24.2.0/lib/node_modules/npm/bin/npm-cli.js',
+        'throw new Error("wrong npm");',
+      );
+      expect(bind(npm)).toEqual({
+        executable: process.execPath,
+        args: [cli, 'view', '@minimax-ai/code@latest', '--json'],
+        display: 'owned npm',
+      });
+      await expect(
+        resolveLatestMcodeRegistryVersion('latest', {
+          npmExecutable: npm,
+          runtimeExecutable: process.execPath,
+          distribution: resolveMcodeNpmDistribution('@minimax-ai/code'),
+        }),
+      ).resolves.toBe('1.2.4');
+      expect(existsSync(marker)).toBe(false);
+    });
+  });
+
+  it.skipIf(process.platform === 'win32')(
+    'preserves regular npm symlinks and resolves symlinked pnpm shims',
+    async () => {
+      await withLayout((root, write) => {
+        const cli = write(`pnpm home/${target}`);
+        const npm = write('pnpm home/npm', shim());
+        symlinkSync(npm, path.join(root, 'npm'));
+        expect(bind(path.join(root, 'npm')).args[0]).toBe(cli);
+        const regularCli = write('node/lib/node_modules/npm/bin/npm-cli.js');
+        mkdirSync(path.join(root, 'node/bin'), { recursive: true });
+        symlinkSync('../lib/node_modules/npm/bin/npm-cli.js', path.join(root, 'node/bin/npm'));
+        expect(bind(path.join(root, 'node/bin/npm')).args[0]).toBe(regularCli);
+      });
+    },
+  );
+
+  it.each([
+    ['node/npm.cmd', 'node/node_modules/npm/bin/npm-cli.js'],
+    ['node/bin/npm', 'node/lib/node_modules/npm/bin/npm-cli.js'],
+  ])('preserves conventional npm layout for %s', async (executable, cliPath) => {
+    await withLayout((_root, write) => {
+      const npm = write(executable, '@ECHO OFF\r\n');
+      const cli = write(cliPath);
+      expect(bind(npm).args[0]).toBe(cli);
+    });
+  });
+
+  it.each([
+    ['missing target', shim()],
+    ['directory target', shim()],
+    ['traversal', shim(`../${target}`)],
+    ['dynamic version', shim('nodejs/$(node -v)/lib/node_modules/npm/bin/npm-cli.js')],
+    [
+      'ambiguous branches',
+      shim().replace('exec node "$basedir/nodejs/26.3.1/', 'exec node "$basedir/nodejs/24.2.0/'),
+    ],
+    ['comment-only target', `#!/bin/sh\n# exec node "$basedir/${target}" "$@"`],
+    ['unknown wrapper', '#!/bin/sh\nexec npm "$@"'],
+  ])('rejects %s without searching other installed versions', async (kind, content) => {
+    await withLayout((root, write) => {
+      const npm = write('pnpm/npm', content);
+      write('pnpm/nodejs/24.2.0/lib/node_modules/npm/bin/npm-cli.js');
+      if (kind === 'directory target')
+        mkdirSync(path.join(root, 'pnpm', target), { recursive: true });
+      else if (kind !== 'missing target') write(`pnpm/${target}`);
+      write(target);
+      expect(() => bind(npm)).toThrow('Cannot locate npm-cli.js for the owned npm executable');
+    });
+  });
+
+  it.skipIf(process.platform === 'win32').each(['file', 'version directory', 'dangling file'])(
+    'rejects a pnpm %s symlink escaping its version directory',
+    async (kind) => {
+      await withLayout((root, write) => {
+        const npm = write('pnpm/npm', shim());
+        const outside = write('outside/lib/node_modules/npm/bin/npm-cli.js');
+        const cli = path.join(root, 'pnpm', target);
+        if (kind === 'version directory') {
+          mkdirSync(path.join(root, 'pnpm/nodejs'), { recursive: true });
+          symlinkSync(path.join(root, 'outside'), path.join(root, 'pnpm/nodejs/26.3.1'));
+        } else {
+          mkdirSync(path.dirname(cli), { recursive: true });
+          symlinkSync(kind === 'dangling file' ? `${outside}.missing` : outside, cli);
+        }
+        expect(() => bind(npm)).toThrow('Cannot locate npm-cli.js for the owned npm executable');
+      });
+    },
+  );
+
+  it('rejects a missing owned executable even when a conventional CLI exists', async () => {
+    await withLayout((root, write) => {
+      write('node_modules/npm/bin/npm-cli.js');
+      expect(() => bind(path.join(root, 'npm'))).toThrow();
+    });
+  });
+});
+
 describe('McodeUpdateApplication', () => {
 describe('McodeUpdateApplication', () => {
   it('keeps signed managed-installer check and apply behind one product intent', async () => {
   it('keeps signed managed-installer check and apply behind one product intent', async () => {
     const check = vi.fn(async () => ({
     const check = vi.fn(async () => ({