smoke-admin-functions.mjs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  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 }),
  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. let memberId = '';
  52. let memberLegacyId = 0;
  53. let coachId = '';
  54. let coachLegacyId = 0;
  55. let temporaryAppointmentId = '';
  56. try {
  57. const sample = await jsonRequest(`${PARSE_URL}/classes/Company?limit=1&keys=objectId`, {}, true);
  58. const companyId = sample.results?.[0]?.objectId;
  59. if (!companyId) throw new Error('没有可用于帐套隔离测试的 Company');
  60. const company = { __type: 'Pointer', className: 'Company', objectId: companyId };
  61. const username = `codex_admin_smoke_${Date.now()}`;
  62. const password = randomBytes(24).toString('base64url');
  63. const created = await jsonRequest(`${PARSE_URL}/users`, {
  64. method: 'POST',
  65. body: JSON.stringify({ username, password, isAdmin: true, roles: ['admin'], company }),
  66. }, true);
  67. userId = created.objectId;
  68. const login = await jsonRequest(`${PARSE_URL}/login`, {
  69. method: 'POST',
  70. body: JSON.stringify({ username, password }),
  71. });
  72. if (!login.sessionToken) throw new Error('临时管理员登录未返回 sessionToken');
  73. const memberUsername = `codex_member_smoke_${Date.now()}`;
  74. const memberPassword = randomBytes(24).toString('base64url');
  75. memberLegacyId = 900000000 + Math.floor(Date.now() / 1000) % 90000000;
  76. const member = await jsonRequest(`${PARSE_URL}/users`, {
  77. method: 'POST',
  78. body: JSON.stringify({ username: memberUsername, password: memberPassword, legacyUserId: memberLegacyId, company }),
  79. }, true);
  80. memberId = member.objectId;
  81. const coachUsername = `codex_coach_smoke_${Date.now()}`;
  82. const coachPassword = randomBytes(24).toString('base64url');
  83. coachLegacyId = memberLegacyId + 1;
  84. const coach = await jsonRequest(`${PARSE_URL}/users`, {
  85. method: 'POST',
  86. body: JSON.stringify({ username: coachUsername, password: coachPassword, legacyUserId: coachLegacyId, legacyGroupId: 3, company }),
  87. }, true);
  88. coachId = coach.objectId;
  89. const createdAppointment = await jsonRequest(`${PARSE_URL}/classes/CourseAppointment`, {
  90. method: 'POST',
  91. body: JSON.stringify({ company, sourceKey: `cloud:smoke-appointment:${memberLegacyId}`, szyh: String(memberLegacyId), kcid: '16', dszt: '0', pl: String(coachLegacyId) }),
  92. }, true);
  93. temporaryAppointmentId = createdAppointment.objectId;
  94. const memberLogin = await jsonRequest(`${PARSE_URL}/login`, {
  95. method: 'POST',
  96. body: JSON.stringify({ username: memberUsername, password: memberPassword }),
  97. });
  98. const coachLogin = await jsonRequest(`${PARSE_URL}/login`, {
  99. method: 'POST',
  100. body: JSON.stringify({ username: coachUsername, password: coachPassword }),
  101. });
  102. const meta = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'meta' });
  103. if (meta.identity?.objectId !== userId || !meta.cloudFunctions) throw new Error('管理员 meta 校验失败');
  104. const dashboard = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'dashboard' });
  105. if (!Array.isArray(dashboard.metrics) || dashboard.metrics.length !== 8) throw new Error('dashboard 指标校验失败');
  106. const schema = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'schema', className: 'CourseAppointment' });
  107. if (schema.className !== 'CourseAppointment' || !Array.isArray(schema.fields)) throw new Error('schema 校验失败');
  108. const page = await callFunction('xiaoshu/admin/gateway', login.sessionToken, { operation: 'list', className: 'CourseAppointment', page: 1, pageSize: 2 });
  109. if (!Array.isArray(page.results) || page.pageSize !== 2) throw new Error('资源分页校验失败');
  110. const normalized = await callFunction('xiaoshu/cms/content-normalizer', login.sessionToken, { content: '<p>中文&nbsp;<strong>内容</strong></p><script>alert(1)</script>' });
  111. if (normalized.content !== '中文 内容') throw new Error(`内容清理结果异常:${normalized.content}`);
  112. const exams = await callFunction('xiaoshu/cms/exams/classes', login.sessionToken, { page: 1, pageSize: 2 });
  113. if (!Array.isArray(exams.results)) throw new Error('考试班级投影校验失败');
  114. const guest = await callFunction('xiaoshu/cms/guest/bar', login.sessionToken, { page: 1, pageSize: 2 });
  115. if (!Array.isArray(guest.results)) throw new Error('互动社区投影校验失败');
  116. const migration = await callLegacyFunction('', { action: 'migration_status' });
  117. const covered = new Set([...(migration.result?.implemented || []), ...Object.keys(migration.result?.blocked || {})]);
  118. const missing = (await sourceActions()).filter((action) => !covered.has(action));
  119. if (missing.length) throw new Error(`app gateway 迁移矩阵缺少:${missing.join(', ')}`);
  120. const content = await callLegacyFunction('', { action: 'content_list', page: 1, pageSize: 2 });
  121. if (!Array.isArray(content.result) || content.result.length !== 2 || Number(content.page?.itemCount) < 89000) throw new Error('公开内容分页校验失败');
  122. const contentExact = await callLegacyFunction('', { action: 'content_list', page: 1, pageSize: 1, objectId: content.result[0].objectId });
  123. if (contentExact.result?.[0]?.objectId !== content.result[0].objectId || contentExact.page?.itemCount !== 1) throw new Error('内容 objectId 精确查询校验失败');
  124. const contentDetail = await callLegacyFunction('', { action: 'content_get', id: content.result[0].objectId });
  125. if (contentDetail.result?.objectId !== content.result[0].objectId) throw new Error('内容详情 ID 校验失败');
  126. const words = await callLegacyFunction('', { action: 'content_list', modelId: 52, page: 1, pageSize: 1 });
  127. if (Number(words.page?.itemCount) < 89000 || !words.result?.[0]?.GeneralID || words.result?.[0]?.sy === undefined) throw new Error('词库 addon 联表校验失败');
  128. const privateContent = await callLegacyFunction('', { action: 'content_list', modelId: 56, page: 1, pageSize: 1 }, 401);
  129. if (!String(privateContent.retmsg).includes('登录')) throw new Error('学习记录未阻止匿名访问');
  130. const learning = await callLegacyFunction(login.sessionToken, { action: 'content_list', modelId: 56, page: 1, pageSize: 1 });
  131. if (!learning.result?.[0]?.GeneralID || learning.result?.[0]?.xxqs === undefined) throw new Error('学习记录 addon 联表校验失败');
  132. const recordDetail = await callLegacyFunction(login.sessionToken, { action: 'e_record_detail', id: learning.result[0].GeneralID });
  133. if (!Array.isArray(recordDetail.result) || !recordDetail.result.length || !recordDetail.result[0]?.detail?.[0]?.Title) throw new Error('学习记录单词详情联查校验失败');
  134. const appointments = await callLegacyFunction(login.sessionToken, { action: 'content_list', modelId: 54, page: 1, pageSize: 1 });
  135. const appointment = await callLegacyFunction(login.sessionToken, { action: 'e_order_detail', id: appointments.result?.[0]?.GeneralID });
  136. if (!appointment.result?.[0]?.GeneralID || appointment.result[0].kcid === undefined) throw new Error('预约详情联查校验失败');
  137. const newWords = await callLegacyFunction(login.sessionToken, { action: 'e_words_list', uid: 58, page: 1, pageSize: 2 });
  138. if (Number(newWords.page?.itemCount) < 1 || !newWords.result?.[0]?.detail?.[0]?.Title) throw new Error('用户生词联查校验失败');
  139. const courseWords = await callLegacyFunction(login.sessionToken, { action: 'e_ck_list', uid: 58, nids: 40, page: 1, pageSize: 1000 });
  140. const learnedWord = courseWords.result?.find((word) => Number(word.GeneralID) === 2505);
  141. if (Number(courseWords.page?.itemCount) < 1 || !courseWords.result?.[0]?.detail?.Title || Number(learnedWord?.w_learned) !== 7) throw new Error('课程词库学习进度联查校验失败');
  142. const memory = await callLegacyFunction(login.sessionToken, { action: 'e_get_21list', uid: 58, page: 1, pageSize: 2 });
  143. if (Number(memory.page?.itemCount) < 1 || !memory.result?.[0]?.GeneralID || memory.result[0].learned === undefined) throw new Error('21 天抗遗忘联查校验失败');
  144. const incomeBlocked = await callLegacyFunction(login.sessionToken, { action: 'e_get_21list_tj', uid: 58 }, 501);
  145. if (!String(incomeBlocked.retmsg).includes('计价规则')) throw new Error('复习收入缺失规则未显式阻塞');
  146. const ownEmpty = await callLegacyFunction(memberLogin.sessionToken, { action: 'content_list', modelId: 56, myfield2: `UserId=${memberLegacyId}`, page: 1, pageSize: 1 });
  147. if (!Array.isArray(ownEmpty.result) || ownEmpty.page?.itemCount !== 0) throw new Error('普通用户本人记录权限校验失败');
  148. const ownCourseWords = await callLegacyFunction(memberLogin.sessionToken, { action: 'e_ck_list', uid: memberLegacyId, nids: 40, page: 1, pageSize: 1 });
  149. if (!Array.isArray(ownCourseWords.result) || ownCourseWords.result[0]?.w_learned !== 0) throw new Error('普通用户本人课程词库权限校验失败');
  150. const learnedWrite = await callLegacyFunction(memberLogin.sessionToken, { action: 'e_add_words', uid: memberLegacyId, wordsId: '2505', kcid: 16, save: 1 });
  151. if (learnedWrite.result?.created !== 1 || learnedWrite.result?.learnedIncremented !== 1) throw new Error('首次学习词进度写入校验失败');
  152. const learnedRead = await callLegacyFunction(memberLogin.sessionToken, { action: 'e_ck_list', uid: memberLegacyId, nids: 40, page: 1, pageSize: 1000 });
  153. if (Number(learnedRead.result?.find((word) => Number(word.GeneralID) === 2505)?.w_learned) !== 1) throw new Error('学习次数写后读校验失败');
  154. await callLegacyFunction(memberLogin.sessionToken, { action: 'e_add_words', uid: memberLegacyId, wordsId: '2505', kcid: 16, ifnew: 1 });
  155. const addedNewWord = await callLegacyFunction(memberLogin.sessionToken, { action: 'e_words_list', uid: memberLegacyId, page: 1, pageSize: 10 });
  156. if (addedNewWord.page?.itemCount !== 1 || Number(addedNewWord.result?.[0]?.detail?.[0]?.GeneralID) !== 2505) throw new Error('加入生词写后读校验失败');
  157. await callLegacyFunction(memberLogin.sessionToken, { action: 'e_add_words', uid: memberLegacyId, wordsId: '2505', kcid: 16, ifnew: 0 });
  158. const removedNewWord = await callLegacyFunction(memberLogin.sessionToken, { action: 'e_words_list', uid: memberLegacyId, page: 1, pageSize: 10 });
  159. if (removedNewWord.page?.itemCount !== 0) throw new Error('移出生词写后读校验失败');
  160. const studyAddon = { con: '云函数学习记录冒烟测试', dqrq: '20260818', UserID: memberLegacyId, learned: 1, ygg: 0, djq: 0, xxqs: JSON.stringify([{ GeneralID: 2505, Title: 'woman', check: 0 }]) };
  161. const createdStudy = await callLegacyFunction(memberLogin.sessionToken, { action: 'stu_record_update_v2', orderId: temporaryAppointmentId, uid: memberLegacyId, inputer: memberUsername, addon: JSON.stringify(studyAddon) });
  162. if (!createdStudy.result?.created || !createdStudy.result?.GeneralID || !createdStudy.result?.recordObjectId) throw new Error('预约学习记录首次双表写入校验失败');
  163. const studyDetail = await callLegacyFunction(memberLogin.sessionToken, { action: 'e_record_detail', id: createdStudy.result.GeneralID });
  164. if (studyDetail.result?.[0]?.detail?.[0]?.Title !== 'woman') throw new Error('预约学习记录写后详情校验失败');
  165. studyAddon.xxqs = JSON.stringify([{ GeneralID: 2505, Title: 'woman', check: 1 }]);
  166. const updatedStudy = await callLegacyFunction(memberLogin.sessionToken, { action: 'stu_record_update_v2', orderId: temporaryAppointmentId, uid: memberLegacyId, inputer: memberUsername, addon: JSON.stringify(studyAddon) });
  167. if (updatedStudy.result?.created || updatedStudy.result?.GeneralID !== createdStudy.result.GeneralID) throw new Error('预约学习记录幂等更新校验失败');
  168. const studyList = await callLegacyFunction(memberLogin.sessionToken, { action: 'content_list', modelId: 56, myfield2: `UserId=${memberLegacyId}|dsid=${temporaryAppointmentId}`, page: 1, pageSize: 2 });
  169. if (studyList.page?.itemCount !== 1 || Number(studyList.result?.[0]?.ygg) !== 1 || Number(studyList.result?.[0]?.learned) !== 1) throw new Error('预约学习记录聚合字段写后读校验失败');
  170. const orderContent = JSON.stringify({ GeneralID: temporaryAppointmentId, UpDateTime: '2026-08-18 12:00' });
  171. await callLegacyFunction(memberLogin.sessionToken, { action: 'e_order_update_v2', uid: memberLegacyId, status: 10, content: orderContent }, 403);
  172. const startedOrder = await callLegacyFunction(coachLogin.sessionToken, { action: 'e_order_update_v2', uid: coachLegacyId, status: 10, content: orderContent });
  173. if (startedOrder.result?.previousStatus !== 0 || startedOrder.result?.status !== 10 || startedOrder.result?.unchanged) throw new Error('预约开始状态迁移校验失败');
  174. const repeatedStart = await callLegacyFunction(coachLogin.sessionToken, { action: 'e_order_update_v2', uid: coachLegacyId, status: 10, content: orderContent });
  175. if (!repeatedStart.result?.unchanged) throw new Error('预约状态幂等更新校验失败');
  176. await callLegacyFunction(memberLogin.sessionToken, { action: 'e_order_update_v2', uid: memberLegacyId, status: 11, content: orderContent }, 403);
  177. await callLegacyFunction(coachLogin.sessionToken, { action: 'e_order_update_v2', uid: coachLegacyId, status: 11, content: orderContent });
  178. await callLegacyFunction(coachLogin.sessionToken, { action: 'e_order_update_v2', uid: coachLegacyId, status: 20, content: orderContent }, 403);
  179. await callLegacyFunction(memberLogin.sessionToken, { action: 'e_order_update_v2', uid: memberLegacyId, status: 20, content: orderContent });
  180. await callLegacyFunction(coachLogin.sessionToken, { action: 'e_order_update_v2', uid: coachLegacyId, status: 30, content: orderContent });
  181. const completedOrder = await callLegacyFunction(memberLogin.sessionToken, { action: 'e_order_detail', id: temporaryAppointmentId });
  182. if (Number(completedOrder.result?.[0]?.dszt) !== 30) throw new Error('预约状态机写后读校验失败');
  183. const deniedCourseWords = await callLegacyFunction(memberLogin.sessionToken, { action: 'e_ck_list', uid: 58, nids: 40, page: 1, pageSize: 1 }, 403);
  184. if (!String(deniedCourseWords.retmsg).includes('无权')) throw new Error('普通用户跨用户课程词库未被拒绝');
  185. const denied = await callLegacyFunction(memberLogin.sessionToken, { action: 'content_list', modelId: 56, myfield2: 'UserId=3', page: 1, pageSize: 1 }, 403);
  186. if (!String(denied.retmsg).includes('无权')) throw new Error('普通用户跨用户记录未被拒绝');
  187. const profile = await callLegacyFunction(login.sessionToken, { action: 'user_get' });
  188. if (profile.retcode !== 0 || profile.result?.objectId !== userId) throw new Error('app gateway 用户会话校验失败');
  189. const blocked = await callLegacyFunction('', { action: 'cart_list' }, 501);
  190. if (!String(blocked.retmsg).startsWith('migration_blocked:')) throw new Error('阻塞接口未返回 migration_blocked');
  191. console.log('Cloud smoke passed: admin auth/tenant/CRUD reads, CMS projections, normalized learning joins, app action coverage, public content, session scope, explicit blocked APIs.');
  192. } finally {
  193. if (memberLegacyId) {
  194. const commonWhere = encodeURIComponent(JSON.stringify({ sourceKey: { $regex: `^cloud:stu_record:${memberLegacyId}:` } }));
  195. const commonRows = await jsonRequest(`${PARSE_URL}/classes/CommonModel?where=${commonWhere}&limit=1000`, {}, true).catch(() => ({ results: [] }));
  196. for (const row of commonRows.results || []) await jsonRequest(`${PARSE_URL}/classes/CommonModel/${row.objectId}`, { method: 'DELETE' }, true).catch((error) => {
  197. console.error(`临时学习主记录清理失败:${error.message}`);
  198. process.exitCode = 1;
  199. });
  200. const studyWhere = encodeURIComponent(JSON.stringify({ userId: memberLegacyId }));
  201. const studyRows = await jsonRequest(`${PARSE_URL}/classes/DailyStudyRecord?where=${studyWhere}&limit=1000`, {}, true).catch(() => ({ results: [] }));
  202. for (const row of studyRows.results || []) await jsonRequest(`${PARSE_URL}/classes/DailyStudyRecord/${row.objectId}`, { method: 'DELETE' }, true).catch((error) => {
  203. console.error(`临时学习 addon 清理失败:${error.message}`);
  204. process.exitCode = 1;
  205. });
  206. }
  207. if (temporaryAppointmentId) await jsonRequest(`${PARSE_URL}/classes/CourseAppointment/${temporaryAppointmentId}`, { method: 'DELETE' }, true).catch((error) => {
  208. console.error(`临时预约清理失败:${error.message}`);
  209. process.exitCode = 1;
  210. });
  211. if (memberLegacyId) {
  212. const where = encodeURIComponent(JSON.stringify({ yhid: String(memberLegacyId) }));
  213. const practices = await jsonRequest(`${PARSE_URL}/classes/PracticeRecord?where=${where}&limit=1000`, {}, true).catch(() => ({ results: [] }));
  214. for (const practice of practices.results || []) await jsonRequest(`${PARSE_URL}/classes/PracticeRecord/${practice.objectId}`, { method: 'DELETE' }, true).catch((error) => {
  215. console.error(`临时学习进度清理失败:${error.message}`);
  216. process.exitCode = 1;
  217. });
  218. }
  219. if (memberId) {
  220. await jsonRequest(`${PARSE_URL}/users/${memberId}`, { method: 'DELETE' }, true).catch((error) => {
  221. console.error(`临时普通用户清理失败:${error.message}`);
  222. process.exitCode = 1;
  223. });
  224. }
  225. if (coachId) {
  226. await jsonRequest(`${PARSE_URL}/users/${coachId}`, { method: 'DELETE' }, true).catch((error) => {
  227. console.error(`临时陪练用户清理失败:${error.message}`);
  228. process.exitCode = 1;
  229. });
  230. }
  231. if (userId) {
  232. await jsonRequest(`${PARSE_URL}/users/${userId}`, { method: 'DELETE' }, true).catch((error) => {
  233. console.error(`临时管理员清理失败:${error.message}`);
  234. process.exitCode = 1;
  235. });
  236. }
  237. }