account-switch-smoke-test.js 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151
  1. #!/usr/bin/env node
  2. 'use strict';
  3. const assert = require('assert/strict');
  4. const fs = require('fs');
  5. const os = require('os');
  6. const path = require('path');
  7. function envValue(filePath, key) {
  8. const content = fs.readFileSync(filePath, 'utf8');
  9. const match = content.match(new RegExp(`^${key}=(.*)$`, 'm'));
  10. return match ? match[1].trim() : undefined;
  11. }
  12. async function main() {
  13. const packageRoot = path.resolve(__dirname, '..');
  14. const tempRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'qiwei-account-switch-'));
  15. const previousCwd = process.cwd();
  16. const previousEnv = { ...process.env };
  17. const originalFetch = global.fetch;
  18. const requests = [];
  19. try {
  20. process.env.USERPROFILE = tempRoot;
  21. process.env.HOME = tempRoot;
  22. process.env.QIWEI_WORKSPACE_ROOT = tempRoot;
  23. process.env.QIWEI_OUTPUTS_DIR = path.join(tempRoot, 'outputs');
  24. process.env.CLAUDE_CODE_WORKDIR = tempRoot;
  25. process.env.QIWEI_AUTH_TOKEN = 'test-account-switch-token';
  26. delete process.env.QIWEI_UID;
  27. delete process.env.QIWE_UID;
  28. delete process.env.QIWEI_GUID;
  29. delete process.env.QIWE_GUID;
  30. process.chdir(tempRoot);
  31. const credentials = require(path.join(packageRoot, 'mcp', 'src', 'core', 'credentials'));
  32. const login = require(path.join(packageRoot, 'mcp', 'src', 'tools', 'qiwei-login-run'));
  33. assert.equal(path.dirname(credentials.CREDENTIALS_FILE), path.join(tempRoot, '.claude'));
  34. const envFile = path.join(tempRoot, '.env.local');
  35. credentials.saveQiweiClientConfig({
  36. uid: 'uid-account-a',
  37. guid: 'guid-account-a',
  38. apiBase: 'https://gateway.example/api/qiwei',
  39. envRoot: tempRoot,
  40. });
  41. assert.equal(envValue(envFile, 'QIWEI_UID'), 'uid-account-a');
  42. assert.equal(envValue(envFile, 'QIWEI_GUID'), 'guid-account-a');
  43. assert.equal(credentials.readQiweiGuid({ uid: 'uid-account-b' }), '');
  44. let checkLoggedIn = false;
  45. global.fetch = async (rawUrl, options = {}) => {
  46. const url = new URL(String(rawUrl));
  47. const body = options.body ? JSON.parse(options.body) : {};
  48. requests.push({ path: url.pathname, body });
  49. let data = {};
  50. if (url.pathname.endsWith('/login/start')) data = { uid: body.uid };
  51. else if (url.pathname.endsWith('/login/check')) {
  52. data = checkLoggedIn
  53. ? { uid: body.uid, status: 2, detail: { userId: 'user-b', nickname: '账号 B', guid: 'guid-account-b' } }
  54. : { uid: body.uid, status: 10, detail: {} };
  55. } else if (url.pathname.endsWith('/login/verify')) data = { accepted: true };
  56. else if (url.pathname.endsWith('/login/status')) data = { configured: true, online: true, statusCode: 2, detail: { userId: 'user-b', nickname: '账号 B' } };
  57. return new Response(JSON.stringify({ code: 0, data }), {
  58. status: 200,
  59. headers: { 'Content-Type': 'application/json' },
  60. });
  61. };
  62. const common = {
  63. uid: 'uid-account-b',
  64. authToken: 'test-account-switch-token',
  65. apiBase: 'https://gateway.example/api/qiwei',
  66. flowUi: false,
  67. openBrowser: false,
  68. persistConfig: false,
  69. skipSubscriptionCheck: true,
  70. };
  71. await login.qiweiLoginStart(common);
  72. const pending = await login.qiweiLoginCheck(common);
  73. assert.equal(pending.status, 'needs_verify_code');
  74. await login.qiweiLoginVerify({ ...common, code: '123456' });
  75. for (const request of requests.slice(0, 3)) {
  76. assert.equal(request.body.uid, 'uid-account-b');
  77. assert.equal(Object.prototype.hasOwnProperty.call(request.body, 'guid'), false);
  78. }
  79. checkLoggedIn = true;
  80. const loggedIn = await login.qiweiLoginCheck(common);
  81. assert.equal(loggedIn.summary.loggedIn, true);
  82. assert.equal(loggedIn.data.guid, 'guid-account-b');
  83. assert.equal(Object.prototype.hasOwnProperty.call(requests.at(-1).body, 'guid'), false);
  84. const { switchActiveAccount } = require(path.join(packageRoot, 'mcp', 'src', 'dashboard', 'agent-service'));
  85. await switchActiveAccount({
  86. uid: 'uid-account-b',
  87. guid: loggedIn.data.guid,
  88. apiBase: common.apiBase,
  89. userId: 'user-b',
  90. nickname: '账号 B',
  91. });
  92. assert.equal(envValue(envFile, 'QIWEI_UID'), 'uid-account-b');
  93. assert.equal(envValue(envFile, 'QIWEI_GUID'), 'guid-account-b');
  94. assert.equal(credentials.readQiweiGuid({ uid: 'uid-account-b' }), 'guid-account-b');
  95. await switchActiveAccount({
  96. uid: 'uid-account-c',
  97. guid: '',
  98. apiBase: common.apiBase,
  99. userId: 'user-c',
  100. nickname: '账号 C',
  101. });
  102. assert.equal(envValue(envFile, 'QIWEI_UID'), 'uid-account-c');
  103. assert.equal(envValue(envFile, 'QIWEI_GUID'), '');
  104. assert.equal(credentials.readQiweiGuid({ uid: 'uid-account-c' }), '');
  105. assert.equal(JSON.parse(fs.readFileSync(credentials.CREDENTIALS_FILE, 'utf8')).guid, undefined);
  106. const appSource = fs.readFileSync(path.join(packageRoot, 'mcp', 'src', 'dashboard', 'app.js'), 'utf8');
  107. assert.match(appSource, /qiwei-\$\{workspaceId\}-accounts/);
  108. assert.match(appSource, /await initializeWorkspaceAccountStorage\(\);[\s\S]*if \(currentAccount\(\)\?\.uid\)/);
  109. assert.match(appSource, /addAccount\(account, \{ activate: false \}\)[\s\S]*await switchAccount\(accountId/);
  110. assert.match(appSource, /if \(!switched\)[\s\S]*state\.currentAccountId = previousAccountId/);
  111. assert.match(appSource, /statusCode === 4[\s\S]*restorePreviousAccountSelection\(\)/);
  112. process.stdout.write(`${JSON.stringify({
  113. status: 'ok',
  114. checks: 20,
  115. coverage: [
  116. 'new_uid_does_not_reuse_old_guid',
  117. 'verify_and_check_keep_uid_isolation',
  118. 'successful_switch_persists_uid_guid',
  119. 'guidless_switch_clears_stale_guid',
  120. 'workspace_scoped_browser_accounts',
  121. 'failed_or_cancelled_login_restores_previous_account',
  122. ],
  123. }, null, 2)}\n`);
  124. } finally {
  125. global.fetch = originalFetch;
  126. process.chdir(previousCwd);
  127. for (const key of Object.keys(process.env)) {
  128. if (!(key in previousEnv)) delete process.env[key];
  129. }
  130. for (const [key, value] of Object.entries(previousEnv)) process.env[key] = value;
  131. fs.rmSync(tempRoot, { recursive: true, force: true });
  132. }
  133. }
  134. main().catch(error => {
  135. process.stderr.write(`${error.stack || error.message}\n`);
  136. process.exitCode = 1;
  137. });