@kevairy/template 0.1.3 → 0.1.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/template/.env +2 -2
- package/template/.env.production +6 -0
- package/template/src/adapters/auth/index.ts +1 -1
- package/template/src/adapters/auth/types.ts +6 -1
- package/template/src/api/auth.ts +3 -2
- package/template/src/components/core/layouts/art-guide/index.vue +9 -1
- package/template/src/components/core/layouts/art-page-content/index.vue +8 -1
- package/template/src/config/index.ts +4 -0
- package/template/src/directives/core/access.ts +125 -0
- package/template/src/directives/core/auth.ts +7 -62
- package/template/src/directives/core/roles.ts +5 -83
- package/template/src/env.d.ts +1 -0
- package/template/src/hooks/core/useAuth.ts +2 -74
- package/template/src/hooks/core/useGuide.ts +6 -0
- package/template/src/hooks/core/usePermission.ts +41 -0
- package/template/src/hooks/index.ts +1 -0
- package/template/src/locales/langs/en.json +11 -1
- package/template/src/locales/langs/zh.json +11 -1
- package/template/src/main.ts +18 -10
- package/template/src/router/core/IframeRouteManager.ts +4 -2
- package/template/src/router/core/MenuProcessor.ts +5 -40
- package/template/src/router/core/RoutePermissionValidator.ts +6 -149
- package/template/src/router/core/access.ts +79 -0
- package/template/src/router/guards/afterEach.ts +6 -10
- package/template/src/router/guards/beforeEach.ts +143 -100
- package/template/src/router/guards/error.ts +42 -0
- package/template/src/router/index.ts +2 -0
- package/template/src/router/modules/examples.ts +4 -3
- package/template/src/router/routes/staticRoutes.ts +5 -3
- package/template/src/services/auth.ts +32 -10
- package/template/src/services/permission.ts +21 -0
- package/template/src/store/modules/menu.ts +28 -8
- package/template/src/store/modules/user.ts +72 -35
- package/template/src/store/modules/worktab.ts +1 -1
- package/template/src/types/api/api.d.ts +4 -1
- package/template/src/types/config/index.ts +5 -0
- package/template/src/types/directive/directive.d.ts +1 -0
- package/template/src/types/router/index.ts +6 -0
- package/template/src/utils/http/contract.ts +51 -19
- package/template/src/utils/http/error.ts +73 -26
- package/template/src/utils/http/index.ts +160 -167
- package/template/src/utils/http/request-manager.ts +124 -0
- package/template/src/utils/http/status.ts +1 -0
- package/template/src/utils/permission/index.ts +66 -0
- package/template/src/utils/session.ts +24 -0
- package/template/src/utils/storage/storage-config.ts +15 -0
- package/template/src/utils/storage/storage.ts +5 -3
- package/template/src/utils/sys/diagnostics.ts +180 -0
- package/template/src/utils/sys/error-handle.ts +56 -126
- package/template/src/utils/sys/recovery.ts +31 -0
- package/template/src/views/examples/permissions/index.vue +69 -13
- package/template/src/views/exception/403/index.vue +33 -0
- package/template/src/views/exception/500/index.vue +52 -10
- package/template/tests/e2e/permissions.spec.ts +53 -0
- package/template/tests/e2e/session-recovery.spec.ts +49 -0
- package/template/tests/unit/diagnostics/diagnostics.spec.ts +132 -0
- package/template/tests/unit/diagnostics/router.spec.ts +84 -0
- package/template/tests/unit/http/auth-lifecycle.spec.ts +203 -0
- package/template/tests/unit/http/contract.spec.ts +46 -0
- package/template/tests/unit/http/request.spec.ts +487 -0
- package/template/tests/unit/permissions/guard.spec.ts +261 -0
- package/template/tests/unit/permissions/guide.spec.ts +30 -0
- package/template/tests/unit/permissions/rules.spec.ts +106 -0
- package/template/tests/unit/permissions/state-and-directives.spec.ts +176 -0
- package/template/tests/unit/router/examples.spec.ts +5 -1
- package/template/vite.config.ts +5 -2
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { expect, test, type Page } from '@playwright/test'
|
|
2
|
+
import { skipInitialGuide } from './helpers/guide'
|
|
3
|
+
|
|
4
|
+
async function selectProfile(page: Page, name: string) {
|
|
5
|
+
const select = page.getByRole('combobox', { name: '演示身份' })
|
|
6
|
+
await select.focus()
|
|
7
|
+
await select.press('ArrowDown')
|
|
8
|
+
await page.getByRole('option', { name, exact: true }).click()
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
test('keeps hook and directive permissions consistent through grant, revoke, restore and protected detail navigation', async ({
|
|
12
|
+
page
|
|
13
|
+
}) => {
|
|
14
|
+
await page.goto('/#/examples/permissions')
|
|
15
|
+
await page.getByRole('button', { name: '进入系统(Mock)' }).click()
|
|
16
|
+
await skipInitialGuide(page)
|
|
17
|
+
const create = page.getByRole('button', { name: '新增资源', exact: true })
|
|
18
|
+
const edit = page.getByRole('button', { name: '编辑资源', exact: true })
|
|
19
|
+
const exportButton = page.getByRole('button', { name: '导出数据', exact: true })
|
|
20
|
+
const approve = page.getByRole('button', { name: '审核资源', exact: true })
|
|
21
|
+
await expect(approve).toBeEnabled()
|
|
22
|
+
await selectProfile(page, '普通成员')
|
|
23
|
+
await expect(create).toBeVisible()
|
|
24
|
+
await expect(edit).toBeVisible()
|
|
25
|
+
await expect(exportButton).toBeVisible()
|
|
26
|
+
await expect(approve).toBeDisabled()
|
|
27
|
+
await selectProfile(page, '无操作权限')
|
|
28
|
+
await expect(create).toBeHidden()
|
|
29
|
+
await expect(edit).toBeHidden()
|
|
30
|
+
await expect(exportButton).toBeHidden()
|
|
31
|
+
await expect(approve).toBeDisabled()
|
|
32
|
+
await expect(page.getByText('管理员区域', { exact: true })).toBeHidden()
|
|
33
|
+
await selectProfile(page, '模板管理员')
|
|
34
|
+
await expect(create).toBeVisible()
|
|
35
|
+
await expect(exportButton).toBeVisible()
|
|
36
|
+
await expect(approve).toBeEnabled()
|
|
37
|
+
await expect(page.getByText('管理员区域', { exact: true })).toBeVisible()
|
|
38
|
+
await selectProfile(page, '无操作权限')
|
|
39
|
+
await page.evaluate(() => {
|
|
40
|
+
location.hash = '/examples/navigation/detail/42'
|
|
41
|
+
})
|
|
42
|
+
await expect(page).toHaveURL(/#\/403$/)
|
|
43
|
+
await page.evaluate(() => {
|
|
44
|
+
location.hash = '/examples/permissions'
|
|
45
|
+
})
|
|
46
|
+
await expect(page.getByRole('heading', { name: '权限演练场' })).toBeVisible()
|
|
47
|
+
await selectProfile(page, '普通成员')
|
|
48
|
+
await page.evaluate(() => {
|
|
49
|
+
location.hash = '/examples/navigation/detail/42'
|
|
50
|
+
})
|
|
51
|
+
await expect(page).toHaveURL(/#\/examples\/navigation\/detail\/42$/)
|
|
52
|
+
await expect(page.getByText('42', { exact: true }).first()).toBeVisible()
|
|
53
|
+
})
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { expect, test } from '@playwright/test'
|
|
2
|
+
import { skipInitialGuide } from './helpers/guide'
|
|
3
|
+
|
|
4
|
+
test('discards cached page state on logout and reinitializes the same account', async ({
|
|
5
|
+
page
|
|
6
|
+
}) => {
|
|
7
|
+
await page.goto('/#/examples/search-table')
|
|
8
|
+
await page.getByRole('button', { name: '进入系统(Mock)' }).click()
|
|
9
|
+
await expect(page.getByText('共 68 项')).toBeVisible()
|
|
10
|
+
await skipInitialGuide(page)
|
|
11
|
+
await page.getByPlaceholder('服务名称或编码').fill('SERVICE_001')
|
|
12
|
+
await page.getByRole('button', { name: '查询', exact: true }).click()
|
|
13
|
+
await expect(page.getByText('共 1 项')).toBeVisible()
|
|
14
|
+
await page.locator('.user-menu-avatar').hover()
|
|
15
|
+
await page.getByText('退出登录', { exact: true }).click()
|
|
16
|
+
await page.getByRole('button', { name: '确定', exact: true }).click()
|
|
17
|
+
await expect(page).toHaveURL(/#\/auth\/login/)
|
|
18
|
+
await page.getByRole('button', { name: '进入系统(Mock)' }).click()
|
|
19
|
+
await expect(page).toHaveURL(/#\/examples\/search-table/)
|
|
20
|
+
await expect(page.getByText('共 68 项')).toBeVisible()
|
|
21
|
+
await expect(page.getByPlaceholder('服务名称或编码')).toHaveValue('')
|
|
22
|
+
// 引导完成属于偏好,重新登录不再次启动。
|
|
23
|
+
await expect(page.getByRole('dialog', { name: '欢迎使用 Admin Template' })).toBeHidden()
|
|
24
|
+
})
|
|
25
|
+
|
|
26
|
+
test('offers explicit reload after a failed lazy chunk and recovers the requested page', async ({
|
|
27
|
+
page
|
|
28
|
+
}) => {
|
|
29
|
+
const diagnostics: string[] = []
|
|
30
|
+
page.on('console', (message) => {
|
|
31
|
+
if (message.type() === 'error') diagnostics.push(message.text())
|
|
32
|
+
})
|
|
33
|
+
await page.goto('/#/dashboard/console')
|
|
34
|
+
await page.getByRole('button', { name: '进入系统(Mock)' }).click()
|
|
35
|
+
await expect(page.getByRole('heading', { name: 'Admin Template' })).toBeVisible()
|
|
36
|
+
await skipInitialGuide(page)
|
|
37
|
+
// 登录后才阻断尚未加载的业务资源,恢复页应已随入口可用。
|
|
38
|
+
await page.route('**/assets/*.js', (route) => route.abort('failed'))
|
|
39
|
+
await page.evaluate(() => {
|
|
40
|
+
window.location.hash = '#/examples/search-table'
|
|
41
|
+
})
|
|
42
|
+
await expect(page).toHaveURL(/#\/500/)
|
|
43
|
+
await expect(page.getByRole('button', { name: '刷新并重试' })).toBeVisible()
|
|
44
|
+
expect(diagnostics.some((message) => message.includes('[Diagnostic]'))).toBe(true)
|
|
45
|
+
await page.unroute('**/assets/*.js')
|
|
46
|
+
await page.getByRole('button', { name: '刷新并重试' }).click()
|
|
47
|
+
await expect(page).toHaveURL(/#\/examples\/search-table/)
|
|
48
|
+
await expect(page.getByText('共 68 项')).toBeVisible()
|
|
49
|
+
})
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
|
2
|
+
import { flushPromises } from '@vue/test-utils'
|
|
3
|
+
|
|
4
|
+
beforeEach(() => {
|
|
5
|
+
vi.resetModules()
|
|
6
|
+
vi.spyOn(console, 'error').mockImplementation(() => {})
|
|
7
|
+
vi.spyOn(console, 'warn').mockImplementation(() => {})
|
|
8
|
+
})
|
|
9
|
+
afterEach(() => {
|
|
10
|
+
vi.restoreAllMocks()
|
|
11
|
+
})
|
|
12
|
+
|
|
13
|
+
describe('production diagnostics', () => {
|
|
14
|
+
it('redacts URL queries, credentials and common secrets without collecting payloads', async () => {
|
|
15
|
+
const diagnostics = await import('@/utils/sys/diagnostics')
|
|
16
|
+
diagnostics.setDiagnosticRouteProvider(() => '/account?token=route-secret#private')
|
|
17
|
+
const error = new Error(
|
|
18
|
+
'Failed https://user:pass@example.com/api?token=url-secret Authorization=header-secret Bearer bearer-secret password=password-secret'
|
|
19
|
+
)
|
|
20
|
+
diagnostics.reportDiagnostic('http', error, {
|
|
21
|
+
url: '/api?token=query-secret',
|
|
22
|
+
method: 'GET',
|
|
23
|
+
code: 500,
|
|
24
|
+
...{ data: 'body-secret', headers: 'headers-secret' }
|
|
25
|
+
})
|
|
26
|
+
const [record] = diagnostics.getDiagnosticRecords()
|
|
27
|
+
expect(record.version).toBe('test')
|
|
28
|
+
expect(record.buildId).toBeTruthy()
|
|
29
|
+
const serialized = JSON.stringify(record)
|
|
30
|
+
for (const secret of [
|
|
31
|
+
'user:pass',
|
|
32
|
+
'route-secret',
|
|
33
|
+
'url-secret',
|
|
34
|
+
'header-secret',
|
|
35
|
+
'bearer-secret',
|
|
36
|
+
'password-secret',
|
|
37
|
+
'query-secret',
|
|
38
|
+
'body-secret',
|
|
39
|
+
'headers-secret'
|
|
40
|
+
]) {
|
|
41
|
+
expect(serialized).not.toContain(secret)
|
|
42
|
+
}
|
|
43
|
+
expect(record.context).toEqual({
|
|
44
|
+
url: `${window.location.origin}/api`,
|
|
45
|
+
method: 'GET',
|
|
46
|
+
code: 500
|
|
47
|
+
})
|
|
48
|
+
record.context.method = 'mutated'
|
|
49
|
+
expect(diagnostics.getDiagnosticRecords()[0].context.method).toBe('GET')
|
|
50
|
+
diagnostics.reportDiagnostic('script', new Error('password="multi word secret"'), {
|
|
51
|
+
url: 'data:text/plain;base64,sensitive-body'
|
|
52
|
+
})
|
|
53
|
+
const last = JSON.stringify(diagnostics.getDiagnosticRecords().at(-1))
|
|
54
|
+
expect(last).not.toContain('multi word secret')
|
|
55
|
+
expect(last).not.toContain('sensitive-body')
|
|
56
|
+
})
|
|
57
|
+
|
|
58
|
+
it('ignores cancellations and noise, deduplicates repeats and bounds retained records', async () => {
|
|
59
|
+
const { reportDiagnostic, getDiagnosticRecords } = await import('@/utils/sys/diagnostics')
|
|
60
|
+
reportDiagnostic('promise', new DOMException('Canceled', 'AbortError'))
|
|
61
|
+
reportDiagnostic('http', { kind: 'cancelled' })
|
|
62
|
+
reportDiagnostic('script', 'ResizeObserver loop limit exceeded')
|
|
63
|
+
expect(getDiagnosticRecords()).toEqual([])
|
|
64
|
+
const error = new Error('Repeated failure')
|
|
65
|
+
reportDiagnostic('script', error)
|
|
66
|
+
reportDiagnostic('script', error)
|
|
67
|
+
expect(getDiagnosticRecords()[0].count).toBe(2)
|
|
68
|
+
for (let i = 0; i < 80; i++) reportDiagnostic('script', `Failure ${i}`)
|
|
69
|
+
expect(getDiagnosticRecords()).toHaveLength(50)
|
|
70
|
+
expect(getDiagnosticRecords().at(-1)?.message).toBe('Failure 79')
|
|
71
|
+
})
|
|
72
|
+
|
|
73
|
+
it('limits reporting and isolates both synchronous and asynchronous reporter failures', async () => {
|
|
74
|
+
const { reportDiagnostic, setDiagnosticReporter, getDiagnosticRecords } = await import(
|
|
75
|
+
'@/utils/sys/diagnostics'
|
|
76
|
+
)
|
|
77
|
+
const reporter = vi
|
|
78
|
+
.fn()
|
|
79
|
+
.mockImplementationOnce(() => {
|
|
80
|
+
throw new Error('Sync reporter error')
|
|
81
|
+
})
|
|
82
|
+
.mockRejectedValue(new Error('Async reporter error'))
|
|
83
|
+
setDiagnosticReporter(reporter)
|
|
84
|
+
for (let i = 0; i < 30; i++) {
|
|
85
|
+
reportDiagnostic('script', `Failure ${i}`)
|
|
86
|
+
await flushPromises()
|
|
87
|
+
}
|
|
88
|
+
expect(reporter).toHaveBeenCalledTimes(20)
|
|
89
|
+
expect(getDiagnosticRecords()).toHaveLength(30)
|
|
90
|
+
expect(console.warn).toHaveBeenCalled()
|
|
91
|
+
})
|
|
92
|
+
|
|
93
|
+
it('installs listeners once, preserves browser errors and removes all global listeners', async () => {
|
|
94
|
+
const { setupGlobalErrorHandlers, scriptErrorHandler, vueErrorHandler } = await import(
|
|
95
|
+
'@/utils/sys/error-handle'
|
|
96
|
+
)
|
|
97
|
+
const { getDiagnosticRecords } = await import('@/utils/sys/diagnostics')
|
|
98
|
+
const stop = setupGlobalErrorHandlers()
|
|
99
|
+
expect(setupGlobalErrorHandlers()).toBe(stop)
|
|
100
|
+
try {
|
|
101
|
+
window.dispatchEvent(
|
|
102
|
+
new ErrorEvent('error', {
|
|
103
|
+
message: 'Runtime failure',
|
|
104
|
+
error: new Error('Runtime failure'),
|
|
105
|
+
filename: '/entry.js?secret=1',
|
|
106
|
+
lineno: 8
|
|
107
|
+
})
|
|
108
|
+
)
|
|
109
|
+
const rejection = new Event('unhandledrejection')
|
|
110
|
+
Object.assign(rejection, { reason: new Error('Promise failure') })
|
|
111
|
+
window.dispatchEvent(rejection)
|
|
112
|
+
const image = document.createElement('img')
|
|
113
|
+
image.src = '/image.png?token=secret'
|
|
114
|
+
document.body.appendChild(image)
|
|
115
|
+
image.dispatchEvent(new Event('error'))
|
|
116
|
+
image.remove()
|
|
117
|
+
vueErrorHandler(new Error('Vue failure'), null, 'render function')
|
|
118
|
+
expect(getDiagnosticRecords().map((record) => record.kind)).toEqual([
|
|
119
|
+
'script',
|
|
120
|
+
'promise',
|
|
121
|
+
'resource',
|
|
122
|
+
'vue'
|
|
123
|
+
])
|
|
124
|
+
expect(scriptErrorHandler('Browser fallback')).toBe(false)
|
|
125
|
+
} finally {
|
|
126
|
+
stop()
|
|
127
|
+
}
|
|
128
|
+
const count = getDiagnosticRecords().length
|
|
129
|
+
window.dispatchEvent(new ErrorEvent('error', { message: 'After disposal' }))
|
|
130
|
+
expect(getDiagnosticRecords()).toHaveLength(count)
|
|
131
|
+
})
|
|
132
|
+
})
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
|
2
|
+
import { createMemoryHistory, createRouter } from 'vue-router'
|
|
3
|
+
import { flushPromises } from '@vue/test-utils'
|
|
4
|
+
|
|
5
|
+
vi.mock('@/router/guards/beforeEach', () => ({ closeLoading: vi.fn() }))
|
|
6
|
+
vi.mock('@/utils/http/error', () => ({
|
|
7
|
+
isRequestCanceled: (error: Error) => error.name === 'AbortError'
|
|
8
|
+
}))
|
|
9
|
+
vi.mock('nprogress', () => ({ default: { done: vi.fn() } }))
|
|
10
|
+
beforeEach(() => {
|
|
11
|
+
vi.resetModules()
|
|
12
|
+
vi.spyOn(console, 'error').mockImplementation(() => {})
|
|
13
|
+
})
|
|
14
|
+
afterEach(() => vi.restoreAllMocks())
|
|
15
|
+
|
|
16
|
+
describe('router recovery', () => {
|
|
17
|
+
it('does not navigate away from a new session when an old lazy import fails late', async () => {
|
|
18
|
+
const { setupRouterErrorHandler } = await import('@/router/guards/error')
|
|
19
|
+
const { invalidateSessionRequests } = await import('@/utils/http/request-manager')
|
|
20
|
+
let fail!: (error: Error) => void
|
|
21
|
+
const router = createRouter({
|
|
22
|
+
history: createMemoryHistory(),
|
|
23
|
+
routes: [
|
|
24
|
+
{
|
|
25
|
+
path: '/old',
|
|
26
|
+
component: () =>
|
|
27
|
+
new Promise((_, reject) => {
|
|
28
|
+
fail = reject
|
|
29
|
+
})
|
|
30
|
+
},
|
|
31
|
+
{ path: '/new', component: { render: () => null } },
|
|
32
|
+
{ path: '/500', name: 'Exception500', component: { render: () => null } }
|
|
33
|
+
]
|
|
34
|
+
})
|
|
35
|
+
const stop = setupRouterErrorHandler(router)
|
|
36
|
+
try {
|
|
37
|
+
const old = router.push('/old').catch(() => {})
|
|
38
|
+
await flushPromises()
|
|
39
|
+
invalidateSessionRequests()
|
|
40
|
+
await router.push('/new')
|
|
41
|
+
fail(new Error('Failed to fetch dynamically imported module'))
|
|
42
|
+
await old
|
|
43
|
+
await flushPromises()
|
|
44
|
+
expect(router.currentRoute.value.path).toBe('/new')
|
|
45
|
+
} finally {
|
|
46
|
+
stop()
|
|
47
|
+
}
|
|
48
|
+
})
|
|
49
|
+
|
|
50
|
+
it('captures failed lazy imports and opens the eager recovery page without retry loops', async () => {
|
|
51
|
+
const { setupRouterErrorHandler } = await import('@/router/guards/error')
|
|
52
|
+
const { resourceRecoveryNeeded } = await import('@/utils/sys/recovery')
|
|
53
|
+
const { getDiagnosticRecords } = await import('@/utils/sys/diagnostics')
|
|
54
|
+
const error = new Error(
|
|
55
|
+
'Failed to fetch dynamically imported module: https://example.com/assets/old.js?token=secret'
|
|
56
|
+
)
|
|
57
|
+
const router = createRouter({
|
|
58
|
+
history: createMemoryHistory(),
|
|
59
|
+
routes: [
|
|
60
|
+
{ path: '/broken', component: () => Promise.reject(error) },
|
|
61
|
+
{ path: '/500', name: 'Exception500', component: { render: () => null } }
|
|
62
|
+
]
|
|
63
|
+
})
|
|
64
|
+
const stop = setupRouterErrorHandler(router)
|
|
65
|
+
try {
|
|
66
|
+
await expect(router.push('/broken?token=secret')).rejects.toBe(error)
|
|
67
|
+
await flushPromises()
|
|
68
|
+
expect(router.currentRoute.value.path).toBe('/500')
|
|
69
|
+
expect(resourceRecoveryNeeded.value).toBe(true)
|
|
70
|
+
expect(getDiagnosticRecords()).toHaveLength(1)
|
|
71
|
+
expect(JSON.stringify(getDiagnosticRecords())).not.toContain('secret')
|
|
72
|
+
const preload = new Event('vite:preloadError')
|
|
73
|
+
Object.assign(preload, { payload: error })
|
|
74
|
+
window.dispatchEvent(preload)
|
|
75
|
+
expect(preload.defaultPrevented).toBe(false)
|
|
76
|
+
expect(getDiagnosticRecords().at(-1)?.kind).toBe('resource')
|
|
77
|
+
} finally {
|
|
78
|
+
stop()
|
|
79
|
+
}
|
|
80
|
+
const count = getDiagnosticRecords().length
|
|
81
|
+
window.dispatchEvent(new Event('vite:preloadError'))
|
|
82
|
+
expect(getDiagnosticRecords()).toHaveLength(count)
|
|
83
|
+
})
|
|
84
|
+
})
|
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
|
2
|
+
import { createPinia, setActivePinia } from 'pinia'
|
|
3
|
+
import { useUserStore } from '@/store/modules/user'
|
|
4
|
+
import { signOut } from '@/services/auth'
|
|
5
|
+
import { beginRequest, SIGN_OUT_REQUEST_SCOPE } from '@/utils/http/request-manager'
|
|
6
|
+
import { registerSessionCleanup } from '@/utils/session'
|
|
7
|
+
import { useWorktabStore } from '@/store/modules/worktab'
|
|
8
|
+
import { useSettingStore } from '@/store/modules/setting'
|
|
9
|
+
import { StorageConfig } from '@/utils/storage/storage-config'
|
|
10
|
+
import { IframeRouteManager } from '@/router/core/IframeRouteManager'
|
|
11
|
+
|
|
12
|
+
const fixtures = vi.hoisted(() => ({ logout: vi.fn() }))
|
|
13
|
+
vi.mock('@/api/auth', () => ({ fetchLogout: fixtures.logout }))
|
|
14
|
+
vi.mock('@/router', () => ({
|
|
15
|
+
HOME_PAGE_PATH: '/home',
|
|
16
|
+
router: {
|
|
17
|
+
currentRoute: { value: { path: '/home', fullPath: '/home' } },
|
|
18
|
+
replace: vi.fn().mockResolvedValue(undefined)
|
|
19
|
+
}
|
|
20
|
+
}))
|
|
21
|
+
vi.mock('@/router/guards/beforeEach', () => ({ resetRouterState: vi.fn() }))
|
|
22
|
+
beforeEach(() => {
|
|
23
|
+
setActivePinia(createPinia())
|
|
24
|
+
localStorage.clear()
|
|
25
|
+
sessionStorage.clear()
|
|
26
|
+
fixtures.logout.mockReset().mockResolvedValue(undefined)
|
|
27
|
+
})
|
|
28
|
+
afterEach(() => {
|
|
29
|
+
vi.useRealTimers()
|
|
30
|
+
vi.restoreAllMocks()
|
|
31
|
+
})
|
|
32
|
+
|
|
33
|
+
describe('session request cleanup', () => {
|
|
34
|
+
it('cancels managed requests when auth state is cleared, including 401 cleanup', () => {
|
|
35
|
+
const user = useUserStore()
|
|
36
|
+
user.establishSession('token')
|
|
37
|
+
const request = beginRequest({})
|
|
38
|
+
user.clearAuthState(false)
|
|
39
|
+
expect(request.signal.aborted).toBe(true)
|
|
40
|
+
expect(user.accessToken).toBe('')
|
|
41
|
+
expect(user.isLogin).toBe(false)
|
|
42
|
+
})
|
|
43
|
+
|
|
44
|
+
it('cancels the old session even when the same token is used for a fresh login', () => {
|
|
45
|
+
const user = useUserStore()
|
|
46
|
+
user.establishSession('token')
|
|
47
|
+
const old = beginRequest({})
|
|
48
|
+
user.establishSession('token')
|
|
49
|
+
expect(old.signal.aborted).toBe(true)
|
|
50
|
+
const next = beginRequest({})
|
|
51
|
+
expect(next.signal.aborted).toBe(false)
|
|
52
|
+
user.setToken('another-token')
|
|
53
|
+
expect(next.signal.aborted).toBe(true)
|
|
54
|
+
})
|
|
55
|
+
|
|
56
|
+
it('cancels before the logout request and always clears local state if remote logout fails', async () => {
|
|
57
|
+
const user = useUserStore()
|
|
58
|
+
user.establishSession('token')
|
|
59
|
+
const old = beginRequest({})
|
|
60
|
+
vi.spyOn(console, 'warn').mockImplementation(() => {})
|
|
61
|
+
fixtures.logout.mockImplementation(async () => {
|
|
62
|
+
expect(old.signal.aborted).toBe(true)
|
|
63
|
+
throw new Error('Offline')
|
|
64
|
+
})
|
|
65
|
+
await signOut()
|
|
66
|
+
expect(user.isLogin).toBe(false)
|
|
67
|
+
expect(user.accessToken).toBe('')
|
|
68
|
+
})
|
|
69
|
+
|
|
70
|
+
it('does not let a delayed logout clear a newer authenticated session', async () => {
|
|
71
|
+
const user = useUserStore()
|
|
72
|
+
user.establishSession('token')
|
|
73
|
+
let complete!: () => void
|
|
74
|
+
fixtures.logout.mockImplementation(
|
|
75
|
+
() =>
|
|
76
|
+
new Promise<void>((resolve) => {
|
|
77
|
+
complete = resolve
|
|
78
|
+
})
|
|
79
|
+
)
|
|
80
|
+
const logout = signOut()
|
|
81
|
+
user.establishSession('token')
|
|
82
|
+
complete()
|
|
83
|
+
await logout
|
|
84
|
+
expect(user.accessToken).toBe('token')
|
|
85
|
+
expect(user.isLogin).toBe(true)
|
|
86
|
+
})
|
|
87
|
+
|
|
88
|
+
it('still completes sign-out if only the access token rotates during logout', async () => {
|
|
89
|
+
const user = useUserStore()
|
|
90
|
+
user.establishSession('token')
|
|
91
|
+
let complete!: () => void
|
|
92
|
+
fixtures.logout.mockImplementation(
|
|
93
|
+
() =>
|
|
94
|
+
new Promise<void>((resolve) => {
|
|
95
|
+
complete = resolve
|
|
96
|
+
})
|
|
97
|
+
)
|
|
98
|
+
const logout = signOut()
|
|
99
|
+
user.setToken('refreshed-token')
|
|
100
|
+
complete()
|
|
101
|
+
await logout
|
|
102
|
+
expect(user.isLogin).toBe(false)
|
|
103
|
+
expect(user.accessToken).toBe('')
|
|
104
|
+
})
|
|
105
|
+
|
|
106
|
+
it('shares repeated sign-out, blocks business requests and permits the scoped remote logout', async () => {
|
|
107
|
+
const user = useUserStore()
|
|
108
|
+
user.establishSession('token')
|
|
109
|
+
let complete!: () => void
|
|
110
|
+
fixtures.logout.mockImplementation(
|
|
111
|
+
() =>
|
|
112
|
+
new Promise<void>((resolve) => {
|
|
113
|
+
complete = resolve
|
|
114
|
+
})
|
|
115
|
+
)
|
|
116
|
+
const first = signOut()
|
|
117
|
+
expect(signOut()).toBe(first)
|
|
118
|
+
expect(fixtures.logout).toHaveBeenCalledOnce()
|
|
119
|
+
expect(fixtures.logout).toHaveBeenCalledWith({ requestScope: SIGN_OUT_REQUEST_SCOPE })
|
|
120
|
+
expect(user.isSigningOut).toBe(true)
|
|
121
|
+
expect(beginRequest({}).signal.aborted).toBe(true)
|
|
122
|
+
const remote = beginRequest({ scope: SIGN_OUT_REQUEST_SCOPE })
|
|
123
|
+
expect(remote.signal.aborted).toBe(false)
|
|
124
|
+
complete()
|
|
125
|
+
await first
|
|
126
|
+
expect(remote.signal.aborted).toBe(true)
|
|
127
|
+
expect(user.isSigningOut).toBe(false)
|
|
128
|
+
expect(beginRequest({}).signal.aborted).toBe(false)
|
|
129
|
+
})
|
|
130
|
+
|
|
131
|
+
it('cleans local state even if a custom remote logout never settles', async () => {
|
|
132
|
+
vi.useFakeTimers()
|
|
133
|
+
vi.spyOn(console, 'error').mockImplementation(() => {})
|
|
134
|
+
const user = useUserStore()
|
|
135
|
+
user.establishSession('token')
|
|
136
|
+
fixtures.logout.mockImplementation(() => new Promise(() => {}))
|
|
137
|
+
const task = signOut()
|
|
138
|
+
await vi.advanceTimersByTimeAsync(10000)
|
|
139
|
+
await task
|
|
140
|
+
expect(user.isLogin).toBe(false)
|
|
141
|
+
expect(user.isSigningOut).toBe(false)
|
|
142
|
+
})
|
|
143
|
+
|
|
144
|
+
it('clears account data and runs all project cleanups while preserving preferences and same-account tab metadata', () => {
|
|
145
|
+
vi.spyOn(console, 'error').mockImplementation(() => {})
|
|
146
|
+
const user = useUserStore()
|
|
147
|
+
const tabs = useWorktabStore()
|
|
148
|
+
const settings = useSettingStore()
|
|
149
|
+
user.establishSession('token')
|
|
150
|
+
user.setUserInfo({ userId: '0', userName: 'A', email: '', roles: [] })
|
|
151
|
+
user.searchHistory = [{ path: '/private', meta: { title: 'Private' } }]
|
|
152
|
+
tabs.opened = [{ path: '/private', title: 'Private' }] as typeof tabs.opened
|
|
153
|
+
tabs.current = tabs.opened[0]
|
|
154
|
+
const preferences = JSON.stringify(settings.$state)
|
|
155
|
+
const epoch = user.sessionEpoch
|
|
156
|
+
const stopBroken = registerSessionCleanup(() => {
|
|
157
|
+
throw new Error('Cleanup failed')
|
|
158
|
+
})
|
|
159
|
+
const cleanup = vi.fn()
|
|
160
|
+
const stop = registerSessionCleanup(cleanup)
|
|
161
|
+
try {
|
|
162
|
+
user.clearAuthState(false)
|
|
163
|
+
expect(user.searchHistory).toEqual([])
|
|
164
|
+
expect(user.info).toEqual({})
|
|
165
|
+
expect(user.sessionEpoch).toBeGreaterThan(epoch)
|
|
166
|
+
expect(tabs.current).toEqual({})
|
|
167
|
+
expect(cleanup).toHaveBeenCalledOnce()
|
|
168
|
+
expect(JSON.stringify(settings.$state)).toBe(preferences)
|
|
169
|
+
user.establishSession('next')
|
|
170
|
+
user.setUserInfo({ userId: '0', userName: 'A', email: '', roles: [] })
|
|
171
|
+
user.checkAndClearWorktabs()
|
|
172
|
+
expect(tabs.opened).toHaveLength(1)
|
|
173
|
+
user.establishSession('other')
|
|
174
|
+
user.setUserInfo({ userId: 'B', userName: 'B', email: '', roles: [] })
|
|
175
|
+
user.checkAndClearWorktabs()
|
|
176
|
+
expect(tabs.opened).toEqual([])
|
|
177
|
+
expect(tabs.current).toEqual({})
|
|
178
|
+
} finally {
|
|
179
|
+
stop()
|
|
180
|
+
stopBroken()
|
|
181
|
+
}
|
|
182
|
+
})
|
|
183
|
+
|
|
184
|
+
it('drops tabs with unknown ownership and namespaces iframe and recovery storage', () => {
|
|
185
|
+
const user = useUserStore()
|
|
186
|
+
const tabs = useWorktabStore()
|
|
187
|
+
tabs.opened = [{ path: '/private' }] as typeof tabs.opened
|
|
188
|
+
user.setUserInfo({ userId: 'A', userName: 'A', email: '', roles: [] })
|
|
189
|
+
user.checkAndClearWorktabs()
|
|
190
|
+
expect(tabs.opened).toEqual([])
|
|
191
|
+
const manager = IframeRouteManager.getInstance()
|
|
192
|
+
manager.add({ path: '/iframe', meta: { title: 'Iframe' } })
|
|
193
|
+
manager.save()
|
|
194
|
+
expect(sessionStorage.getItem(StorageConfig.IFRAME_ROUTES_KEY)).not.toBeNull()
|
|
195
|
+
manager.clear()
|
|
196
|
+
expect(sessionStorage.getItem(StorageConfig.IFRAME_ROUTES_KEY)).toBeNull()
|
|
197
|
+
localStorage.setItem('neighbor-token', 'keep')
|
|
198
|
+
localStorage.setItem(StorageConfig.generateStorageKey('user'), 'remove')
|
|
199
|
+
StorageConfig.clearApplicationStorage(localStorage)
|
|
200
|
+
expect(localStorage.getItem('neighbor-token')).toBe('keep')
|
|
201
|
+
expect(localStorage.getItem(StorageConfig.generateStorageKey('user'))).toBeNull()
|
|
202
|
+
})
|
|
203
|
+
})
|
|
@@ -44,4 +44,50 @@ describe('HTTP contract helpers', () => {
|
|
|
44
44
|
|
|
45
45
|
expect(left).toBe(right)
|
|
46
46
|
})
|
|
47
|
+
|
|
48
|
+
it('does not collide on types, delimiters, sparse arrays or nested values', () => {
|
|
49
|
+
const pairs = [
|
|
50
|
+
[{ a: 'x,b:y' }, { a: 'x', b: 'y' }],
|
|
51
|
+
[1, '1'],
|
|
52
|
+
[null, undefined],
|
|
53
|
+
[
|
|
54
|
+
[1, 2],
|
|
55
|
+
['1', '2']
|
|
56
|
+
],
|
|
57
|
+
[[undefined], Array(1)],
|
|
58
|
+
[{ a: ['x,y'] }, { a: ['x', 'y'] }]
|
|
59
|
+
]
|
|
60
|
+
for (const [left, right] of pairs)
|
|
61
|
+
expect(stableSerialize(left)).not.toBe(stableSerialize(right))
|
|
62
|
+
})
|
|
63
|
+
|
|
64
|
+
it('skips automatic comparison for uploads, binary data, custom serialization and cycles', () => {
|
|
65
|
+
const circular: Record<string, unknown> = {}
|
|
66
|
+
circular.self = circular
|
|
67
|
+
for (const data of [
|
|
68
|
+
new FormData(),
|
|
69
|
+
new Blob(['x']),
|
|
70
|
+
new ArrayBuffer(2),
|
|
71
|
+
new Uint8Array(2),
|
|
72
|
+
new Date(),
|
|
73
|
+
circular
|
|
74
|
+
]) {
|
|
75
|
+
expect(createRequestKey({ url: '/upload', data })).toBeUndefined()
|
|
76
|
+
}
|
|
77
|
+
expect(createRequestKey({ url: '/list', paramsSerializer: () => 'custom' })).toBeUndefined()
|
|
78
|
+
expect(createRequestKey({ url: '/list', transformRequest: [(data) => data] })).toBeUndefined()
|
|
79
|
+
})
|
|
80
|
+
|
|
81
|
+
it('distinguishes origins, response modes and authentication contexts', () => {
|
|
82
|
+
const base = { url: '/list', baseURL: '/api', params: { page: 1 } }
|
|
83
|
+
for (const extra of [
|
|
84
|
+
{ baseURL: '/other' },
|
|
85
|
+
{ responseType: 'blob' as const },
|
|
86
|
+
{ headers: { 'X-Tenant': 'other' } },
|
|
87
|
+
{ withCredentials: true },
|
|
88
|
+
{ auth: { username: 'other', password: 'test' } }
|
|
89
|
+
]) {
|
|
90
|
+
expect(createRequestKey({ ...base, ...extra })).not.toBe(createRequestKey(base))
|
|
91
|
+
}
|
|
92
|
+
})
|
|
47
93
|
})
|