account-switch-smoke-test.js 6.3 KB

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