server-admin-api.test.js 80 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237
  1. import assert from 'node:assert/strict';
  2. import { spawn, spawnSync } from 'node:child_process';
  3. import { mkdtempSync, readdirSync } from 'node:fs';
  4. import { tmpdir } from 'node:os';
  5. import path from 'node:path';
  6. import process from 'node:process';
  7. import { test } from 'node:test';
  8. import net from 'node:net';
  9. test('admin API routes respond once and keep the server alive', async () => {
  10. const port = await freePort();
  11. const child = spawn(process.execPath, ['src/server.js'], {
  12. cwd: process.cwd(),
  13. env: {
  14. ...process.env,
  15. PORT: String(port),
  16. DATA_DIR: mkdtempSync(path.join(tmpdir(), 'mailhub-server-test-')),
  17. ADMIN_PASSWORD: 'password123',
  18. SUBMISSION_ENABLED: 'false',
  19. IMAP_ENABLED: 'false',
  20. POP3_ENABLED: 'false'
  21. },
  22. stdio: ['ignore', 'pipe', 'pipe']
  23. });
  24. try {
  25. await waitForOutput(child, 'MailHub listening');
  26. const baseUrl = `http://127.0.0.1:${port}`;
  27. const login = await fetch(`${baseUrl}/api/login`, {
  28. method: 'POST',
  29. headers: { 'Content-Type': 'application/json' },
  30. body: JSON.stringify({ username: 'admin', password: 'password123' })
  31. });
  32. assert.equal(login.status, 200);
  33. const cookie = login.headers.get('set-cookie')?.split(';')[0] || '';
  34. assert.ok(cookie);
  35. const settings = await fetch(`${baseUrl}/api/admin/settings`, {
  36. headers: { Cookie: cookie }
  37. });
  38. assert.equal(settings.status, 200);
  39. const settingsPayload = await settings.json();
  40. assert.equal(settingsPayload.settings.mailHostname, 'mailhub.local');
  41. assert.equal(settingsPayload.settings.systemChecks.ptr.key, 'ptr');
  42. const exited = await waitForExit(child, 300);
  43. assert.equal(exited, false);
  44. } finally {
  45. child.kill('SIGTERM');
  46. await waitForExit(child, 1000);
  47. }
  48. });
  49. test('built auth assets are served before authentication', async () => {
  50. const assetName = readdirSync(path.join(process.cwd(), 'public', 'assets')).find((name) => /\.(js|css)$/.test(name));
  51. assert.ok(assetName, 'expected at least one built frontend asset');
  52. const port = await freePort();
  53. const child = spawn(process.execPath, ['src/server.js'], {
  54. cwd: process.cwd(),
  55. env: {
  56. ...process.env,
  57. PORT: String(port),
  58. DATA_DIR: mkdtempSync(path.join(tmpdir(), 'mailhub-server-test-')),
  59. ADMIN_PASSWORD: 'password123',
  60. SUBMISSION_ENABLED: 'false',
  61. IMAP_ENABLED: 'false',
  62. POP3_ENABLED: 'false'
  63. },
  64. stdio: ['ignore', 'pipe', 'pipe']
  65. });
  66. try {
  67. await waitForOutput(child, 'MailHub listening');
  68. const baseUrl = `http://127.0.0.1:${port}`;
  69. const login = await fetch(`${baseUrl}/login`);
  70. assert.equal(login.status, 200);
  71. const asset = await fetch(`${baseUrl}/assets/${assetName}`, { redirect: 'manual' });
  72. assert.equal(asset.status, 200);
  73. assert.notEqual(asset.headers.get('location'), '/login');
  74. } finally {
  75. child.kill('SIGTERM');
  76. await waitForExit(child, 1000);
  77. }
  78. });
  79. test('auth pages preserve query messages instead of redirecting them away', async () => {
  80. const { child, baseUrl } = await startTestServer();
  81. try {
  82. for (const pathname of ['/login?error=hello', '/reset-password?token=abc123']) {
  83. const response = await fetch(`${baseUrl}${pathname}`, { redirect: 'manual' });
  84. assert.equal(response.status, 200);
  85. assert.equal(response.headers.get('location'), null);
  86. assert.match(await response.text(), /auth-root/);
  87. }
  88. } finally {
  89. child.kill('SIGTERM');
  90. await waitForExit(child, 1000);
  91. }
  92. });
  93. test('users can manage multiple smtp login credentials', async () => {
  94. const { child, baseUrl } = await startTestServer();
  95. try {
  96. const cookie = await login(baseUrl, 'admin', 'password123');
  97. const first = await createSmtpCredential(baseUrl, cookie, {
  98. username: 'admin-smtp-main',
  99. password: 'main-secret'
  100. });
  101. const second = await createSmtpCredential(baseUrl, cookie, {
  102. username: 'admin-smtp-app',
  103. password: 'app-secret'
  104. });
  105. assert.equal(first.username, 'admin-smtp-main');
  106. assert.equal(first.passwordSet, true);
  107. assert.equal('password' in first, false);
  108. assert.equal(second.username, 'admin-smtp-app');
  109. assert.equal(second.passwordSet, true);
  110. assert.equal('password' in second, false);
  111. const list = await fetch(`${baseUrl}/api/smtp-credentials`, { headers: { Cookie: cookie } });
  112. assert.equal(list.status, 200);
  113. const listPayload = await list.json();
  114. assert.deepEqual(listPayload.credentials.map((credential) => credential.username), ['admin-smtp-app', 'admin-smtp-main']);
  115. assert.equal(listPayload.credentials[0].passwordSet, true);
  116. assert.equal('password' in listPayload.credentials[0], false);
  117. const update = await fetch(`${baseUrl}/api/smtp-credentials/${second.id}`, {
  118. method: 'PATCH',
  119. headers: {
  120. 'Content-Type': 'application/json',
  121. Cookie: cookie
  122. },
  123. body: JSON.stringify({ username: 'admin-smtp-app-renamed' })
  124. });
  125. assert.equal(update.status, 200);
  126. const updatedCredential = (await update.json()).credential;
  127. assert.equal(updatedCredential.passwordSet, true);
  128. assert.equal('password' in updatedCredential, false);
  129. const deleted = await fetch(`${baseUrl}/api/smtp-credentials/${first.id}`, {
  130. method: 'DELETE',
  131. headers: { Cookie: cookie }
  132. });
  133. assert.equal(deleted.status, 200);
  134. assert.equal((await deleted.json()).deleted, true);
  135. } finally {
  136. child.kill('SIGTERM');
  137. await waitForExit(child, 1000);
  138. }
  139. });
  140. test('users can manage inbound mailboxes and read inbound messages', async () => {
  141. const { child, baseUrl, dataDir, sessionSecret } = await startTestServer();
  142. try {
  143. const cookie = await login(baseUrl, 'admin', 'password123');
  144. await createSendingDomain(baseUrl, cookie, { domain: 'inbound-api.example' });
  145. const createMailbox = await fetch(`${baseUrl}/api/inbound-mailboxes`, {
  146. method: 'POST',
  147. headers: {
  148. 'Content-Type': 'application/json',
  149. Cookie: cookie
  150. },
  151. body: JSON.stringify({
  152. address: 'Support@inbound-api.example',
  153. displayName: 'Support',
  154. password: 'mailbox-pass-123',
  155. forwardTo: 'archive@example.net',
  156. keepForwarded: true
  157. })
  158. });
  159. assert.equal(createMailbox.status, 201);
  160. const createMailboxBody = await createMailbox.json();
  161. const mailbox = createMailboxBody.mailbox;
  162. assert.equal(mailbox.address, 'support@inbound-api.example');
  163. assert.equal(mailbox.displayName, 'Support');
  164. assert.equal(mailbox.passwordSet, true);
  165. assert.deepEqual(mailbox.forwardTo, ['archive@example.net']);
  166. assert.equal(mailbox.unreadCount, 0);
  167. assert.equal(createMailboxBody.clientConfig.username, 'support@inbound-api.example');
  168. assert.equal(createMailboxBody.clientConfig.password, 'mailbox-pass-123');
  169. assert.equal(createMailboxBody.clientConfig.outgoing.authMethod, 'Normal password');
  170. const mailboxes = await fetch(`${baseUrl}/api/inbound-mailboxes`, { headers: { Cookie: cookie } });
  171. assert.equal(mailboxes.status, 200);
  172. const mailboxesBody = await mailboxes.json();
  173. assert.deepEqual(mailboxesBody.mailboxes.map((entry) => entry.address), ['support@inbound-api.example']);
  174. const messageId = seedInboundMessage(dataDir, sessionSecret, 'support@inbound-api.example');
  175. const messages = await fetch(`${baseUrl}/api/inbound-messages?mailboxId=${mailbox.id}`, { headers: { Cookie: cookie } });
  176. assert.equal(messages.status, 200);
  177. const messagesBody = await messages.json();
  178. assert.equal(messagesBody.messages.length, 1);
  179. assert.equal(messagesBody.messages[0].id, messageId);
  180. assert.equal(messagesBody.messages[0].subject, 'Inbound API message');
  181. assert.equal(messagesBody.messages[0].textBody, undefined);
  182. const detail = await fetch(`${baseUrl}/api/inbound-messages/${messageId}`, { headers: { Cookie: cookie } });
  183. assert.equal(detail.status, 200);
  184. const detailBody = await detail.json();
  185. assert.equal(detailBody.message.textBody, 'Hello from inbound API.');
  186. assert.equal(detailBody.message.rawMessage.includes('Inbound API message'), true);
  187. const markRead = await fetch(`${baseUrl}/api/inbound-messages/${messageId}`, {
  188. method: 'PATCH',
  189. headers: {
  190. 'Content-Type': 'application/json',
  191. Cookie: cookie
  192. },
  193. body: JSON.stringify({ read: true })
  194. });
  195. assert.equal(markRead.status, 200);
  196. assert.equal((await markRead.json()).message.read, true);
  197. } finally {
  198. child.kill('SIGTERM');
  199. await waitForExit(child, 1000);
  200. }
  201. });
  202. test('shared domains are available for mailbox creation but not domain management', async () => {
  203. const { child, baseUrl, dataDir, sessionSecret } = await startTestServer();
  204. try {
  205. const ownerCookie = await login(baseUrl, 'admin', 'password123');
  206. const sharedDomain = await createSendingDomain(baseUrl, ownerCookie, { domain: 'shared-mailbox.example' });
  207. const share = await fetch(`${baseUrl}/api/domains/${sharedDomain.id}`, {
  208. method: 'PATCH',
  209. headers: {
  210. 'Content-Type': 'application/json',
  211. Cookie: ownerCookie
  212. },
  213. body: JSON.stringify({ mailboxSignupEnabled: true })
  214. });
  215. assert.equal(share.status, 200);
  216. assert.equal((await share.json()).domain.mailboxSignupEnabled, true);
  217. seedUsers(dataDir, sessionSecret, [
  218. { username: 'shared-user', email: 'shared-user@example.com', password: 'password123', status: 'active' }
  219. ]);
  220. const userCookie = await login(baseUrl, 'shared-user', 'password123');
  221. const manageableDomains = await fetch(`${baseUrl}/api/domains`, { headers: { Cookie: userCookie } });
  222. assert.equal(manageableDomains.status, 200);
  223. assert.deepEqual((await manageableDomains.json()).domains, []);
  224. const mailboxDomains = await fetch(`${baseUrl}/api/inbound-mailbox-domains`, { headers: { Cookie: userCookie } });
  225. assert.equal(mailboxDomains.status, 200);
  226. const mailboxDomainRows = (await mailboxDomains.json()).domains;
  227. assert.deepEqual(mailboxDomainRows.map((domain) => domain.domain), ['shared-mailbox.example']);
  228. assert.equal('dkimPublic' in mailboxDomainRows[0], false);
  229. const ownerMailbox = await fetch(`${baseUrl}/api/inbound-mailboxes`, {
  230. method: 'POST',
  231. headers: {
  232. 'Content-Type': 'application/json',
  233. Cookie: ownerCookie
  234. },
  235. body: JSON.stringify({
  236. address: 'owner@shared-mailbox.example',
  237. password: 'mailbox-pass-123',
  238. aliases: ['claimed']
  239. })
  240. });
  241. assert.equal(ownerMailbox.status, 201);
  242. const addressConflict = await fetch(`${baseUrl}/api/inbound-mailboxes`, {
  243. method: 'POST',
  244. headers: {
  245. 'Content-Type': 'application/json',
  246. Cookie: userCookie
  247. },
  248. body: JSON.stringify({
  249. address: 'claimed@shared-mailbox.example',
  250. password: 'mailbox-pass-123'
  251. })
  252. });
  253. assert.equal(addressConflict.status, 409);
  254. assert.match((await addressConflict.json()).error, /claimed@shared-mailbox\.example 已被其他邮箱占用/);
  255. const createMailbox = await fetch(`${baseUrl}/api/inbound-mailboxes`, {
  256. method: 'POST',
  257. headers: {
  258. 'Content-Type': 'application/json',
  259. Cookie: userCookie
  260. },
  261. body: JSON.stringify({
  262. address: 'user@shared-mailbox.example',
  263. password: 'mailbox-pass-123',
  264. aliases: ['user-alias']
  265. })
  266. });
  267. assert.equal(createMailbox.status, 201);
  268. const createdMailbox = (await createMailbox.json()).mailbox;
  269. assert.equal(createdMailbox.address, 'user@shared-mailbox.example');
  270. const aliasConflict = await fetch(`${baseUrl}/api/inbound-mailboxes/${createdMailbox.id}`, {
  271. method: 'PATCH',
  272. headers: {
  273. 'Content-Type': 'application/json',
  274. Cookie: userCookie
  275. },
  276. body: JSON.stringify({ aliases: ['owner'] })
  277. });
  278. assert.equal(aliasConflict.status, 409);
  279. assert.match((await aliasConflict.json()).error, /owner@shared-mailbox\.example 已被其他邮箱占用/);
  280. const blockedDelete = await fetch(`${baseUrl}/api/domains/${sharedDomain.id}`, {
  281. method: 'DELETE',
  282. headers: { Cookie: ownerCookie }
  283. });
  284. assert.equal(blockedDelete.status, 409);
  285. assert.match((await blockedDelete.json()).error, /仍有关联收信邮箱/);
  286. const blockedPatch = await fetch(`${baseUrl}/api/domains/${sharedDomain.id}`, {
  287. method: 'PATCH',
  288. headers: {
  289. 'Content-Type': 'application/json',
  290. Cookie: userCookie
  291. },
  292. body: JSON.stringify({ catchAllAddress: 'user@shared-mailbox.example' })
  293. });
  294. assert.equal(blockedPatch.status, 404);
  295. } finally {
  296. child.kill('SIGTERM');
  297. await waitForExit(child, 1000);
  298. }
  299. });
  300. test('scoped API tokens create persistent and temporary mailboxes', async () => {
  301. const { child, baseUrl } = await startTestServer();
  302. try {
  303. const cookie = await login(baseUrl, 'admin', 'password123');
  304. await createSendingDomain(baseUrl, cookie, { domain: 'mailbox-token-api.example' });
  305. const sendOnlyResponse = await fetch(`${baseUrl}/api/api-tokens`, {
  306. method: 'POST',
  307. headers: { 'Content-Type': 'application/json', Cookie: cookie },
  308. body: JSON.stringify({ name: 'send only', scopes: ['send'] })
  309. });
  310. assert.equal(sendOnlyResponse.status, 201);
  311. const sendOnly = (await sendOnlyResponse.json()).token;
  312. const denied = await fetch(`${baseUrl}/api/mailboxes`, {
  313. method: 'POST',
  314. headers: {
  315. Authorization: `Bearer ${sendOnly.token}`,
  316. 'Content-Type': 'application/json'
  317. },
  318. body: JSON.stringify({ mode: 'temporary', domain: 'mailbox-token-api.example', expiresInMinutes: 60 })
  319. });
  320. assert.equal(denied.status, 403);
  321. const tokenResponse = await fetch(`${baseUrl}/api/api-tokens`, {
  322. method: 'POST',
  323. headers: { 'Content-Type': 'application/json', Cookie: cookie },
  324. body: JSON.stringify({ name: 'mailboxes', scopes: ['mailboxes:read', 'mailboxes:write'] })
  325. });
  326. assert.equal(tokenResponse.status, 201);
  327. const mailboxToken = (await tokenResponse.json()).token;
  328. const temporary = await fetch(`${baseUrl}/api/mailboxes`, {
  329. method: 'POST',
  330. headers: {
  331. Authorization: `Bearer ${mailboxToken.token}`,
  332. 'Content-Type': 'application/json'
  333. },
  334. body: JSON.stringify({ mode: 'temporary', domain: 'mailbox-token-api.example', expiresInMinutes: 60 })
  335. });
  336. assert.equal(temporary.status, 201);
  337. const temporaryBody = await temporary.json();
  338. assert.match(temporaryBody.mailbox.address, /^tmp-[a-f0-9]+@mailbox-token-api\.example$/);
  339. assert.equal(temporaryBody.mailbox.temporary, true);
  340. assert.ok(temporaryBody.mailbox.expiresAt);
  341. assert.equal(temporaryBody.password.length >= 8, true);
  342. assert.equal(temporaryBody.clientConfig.incoming.protocol, 'IMAP');
  343. const permanent = await fetch(`${baseUrl}/api/mailboxes`, {
  344. method: 'POST',
  345. headers: {
  346. Authorization: `Bearer ${mailboxToken.token}`,
  347. 'Content-Type': 'application/json'
  348. },
  349. body: JSON.stringify({
  350. mode: 'permanent',
  351. address: 'support@mailbox-token-api.example',
  352. password: 'mailbox-pass-123'
  353. })
  354. });
  355. assert.equal(permanent.status, 201);
  356. const permanentBody = await permanent.json();
  357. assert.equal(permanentBody.mailbox.temporary, false);
  358. assert.equal(permanentBody.mailbox.expiresAt, null);
  359. assert.equal(permanentBody.clientConfig.outgoing.protocol, 'SMTP');
  360. const listed = await fetch(`${baseUrl}/api/mailboxes`, {
  361. headers: { Authorization: `Bearer ${mailboxToken.token}` }
  362. });
  363. assert.equal(listed.status, 200);
  364. assert.equal((await listed.json()).mailboxes.length, 2);
  365. const sendDenied = await fetch(`${baseUrl}/api/send`, {
  366. method: 'POST',
  367. headers: {
  368. Authorization: `Bearer ${mailboxToken.token}`,
  369. 'Content-Type': 'application/json'
  370. },
  371. body: JSON.stringify({ from: 'noreply@mailbox-token-api.example', to: 'user@example.com', text: 'blocked' })
  372. });
  373. assert.equal(sendDenied.status, 403);
  374. const revoke = await fetch(`${baseUrl}/api/api-tokens/${mailboxToken.id}`, {
  375. method: 'DELETE',
  376. headers: { Cookie: cookie }
  377. });
  378. assert.equal(revoke.status, 200);
  379. assert.equal((await revoke.json()).token.status, 'revoked');
  380. const rejectedAfterRevoke = await fetch(`${baseUrl}/api/mailboxes`, {
  381. headers: { Authorization: `Bearer ${mailboxToken.token}` }
  382. });
  383. assert.equal(rejectedAfterRevoke.status, 401);
  384. } finally {
  385. child.kill('SIGTERM');
  386. await waitForExit(child, 1000);
  387. }
  388. });
  389. test('users can manage outbound smtp relays with recoverable passwords and send through a selected relay', async () => {
  390. const relayServer = await startFakeSmtpServer();
  391. const { child, baseUrl } = await startTestServer();
  392. try {
  393. const cookie = await login(baseUrl, 'admin', 'password123');
  394. const domainResponse = await fetch(`${baseUrl}/api/domains`, {
  395. method: 'POST',
  396. headers: {
  397. 'Content-Type': 'application/json',
  398. Cookie: cookie
  399. },
  400. body: JSON.stringify({
  401. domain: 'relay.example',
  402. selector: 'mh',
  403. senderHost: 'mail.relay.example',
  404. sendingIp: '127.0.0.1'
  405. })
  406. });
  407. assert.equal(domainResponse.status, 201);
  408. const createRelay = await fetch(`${baseUrl}/api/smtp-relays`, {
  409. method: 'POST',
  410. headers: {
  411. 'Content-Type': 'application/json',
  412. Cookie: cookie
  413. },
  414. body: JSON.stringify({
  415. name: 'Primary outbound',
  416. host: '127.0.0.1',
  417. port: relayServer.port,
  418. secure: false,
  419. username: 'relay-user',
  420. password: 'relay-password',
  421. helo: 'helo.relay.example',
  422. isDefault: true
  423. })
  424. });
  425. assert.equal(createRelay.status, 201);
  426. const created = await createRelay.json();
  427. assert.equal(created.relay.passwordSet, true);
  428. assert.equal('password' in created.relay, false);
  429. const list = await fetch(`${baseUrl}/api/smtp-relays`, { headers: { Cookie: cookie } });
  430. assert.equal(list.status, 200);
  431. const listed = await list.json();
  432. assert.equal(listed.relays.length, 1);
  433. assert.equal('password' in listed.relays[0], false);
  434. const detail = await fetch(`${baseUrl}/api/smtp-relays/${created.relay.id}`, { headers: { Cookie: cookie } });
  435. assert.equal(detail.status, 200);
  436. const detailBody = await detail.json();
  437. assert.equal(detailBody.relay.passwordSet, true);
  438. assert.equal('password' in detailBody.relay, false);
  439. assert.equal('passwordSecret' in detailBody.relay, false);
  440. const missingPatch = await fetch(`${baseUrl}/api/smtp-relays/999999`, {
  441. method: 'PATCH',
  442. headers: {
  443. 'Content-Type': 'application/json',
  444. Cookie: cookie
  445. },
  446. body: JSON.stringify({
  447. name: 'Missing relay',
  448. host: '127.0.0.1',
  449. port: relayServer.port,
  450. secure: false,
  451. username: 'missing-user',
  452. password: 'missing-password'
  453. })
  454. });
  455. assert.equal(missingPatch.status, 404);
  456. const updateWithoutPassword = await fetch(`${baseUrl}/api/smtp-relays/${created.relay.id}`, {
  457. method: 'PATCH',
  458. headers: {
  459. 'Content-Type': 'application/json',
  460. Cookie: cookie
  461. },
  462. body: JSON.stringify({
  463. name: 'Primary outbound renamed',
  464. host: '127.0.0.1',
  465. port: relayServer.port,
  466. secure: false,
  467. username: 'relay-user'
  468. })
  469. });
  470. assert.equal(updateWithoutPassword.status, 200);
  471. const updatedRelay = (await updateWithoutPassword.json()).relay;
  472. assert.equal(updatedRelay.isDefault, true);
  473. assert.equal(updatedRelay.passwordSet, true);
  474. assert.equal('password' in updatedRelay, false);
  475. const detailAfterPatch = await fetch(`${baseUrl}/api/smtp-relays/${created.relay.id}`, { headers: { Cookie: cookie } });
  476. const detailAfterPatchBody = await detailAfterPatch.json();
  477. assert.equal(detailAfterPatchBody.relay.passwordSet, true);
  478. assert.equal('password' in detailAfterPatchBody.relay, false);
  479. const invalidRelaySend = await fetch(`${baseUrl}/api/send`, {
  480. method: 'POST',
  481. headers: {
  482. 'Content-Type': 'application/json',
  483. Cookie: cookie
  484. },
  485. body: JSON.stringify({
  486. from: 'noreply@relay.example',
  487. to: 'user@example.com',
  488. subject: 'Invalid relay',
  489. text: 'hello',
  490. smtpRelayId: 999999
  491. })
  492. });
  493. assert.equal(invalidRelaySend.status, 400);
  494. const send = await fetch(`${baseUrl}/api/send`, {
  495. method: 'POST',
  496. headers: {
  497. 'Content-Type': 'application/json',
  498. Cookie: cookie
  499. },
  500. body: JSON.stringify({
  501. from: 'noreply@relay.example',
  502. to: 'user@example.com',
  503. subject: 'Relay send',
  504. text: 'hello',
  505. smtpRelayId: created.relay.id
  506. })
  507. });
  508. assert.equal(send.status, 202);
  509. assert.equal((await send.json()).smtpRelayId, created.relay.id);
  510. await waitForCondition(() => relayServer.messages.length === 1);
  511. const authCommand = relayServer.commands.find((command) => command.startsWith('AUTH PLAIN '));
  512. assert.ok(authCommand);
  513. assert.equal(Buffer.from(authCommand.replace('AUTH PLAIN ', ''), 'base64').toString('utf8'), '\0relay-user\0relay-password');
  514. const events = await fetch(`${baseUrl}/api/events`, { headers: { Cookie: cookie } });
  515. assert.equal(events.status, 200);
  516. const eventsBody = await events.json();
  517. assert.equal(eventsBody.events[0].smtpRelayId, created.relay.id);
  518. const eventDetail = await fetch(`${baseUrl}/api/events/${eventsBody.events[0].id}`, {
  519. headers: { Cookie: cookie }
  520. });
  521. assert.equal(eventDetail.status, 200);
  522. const eventDetailBody = await eventDetail.json();
  523. assert.equal(eventDetailBody.event.id, eventsBody.events[0].id);
  524. assert.equal(eventDetailBody.event.smtpRelayId, created.relay.id);
  525. assert.equal(Array.isArray(eventDetailBody.event.webhookDeliveries), true);
  526. } finally {
  527. child.kill('SIGTERM');
  528. await waitForExit(child, 1000);
  529. await relayServer.close();
  530. }
  531. });
  532. test('smtp relay selection prefers request relay then domain relay then user default relay', async () => {
  533. const requestRelayServer = await startFakeSmtpServer();
  534. const domainRelayServer = await startFakeSmtpServer();
  535. const defaultRelayServer = await startFakeSmtpServer();
  536. const { child, baseUrl } = await startTestServer();
  537. try {
  538. const cookie = await login(baseUrl, 'admin', 'password123');
  539. const settings = await fetch(`${baseUrl}/api/admin/settings`, {
  540. method: 'PATCH',
  541. headers: {
  542. 'Content-Type': 'application/json',
  543. Cookie: cookie
  544. },
  545. body: JSON.stringify({
  546. appBaseUrl: baseUrl,
  547. engagementTrackingEnabled: true
  548. })
  549. });
  550. assert.equal(settings.status, 200);
  551. const defaultRelay = await createSmtpRelay(baseUrl, cookie, {
  552. name: 'Default relay',
  553. host: '127.0.0.1',
  554. port: defaultRelayServer.port,
  555. username: 'default-user',
  556. password: 'default-password',
  557. isDefault: true
  558. });
  559. const domainRelay = await createSmtpRelay(baseUrl, cookie, {
  560. name: 'Domain relay',
  561. host: '127.0.0.1',
  562. port: domainRelayServer.port,
  563. username: 'domain-user',
  564. password: 'domain-password'
  565. });
  566. const requestRelay = await createSmtpRelay(baseUrl, cookie, {
  567. name: 'Request relay',
  568. host: '127.0.0.1',
  569. port: requestRelayServer.port,
  570. username: 'request-user',
  571. password: 'request-password'
  572. });
  573. const domain = await createSendingDomain(baseUrl, cookie, {
  574. domain: 'relay-order.example',
  575. smtpRelayId: domainRelay.id
  576. });
  577. assert.equal(domain.smtpRelayId, domainRelay.id);
  578. const domainSend = await sendApiMail(baseUrl, cookie, {
  579. from: 'noreply@relay-order.example',
  580. to: 'domain@example.com',
  581. subject: 'Domain relay'
  582. });
  583. assert.equal(domainSend.smtpRelayId, domainRelay.id);
  584. await waitForCondition(() => domainRelayServer.messages.length === 1);
  585. assertRelayAuth(domainRelayServer, 'domain-user', 'domain-password');
  586. const requestSend = await sendApiMail(baseUrl, cookie, {
  587. from: 'noreply@relay-order.example',
  588. to: 'request@example.com',
  589. subject: 'Request relay',
  590. smtpRelayId: requestRelay.id
  591. });
  592. assert.equal(requestSend.smtpRelayId, requestRelay.id);
  593. await waitForCondition(() => requestRelayServer.messages.length === 1);
  594. assertRelayAuth(requestRelayServer, 'request-user', 'request-password');
  595. const testSend = await fetch(`${baseUrl}/api/domains/${domain.id}/test-send`, {
  596. method: 'POST',
  597. headers: {
  598. 'Content-Type': 'application/json',
  599. Cookie: cookie
  600. },
  601. body: JSON.stringify({
  602. to: 'test-send@example.com',
  603. subject: 'Selected relay test send',
  604. text: 'Open the HTML version to verify tracking.',
  605. html: '<html><body><p>MailHub tracking test.</p><a href="https://example.net/tracked">Tracked link</a></body></html>',
  606. smtpRelayId: requestRelay.id
  607. })
  608. });
  609. assert.equal(testSend.status, 202);
  610. const testSendBody = await testSend.json();
  611. assert.equal(testSendBody.smtpRelayId, requestRelay.id);
  612. assert.deepEqual(testSendBody.tracking, { enabled: true, opens: true, clicks: true, messageLevel: false });
  613. await waitForCondition(() => requestRelayServer.messages.length === 2);
  614. const testHtml = decodeHtmlPart(requestRelayServer.messages[1]);
  615. assert.match(testHtml, new RegExp(`${escapeRegExp(baseUrl)}/t/o/[A-Za-z0-9_-]+\\.gif`));
  616. assert.match(testHtml, new RegExp(`${escapeRegExp(baseUrl)}/t/c/[A-Za-z0-9_-]+`));
  617. assert.equal(testHtml.includes('https://example.net/tracked'), false);
  618. const invalidTestSend = await fetch(`${baseUrl}/api/domains/${domain.id}/test-send`, {
  619. method: 'POST',
  620. headers: {
  621. 'Content-Type': 'application/json',
  622. Cookie: cookie
  623. },
  624. body: JSON.stringify({
  625. to: 'invalid-test-send@example.com',
  626. smtpRelayId: 999999
  627. })
  628. });
  629. assert.equal(invalidTestSend.status, 400);
  630. const defaultDomain = await createSendingDomain(baseUrl, cookie, {
  631. domain: 'default-relay.example'
  632. });
  633. assert.equal(defaultDomain.smtpRelayId, null);
  634. const defaultSend = await sendApiMail(baseUrl, cookie, {
  635. from: 'noreply@default-relay.example',
  636. to: 'default@example.com',
  637. subject: 'Default relay'
  638. });
  639. assert.equal(defaultSend.smtpRelayId, defaultRelay.id);
  640. await waitForCondition(() => defaultRelayServer.messages.length === 1);
  641. assertRelayAuth(defaultRelayServer, 'default-user', 'default-password');
  642. } finally {
  643. child.kill('SIGTERM');
  644. await waitForExit(child, 1000);
  645. await requestRelayServer.close();
  646. await domainRelayServer.close();
  647. await defaultRelayServer.close();
  648. }
  649. });
  650. test('admin users can list audit logs', async () => {
  651. const { child, baseUrl } = await startTestServer();
  652. try {
  653. const cookie = await login(baseUrl, 'admin', 'password123');
  654. const response = await fetch(`${baseUrl}/api/admin/audit-logs`, {
  655. headers: { Cookie: cookie }
  656. });
  657. assert.equal(response.status, 200);
  658. assert.deepEqual(await response.json(), { logs: [] });
  659. } finally {
  660. child.kill('SIGTERM');
  661. await waitForExit(child, 1000);
  662. }
  663. });
  664. test('admin users can list resource inventory', async () => {
  665. const { child, baseUrl, dataDir, sessionSecret } = await startTestServer();
  666. try {
  667. seedUsers(dataDir, sessionSecret, [{
  668. username: 'alice',
  669. email: 'alice@example.com',
  670. password: 'password123',
  671. status: 'active'
  672. }]);
  673. const adminCookie = await login(baseUrl, 'admin', 'password123');
  674. const userCookie = await login(baseUrl, 'alice', 'password123');
  675. const forbidden = await fetch(`${baseUrl}/api/admin/resources`, {
  676. headers: { Cookie: userCookie }
  677. });
  678. assert.equal(forbidden.status, 403);
  679. const response = await fetch(`${baseUrl}/api/admin/resources`, {
  680. headers: { Cookie: adminCookie }
  681. });
  682. assert.equal(response.status, 200);
  683. const body = await response.json();
  684. assert.ok(Array.isArray(body.inventory.users));
  685. assert.ok(Array.isArray(body.inventory.warnings));
  686. assert.ok(body.inventory.users.some((entry) => entry.user.username === 'alice'));
  687. } finally {
  688. child.kill('SIGTERM');
  689. await waitForExit(child, 1000);
  690. }
  691. });
  692. test('admin users can transfer individual resources', async () => {
  693. const { child, baseUrl, dataDir, sessionSecret } = await startTestServer();
  694. try {
  695. const seeded = seedTransferResources(dataDir, sessionSecret);
  696. const adminCookie = await login(baseUrl, 'admin', 'password123');
  697. const aliceCookie = await login(baseUrl, 'alice', 'password123');
  698. const forbidden = await fetch(`${baseUrl}/api/admin/resources/domains/${seeded.domainId}/transfer`, {
  699. method: 'POST',
  700. headers: {
  701. 'Content-Type': 'application/json',
  702. Cookie: aliceCookie
  703. },
  704. body: JSON.stringify({ targetUserId: seeded.bobId })
  705. });
  706. assert.equal(forbidden.status, 403);
  707. const domain = await fetch(`${baseUrl}/api/admin/resources/domains/${seeded.domainId}/transfer`, {
  708. method: 'POST',
  709. headers: {
  710. 'Content-Type': 'application/json',
  711. Cookie: adminCookie
  712. },
  713. body: JSON.stringify({
  714. targetUserId: seeded.bobId,
  715. dnsCredentialMode: 'with_dns_credential'
  716. })
  717. });
  718. assert.equal(domain.status, 200);
  719. const domainBody = await domain.json();
  720. assert.equal(domainBody.domain.userId, seeded.bobId);
  721. assert.equal(domainBody.domain.dnsCredentialId, seeded.credentialId);
  722. const dns = await fetch(`${baseUrl}/api/admin/resources/dns-credentials/${seeded.standaloneCredentialId}/transfer`, {
  723. method: 'POST',
  724. headers: {
  725. 'Content-Type': 'application/json',
  726. Cookie: adminCookie
  727. },
  728. body: JSON.stringify({ targetUserId: seeded.bobId })
  729. });
  730. assert.equal(dns.status, 200);
  731. assert.equal((await dns.json()).credential.userId, seeded.bobId);
  732. const tokens = await fetch(`${baseUrl}/api/admin/resources/api-tokens/transfer`, {
  733. method: 'POST',
  734. headers: {
  735. 'Content-Type': 'application/json',
  736. Cookie: adminCookie
  737. },
  738. body: JSON.stringify({
  739. targetUserId: seeded.bobId,
  740. tokenIds: [seeded.apiTokenId]
  741. })
  742. });
  743. assert.equal(tokens.status, 200);
  744. const tokensBody = await tokens.json();
  745. assert.equal(tokensBody.tokens.length, 1);
  746. assert.equal(tokensBody.tokens[0].userId, seeded.bobId);
  747. const audit = await fetch(`${baseUrl}/api/admin/audit-logs?targetUserId=${seeded.bobId}`, {
  748. headers: { Cookie: adminCookie }
  749. });
  750. const actions = (await audit.json()).logs.map((entry) => entry.action);
  751. assert.ok(actions.includes('admin.transfer_domain'));
  752. assert.ok(actions.includes('admin.transfer_dns_credential'));
  753. assert.ok(actions.includes('admin.transfer_api_tokens'));
  754. } finally {
  755. child.kill('SIGTERM');
  756. await waitForExit(child, 1000);
  757. }
  758. });
  759. test('admin users can preview and execute user merge', async () => {
  760. const { child, baseUrl, dataDir, sessionSecret } = await startTestServer();
  761. try {
  762. const seeded = seedMergeResources(dataDir, sessionSecret);
  763. const adminCookie = await login(baseUrl, 'admin', 'password123');
  764. const previewResponse = await fetch(`${baseUrl}/api/admin/migrations/user-merge/preview`, {
  765. method: 'POST',
  766. headers: {
  767. 'Content-Type': 'application/json',
  768. Cookie: adminCookie
  769. },
  770. body: JSON.stringify({
  771. sourceUserId: seeded.sourceId,
  772. targetUserId: seeded.targetId
  773. })
  774. });
  775. assert.equal(previewResponse.status, 200);
  776. const preview = (await previewResponse.json()).preview;
  777. assert.equal(preview.confirmationText, 'MERGE mergesource INTO mergetarget');
  778. assert.equal(preview.counts.domains, 1);
  779. const invalid = await fetch(`${baseUrl}/api/admin/migrations/user-merge/execute`, {
  780. method: 'POST',
  781. headers: {
  782. 'Content-Type': 'application/json',
  783. Cookie: adminCookie
  784. },
  785. body: JSON.stringify({
  786. sourceUserId: seeded.sourceId,
  787. targetUserId: seeded.targetId,
  788. confirmation: 'wrong'
  789. })
  790. });
  791. assert.equal(invalid.status, 400);
  792. const execute = await fetch(`${baseUrl}/api/admin/migrations/user-merge/execute`, {
  793. method: 'POST',
  794. headers: {
  795. 'Content-Type': 'application/json',
  796. Cookie: adminCookie
  797. },
  798. body: JSON.stringify({
  799. sourceUserId: seeded.sourceId,
  800. targetUserId: seeded.targetId,
  801. confirmation: preview.confirmationText
  802. })
  803. });
  804. assert.equal(execute.status, 200);
  805. const result = (await execute.json()).result;
  806. assert.equal(result.counts.domains, 1);
  807. assert.equal(result.sourceUser.status, 'disabled');
  808. const audit = await fetch(`${baseUrl}/api/admin/audit-logs?action=admin.user_merge`, {
  809. headers: { Cookie: adminCookie }
  810. });
  811. assert.equal(audit.status, 200);
  812. assert.equal((await audit.json()).logs[0].targetUserId, seeded.targetId);
  813. } finally {
  814. child.kill('SIGTERM');
  815. await waitForExit(child, 1000);
  816. }
  817. });
  818. test('admin users can manage system email settings without exposing password', async () => {
  819. const { child, baseUrl, dataDir, sessionSecret } = await startTestServer();
  820. try {
  821. seedUsers(dataDir, sessionSecret, [{
  822. username: 'alice',
  823. email: 'alice@example.com',
  824. password: 'password123',
  825. status: 'active'
  826. }]);
  827. const adminCookie = await login(baseUrl, 'admin', 'password123');
  828. const userCookie = await login(baseUrl, 'alice', 'password123');
  829. const forbidden = await fetch(`${baseUrl}/api/admin/system-email`, {
  830. headers: { Cookie: userCookie }
  831. });
  832. assert.equal(forbidden.status, 403);
  833. const empty = await fetch(`${baseUrl}/api/admin/system-email`, {
  834. headers: { Cookie: adminCookie }
  835. });
  836. assert.equal(empty.status, 200);
  837. assert.equal((await empty.json()).settings.passwordSet, false);
  838. const saved = await fetch(`${baseUrl}/api/admin/system-email`, {
  839. method: 'PATCH',
  840. headers: {
  841. 'Content-Type': 'application/json',
  842. Cookie: adminCookie
  843. },
  844. body: JSON.stringify({
  845. host: 'smtp.example.com',
  846. port: 587,
  847. secure: false,
  848. username: 'mailer@example.com',
  849. password: 'smtp-password-123',
  850. helo: 'mail.example.com',
  851. fromEmail: 'notify@example.com',
  852. fromName: 'MailHub Notify',
  853. testRecipient: 'admin@example.com'
  854. })
  855. });
  856. assert.equal(saved.status, 200);
  857. const savedBody = await saved.json();
  858. assert.equal(savedBody.settings.host, 'smtp.example.com');
  859. assert.equal(savedBody.settings.port, 587);
  860. assert.equal(savedBody.settings.secure, false);
  861. assert.equal(savedBody.settings.passwordSet, true);
  862. assert.equal('password' in savedBody.settings, false);
  863. assert.equal(JSON.stringify(savedBody).includes('smtp-password-123'), false);
  864. const preserved = await fetch(`${baseUrl}/api/admin/system-email`, {
  865. method: 'PATCH',
  866. headers: {
  867. 'Content-Type': 'application/json',
  868. Cookie: adminCookie
  869. },
  870. body: JSON.stringify({
  871. host: 'smtp2.example.com',
  872. password: ''
  873. })
  874. });
  875. assert.equal(preserved.status, 200);
  876. const preservedBody = await preserved.json();
  877. assert.equal(preservedBody.settings.host, 'smtp2.example.com');
  878. assert.equal(preservedBody.settings.passwordSet, true);
  879. assert.equal(JSON.stringify(preservedBody).includes('smtp-password-123'), false);
  880. const audit = await fetch(`${baseUrl}/api/admin/audit-logs?action=admin.update_system_email`, {
  881. headers: { Cookie: adminCookie }
  882. });
  883. assert.equal(audit.status, 200);
  884. const [entry] = (await audit.json()).logs;
  885. assert.equal(entry.action, 'admin.update_system_email');
  886. assert.equal(entry.targetType, 'system_email');
  887. assert.equal(entry.summary.host, 'smtp2.example.com');
  888. assert.equal(entry.summary.password, undefined);
  889. assert.equal(entry.summary.passwordSet, true);
  890. } finally {
  891. child.kill('SIGTERM');
  892. await waitForExit(child, 1000);
  893. }
  894. });
  895. test('registration and verification resend use configured system email', async () => {
  896. const smtp = await startFakeSmtpServer();
  897. const { child, baseUrl, dataDir, sessionSecret } = await startTestServer();
  898. try {
  899. seedUsers(dataDir, sessionSecret, [
  900. { username: 'publicpending', email: 'publicpending@example.com', password: 'password123', status: 'pending_email' },
  901. { username: 'adminpending', email: 'adminpending@example.com', password: 'password123', status: 'pending_email' }
  902. ]);
  903. const adminCookie = await login(baseUrl, 'admin', 'password123');
  904. await saveSystemEmailSettings(baseUrl, adminCookie, smtp.port);
  905. const register = await fetch(`${baseUrl}/api/register`, {
  906. method: 'POST',
  907. headers: { 'Content-Type': 'application/json' },
  908. body: JSON.stringify({
  909. username: 'mailuser',
  910. email: 'mailuser@example.com',
  911. password: 'password123'
  912. })
  913. });
  914. assert.equal(register.status, 201);
  915. const registerBody = await register.json();
  916. assert.equal(registerBody.user.status, 'pending_email');
  917. assert.equal(registerBody.verificationEmailSent, true);
  918. assert.equal(countAccountTokensForUser(dataDir, sessionSecret, 'mailuser', 'email_verification'), 1);
  919. const publicResend = await fetch(`${baseUrl}/api/auth/resend-verification`, {
  920. method: 'POST',
  921. headers: { 'Content-Type': 'application/json' },
  922. body: JSON.stringify({ email: 'publicpending@example.com' })
  923. });
  924. assert.equal(publicResend.status, 202);
  925. const publicResendBody = await publicResend.json();
  926. assert.equal(publicResendBody.message, '如果账号需要验证,我们会发送验证邮件。');
  927. assert.equal('verificationEmailSent' in publicResendBody, false);
  928. assert.equal('result' in publicResendBody, false);
  929. await waitForCondition(() => countAccountTokensForUser(dataDir, sessionSecret, 'publicpending', 'email_verification') === 1);
  930. const usersResponse = await fetch(`${baseUrl}/api/admin/users`, {
  931. headers: { Cookie: adminCookie }
  932. });
  933. const adminPending = (await usersResponse.json()).users.find((user) => user.username === 'adminpending');
  934. assert.ok(adminPending);
  935. const adminResend = await fetch(`${baseUrl}/api/admin/users/${adminPending.id}/resend-verification`, {
  936. method: 'POST',
  937. headers: { Cookie: adminCookie }
  938. });
  939. assert.equal(adminResend.status, 202);
  940. assert.equal((await adminResend.json()).verificationEmailSent, true);
  941. assert.equal(countAccountTokensForUser(dataDir, sessionSecret, 'adminpending', 'email_verification'), 1);
  942. assert.ok(smtp.commands.some((command) => command === 'MAIL FROM:<notify@example.com>'));
  943. assert.ok(smtp.commands.some((command) => command === 'RCPT TO:<mailuser@example.com>'));
  944. assert.ok(smtp.commands.some((command) => command === 'RCPT TO:<publicpending@example.com>'));
  945. assert.ok(smtp.commands.some((command) => command === 'RCPT TO:<adminpending@example.com>'));
  946. assert.equal(JSON.stringify(smtp.commands).includes('smtp-password-123'), false);
  947. } finally {
  948. child.kill('SIGTERM');
  949. await waitForExit(child, 1000);
  950. await smtp.close();
  951. }
  952. });
  953. test('public verification resend is generic and does not create tokens without mail config', async () => {
  954. const { child, baseUrl, dataDir, sessionSecret } = await startTestServer();
  955. try {
  956. seedUsers(dataDir, sessionSecret, [{
  957. username: 'pendingnomail',
  958. email: 'pendingnomail@example.com',
  959. password: 'password123',
  960. status: 'pending_email'
  961. }]);
  962. const response = await fetch(`${baseUrl}/api/auth/resend-verification`, {
  963. method: 'POST',
  964. headers: { 'Content-Type': 'application/json' },
  965. body: JSON.stringify({ email: 'pendingnomail@example.com' })
  966. });
  967. assert.equal(response.status, 202);
  968. assert.deepEqual(await response.json(), {
  969. message: '如果账号需要验证,我们会发送验证邮件。'
  970. });
  971. assert.equal(countAccountTokensForUser(dataDir, sessionSecret, 'pendingnomail', 'email_verification'), 0);
  972. } finally {
  973. child.kill('SIGTERM');
  974. await waitForExit(child, 1000);
  975. }
  976. });
  977. test('registration reports pending email when system email is not configured', async () => {
  978. const { child, baseUrl, dataDir, sessionSecret } = await startTestServer();
  979. try {
  980. const register = await fetch(`${baseUrl}/api/register`, {
  981. method: 'POST',
  982. headers: { 'Content-Type': 'application/json' },
  983. body: JSON.stringify({
  984. username: 'nomailuser',
  985. email: 'nomailuser@example.com',
  986. password: 'password123'
  987. })
  988. });
  989. assert.equal(register.status, 201);
  990. const body = await register.json();
  991. assert.equal(body.user.status, 'pending_email');
  992. assert.equal(body.verificationEmailSent, false);
  993. assert.match(body.message, /验证邮件暂未发送/);
  994. assert.equal(countAccountTokensForUser(dataDir, sessionSecret, 'nomailuser', 'email_verification'), 1);
  995. } finally {
  996. child.kill('SIGTERM');
  997. await waitForExit(child, 1000);
  998. }
  999. });
  1000. test('admin users can send system email test messages', async () => {
  1001. const smtp = await startFakeSmtpServer();
  1002. const { child, baseUrl } = await startTestServer();
  1003. try {
  1004. const adminCookie = await login(baseUrl, 'admin', 'password123');
  1005. await saveSystemEmailSettings(baseUrl, adminCookie, smtp.port);
  1006. const response = await fetch(`${baseUrl}/api/admin/system-email/test`, {
  1007. method: 'POST',
  1008. headers: {
  1009. 'Content-Type': 'application/json',
  1010. Cookie: adminCookie
  1011. },
  1012. body: JSON.stringify({ to: 'operator@example.com' })
  1013. });
  1014. assert.equal(response.status, 202);
  1015. const body = await response.json();
  1016. assert.equal(body.result.ok, true);
  1017. assert.equal(body.result.queueId, 'SYS123');
  1018. assert.equal(JSON.stringify(body).includes('smtp-password-123'), false);
  1019. assert.ok(smtp.commands.some((command) => command === 'RCPT TO:<operator@example.com>'));
  1020. const audit = await fetch(`${baseUrl}/api/admin/audit-logs?action=admin.test_system_email`, {
  1021. headers: { Cookie: adminCookie }
  1022. });
  1023. assert.equal(audit.status, 200);
  1024. const [entry] = (await audit.json()).logs;
  1025. assert.equal(entry.targetType, 'system_email');
  1026. assert.equal(entry.summary.to, 'operator@example.com');
  1027. assert.equal(entry.summary.ok, true);
  1028. } finally {
  1029. child.kill('SIGTERM');
  1030. await waitForExit(child, 1000);
  1031. await smtp.close();
  1032. }
  1033. });
  1034. test('public forgot password is generic and sends reset email when configured', async () => {
  1035. const smtp = await startFakeSmtpServer({ responseDelayMs: 700 });
  1036. const { child, baseUrl, dataDir, sessionSecret } = await startTestServer();
  1037. try {
  1038. seedUsers(dataDir, sessionSecret, [{
  1039. username: 'resetme',
  1040. email: 'resetme@example.com',
  1041. password: 'password123',
  1042. status: 'active'
  1043. }]);
  1044. const adminCookie = await login(baseUrl, 'admin', 'password123');
  1045. await saveSystemEmailSettings(baseUrl, adminCookie, smtp.port);
  1046. const startedAt = Date.now();
  1047. const existing = await fetch(`${baseUrl}/api/auth/forgot-password`, {
  1048. method: 'POST',
  1049. headers: { 'Content-Type': 'application/json' },
  1050. body: JSON.stringify({ email: 'resetme@example.com' })
  1051. });
  1052. const elapsedMs = Date.now() - startedAt;
  1053. assert.equal(existing.status, 202);
  1054. assert.equal(elapsedMs < 500, true);
  1055. assert.deepEqual(await existing.json(), {
  1056. message: '如果邮箱存在,我们会发送密码重置邮件。'
  1057. });
  1058. await waitForCondition(() => countAccountTokensForUser(dataDir, sessionSecret, 'resetme', 'password_reset') === 1);
  1059. const missing = await fetch(`${baseUrl}/api/auth/forgot-password`, {
  1060. method: 'POST',
  1061. headers: { 'Content-Type': 'application/json' },
  1062. body: JSON.stringify({ email: 'missing@example.com' })
  1063. });
  1064. assert.equal(missing.status, 202);
  1065. assert.deepEqual(await missing.json(), {
  1066. message: '如果邮箱存在,我们会发送密码重置邮件。'
  1067. });
  1068. await waitForCondition(() => smtp.commands.some((command) => command === 'RCPT TO:<resetme@example.com>'));
  1069. } finally {
  1070. child.kill('SIGTERM');
  1071. await waitForExit(child, 1000);
  1072. await smtp.close();
  1073. }
  1074. });
  1075. test('public reset password consumes token and updates password', async () => {
  1076. const { child, baseUrl, dataDir, sessionSecret } = await startTestServer();
  1077. try {
  1078. seedUsers(dataDir, sessionSecret, [{
  1079. username: 'tokenreset',
  1080. email: 'tokenreset@example.com',
  1081. password: 'password123',
  1082. status: 'active'
  1083. }]);
  1084. const token = createPasswordResetToken(dataDir, sessionSecret, 'tokenreset');
  1085. const response = await fetch(`${baseUrl}/api/auth/reset-password`, {
  1086. method: 'POST',
  1087. headers: { 'Content-Type': 'application/json' },
  1088. body: JSON.stringify({
  1089. token,
  1090. password: 'new-password-123'
  1091. })
  1092. });
  1093. assert.equal(response.status, 200);
  1094. assert.deepEqual(await response.json(), {
  1095. message: '密码已重置,请使用新密码登录。'
  1096. });
  1097. const oldLogin = await loginResponse(baseUrl, 'tokenreset', 'password123');
  1098. assert.equal(oldLogin.status, 401);
  1099. const newLogin = await loginResponse(baseUrl, 'tokenreset', 'new-password-123');
  1100. assert.equal(newLogin.status, 200);
  1101. const reused = await fetch(`${baseUrl}/api/auth/reset-password`, {
  1102. method: 'POST',
  1103. headers: { 'Content-Type': 'application/json' },
  1104. body: JSON.stringify({
  1105. token,
  1106. password: 'another-password-123'
  1107. })
  1108. });
  1109. assert.equal(reused.status, 400);
  1110. } finally {
  1111. child.kill('SIGTERM');
  1112. await waitForExit(child, 1000);
  1113. }
  1114. });
  1115. test('admin users can trigger password reset email and set temporary password', async () => {
  1116. const smtp = await startFakeSmtpServer();
  1117. const { child, baseUrl, dataDir, sessionSecret } = await startTestServer();
  1118. try {
  1119. seedUsers(dataDir, sessionSecret, [
  1120. { username: 'targetuser', email: 'targetuser@example.com', password: 'password123', status: 'active' },
  1121. { username: 'member2', email: 'member2@example.com', password: 'password123', status: 'active' }
  1122. ]);
  1123. const adminCookie = await login(baseUrl, 'admin', 'password123');
  1124. const memberCookie = await login(baseUrl, 'member2', 'password123');
  1125. await saveSystemEmailSettings(baseUrl, adminCookie, smtp.port);
  1126. const usersResponse = await fetch(`${baseUrl}/api/admin/users`, {
  1127. headers: { Cookie: adminCookie }
  1128. });
  1129. const target = (await usersResponse.json()).users.find((user) => user.username === 'targetuser');
  1130. assert.ok(target);
  1131. const forbiddenReset = await fetch(`${baseUrl}/api/admin/users/${target.id}/password-reset`, {
  1132. method: 'POST',
  1133. headers: { Cookie: memberCookie }
  1134. });
  1135. assert.equal(forbiddenReset.status, 403);
  1136. const reset = await fetch(`${baseUrl}/api/admin/users/${target.id}/password-reset`, {
  1137. method: 'POST',
  1138. headers: { Cookie: adminCookie }
  1139. });
  1140. assert.equal(reset.status, 202);
  1141. assert.equal((await reset.json()).result.ok, true);
  1142. assert.equal(countAccountTokensForUser(dataDir, sessionSecret, 'targetuser', 'password_reset'), 1);
  1143. assert.ok(smtp.commands.some((command) => command === 'RCPT TO:<targetuser@example.com>'));
  1144. const forbiddenTemporary = await fetch(`${baseUrl}/api/admin/users/${target.id}/temporary-password`, {
  1145. method: 'POST',
  1146. headers: {
  1147. 'Content-Type': 'application/json',
  1148. Cookie: memberCookie
  1149. },
  1150. body: JSON.stringify({ password: 'temporary-123' })
  1151. });
  1152. assert.equal(forbiddenTemporary.status, 403);
  1153. const temporary = await fetch(`${baseUrl}/api/admin/users/${target.id}/temporary-password`, {
  1154. method: 'POST',
  1155. headers: {
  1156. 'Content-Type': 'application/json',
  1157. Cookie: adminCookie
  1158. },
  1159. body: JSON.stringify({ password: 'temporary-123' })
  1160. });
  1161. assert.equal(temporary.status, 200);
  1162. assert.equal((await temporary.json()).user.id, target.id);
  1163. assert.equal(countUnusedAccountTokensForUser(dataDir, sessionSecret, 'targetuser', 'password_reset'), 0);
  1164. const oldLogin = await loginResponse(baseUrl, 'targetuser', 'password123');
  1165. assert.equal(oldLogin.status, 401);
  1166. const tempLogin = await loginResponse(baseUrl, 'targetuser', 'temporary-123');
  1167. assert.equal(tempLogin.status, 200);
  1168. const audit = await fetch(`${baseUrl}/api/admin/audit-logs?targetUserId=${target.id}`, {
  1169. headers: { Cookie: adminCookie }
  1170. });
  1171. assert.equal(audit.status, 200);
  1172. const logs = (await audit.json()).logs;
  1173. assert.ok(logs.some((entry) => entry.action === 'admin.password_reset'));
  1174. const temporaryLog = logs.find((entry) => entry.action === 'admin.temporary_password');
  1175. assert.ok(temporaryLog);
  1176. assert.equal(temporaryLog.summary.username, 'targetuser');
  1177. assert.equal(temporaryLog.summary.password, undefined);
  1178. assert.equal(JSON.stringify(temporaryLog).includes('temporary-123'), false);
  1179. } finally {
  1180. child.kill('SIGTERM');
  1181. await waitForExit(child, 1000);
  1182. await smtp.close();
  1183. }
  1184. });
  1185. test('non-admin users cannot list audit logs', async () => {
  1186. const { child, baseUrl, dataDir, sessionSecret } = await startTestServer();
  1187. try {
  1188. seedUsers(dataDir, sessionSecret, [{
  1189. username: 'alice',
  1190. email: 'alice@example.com',
  1191. password: 'password123',
  1192. status: 'active'
  1193. }]);
  1194. const cookie = await login(baseUrl, 'alice', 'password123');
  1195. const response = await fetch(`${baseUrl}/api/admin/audit-logs`, {
  1196. headers: { Cookie: cookie }
  1197. });
  1198. assert.equal(response.status, 403);
  1199. } finally {
  1200. child.kill('SIGTERM');
  1201. await waitForExit(child, 1000);
  1202. }
  1203. });
  1204. test('admin user patch rejects invalid status with a bad request', async () => {
  1205. const { child, baseUrl, dataDir, sessionSecret } = await startTestServer();
  1206. try {
  1207. seedUsers(dataDir, sessionSecret, [{
  1208. username: 'badstatus',
  1209. email: 'badstatus@example.com',
  1210. password: 'password123',
  1211. status: 'active'
  1212. }]);
  1213. const cookie = await login(baseUrl, 'admin', 'password123');
  1214. const usersResponse = await fetch(`${baseUrl}/api/admin/users`, {
  1215. headers: { Cookie: cookie }
  1216. });
  1217. assert.equal(usersResponse.status, 200);
  1218. const usersBody = await usersResponse.json();
  1219. const target = usersBody.users.find((user) => user.username === 'badstatus');
  1220. assert.ok(target);
  1221. const response = await fetch(`${baseUrl}/api/admin/users/${target.id}`, {
  1222. method: 'PATCH',
  1223. headers: {
  1224. 'Content-Type': 'application/json',
  1225. Cookie: cookie
  1226. },
  1227. body: JSON.stringify({ status: 'archived' })
  1228. });
  1229. assert.equal(response.status, 400);
  1230. assert.equal((await response.json()).error, '用户状态不正确。');
  1231. const shortPassword = await fetch(`${baseUrl}/api/admin/users/${target.id}`, {
  1232. method: 'PATCH',
  1233. headers: {
  1234. 'Content-Type': 'application/json',
  1235. Cookie: cookie
  1236. },
  1237. body: JSON.stringify({ password: 'short' })
  1238. });
  1239. assert.equal(shortPassword.status, 400);
  1240. assert.equal((await shortPassword.json()).error, '密码至少需要 8 位。');
  1241. } finally {
  1242. child.kill('SIGTERM');
  1243. await waitForExit(child, 1000);
  1244. }
  1245. });
  1246. test('self registration creates a pending email user and verification token without a session', async () => {
  1247. const { child, baseUrl, dataDir, sessionSecret } = await startTestServer();
  1248. try {
  1249. const register = await fetch(`${baseUrl}/api/register`, {
  1250. method: 'POST',
  1251. headers: { 'Content-Type': 'application/json' },
  1252. body: JSON.stringify({
  1253. username: 'newuser',
  1254. email: 'newuser@example.com',
  1255. password: 'password123'
  1256. })
  1257. });
  1258. assert.equal(register.status, 201);
  1259. assert.equal(sessionCookieFrom(register), '');
  1260. const text = await register.text();
  1261. assert.doesNotMatch(text, /token/i);
  1262. const body = JSON.parse(text);
  1263. assert.equal('token' in body, false);
  1264. assert.equal('token' in body.user, false);
  1265. assert.equal('tokenHash' in body.user, false);
  1266. assert.equal(body.user.status, 'pending_email');
  1267. assert.match(body.message, /验证邮箱/);
  1268. assert.equal(countAccountTokensForUser(dataDir, sessionSecret, 'newuser', 'email_verification'), 1);
  1269. const login = await loginResponse(baseUrl, 'newuser', 'password123');
  1270. assert.equal(login.status, 403);
  1271. assert.equal(sessionCookieFrom(login), '');
  1272. assert.equal((await login.json()).error, '请先验证邮箱。');
  1273. } finally {
  1274. child.kill('SIGTERM');
  1275. await waitForExit(child, 1000);
  1276. }
  1277. });
  1278. test('email verification route consumes token and moves user to admin review', async () => {
  1279. const { child, baseUrl, dataDir, sessionSecret } = await startTestServer();
  1280. try {
  1281. const created = createPendingEmailUserWithVerificationToken(dataDir, sessionSecret, {
  1282. username: 'verifyme',
  1283. email: 'verifyme@example.com',
  1284. password: 'password123',
  1285. status: 'pending_email'
  1286. });
  1287. const missing = await fetch(`${baseUrl}/api/auth/verify-email`);
  1288. assert.equal(missing.status, 400);
  1289. assert.equal(sessionCookieFrom(missing), '');
  1290. const invalid = await fetch(`${baseUrl}/api/auth/verify-email?token=not-a-real-token`);
  1291. assert.equal(invalid.status, 400);
  1292. assert.equal(sessionCookieFrom(invalid), '');
  1293. const htmlInvalid = await fetch(`${baseUrl}/api/auth/verify-email?token=not-a-real-token`, {
  1294. redirect: 'manual',
  1295. headers: { Accept: 'text/html,application/xhtml+xml' }
  1296. });
  1297. assert.equal(htmlInvalid.status, 303);
  1298. assert.match(htmlInvalid.headers.get('location') || '', /^\/login\?error=/);
  1299. assert.equal(sessionCookieFrom(htmlInvalid), '');
  1300. const browserCreated = createPendingEmailUserWithVerificationToken(dataDir, sessionSecret, {
  1301. username: 'verifybrowser',
  1302. email: 'verifybrowser@example.com',
  1303. password: 'password123',
  1304. status: 'pending_email'
  1305. });
  1306. const browserResponse = await fetch(`${baseUrl}/api/auth/verify-email?token=${encodeURIComponent(browserCreated.token)}`, {
  1307. redirect: 'manual',
  1308. headers: { Accept: 'text/html,application/xhtml+xml' }
  1309. });
  1310. assert.equal(browserResponse.status, 303);
  1311. assert.match(browserResponse.headers.get('location') || '', /^\/login\?message=/);
  1312. assert.equal(sessionCookieFrom(browserResponse), '');
  1313. const response = await fetch(`${baseUrl}/api/auth/verify-email?token=${encodeURIComponent(created.token)}`);
  1314. assert.equal(response.status, 200);
  1315. assert.equal(sessionCookieFrom(response), '');
  1316. const body = await response.json();
  1317. assert.equal(body.user.id, created.user.id);
  1318. assert.equal(body.user.status, 'pending_review');
  1319. assert.match(body.message, /管理员审核/);
  1320. const reused = await fetch(`${baseUrl}/api/auth/verify-email?token=${encodeURIComponent(created.token)}`);
  1321. assert.equal(reused.status, 400);
  1322. assert.equal(sessionCookieFrom(reused), '');
  1323. const login = await loginResponse(baseUrl, 'verifyme', 'password123');
  1324. assert.equal(login.status, 403);
  1325. assert.equal(sessionCookieFrom(login), '');
  1326. assert.equal((await login.json()).error, '账号正在等待管理员审核。');
  1327. } finally {
  1328. child.kill('SIGTERM');
  1329. await waitForExit(child, 1000);
  1330. }
  1331. });
  1332. test('admin users can approve pending review users with an audit log', async () => {
  1333. const { child, baseUrl, dataDir, sessionSecret } = await startTestServer();
  1334. try {
  1335. seedUsers(dataDir, sessionSecret, [
  1336. { username: 'reviewme', email: 'reviewme@example.com', password: 'password123', status: 'pending_review' },
  1337. { username: 'emailonly', email: 'emailonly@example.com', password: 'password123', status: 'pending_email' },
  1338. { username: 'disabledreview', email: 'disabledreview@example.com', password: 'password123', status: 'disabled' },
  1339. { username: 'member', email: 'member@example.com', password: 'password123', status: 'active' }
  1340. ]);
  1341. const adminCookie = await login(baseUrl, 'admin', 'password123');
  1342. const usersResponse = await fetch(`${baseUrl}/api/admin/users`, {
  1343. headers: { Cookie: adminCookie }
  1344. });
  1345. assert.equal(usersResponse.status, 200);
  1346. const users = (await usersResponse.json()).users;
  1347. const target = users.find((user) => user.username === 'reviewme');
  1348. const pendingEmail = users.find((user) => user.username === 'emailonly');
  1349. const disabled = users.find((user) => user.username === 'disabledreview');
  1350. assert.ok(target);
  1351. assert.ok(pendingEmail);
  1352. assert.ok(disabled);
  1353. const memberCookie = await login(baseUrl, 'member', 'password123');
  1354. const nonAdmin = await fetch(`${baseUrl}/api/admin/users/${target.id}/approve`, {
  1355. method: 'POST',
  1356. headers: { Cookie: memberCookie }
  1357. });
  1358. assert.equal(nonAdmin.status, 403);
  1359. const missing = await fetch(`${baseUrl}/api/admin/users/999999/approve`, {
  1360. method: 'POST',
  1361. headers: { Cookie: adminCookie }
  1362. });
  1363. assert.equal(missing.status, 404);
  1364. const pendingEmailResponse = await fetch(`${baseUrl}/api/admin/users/${pendingEmail.id}/approve`, {
  1365. method: 'POST',
  1366. headers: { Cookie: adminCookie }
  1367. });
  1368. assert.equal(pendingEmailResponse.status, 400);
  1369. assert.match((await pendingEmailResponse.json()).error, /验证邮箱|等待审核/);
  1370. const disabledResponse = await fetch(`${baseUrl}/api/admin/users/${disabled.id}/approve`, {
  1371. method: 'POST',
  1372. headers: { Cookie: adminCookie }
  1373. });
  1374. assert.equal(disabledResponse.status, 400);
  1375. assert.match((await disabledResponse.json()).error, /等待审核|只能审批/);
  1376. const response = await fetch(`${baseUrl}/api/admin/users/${target.id}/approve`, {
  1377. method: 'POST',
  1378. headers: { Cookie: adminCookie }
  1379. });
  1380. assert.equal(response.status, 200);
  1381. const body = await response.json();
  1382. assert.equal(body.user.id, target.id);
  1383. assert.equal(body.user.status, 'active');
  1384. const approvedCookie = await login(baseUrl, 'reviewme', 'password123');
  1385. assert.ok(approvedCookie);
  1386. const auditResponse = await fetch(`${baseUrl}/api/admin/audit-logs?action=admin.approve_user`, {
  1387. headers: { Cookie: adminCookie }
  1388. });
  1389. assert.equal(auditResponse.status, 200);
  1390. const [entry] = (await auditResponse.json()).logs;
  1391. assert.equal(entry.action, 'admin.approve_user');
  1392. assert.equal(entry.targetType, 'user');
  1393. assert.equal(entry.targetId, String(target.id));
  1394. assert.equal(entry.targetUserId, target.id);
  1395. assert.equal(entry.summary.username, 'reviewme');
  1396. assert.equal(entry.summary.status, 'active');
  1397. assert.equal(entry.summary.password, undefined);
  1398. assert.equal(entry.summary.token, undefined);
  1399. } finally {
  1400. child.kill('SIGTERM');
  1401. await waitForExit(child, 1000);
  1402. }
  1403. });
  1404. test('login returns account status restrictions only after password verification', async () => {
  1405. const { child, baseUrl, dataDir, sessionSecret } = await startTestServer();
  1406. try {
  1407. seedUsers(dataDir, sessionSecret, [
  1408. { username: 'pendingemail', email: 'pendingemail@example.com', password: 'password123', status: 'pending_email' },
  1409. { username: 'pendingreview', email: 'pendingreview@example.com', password: 'password123', status: 'pending_review' },
  1410. { username: 'disableduser', email: 'disableduser@example.com', password: 'password123', status: 'disabled' },
  1411. { username: 'activeuser', email: 'activeuser@example.com', password: 'password123', status: 'active' }
  1412. ]);
  1413. await assertLoginDeniedByStatus(baseUrl, 'pendingemail', '请先验证邮箱。');
  1414. await assertLoginDeniedByStatus(baseUrl, 'pendingreview', '账号正在等待管理员审核。');
  1415. await assertLoginDeniedByStatus(baseUrl, 'disableduser', '账号已被禁用。');
  1416. const active = await loginResponse(baseUrl, 'activeuser', 'password123');
  1417. assert.equal(active.status, 200);
  1418. assert.ok(sessionCookieFrom(active));
  1419. } finally {
  1420. child.kill('SIGTERM');
  1421. await waitForExit(child, 1000);
  1422. }
  1423. });
  1424. test('admin audit log actor filter rejects non-decimal user ids', async () => {
  1425. const { child, baseUrl, dataDir, sessionSecret } = await startTestServer();
  1426. try {
  1427. seedAuditLogs(dataDir, sessionSecret);
  1428. const cookie = await login(baseUrl, 'admin', 'password123');
  1429. assert.deepEqual(
  1430. await auditLogActions(baseUrl, cookie, 'actorUserId=1'),
  1431. ['audit.actor-one']
  1432. );
  1433. assert.deepEqual(
  1434. await auditLogActions(baseUrl, cookie, 'actorUserId=1e2'),
  1435. ['audit.actor-one-hundred', 'audit.actor-one']
  1436. );
  1437. } finally {
  1438. child.kill('SIGTERM');
  1439. await waitForExit(child, 1000);
  1440. }
  1441. });
  1442. test('admin audit log date filter ignores invalid dates', async () => {
  1443. const { child, baseUrl, dataDir, sessionSecret } = await startTestServer();
  1444. try {
  1445. seedAuditLogs(dataDir, sessionSecret);
  1446. const cookie = await login(baseUrl, 'admin', 'password123');
  1447. assert.deepEqual(await auditLogActions(baseUrl, cookie, 'from=2999-01-01T00%3A00%3A00.000Z'), []);
  1448. assert.deepEqual(
  1449. await auditLogActions(baseUrl, cookie, 'from=2026-02-31'),
  1450. ['audit.actor-one-hundred', 'audit.actor-one']
  1451. );
  1452. } finally {
  1453. child.kill('SIGTERM');
  1454. await waitForExit(child, 1000);
  1455. }
  1456. });
  1457. async function startTestServer() {
  1458. const port = await freePort();
  1459. const dataDir = mkdtempSync(path.join(tmpdir(), 'mailhub-server-test-'));
  1460. const sessionSecret = 'test-session-secret';
  1461. const child = spawn(process.execPath, ['src/server.js'], {
  1462. cwd: process.cwd(),
  1463. env: {
  1464. ...process.env,
  1465. PORT: String(port),
  1466. DATA_DIR: dataDir,
  1467. ADMIN_PASSWORD: 'password123',
  1468. SESSION_SECRET: sessionSecret,
  1469. DNS_AUTO_CHECK_ENABLED: 'false',
  1470. SUBMISSION_ENABLED: 'false',
  1471. IMAP_ENABLED: 'false',
  1472. POP3_ENABLED: 'false'
  1473. },
  1474. stdio: ['ignore', 'pipe', 'pipe']
  1475. });
  1476. await waitForOutput(child, 'MailHub listening');
  1477. return { child, baseUrl: `http://127.0.0.1:${port}`, dataDir, sessionSecret };
  1478. }
  1479. async function login(baseUrl, username, password) {
  1480. const response = await loginResponse(baseUrl, username, password);
  1481. assert.equal(response.status, 200);
  1482. const cookie = sessionCookieFrom(response);
  1483. assert.ok(cookie);
  1484. return cookie;
  1485. }
  1486. function loginResponse(baseUrl, username, password) {
  1487. return fetch(`${baseUrl}/api/login`, {
  1488. method: 'POST',
  1489. headers: { 'Content-Type': 'application/json' },
  1490. body: JSON.stringify({ username, password })
  1491. });
  1492. }
  1493. async function assertLoginDeniedByStatus(baseUrl, username, message) {
  1494. const wrongPassword = await loginResponse(baseUrl, username, 'wrong-password');
  1495. assert.equal(wrongPassword.status, 401);
  1496. assert.equal((await wrongPassword.json()).error, '账号或密码不正确。');
  1497. assert.equal(sessionCookieFrom(wrongPassword), '');
  1498. const correctPassword = await loginResponse(baseUrl, username, 'password123');
  1499. assert.equal(correctPassword.status, 403);
  1500. assert.equal((await correctPassword.json()).error, message);
  1501. assert.equal(sessionCookieFrom(correctPassword), '');
  1502. }
  1503. function sessionCookieFrom(response) {
  1504. return response.headers.get('set-cookie')?.split(';')[0] || '';
  1505. }
  1506. function seedUsers(dataDir, sessionSecret, users) {
  1507. const script = `
  1508. import { initDatabase, createUser } from './src/db.js';
  1509. initDatabase(process.env.DATA_DIR, process.env.SESSION_SECRET);
  1510. for (const user of JSON.parse(process.env.SEED_USERS)) {
  1511. createUser(user);
  1512. }
  1513. `;
  1514. const result = spawnSync(process.execPath, ['--input-type=module', '-e', script], {
  1515. cwd: process.cwd(),
  1516. env: {
  1517. ...process.env,
  1518. DATA_DIR: dataDir,
  1519. SESSION_SECRET: sessionSecret,
  1520. SEED_USERS: JSON.stringify(users)
  1521. },
  1522. encoding: 'utf8'
  1523. });
  1524. assert.equal(result.status, 0, result.stderr || result.stdout);
  1525. }
  1526. function seedInboundMessage(dataDir, sessionSecret, address) {
  1527. const script = `
  1528. import {
  1529. createInboundMessage,
  1530. getInboundMailboxByAddress,
  1531. initDatabase
  1532. } from './src/db.js';
  1533. initDatabase(process.env.DATA_DIR, process.env.SESSION_SECRET);
  1534. const mailbox = getInboundMailboxByAddress(process.env.INBOUND_ADDRESS);
  1535. const message = createInboundMessage(mailbox, {
  1536. sender: 'alice@example.net',
  1537. recipients: [process.env.INBOUND_ADDRESS],
  1538. subject: 'Inbound API message',
  1539. messageId: '<inbound-api@example.net>',
  1540. rawMessage: [
  1541. 'From: Alice <alice@example.net>',
  1542. 'To: Support <' + process.env.INBOUND_ADDRESS + '>',
  1543. 'Subject: Inbound API message',
  1544. '',
  1545. 'Hello from inbound API.'
  1546. ].join('\\r\\n'),
  1547. textBody: 'Hello from inbound API.'
  1548. });
  1549. console.log(String(message.id));
  1550. `;
  1551. const result = spawnSync(process.execPath, ['--input-type=module', '-e', script], {
  1552. cwd: process.cwd(),
  1553. env: {
  1554. ...process.env,
  1555. DATA_DIR: dataDir,
  1556. SESSION_SECRET: sessionSecret,
  1557. INBOUND_ADDRESS: address
  1558. },
  1559. encoding: 'utf8'
  1560. });
  1561. assert.equal(result.status, 0, result.stderr || result.stdout);
  1562. return Number(result.stdout.trim());
  1563. }
  1564. function seedTransferResources(dataDir, sessionSecret) {
  1565. const script = `
  1566. import {
  1567. initDatabase,
  1568. createApiToken,
  1569. createDomain,
  1570. createUser,
  1571. saveDnsCredential
  1572. } from './src/db.js';
  1573. initDatabase(process.env.DATA_DIR, process.env.SESSION_SECRET);
  1574. const alice = createUser({ username: 'alice', email: 'alice@example.com', password: 'password123', status: 'active' });
  1575. const bob = createUser({ username: 'bob', email: 'bob@example.com', password: 'password123', status: 'active' });
  1576. const credential = saveDnsCredential(alice.id, {
  1577. name: 'Alice DNS',
  1578. provider: 'cloudflare',
  1579. zoneName: 'alice.example',
  1580. credentials: { apiToken: 'secret-token' }
  1581. });
  1582. const standaloneCredential = saveDnsCredential(alice.id, {
  1583. name: 'Standalone DNS',
  1584. provider: 'cloudflare',
  1585. zoneName: 'standalone.example',
  1586. credentials: { apiToken: 'standalone-secret-token' }
  1587. });
  1588. const domain = createDomain(alice.id, {
  1589. dnsCredentialId: credential.id,
  1590. domain: 'alice.example',
  1591. selector: 'mh202607',
  1592. verificationToken: 'token',
  1593. dkimPublic: 'public',
  1594. dkimPrivate: 'private',
  1595. senderHost: 'mail.alice.example',
  1596. sendingIp: '127.0.0.1',
  1597. spfExtra: '',
  1598. dmarcPolicy: 'none',
  1599. dmarcRua: ''
  1600. });
  1601. const apiToken = createApiToken(alice.id, 'primary');
  1602. console.log(JSON.stringify({
  1603. aliceId: alice.id,
  1604. bobId: bob.id,
  1605. domainId: domain.id,
  1606. credentialId: credential.id,
  1607. standaloneCredentialId: standaloneCredential.id,
  1608. apiTokenId: apiToken.id
  1609. }));
  1610. `;
  1611. const result = spawnSync(process.execPath, ['--input-type=module', '-e', script], {
  1612. cwd: process.cwd(),
  1613. env: {
  1614. ...process.env,
  1615. DATA_DIR: dataDir,
  1616. SESSION_SECRET: sessionSecret
  1617. },
  1618. encoding: 'utf8'
  1619. });
  1620. assert.equal(result.status, 0, result.stderr || result.stdout);
  1621. return JSON.parse(result.stdout);
  1622. }
  1623. function seedMergeResources(dataDir, sessionSecret) {
  1624. const script = `
  1625. import {
  1626. initDatabase,
  1627. createApiToken,
  1628. createDomain,
  1629. createUser,
  1630. logSendEvent,
  1631. saveDnsCredential
  1632. } from './src/db.js';
  1633. initDatabase(process.env.DATA_DIR, process.env.SESSION_SECRET);
  1634. const source = createUser({ username: 'mergesource', email: 'mergesource@example.com', password: 'password123', status: 'active' });
  1635. const target = createUser({ username: 'mergetarget', email: 'mergetarget@example.com', password: 'password123', status: 'active' });
  1636. const credential = saveDnsCredential(source.id, {
  1637. name: 'Merge DNS',
  1638. provider: 'cloudflare',
  1639. zoneName: 'merge.example',
  1640. credentials: { apiToken: 'merge-secret-token' }
  1641. });
  1642. const domain = createDomain(source.id, {
  1643. dnsCredentialId: credential.id,
  1644. domain: 'merge.example',
  1645. selector: 'mh202607',
  1646. verificationToken: 'token',
  1647. dkimPublic: 'public',
  1648. dkimPrivate: 'private',
  1649. senderHost: 'mail.merge.example',
  1650. sendingIp: '127.0.0.1',
  1651. spfExtra: '',
  1652. dmarcPolicy: 'none',
  1653. dmarcRua: ''
  1654. });
  1655. createApiToken(source.id, 'primary');
  1656. logSendEvent({
  1657. userId: source.id,
  1658. domainId: domain.id,
  1659. sender: 'noreply@merge.example',
  1660. recipients: ['a@example.com'],
  1661. subject: 'Queued',
  1662. status: 'queued'
  1663. });
  1664. console.log(JSON.stringify({ sourceId: source.id, targetId: target.id }));
  1665. `;
  1666. const result = spawnSync(process.execPath, ['--input-type=module', '-e', script], {
  1667. cwd: process.cwd(),
  1668. env: {
  1669. ...process.env,
  1670. DATA_DIR: dataDir,
  1671. SESSION_SECRET: sessionSecret
  1672. },
  1673. encoding: 'utf8'
  1674. });
  1675. assert.equal(result.status, 0, result.stderr || result.stdout);
  1676. return JSON.parse(result.stdout);
  1677. }
  1678. function createPendingEmailUserWithVerificationToken(dataDir, sessionSecret, user) {
  1679. const script = `
  1680. import { initDatabase, createUser, createAccountToken } from './src/db.js';
  1681. initDatabase(process.env.DATA_DIR, process.env.SESSION_SECRET);
  1682. const user = createUser(JSON.parse(process.env.SEED_USER));
  1683. const token = createAccountToken(user.id, 'email_verification', { ttlMinutes: 24 * 60 });
  1684. console.log(JSON.stringify({ user, token: token.token }));
  1685. `;
  1686. const result = spawnSync(process.execPath, ['--input-type=module', '-e', script], {
  1687. cwd: process.cwd(),
  1688. env: {
  1689. ...process.env,
  1690. DATA_DIR: dataDir,
  1691. SESSION_SECRET: sessionSecret,
  1692. SEED_USER: JSON.stringify(user)
  1693. },
  1694. encoding: 'utf8'
  1695. });
  1696. assert.equal(result.status, 0, result.stderr || result.stdout);
  1697. return JSON.parse(result.stdout);
  1698. }
  1699. function createPasswordResetToken(dataDir, sessionSecret, username) {
  1700. const script = `
  1701. import { initDatabase, getUserByLogin, createAccountToken } from './src/db.js';
  1702. initDatabase(process.env.DATA_DIR, process.env.SESSION_SECRET);
  1703. const user = getUserByLogin(process.env.TOKEN_USERNAME);
  1704. const token = createAccountToken(user.id, 'password_reset', { ttlMinutes: 60 });
  1705. console.log(token.token);
  1706. `;
  1707. const result = spawnSync(process.execPath, ['--input-type=module', '-e', script], {
  1708. cwd: process.cwd(),
  1709. env: {
  1710. ...process.env,
  1711. DATA_DIR: dataDir,
  1712. SESSION_SECRET: sessionSecret,
  1713. TOKEN_USERNAME: username
  1714. },
  1715. encoding: 'utf8'
  1716. });
  1717. assert.equal(result.status, 0, result.stderr || result.stdout);
  1718. return result.stdout.trim();
  1719. }
  1720. function countAccountTokensForUser(dataDir, sessionSecret, username, purpose) {
  1721. return countAccountTokens(dataDir, sessionSecret, username, purpose, false);
  1722. }
  1723. function countUnusedAccountTokensForUser(dataDir, sessionSecret, username, purpose) {
  1724. return countAccountTokens(dataDir, sessionSecret, username, purpose, true);
  1725. }
  1726. function countAccountTokens(dataDir, sessionSecret, username, purpose, unusedOnly) {
  1727. const script = `
  1728. import path from 'node:path';
  1729. import { DatabaseSync } from 'node:sqlite';
  1730. import { initDatabase, getUserByLogin } from './src/db.js';
  1731. initDatabase(process.env.DATA_DIR, process.env.SESSION_SECRET);
  1732. const user = getUserByLogin(process.env.TOKEN_USERNAME);
  1733. const database = new DatabaseSync(path.join(process.env.DATA_DIR, 'mailhub.sqlite'));
  1734. database.exec('PRAGMA journal_mode = WAL; PRAGMA foreign_keys = ON;');
  1735. const unusedFilter = process.env.TOKEN_UNUSED_ONLY === 'true' ? ' AND used_at IS NULL' : '';
  1736. const row = user
  1737. ? database
  1738. .prepare('SELECT COUNT(*) AS count FROM account_tokens WHERE user_id = ? AND purpose = ?' + unusedFilter)
  1739. .get(user.id, process.env.TOKEN_PURPOSE)
  1740. : { count: 0 };
  1741. console.log(String(row.count));
  1742. `;
  1743. const result = spawnSync(process.execPath, ['--input-type=module', '-e', script], {
  1744. cwd: process.cwd(),
  1745. env: {
  1746. ...process.env,
  1747. DATA_DIR: dataDir,
  1748. SESSION_SECRET: sessionSecret,
  1749. TOKEN_USERNAME: username,
  1750. TOKEN_PURPOSE: purpose,
  1751. TOKEN_UNUSED_ONLY: String(unusedOnly)
  1752. },
  1753. encoding: 'utf8'
  1754. });
  1755. assert.equal(result.status, 0, result.stderr || result.stdout);
  1756. return Number(result.stdout.trim());
  1757. }
  1758. function seedAuditLogs(dataDir, sessionSecret) {
  1759. const script = `
  1760. import path from 'node:path';
  1761. import { DatabaseSync } from 'node:sqlite';
  1762. import { initDatabase, logAudit } from './src/db.js';
  1763. initDatabase(process.env.DATA_DIR, process.env.SESSION_SECRET);
  1764. const actorOneId = logAudit({
  1765. actorUserId: 1,
  1766. action: 'audit.actor-one',
  1767. targetType: 'system',
  1768. summary: { label: 'actor-one' }
  1769. });
  1770. const actorOneHundredId = logAudit({
  1771. actorUserId: 100,
  1772. action: 'audit.actor-one-hundred',
  1773. targetType: 'system',
  1774. summary: { label: 'actor-one-hundred' }
  1775. });
  1776. const db = new DatabaseSync(path.join(process.env.DATA_DIR, 'mailhub.sqlite'));
  1777. db.exec('PRAGMA journal_mode = WAL; PRAGMA foreign_keys = ON;');
  1778. const update = db.prepare('UPDATE audit_logs SET created_at = ? WHERE id = ?');
  1779. update.run('2026-02-01T00:00:00.000Z', actorOneId);
  1780. update.run('2026-02-02T00:00:00.000Z', actorOneHundredId);
  1781. `;
  1782. const result = spawnSync(process.execPath, ['--input-type=module', '-e', script], {
  1783. cwd: process.cwd(),
  1784. env: {
  1785. ...process.env,
  1786. DATA_DIR: dataDir,
  1787. SESSION_SECRET: sessionSecret
  1788. },
  1789. encoding: 'utf8'
  1790. });
  1791. assert.equal(result.status, 0, result.stderr || result.stdout);
  1792. }
  1793. async function auditLogActions(baseUrl, cookie, query) {
  1794. const response = await fetch(`${baseUrl}/api/admin/audit-logs?${query}`, {
  1795. headers: { Cookie: cookie }
  1796. });
  1797. assert.equal(response.status, 200);
  1798. const body = await response.json();
  1799. return body.logs.map((log) => log.action);
  1800. }
  1801. async function saveSystemEmailSettings(baseUrl, cookie, smtpPort) {
  1802. const response = await fetch(`${baseUrl}/api/admin/system-email`, {
  1803. method: 'PATCH',
  1804. headers: {
  1805. 'Content-Type': 'application/json',
  1806. Cookie: cookie
  1807. },
  1808. body: JSON.stringify({
  1809. host: '127.0.0.1',
  1810. port: smtpPort,
  1811. secure: false,
  1812. username: 'mailer@example.com',
  1813. password: 'smtp-password-123',
  1814. helo: 'mail.example.com',
  1815. fromEmail: 'notify@example.com',
  1816. fromName: 'MailHub Notify',
  1817. testRecipient: 'admin@example.com'
  1818. })
  1819. });
  1820. assert.equal(response.status, 200);
  1821. }
  1822. async function createSendingDomain(baseUrl, cookie, data = {}) {
  1823. const domain = data.domain || 'send.example';
  1824. const response = await fetch(`${baseUrl}/api/domains`, {
  1825. method: 'POST',
  1826. headers: {
  1827. 'Content-Type': 'application/json',
  1828. Cookie: cookie
  1829. },
  1830. body: JSON.stringify({
  1831. domain,
  1832. selector: data.selector || 'mh',
  1833. senderHost: data.senderHost || `mail.${domain}`,
  1834. sendingIp: data.sendingIp || '127.0.0.1',
  1835. smtpRelayId: data.smtpRelayId
  1836. })
  1837. });
  1838. assert.equal(response.status, 201);
  1839. return (await response.json()).domain;
  1840. }
  1841. async function createSmtpRelay(baseUrl, cookie, data = {}) {
  1842. const response = await fetch(`${baseUrl}/api/smtp-relays`, {
  1843. method: 'POST',
  1844. headers: {
  1845. 'Content-Type': 'application/json',
  1846. Cookie: cookie
  1847. },
  1848. body: JSON.stringify({
  1849. name: data.name || 'Relay',
  1850. host: data.host || '127.0.0.1',
  1851. port: data.port,
  1852. secure: data.secure || false,
  1853. username: data.username || '',
  1854. password: data.password || '',
  1855. helo: data.helo || '',
  1856. isDefault: data.isDefault || false
  1857. })
  1858. });
  1859. assert.equal(response.status, 201);
  1860. return (await response.json()).relay;
  1861. }
  1862. async function createSmtpCredential(baseUrl, cookie, data = {}) {
  1863. const response = await fetch(`${baseUrl}/api/smtp-credentials`, {
  1864. method: 'POST',
  1865. headers: {
  1866. 'Content-Type': 'application/json',
  1867. Cookie: cookie
  1868. },
  1869. body: JSON.stringify(data)
  1870. });
  1871. assert.equal(response.status, 201);
  1872. return (await response.json()).credential;
  1873. }
  1874. async function sendApiMail(baseUrl, cookie, data) {
  1875. const response = await fetch(`${baseUrl}/api/send`, {
  1876. method: 'POST',
  1877. headers: {
  1878. 'Content-Type': 'application/json',
  1879. Cookie: cookie
  1880. },
  1881. body: JSON.stringify({
  1882. from: data.from,
  1883. to: data.to,
  1884. subject: data.subject,
  1885. text: data.text || 'hello',
  1886. smtpRelayId: data.smtpRelayId
  1887. })
  1888. });
  1889. assert.equal(response.status, 202);
  1890. return response.json();
  1891. }
  1892. function assertRelayAuth(relayServer, username, password) {
  1893. const authCommand = relayServer.commands.find((command) => command.startsWith('AUTH PLAIN '));
  1894. assert.ok(authCommand);
  1895. assert.equal(Buffer.from(authCommand.replace('AUTH PLAIN ', ''), 'base64').toString('utf8'), `\0${username}\0${password}`);
  1896. }
  1897. function decodeHtmlPart(rawMessage) {
  1898. const match = rawMessage.match(/Content-Type: text\/html[^]*?\n\n([A-Za-z0-9+/=\n]+?)(?:\n--|$)/i);
  1899. assert.ok(match, 'expected an HTML MIME part');
  1900. return Buffer.from(match[1].replace(/\s+/g, ''), 'base64').toString('utf8');
  1901. }
  1902. function escapeRegExp(value) {
  1903. return String(value).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
  1904. }
  1905. function startFakeSmtpServer({ responseDelayMs = 0 } = {}) {
  1906. const commands = [];
  1907. const messages = [];
  1908. const server = net.createServer((socket) => {
  1909. socket.setEncoding('utf8');
  1910. writeSmtpResponse(socket, '220 relay.test ESMTP ready', responseDelayMs);
  1911. let buffer = '';
  1912. let dataMode = false;
  1913. let messageLines = [];
  1914. socket.on('data', (chunk) => {
  1915. buffer += chunk;
  1916. let index;
  1917. while ((index = buffer.indexOf('\n')) !== -1) {
  1918. const line = buffer.slice(0, index).replace(/\r$/, '');
  1919. buffer = buffer.slice(index + 1);
  1920. if (dataMode) {
  1921. if (line === '.') {
  1922. dataMode = false;
  1923. messages.push(messageLines.join('\n'));
  1924. messageLines = [];
  1925. writeSmtpResponse(socket, '250 2.0.0 queued as SYS123', responseDelayMs);
  1926. } else {
  1927. messageLines.push(line);
  1928. }
  1929. continue;
  1930. }
  1931. commands.push(line);
  1932. if (line.startsWith('EHLO')) {
  1933. writeSmtpResponse(socket, '250-relay.test\r\n250 AUTH PLAIN', responseDelayMs);
  1934. } else if (line.startsWith('AUTH PLAIN')) {
  1935. writeSmtpResponse(socket, '235 2.7.0 authentication successful', responseDelayMs);
  1936. } else if (line.startsWith('MAIL FROM')) {
  1937. writeSmtpResponse(socket, '250 2.1.0 sender ok', responseDelayMs);
  1938. } else if (line.startsWith('RCPT TO')) {
  1939. writeSmtpResponse(socket, '250 2.1.5 recipient ok', responseDelayMs);
  1940. } else if (line === 'DATA') {
  1941. dataMode = true;
  1942. writeSmtpResponse(socket, '354 end with dot', responseDelayMs);
  1943. } else if (line === 'QUIT') {
  1944. writeSmtpResponse(socket, '221 bye', responseDelayMs);
  1945. socket.end();
  1946. }
  1947. }
  1948. });
  1949. });
  1950. return new Promise((resolve, reject) => {
  1951. server.once('error', reject);
  1952. server.listen(0, '127.0.0.1', () => {
  1953. server.off('error', reject);
  1954. resolve({
  1955. port: server.address().port,
  1956. commands,
  1957. messages,
  1958. close: () => new Promise((closeResolve) => server.close(closeResolve))
  1959. });
  1960. });
  1961. });
  1962. }
  1963. function writeSmtpResponse(socket, response, delayMs) {
  1964. const write = () => socket.write(`${response}\r\n`);
  1965. if (delayMs > 0) setTimeout(write, delayMs);
  1966. else write();
  1967. }
  1968. async function waitForCondition(predicate, { timeoutMs = 7000, intervalMs = 50 } = {}) {
  1969. const startedAt = Date.now();
  1970. while (Date.now() - startedAt < timeoutMs) {
  1971. if (predicate()) return;
  1972. await new Promise((resolve) => setTimeout(resolve, intervalMs));
  1973. }
  1974. assert.fail('Timed out waiting for condition.');
  1975. }
  1976. function freePort() {
  1977. return new Promise((resolve, reject) => {
  1978. const server = net.createServer();
  1979. server.listen(0, '127.0.0.1', () => {
  1980. const address = server.address();
  1981. server.close(() => {
  1982. if (address && typeof address === 'object') resolve(address.port);
  1983. else reject(new Error('Unable to allocate a test port.'));
  1984. });
  1985. });
  1986. });
  1987. }
  1988. function waitForOutput(child, text) {
  1989. return new Promise((resolve, reject) => {
  1990. const timeout = setTimeout(() => reject(new Error(`Timed out waiting for ${text}`)), 5000);
  1991. const chunks = [];
  1992. const onData = (chunk) => {
  1993. chunks.push(String(chunk));
  1994. if (chunks.join('').includes(text)) {
  1995. clearTimeout(timeout);
  1996. child.stdout.off('data', onData);
  1997. child.stderr.off('data', onData);
  1998. resolve();
  1999. }
  2000. };
  2001. child.stdout.on('data', onData);
  2002. child.stderr.on('data', onData);
  2003. child.once('exit', (code) => {
  2004. clearTimeout(timeout);
  2005. reject(new Error(`Server exited early with code ${code}: ${chunks.join('')}`));
  2006. });
  2007. });
  2008. }
  2009. function waitForExit(child, timeoutMs) {
  2010. if (child.exitCode !== null) return Promise.resolve(true);
  2011. return new Promise((resolve) => {
  2012. const timeout = setTimeout(() => {
  2013. child.off('exit', onExit);
  2014. resolve(false);
  2015. }, timeoutMs);
  2016. const onExit = () => {
  2017. clearTimeout(timeout);
  2018. resolve(true);
  2019. };
  2020. child.once('exit', onExit);
  2021. });
  2022. }