Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,5 @@
# side as of the last confirmed-consistent state. Both languages carry equal authority;
# after editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-09-21-provider-sign-in-flow.md
2026-09-21-provider-sign-in-flow.md: 1f22d85ecc5029a6332ba7ae52a12a8145c97331
2026-09-21-provider-sign-in-flow.zh.md: 8dbb8fe9194f14a993c8dc0d95816662bb9c4aa7
2026-09-21-provider-sign-in-flow.md: ba8bc36c54bcb3e1798c5cbb2fa0650740da04e3
2026-09-21-provider-sign-in-flow.zh.md: e21f656d1d1a792e1eacca4b579fa5cdafaa4d4e
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ Nothing in the page said which shape the deployment wanted, so the client could

**Under `window`, the provider is reached from a window of its own and the page never moves.** `openProviderSignIn(url)` opens it under a fixed name, so a second provider button replaces the first window instead of stacking another behind it.

**The session is the handoff, not a message between documents.** The landing window is this application's own `/oauth-result`, so it exchanges the provider's answer itself — the same `checkOauthToken` and `getProfile` a redirected document runs — which establishes the session in the origin's cookies, shared by both windows. `OauthResult` then reports by closing: a landing in a window this application opened is where the sign-in finishes, not where the application belongs ([the boot gate](../bug-fix/2026-09-21-auth-gate-boots-in-place.md) is what would otherwise boot a shell inside it, and the window that opened it is already waiting). The document that opened the window waits for that session with `awaitProviderSession()`, reading the profile until the API answers one, and then continues exactly as it does after the email form: read the profile, move off the authentication surface, and let the gate boot.
**The session is the handoff, not a message between documents.** The landing window is this application's own `/oauth-result`, so it exchanges the provider's answer itself — the same `checkOauthToken` and `getProfile` a redirected document runs — which establishes the session in the origin's cookies, shared by both windows. `OauthResult` then reports by closing: a landing in a window this application opened is where the sign-in finishes, not where the application belongs ([the boot gate](../bug-fix/2026-09-21-auth-gate-boots-in-place.md) is what would otherwise boot a shell inside it, and the window that opened it is already waiting). The opener does not mark that window: the sign-in starts at `aeven.io/oauth/<provider>`, whose `Cross-Origin-Opener-Policy: same-origin` clears both `window.opener` and `window.name` on the way back, so a landing without either asks over the origin's `BroadcastChannel` whether a page is waiting on a provider window and closes only when one claims it; unclaimed, it goes on to the application itself, so exactly one window boots ([issue 773](https://github.com/Aeven-AI/Aeven/issues/773)). The waiting page keeps claiming for 30 s after its own read of the session, because the landing announces itself only after its profile read. A browser that refuses the close shows a signed-in note instead of a second shell. The document that opened the window waits for that session with `awaitProviderSession()`, reading the profile until the API answers one, and then continues exactly as it does after the email form: read the profile, move off the authentication surface, and let the gate boot.

**A refusal is still shown where a refused sign-in is shown.** A landing that carries an error, or one whose exchange fails, leaves the apology on screen in the window that opened, exactly as `redirect` shows it; this document keeps waiting, and the reader closing that window leaves them on the sign-in screen with the button in their hands.

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ Status: implemented

**在 `window` 下,提供方由独立窗口抵达,页面本身永不移动。** `openProviderSignIn(url)` 以固定名称打开该窗口,因此读者第二次按下提供方按钮时替换第一个窗口,而不是在其后叠出第二个。

**交接靠的是会话,而不是文档之间的消息。** 落地窗口就是本应用自己的 `/oauth-result`,因此它自行交换提供方的回答——与跳转文档所运行的同一套 `checkOauthToken` 与 `getProfile`——从而在该 origin 的 cookie 中建立会话,两个窗口共享它。随后 `OauthResult` 以关闭窗口来报告:由本应用打开的窗口中的落地,是登录完成之处,而不是应用该存在之处(否则[启动 gate](../bug-fix/2026-09-21-auth-gate-boots-in-place.zh.md) 会在其中启动一个外壳,而打开它的那个文档已经在等待了)。打开该窗口的文档用 `awaitProviderSession()` 等待该会话,反复读取 profile 直到 API 给出一个,随后完全按邮件表单之后的方式继续:读取 profile、离开认证界面,并让 gate 启动。
**交接靠的是会话,而不是文档之间的消息。** 落地窗口就是本应用自己的 `/oauth-result`,因此它自行交换提供方的回答——与跳转文档所运行的同一套 `checkOauthToken` 与 `getProfile`——从而在该 origin 的 cookie 中建立会话,两个窗口共享它。随后 `OauthResult` 以关闭窗口来报告:由本应用打开的窗口中的落地,是登录完成之处,而不是应用该存在之处(否则[启动 gate](../bug-fix/2026-09-21-auth-gate-boots-in-place.zh.md) 会在其中启动一个外壳,而打开它的那个文档已经在等待了)。opener 不标记该窗口:登录从 `aeven.io/oauth/<provider>` 开始,其 `Cross-Origin-Opener-Policy: same-origin` 会在返回途中清除 `window.opener` 与 `window.name`,因此两者都没有的落地会通过该 origin 的 `BroadcastChannel` 询问是否有页面正在等待提供方窗口,只有被认领时才关闭;无人认领时它自己进入应用,所以只有一个窗口启动([issue 773](https://github.com/Aeven-AI/Aeven/issues/773))。等待的页面在自己读到会话后仍认领 30 秒,因为落地只在读取 profile 之后才宣告自己。拒绝关闭的浏览器显示已登录提示,而不是第二个外壳。打开该窗口的文档用 `awaitProviderSession()` 等待该会话,反复读取 profile 直到 API 给出一个,随后完全按邮件表单之后的方式继续:读取 profile、离开认证界面,并让 gate 启动。

**被拒绝仍在被拒绝登录所在之处呈现。** 携带错误的落地,或交换失败的落地,会把致歉留在打开它的那个窗口中,与 `redirect` 的呈现一致;本文档继续等待,而读者关闭那个窗口后,仍停留在登录界面、按钮就在手边。

Expand Down
1 change: 1 addition & 0 deletions packages/client/ui-auth-aeven/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
"devDependencies": {
"@aeven/client-ui-primitives": "workspace:^",
"@aeven/client-ui-theme": "workspace:^",
"@aeven/util-crypto": "workspace:^",
"@deepseek-ai/cordis": "workspace:^",
"@types/react": "~18.3.1",
"@types/react-dom": "~18.3.0",
Expand Down
102 changes: 94 additions & 8 deletions packages/client/ui-auth-aeven/src/client/auth/services/oauth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,9 @@
* @module
*/

import { randomUUID } from '@aeven/util-crypto'
import { getProfile } from './api.ts'
import type { OAuthFlow } from './config.ts'

/** How long this document waits between reads of the session. */
const SESSION_POLL_MS = 1000
Expand Down Expand Up @@ -48,6 +50,31 @@ export const PROVIDER_SIGN_IN_ENDED_EVENT = 'aeven:provider-sign-in-ended'
/** Window features for a provider's consent form. */
const PROVIDER_WINDOW_FEATURES = 'popup=yes,width=520,height=760'

/** Name of the window a provider sign-in opens. */
const PROVIDER_WINDOW_NAME = 'aeven-provider-signin'

/** Channel within this origin that a provider landing and the page waiting on it share. */
const LANDING_CHANNEL = 'aeven-provider-landing'

/**
* How long a landing that cannot tell whether it is a provider window waits for
* a waiting page to claim it; a waiting page answers within milliseconds.
*/
const LANDING_CLAIM_MS = 1000

/**
* How long a page keeps claiming landings after its wait ended on the session:
* the landing announces itself only after its profile read, which can come
* after this page's own read of the session.
*/
const CLAIM_LINGER_MS = 30_000

/** What a landing and a waiting page say on {@link LANDING_CHANNEL}. */
type LandingMessage = { readonly type: 'landed'; readonly id: string } | { readonly type: 'claimed'; readonly id: string }

/** How a provider landing finishes: it closes and the waiting page boots, or it goes on to the app itself. */
export type ProviderLandingFinish = 'close' | 'navigate'

/**
* Open the provider in a window of its own.
*
Expand All @@ -56,19 +83,75 @@ const PROVIDER_WINDOW_FEATURES = 'popup=yes,width=520,height=760'
* @param url - the provider's sign-in URL as the deployment states it.
*/
export function openProviderSignIn(url: string): void {
window.open(url, 'aeven-provider-signin', PROVIDER_WINDOW_FEATURES)
window.open(url, PROVIDER_WINDOW_NAME, PROVIDER_WINDOW_FEATURES)
}

/**
* Whether this document is the landing window of a provider sign-in.
* Decide how a provider landing finishes, so exactly one window boots the app.
*
* A window this application opened has an opener; a tab the reader navigated
* themselves does not. The landing reports itself by closing, so the
* distinction only decides who closes whom.
* @returns true when another document opened this one.
* A landing that still has its opener or the provider window's name is that
* window. A provider's pages can sever both on the way back (a
* `Cross-Origin-Opener-Policy` switch clears the opener and the name), so under
* the `window` flow a landing that has neither announces itself on
* {@link LANDING_CHANNEL} and closes only when a page waiting on a provider
* window claims it; unclaimed, no page will boot, and it goes on to the app.
* Every landing also announces itself, so the waiting page boots without waiting
* for its next read of the session. A `redirect` landing without an opener is
* the reader's own tab and goes on at once.
* @param flow - the deployment's provider flow.
* @returns `close` when a waiting page boots the app, `navigate` when this landing must.
*/
export async function providerLandingFinish(flow: OAuthFlow): Promise<ProviderLandingFinish> {
const providerWindow = window.opener !== null || window.name === PROVIDER_WINDOW_NAME
if (!providerWindow && flow !== 'window') return 'navigate'
const claimed = await announceLanding(providerWindow ? 0 : LANDING_CLAIM_MS)
return providerWindow || claimed ? 'close' : 'navigate'
}

/**
* Announce this landing to the pages of this origin.
* @param waitMs - how long to wait for a waiting page's claim.
* @returns whether a waiting page claimed the landing in time; false where the browser has no channel.
*/
function announceLanding(waitMs: number): Promise<boolean> {
if (typeof BroadcastChannel === 'undefined') return Promise.resolve(false)
const channel = new BroadcastChannel(LANDING_CHANNEL)
const id = randomUUID()
return new Promise<boolean>((resolve) => {
const settle = (claimed: boolean): void => {
clearTimeout(timer)
channel.close()
resolve(claimed)
}
channel.onmessage = (event: MessageEvent<LandingMessage>): void => {
if (event.data.type === 'claimed' && event.data.id === id) settle(true)
}
const timer = setTimeout(() => { settle(false) }, waitMs)
channel.postMessage({ type: 'landed', id } satisfies LandingMessage)
})
}

/**
* Claim the landings announced on {@link LANDING_CHANNEL} while a provider
* window is out, so they close instead of booting the app a second time.
* @param onLanded - called for a landing while the wait is armed.
* @returns ends the claim: at once for an abandoned wait, after
* {@link CLAIM_LINGER_MS} for one that ended on the session.
*/
export function isProviderLanding(): boolean {
return window.opener !== null
function claimLandings(onLanded: () => void): (abandoned: boolean) => void {
if (typeof BroadcastChannel === 'undefined') return () => {}
const channel = new BroadcastChannel(LANDING_CHANNEL)
let armed = true
channel.onmessage = (event: MessageEvent<LandingMessage>): void => {
if (event.data.type !== 'landed') return
channel.postMessage({ type: 'claimed', id: event.data.id } satisfies LandingMessage)
if (armed) onLanded()
}
return (abandoned) => {
armed = false
if (abandoned) channel.close()
else setTimeout(() => { channel.close() }, CLAIM_LINGER_MS)
}
}

/**
Expand All @@ -94,6 +177,8 @@ export async function awaitProviderSession(signal: AbortSignal): Promise<boolean
let reported = false
const onReported = (): void => { reported = true }
window.addEventListener(PROVIDER_SIGNED_IN_EVENT, onReported)
// A landing that announces itself has established the session, as a shell's report has.
const endClaim = claimLandings(() => { window.dispatchEvent(new Event(PROVIDER_SIGNED_IN_EVENT)) })
try {
// oxlint-disable-next-line typescript/no-unnecessary-condition -- the abort and sign-in listeners can run during either await.
while (!signal.aborted && !reported && !await hasSession()) {
Expand All @@ -114,6 +199,7 @@ export async function awaitProviderSession(signal: AbortSignal): Promise<boolean
return !signal.aborted
} finally {
window.removeEventListener(PROVIDER_SIGNED_IN_EVENT, onReported)
endClaim(signal.aborted)
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1417,8 +1417,8 @@ export function Authenticate(props: AuthenticateProps): React.JSX.Element {
* they came from.
* @returns the settled navigation.
*/
const finishMfa = (): Promise<void> => api.getProfile().then(() => {
if (oauth.isProviderLanding()) window.close()
const finishMfa = (): Promise<void> => api.getProfile().then(async () => {
if (await oauth.providerLandingFinish(configService.oauthFlow()) === 'close') window.close()
else routeService.navigateRoute(referrer || '/')
})

Expand Down
35 changes: 23 additions & 12 deletions packages/client/ui-auth-aeven/src/client/auth/views/OauthResult.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@
* The screen a social sign-in returns to.
*
* The provider redirects the browser here with either an error or a
* session/challenge pair. A pair is exchanged for a session and the reader is
* sent on to where they came from; anything else leaves the apology on screen.
* session/challenge pair. A pair is exchanged for a session; a provider window
* then closes so the page waiting on it boots the app, and any other landing
* sends the reader on to where they came from. Anything else leaves the apology
* on screen.
* Rendering matches the Aeven client exactly.
* @module
*/
Expand All @@ -15,7 +17,8 @@ import * as api from '../services/api.ts'
import { t } from '../../locales.ts'
import * as events from '../services/events.ts'
import { navigateRoute, AUTH_ROUTES } from '../services/routes.ts'
import { isProviderLanding } from '../services/oauth.ts'
import { oauthFlow } from '../services/config.ts'
import { providerLandingFinish } from '../services/oauth.ts'
import { href } from '../services/utility.ts'
import { session, storage } from '../services/session.ts'

Expand All @@ -39,8 +42,11 @@ function currentReferrer(): string {
return storage.getItem('authReferrer') ?? AUTH_ROUTES.home
}

/** How long a landing that asked to close stays before it counts the close as refused. */
const CLOSE_REFUSED_MS = 500

export function OauthResult(props: OauthResultProps): React.JSX.Element | null {
const [status, setStatus] = useState<'error' | null>(null)
const [status, setStatus] = useState<'error' | 'signed-in' | null>(null)
const referrer = useRef(currentReferrer())

useEffect(() => {
Expand Down Expand Up @@ -69,13 +75,16 @@ export function OauthResult(props: OauthResultProps): React.JSX.Element | null {
await api.checkOauthToken(oAuthSession, oAuthChallenge)
await api.getProfile()
if (cancelled) return
// A landing in a window this application opened is where the sign-in
// finishes, not where the application belongs: the window that opened it
// is waiting on the session this call just established, and it boots the
// shell there. A landing the reader navigated to themselves goes on to
// the screen they came from.
if (isProviderLanding()) {
// A landing in a provider window is where the sign-in finishes, not where
// the application belongs: the page waiting on that window boots the shell.
// A landing no page waits on goes on to the screen the reader came from.
const finish = await providerLandingFinish(oauthFlow())
// oxlint-disable-next-line typescript/no-unnecessary-condition -- the effect's cleanup can run during the await.
if (cancelled) return
if (finish === 'close') {
window.close()
// A browser that refuses the close leaves this note, never a second shell.
setTimeout(() => { if (!cancelled) setStatus('signed-in') }, CLOSE_REFUSED_MS)
} else {
navigateRoute(href(referrer.current))
}
Expand All @@ -95,15 +104,17 @@ export function OauthResult(props: OauthResultProps): React.JSX.Element | null {
}, [props.match.params])

if (status === null) return null
const heading = status === 'error' ? t('oauth.failedHeading') : t('oauth.signedInHeading')
const body = status === 'error' ? t('oauth.failedBody') : t('oauth.signedInBody')
return (
<div className="oauth-result view">
<div id="main-content" className="main-content">
<div className="content-container">
<div className="message-container">
<div className="message">
<span className="txt-header">{t('oauth.failedHeading')}</span>
<span className="txt-header">{heading}</span>
<span className="txt-content">
<span>{t('oauth.failedBody')}</span>
<span>{body}</span>
</span>
</div>
</div>
Expand Down
6 changes: 6 additions & 0 deletions packages/client/ui-auth-aeven/src/client/locales.ts
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,8 @@ export const zh = {
'modal.tooManyCodeAttempts': '你输入错误验证码的次数过多。请 15 分钟后再试',
'oauth.failedHeading': '出错了!',
'oauth.failedBody': '你好,似乎出了点问题。请重试',
'oauth.signedInHeading': '已登录',
'oauth.signedInBody': 'Æven 会在你开始登录的窗口中继续。可以关闭此窗口了。',
'name.title': '你好!',
'name.prompt': '在我们开始聊天之前,我该怎么称呼你?',
'name.promptAnonymous': '在我这里你不必匿名 ;)',
Expand Down Expand Up @@ -256,6 +258,8 @@ export const en: Record<AuthAevenKey, string> = {
'modal.tooManyCodeAttempts': 'You entered a wrong code too many times. Please try again in 15 minutes',
'oauth.failedHeading': 'Oops!',
'oauth.failedBody': 'Hi, It seems i have an issue. Please try again',
'oauth.signedInHeading': 'You’re signed in',
'oauth.signedInBody': 'Æven continues in the window you started from. You can close this window.',
'name.title': 'Hi there!',
'name.prompt': 'Before we continue to chat, how should I call you?',
'name.promptAnonymous': "You don't have to be anonymous with me ;)",
Expand Down Expand Up @@ -382,6 +386,8 @@ export const es: Record<AuthAevenKey, string> = {
'modal.tooManyCodeAttempts': 'Introdujiste un código incorrecto demasiadas veces. Inténtalo de nuevo en 15 minutos',
'oauth.failedHeading': '¡Vaya!',
'oauth.failedBody': 'Hola, parece que tengo un problema. Inténtalo de nuevo',
'oauth.signedInHeading': 'Sesión iniciada',
'oauth.signedInBody': 'Æven continúa en la ventana desde la que empezaste. Puedes cerrar esta ventana.',
'name.title': '¡Hola!',
'name.prompt': 'Antes de seguir chateando, ¿cómo quieres que te llame?',
'name.promptAnonymous': 'Conmigo no tienes que ser anónimo ;)',
Expand Down
Loading