Files
zyt/server/tests/IamLoginUiContractTest.mjs
T

89 lines
5.2 KiB
JavaScript

import assert from 'node:assert/strict'
import fs from 'node:fs'
import vm from 'node:vm'
import { createRequire } from 'node:module'
const require = createRequire(import.meta.url)
const ts = require('typescript')
const root = new URL('../../', import.meta.url)
const vue = fs.readFileSync(new URL('admin/src/views/account/login.vue', root), 'utf8')
const api = fs.readFileSync(new URL('admin/src/api/user.ts', root), 'utf8')
const store = fs.readFileSync(new URL('admin/src/stores/modules/user.ts', root), 'utf8')
const script = vue.match(/<script lang="ts" setup>([\s\S]*?)<\/script>/)[1]
const js = ts.transpileModule(script, { compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020 } }).outputText
// Imports are injected with controlled test doubles; all actual component handlers execute.
const runnable = js.replace(/^.*require\(.+\);?$/gm, '').replace(/^Object.defineProperty\(exports.*$/gm, '')
async function scenario(query, result, fail = false, enabled = true, wecomEnabled = false) {
const calls = [], paths = [], errors = []
let mounted, cleaned = ''
const ref = value => ({ value })
const userStore = {
iamLogin: async ticket => { calls.push(['iam', ticket, cleaned]); if (fail) throw new Error('expired'); return result },
workWechatLogin: async code => { calls.push(['wechat', code]); return result }
}
const c = {
exports: {}, console, URL, URLSearchParams,
vue_1: { ref, shallowRef: ref, computed: fn => ref(fn()), watch() {}, nextTick: async fn => fn?.(), onMounted: fn => { mounted = fn } },
user_2: { getIamConfig: async () => ({ enabled, loginUrl: 'https://iam.example/login' }), getWorkWechatConfig: async () => ({ enabled: wecomEnabled, corp_id: 'corp', agent_id: 'agent' }) },
user_1: { default: () => userStore },
app_1: { default: () => ({ config: {} }) },
cache_1: { default: { get() {}, set() {} } },
cacheEnums_1: { ACCOUNT_KEY: 'account' },
pageEnum_1: { PageEnum: { INDEX: '/' } },
useLockFn_1: { useLockFn: fn => ({ isLock: ref(false), lockFn: fn }) },
element_plus_1: { ElMessage: { error: text => errors.push(text) } },
reactive: value => value,
useRoute: () => ({ query: { redirect: '/dashboard' } }),
useRouter: () => ({ push: async path => paths.push(path) }),
navigator: { userAgent: 'wxwork' },
window: { location: { href: `https://zyt.example/admin/login${query}`, origin: 'https://zyt.example', pathname: '/admin/login', search: query, assign: url => calls.push(['assign', url]) }, history: { state: { back: '/' }, replaceState: (_, __, url) => { cleaned = url } } }
}
vm.createContext(c)
vm.runInContext(runnable, c)
await mounted()
await Promise.resolve()
return { calls, paths, errors, cleaned, context: c }
}
for (const [result, destination] of [[{ is_paw: 0, need_bind_work_wechat: true }, '/change-password'], [{ is_paw: 1, need_bind_work_wechat: true }, '/bind-work-wechat'], [{ is_paw: 1 }, '/dashboard']]) {
const s = await scenario('?iam_ticket=one-use&code=wecom&state=admin_login&redirect=%2Fdashboard', result)
assert.equal(s.calls.length, 1)
assert.equal(s.calls[0][0], 'iam')
assert.equal(s.calls[0][1], 'one-use')
assert.equal(s.calls[0][2], '/admin/login?redirect=%2Fdashboard')
assert.deepEqual(s.paths, [destination])
await vm.runInContext("handleIamCallback('one-use', null)", s.context)
assert.equal(s.calls.length, 1)
}
for (const query of ['?iam_error=Denied&code=wecom&state=admin_login', '?iam_ticket=']) {
const s = await scenario(query, {})
assert.equal(s.calls.length, 0)
assert.equal(s.errors.length, 1)
assert.equal(s.cleaned, '/admin/login')
}
const failed = await scenario('?iam_ticket=expired', {}, true)
assert.equal(failed.errors[0], 'expired')
assert.equal(vm.runInContext('iamLoading.value', failed.context), false)
const iamErrorWithWecom = await scenario('?iam_error=Denied', {}, false, true, true)
assert.equal(vm.runInContext('wxWorkEnabled.value', iamErrorWithWecom.context), true)
assert.equal(vm.runInContext('wxWorkAutoLogin.value', iamErrorWithWecom.context), false)
assert.equal(iamErrorWithWecom.calls.length, 0)
const wecom = await scenario('?code=original&state=admin_login', { is_paw: 1 })
assert.equal(wecom.calls[0][0], 'wechat')
assert.equal(wecom.calls[0][1], 'original')
const disabled = await scenario('', {}, false, false)
vm.runInContext('handleIamLogin()', disabled.context)
assert.equal(disabled.calls.length, 0)
const enabled = await scenario('', {})
assert.equal(enabled.calls.length, 0, 'IAM never auto redirects')
vm.runInContext('handleIamLogin()', enabled.context)
assert.equal(enabled.calls[0][0], 'assign')
assert.match(api, /url: '\/iam\/exchange'[\s\S]*withCredentials: true/)
assert.match(api, /withToken: false, isOpenRetry: false/)
assert.match(store, /async iamLogin\(ticket: string\)[\s\S]*cache\.set\(TOKEN_KEY, data\.token\)/)
assert.match(vue, /v-if="iamEnabled"/)
assert.match(vue, /userStore\.login\(formData\)/)
assert.match(vue, /userStore\.workWechatLogin\(code\)/)
console.log('PASS IAM UI: optional entry, callback priority, URL cleanup, one exchange, error recovery, password/bind/local redirects, existing login contracts')