diff --git a/CONTEXT.md b/CONTEXT.md index 1e5b272e..090218a9 100644 --- a/CONTEXT.md +++ b/CONTEXT.md @@ -123,6 +123,9 @@ _Avoid_:历史图谱配置、原始测量数据、归档正文 **云账号登录(Cloud Account Login)**:用户通过云端账号建立在线身份的过程;与 Sequence 锁的本地用户解锁分别管理。 _Avoid_:本地用户解锁、离线授权 +**云账号密码(Cloud Account Password)**:用于验证 OpenTest 云账号身份的密码,与 Sequence 锁的本地用户密码分别管理。 +_Avoid_:Sequence 锁本地用户密码、离线授权材料 + **云许可证服务(Cloud License Service)**:签发、刷新和管理产品使用权益的云端服务;与建立用户身份的云账号登录服务分别配置。本机绑定的权益可通过该服务取得离线证书。 _Avoid_:登录服务器、Casdoor 服务 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 2e2ab692..a6d72f8c 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -43,6 +43,12 @@ node --test tools/__tests__/docs-policy.test.mjs The `community-package` workflow builds three community installers: an EXE executable installer for Windows x64, a DEB Debian package for Linux x64, and a DMG disk image for macOS ARM64. They include OpenTest, the business plugins listed in `default-plugins.json` (currently `fft-tools`) from `crysound/OpenTest-Plugins`, and the SonoDAQ device plugin, but not the other plugins from the website package. Device plugins are bundled under `backend/native/plugins/devices` in the application resources. Windows retains `test` mode and uses the backend defaults without an explicit `cloud.license.url`; Linux and macOS use `production` license mode with the formal license service and separate generated configurations. There is no separate test server. Automatic updates are disabled. Windows is unsigned; macOS retains its multilingual license agreement and has only ad hoc signatures, without developer signing or Apple notarization. On first launch, choose Open Anyway in Privacy & Security. The SonoDAQ device plugin requires macOS 26 or later. +Desktop configuration owns the password-page URL independently of the native `test` / `production` license mode. Source runs and all platform installers, including Windows community packages, default to `https://www.opentest.com/account/#change-password`. The only developer override is `CASDOOR_CHANGE_PASSWORD_URL`: put it in the Git-ignored `.local/runtime.env` for local use, or inject it into the final CI packaging step. Quote URLs containing `#` in `.env` files (for example, `"https://accounts.example/account/#change-password"`) to preserve the page fragment. Real test URLs are not committed to Git, and the frontend has no separate password-page environment variable. + +Packaging writes the resolved URL into the bundled desktop field `auth.changePasswordUrl`. This is generated delivery data; manually edited local JSON and packaging modes do not override the URL. Installed applications read the bundled result and ignore the user's environment variable. Overrides must be HTTPS URLs without embedded credentials. An unset or blank value selects the official default; invalid values report a configuration error. Standalone browser builds without desktop configuration hide the entry. + +The client opens the page in the system browser. The website manages the browser session; this entry does not synchronize client and website sessions. Deployments using another account service must supply its matching password page through the same override. + Each push to `main` publishes a daily prerelease `A.B.C-dev.`; later builds on the same Beijing day add `.2`, `.3` and so on. Pushing `vA.B.C-rc.N` or `vA.B.C` publishes a release candidate or release. First create the same tag in `OpenTest-Plugins`: a missing tag fails the build instead of falling back to `main`. Daily builds, pull requests, and manual runs use the plugin repository's `main`; manual runs cannot select an arbitrary plugin revision. Tag runs require the matching plugin tag. All three platforms check out the same resolved commit directly and verify it again, so a moving branch cannot change the build inputs. After every build and installation check succeeds, one publishing job uploads three installers and their SHA-256 checksum files before making the release public. Pull requests targeting `main` trigger all three builds and installation checks, without publishing, when they change `.github/workflows/community-package.yml`, `default-plugins.json`, `packaging.config.json`, the packaging scripts listed in the workflow, `tools/__tests__/**`, `tools/ci/**`, or `tools/publish-community-build.cjs`. The workflow uses `--edition community` and does not trigger for unrelated application, SDK, vendor, manifest, or lockfile changes. `package.json` keeps the plain `A.B.C` used for plugin compatibility; the full version is passed to `node tools/package.mjs --version`. diff --git a/CONTRIBUTING.zh-CN.md b/CONTRIBUTING.zh-CN.md index f8e9c5d4..cf4dc996 100644 --- a/CONTRIBUTING.zh-CN.md +++ b/CONTRIBUTING.zh-CN.md @@ -43,6 +43,12 @@ node --test tools/__tests__/docs-policy.test.mjs `community-package` 工作流构建三平台社区安装包:Windows x64 的 EXE(可执行安装程序)、Linux x64 的 DEB(Debian 软件包)、macOS ARM64 的 DMG(磁盘映像)。社区包包含 OpenTest、`crysound/OpenTest-Plugins` 中由 `default-plugins.json` 列出的业务插件(当前为 `fft-tools`)和 SonoDAQ 设备插件,不含官网完整包的其他插件。设备插件放在应用资源目录的 `backend/native/plugins/devices` 下。Windows 保留 `test` 测试模式,使用后端默认配置且不写入 `cloud.license.url`;Linux、macOS 使用正式授权服务的 `production` 模式,各模式独立生成配置。当前没有独立测试服务器;自动更新均关闭。Windows 未签名;macOS 保留多语言许可协议,仅作本机临时签名,未取得开发者签名或 Apple 公证,首次打开需在“隐私与安全性”中点“仍要打开”。SonoDAQ 设备插件要求 macOS 26 或更高版本。 +修改密码页由 desktop 统一配置,与原生授权材料的 `test` / `production` 模式无关;源码运行及各平台安装包均默认使用 `https://www.opentest.com/account/#change-password`,Windows 社区包也沿用该正式地址。唯一人工覆盖入口为 `CASDOOR_CHANGE_PASSWORD_URL`:本地可写入 Git 忽略的 `.local/runtime.env`,CI 在最终打包步骤注入。`.env` 中包含 `#` 的地址必须加引号(例如 `"https://accounts.example/account/#change-password"`),以保留网页路由片段。真实测试地址不提交到 Git,前端没有独立的密码页环境变量。 + +打包会将解析后的地址写入包内桌面配置 `auth.changePasswordUrl`;该字段是自动生成的交付结果,手写本机 JSON 或打包模式配置不能覆盖地址。安装版只读取包内结果,不使用用户机器的同名环境变量。覆盖值必须是无内嵌凭据的 HTTPS URL;未设置或留空时使用正式默认值,无效值报告配置错误。独立浏览器构建没有桌面配置时不显示该入口。 + +客户端只负责在系统浏览器中打开网页,浏览器的登录状态由网站管理;该入口不提供客户端与网站的会话同步。部署采用其他账号服务时,应通过上述唯一入口提供与该账号体系匹配的修改密码页。 + 每次推送到 `main` 都发布一个日常预发布版本 `A.B.C-dev.<年月日>`,北京时间同一天的后续构建依次加 `.2`、`.3`。推送 `vA.B.C-rc.N` 或 `vA.B.C` 标签会发布候选版本或正式版本;必须先在 `OpenTest-Plugins` 创建同名标签,缺失时构建立即失败,不回落到 `main`。日常构建、拉取请求和手动运行都使用插件仓库的 `main`;手动运行不能指定任意插件版本,标签运行必须使用同名插件标签。三个平台直接检出解析得到的同一提交,并再次核对,防止构建期间分支前移。全部构建及安装验证通过后,单一发布任务先上传三个安装包及各自的 SHA-256 文件校验值,再公开版本。 面向 `main` 的拉取请求若修改 `.github/workflows/community-package.yml`、`default-plugins.json`、`packaging.config.json`、工作流中列出的打包脚本、`tools/__tests__/**`、`tools/ci/**` 或 `tools/publish-community-build.cjs`,会触发三平台构建和安装验证,但不发布。工作流使用 `--edition community`;无关的应用、软件开发套件、vendor、清单或锁文件变更不会触发这条流程。`package.json` 保留用于插件兼容性的 `A.B.C`,完整版本号通过 `node tools/package.mjs --version` 传入。 diff --git a/apps/desktop/src/config/change-password.js b/apps/desktop/src/config/change-password.js new file mode 100644 index 00000000..9bf7ddc0 --- /dev/null +++ b/apps/desktop/src/config/change-password.js @@ -0,0 +1,17 @@ +const DEFAULT_CHANGE_PASSWORD_URL = 'https://www.opentest.com/account/#change-password' + +// Account pages are independent of the native license mode. This is the only +// developer override; packaged applications consume the generated desktop settings. +function resolveChangePasswordUrl(env = process.env) { + const value = env.CASDOOR_CHANGE_PASSWORD_URL + if (value === undefined || (typeof value === 'string' && !value.trim())) return DEFAULT_CHANGE_PASSWORD_URL + try { + const url = new URL(value) + if (url.protocol !== 'https:' || url.username || url.password) throw new Error('invalid URL') + return url.href + } catch { + throw new Error('CASDOOR_CHANGE_PASSWORD_URL 必须是无凭据的 HTTPS URL') + } +} + +module.exports = { DEFAULT_CHANGE_PASSWORD_URL, resolveChangePasswordUrl } diff --git a/apps/desktop/src/config/public-auth.js b/apps/desktop/src/config/public-auth.js index 7d15ff93..1367c2fc 100644 --- a/apps/desktop/src/config/public-auth.js +++ b/apps/desktop/src/config/public-auth.js @@ -1,6 +1,7 @@ const { readLocalSettings } = require('./local-settings') const { resolveProjectPaths } = require('./project-paths') const { prepareServiceEnvironment, validateServiceConfiguration } = require('./service-environment') +const { DEFAULT_CHANGE_PASSWORD_URL, resolveChangePasswordUrl } = require('./change-password') function getPublicAuthConfig() { const local = readLocalSettings().auth || {} @@ -11,7 +12,12 @@ function getPublicAuthConfig() { forgetPasswordUrl: 'CASDOOR_FORGET_PASSWORD_URL' } validateServiceConfiguration({ services: paths.services, backendConfig: paths.backendConfig }) - return Object.fromEntries(Object.entries(fields).map(([field, variable]) => [field, env[variable] || local[field] || ''])) + return { + ...Object.fromEntries(Object.entries(fields).map(([field, variable]) => [field, env[variable] || local[field] || ''])), + changePasswordUrl: paths.packaged + ? local.changePasswordUrl || DEFAULT_CHANGE_PASSWORD_URL + : resolveChangePasswordUrl(env) + } } module.exports = { getPublicAuthConfig } diff --git a/apps/desktop/src/ipcMainHandler.js b/apps/desktop/src/ipcMainHandler.js index b1f84239..82cb033e 100644 --- a/apps/desktop/src/ipcMainHandler.js +++ b/apps/desktop/src/ipcMainHandler.js @@ -602,8 +602,8 @@ const ipcMainHandler = (win, { restart } = {}) => { } }) - // 使用系统默认浏览器打开外部链接 - ipcMain.handle('open-external-browser', async (event, url) => { + // 使用系统默认浏览器打开外部链接;渲染进程依赖稳定的结果对象判断是否关闭菜单。 + const openExternalBrowser = async (event, url) => { try { assertFrameworkSender(event, serviceConfig.frontendUrl) await shell.openExternal(resolveExternalHttpUrl(url)) @@ -612,7 +612,8 @@ const ipcMainHandler = (win, { restart } = {}) => { logger.warn('外部链接请求未完成', { code: error.code || 'EXTERNAL_LINK_REJECTED' }) return { success: false, error: '外部链接无效或无法打开' } } - }) + } + ipcMain.handle('open-external-browser', openExternalBrowser) ipcMain.handle('should-force-login', shouldForceLogin) ipcMain.handle('mark-first-login-success', markFirstLoginSuccess) diff --git a/apps/desktop/tests/unit/open-external-browser.test.mjs b/apps/desktop/tests/unit/open-external-browser.test.mjs new file mode 100644 index 00000000..63a6bb15 --- /dev/null +++ b/apps/desktop/tests/unit/open-external-browser.test.mjs @@ -0,0 +1,75 @@ +import { expect, it, vi } from 'vitest' +import { readFileSync } from 'node:fs' +import { createRequire } from 'node:module' +import { runInNewContext } from 'node:vm' + +const require = createRequire(import.meta.url) +const frontendUrl = 'http://127.0.0.1:19010' +const event = { senderFrame: { url: `${frontendUrl}/home` } } + +function load(file, mocks) { + const module = { exports: {} } + runInNewContext(readFileSync(new URL(`../../src/${file}`, import.meta.url), 'utf8'), { + module, exports: module.exports, require: id => { + if (!Object.hasOwn(mocks, id)) throw new Error(`Unexpected dependency in ${file}: ${id}`) + return mocks[id] + }, + __dirname: 'desktop/src', process, console: { ...console, error() {} } + }) + return module.exports +} + +function environment() { + const handlers = new Map() + const ipcMain = { handle: (name, handler) => handlers.set(name, handler), on: () => {} } + const shell = { openExternal: vi.fn().mockResolvedValue(undefined) } + const noop = () => {} + const register = load('ipcMainHandler.js', { + electron: { ipcMain, shell }, https: {}, fs: {}, path: require('node:path'), + './logger': { warn: vi.fn() }, './utils/launch-info': {}, './utils': {}, + './config/index': { APP_CONFIG: { dev: {} }, IS_DEV_MODE: false, IS_PRODUCTION: true, VERSION: 'test' }, + './page-zoom': { registerPageZoomIpcHandlers: noop }, './window/native-close': { registerNativeWindowCloseIpcHandlers: noop }, + './analytics/ipc-handlers': { registerAnalyticsIpcHandlers: noop }, + './feedback/ipc-handlers': { registerFeedbackIpcHandlers: noop }, + './report-pdf-export': { registerReportPdfExportHandler: noop }, './app-update': { registerAppUpdateHandler: noop }, + './config/service': { serviceConfig: { frontendUrl } }, './config/project-paths': {}, + './config/public-auth': { getPublicAuthConfig: () => ({}) }, './config/updates': { getProductUpdateConfig: () => ({}) }, + './policies/window-navigation-policy': require('../../src/policies/window-navigation-policy'), + './utils/window': {}, './detached-card/window-manager': { createDetachedCardWindowManager: () => ({}) }, + './detached-card/ipc-handlers': { registerDetachedCardIpcHandlers: noop }, './service/backend': {}, + './grpc/dialog-interaction-client': {}, + './sequence-dialog/session-manager': { createSequenceDialogSessionManager: () => ({}) }, + './utils/storage': {}, './service/auth': {} + }) + register({ webContents: { id: 1, on: noop }, on: noop }) + const bridge = {} + load('preload.js', { + electron: { + contextBridge: { exposeInMainWorld: (name, api) => { bridge[name] = api } }, + webUtils: { getPathForFile: () => '' }, + ipcRenderer: { invoke: (channel, ...args) => handlers.get(channel)(event, ...args) } + }, + './feedback/fingerprint': { createFeedbackFingerprint: () => ({}) }, + '../../../cli/bridge/preload.cjs': { createAutomationPreload: () => ({}) } + }) + return { api: bridge.electronAPI, handlers, shell } +} + +it('returns the successful external browser result through the preload bridge', async () => { + const environmentState = environment() + const url = 'https://test-account.example/account/#change-password' + + await expect(environmentState.api.openExternalBrowser(url)).resolves.toEqual({ success: true }) + expect(environmentState.shell.openExternal).toHaveBeenCalledExactlyOnceWith(url) +}) + +it('returns a failure result when the external browser rejects or the URL is invalid', async () => { + const environmentState = environment() + environmentState.shell.openExternal.mockRejectedValueOnce(new Error('browser unavailable')) + + await expect(environmentState.api.openExternalBrowser('https://test-account.example/account/#change-password')) + .resolves.toMatchObject({ success: false }) + await expect(environmentState.api.openExternalBrowser('javascript:alert(1)')) + .resolves.toMatchObject({ success: false }) + expect(environmentState.shell.openExternal).toHaveBeenCalledOnce() +}) diff --git a/apps/frontend/src/composables/electron-api.ts b/apps/frontend/src/composables/electron-api.ts index 67cc48ec..4d8c9048 100644 --- a/apps/frontend/src/composables/electron-api.ts +++ b/apps/frontend/src/composables/electron-api.ts @@ -6,6 +6,7 @@ export type NativeWindowCloseRequest = NativeWindowCloseContext & { requestId: n export type NativeWindowCloseResponse = NativeWindowCloseRequest & { allow: boolean } export type MaybePromise = T | Promise +export type OpenExternalResult = { success: boolean; error?: string } export interface FeedbackHostResult { ok: boolean @@ -344,7 +345,7 @@ export interface ElectronApi { onAppUpdateDownloaded?: (..._args: unknown[]) => MaybePromise onAppUpdateProgress?: (..._args: unknown[]) => MaybePromise openDevTools?: (..._args: unknown[]) => MaybePromise - openExternalBrowser?: (..._args: unknown[]) => MaybePromise + openExternalBrowser?: (_url: string) => MaybePromise initFileParser?: (..._args: unknown[]) => MaybePromise readAndParseFile?: (..._args: unknown[]) => MaybePromise parseFileByChunks?: (..._args: unknown[]) => MaybePromise diff --git a/apps/frontend/src/composables/use-electron.ts b/apps/frontend/src/composables/use-electron.ts index a020d986..6bdebd1c 100644 --- a/apps/frontend/src/composables/use-electron.ts +++ b/apps/frontend/src/composables/use-electron.ts @@ -12,6 +12,7 @@ import type { ElectronListenerDisposer, ElectronStorageLike, MaybePromise, + OpenExternalResult, NativeWindowCloseContext, NativeWindowCloseReady, NativeWindowCloseRequest, @@ -55,7 +56,7 @@ type UseElectronApiReturn = { appUpdate: AsyncHandler appUpdateQuitAndInstall: AsyncHandler openDevTools: AsyncHandler - openExternal: AsyncHandler + openExternal: AsyncHandler<[string], OpenExternalResult> initFileParser: AsyncHandler readAndParseFile: AsyncHandler parseFileByChunks: AsyncHandler diff --git a/apps/frontend/src/locales/de-DE.ts b/apps/frontend/src/locales/de-DE.ts index 456058d1..1a1fd6bf 100644 --- a/apps/frontend/src/locales/de-DE.ts +++ b/apps/frontend/src/locales/de-DE.ts @@ -4411,6 +4411,7 @@ guidance: { verificationCode: 'Code', getCode: 'Code abrufen', forgetPassword: 'Passwort vergessen', + changePassword: 'Passwort ändern', signUp: 'Anmelden', emailLogin: 'Anmelden mit E-Mail', loginWithOtherMethods: 'Anmelden mit anderen Methoden', diff --git a/apps/frontend/src/locales/en.ts b/apps/frontend/src/locales/en.ts index 362b88d5..d499be00 100644 --- a/apps/frontend/src/locales/en.ts +++ b/apps/frontend/src/locales/en.ts @@ -4400,6 +4400,7 @@ guidance: { verificationCode: 'Code', getCode: 'Get Code', forgetPassword: 'Forgot password', + changePassword: 'Change Password', signUp: 'Sign up', emailLogin: 'Login with email', loginWithOtherMethods: 'Login with other methods', diff --git a/apps/frontend/src/locales/es-ES.ts b/apps/frontend/src/locales/es-ES.ts index 9aaed74b..56ade41d 100644 --- a/apps/frontend/src/locales/es-ES.ts +++ b/apps/frontend/src/locales/es-ES.ts @@ -4409,6 +4409,7 @@ guidance: { verificationCode: 'Código', getCode: 'Obtener Código', forgetPassword: 'Olvidé mi contraseña', + changePassword: 'Modificar contraseña', signUp: 'Registrarse', emailLogin: 'Iniciar sesión con correo electrónico', loginWithOtherMethods: 'Iniciar sesión con otros métodos', diff --git a/apps/frontend/src/locales/fr-FR.ts b/apps/frontend/src/locales/fr-FR.ts index b4e35c35..733ff7f6 100644 --- a/apps/frontend/src/locales/fr-FR.ts +++ b/apps/frontend/src/locales/fr-FR.ts @@ -4413,6 +4413,7 @@ guidance: { verificationCode: 'Code', getCode: 'Obtenir le code', forgetPassword: 'Mot de passe oublié', + changePassword: 'Changer de mot de passe', signUp: "S'inscrire", emailLogin: 'Connexion avec email', loginWithOtherMethods: "Connexion avec d'autres méthodes", diff --git a/apps/frontend/src/locales/ja-JP.ts b/apps/frontend/src/locales/ja-JP.ts index 82cb05ff..ff669c34 100644 --- a/apps/frontend/src/locales/ja-JP.ts +++ b/apps/frontend/src/locales/ja-JP.ts @@ -4377,6 +4377,7 @@ guidance: { verificationCode: 'コード', getCode: 'コードを取得', forgetPassword: 'パスワードを忘れた', + changePassword: 'パスワードを変更', signUp: 'サインアップ', emailLogin: 'メールでログイン', loginWithOtherMethods: '他の方法でログイン', diff --git a/apps/frontend/src/locales/ko-KR.ts b/apps/frontend/src/locales/ko-KR.ts index 04d79508..23cd65eb 100644 --- a/apps/frontend/src/locales/ko-KR.ts +++ b/apps/frontend/src/locales/ko-KR.ts @@ -4361,6 +4361,7 @@ guidance: { verificationCode: '코드', getCode: '코드 받기', forgetPassword: '비밀번호 분실', + changePassword: '비밀번호 변경', signUp: '회원가입', emailLogin: '이메일로 로그인', loginWithOtherMethods: '다른 방법으로 로그인', diff --git a/apps/frontend/src/locales/ru-RU.ts b/apps/frontend/src/locales/ru-RU.ts index b3cb461f..d215ec82 100644 --- a/apps/frontend/src/locales/ru-RU.ts +++ b/apps/frontend/src/locales/ru-RU.ts @@ -4389,6 +4389,7 @@ guidance: { verificationCode: 'Код', getCode: 'Получить код', forgetPassword: 'Забыли пароль', + changePassword: 'Сменить пароль', signUp: 'Зарегистрироваться', emailLogin: 'Войти с помощью email', loginWithOtherMethods: 'Войти другими способами', diff --git a/apps/frontend/src/locales/tr-TR.ts b/apps/frontend/src/locales/tr-TR.ts index a1a933f1..b4ac813c 100644 --- a/apps/frontend/src/locales/tr-TR.ts +++ b/apps/frontend/src/locales/tr-TR.ts @@ -4403,6 +4403,7 @@ averagingMode: 'Ortalama Alma Modu', verificationCode: 'Kod', getCode: 'Kod Al', forgetPassword: 'Şifremi unuttum', + changePassword: 'Şifre Değiştir', signUp: 'Kaydol', emailLogin: 'E-posta ile giriş yap', loginWithOtherMethods: 'Diğer yöntemlerle giriş yap', diff --git a/apps/frontend/src/locales/zh-CN.ts b/apps/frontend/src/locales/zh-CN.ts index b9e34cb7..e171c1b6 100644 --- a/apps/frontend/src/locales/zh-CN.ts +++ b/apps/frontend/src/locales/zh-CN.ts @@ -4430,6 +4430,7 @@ guidance: { verificationCode: '验证码', getCode: '获取验证码', forgetPassword: '忘记密码', + changePassword: '修改密码', signUp: '注册', emailLogin: '邮箱登录', loginWithOtherMethods: '其他方式登录', diff --git a/apps/frontend/src/locales/zh-TW.ts b/apps/frontend/src/locales/zh-TW.ts index f6444537..f5d846d0 100644 --- a/apps/frontend/src/locales/zh-TW.ts +++ b/apps/frontend/src/locales/zh-TW.ts @@ -4371,6 +4371,7 @@ guidance: { verificationCode: '驗證碼', getCode: '取得驗證碼', forgetPassword: '忘記密碼', + changePassword: '變更密碼', signUp: '註冊', emailLogin: '使用電子郵件登入', loginWithOtherMethods: '使用其他方式登入', diff --git a/apps/frontend/src/modules/user/__tests__/index.test.ts b/apps/frontend/src/modules/user/__tests__/index.test.ts index c853cf9f..edf4e6c3 100644 --- a/apps/frontend/src/modules/user/__tests__/index.test.ts +++ b/apps/frontend/src/modules/user/__tests__/index.test.ts @@ -370,6 +370,7 @@ async function mountUser() { }), ElPopover: ElPopoverStub, ElSwitch: ElSwitchStub, + ElDivider: true, DcUserCenter: true, DcUserLoginGateway: defineComponent({ name: 'DcUserLoginGateway', @@ -395,6 +396,118 @@ async function mountUser() { }) } +describe('DcUser cloud account password link', () => { + beforeEach(() => { + vi.clearAllMocks() + createStores() + }) + + afterEach(() => { + vi.restoreAllMocks() + vi.unstubAllGlobals() + vi.unstubAllEnvs() + }) + + it.each([ + 'https://test-account.example/account/#change-password', + 'https://www.opentest.com/account/#change-password' + ])('opens a configured account page (%s)', async url => { + const openExternalBrowser = vi.fn().mockResolvedValue({ success: true }) + vi.stubGlobal('electronAPI', { + getServiceConfig: () => ({ auth: { changePasswordUrl: url } }), + openExternalBrowser + }) + const wrapper = await mountUser() + await flushPromises() + + const menu = wrapper.findAll('.menu-item-stub').map(item => item.attributes('data-text')) + expect(menu.slice(0, 3)).toEqual(['user.userCenter.title', 'user.changePassword', 'user.logout']) + await wrapper.get('[data-text="user.changePassword"]').trigger('click') + await flushPromises() + + expect(openExternalBrowser).toHaveBeenCalledExactlyOnceWith(url) + expect(mocks.loginGateway.open).not.toHaveBeenCalled() + wrapper.unmount() + }) + + it('hides the link in a browser build without desktop configuration', async () => { + const open = vi.spyOn(window, 'open').mockReturnValue(null) + vi.stubGlobal('electronAPI', undefined) + const wrapper = await mountUser() + await flushPromises() + + expect(wrapper.find('[data-text="user.changePassword"]').exists()).toBe(false) + expect(open).not.toHaveBeenCalled() + wrapper.unmount() + }) + + it.each([ + [undefined, 'missing result'], + [{ success: false }, 'failed result'] + ])('keeps the menu open when the browser link has a %s', async (result, _reason) => { + const openExternalBrowser = vi.fn().mockResolvedValue(result) + vi.stubGlobal('electronAPI', { + getServiceConfig: () => ({ auth: { changePasswordUrl: 'https://test-account.example/account/#change-password' } }), + openExternalBrowser + }) + const wrapper = await mountUser() + await flushPromises() + const popover = wrapper.findComponent({ name: 'ElPopover' }) + popover.vm.$emit('update:visible', true) + await nextTick() + + await wrapper.get('[data-text="user.changePassword"]').trigger('click') + await flushPromises() + expect(popover.props('visible')).toBe(true) + expect(mocks.messageError).toHaveBeenCalled() + wrapper.unmount() + }) + + it('keeps the menu open when opening the browser rejects', async () => { + const openExternalBrowser = vi.fn().mockRejectedValue(new Error('browser unavailable')) + vi.stubGlobal('electronAPI', { + getServiceConfig: () => ({ auth: { changePasswordUrl: 'https://test-account.example/account/#change-password' } }), + openExternalBrowser + }) + const wrapper = await mountUser() + await flushPromises() + const popover = wrapper.findComponent({ name: 'ElPopover' }) + popover.vm.$emit('update:visible', true) + await nextTick() + + await wrapper.get('[data-text="user.changePassword"]').trigger('click') + await flushPromises() + expect(popover.props('visible')).toBe(true) + expect(mocks.messageError).toHaveBeenCalled() + wrapper.unmount() + }) + + it('hides the link when Electron provides an invalid URL', async () => { + vi.stubGlobal('electronAPI', { + getServiceConfig: () => ({ auth: { changePasswordUrl: 'javascript:alert(1)' } }), + openExternalBrowser: vi.fn() + }) + const wrapper = await mountUser() + await flushPromises() + + expect(wrapper.find('[data-text="user.changePassword"]').exists()).toBe(false) + wrapper.unmount() + }) + + it.each([true, false])('hides the password link without a cloud login (authorized: %s)', async isAuthorized => { + createStores({ isAuthorized, isLogined: false }) + vi.stubGlobal('electronAPI', { + getServiceConfig: () => ({ auth: { changePasswordUrl: 'https://test-account.example/account/#change-password' } }), + openExternalBrowser: vi.fn() + }) + const wrapper = await mountUser() + await flushPromises() + + expect(wrapper.find('[data-text="user.changePassword"]').exists()).toBe(false) + wrapper.unmount() + }) +}) + describe('DcUser force-login gateway visibility', () => { beforeEach(() => { vi.clearAllMocks() diff --git a/apps/frontend/src/modules/user/index.vue b/apps/frontend/src/modules/user/index.vue index d4e1b1a2..d71a06b5 100644 --- a/apps/frontend/src/modules/user/index.vue +++ b/apps/frontend/src/modules/user/index.vue @@ -28,6 +28,21 @@ :text="editionName || $t('user.userCenter.title')" @click="openUserCenter" /> +