Skip to content

Commit f35b361

Browse files
fix(console): the sign-in page finishes the mobile sign-in hand-off instead of landing on a missing Console page (#29979)
<!-- claude-projects-attribution: {"github_login":"os-support-ai"} --> _Requested by **Yibo Wang** · [project thread](https://claude.ai/code/project/chan_01BVUyyPie8gHwoPM18iABwB?thread=cmsg_01BVUyyPie8gHwoPM18iABwB9ZFKq8kvUEM1zfaJkpDrs7)_ Fixes #29971 ## 维护者速读 - **改了什么**:Console 的登录页(和注册页)在 `?redirect=` 恰好指向移动端 hand-off 路由时,登录后直接用脚本跳过去(不再拼进 `/_console`),并且排在选组织之前;浏览器里已有的会话若超过 5 分钟,先显示登录表单,重新登录后再跳。 - **为什么改**:移动端在系统浏览器里打开登录页完成 Google 等登录后,本该跳到 hand-off 拿 302 回 App,现在却落在「页面不存在」,服务端在 18.3.0 已上线的那一半没人能用到。 - **风险与回滚**:只认 hand-off 这一条路径(同源、同 auth base、路径完全相等),其他所有 redirect 行为不变;回滚即 revert 本 PR,登录页回到旧行为。 - **先看**:`ui/apps/console/src/pages/auth/handoffRedirect.ts`(`handoffNavigationTarget` 的匹配条件、`useHandoffRedirect` 的五分钟判定),`LoginPage.tsx` 登录后编排里新增的第 2 步。 - **两分钟验证**:`pnpm --dir ui exec vitest run apps/console/src/pages/auth/__tests__/signInHandoff-29971.test.tsx apps/console/src/pages/auth/__tests__/handoffRedirect-29971.test.ts`,预期 2 个文件、29 条全部通过。 - **需要你做的**:这是会话转移(auth)流程,请维护者审阅并合并本 PR。 Clause-②: no Metadata-protocol: none ## Design: the five-minute session **What the auth client exposes (measured).** `createAuthClient().getSession()` hands back the `session` object of better-auth's `get-session` answer as received, so the server's `createdAt` is there at runtime even though `AuthClientSession` does not declare it: a `Date` through better-auth's client JSON parser (it revives ISO dates), an ISO string through the raw-`fetch` stale-bearer retry. A sign-in answer is different: `/sign-in/email` answers `{ redirect, token, url, user }`, so after a password sign-in the provider holds `session: undefined` (two-factor and phone sign-ins hold `{ token }`). No new endpoint and no change to `@object-ui/auth` was needed. **The choice: re-authenticate on top of the old session, not sign it out first.** On a hand-off redirect, a session older than five minutes keeps the ordinary sign-in form on screen; signing in on it creates a new session, the sign-in answer sets this browser's session cookie to it, and the page forwards. Why not sign the old session out first: 1. `signOut()` in the auth client navigates to the provider's end-session URL whenever the server answers one (RP-initiated logout for a federated session). For a visitor whose stale session came from SSO, that takes the browser off the sign-in page and ends the hand-off attempt. 2. On Android, Custom Tabs share Chrome's cookies, which is exactly how a stale session arrives. Signing it out also signs the user out of the web Console in Chrome; signing in on top only replaces this browser's cookie. 3. It adds a request with its own failure leg (a sign-out that fails leaves the state unknown) and buys nothing: the hand-off route is the authority on freshness and refuses an old session itself. The cost, stated: the old session row is not revoked; it stays valid until it expires, with no cookie in this browser pointing at it. A visitor may sign in as a different account on that form; the hand-off then carries the account they signed in as. **How "older than five minutes" is decided.** Each session the page holds is judged once, when it arrives, in a layout effect (the clock is never read during render): with a `createdAt`, its age decides (`HANDOFF_SESSION_MAX_AGE_MS`, restating the route's `ONE_TIME_TOKEN_HANDOFF_SESSION_MAX_AGE_SECONDS`); without one, the session is fresh only if it is not the one the first session check answered, which means a sign-in on this page made it. A session found on arrival with no `createdAt`, or one not judged yet, holds the form. A wrong verdict on the page is never a security question (the route refuses on its own clock); it only decides between showing the form and forwarding to the route's own `401`. ## What changes - `ui/apps/console/src/pages/auth/handoffRedirect.ts` (new): `handoffNavigationTarget` answers the navigation target for a redirect that names the hand-off, or `null`. The route is built with the spec's `getAuthEndpointUrl(base, 'oneTimeTokenHandoff')` over the auth base every Console auth page uses (`VITE_SERVER_URL` + `/api/v1/auth`, the URL `App.tsx` hands `AuthProvider`). A match needs a root-relative redirect on this page's origin whose parsed path equals the route's path exactly; the answer is re-serialized from the parsed URL. `useHandoffRedirect` adds the five-minute verdict above. - `LoginPage.tsx`: the post-sign-in orchestration gains a step 2, after the OAuth `/oauth2/authorize` replay and before the organization steps: a hand-off target is navigated to once with `window.location.assign`, unprefixed; a session the route would refuse returns without navigating, and the page renders its form for it (the bootstrap probe for the sign-up offer runs for that visitor as for a signed-out one). Every other redirect keeps `withConsoleBase`. - `RegisterPage.tsx`: the same step in its post-sign-up orchestration (rules 1 to 4), so a user who follows "Sign up" from the system auth session ends on the hand-off too. - One `@object-ui/console` patch changeset. Rule 2 needs no code: the social buttons' default `callbackURL` is the current page, and neither page passes the hand-off as one; a pin holds that. ## Why The mobile shell (objectstack-ai/mobile#148) opens the Console's sign-in page in the system auth session because some providers refuse embedded WebViews. The server half (#29766) answers the hand-off with `302 SCHEME://…?token=T`, but the sign-in page treated the redirect as a Console route and the browser landed on a Console page that does not exist. ## Tests <details><summary>New pins (2 files, 29 tests)</summary> `pages/auth/__tests__/handoffRedirect-29971.test.ts` (the matcher and the verdict): - the route the spec names under the auth base; the hand-off path with its query answers itself, unprefixed; - CONTROL `/api/v1/data/x`, `/settings`, `/` answer `null`; - lookalikes answer `null`: `…/handoffX`, a trailing slash, an extra segment, `…/verify`, upper case, an encoded slash, the path under `/_console`; - a different base path (`/tenant-a/api/v1/auth`) both ways; - absolute, protocol-relative, backslash-smuggled and tab-smuggled URLs, and `javascript:`; - an auth base on another origin; - the five-minute window (4 min, exactly 5, 6 min, a week), a `Date` or an ISO string, a session without `createdAt` found on arrival vs made by a sign-in, an unreadable `createdAt`. `pages/auth/__tests__/signInHandoff-29971.test.tsx` (the real `AuthProvider` over a mock client, the Console mounted as the shipped embeddable build, `base href /_console/`): - rule 1: the hand-off is assigned unprefixed and lands on the route's path; CONTROL `/api/v1/data/x` lands on `/_console/api/v1/data/x`; a lookalike lands under `/_console`; an absolute `https://evil.example…` lands on `/_console/`; - rule 2: a provider sign-in's `callbackURL` and `errorCallbackURL` are this sign-in page, carrying the hand-off in `?redirect=`, and nothing navigates; - rule 3: several organizations with none active go to the hand-off, not `/organizations`; a single organization whose activation never answers still goes to the hand-off; - rule 4: a 6-minute-old session shows the form and does not navigate; a sign-in on that form forwards; a session found without `createdAt` is held; a visitor who arrives signed out is forwarded once signed in; CONTROL: an hour-old session on `?redirect=/settings` still forwards as today; - RegisterPage: a fresh session goes to the hand-off; CONTROL `/api/v1/data/x`; a 6-minute-old session shows the sign-up form and a sign-up on it forwards. </details> <details><summary>Ablation (the hand-off branch dropped)</summary> Run under `scripts/pm/os-verify-lock.sh` with `scripts/ablation-replace.mjs` on `LoginPage.tsx`: the anchor ` if (handoff.target) {` replaced by ` if (false && handoff.target) {` (anchor hits 1 → 0, blob `5339378f1236` → `98b3e8304e15`), then `pnpm --dir ui exec vitest run apps/console/src/pages/auth/__tests__/signInHandoff-29971.test.tsx -t LoginPage`: - `Tests 7 failed | 5 passed | 3 skipped (15)` (the 3 skipped are the RegisterPage pins, outside `-t LoginPage`). - Red: rule 1 "navigates to the hand-off unprefixed, outside the Console mount" (`assign` called twice, not once), both rule-3 pins (`expected './api/v1/auth/one-time-token/handoff?…' to be '/api/v1/auth/one-time-token/handoff?r…'`: the old `withConsoleBase` target, which lands under `/_console/`), and four rule-4 pins. - Green under the ablation, as they should be: the three rule-1 CONTROL/lookalike/absolute pins, rule 2, and the rule-4 CONTROL on `?redirect=/settings`. - Restored: blob back to `5339378f1236` (= HEAD), `git diff HEAD` empty. </details> ## Acceptance notes - **RegisterPage: handled.** The same step, rules 1 to 4, in its post-sign-up orchestration. Not changed: its `verificationCallbackURL`. When a deployment requires email verification, the verification mail's link still resolves `?redirect=` as a Console route. That link opens from the mail app, outside the system auth session the mobile shell is waiting on, so a hand-off from there could not return to the app anyway. Whether the shell wants a sign-up that needs verification to come back some other way is the mobile card's call, not this page's. - **`os serve` cannot register an app scheme (out of scope, server/cli lane).** `packages/cli` composes `AuthPlugin` without `trustedAppSchemes`, and neither a stack's config nor a settings key or env var reaches it (0 hits for `trustedAppSchemes` under `packages/cli` and `packages/runtime`). Measured on a stock `pnpm dev:crm` boot: a signed-in, same-origin `GET /api/v1/auth/one-time-token/handoff?redirect_uri=ai.objectos.mobile://auth/callback…` answers `400 VALIDATION_ERROR`, with the message: The "redirect_uri" scheme "ai.objectos.mobile" is not a registered app scheme, so no token is handed to it. A deployment registers the app schemes it hands sign-ins to in its auth configuration. That boot has no auth configuration that could register one. The live check below therefore used a local, measurement-only one-line patch to `packages/cli/src/commands/serve.ts`; it was never committed, and the source and the cli dist were restored afterwards. - **Drift risk.** `HANDOFF_SESSION_MAX_AGE_MS` restates plugin-auth's `ONE_TIME_TOKEN_HANDOFF_SESSION_MAX_AGE_SECONDS`, because that module is server-only and this card does not touch `packages/plugins/plugin-auth/**` or `packages/spec/**`. If the server window changes, the page's copy decides only whether a visitor sees the form or the route's own `401`; the route stays the authority. - **Fails closed.** With a `VITE_SERVER_URL` on another origin, the matcher answers `null` and the redirect keeps today's Console-route behaviour. A skewed client clock moves only the verdict on a session found on arrival (form vs the route's `401`); a session made by a sign-in on the page carries no `createdAt` and is judged as made here. - **Lint.** eslint on the touched files: 0 errors, 5 warnings. Four are the existing `react-hooks/set-state-in-effect` warnings in the two pages; one is new, the same rule (warn level), on the layout effect that records the verdict in `handoffRedirect.ts`. - **Type-check coverage of the new test files: not shown.** The Console `type-check` exited 0 and its tsconfig includes `src`, but a `--listFiles` count for the two new test files read 0, so I do not claim they are type-checked by that lane (vitest compiles them without type-checking). ## Verification All on head `c6ac92e1`; the builds and test runs under `scripts/pm/os-verify-lock.sh`, their exit codes read from its `VERDICT command-exit` line: | Check | Result | | --- | --- | | `pnpm --filter '@object-ui/console^...' build` (the closure) | exit 0 (9m32s) | | `pnpm --dir ui exec vitest run` on the two new files | 2 files, 29 / 29 passed | | `pnpm --filter @object-ui/console run build` then `run type-check` | exit 0 (2m55s) | | `node ui/scripts/check-eager-closure-budget.mjs` on that build | 2109.4 KB gzipped over 104 of 2401 chunks, budget 2431.6 KB (headroom 322.2 KB); `vendor-objectstack`, where the new module lands, 577.4 / 823.0 KB. No `main` baseline measured. | | `pnpm --dir ui exec vitest run --project @object-ui/console` | 295 / 295 files, 2870 / 2870 tests, exit 0 (20m43s) | | eslint on the touched files | 0 errors, 5 warnings (see Acceptance notes) | | `node scripts/check-sdui-manifest.mjs` (+ `--self-test`) | exit 0, exit 0 | | `node scripts/pm/dispatch-gates.mjs --commands` | 34 commands, every one exit 0 | | `node scripts/pm/dispatch-gates.mjs --ran` | `34 derived famil(ies) accounted for — 34 run, 0 NOT-MEASURED` | **Live, in a browser** (Playwright Chromium against `pnpm dev:crm -- --fresh`, the Console built from this head and served at `/_console/`, the dev-seeded admin; the CLI carried the measurement-only `trustedAppSchemes: ['ai.objectos.mobile']` noted above): - **Fresh sign-in.** `/_console/login?redirect=` naming the hand-off, then a password sign-in on the form: the browser's next navigation is `GET /api/v1/auth/one-time-token/handoff?redirect_uri=ai.objectos.mobile%3A%2F%2Fauth%2Fcallback&code_challenge=…&code_challenge_method=S256` with `Sec-Fetch-Site: same-origin` and `Sec-Fetch-Mode: navigate`, answered `302` with `Location: ai.objectos.mobile://auth/callback?token=` and a token (redacted in the log). No "page not found". Headless Chromium has no handler for the app scheme, so the tab stays put after the `302`; on a device the system auth session hands that URL to the app. - **CONTROL.** The same sign-in on `?redirect=/api/v1/data/x` navigates to `/_console/api/v1/data/x`, a Console route, as before. - **A session older than five minutes.** A browser signed in at 21:39:21Z (`get-session` `createdAt` read back), opened on the hand-off redirect at 21:45:00Z: the sign-in form is shown and no hand-off request is made. The route itself answers that session's cookie with `401`. Signing in on the form then ends in the same `302` with a token, `Sec-Fetch-Site: same-origin`. The old session still answers `get-session` afterwards, as the design above says (not revoked). - **Provider sign-in: NOT MEASURED live.** The container has no identity provider (`/api/v1/auth/config` lists no social providers). Rule 2 is held by the unit pin above. ## Human Minimum - [x] 1. Schemas start as Zod; `packages/spec` holds no runtime logic. (No `packages/spec` change.) - [x] 2. Every name I added uses the casing for its kind. - [x] 3. No formatter ran; eslint on the touched files reports 0 errors (CI's Lint UI is the authority). - [x] 4. One issue, one branch off an up-to-date `main`, one pull request. - [x] 5. A change that publishes carries a changeset, and both declaration lines are filled in here and in the changeset. - [x] 6. `packages/spec` touched: not touched. - [x] 7. No hand edits to `content/docs/references/`, `packages/*/CHANGELOG.md` or `content/docs/releases/`. - [x] 8. Title, body and comments are in English (the maintainer brief above is Chinese by the project's convention). - [x] The *Before Submitting* list in CONTRIBUTING.md is done. --- _Generated by [Claude Code](https://claude.ai/code/session_01WGufzfukSC9MVr7odALmfg)_ --------- Co-authored-by: Claude <noreply@anthropic.com> Co-authored-by: objectstack-fleet[bot] <332303061+objectstack-fleet[bot]@users.noreply.github.com>
1 parent 89803c5 commit f35b361

6 files changed

Lines changed: 634 additions & 7 deletions

File tree

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
---
2+
'@object-ui/console': patch
3+
---
4+
5+
fix(console): the sign-in page finishes the mobile sign-in hand-off instead of landing on a missing Console page
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
The mobile app opens the Console's sign-in page in the system browser with `?redirect=` naming the hand-off route (`/api/v1/auth/one-time-token/handoff?...`), so that a user whose identity provider refuses embedded WebViews can still sign in. After sign-in the page sent every safe redirect through the Console mount, so the browser landed on `/_console/apps/.../api/v1/auth/one-time-token/handoff?...` and the page said it does not exist. Now:
11+
12+
- A `redirect` whose path is exactly the hand-off route under the auth base the Console talks to is navigated to unprefixed, by script from the sign-in page. Every other redirect, `/api/v1/data/x` included, stays a Console route as before; a lookalike path, another base path or an absolute URL is never followed out of the mount.
13+
- The hand-off comes before the organization steps: a user with several organizations is no longer sent to the picker first, and one with no active organization does not wait for it to be chosen.
14+
- A session created more than five minutes ago, which the hand-off refuses, keeps the sign-in form on screen instead of forwarding to a JSON refusal. Signing in on that form makes a new session and forwards.
15+
- The sign-up page does the same after a sign-up.

‎ui/apps/console/src/pages/auth/LoginPage.tsx‎

Lines changed: 33 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,9 @@
1010
* in the query string (better-auth's oauth-provider redirects the
1111
* unauthenticated user here before issuing a code).
1212
* - Post-login orchestration: replay the original `/oauth2/authorize`
13-
* request, auto-select the user's single organization, or honour a
14-
* safe `?redirect=` target.
13+
* request, forward to the mobile sign-in hand-off when `?redirect=` names
14+
* it (#29971, `./handoffRedirect`), auto-select the user's single
15+
* organization, or honour a safe `?redirect=` target.
1516
* - Offers the "Sign up" link only when the server would accept a sign-up
1617
* from this visitor: never under `emailPassword.disableSignUp === true`,
1718
* and under an audience posture closed to strangers (`invite_only`) only
@@ -73,6 +74,7 @@ import {
7374
import { AuthLayout } from './AuthLayout';
7475
import { AuthFooter, readLegalLinks } from './AuthFooter';
7576
import { followOauthAuthorize } from './followAuthorize';
77+
import { useHandoffRedirect } from './handoffRedirect';
7678
// Was module-private here; lifted to a shared module so `SetupPage` (whose
7779
// first-run exits went without it) and `RegisterPage` (which had copied it)
7880
// share ONE implementation — objectui#4181. Behaviour here is unchanged.
@@ -103,13 +105,21 @@ export function LoginPage() {
103105
const redirect = params.get('redirect');
104106
const {
105107
user,
108+
session,
106109
isLoading,
107110
organizations,
108111
isOrganizationsLoading,
109112
activeOrganization,
110113
switchOrganization,
111114
getAuthConfig,
112115
} = useAuth();
116+
// #29971 — a `redirect` naming the mobile sign-in hand-off: where to go
117+
// after sign-in, and whether the signed-in session is too old for it, in
118+
// which case the form shows instead (see `./handoffRedirect`).
119+
const handoff = useHandoffRedirect(redirect, { user, session, isLoading });
120+
// Nobody signed in, or a session the hand-off would refuse: either way this
121+
// page is talking to someone who has to sign in.
122+
const signInNeeded = !user || handoff.holdForSignIn;
113123

114124
// The public auth config and where its read stands (objectui#11806):
115125
// `loading` until `getAuthConfig()` settles, `failed` once it rejected — the
@@ -141,6 +151,8 @@ export function LoginPage() {
141151
// The OAuth hand-off fetch must fire at most once even though the post-login
142152
// effect re-runs as org state settles (it navigates away on success).
143153
const ssoHandoffStartedRef = useRef(false);
154+
// The same once-only latch for the mobile sign-in hand-off navigation.
155+
const mobileHandoffStartedRef = useRef(false);
144156

145157
// `isLoading` from useAuth() is overloaded: it is true both during the
146158
// initial session check AND during every in-flight signIn. The full-page
@@ -159,7 +171,7 @@ export function LoginPage() {
159171
// did not come from an invitation; see app-shell's `decideSignUpOffer`.
160172
const invitationRedirect = isInvitationRedirect(redirect);
161173
const bootstrap = useBootstrapStatus(
162-
hasBootstrapped && !user && needsBootstrapProbe(authConfig, invitationRedirect),
174+
hasBootstrapped && signInNeeded && needsBootstrapProbe(authConfig, invitationRedirect),
163175
);
164176
const signUpOffer = decideSignUpOffer(authConfig, { invitationRedirect, bootstrap });
165177
// #26473 — who invited this visitor, and to what; `null` keeps the generic
@@ -249,7 +261,21 @@ export function LoginPage() {
249261
}
250262
}
251263

252-
// 2. Auto-select a single org so post-login redirect doesn't bounce
264+
// 2. The mobile sign-in hand-off (#29971), before the organization steps:
265+
// it carries the session and nothing else, and the app's WebView picks
266+
// the organization after it. Navigated to unprefixed, by script from
267+
// this page, so the route sees `Sec-Fetch-Site: same-origin`. A session
268+
// the route would refuse for its age keeps the form up instead.
269+
if (handoff.target) {
270+
if (handoff.holdForSignIn) return;
271+
if (!mobileHandoffStartedRef.current) {
272+
mobileHandoffStartedRef.current = true;
273+
window.location.assign(handoff.target);
274+
}
275+
return;
276+
}
277+
278+
// 3. Auto-select a single org so post-login redirect doesn't bounce
253279
// off `RequireOrganization`.
254280
if (!activeOrganization) {
255281
if (isOrganizationsLoading || autoSelectingOrg) return;
@@ -282,9 +308,11 @@ export function LoginPage() {
282308
autoSelectingOrg,
283309
redirect,
284310
switchOrganization,
311+
handoff.target,
312+
handoff.holdForSignIn,
285313
]);
286314

287-
if ((isLoading && !hasBootstrapped) || user) {
315+
if ((isLoading && !hasBootstrapped) || !signInNeeded) {
288316
return (
289317
<AuthLayout>
290318
<div className="flex flex-col items-center gap-3 py-10 text-sm text-muted-foreground">

‎ui/apps/console/src/pages/auth/RegisterPage.tsx‎

Lines changed: 26 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,8 @@
2323
* verification mail's link so it survives the inbox (objectui#10893).
2424
* - Replays an `/oauth2/authorize` query string when the user landed
2525
* here mid-SSO so the IdP can continue the flow post-signup.
26+
* - Forwards to the mobile sign-in hand-off when `?redirect=` names it,
27+
* exactly as `/login` does (#29971, `./handoffRedirect`).
2628
* - Draws `/login`'s footer under the form — the locale switch and the
2729
* privacy / terms links the server's auth config serves, from the same
2830
* reader (#25885): sign-up is where a visitor accepts the terms.
@@ -52,6 +54,7 @@ import {
5254
} from '@object-ui/app-shell';
5355
import { AuthLayout } from './AuthLayout';
5456
import { followOauthAuthorize } from './followAuthorize';
57+
import { useHandoffRedirect } from './handoffRedirect';
5558
// Was a second module-private copy of LoginPage's helper; both now share one
5659
// implementation — objectui#4181. Behaviour here is unchanged.
5760
import { withConsoleBase, withConsoleBaseRootRelative } from '../../utils/consoleBase';
@@ -77,13 +80,19 @@ export function RegisterPage() {
7780
const redirect = params.get('redirect');
7881
const {
7982
user,
83+
session,
8084
isLoading,
8185
organizations,
8286
isOrganizationsLoading,
8387
activeOrganization,
8488
switchOrganization,
8589
getAuthConfig,
8690
} = useAuth();
91+
// #29971 — the mobile sign-in hand-off, as on `/login`: a sign-up from the
92+
// system auth session ends there too, and a session too old for it keeps
93+
// the form up (see `./handoffRedirect`).
94+
const handoff = useHandoffRedirect(redirect, { user, session, isLoading });
95+
const signUpNeeded = !user || handoff.holdForSignIn;
8796

8897
// The public auth config and where its read stands (objectui#11806), as on
8998
// `/login`: `loading` until `getAuthConfig()` settles, `failed` once it
@@ -105,6 +114,8 @@ export function RegisterPage() {
105114
const [autoSelectingOrg, setAutoSelectingOrg] = useState(false);
106115
// Fire the OAuth hand-off fetch at most once (see LoginPage).
107116
const ssoHandoffStartedRef = useRef(false);
117+
// And the mobile sign-in hand-off navigation.
118+
const mobileHandoffStartedRef = useRef(false);
108119

109120
// See LoginPage: `isLoading` is overloaded (initial session check + every
110121
// in-flight signUp). Latch once the first check resolves so a failed
@@ -143,7 +154,7 @@ export function RegisterPage() {
143154
const bootstrap = useBootstrapStatus(
144155
configRead === 'known' &&
145156
hasBootstrapped &&
146-
!user &&
157+
signUpNeeded &&
147158
needsBootstrapProbe(authConfig, invitationRedirect),
148159
);
149160
const signUpOffer = decideSignUpOffer(authConfig, { invitationRedirect, bootstrap });
@@ -176,6 +187,17 @@ export function RegisterPage() {
176187
}
177188
}
178189

190+
// #29971 — the mobile sign-in hand-off, before the organization steps,
191+
// by script from this page (see LoginPage).
192+
if (handoff.target) {
193+
if (handoff.holdForSignIn) return;
194+
if (!mobileHandoffStartedRef.current) {
195+
mobileHandoffStartedRef.current = true;
196+
window.location.assign(handoff.target);
197+
}
198+
return;
199+
}
200+
179201
if (!activeOrganization) {
180202
if (isOrganizationsLoading || autoSelectingOrg) return;
181203
if (organizations.length === 1) {
@@ -203,11 +225,13 @@ export function RegisterPage() {
203225
autoSelectingOrg,
204226
redirect,
205227
switchOrganization,
228+
handoff.target,
229+
handoff.holdForSignIn,
206230
]);
207231

208232
// The first session check has answered and nobody is signed in: the page is
209233
// talking to a visitor, so a failed config read is theirs to see.
210-
const awaitingSession = (isLoading && !hasBootstrapped) || !!user;
234+
const awaitingSession = (isLoading && !hasBootstrapped) || !signUpNeeded;
211235
if (!awaitingSession && serverUnreachable) {
212236
return (
213237
<AuthLayout formWidth="md">
Lines changed: 137 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,137 @@
1+
/**
2+
* The mobile sign-in hand-off as a sign-in redirect target (#29971): which
3+
* `?redirect=` values name the hand-off route, and which sessions it carries.
4+
* The sign-in pages' behaviour is pinned in `authExitBasename.test.tsx`.
5+
*/
6+
7+
import { describe, it, expect } from 'vitest';
8+
import { AuthEndpointPaths } from '@objectstack/spec/api';
9+
import {
10+
HANDOFF_SESSION_MAX_AGE_MS,
11+
handoffNavigationTarget,
12+
isHandoffSessionFresh,
13+
sessionCreatedAtMs,
14+
} from '../handoffRedirect';
15+
16+
const ORIGIN = 'https://os.example.com';
17+
const AUTH_BASE = '/api/v1/auth';
18+
const HANDOFF_PATH = '/api/v1/auth/one-time-token/handoff';
19+
const QUERY =
20+
'?redirect_uri=ai.objectos.mobile%3A%2F%2Fauth%2Fcallback' +
21+
'&code_challenge=E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM&code_challenge_method=S256';
22+
23+
const target = (redirect: string | null, authBase = AUTH_BASE) =>
24+
handoffNavigationTarget(redirect, { origin: ORIGIN, authBase });
25+
26+
describe('handoffNavigationTarget — the hand-off route and nothing wider', () => {
27+
it('is the route the spec names under the auth base', () => {
28+
expect(`${AUTH_BASE}${AuthEndpointPaths.oneTimeTokenHandoff}`).toBe(HANDOFF_PATH);
29+
});
30+
31+
it('answers the hand-off path with its query, unprefixed', () => {
32+
expect(target(`${HANDOFF_PATH}${QUERY}`)).toBe(`${HANDOFF_PATH}${QUERY}`);
33+
expect(target(HANDOFF_PATH)).toBe(HANDOFF_PATH);
34+
});
35+
36+
it('CONTROL: an ordinary API path is not the hand-off (it stays a Console route)', () => {
37+
expect(target('/api/v1/data/x')).toBeNull();
38+
expect(target('/settings')).toBeNull();
39+
expect(target('/')).toBeNull();
40+
});
41+
42+
it('refuses lookalike paths', () => {
43+
for (const lookalike of [
44+
'/api/v1/auth/one-time-token/handoffX',
45+
`/api/v1/auth/one-time-token/handoffX${QUERY}`,
46+
'/api/v1/auth/one-time-token/handoff/',
47+
'/api/v1/auth/one-time-token/handoff/x',
48+
'/api/v1/auth/one-time-token/verify',
49+
'/API/v1/auth/one-time-token/handoff',
50+
'/api/v1/auth/one-time-token%2Fhandoff',
51+
'/_console/api/v1/auth/one-time-token/handoff',
52+
]) {
53+
expect(target(lookalike), lookalike).toBeNull();
54+
}
55+
});
56+
57+
it('refuses the hand-off under a different base path', () => {
58+
// A Console whose auth base carries a prefix: only that prefix's hand-off.
59+
expect(target(`${HANDOFF_PATH}${QUERY}`, '/tenant-a/api/v1/auth')).toBeNull();
60+
expect(target(`/tenant-a${HANDOFF_PATH}${QUERY}`, '/tenant-a/api/v1/auth')).toBe(
61+
`/tenant-a${HANDOFF_PATH}${QUERY}`,
62+
);
63+
// And the other way round.
64+
expect(target(`/tenant-a${HANDOFF_PATH}`)).toBeNull();
65+
});
66+
67+
it('refuses an absolute, protocol-relative or backslash-smuggled URL', () => {
68+
for (const offsite of [
69+
`https://evil.example${HANDOFF_PATH}${QUERY}`,
70+
`${ORIGIN}${HANDOFF_PATH}${QUERY}`,
71+
`//evil.example${HANDOFF_PATH}${QUERY}`,
72+
`/\\evil.example${HANDOFF_PATH}${QUERY}`,
73+
`/\t/evil.example${HANDOFF_PATH}`,
74+
`javascript:alert(1)//${HANDOFF_PATH}`,
75+
]) {
76+
expect(target(offsite), offsite).toBeNull();
77+
}
78+
});
79+
80+
it('refuses when the auth base is on another origin: that route is not reachable from this page', () => {
81+
expect(target(`${HANDOFF_PATH}${QUERY}`, 'https://api.example.com/api/v1/auth')).toBeNull();
82+
});
83+
84+
it('answers null for no redirect or a relative one', () => {
85+
expect(target(null)).toBeNull();
86+
expect(target('')).toBeNull();
87+
expect(target('api/v1/auth/one-time-token/handoff')).toBeNull();
88+
});
89+
90+
it('answers the parsed URL, so what is navigated to is what was checked', () => {
91+
expect(target(`/api/v1/data/../auth/one-time-token/handoff${QUERY}`)).toBe(
92+
`${HANDOFF_PATH}${QUERY}`,
93+
);
94+
expect(target(`${HANDOFF_PATH}${QUERY}#fragment`)).toBe(`${HANDOFF_PATH}${QUERY}`);
95+
});
96+
});
97+
98+
describe('isHandoffSessionFresh — the five-minute window', () => {
99+
const now = Date.parse('2026-11-03T12:00:00Z');
100+
const ago = (ms: number) => new Date(now - ms);
101+
const arrival = { session: null };
102+
103+
it('carries a session created within five minutes', () => {
104+
expect(isHandoffSessionFresh({ createdAt: ago(4 * 60_000) }, { arrival, now })).toBe(true);
105+
expect(isHandoffSessionFresh({ createdAt: ago(HANDOFF_SESSION_MAX_AGE_MS) }, { arrival, now })).toBe(true);
106+
});
107+
108+
it('refuses a session created more than five minutes ago', () => {
109+
expect(isHandoffSessionFresh({ createdAt: ago(6 * 60_000) }, { arrival, now })).toBe(false);
110+
expect(isHandoffSessionFresh({ createdAt: ago(7 * 24 * 3_600_000) }, { arrival, now })).toBe(false);
111+
});
112+
113+
it('reads createdAt as a Date or as the ISO string a raw fetch leaves', () => {
114+
const iso = ago(6 * 60_000).toISOString();
115+
expect(sessionCreatedAtMs({ createdAt: iso })).toBe(now - 6 * 60_000);
116+
expect(isHandoffSessionFresh({ createdAt: iso }, { arrival, now })).toBe(false);
117+
});
118+
119+
it('a session without createdAt is fresh only when the page did not find it on arrival', () => {
120+
const found = { token: 't0' };
121+
// Found on arrival: treated as too old.
122+
expect(isHandoffSessionFresh(found, { arrival: { session: found }, now })).toBe(false);
123+
// Before the first session check answered: not judged fresh either.
124+
expect(isHandoffSessionFresh(found, { arrival: null, now })).toBe(false);
125+
// Made by a sign-in on the page (better-auth's sign-in answer has no
126+
// session record, so the provider holds `undefined` or `{ token }`).
127+
expect(isHandoffSessionFresh(undefined, { arrival: { session: null }, now })).toBe(true);
128+
expect(isHandoffSessionFresh({ token: 't1' }, { arrival: { session: found }, now })).toBe(true);
129+
});
130+
131+
it('an unreadable createdAt counts as none', () => {
132+
expect(sessionCreatedAtMs({ createdAt: 'not a date' })).toBeNull();
133+
expect(sessionCreatedAtMs({ createdAt: new Date(Number.NaN) })).toBeNull();
134+
const found = { createdAt: 'not a date' };
135+
expect(isHandoffSessionFresh(found, { arrival: { session: found }, now })).toBe(false);
136+
});
137+
});

0 commit comments

Comments
 (0)