frontend-auth-model.test.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. import assert from 'node:assert/strict';
  2. import { test } from 'node:test';
  3. import { authModeFromLocation, nextAuthSuccessState, safeInternalPath } from '../src/frontend/auth/auth-model.js';
  4. test('registration success returns to login without navigating to the protected app', () => {
  5. assert.deepEqual(
  6. nextAuthSuccessState('/api/register', {
  7. user: { status: 'pending_email' },
  8. message: '注册成功,请先验证邮箱,验证后等待管理员审核。'
  9. }),
  10. {
  11. mode: 'login',
  12. path: '/login',
  13. message: '注册成功,请先验证邮箱,验证后等待管理员审核。',
  14. redirectTo: ''
  15. }
  16. );
  17. });
  18. test('login success still redirects to the protected app', () => {
  19. assert.deepEqual(
  20. nextAuthSuccessState('/api/login', {
  21. user: { status: 'active' }
  22. }),
  23. {
  24. mode: 'login',
  25. path: '/login',
  26. message: '',
  27. redirectTo: '/overview'
  28. }
  29. );
  30. });
  31. test('login success returns to a safe internal deep link', () => {
  32. assert.equal(
  33. nextAuthSuccessState('/api/login', {}, '/activity?status=failed#event-12').redirectTo,
  34. '/activity?status=failed#event-12'
  35. );
  36. });
  37. test('rejects external and ambiguous auth next destinations', () => {
  38. for (const value of [
  39. 'https://example.com',
  40. '//example.com/path',
  41. '/\\example.com',
  42. '/login',
  43. '/register?next=/overview',
  44. '/api/events',
  45. 'javascript:alert(1)',
  46. '/overview\nLocation:https://example.com'
  47. ]) {
  48. assert.equal(safeInternalPath(value, '/overview'), '/overview');
  49. }
  50. assert.equal(safeInternalPath('/domains/12/dns?tab=records'), '/domains/12/dns?tab=records');
  51. });
  52. test('detects account recovery modes from auth routes', () => {
  53. assert.deepEqual(authModeFromLocation('/forgot-password'), { mode: 'forgot', token: '' });
  54. assert.deepEqual(authModeFromLocation('/resend-verification'), { mode: 'resend', token: '' });
  55. assert.deepEqual(authModeFromLocation('/reset-password', '?token=abc123'), { mode: 'reset', token: 'abc123' });
  56. assert.deepEqual(authModeFromLocation('/login'), { mode: 'login', token: '' });
  57. assert.deepEqual(authModeFromLocation('/register'), { mode: 'register', token: '' });
  58. });