smoke-admin-functions.mjs 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124
  1. #!/usr/bin/env node
  2. import { randomBytes } from 'node:crypto';
  3. import { readFile } from 'node:fs/promises';
  4. const APP_ID = process.env.XIAOSHU_PARSE_APP_ID || '7pIbDBJmKx_main';
  5. const MASTER_KEY = process.env.XIAOSHU_MASTER_KEY || '';
  6. const PARSE_URL = (process.env.XIAOSHU_PARSE_URL || 'https://server.xiaoshu.pro/parse').replace(/\/$/, '');
  7. const FUNCTION_URL = (process.env.XIAOSHU_FUNCTION_URL || 'https://server.xiaoshu.pro/api/functions').replace(/\/$/, '');
  8. if (!MASTER_KEY) throw new Error('缺少 XIAOSHU_MASTER_KEY');
  9. async function jsonRequest(url, init = {}, master = false) {
  10. const response = await fetch(url, {
  11. ...init,
  12. headers: {
  13. 'X-Parse-Application-Id': APP_ID,
  14. ...(master ? { 'X-Parse-Master-Key': MASTER_KEY } : {}),
  15. 'Content-Type': 'application/json',
  16. ...(init.headers || {}),
  17. },
  18. });
  19. const payload = await response.json().catch(() => ({}));
  20. if (!response.ok) {
  21. const detail = payload.message || payload.error || payload;
  22. throw new Error(`${response.status}: ${typeof detail === 'string' ? detail : JSON.stringify(detail)}`);
  23. }
  24. return payload;
  25. }
  26. async function callFunction(path, token, params) {
  27. const payload = await jsonRequest(`${FUNCTION_URL}/${path}`, {
  28. method: 'POST',
  29. body: JSON.stringify({ token, params }),
  30. });
  31. if (!payload.success) throw new Error(payload.message || `${path} 返回失败`);
  32. return payload.data;
  33. }
  34. async function callLegacyFunction(token, params, expectedStatus = 200) {
  35. const response = await fetch(`${FUNCTION_URL}/xiaoshu/app/gateway`, {
  36. method: 'POST',
  37. headers: { 'X-Parse-Application-Id': APP_ID, 'Content-Type': 'application/json' },
  38. body: JSON.stringify(token ? { token, params } : params),
  39. });
  40. const payload = await response.json().catch(() => ({}));
  41. if (response.status !== expectedStatus) throw new Error(`app gateway ${params.action} 期望 ${expectedStatus},实际 ${response.status}: ${payload.retmsg || payload.error || ''}`);
  42. return payload;
  43. }
  44. async function sourceActions() {
  45. const source = await readFile(new URL('../src/app/core/source-parity.generated.ts', import.meta.url), 'utf8');
  46. const match = source.match(/export const SOURCE_API_ACTIONS = (\[[\s\S]*?\]) as const;/);
  47. if (!match) throw new Error('无法读取 SOURCE_API_ACTIONS');
  48. return JSON.parse(match[1]);
  49. }
  50. let userId = '';
  51. try {
  52. const sample = await jsonRequest(`${PARSE_URL}/classes/Company?limit=1&keys=objectId`, {}, true);
  53. const companyId = sample.results?.[0]?.objectId;
  54. if (!companyId) throw new Error('没有可用于帐套隔离测试的 Company');
  55. const company = { __type: 'Pointer', className: 'Company', objectId: companyId };
  56. const username = `codex_admin_smoke_${Date.now()}`;
  57. const password = randomBytes(24).toString('base64url');
  58. const created = await jsonRequest(`${PARSE_URL}/users`, {
  59. method: 'POST',
  60. body: JSON.stringify({ username, password, isAdmin: true, roles: ['admin'], company }),
  61. }, true);
  62. userId = created.objectId;
  63. const login = await jsonRequest(`${PARSE_URL}/login`, {
  64. method: 'POST',
  65. body: JSON.stringify({ username, password }),
  66. });
  67. if (!login.sessionToken) throw new Error('临时管理员登录未返回 sessionToken');
  68. const meta = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'meta' });
  69. if (meta.identity?.objectId !== userId || !meta.cloudFunctions) throw new Error('管理员 meta 校验失败');
  70. const dashboard = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'dashboard' });
  71. if (!Array.isArray(dashboard.metrics) || dashboard.metrics.length !== 8) throw new Error('dashboard 指标校验失败');
  72. const schema = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'schema', className: 'CourseAppointment' });
  73. if (schema.className !== 'CourseAppointment' || !Array.isArray(schema.fields)) throw new Error('schema 校验失败');
  74. const page = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'list', className: 'CourseAppointment', page: 1, pageSize: 2 });
  75. if (!Array.isArray(page.results) || page.pageSize !== 2) throw new Error('资源分页校验失败');
  76. const normalized = await callFunction('xiaoshu/cms/content-normalizer', login.sessionToken, { content: '<p>中文&nbsp;<strong>内容</strong></p><script>alert(1)</script>' });
  77. if (normalized.content !== '中文 内容') throw new Error(`内容清理结果异常:${normalized.content}`);
  78. const exams = await callFunction('xiaoshu/cms/exams/classes', login.sessionToken, { page: 1, pageSize: 2 });
  79. if (!Array.isArray(exams.results)) throw new Error('考试班级投影校验失败');
  80. const guest = await callFunction('xiaoshu/cms/guest/bar', login.sessionToken, { page: 1, pageSize: 2 });
  81. if (!Array.isArray(guest.results)) throw new Error('互动社区投影校验失败');
  82. const migration = await callLegacyFunction('', { action: 'migration_status' });
  83. const covered = new Set([...(migration.result?.implemented || []), ...Object.keys(migration.result?.blocked || {})]);
  84. const missing = (await sourceActions()).filter((action) => !covered.has(action));
  85. if (missing.length) throw new Error(`app gateway 迁移矩阵缺少:${missing.join(', ')}`);
  86. const content = await callLegacyFunction('', { action: 'content_list', page: 1, pageSize: 2 });
  87. if (!Array.isArray(content.result) || content.result.length !== 2 || Number(content.page?.itemCount) < 90000) throw new Error('公开内容分页校验失败');
  88. const contentExact = await callLegacyFunction('', { action: 'content_list', page: 1, pageSize: 1, objectId: content.result[0].objectId });
  89. if (contentExact.result?.[0]?.objectId !== content.result[0].objectId || contentExact.page?.itemCount !== 1) throw new Error('内容 objectId 精确查询校验失败');
  90. const profile = await callLegacyFunction(login.sessionToken, { action: 'user_get' });
  91. if (profile.retcode !== 0 || profile.result?.objectId !== userId) throw new Error('app gateway 用户会话校验失败');
  92. const blocked = await callLegacyFunction('', { action: 'cart_list' }, 501);
  93. if (!String(blocked.retmsg).startsWith('migration_blocked:')) throw new Error('阻塞接口未返回 migration_blocked');
  94. console.log('Cloud smoke passed: admin auth/tenant/CRUD reads, CMS projections, app action coverage, public content, session scope, explicit blocked APIs.');
  95. } finally {
  96. if (userId) {
  97. await jsonRequest(`${PARSE_URL}/users/${userId}`, { method: 'DELETE' }, true).catch((error) => {
  98. console.error(`临时管理员清理失败:${error.message}`);
  99. process.exitCode = 1;
  100. });
  101. }
  102. }