fix: tighten pending oauth email routing and binding state
This commit is contained in:
@@ -208,6 +208,12 @@ export type PendingOAuthExchangeResponse = PendingOAuthBindLoginResponse
|
||||
|
||||
export interface PendingOAuthCreateAccountResponse extends OAuthTokenResponse {}
|
||||
|
||||
export interface PendingOAuthSendVerifyCodeResponse extends SendVerifyCodeResponse {
|
||||
auth_result?: string
|
||||
provider?: string
|
||||
redirect?: string
|
||||
}
|
||||
|
||||
export type OAuthCompletionKind = 'login' | 'bind'
|
||||
|
||||
export interface OAuthAdoptionDecision {
|
||||
@@ -451,8 +457,8 @@ export async function sendVerifyCode(
|
||||
|
||||
export async function sendPendingOAuthVerifyCode(
|
||||
request: SendVerifyCodeRequest
|
||||
): Promise<SendVerifyCodeResponse> {
|
||||
const { data } = await apiClient.post<SendVerifyCodeResponse>(
|
||||
): Promise<PendingOAuthSendVerifyCodeResponse> {
|
||||
const { data } = await apiClient.post<PendingOAuthSendVerifyCodeResponse>(
|
||||
'/auth/oauth/pending/send-verify-code',
|
||||
request
|
||||
)
|
||||
|
||||
@@ -209,7 +209,12 @@ function getBindingStatus(provider: UserAuthProvider): boolean {
|
||||
|
||||
function getBindingStatusForUser(user: User | null | undefined, provider: UserAuthProvider): boolean {
|
||||
if (provider === 'email') {
|
||||
return typeof user?.email_bound === 'boolean' ? user.email_bound : Boolean(user?.email)
|
||||
if (typeof user?.email_bound === 'boolean') {
|
||||
return user.email_bound
|
||||
}
|
||||
const nested = user?.auth_bindings?.email ?? user?.identity_bindings?.email
|
||||
const normalized = normalizeBindingStatus(nested)
|
||||
return normalized ?? false
|
||||
}
|
||||
|
||||
const directFlag = user?.[`${provider}_bound` as keyof User]
|
||||
|
||||
@@ -301,4 +301,27 @@ describe('ProfileIdentityBindingsSection', () => {
|
||||
expect(wrapper.get('[data-testid="profile-binding-email-status"]').text()).toBe('Bound')
|
||||
expect(authStore.user?.email).toBe('bound@example.com')
|
||||
})
|
||||
|
||||
it('keeps the email binding form visible when the user still lacks an email identity', () => {
|
||||
const wrapper = mount(ProfileIdentityBindingsSection, {
|
||||
global: {
|
||||
plugins: [pinia],
|
||||
},
|
||||
props: {
|
||||
user: createUser({
|
||||
email: 'legacy@example.com',
|
||||
email_bound: false,
|
||||
auth_bindings: {
|
||||
email: { bound: false },
|
||||
},
|
||||
}),
|
||||
linuxdoEnabled: false,
|
||||
oidcEnabled: false,
|
||||
wechatEnabled: false,
|
||||
},
|
||||
})
|
||||
|
||||
expect(wrapper.get('[data-testid="profile-binding-email-status"]').text()).toBe('Not bound')
|
||||
expect(wrapper.get('[data-testid="profile-binding-email-input"]').exists()).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -179,6 +179,8 @@ import { useAuthStore, useAppStore } from '@/stores'
|
||||
import {
|
||||
persistOAuthTokenContext,
|
||||
getPublicSettings,
|
||||
isOAuthLoginCompletion,
|
||||
type PendingOAuthSendVerifyCodeResponse,
|
||||
sendPendingOAuthVerifyCode,
|
||||
sendVerifyCode,
|
||||
} from '@/api/auth'
|
||||
@@ -216,10 +218,13 @@ type PendingAuthSessionSummary = {
|
||||
redirect?: string
|
||||
}
|
||||
type PendingOAuthCreateAccountResponse = {
|
||||
auth_result?: string
|
||||
access_token: string
|
||||
refresh_token?: string
|
||||
expires_in?: number
|
||||
token_type?: string
|
||||
provider?: string
|
||||
redirect?: string
|
||||
}
|
||||
|
||||
const email = ref<string>('')
|
||||
@@ -353,6 +358,46 @@ function onTurnstileError(): void {
|
||||
errors.value.turnstile = t('auth.turnstileFailed')
|
||||
}
|
||||
|
||||
function isPendingOAuthFlow(): boolean {
|
||||
return Boolean(pendingProvider.value.trim())
|
||||
}
|
||||
|
||||
function shouldBypassRegistrationEmailPolicy(): boolean {
|
||||
return isPendingOAuthFlow() || Boolean(pendingAuthToken.value.trim())
|
||||
}
|
||||
|
||||
function resolvePendingOAuthCallbackRoute(provider: string): string {
|
||||
switch (provider.trim().toLowerCase()) {
|
||||
case 'linuxdo':
|
||||
return '/auth/linuxdo/callback'
|
||||
case 'oidc':
|
||||
return '/auth/oidc/callback'
|
||||
case 'wechat':
|
||||
return '/auth/wechat/callback'
|
||||
default:
|
||||
return '/auth/callback'
|
||||
}
|
||||
}
|
||||
|
||||
function isPendingOAuthSessionResponse(data: PendingOAuthCreateAccountResponse): boolean {
|
||||
return data.auth_result === 'pending_session'
|
||||
}
|
||||
|
||||
function getPendingOAuthSendCodeSessionResponse(
|
||||
data: PendingOAuthSendVerifyCodeResponse,
|
||||
): PendingOAuthSendVerifyCodeResponse | null {
|
||||
return data.auth_result === 'pending_session' ? data : null
|
||||
}
|
||||
|
||||
function persistPendingOAuthSession(provider: string, redirect?: string): void {
|
||||
authStore.setPendingAuthSession({
|
||||
token: pendingAuthToken.value,
|
||||
token_field: pendingAuthTokenField.value,
|
||||
provider: provider.trim() || pendingProvider.value.trim(),
|
||||
redirect: redirect || pendingRedirect.value || undefined,
|
||||
})
|
||||
}
|
||||
|
||||
// ==================== Send Code ====================
|
||||
|
||||
async function sendCode(): Promise<void> {
|
||||
@@ -360,7 +405,7 @@ async function sendCode(): Promise<void> {
|
||||
errorMessage.value = ''
|
||||
|
||||
try {
|
||||
if (!pendingAuthToken.value && !isRegistrationEmailSuffixAllowed(email.value, registrationEmailSuffixWhitelist.value)) {
|
||||
if (!shouldBypassRegistrationEmailPolicy() && !isRegistrationEmailSuffixAllowed(email.value, registrationEmailSuffixWhitelist.value)) {
|
||||
errorMessage.value = buildEmailSuffixNotAllowedMessage()
|
||||
appStore.showError(errorMessage.value)
|
||||
return
|
||||
@@ -372,10 +417,25 @@ async function sendCode(): Promise<void> {
|
||||
// 优先使用重发时新获取的 token(因为初始 token 可能已被使用)
|
||||
turnstile_token: resendTurnstileToken.value || initialTurnstileToken.value || undefined
|
||||
} as Parameters<typeof sendVerifyCode>[0]
|
||||
const response = pendingAuthToken.value
|
||||
const response = isPendingOAuthFlow()
|
||||
? await sendPendingOAuthVerifyCode(requestPayload)
|
||||
: await sendVerifyCode(requestPayload)
|
||||
|
||||
const pendingSendCodeSession = isPendingOAuthFlow()
|
||||
? getPendingOAuthSendCodeSessionResponse(response as PendingOAuthSendVerifyCodeResponse)
|
||||
: null
|
||||
if (pendingSendCodeSession) {
|
||||
sessionStorage.removeItem('register_data')
|
||||
persistPendingOAuthSession(
|
||||
pendingSendCodeSession.provider || pendingProvider.value,
|
||||
pendingSendCodeSession.redirect,
|
||||
)
|
||||
await router.push(
|
||||
resolvePendingOAuthCallbackRoute(pendingSendCodeSession.provider || pendingProvider.value),
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
codeSent.value = true
|
||||
startCountdown(response.countdown)
|
||||
|
||||
@@ -438,13 +498,13 @@ async function handleVerify(): Promise<void> {
|
||||
isLoading.value = true
|
||||
|
||||
try {
|
||||
if (!isRegistrationEmailSuffixAllowed(email.value, registrationEmailSuffixWhitelist.value)) {
|
||||
if (!shouldBypassRegistrationEmailPolicy() && !isRegistrationEmailSuffixAllowed(email.value, registrationEmailSuffixWhitelist.value)) {
|
||||
errorMessage.value = buildEmailSuffixNotAllowedMessage()
|
||||
appStore.showError(errorMessage.value)
|
||||
return
|
||||
}
|
||||
|
||||
if (pendingProvider.value) {
|
||||
if (isPendingOAuthFlow()) {
|
||||
const { data } = await apiClient.post<PendingOAuthCreateAccountResponse>(
|
||||
'/auth/oauth/pending/create-account',
|
||||
{
|
||||
@@ -456,6 +516,16 @@ async function handleVerify(): Promise<void> {
|
||||
adopt_avatar: pendingAdoptionDecision.value?.adoptAvatar
|
||||
}
|
||||
)
|
||||
if (isPendingOAuthSessionResponse(data)) {
|
||||
sessionStorage.removeItem('register_data')
|
||||
persistPendingOAuthSession(data.provider || pendingProvider.value, data.redirect)
|
||||
await router.push(resolvePendingOAuthCallbackRoute(data.provider || pendingProvider.value))
|
||||
return
|
||||
}
|
||||
if (!isOAuthLoginCompletion(data)) {
|
||||
throw new Error(t('auth.verifyFailed'))
|
||||
}
|
||||
|
||||
persistOAuthTokenContext(data)
|
||||
await authStore.setToken(data.access_token)
|
||||
authStore.clearPendingAuthSession?.()
|
||||
|
||||
@@ -8,6 +8,7 @@ const {
|
||||
showErrorMock,
|
||||
registerMock,
|
||||
setTokenMock,
|
||||
setPendingAuthSessionMock,
|
||||
clearPendingAuthSessionMock,
|
||||
getPublicSettingsMock,
|
||||
sendVerifyCodeMock,
|
||||
@@ -21,6 +22,7 @@ const {
|
||||
showErrorMock: vi.fn(),
|
||||
registerMock: vi.fn(),
|
||||
setTokenMock: vi.fn(),
|
||||
setPendingAuthSessionMock: vi.fn(),
|
||||
clearPendingAuthSessionMock: vi.fn(),
|
||||
getPublicSettingsMock: vi.fn(),
|
||||
sendVerifyCodeMock: vi.fn(),
|
||||
@@ -68,6 +70,7 @@ vi.mock('@/stores', () => ({
|
||||
pendingAuthSession: authStoreState.pendingAuthSession,
|
||||
register: (...args: any[]) => registerMock(...args),
|
||||
setToken: (...args: any[]) => setTokenMock(...args),
|
||||
setPendingAuthSession: (...args: any[]) => setPendingAuthSessionMock(...args),
|
||||
clearPendingAuthSession: (...args: any[]) => clearPendingAuthSessionMock(...args),
|
||||
}),
|
||||
useAppStore: () => ({
|
||||
@@ -100,6 +103,7 @@ describe('EmailVerifyView', () => {
|
||||
showErrorMock.mockReset()
|
||||
registerMock.mockReset()
|
||||
setTokenMock.mockReset()
|
||||
setPendingAuthSessionMock.mockReset()
|
||||
clearPendingAuthSessionMock.mockReset()
|
||||
getPublicSettingsMock.mockReset()
|
||||
sendVerifyCodeMock.mockReset()
|
||||
@@ -196,6 +200,97 @@ describe('EmailVerifyView', () => {
|
||||
expect(showErrorMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('uses the pending oauth verify-code endpoint when auth store only carries the pending provider', async () => {
|
||||
authStoreState.pendingAuthSession = {
|
||||
token: '',
|
||||
token_field: 'pending_oauth_token',
|
||||
provider: 'oidc',
|
||||
redirect: '/profile',
|
||||
}
|
||||
getPublicSettingsMock.mockResolvedValue({
|
||||
turnstile_enabled: false,
|
||||
turnstile_site_key: '',
|
||||
site_name: 'Sub2API',
|
||||
registration_email_suffix_whitelist: ['allowed.com'],
|
||||
})
|
||||
sessionStorage.setItem(
|
||||
'register_data',
|
||||
JSON.stringify({
|
||||
email: 'fresh@example.com',
|
||||
password: 'secret-123',
|
||||
})
|
||||
)
|
||||
|
||||
mount(EmailVerifyView, {
|
||||
global: {
|
||||
stubs: {
|
||||
AuthLayout: { template: '<div><slot /><slot name="footer" /></div>' },
|
||||
Icon: true,
|
||||
TurnstileWidget: true,
|
||||
transition: false,
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
await flushPromises()
|
||||
|
||||
expect(sendPendingOAuthVerifyCodeMock).toHaveBeenCalledWith({
|
||||
email: 'fresh@example.com',
|
||||
pending_oauth_token: undefined,
|
||||
})
|
||||
expect(sendVerifyCodeMock).not.toHaveBeenCalled()
|
||||
expect(showErrorMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('returns to the oauth callback flow when pending send-code detects an existing account email', async () => {
|
||||
authStoreState.pendingAuthSession = {
|
||||
token: '',
|
||||
token_field: 'pending_oauth_token',
|
||||
provider: 'oidc',
|
||||
redirect: '/profile/security',
|
||||
}
|
||||
getPublicSettingsMock.mockResolvedValue({
|
||||
turnstile_enabled: false,
|
||||
turnstile_site_key: '',
|
||||
site_name: 'Sub2API',
|
||||
registration_email_suffix_whitelist: ['allowed.com'],
|
||||
})
|
||||
sendPendingOAuthVerifyCodeMock.mockResolvedValue({
|
||||
auth_result: 'pending_session',
|
||||
provider: 'oidc',
|
||||
redirect: '/profile/security',
|
||||
})
|
||||
sessionStorage.setItem(
|
||||
'register_data',
|
||||
JSON.stringify({
|
||||
email: 'fresh@example.com',
|
||||
password: 'secret-123',
|
||||
})
|
||||
)
|
||||
|
||||
mount(EmailVerifyView, {
|
||||
global: {
|
||||
stubs: {
|
||||
AuthLayout: { template: '<div><slot /><slot name="footer" /></div>' },
|
||||
Icon: true,
|
||||
TurnstileWidget: true,
|
||||
transition: false,
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
await flushPromises()
|
||||
|
||||
expect(setPendingAuthSessionMock).toHaveBeenCalledWith({
|
||||
token: '',
|
||||
token_field: 'pending_oauth_token',
|
||||
provider: 'oidc',
|
||||
redirect: '/profile/security',
|
||||
})
|
||||
expect(pushMock).toHaveBeenCalledWith('/auth/oidc/callback')
|
||||
expect(showErrorMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('submits pending auth account creation when session storage has no pending metadata but auth store does', async () => {
|
||||
authStoreState.pendingAuthSession = {
|
||||
token: 'pending-token-1',
|
||||
@@ -252,6 +347,70 @@ describe('EmailVerifyView', () => {
|
||||
expect(registerMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('returns to the oauth callback flow when pending account creation becomes bind-login', async () => {
|
||||
authStoreState.pendingAuthSession = {
|
||||
token: '',
|
||||
token_field: 'pending_oauth_token',
|
||||
provider: 'oidc',
|
||||
redirect: '/profile/security',
|
||||
}
|
||||
getPublicSettingsMock.mockResolvedValue({
|
||||
turnstile_enabled: false,
|
||||
turnstile_site_key: '',
|
||||
site_name: 'Sub2API',
|
||||
registration_email_suffix_whitelist: ['allowed.com'],
|
||||
})
|
||||
sessionStorage.setItem(
|
||||
'register_data',
|
||||
JSON.stringify({
|
||||
email: 'fresh@example.com',
|
||||
password: 'secret-123',
|
||||
})
|
||||
)
|
||||
apiClientPostMock.mockResolvedValue({
|
||||
data: {
|
||||
auth_result: 'pending_session',
|
||||
provider: 'oidc',
|
||||
step: 'bind_login_required',
|
||||
redirect: '/profile/security',
|
||||
email: 'fresh@example.com',
|
||||
},
|
||||
})
|
||||
|
||||
const wrapper = mount(EmailVerifyView, {
|
||||
global: {
|
||||
stubs: {
|
||||
AuthLayout: { template: '<div><slot /><slot name="footer" /></div>' },
|
||||
Icon: true,
|
||||
TurnstileWidget: true,
|
||||
transition: false,
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
await flushPromises()
|
||||
await wrapper.get('#code').setValue('123456')
|
||||
await wrapper.get('form').trigger('submit.prevent')
|
||||
await flushPromises()
|
||||
|
||||
expect(apiClientPostMock).toHaveBeenCalledWith('/auth/oauth/pending/create-account', {
|
||||
email: 'fresh@example.com',
|
||||
password: 'secret-123',
|
||||
verify_code: '123456',
|
||||
})
|
||||
expect(setPendingAuthSessionMock).toHaveBeenCalledWith({
|
||||
token: '',
|
||||
token_field: 'pending_oauth_token',
|
||||
provider: 'oidc',
|
||||
redirect: '/profile/security',
|
||||
})
|
||||
expect(pushMock).toHaveBeenCalledWith('/auth/oidc/callback')
|
||||
expect(setTokenMock).not.toHaveBeenCalled()
|
||||
expect(persistOAuthTokenContextMock).not.toHaveBeenCalled()
|
||||
expect(clearPendingAuthSessionMock).not.toHaveBeenCalled()
|
||||
expect(showSuccessMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('keeps the normal email registration flow unchanged', async () => {
|
||||
sessionStorage.setItem(
|
||||
'register_data',
|
||||
|
||||
Reference in New Issue
Block a user