diff --git a/.changeset/studio-guest-login.md b/.changeset/studio-guest-login.md new file mode 100644 index 00000000..f70253ab --- /dev/null +++ b/.changeset/studio-guest-login.md @@ -0,0 +1,5 @@ +--- +"@cloudhal/cli": patch +--- + +Studio's `/login`, `/forgot-password` and `/reset-password` no longer show their forms to a signed-in member: they go on to `/sites`, or to the page the member was opening (#388). An MCP client's authorization request (`/login?client_id=…&sig=…`) still shows the sign-in form. A signed-out member who opens a deep link now returns to it after signing in, through `/login?redirect=`, which accepts only paths on Studio's own origin. In sign-in mode the email field is marked `autocomplete="username"`, so password managers offer the saved account. diff --git a/.changeset/studio-remembered-accounts.md b/.changeset/studio-remembered-accounts.md new file mode 100644 index 00000000..8267e3f5 --- /dev/null +++ b/.changeset/studio-remembered-accounts.md @@ -0,0 +1,5 @@ +--- +"@cloudhal/cli": patch +--- + +Studio's sign-in page can remember accounts on a device, like Cloudflare's login profiles (#388). "Remember this account on this device" is off by default; when ticked, a successful sign-in keeps the email, the display name and the time of the sign-in in the browser's `localStorage` (no password, token, session id or role), for at most five accounts per Studio address, each dropped after 30 days unused. The signed-out `/login` then lists them first: picking one fills in the email and focuses the password, ✕ forgets one, and "Use another account" shows the empty form. The account menu adds "Sign out and forget", which forgets the signed-in member's entry and signs out; plain "Sign out" keeps it. The new strings are AI drafts in every language but English, awaiting review. diff --git a/apps/studio/src/components/PasswordField.tsx b/apps/studio/src/components/PasswordField.tsx index f52e6692..3075f48b 100644 --- a/apps/studio/src/components/PasswordField.tsx +++ b/apps/studio/src/components/PasswordField.tsx @@ -1,6 +1,6 @@ import { InputGroup } from "@cloudhal/ui"; import { Eye, EyeSlash } from "@phosphor-icons/react"; -import { type KeyboardEvent, useState } from "react"; +import { type KeyboardEvent, type Ref, useState } from "react"; import { useT } from "../i18n/index.tsx"; /** @@ -17,6 +17,7 @@ export function PasswordField({ autoComplete, onEnter, disabled, + inputRef, }: { label: string; description?: string | undefined; @@ -26,6 +27,8 @@ export function PasswordField({ autoComplete: "current-password" | "new-password"; onEnter?: (() => void) | undefined; disabled?: boolean | undefined; + /** The input itself, e.g. to focus it once the login page has filled in a remembered email. */ + inputRef?: Ref | undefined; }) { const t = useT(); const [visible, setVisible] = useState(false); @@ -38,6 +41,7 @@ export function PasswordField({ disabled={disabled} > void; + onForget: (email: string) => void; + onOther: () => void; +}) { + const t = useT(); + return ( +
+ ({ + email: a.email, + name: a.name, + initials: initials(a.name, a.email), + }))} + onChoose={(a) => onChoose(a.email)} + onForget={(a) => onForget(a.email)} + labels={{ + list: t("auth.rememberedAccounts"), + choose: (a) => + a.name + ? t("auth.continueAs", { name: a.name, email: a.email }) + : t("auth.continueAsEmail", { email: a.email }), + forget: (a) => t("auth.forgetAccount", { email: a.email }), + }} + /> + +
+ ); +} + +/** The opt-in under the sign-in form: off until the member ticks it. */ +export function RememberAccountCheckbox({ + checked, + onCheckedChange, +}: { + checked: boolean; + onCheckedChange: (checked: boolean) => void; +}) { + const t = useT(); + return ( + onCheckedChange(value === true)} + data-testid="remember-account" + /> + ); +} diff --git a/apps/studio/src/components/UserMenu.tsx b/apps/studio/src/components/UserMenu.tsx index d085da60..8d0ec95b 100644 --- a/apps/studio/src/components/UserMenu.tsx +++ b/apps/studio/src/components/UserMenu.tsx @@ -1,9 +1,18 @@ import { Avatar, Button, DropdownMenu, directional, Text, Tooltip } from "@cloudhal/ui"; -import { SignOut, SquaresFour, Translate, UserGear, UsersThree } from "@phosphor-icons/react"; +import { + SignOut, + SquaresFour, + Translate, + UserGear, + UserMinus, + UsersThree, +} from "@phosphor-icons/react"; import { useNavigate } from "@tanstack/react-router"; import { LOCALES, type Locale, useI18n } from "../i18n/index.tsx"; import { authClient } from "../lib/auth.ts"; import { initials } from "../lib/initials.ts"; +import { forgetRememberedAccount, readRememberedAccounts } from "../lib/remembered-accounts.ts"; +import { cachedSession } from "../lib/session-cache.ts"; import { useThemePreference } from "../lib/theme.ts"; import { isMachineTranslated, @@ -34,6 +43,13 @@ export function UserMenu() { await authClient.signOut(); await navigate({ to: "/login" }); }; + // #388 step 3: offered while this browser remembers an account; forgets only the member's own. + const remembers = people && readRememberedAccounts().length > 0; + const signOutAndForget = async () => { + const email = await currentEmail(); + if (email) forgetRememberedAccount(email); + await signOut(); + }; return ( )} + {remembers && ( + + {t("auth.signOutAndForget")} + + )} ); } + +/** The signed-in member's email, from the session kept between navigations (no extra request). */ +async function currentEmail(): Promise { + try { + const session = await cachedSession(async () => (await authClient.getSession()).data); + const email = (session as { user?: { email?: unknown } } | null)?.user?.email; + return typeof email === "string" ? email : undefined; + } catch { + return undefined; + } +} diff --git a/apps/studio/src/components/useRememberedLogin.ts b/apps/studio/src/components/useRememberedLogin.ts new file mode 100644 index 00000000..8c37594d --- /dev/null +++ b/apps/studio/src/components/useRememberedLogin.ts @@ -0,0 +1,72 @@ +import { useEffect, useRef, useState } from "react"; +import { + emailKey, + forgetRememberedAccount, + readRememberedAccounts, + rememberAccount, + touchRememberedAccount, +} from "../lib/remembered-accounts.ts"; + +/** + * The login page's remembered accounts (#388 step 3): listed first in sign-in mode while any + * exist; picking one hands its email to the page (`onChosen`) and focuses the password; "Use + * another account" shows the empty form; `keep` runs after a successful sign-in. + */ +export function useRememberedLogin({ + signingIn, + email, + onChosen, +}: { + signingIn: boolean; + /** The email in the form, to tell whether it is remembered already. */ + email: string; + /** Fills in `email` (empty for "Use another account"). */ + onChosen: (email: string) => void; +}) { + const [accounts, setAccounts] = useState(() => readRememberedAccounts()); + const [choosing, setChoosing] = useState(true); + const [remember, setRemember] = useState(false); + const [focusPassword, setFocusPassword] = useState(false); + const passwordRef = useRef(null); + useEffect(() => { + if (!focusPassword) return; + passwordRef.current?.focus(); + setFocusPassword(false); + }, [focusPassword]); + + return { + accounts, + showChooser: signingIn && choosing && accounts.length > 0, + /** The typed email is remembered already: no opt-in shown, and sign-in refreshes it. */ + remembered: accounts.some((a) => emailKey(a.email) === emailKey(email)), + remember, + setRemember, + passwordRef, + choose(chosen: string) { + onChosen(chosen); + setChoosing(false); + setFocusPassword(true); + }, + forget(forgotten: string) { + setAccounts(forgetRememberedAccount(forgotten)); + }, + useAnother() { + onChosen(""); + setChoosing(false); + }, + /** + * After a successful sign-in: remember the account when the member asked to, or refresh it + * when it is remembered already. The email and name come from the response, else the typed + * email (an OAuth sign-in answers with where to go, without the user). + */ + keep(data: unknown, typed: string) { + const user = (data as { user?: { email?: unknown; name?: unknown } } | null)?.user; + const account = { + email: typeof user?.email === "string" ? user.email : typed, + name: typeof user?.name === "string" ? user.name : undefined, + }; + if (remember) rememberAccount(account); + else touchRememberedAccount(account); + }, + }; +} diff --git a/apps/studio/src/i18n/ar.ts b/apps/studio/src/i18n/ar.ts index 132737fb..efb175d3 100644 --- a/apps/studio/src/i18n/ar.ts +++ b/apps/studio/src/i18n/ar.ts @@ -1,6 +1,6 @@ // Generated by `pnpm i18n:import` (ADR-0034): ar core messages. // Do not edit: change the translation file and import it; only English is edited here. -// hash: 830eafd5ee91d95b +// hash: 73c0e0a127fdc76c import type { Messages } from "./en.ts"; export const messages: Messages = { @@ -77,6 +77,14 @@ export const messages: Messages = { setupTitle: "إعداد هذا الـStudio", setupDescription: "فتحت رابط الإعداد الذي ظهر عند تشغيل Cloudhal أو نشره. الحساب الذي تنشئه الآن يصبح المالك؛ وبعد ذلك يُغلق التسجيل.", + rememberAccount: "تذكّر هذا الحساب على هذا الجهاز", + chooseAccount: "اختر حسابًا للمتابعة.", + rememberedAccounts: "الحسابات المحفوظة", + continueAs: "المتابعة باسم {name} ({email})", + continueAsEmail: "المتابعة باسم {email}", + forgetAccount: "انسَ {email} على هذا الجهاز", + useAnotherAccount: "استخدم حسابًا آخر", + signOutAndForget: "تسجيل الخروج ونسيان الحساب", }, sites: { title: "المواقع", diff --git a/apps/studio/src/i18n/de.ts b/apps/studio/src/i18n/de.ts index 15cd9440..34b0d4d3 100644 --- a/apps/studio/src/i18n/de.ts +++ b/apps/studio/src/i18n/de.ts @@ -1,6 +1,6 @@ // Generated by `pnpm i18n:import` (ADR-0034): de core messages. // Do not edit: change the translation file and import it; only English is edited here. -// hash: e7b7c6e7401e9d7f +// hash: f4b3c7b2495df788 import type { Messages } from "./en.ts"; export const messages: Messages = { @@ -78,6 +78,14 @@ export const messages: Messages = { setupTitle: "Dieses Studio einrichten", setupDescription: "Du hast den Einrichtungslink geöffnet, den Cloudhal beim Start oder beim Deployment ausgegeben hat. Das Konto, das du jetzt erstellst, wird Inhaber; danach ist die Registrierung geschlossen.", + rememberAccount: "Dieses Konto auf diesem Gerät merken", + chooseAccount: "Wähle ein Konto, um fortzufahren.", + rememberedAccounts: "Gemerkte Konten", + continueAs: "Weiter als {name} ({email})", + continueAsEmail: "Weiter als {email}", + forgetAccount: "{email} auf diesem Gerät vergessen", + useAnotherAccount: "Anderes Konto verwenden", + signOutAndForget: "Abmelden und vergessen", }, sites: { title: "Websites", diff --git a/apps/studio/src/i18n/en.ts b/apps/studio/src/i18n/en.ts index 60ed9b47..94f6b1da 100644 --- a/apps/studio/src/i18n/en.ts +++ b/apps/studio/src/i18n/en.ts @@ -77,6 +77,22 @@ export const en = { setupTitle: "Set up this Studio", setupDescription: "You opened the setup link printed when Cloudhal started or was deployed. The account you create now becomes the owner; afterwards sign-up closes.", + /** Checkbox under the sign-in form, off by default: keeps the email and name in this browser for the account list. */ + rememberAccount: "Remember this account on this device", + /** Description over the list of accounts remembered on this device. */ + chooseAccount: "Choose an account to continue.", + /** Accessible name of the list of remembered accounts. */ + rememberedAccounts: "Remembered accounts", + /** Accessible name of a remembered account's row. */ + continueAs: "Continue as {name} ({email})", + /** Accessible name of a remembered account's row when it has no name. */ + continueAsEmail: "Continue as {email}", + /** Icon button beside a remembered account: removes it from this browser's list. */ + forgetAccount: "Forget {email} on this device", + /** Button under the list of remembered accounts: shows the empty sign-in form. */ + useAnotherAccount: "Use another account", + /** Account menu item: removes the member from this browser's remembered accounts, then signs out. */ + signOutAndForget: "Sign out and forget", }, sites: { title: "Sites", diff --git a/apps/studio/src/i18n/es.ts b/apps/studio/src/i18n/es.ts index 0bd93577..a2e77d14 100644 --- a/apps/studio/src/i18n/es.ts +++ b/apps/studio/src/i18n/es.ts @@ -1,6 +1,6 @@ // Generated by `pnpm i18n:import` (ADR-0034): es core messages. // Do not edit: change the translation file and import it; only English is edited here. -// hash: ae3c6dd87f980d83 +// hash: bb0013fa0505bc01 import type { Messages } from "./en.ts"; export const messages: Messages = { @@ -77,6 +77,14 @@ export const messages: Messages = { setupTitle: "Configura este Studio", setupDescription: "Abriste el enlace de configuración que Cloudhal mostró al iniciarse o al desplegarse. La cuenta que crees ahora será la propietaria; después se cierra el registro.", + rememberAccount: "Recordar esta cuenta en este dispositivo", + chooseAccount: "Elige una cuenta para continuar.", + rememberedAccounts: "Cuentas recordadas", + continueAs: "Continuar como {name} ({email})", + continueAsEmail: "Continuar como {email}", + forgetAccount: "Olvidar {email} en este dispositivo", + useAnotherAccount: "Usar otra cuenta", + signOutAndForget: "Cerrar sesión y olvidar", }, sites: { title: "Sitios", diff --git a/apps/studio/src/i18n/fa.ts b/apps/studio/src/i18n/fa.ts index af1b747c..bed9acfc 100644 --- a/apps/studio/src/i18n/fa.ts +++ b/apps/studio/src/i18n/fa.ts @@ -1,6 +1,6 @@ // Generated by `pnpm i18n:import` (ADR-0034): fa core messages. // Do not edit: change the translation file and import it; only English is edited here. -// hash: cbba59c8a0333652 +// hash: c1245b3a22530500 import type { Messages } from "./en.ts"; export const messages: Messages = { @@ -77,6 +77,14 @@ export const messages: Messages = { setupTitle: "راه‌اندازی این Studio", setupDescription: "شما پیوند راه‌اندازی‌ای را باز کرده‌اید که Cloudhal هنگام اجرا یا استقرار نشان داد. حسابی که اکنون می‌سازید مالک می‌شود؛ پس از آن ثبت‌نام بسته می‌شود.", + rememberAccount: "این حساب را در این دستگاه به خاطر بسپار", + chooseAccount: "برای ادامه، یک حساب انتخاب کنید.", + rememberedAccounts: "حساب‌های به‌خاطرسپرده", + continueAs: "ادامه به‌عنوان {name} ({email})", + continueAsEmail: "ادامه به‌عنوان {email}", + forgetAccount: "فراموش کردن {email} در این دستگاه", + useAnotherAccount: "استفاده از حساب دیگر", + signOutAndForget: "خروج و فراموش کردن", }, sites: { title: "سایت‌ها", diff --git a/apps/studio/src/i18n/fr.ts b/apps/studio/src/i18n/fr.ts index 51cbaf51..5b056689 100644 --- a/apps/studio/src/i18n/fr.ts +++ b/apps/studio/src/i18n/fr.ts @@ -1,6 +1,6 @@ // Generated by `pnpm i18n:import` (ADR-0034): fr core messages. // Do not edit: change the translation file and import it; only English is edited here. -// hash: 2165aa26fabf49d8 +// hash: 0735a5147eb170e3 import type { Messages } from "./en.ts"; export const messages: Messages = { @@ -77,6 +77,14 @@ export const messages: Messages = { setupTitle: "Configurer ce Studio", setupDescription: "Vous avez ouvert le lien de configuration affiché par Cloudhal à son démarrage ou à son déploiement. Le compte que vous créez maintenant en devient le propriétaire ; les inscriptions se ferment ensuite.", + rememberAccount: "Se souvenir de ce compte sur cet appareil", + chooseAccount: "Choisissez un compte pour continuer.", + rememberedAccounts: "Comptes mémorisés", + continueAs: "Continuer en tant que {name} ({email})", + continueAsEmail: "Continuer en tant que {email}", + forgetAccount: "Oublier {email} sur cet appareil", + useAnotherAccount: "Utiliser un autre compte", + signOutAndForget: "Se déconnecter et oublier", }, sites: { title: "Sites", diff --git a/apps/studio/src/i18n/generated/params.ts b/apps/studio/src/i18n/generated/params.ts index 52849715..2d44bec9 100644 --- a/apps/studio/src/i18n/generated/params.ts +++ b/apps/studio/src/i18n/generated/params.ts @@ -130,6 +130,9 @@ export interface MessageParams { "articleTerms.requiredToast": { singular: string | number }; "articles.facets.allCategories": { label: string | number }; "articles.facets.allTags": { label: string | number }; + "auth.continueAs": { name: string | number; email: string | number }; + "auth.continueAsEmail": { email: string | number }; + "auth.forgetAccount": { email: string | number }; "bodyEditor.focusShortcut": { keys: string | number }; "build.activity.changed": { count: number }; "build.activity.operations": { count: string | number }; diff --git a/apps/studio/src/i18n/he.ts b/apps/studio/src/i18n/he.ts index 4b95c4cf..36e56ac6 100644 --- a/apps/studio/src/i18n/he.ts +++ b/apps/studio/src/i18n/he.ts @@ -1,6 +1,6 @@ // Generated by `pnpm i18n:import` (ADR-0034): he core messages. // Do not edit: change the translation file and import it; only English is edited here. -// hash: d8cd1171ca294fad +// hash: f9f3fe50f45237a0 import type { Messages } from "./en.ts"; export const messages: Messages = { @@ -77,6 +77,14 @@ export const messages: Messages = { setupTitle: "הגדרת ה-Studio הזה", setupDescription: "קישור ההגדרה שהוצג כש־Cloudhal הופעל או נפרס נפתח. החשבון שנוצר עכשיו הופך לבעלים; לאחר מכן ההרשמה נסגרת.", + rememberAccount: "לזכור את החשבון הזה במכשיר הזה", + chooseAccount: "בחרו חשבון כדי להמשיך.", + rememberedAccounts: "חשבונות שמורים", + continueAs: "להמשיך בתור {name} ({email})", + continueAsEmail: "להמשיך בתור {email}", + forgetAccount: "לשכוח את {email} במכשיר הזה", + useAnotherAccount: "שימוש בחשבון אחר", + signOutAndForget: "התנתקות ושכחת החשבון", }, sites: { title: "אתרים", diff --git a/apps/studio/src/i18n/hi.ts b/apps/studio/src/i18n/hi.ts index ca1617fe..47737af7 100644 --- a/apps/studio/src/i18n/hi.ts +++ b/apps/studio/src/i18n/hi.ts @@ -1,6 +1,6 @@ // Generated by `pnpm i18n:import` (ADR-0034): hi core messages. // Do not edit: change the translation file and import it; only English is edited here. -// hash: 3ea7ec891fb56c2e +// hash: 38b59cf8a19bc26a import type { Messages } from "./en.ts"; export const messages: Messages = { @@ -77,6 +77,14 @@ export const messages: Messages = { setupTitle: "यह Studio सेट अप करें", setupDescription: "आपने वह सेटअप लिंक खोला है जो Cloudhal के शुरू या डिप्लॉय होने पर दिखाया गया था। अभी जो खाता आप बनाएँगे वह स्वामी बनेगा; इसके बाद साइन-अप बंद हो जाता है।", + rememberAccount: "इस डिवाइस पर यह खाता याद रखें", + chooseAccount: "जारी रखने के लिए कोई खाता चुनें।", + rememberedAccounts: "याद रखे गए खाते", + continueAs: "{name} ({email}) के रूप में जारी रखें", + continueAsEmail: "{email} के रूप में जारी रखें", + forgetAccount: "इस डिवाइस पर {email} को भूल जाएँ", + useAnotherAccount: "दूसरा खाता इस्तेमाल करें", + signOutAndForget: "साइन आउट करें और भूल जाएँ", }, sites: { title: "साइटें", diff --git a/apps/studio/src/i18n/id.ts b/apps/studio/src/i18n/id.ts index 6e0cf6f0..ab3bdb66 100644 --- a/apps/studio/src/i18n/id.ts +++ b/apps/studio/src/i18n/id.ts @@ -1,6 +1,6 @@ // Generated by `pnpm i18n:import` (ADR-0034): id core messages. // Do not edit: change the translation file and import it; only English is edited here. -// hash: c1afe02532a73163 +// hash: c9a99ea4166494fa import type { Messages } from "./en.ts"; export const messages: Messages = { @@ -77,6 +77,14 @@ export const messages: Messages = { setupTitle: "Siapkan Studio ini", setupDescription: "Anda membuka tautan penyiapan yang ditampilkan saat Cloudhal dijalankan atau di-deploy. Akun yang Anda buat sekarang menjadi pemilik; setelah itu pendaftaran ditutup.", + rememberAccount: "Ingat akun ini di perangkat ini", + chooseAccount: "Pilih akun untuk melanjutkan.", + rememberedAccounts: "Akun yang diingat", + continueAs: "Lanjutkan sebagai {name} ({email})", + continueAsEmail: "Lanjutkan sebagai {email}", + forgetAccount: "Lupakan {email} di perangkat ini", + useAnotherAccount: "Gunakan akun lain", + signOutAndForget: "Keluar dan lupakan", }, sites: { title: "Situs", diff --git a/apps/studio/src/i18n/it.ts b/apps/studio/src/i18n/it.ts index 03cad6e1..43c3c549 100644 --- a/apps/studio/src/i18n/it.ts +++ b/apps/studio/src/i18n/it.ts @@ -1,6 +1,6 @@ // Generated by `pnpm i18n:import` (ADR-0034): it core messages. // Do not edit: change the translation file and import it; only English is edited here. -// hash: cafef8cd7df84437 +// hash: ebb3414e68d737f9 import type { Messages } from "./en.ts"; export const messages: Messages = { @@ -77,6 +77,14 @@ export const messages: Messages = { setupTitle: "Configura questo Studio", setupDescription: "Hai aperto il link di configurazione mostrato da Cloudhal all’avvio o al deploy. L’account che crei ora diventa il proprietario; dopo, la registrazione si chiude.", + rememberAccount: "Ricorda questo account su questo dispositivo", + chooseAccount: "Scegli un account per continuare.", + rememberedAccounts: "Account memorizzati", + continueAs: "Continua come {name} ({email})", + continueAsEmail: "Continua come {email}", + forgetAccount: "Dimentica {email} su questo dispositivo", + useAnotherAccount: "Usa un altro account", + signOutAndForget: "Esci e dimentica", }, sites: { title: "Siti", diff --git a/apps/studio/src/i18n/ja.ts b/apps/studio/src/i18n/ja.ts index b4e7d4d5..eddef6d7 100644 --- a/apps/studio/src/i18n/ja.ts +++ b/apps/studio/src/i18n/ja.ts @@ -1,6 +1,6 @@ // Generated by `pnpm i18n:import` (ADR-0034): ja core messages. // Do not edit: change the translation file and import it; only English is edited here. -// hash: 130762ebd15e112c +// hash: b1d48d208a60dd37 import type { Messages } from "./en.ts"; export const messages: Messages = { @@ -77,6 +77,14 @@ export const messages: Messages = { setupTitle: "このStudioをセットアップ", setupDescription: "Cloudhal の起動時またはデプロイ時に表示されたセットアップリンクを開きました。ここで作成するアカウントがオーナーになり、その後は新規登録が締め切られます。", + rememberAccount: "このデバイスでこのアカウントを記憶する", + chooseAccount: "続行するアカウントを選択してください。", + rememberedAccounts: "記憶されたアカウント", + continueAs: "{name}({email})として続行", + continueAsEmail: "{email} として続行", + forgetAccount: "このデバイスで {email} を削除", + useAnotherAccount: "別のアカウントを使用", + signOutAndForget: "サインアウトして削除", }, sites: { title: "サイト", diff --git a/apps/studio/src/i18n/ko.ts b/apps/studio/src/i18n/ko.ts index 3fa7cc30..f62d5992 100644 --- a/apps/studio/src/i18n/ko.ts +++ b/apps/studio/src/i18n/ko.ts @@ -1,6 +1,6 @@ // Generated by `pnpm i18n:import` (ADR-0034): ko core messages. // Do not edit: change the translation file and import it; only English is edited here. -// hash: dacaea7556d1f030 +// hash: e7f32cebd9738313 import type { Messages } from "./en.ts"; export const messages: Messages = { @@ -77,6 +77,14 @@ export const messages: Messages = { setupTitle: "이 Studio 설정", setupDescription: "Cloudhal을 시작하거나 배포할 때 표시된 설정 링크를 열었어요. 지금 만드는 계정이 소유자가 되며, 그 후에는 가입이 닫혀요.", + rememberAccount: "이 기기에서 이 계정 기억하기", + chooseAccount: "계속할 계정을 선택하세요.", + rememberedAccounts: "기억된 계정", + continueAs: "{name}({email})(으)로 계속", + continueAsEmail: "{email}(으)로 계속", + forgetAccount: "이 기기에서 {email} 삭제", + useAnotherAccount: "다른 계정 사용", + signOutAndForget: "로그아웃하고 삭제", }, sites: { title: "사이트", diff --git a/apps/studio/src/i18n/nl.ts b/apps/studio/src/i18n/nl.ts index fadd59ce..0d0711dc 100644 --- a/apps/studio/src/i18n/nl.ts +++ b/apps/studio/src/i18n/nl.ts @@ -1,6 +1,6 @@ // Generated by `pnpm i18n:import` (ADR-0034): nl core messages. // Do not edit: change the translation file and import it; only English is edited here. -// hash: 12d9d9ac755efefe +// hash: b91723d38cb3b4b3 import type { Messages } from "./en.ts"; export const messages: Messages = { @@ -78,6 +78,14 @@ export const messages: Messages = { setupTitle: "Deze Studio instellen", setupDescription: "Je hebt de installatielink geopend die Cloudhal bij het starten of deployen liet zien. Het account dat je nu aanmaakt, wordt de eigenaar; daarna sluit de registratie.", + rememberAccount: "Dit account onthouden op dit apparaat", + chooseAccount: "Kies een account om verder te gaan.", + rememberedAccounts: "Onthouden accounts", + continueAs: "Doorgaan als {name} ({email})", + continueAsEmail: "Doorgaan als {email}", + forgetAccount: "{email} op dit apparaat vergeten", + useAnotherAccount: "Een ander account gebruiken", + signOutAndForget: "Uitloggen en vergeten", }, sites: { title: "Sites", diff --git a/apps/studio/src/i18n/pl.ts b/apps/studio/src/i18n/pl.ts index b1da5eb3..2e65d8cd 100644 --- a/apps/studio/src/i18n/pl.ts +++ b/apps/studio/src/i18n/pl.ts @@ -1,6 +1,6 @@ // Generated by `pnpm i18n:import` (ADR-0034): pl core messages. // Do not edit: change the translation file and import it; only English is edited here. -// hash: ab65addf8e204c1f +// hash: cbf9704224142224 import type { Messages } from "./en.ts"; export const messages: Messages = { @@ -77,6 +77,14 @@ export const messages: Messages = { setupTitle: "Skonfiguruj to Studio", setupDescription: "Otwarto link konfiguracyjny wyświetlony przy uruchomieniu lub wdrożeniu Cloudhal. Konto, które teraz utworzysz, stanie się właścicielem; potem rejestracja zostanie zamknięta.", + rememberAccount: "Zapamiętaj to konto na tym urządzeniu", + chooseAccount: "Wybierz konto, aby kontynuować.", + rememberedAccounts: "Zapamiętane konta", + continueAs: "Kontynuuj jako {name} ({email})", + continueAsEmail: "Kontynuuj jako {email}", + forgetAccount: "Zapomnij {email} na tym urządzeniu", + useAnotherAccount: "Użyj innego konta", + signOutAndForget: "Wyloguj się i zapomnij", }, sites: { title: "Witryny", diff --git a/apps/studio/src/i18n/pt-BR.ts b/apps/studio/src/i18n/pt-BR.ts index 31a668f3..8e196d69 100644 --- a/apps/studio/src/i18n/pt-BR.ts +++ b/apps/studio/src/i18n/pt-BR.ts @@ -1,6 +1,6 @@ // Generated by `pnpm i18n:import` (ADR-0034): pt-BR core messages. // Do not edit: change the translation file and import it; only English is edited here. -// hash: cbade8868d25bd82 +// hash: e7aa2a35f9bf2d6a import type { Messages } from "./en.ts"; export const messages: Messages = { @@ -77,6 +77,14 @@ export const messages: Messages = { setupTitle: "Configurar este Studio", setupDescription: "Você abriu o link de configuração exibido quando o Cloudhal foi iniciado ou implantado. A conta que você criar agora se torna a proprietária; depois disso, o cadastro é fechado.", + rememberAccount: "Lembrar esta conta neste dispositivo", + chooseAccount: "Escolha uma conta para continuar.", + rememberedAccounts: "Contas lembradas", + continueAs: "Continuar como {name} ({email})", + continueAsEmail: "Continuar como {email}", + forgetAccount: "Esquecer {email} neste dispositivo", + useAnotherAccount: "Usar outra conta", + signOutAndForget: "Sair e esquecer", }, sites: { title: "Sites", diff --git a/apps/studio/src/i18n/ru.ts b/apps/studio/src/i18n/ru.ts index 1e2fa272..f42f3464 100644 --- a/apps/studio/src/i18n/ru.ts +++ b/apps/studio/src/i18n/ru.ts @@ -1,6 +1,6 @@ // Generated by `pnpm i18n:import` (ADR-0034): ru core messages. // Do not edit: change the translation file and import it; only English is edited here. -// hash: c19915dbe8b8c235 +// hash: 2de3ad00b5c14d8f import type { Messages } from "./en.ts"; export const messages: Messages = { @@ -77,6 +77,14 @@ export const messages: Messages = { setupTitle: "Настройка этого Studio", setupDescription: "Вы открыли ссылку настройки, которую Cloudhal показал при запуске или развёртывании. Учётная запись, которую вы сейчас создадите, станет владельцем; после этого регистрация закроется.", + rememberAccount: "Запомнить этот аккаунт на этом устройстве", + chooseAccount: "Выберите аккаунт, чтобы продолжить.", + rememberedAccounts: "Запомненные аккаунты", + continueAs: "Продолжить как {name} ({email})", + continueAsEmail: "Продолжить как {email}", + forgetAccount: "Забыть {email} на этом устройстве", + useAnotherAccount: "Использовать другой аккаунт", + signOutAndForget: "Выйти и забыть", }, sites: { title: "Сайты", diff --git a/apps/studio/src/i18n/sv.ts b/apps/studio/src/i18n/sv.ts index 9768b4de..e0806a9f 100644 --- a/apps/studio/src/i18n/sv.ts +++ b/apps/studio/src/i18n/sv.ts @@ -1,6 +1,6 @@ // Generated by `pnpm i18n:import` (ADR-0034): sv core messages. // Do not edit: change the translation file and import it; only English is edited here. -// hash: 0e9103823cbb2caf +// hash: cfa23c5d11aa851c import type { Messages } from "./en.ts"; export const messages: Messages = { @@ -77,6 +77,14 @@ export const messages: Messages = { setupTitle: "Konfigurera den här Studion", setupDescription: "Du öppnade konfigurationslänken som skrevs ut när Cloudhal startades eller driftsattes. Kontot du skapar nu blir ägare; därefter stängs registreringen.", + rememberAccount: "Kom ihåg det här kontot på den här enheten", + chooseAccount: "Välj ett konto för att fortsätta.", + rememberedAccounts: "Sparade konton", + continueAs: "Fortsätt som {name} ({email})", + continueAsEmail: "Fortsätt som {email}", + forgetAccount: "Glöm {email} på den här enheten", + useAnotherAccount: "Använd ett annat konto", + signOutAndForget: "Logga ut och glöm", }, sites: { title: "Webbplatser", diff --git a/apps/studio/src/i18n/tr.ts b/apps/studio/src/i18n/tr.ts index 528b5f48..312edcdd 100644 --- a/apps/studio/src/i18n/tr.ts +++ b/apps/studio/src/i18n/tr.ts @@ -1,6 +1,6 @@ // Generated by `pnpm i18n:import` (ADR-0034): tr core messages. // Do not edit: change the translation file and import it; only English is edited here. -// hash: b0e2d5c49195ee40 +// hash: eeec3eceb087d2de import type { Messages } from "./en.ts"; export const messages: Messages = { @@ -77,6 +77,14 @@ export const messages: Messages = { setupTitle: "Bu Studio'yu kur", setupDescription: "Cloudhal başlarken ya da dağıtılırken yazdırılan kurulum bağlantısıyla geldin. Şimdi oluşturacağın hesap Sahip olur; ardından kayıt kapanır.", + rememberAccount: "Bu hesabı bu cihazda hatırla", + chooseAccount: "Devam etmek için bir hesap seç.", + rememberedAccounts: "Hatırlanan hesaplar", + continueAs: "{name} ({email}) olarak devam et", + continueAsEmail: "{email} olarak devam et", + forgetAccount: "{email} hesabını bu cihazda unut", + useAnotherAccount: "Başka bir hesap kullan", + signOutAndForget: "Çıkış yap ve unut", }, sites: { title: "Siteler", diff --git a/apps/studio/src/i18n/uk.ts b/apps/studio/src/i18n/uk.ts index c4c392ef..3609e3db 100644 --- a/apps/studio/src/i18n/uk.ts +++ b/apps/studio/src/i18n/uk.ts @@ -1,6 +1,6 @@ // Generated by `pnpm i18n:import` (ADR-0034): uk core messages. // Do not edit: change the translation file and import it; only English is edited here. -// hash: 571695039fc6ea57 +// hash: d20efa8d49457fab import type { Messages } from "./en.ts"; export const messages: Messages = { @@ -77,6 +77,14 @@ export const messages: Messages = { setupTitle: "Налаштування цієї Studio", setupDescription: "Ви відкрили посилання для налаштування, яке Cloudhal показав під час запуску або розгортання. Обліковий запис, який ви зараз створите, стане власником; після цього реєстрацію буде закрито.", + rememberAccount: "Запам’ятати цей обліковий запис на цьому пристрої", + chooseAccount: "Виберіть обліковий запис, щоб продовжити.", + rememberedAccounts: "Запам’ятані облікові записи", + continueAs: "Продовжити як {name} ({email})", + continueAsEmail: "Продовжити як {email}", + forgetAccount: "Забути {email} на цьому пристрої", + useAnotherAccount: "Використати інший обліковий запис", + signOutAndForget: "Вийти й забути", }, sites: { title: "Сайти", diff --git a/apps/studio/src/i18n/zh-Hans.ts b/apps/studio/src/i18n/zh-Hans.ts index 1c16b6d6..5ffb01e2 100644 --- a/apps/studio/src/i18n/zh-Hans.ts +++ b/apps/studio/src/i18n/zh-Hans.ts @@ -1,6 +1,6 @@ // Generated by `pnpm i18n:import` (ADR-0034): zh-Hans core messages. // Do not edit: change the translation file and import it; only English is edited here. -// hash: 563fa92c7cce160a +// hash: 05016bbf65f0f92a import type { Messages } from "./en.ts"; export const messages: Messages = { @@ -77,6 +77,14 @@ export const messages: Messages = { setupTitle: "设置此 Studio", setupDescription: "你打开了 Cloudhal 启动或部署时显示的设置链接。你现在创建的账户将成为所有者;之后注册将关闭。", + rememberAccount: "在此设备上记住此账户", + chooseAccount: "选择一个账户以继续。", + rememberedAccounts: "已记住的账户", + continueAs: "以 {name}({email})身份继续", + continueAsEmail: "以 {email} 身份继续", + forgetAccount: "在此设备上忘记 {email}", + useAnotherAccount: "使用其他账户", + signOutAndForget: "退出登录并忘记", }, sites: { title: "站点", diff --git a/apps/studio/src/lib/login-redirect.ts b/apps/studio/src/lib/login-redirect.ts new file mode 100644 index 00000000..ac78c2e7 --- /dev/null +++ b/apps/studio/src/lib/login-redirect.ts @@ -0,0 +1,37 @@ +/** + * Where sign-in goes next (#388): `requireSession` sends a signed-out member to + * `/login?redirect=`, and the login page goes back there afterwards. The + * value comes from the URL, so anyone can craft it: only a path on Studio's own origin is kept, + * never another site (an open redirect) or a script URL. + */ +export const MAX_REDIRECT_LENGTH = 2048; + +/** Any C0 control character, DEL, or a C1 control: browsers strip or reinterpret them in URLs. */ +function isControl(code: number): boolean { + return code < 0x20 || (code >= 0x7f && code <= 0x9f); +} + +/** + * `value` when it is a same-origin path (`/sites/a?x=1#y`), else `undefined`. Rejected: anything + * not starting with `/`, a protocol-relative start (`//`, `/\`), a scheme, a backslash or control + * character anywhere (the URL parser drops tabs and turns `\` into `/`, so `/\t/evil` would + * become `//evil`), and anything longer than 2 kB. One pass over the string, no patterns + * (AGENTS.md rule 13). + */ +export function safeRedirect(value: unknown): string | undefined { + if (typeof value !== "string") return undefined; + if (value.length === 0 || value.length > MAX_REDIRECT_LENGTH) return undefined; + if (value[0] !== "/" || value[1] === "/" || value[1] === "\\") return undefined; + for (let i = 0; i < value.length; i++) { + const code = value.charCodeAt(i); + if (code === 0x5c || isControl(code)) return undefined; + } + // Belt and braces: whatever the browser makes of it must stay on this origin. + try { + const base = "https://studio.invalid"; + if (new URL(value, base).origin !== base) return undefined; + } catch { + return undefined; + } + return value; +} diff --git a/apps/studio/src/lib/remembered-accounts.ts b/apps/studio/src/lib/remembered-accounts.ts new file mode 100644 index 00000000..5e490169 --- /dev/null +++ b/apps/studio/src/lib/remembered-accounts.ts @@ -0,0 +1,223 @@ +/** + * Remembered accounts on the signed-out `/login` (#388 step 3, like Cloudflare's login + * profiles). Opt-in: a member ticks "Remember this account on this device" when signing in, and + * the login page then lists the account. An entry holds the email, the display name and when it + * was last used — never a token, a session id, a role or a user id: it is a convenience, not a + * credential, and sessions stay in HttpOnly cookies. + * + * Bounded: at most `MAX_ACCOUNTS` entries per origin (the oldest goes), each dropped after + * `MAX_AGE_MS` without a sign-in, removed by "Forget" or "Sign out and forget". Every read checks + * the shape and drops what does not fit; every access is guarded, so the login page works when + * storage is disabled, full or throws. + */ + +/** One `localStorage` key per origin, versioned so a later shape can move on without a migration. */ +export const REMEMBERED_ACCOUNTS_KEY = "cloudhal.rememberedAccounts.v1"; +export const MAX_ACCOUNTS = 5; +export const MAX_AGE_MS = 30 * 24 * 60 * 60_000; +/** RFC 5321's longest usable address. */ +export const MAX_EMAIL_LENGTH = 254; +export const MAX_NAME_LENGTH = 100; +/** A clock a little ahead of the one that wrote the entry is fine; a date far ahead is not. */ +const MAX_FUTURE_SKEW_MS = 24 * 60 * 60_000; + +export interface RememberedAccount { + email: string; + /** Display name from the sign-in response; may be empty. */ + name: string; + /** Milliseconds since the epoch. */ + lastUsedAt: number; +} + +/** The part of `Storage` this module uses; tests pass their own. */ +export type AccountStorage = Pick; + +export interface StoreOptions { + /** Defaults to `window.localStorage` (none when it throws). */ + storage?: AccountStorage | undefined; + /** Defaults to `Date.now()`. */ + now?: number | undefined; +} + +function defaultStorage(): AccountStorage | undefined { + try { + return globalThis.localStorage ?? undefined; + } catch { + return undefined; + } +} + +/** The key emails are compared by. */ +export function emailKey(email: string): string { + return email.trim().toLowerCase(); +} + +function validEmail(email: unknown): email is string { + if (typeof email !== "string") return false; + const trimmed = email.trim(); + if (trimmed.length < 3 || trimmed.length > MAX_EMAIL_LENGTH || trimmed !== email) return false; + const at = trimmed.indexOf("@"); + return at > 0 && at < trimmed.length - 1 && !hasControl(trimmed); +} + +function hasControl(text: string): boolean { + for (let i = 0; i < text.length; i++) { + const code = text.charCodeAt(i); + if (code < 0x20 || code === 0x7f) return true; + } + return false; +} + +/** A stored entry, or `undefined` when it is malformed or expired. */ +function parseEntry(value: unknown, now: number): RememberedAccount | undefined { + if (typeof value !== "object" || value === null || Array.isArray(value)) return undefined; + const { email, name, lastUsedAt, ...rest } = value as Record; + if (Object.keys(rest).length > 0) return undefined; + if (!validEmail(email)) return undefined; + if (typeof name !== "string" || name.length > MAX_NAME_LENGTH || hasControl(name)) { + return undefined; + } + if (typeof lastUsedAt !== "number" || !Number.isFinite(lastUsedAt) || lastUsedAt < 0) { + return undefined; + } + if (lastUsedAt > now + MAX_FUTURE_SKEW_MS || now - lastUsedAt > MAX_AGE_MS) return undefined; + return { email, name, lastUsedAt }; +} + +/** Newest first, one entry per email (the newest), at most `MAX_ACCOUNTS`. */ +function normalize(entries: RememberedAccount[]): RememberedAccount[] { + const sorted = [...entries].sort((a, b) => b.lastUsedAt - a.lastUsedAt); + const seen = new Set(); + const out: RememberedAccount[] = []; + for (const entry of sorted) { + const key = emailKey(entry.email); + if (seen.has(key)) continue; + seen.add(key); + out.push(entry); + if (out.length === MAX_ACCOUNTS) break; + } + return out; +} + +function load( + storage: AccountStorage, + now: number, +): { entries: RememberedAccount[]; raw: string | null } { + let raw: string | null; + try { + raw = storage.getItem(REMEMBERED_ACCOUNTS_KEY); + } catch { + return { entries: [], raw: null }; + } + if (raw === null) return { entries: [], raw }; + let parsed: unknown; + try { + parsed = JSON.parse(raw); + } catch { + return { entries: [], raw }; + } + if (!Array.isArray(parsed)) return { entries: [], raw }; + const entries: RememberedAccount[] = []; + for (const item of parsed.slice(0, MAX_ACCOUNTS * 4)) { + const entry = parseEntry(item, now); + if (entry) entries.push(entry); + } + return { entries: normalize(entries), raw }; +} + +/** Writes `entries` (removing the key when empty); `false` when storage refused. */ +function save(storage: AccountStorage, entries: RememberedAccount[]): boolean { + try { + if (entries.length === 0) storage.removeItem(REMEMBERED_ACCOUNTS_KEY); + else storage.setItem(REMEMBERED_ACCOUNTS_KEY, JSON.stringify(entries)); + return true; + } catch { + return false; + } +} + +function context(options: StoreOptions): { storage: AccountStorage | undefined; now: number } { + return { storage: options.storage ?? defaultStorage(), now: options.now ?? Date.now() }; +} + +/** + * The remembered accounts, newest first. Expired, malformed and duplicate entries are dropped, + * and the stored list is rewritten without them, so a forgotten email does not linger. + */ +export function readRememberedAccounts(options: StoreOptions = {}): RememberedAccount[] { + const { storage, now } = context(options); + if (!storage) return []; + const { entries, raw } = load(storage, now); + if (raw !== null && raw !== JSON.stringify(entries)) save(storage, entries); + return entries; +} + +/** + * Remembers `account` (after a sign-in the member asked to be remembered for) or refreshes its + * entry: the email matches case-insensitively, the name and `lastUsedAt` are updated. An email + * that does not fit is not stored; a long name is cut. Returns the list as stored. + */ +export function rememberAccount( + account: { email: string; name?: string | null | undefined }, + options: StoreOptions = {}, +): RememberedAccount[] { + const { storage, now } = context(options); + if (!storage) return []; + const { entries } = load(storage, now); + const email = account.email.trim(); + if (!validEmail(email)) return entries; + const key = emailKey(email); + // A response without a name (an OAuth sign-in answers with where to go) keeps the one known. + const name = + cleanName(account.name) || entries.find((e) => emailKey(e.email) === key)?.name || ""; + const next = normalize([ + { email, name, lastUsedAt: now }, + ...entries.filter((e) => emailKey(e.email) !== key), + ]); + return save(storage, next) ? next : entries; +} + +function cleanName(name: string | null | undefined): string { + if (typeof name !== "string") return ""; + let out = ""; + for (const ch of name.trim()) { + const code = ch.charCodeAt(0); + if (code < 0x20 || code === 0x7f) continue; + if (out.length + ch.length > MAX_NAME_LENGTH) break; + out += ch; + } + return out; +} + +/** Whether `email` is remembered on this device. */ +export function isRemembered(email: string, options: StoreOptions = {}): boolean { + const key = emailKey(email); + return readRememberedAccounts(options).some((e) => emailKey(e.email) === key); +} + +/** + * Refreshes an entry that is already remembered (a sign-in without ticking the box again); does + * nothing for an email that is not. Returns whether it was remembered. + */ +export function touchRememberedAccount( + account: { email: string; name?: string | null | undefined }, + options: StoreOptions = {}, +): boolean { + const opts = { ...options, now: options.now ?? Date.now() }; + if (!isRemembered(account.email, opts)) return false; + rememberAccount(account, opts); + return true; +} + +/** Forgets `email` on this device. Returns the remaining list. */ +export function forgetRememberedAccount( + email: string, + options: StoreOptions = {}, +): RememberedAccount[] { + const { storage, now } = context(options); + if (!storage) return []; + const { entries } = load(storage, now); + const key = emailKey(email); + const next = entries.filter((e) => emailKey(e.email) !== key); + return save(storage, next) ? next : entries; +} diff --git a/apps/studio/src/lib/route-guards.ts b/apps/studio/src/lib/route-guards.ts new file mode 100644 index 00000000..97de0e24 --- /dev/null +++ b/apps/studio/src/lib/route-guards.ts @@ -0,0 +1,64 @@ +import { redirect } from "@tanstack/react-router"; +import { api } from "./api.ts"; +import { authClient } from "./auth.ts"; +import { safeRedirect } from "./login-redirect.ts"; +import { cachedSession } from "./session-cache.ts"; + +/** What `beforeLoad` passes that the guards read: the address being opened. */ +interface GuardInput { + location?: { href: string; search: Record }; +} + +/** + * The signed-in session (kept between navigations, lib/session-cache.ts: asking each time held + * every screen back), and whether this deployment is a playground. RFC-0036 §5: a playground has + * no sign-in (its API refuses /api/auth with 403) and answers every call as its one fixed + * principal. A caller that shared another's request has no status of its own, so it asks too. + */ +async function sessionState(): Promise<{ session: unknown; playground: boolean }> { + const last: { status?: number } = {}; + const session = await cachedSession(async () => { + const r = await authClient.getSession(); + if (r.error) last.status = r.error.status; + return r.data; + }); + if (session) return { session, playground: false }; + return { session: null, playground: (last.status ?? 403) === 403 && (await isPlayground()) }; +} + +async function isPlayground(): Promise { + try { + return (await api.instance()).features.playground !== undefined; + } catch { + return false; + } +} + +/** + * `beforeLoad` of the signed-in screens. Signed out, it sends the member to the login page with + * the address they opened (`?redirect=`), where sign-in brings them back (#388). + */ +export async function requireSession(input: GuardInput = {}) { + const { session, playground } = await sessionState(); + if (session) return session; + if (playground) return null; + const back = input.location ? safeRedirect(input.location.href) : undefined; + throw redirect({ + to: "/login", + search: back && back !== "/" ? { redirect: back } : {}, + }); +} + +/** + * `beforeLoad` of the guest pages (`/login`, `/forgot-password`, `/reset-password`, #388): a + * signed-in member goes on to the `redirect` they came for, or to `/sites`; a playground, which + * has no sign-in, goes to `/sites`. An RFC-0044 authorization request (`?client_id=…&sig=…`) + * stays: the provider may ask a signed-in member to sign in again. + */ +export async function guestOnly(input: GuardInput = {}) { + const search = input.location?.search ?? {}; + if ("client_id" in search && "sig" in search) return; + const { session, playground } = await sessionState(); + if (session) throw redirect({ href: safeRedirect(search.redirect) ?? "/sites", replace: true }); + if (playground) throw redirect({ to: "/sites", replace: true }); +} diff --git a/apps/studio/src/router.tsx b/apps/studio/src/router.tsx index 6fa719f5..eb10ba36 100644 --- a/apps/studio/src/router.tsx +++ b/apps/studio/src/router.tsx @@ -10,11 +10,10 @@ import { import { RouteError, RoutePending } from "./components/RouteStates.tsx"; import { LOCALE_LIST, withMessages } from "./i18n/index.tsx"; import { type AnalyticsSearch, validateAnalyticsSearch } from "./lib/analytics-search.ts"; -import { api } from "./lib/api.ts"; -import { authClient } from "./lib/auth.ts"; import { isQueueTab, type QueueTab } from "./lib/comments-shell.ts"; import { listingSearch } from "./lib/listing-search.ts"; -import { cachedSession } from "./lib/session-cache.ts"; +import { safeRedirect } from "./lib/login-redirect.ts"; +import { guestOnly, requireSession } from "./lib/route-guards.ts"; import { AccountShell } from "./routes/AccountShell.tsx"; import { SiteShell } from "./routes/SiteShell.tsx"; @@ -179,34 +178,18 @@ export interface RouterContext { queryClient: QueryClient; } -async function requireSession() { - // Kept between navigations (lib/session-cache.ts): asking each time held every screen back. - const last: { status?: number } = {}; - const data = await cachedSession(async () => { - const r = await authClient.getSession(); - if (r.error) last.status = r.error.status; - return r.data; - }); - if (data) return data; - // RFC-0036 §5: a playground has no sign-in (its API refuses /api/auth with 403) and answers - // every call as its one fixed principal. - // (A caller that shared another's request has no status of its own: it asks too.) - if ((last.status ?? 403) === 403 && (await isPlayground())) return null; - throw redirect({ to: "/login" }); -} - -async function isPlayground(): Promise { - try { - return (await api.instance()).features.playground !== undefined; - } catch { - return false; - } -} - const rootRoute = createRootRouteWithContext()({ component: () => }); +/** + * Guest pages (#388): a signed-in member is sent on (`guestOnly`). `?redirect=` is where sign-in + * goes next, kept only when it is a path on this origin (`lib/login-redirect.ts`). + */ const loginRoute = createRoute({ getParentRoute: () => rootRoute, path: "/login", + validateSearch: (search: Record): { redirect?: string } => ({ + redirect: safeRedirect(search.redirect), + }), + beforeLoad: guestOnly, component: LoginPage, }); /** @@ -222,11 +205,13 @@ const inviteRoute = createRoute({ const forgotPasswordRoute = createRoute({ getParentRoute: () => rootRoute, path: "/forgot-password", + beforeLoad: guestOnly, component: ForgotPasswordPage, }); const resetPasswordRoute = createRoute({ getParentRoute: () => rootRoute, path: "/reset-password", + beforeLoad: guestOnly, component: ResetPasswordPage, }); const indexRoute = createRoute({ diff --git a/apps/studio/src/routes/LoginPage.tsx b/apps/studio/src/routes/LoginPage.tsx index 7eaf731d..e5e1d20b 100644 --- a/apps/studio/src/routes/LoginPage.tsx +++ b/apps/studio/src/routes/LoginPage.tsx @@ -1,12 +1,18 @@ import { AuthLayout, Banner, Button, Input, Link, Tabs, Text } from "@cloudhal/ui"; import { Key, SquaresFour } from "@phosphor-icons/react"; -import { useNavigate } from "@tanstack/react-router"; +import { useNavigate, useSearch } from "@tanstack/react-router"; import { type FormEvent, useEffect, useState } from "react"; import { ErrorBanner } from "../components/ErrorBanner.tsx"; import { LanguageSwitch } from "../components/LanguageSwitch.tsx"; import { PasswordField } from "../components/PasswordField.tsx"; +import { + RememberAccountCheckbox, + RememberedAccountChooser, +} from "../components/RememberedAccounts.tsx"; +import { useRememberedLogin } from "../components/useRememberedLogin.ts"; import { useT } from "../i18n/index.tsx"; import { authClient } from "../lib/auth.ts"; +import { safeRedirect } from "../lib/login-redirect.ts"; const SETUP_KEY = "cloudhal.setupToken"; @@ -74,6 +80,8 @@ export function oauthRequest(): string | undefined { export function LoginPage() { const t = useT(); const navigate = useNavigate(); + // Where the member was going when `requireSession` sent them here (#388); same-origin paths only. + const back = safeRedirect((useSearch({ strict: false }) as { redirect?: unknown }).redirect); const [setupToken] = useState(takeSetupToken); const [authorization] = useState(oauthRequest); const [mode, setMode] = useState<"signin" | "signup">(setupToken ? "signup" : "signin"); @@ -85,6 +93,16 @@ export function LoginPage() { const [password, setPassword] = useState(""); const [error, setError] = useState(); const [busy, setBusy] = useState(false); + // #388 step 3: accounts remembered on this device are listed first, in sign-in mode only. + const saved = useRememberedLogin({ + signingIn: mode === "signin", + email, + onChosen: (chosen) => { + setEmail(chosen); + setPassword(""); + setError(undefined); + }, + }); async function submit(e: FormEvent) { e.preventDefault(); @@ -106,6 +124,7 @@ export function LoginPage() { setError(result.error.message ?? t("auth.failed")); return; } + if (mode === "signin") saved.keep(result.data, email); try { sessionStorage.removeItem(SETUP_KEY); } catch { @@ -116,7 +135,8 @@ export function LoginPage() { window.location.assign(next); return; } - await navigate({ to: "/sites" }); + if (back) await navigate({ href: back }); + else await navigate({ to: "/sites" }); } return ( @@ -124,25 +144,17 @@ export function LoginPage() { brand={} product={t("app.name")} title={mode === "signup" ? t("auth.signUpTitle") : t("auth.signInTitle")} - description={mode === "signup" ? t("auth.signUpDescription") : t("app.tagline")} - footer={ - <> - - {t("auth.footer")} - - - + description={ + mode === "signup" + ? t("auth.signUpDescription") + : saved.showChooser + ? t("auth.chooseAccount") + : t("app.tagline") } + footer={} >
- {setupToken && mode === "signup" && ( - } - title={t("auth.setupTitle")} - description={t("auth.setupDescription")} - /> - )} + {setupToken && mode === "signup" && } - {mode === "signup" && ( - + ) : ( + <> + {mode === "signup" && ( + + )} + + + {mode === "signin" && ( + + )} + + + )} - - - {mode === "signin" && ( - - {t("forgotPassword.link")} - - )} - - ); } + +/** A fresh deployment's owner, arrived with the setup link. */ +function SetupBanner() { + const t = useT(); + return ( + } + title={t("auth.setupTitle")} + description={t("auth.setupDescription")} + /> + ); +} + +function LoginFooter() { + const t = useT(); + return ( + <> + + {t("auth.footer")} + + + + ); +} + +/** Under the sign-in fields: "Forgot password?" and the opt-in, unless the email is remembered already. */ +function SignInExtras({ + remembered, + remember, + onRememberChange, +}: { + remembered: boolean; + remember: boolean; + onRememberChange: (remember: boolean) => void; +}) { + const t = useT(); + return ( + <> + + {t("forgotPassword.link")} + + {!remembered && ( + + )} + + ); +} diff --git a/apps/studio/test/login-guest.test.tsx b/apps/studio/test/login-guest.test.tsx new file mode 100644 index 00000000..dc641999 --- /dev/null +++ b/apps/studio/test/login-guest.test.tsx @@ -0,0 +1,261 @@ +/** + * #388: `/login` is a guest page (a signed-in member goes on), and a signed-out member's deep link + * survives sign-in (`?redirect=`). + */ +import { + createMemoryHistory, + createRootRoute, + createRoute, + createRouter, + RouterProvider, +} from "@tanstack/react-router"; +import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { authClient } from "../src/lib/auth.ts"; +import { safeRedirect } from "../src/lib/login-redirect.ts"; +import { forgetSession } from "../src/lib/session-cache.ts"; +import { createStudioRouter } from "../src/router.tsx"; +import { LoginPage } from "../src/routes/LoginPage.tsx"; +import { INSTANCE, wrap } from "./roles-fixtures.tsx"; + +/** + * Better Auth's client keeps the `fetch` it saw when `lib/auth.ts` loaded, so `vi.stubGlobal` + * would come too late: a forwarding `fetch` is in place before the imports run. + */ +const fetchStub = vi.hoisted(() => { + const stub: { impl?: typeof fetch } = {}; + const real = globalThis.fetch; + globalThis.fetch = ((...args: Parameters) => + (stub.impl ?? real)(...args)) as typeof fetch; + return stub; +}); + +afterEach(() => { + cleanup(); + forgetSession(); + fetchStub.impl = undefined; + window.history.replaceState(null, "", "/"); +}); + +const SESSION = { + session: { id: "s1", token: "t1", userId: "u1", expiresAt: "2999-01-01T00:00:00.000Z" }, + user: { id: "u1", name: "Ada", email: "ada@example.test" }, +}; + +/** Stubs `fetch` for the auth calls the guards and the login form make. */ +function server(opts: { signedIn: boolean; playground?: boolean }) { + const state = { signedIn: opts.signedIn }; + const json = (body: unknown, status = 200) => + new Response(JSON.stringify(body), { + status, + headers: { "content-type": "application/json" }, + }); + const fetch = vi.fn(async (input: string | URL | Request, init?: RequestInit) => { + const url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url; + const path = url.replace(/^https?:\/\/[^/]+/, "").split("?")[0]; + const method = ( + init?.method ?? (input instanceof Request ? input.method : "GET") + ).toUpperCase(); + if (path === "/api/auth/get-session") { + if (opts.playground) return json({ message: "forbidden" }, 403); + return json(state.signedIn ? SESSION : null); + } + if (path === "/api/auth/sign-out" && method === "POST") { + state.signedIn = false; + return json({ success: true }); + } + if (path === "/api/auth/sign-in/email" && method === "POST") { + state.signedIn = true; + return json({ redirect: false, token: "t1", user: SESSION.user }); + } + if (path === "/api/instance") { + const features = opts.playground + ? { ...INSTANCE.features, playground: { expiresAt: "2999-01-01T00:00:00.000Z" } } + : INSTANCE.features; + return json({ ...INSTANCE, features }); + } + return json({ error: "not_found", message: path }, 404); + }); + fetchStub.impl = fetch as unknown as typeof globalThis.fetch; + const sessionChecks = () => + fetch.mock.calls.filter(([u]) => String(u).includes("/api/auth/get-session")).length; + return { fetch, sessionChecks }; +} + +/** Runs a route's `beforeLoad` as the router would for `href`; the redirect it throws, if any. */ +async function beforeLoad(routeId: string, href: string) { + const router = createStudioRouter(undefined as never); + const route = router.routesById[routeId as keyof typeof router.routesById]; + const url = new URL(href, "http://studio.test"); + const location = router.parseLocation({ + pathname: url.pathname, + search: url.search, + hash: url.hash, + href, + state: {} as never, + }); + try { + await route.options.beforeLoad?.({ location, params: {}, search: location.search } as never); + return undefined; + } catch (thrown) { + return (thrown as { options?: Record }).options ?? thrown; + } +} + +describe("guest pages with a session (#388)", () => { + it("/login goes to /sites", async () => { + server({ signedIn: true }); + expect(await beforeLoad("/login", "/login")).toMatchObject({ href: "/sites", replace: true }); + }); + + it("/login?redirect=/sites/a goes to /sites/a", async () => { + server({ signedIn: true }); + expect(await beforeLoad("/login", "/login?redirect=%2Fsites%2Fa")).toMatchObject({ + href: "/sites/a", + }); + }); + + it("an unsafe redirect goes to /sites instead", async () => { + server({ signedIn: true }); + expect(await beforeLoad("/login", "/login?redirect=%2F%2Fevil.example")).toMatchObject({ + href: "/sites", + }); + }); + + it("an RFC-0044 authorization request stays, without asking for the session", async () => { + const { sessionChecks } = server({ signedIn: true }); + expect(await beforeLoad("/login", "/login?client_id=x&sig=y")).toBeUndefined(); + expect(sessionChecks()).toBe(0); + }); + + it("/forgot-password and /reset-password go on too; /invite does not check", async () => { + server({ signedIn: true }); + expect(await beforeLoad("/forgot-password", "/forgot-password")).toMatchObject({ + href: "/sites", + }); + expect(await beforeLoad("/reset-password", "/reset-password")).toMatchObject({ + href: "/sites", + }); + const router = createStudioRouter(undefined as never); + expect(router.routesById["/invite"].options.beforeLoad).toBeUndefined(); + }); + + it("a cached session costs no request", async () => { + const { sessionChecks } = server({ signedIn: true }); + await beforeLoad("/login", "/login"); + await beforeLoad("/login", "/login"); + expect(sessionChecks()).toBe(1); + }); +}); + +describe("guest pages without a session", () => { + it("/login shows the form", async () => { + server({ signedIn: false }); + expect(await beforeLoad("/login", "/login?redirect=%2Fsites%2Fa")).toBeUndefined(); + }); + + it("a playground, which has no sign-in, goes to /sites", async () => { + server({ signedIn: false, playground: true }); + expect(await beforeLoad("/login", "/login")).toMatchObject({ to: "/sites" }); + }); + + it("sign-out forgets the cached session, so /login then shows the form", async () => { + const { sessionChecks } = server({ signedIn: true }); + expect(await beforeLoad("/login", "/login")).toMatchObject({ href: "/sites" }); + await authClient.signOut(); + expect(await beforeLoad("/login", "/login")).toBeUndefined(); + expect(sessionChecks()).toBe(2); + }); +}); + +describe("a signed-out deep link", () => { + it("redirects to /login?redirect=", async () => { + server({ signedIn: false }); + const target = "/sites/a/collections/posts/e1?tab=x#top"; + expect(await beforeLoad("/sites/$siteId", target)).toMatchObject({ + to: "/login", + search: { redirect: target }, + }); + }); + + it("through the router: the URL keeps the target, and the login route validates it", async () => { + server({ signedIn: false }); + const router = createStudioRouter(undefined as never); + router.update({ + ...router.options, + history: createMemoryHistory({ initialEntries: ["/sites/a/pages"] }), + }); + await router.load(); + expect(router.state.location.pathname).toBe("/login"); + expect(safeRedirect(router.state.location.search.redirect)).toBe("/sites/a/pages"); + const validate = router.routesById["/login"].options.validateSearch as ( + s: Record, + ) => { redirect?: string }; + expect(validate({ redirect: "/sites/a" })).toEqual({ redirect: "/sites/a" }); + expect(validate({ redirect: "https://evil.example" }).redirect).toBeUndefined(); + }); +}); + +describe("LoginPage after sign-in", () => { + function renderLogin(href: string) { + const root = createRootRoute(); + const login = createRoute({ + getParentRoute: () => root, + path: "/login", + validateSearch: (s: Record) => ({ redirect: safeRedirect(s.redirect) }), + component: LoginPage, + }); + const site = createRoute({ + getParentRoute: () => root, + path: "/sites/$siteId", + component: () => site, + }); + const sites = createRoute({ + getParentRoute: () => root, + path: "/sites", + component: () => sites, + }); + const router = createRouter({ + routeTree: root.addChildren([login, site, sites]), + history: createMemoryHistory({ initialEntries: [href] }), + }); + render(wrap()); + return router; + } + + async function signIn() { + fireEvent.change(await screen.findByLabelText("Email"), { + target: { value: "ada@example.test" }, + }); + fireEvent.change(screen.getByLabelText("Password"), { target: { value: "correct horse" } }); + fireEvent.submit(screen.getByTestId("login-form")); + } + + it("goes to the validated redirect", async () => { + server({ signedIn: false }); + const router = renderLogin("/login?redirect=%2Fsites%2Fa"); + await signIn(); + expect(await screen.findByText("site")).toBeInTheDocument(); + expect(router.state.location.href).toBe("/sites/a"); + }); + + it("goes to /sites when the redirect is unsafe or missing", async () => { + server({ signedIn: false }); + const router = renderLogin("/login?redirect=%2F%2Fevil.example"); + await signIn(); + expect(await screen.findByText("sites")).toBeInTheDocument(); + expect(router.state.location.href).toBe("/sites"); + }); + + it("names the email field `username` for sign-in and `email` for a new account", async () => { + server({ signedIn: false }); + renderLogin("/login"); + expect((await screen.findByLabelText("Email")).getAttribute("autocomplete")).toBe("username"); + expect(screen.getByLabelText("Password").getAttribute("autocomplete")).toBe("current-password"); + fireEvent.click(screen.getByRole("tab", { name: "Create account" })); + await waitFor(() => + expect(screen.getByLabelText("Email").getAttribute("autocomplete")).toBe("email"), + ); + expect(screen.getByLabelText("Password").getAttribute("autocomplete")).toBe("new-password"); + }); +}); diff --git a/apps/studio/test/login-redirect.test.ts b/apps/studio/test/login-redirect.test.ts new file mode 100644 index 00000000..5323e3d9 --- /dev/null +++ b/apps/studio/test/login-redirect.test.ts @@ -0,0 +1,51 @@ +import { describe, expect, it } from "vitest"; +import { MAX_REDIRECT_LENGTH, safeRedirect } from "../src/lib/login-redirect.ts"; + +describe("safeRedirect (#388: where sign-in goes next, never off this origin)", () => { + it("keeps a path on this origin, with its query and fragment", () => { + for (const ok of ["/", "/sites", "/sites/a", "/sites/a/collections/posts/e1?tab=x#top"]) + expect(safeRedirect(ok), ok).toBe(ok); + }); + + it("refuses other sites, schemes and protocol-relative starts", () => { + for (const bad of [ + "//evil.example", + "/\\evil.example", + "https://evil.example", + "http:/evil.example", + "javascript:alert(1)", + "JavaScript:alert(1)", + "data:text/html,x", + "evil.example", + "sites/a", + " /sites", + "", + ]) + expect(safeRedirect(bad), bad).toBeUndefined(); + }); + + it("refuses backslashes and control characters anywhere (the URL parser rewrites them)", () => { + for (const bad of ["/a\\b", "/\t/evil.example", "/\n/evil.example", "/a\u0000", "/a\u007f"]) + expect(safeRedirect(bad), JSON.stringify(bad)).toBeUndefined(); + }); + + it("refuses what is not a string", () => { + for (const bad of [undefined, null, 1, ["/sites"], { href: "/sites" }]) + expect(safeRedirect(bad)).toBeUndefined(); + }); + + it("refuses more than 2 kB, and a 100k-character value at once (AGENTS.md rule 13)", () => { + const longest = `/${"a".repeat(MAX_REDIRECT_LENGTH - 1)}`; + expect(safeRedirect(longest)).toBe(longest); + expect(safeRedirect(`${longest}a`)).toBeUndefined(); + for (const huge of [ + `/${"a".repeat(100_000)}`, + `/${"/".repeat(100_000)}`, + "\\".repeat(100_000), + ]) { + const start = performance.now(); + expect(safeRedirect(huge)).toBeUndefined(); + expect(performance.now() - start).toBeLessThan(50); + } + }); +}); diff --git a/apps/studio/test/login-remembered.test.tsx b/apps/studio/test/login-remembered.test.tsx new file mode 100644 index 00000000..a1ab8851 --- /dev/null +++ b/apps/studio/test/login-remembered.test.tsx @@ -0,0 +1,306 @@ +/** + * #388 step 3: opt-in remembered accounts on the signed-out `/login`, and "Sign out and forget" + * in the account menu. + */ +import { + createMemoryHistory, + createRootRoute, + createRoute, + createRouter, + RouterProvider, +} from "@tanstack/react-router"; +import { cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react"; +import type { ReactNode } from "react"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { UserMenu } from "../src/components/UserMenu.tsx"; +import { safeRedirect } from "../src/lib/login-redirect.ts"; +import { + REMEMBERED_ACCOUNTS_KEY, + readRememberedAccounts, + rememberAccount, +} from "../src/lib/remembered-accounts.ts"; +import { forgetSession } from "../src/lib/session-cache.ts"; +import { LoginPage } from "../src/routes/LoginPage.tsx"; +import { INSTANCE, wrap } from "./roles-fixtures.tsx"; + +/** Better Auth's client keeps the `fetch` it saw at import, so a forwarding one goes in first. */ +const fetchStub = vi.hoisted(() => { + const stub: { impl?: typeof fetch } = {}; + const real = globalThis.fetch; + globalThis.fetch = ((...args: Parameters) => + (stub.impl ?? real)(...args)) as typeof fetch; + return stub; +}); + +beforeEach(() => localStorage.clear()); +afterEach(() => { + cleanup(); + forgetSession(); + fetchStub.impl = undefined; + localStorage.clear(); + window.history.replaceState(null, "", "/"); +}); + +const ADA = { id: "u1", name: "Ada Lovelace", email: "ada@example.test" }; + +/** Stubs `fetch` for the auth calls; sign-in succeeds only with `correct horse`. */ +function server() { + const json = (body: unknown, status = 200) => + new Response(JSON.stringify(body), { + status, + headers: { "content-type": "application/json" }, + }); + const fetch = vi.fn(async (input: string | URL | Request, init?: RequestInit) => { + const url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url; + const path = url.replace(/^https?:\/\/[^/]+/, "").split("?")[0]; + if (path === "/api/auth/sign-in/email") { + const body = JSON.parse(String(init?.body ?? "{}")) as { + email?: string; + password?: string; + oauth_query?: string; + }; + if (body.password !== "correct horse") { + return json( + { code: "INVALID_EMAIL_OR_PASSWORD", message: "Invalid email or password" }, + 401, + ); + } + if (body.oauth_query) return json({ redirect: true, url: "/oauth/consent?x=1" }); + return json({ redirect: false, token: "t1", user: { ...ADA, email: body.email } }); + } + if (path === "/api/auth/get-session") { + return json({ session: { id: "s1", userId: "u1" }, user: ADA }); + } + if (path === "/api/auth/sign-out") return json({ success: true }); + if (path === "/api/me") { + return json({ actor: { kind: "human", id: "user_u1", name: ADA.name }, role: "owner" }); + } + if (path === "/api/instance") return json(INSTANCE); + return json({ error: "not_found", message: path }, 404); + }); + fetchStub.impl = fetch as unknown as typeof globalThis.fetch; + return fetch; +} + +function renderAt(href: string, page: () => ReactNode = LoginPage) { + const root = createRootRoute(); + const login = createRoute({ + getParentRoute: () => root, + path: "/login", + validateSearch: (s: Record) => ({ redirect: safeRedirect(s.redirect) }), + component: page, + }); + const menu = createRoute({ getParentRoute: () => root, path: "/menu", component: UserMenu }); + const site = createRoute({ + getParentRoute: () => root, + path: "/sites/$siteId", + component: () => site, + }); + const sites = createRoute({ + getParentRoute: () => root, + path: "/sites", + component: () => sites, + }); + const router = createRouter({ + routeTree: root.addChildren([login, menu, site, sites]), + history: createMemoryHistory({ initialEntries: [href] }), + }); + render(wrap()); + return router; +} + +async function fillAndSubmit(email: string | undefined, password: string) { + if (email !== undefined) { + fireEvent.change(await screen.findByLabelText("Email"), { target: { value: email } }); + } + fireEvent.change(screen.getByLabelText("Password"), { target: { value: password } }); + fireEvent.submit(screen.getByTestId("login-form")); +} + +const rememberBox = () => screen.getByRole("checkbox", { name: /Remember this account/ }); + +describe("the remember choice", () => { + it("is off by default, and an unticked sign-in stores nothing", async () => { + server(); + renderAt("/login"); + await screen.findByLabelText("Email"); + expect(rememberBox()).not.toBeChecked(); + await fillAndSubmit("ada@example.test", "correct horse"); + expect(await screen.findByText("sites")).toBeInTheDocument(); + expect(localStorage.getItem(REMEMBERED_ACCOUNTS_KEY)).toBeNull(); + }); + + it("remembers the email and the name from the response after a successful sign-in", async () => { + server(); + renderAt("/login"); + await screen.findByLabelText("Email"); + fireEvent.click(screen.getByText("Remember this account on this device")); + await waitFor(() => expect(rememberBox()).toBeChecked()); + // Ticking the box does not submit the form. + expect(screen.queryByText("sites")).not.toBeInTheDocument(); + await fillAndSubmit("ada@example.test", "correct horse"); + expect(await screen.findByText("sites")).toBeInTheDocument(); + const [entry] = readRememberedAccounts(); + expect(entry).toMatchObject({ email: "ada@example.test", name: "Ada Lovelace" }); + expect(Object.keys(entry ?? {}).sort()).toEqual(["email", "lastUsedAt", "name"]); + }); + + it("stores nothing when sign-in fails, and keeps the generic error", async () => { + server(); + renderAt("/login"); + await screen.findByLabelText("Email"); + fireEvent.click(screen.getByText("Remember this account on this device")); + await waitFor(() => expect(rememberBox()).toBeChecked()); + await fillAndSubmit("ada@example.test", "wrong"); + expect(await screen.findByRole("alert")).toHaveTextContent("Something went wrong"); + expect(localStorage.getItem(REMEMBERED_ACCOUNTS_KEY)).toBeNull(); + }); + + it("sign-up never remembers and shows no choice", async () => { + server(); + renderAt("/login"); + fireEvent.click(await screen.findByRole("tab", { name: "Create account" })); + await waitFor(() => expect(screen.getByLabelText("Name")).toBeInTheDocument()); + expect(screen.queryByRole("checkbox", { name: /Remember this account/ })).toBeNull(); + }); +}); + +describe("the account chooser", () => { + beforeEach(() => { + rememberAccount({ email: "bob@example.test", name: "Bob" }, { now: Date.now() - 1000 }); + rememberAccount({ email: "ada@example.test", name: "Ada Lovelace" }); + }); + + it("lists remembered accounts first, newest on top", async () => { + server(); + renderAt("/login"); + const list = await screen.findByRole("list", { name: "Remembered accounts" }); + const rows = within(list).getAllByRole("button", { name: /^Continue as/ }); + expect(rows.map((r) => r.getAttribute("aria-label"))).toEqual([ + "Continue as Ada Lovelace (ada@example.test)", + "Continue as Bob (bob@example.test)", + ]); + expect(screen.queryByLabelText("Password")).toBeNull(); + expect(screen.getByText("Choose an account to continue.")).toBeInTheDocument(); + }); + + it("picking one fills in the email and focuses the password", async () => { + server(); + renderAt("/login"); + fireEvent.click( + await screen.findByRole("button", { name: "Continue as Bob (bob@example.test)" }), + ); + expect(await screen.findByLabelText("Email")).toHaveValue("bob@example.test"); + await waitFor(() => expect(screen.getByLabelText("Password")).toHaveFocus()); + // Already remembered: no box, and the sign-in refreshes the entry. + expect(screen.queryByRole("checkbox", { name: /Remember this account/ })).toBeNull(); + const before = readRememberedAccounts()[1]?.lastUsedAt ?? 0; + await fillAndSubmit(undefined, "correct horse"); + expect(await screen.findByText("sites")).toBeInTheDocument(); + const [first] = readRememberedAccounts(); + expect(first?.email).toBe("bob@example.test"); + expect(first?.lastUsedAt).toBeGreaterThan(before); + }); + + it("Forget removes only that account; the form shows once none are left", async () => { + server(); + renderAt("/login"); + fireEvent.click( + await screen.findByRole("button", { name: "Forget ada@example.test on this device" }), + ); + expect(readRememberedAccounts().map((a) => a.email)).toEqual(["bob@example.test"]); + expect(screen.queryByRole("button", { name: /Continue as Ada/ })).toBeNull(); + fireEvent.click(screen.getByRole("button", { name: "Forget bob@example.test on this device" })); + expect(await screen.findByLabelText("Email")).toHaveValue(""); + expect(localStorage.getItem(REMEMBERED_ACCOUNTS_KEY)).toBeNull(); + }); + + it("“Use another account” shows the empty form", async () => { + server(); + renderAt("/login"); + fireEvent.click(await screen.findByRole("button", { name: "Use another account" })); + expect(await screen.findByLabelText("Email")).toHaveValue(""); + expect(rememberBox()).not.toBeChecked(); + }); + + it("is not shown in sign-up mode", async () => { + server(); + renderAt("/login"); + await screen.findByRole("list", { name: "Remembered accounts" }); + fireEvent.click(screen.getByRole("tab", { name: "Create account" })); + await waitFor(() => expect(screen.getByLabelText("Name")).toBeInTheDocument()); + expect(screen.queryByRole("list", { name: "Remembered accounts" })).toBeNull(); + }); + + it("keeps ?redirect= through the chooser", async () => { + server(); + const router = renderAt("/login?redirect=%2Fsites%2Fa"); + fireEvent.click( + await screen.findByRole("button", { name: "Continue as Ada Lovelace (ada@example.test)" }), + ); + await fillAndSubmit(undefined, "correct horse"); + expect(await screen.findByText("site")).toBeInTheDocument(); + expect(router.state.location.href).toBe("/sites/a"); + }); + + it("keeps an RFC-0044 authorization request through the chooser", async () => { + const fetch = server(); + window.history.replaceState(null, "", "/login?client_id=c1&sig=s1"); + const assign = vi.fn(); + vi.spyOn(window, "location", "get").mockReturnValue({ + ...window.location, + search: "?client_id=c1&sig=s1", + href: "http://localhost/login?client_id=c1&sig=s1", + assign, + } as Location); + renderAt("/login?client_id=c1&sig=s1"); + fireEvent.click( + await screen.findByRole("button", { name: "Continue as Ada Lovelace (ada@example.test)" }), + ); + await fillAndSubmit(undefined, "correct horse"); + await waitFor(() => expect(assign).toHaveBeenCalledWith("/oauth/consent?x=1")); + const signIn = fetch.mock.calls.find(([u]) => String(u).includes("/sign-in/email")); + expect(JSON.parse(String(signIn?.[1]?.body))).toMatchObject({ + email: "ada@example.test", + oauth_query: "client_id=c1&sig=s1", + }); + vi.restoreAllMocks(); + // The response had no user: the remembered name stays. + expect(readRememberedAccounts()[0]).toMatchObject({ + email: "ada@example.test", + name: "Ada Lovelace", + }); + }); +}); + +describe("Sign out and forget", () => { + it("removes only the signed-in member's entry, then signs out", async () => { + rememberAccount({ email: "bob@example.test", name: "Bob" }); + rememberAccount({ email: "ADA@example.test", name: "Ada Lovelace" }); + const fetch = server(); + const router = renderAt("/menu"); + fireEvent.click(await screen.findByTestId("user-menu")); + fireEvent.click(await screen.findByRole("menuitem", { name: "Sign out and forget" })); + await waitFor(() => expect(router.state.location.pathname).toBe("/login")); + expect(readRememberedAccounts().map((a) => a.email)).toEqual(["bob@example.test"]); + expect(fetch.mock.calls.some(([u]) => String(u).includes("/api/auth/sign-out"))).toBe(true); + }); + + it("plain Sign out keeps the entry", async () => { + rememberAccount({ email: "ada@example.test", name: "Ada Lovelace" }); + server(); + const router = renderAt("/menu"); + fireEvent.click(await screen.findByTestId("user-menu")); + fireEvent.click(await screen.findByRole("menuitem", { name: "Sign out" })); + await waitFor(() => expect(router.state.location.pathname).toBe("/login")); + expect(readRememberedAccounts().map((a) => a.email)).toEqual(["ada@example.test"]); + }); + + it("is not offered when this browser remembers no account", async () => { + server(); + renderAt("/menu"); + fireEvent.click(await screen.findByTestId("user-menu")); + await screen.findByRole("menuitem", { name: "Sign out" }); + expect(screen.queryByRole("menuitem", { name: "Sign out and forget" })).toBeNull(); + }); +}); diff --git a/apps/studio/test/remembered-accounts.test.ts b/apps/studio/test/remembered-accounts.test.ts new file mode 100644 index 00000000..95e06caa --- /dev/null +++ b/apps/studio/test/remembered-accounts.test.ts @@ -0,0 +1,186 @@ +/** #388 step 3: the remembered accounts kept for the signed-out `/login`. */ +import { describe, expect, it } from "vitest"; +import { + type AccountStorage, + forgetRememberedAccount, + isRemembered, + MAX_AGE_MS, + MAX_NAME_LENGTH, + REMEMBERED_ACCOUNTS_KEY, + readRememberedAccounts, + rememberAccount, + touchRememberedAccount, +} from "../src/lib/remembered-accounts.ts"; + +const NOW = Date.UTC(2026, 11, 2, 12); +const DAY = 24 * 60 * 60_000; + +function memory(initial?: string): AccountStorage & { value: () => string | null } { + let value: string | null = initial ?? null; + return { + getItem: (key) => (key === REMEMBERED_ACCOUNTS_KEY ? value : null), + setItem: (key, v) => { + if (key === REMEMBERED_ACCOUNTS_KEY) value = v; + }, + removeItem: (key) => { + if (key === REMEMBERED_ACCOUNTS_KEY) value = null; + }, + value: () => value, + }; +} + +const throwing: AccountStorage = { + getItem: () => { + throw new Error("SecurityError"); + }, + setItem: () => { + throw new Error("QuotaExceededError"); + }, + removeItem: () => { + throw new Error("SecurityError"); + }, +}; + +describe("remembered accounts", () => { + it("stores only the email, the name and when it was used", () => { + const storage = memory(); + rememberAccount({ email: "ada@example.test", name: "Ada" }, { storage, now: NOW }); + expect(JSON.parse(storage.value() ?? "")).toEqual([ + { email: "ada@example.test", name: "Ada", lastUsedAt: NOW }, + ]); + expect(readRememberedAccounts({ storage, now: NOW })).toEqual([ + { email: "ada@example.test", name: "Ada", lastUsedAt: NOW }, + ]); + }); + + it("reads nothing from corrupt JSON or the wrong shape, and clears it", () => { + for (const raw of ["{not json", '"text"', "42", "null", '{"email":"a@b.c"}']) { + const storage = memory(raw); + expect(readRememberedAccounts({ storage, now: NOW })).toEqual([]); + expect(storage.value()).toBeNull(); + } + }); + + it("drops malformed entries and keeps the good ones", () => { + const good = { email: "ada@example.test", name: "Ada", lastUsedAt: NOW - DAY }; + const storage = memory( + JSON.stringify([ + null, + "ada@example.test", + [good], + { email: "no-at-sign", name: "X", lastUsedAt: NOW }, + { email: "bob@example.test", name: 7, lastUsedAt: NOW }, + { email: "bob@example.test", name: "Bob", lastUsedAt: "yesterday" }, + { email: "bob@example.test", name: "Bob", lastUsedAt: Number.NaN }, + { email: "bob@example.test", name: "Bob", lastUsedAt: NOW + 10 * DAY }, + { email: "bob@example.test", name: "Bob", lastUsedAt: NOW, token: "t1" }, + { email: " bob@example.test", name: "Bob", lastUsedAt: NOW }, + { email: "bob@example.test", name: "B\u0000ob", lastUsedAt: NOW }, + good, + ]), + ); + expect(readRememberedAccounts({ storage, now: NOW })).toEqual([good]); + expect(JSON.parse(storage.value() ?? "")).toEqual([good]); + }); + + it("keeps at most five: the sixth evicts the oldest", () => { + const storage = memory(); + for (let i = 1; i <= 6; i++) { + rememberAccount({ email: `p${i}@example.test`, name: `P${i}` }, { storage, now: NOW + i }); + } + const emails = readRememberedAccounts({ storage, now: NOW + 7 }).map((a) => a.email); + expect(emails).toEqual([ + "p6@example.test", + "p5@example.test", + "p4@example.test", + "p3@example.test", + "p2@example.test", + ]); + }); + + it("forgets an entry unused for 30 days", () => { + const storage = memory(); + rememberAccount({ email: "old@example.test", name: "Old" }, { storage, now: NOW }); + rememberAccount({ email: "new@example.test", name: "New" }, { storage, now: NOW + 10 * DAY }); + expect(readRememberedAccounts({ storage, now: NOW + MAX_AGE_MS })).toHaveLength(2); + const later = readRememberedAccounts({ storage, now: NOW + MAX_AGE_MS + 1 }); + expect(later.map((a) => a.email)).toEqual(["new@example.test"]); + expect(storage.value()).not.toContain("old@example.test"); + }); + + it("matches emails case-insensitively, with no duplicates", () => { + const storage = memory(); + rememberAccount({ email: "Ada@Example.test", name: "Ada" }, { storage, now: NOW }); + rememberAccount({ email: "ada@example.test", name: "Ada L." }, { storage, now: NOW + 1 }); + expect(readRememberedAccounts({ storage, now: NOW + 2 })).toEqual([ + { email: "ada@example.test", name: "Ada L.", lastUsedAt: NOW + 1 }, + ]); + expect(isRemembered("ADA@example.TEST", { storage, now: NOW + 2 })).toBe(true); + // A stored list with duplicates keeps the newest. + const dup = memory( + JSON.stringify([ + { email: "a@example.test", name: "Old", lastUsedAt: NOW - 2 }, + { email: "A@example.test", name: "New", lastUsedAt: NOW - 1 }, + ]), + ); + expect(readRememberedAccounts({ storage: dup, now: NOW })).toEqual([ + { email: "A@example.test", name: "New", lastUsedAt: NOW - 1 }, + ]); + }); + + it("caps the lengths: long emails are refused, long names cut", () => { + const storage = memory(); + const local = "a".repeat(64); + const longEmail = `${local}@${"b".repeat(250)}.test`; + rememberAccount({ email: longEmail, name: "Long" }, { storage, now: NOW }); + expect(storage.value()).toBeNull(); + rememberAccount({ email: "ada@example.test", name: "N".repeat(500) }, { storage, now: NOW }); + const [entry] = readRememberedAccounts({ storage, now: NOW }); + expect(entry?.name).toHaveLength(MAX_NAME_LENGTH); + // A stored name over the cap is malformed. + const tooLong = memory( + JSON.stringify([{ email: "ada@example.test", name: "N".repeat(101), lastUsedAt: NOW }]), + ); + expect(readRememberedAccounts({ storage: tooLong, now: NOW })).toEqual([]); + }); + + it("works when storage throws, is full or is missing", () => { + expect(readRememberedAccounts({ storage: throwing, now: NOW })).toEqual([]); + expect(rememberAccount({ email: "a@example.test" }, { storage: throwing, now: NOW })).toEqual( + [], + ); + expect(forgetRememberedAccount("a@example.test", { storage: throwing, now: NOW })).toEqual([]); + expect(touchRememberedAccount({ email: "a@example.test" }, { storage: throwing })).toBe(false); + const full = memory(); + full.setItem = () => { + throw new Error("QuotaExceededError"); + }; + expect(rememberAccount({ email: "a@example.test" }, { storage: full, now: NOW })).toEqual([]); + }); + + it("forgets one account and leaves the others", () => { + const storage = memory(); + rememberAccount({ email: "ada@example.test", name: "Ada" }, { storage, now: NOW }); + rememberAccount({ email: "bob@example.test", name: "Bob" }, { storage, now: NOW + 1 }); + const left = forgetRememberedAccount("ADA@example.test", { storage, now: NOW + 2 }); + expect(left.map((a) => a.email)).toEqual(["bob@example.test"]); + forgetRememberedAccount("bob@example.test", { storage, now: NOW + 2 }); + expect(storage.value()).toBeNull(); + }); + + it("refreshes only an account that is already remembered", () => { + const storage = memory(); + expect(touchRememberedAccount({ email: "ada@example.test" }, { storage, now: NOW })).toBe( + false, + ); + expect(storage.value()).toBeNull(); + rememberAccount({ email: "ada@example.test", name: "Ada" }, { storage, now: NOW }); + expect( + touchRememberedAccount( + { email: "ada@example.test", name: "Ada" }, + { storage, now: NOW + DAY }, + ), + ).toBe(true); + expect(readRememberedAccounts({ storage, now: NOW + DAY })[0]?.lastUsedAt).toBe(NOW + DAY); + }); +}); diff --git a/docs/design/DESIGN.md b/docs/design/DESIGN.md index 46a59e4b..cd6c2003 100644 --- a/docs/design/DESIGN.md +++ b/docs/design/DESIGN.md @@ -14,7 +14,7 @@ Studio mirrors this one-to-one: |---|---| | App shell | `Sidebar.Provider defaultOpen collapsible="icon" peekable mobileBreakpoint={768} className="h-dvh"` → `` + a content column `flex h-full min-h-0 flex-1 flex-col overflow-y-auto overscroll-y-contain bg-kumo-overlay`. The provider must have a definite height because Kumo's `