website based login challenges (#1956)

This commit is contained in:
Brandon Thomas
2026-09-26 03:42:09 -07:00
committed by GitHub
parent 95f8f659a5
commit 8456e2fd06
39 changed files with 2131 additions and 126 deletions
@@ -0,0 +1,167 @@
import { act, cleanup, fireEvent, render, screen } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { DesktopLoginBridge } from "./DesktopLoginBridge";
const { native, forbiddenFetch } = vi.hoisted(() => ({ native: vi.fn(), forbiddenFetch: vi.fn(() => { throw new Error("JavaScript must never call HTTP for login"); }) }));
vi.mock("@tauri-apps/api/core", () => ({ invoke: native }));
vi.mock("@storyteller/tauri-utils", () => ({ FetchProxy: forbiddenFetch }));
vi.mock("@storyteller/api", () => { throw new Error("Login UI must only import API types"); });
vi.mock("qrcode.react", () => ({ QRCodeSVG: ({ value }: { value: string }) => <svg role="img" aria-label="Login QR" data-value={value} /> }));
const CHALLENGE_ID = "local-handle";
const APPROVAL_URL = `https://app.getartcraft.com/login/desktop#approval_token=${"A".repeat(43)}`;
const USER = { user_token: "user_fixture", username: "google_user" };
let outcome: Record<string, unknown>;
let expiresIn: number;
beforeEach(() => {
vi.useFakeTimers();
vi.setSystemTime(new Date("2026-09-25T12:00:00Z"));
vi.stubGlobal("fetch", forbiddenFetch);
localStorage.clear();
native.mockReset();
forbiddenFetch.mockClear();
expiresIn = 1_200_000;
outcome = { status: "pending", maybe_failure_type: null, maybe_user: null };
native.mockImplementation(async (command: string) => {
if (command === "storyteller_create_login_challenge_command") return {
challenge_id: CHALLENGE_ID, verification_url: APPROVAL_URL,
confirmation_code: "WDJBMJHT", expires_at: new Date(Date.now() + expiresIn).toISOString(), poll_interval_seconds: 5,
};
if (command === "storyteller_poll_login_challenge_command") return outcome;
if (command === "storyteller_cancel_login_challenge_command" || command === "plugin:opener|open_url") return;
throw new Error(`Unexpected native command: ${command}`);
});
});
afterEach(() => {
cleanup();
expect(forbiddenFetch).not.toHaveBeenCalled();
expect(localStorage.getItem("artcraft_signed_session")).toBeNull();
vi.unstubAllGlobals();
vi.useRealTimers();
});
describe("desktop native login bridge integration", () => {
it("creates through IPC and opens the native browser with the matching QR/code", async () => {
render(<DesktopLoginBridge onSuccess={vi.fn()} />);
await start("Login with Website");
expect(native).toHaveBeenCalledWith("storyteller_create_login_challenge_command");
expect(native).toHaveBeenCalledWith("plugin:opener|open_url", { url: APPROVAL_URL });
expect(screen.getByRole("img", { name: "Login QR" }).getAttribute("data-value")).toBe(APPROVAL_URL);
expect(screen.getByText("WDJB-MJHT")).toBeTruthy();
});
it("polls with only a local handle and accepts the natively verified user without seeing credentials", async () => {
const success = vi.fn();
render(<DesktopLoginBridge onSuccess={success} />);
await start("Scan to Login");
await tick(5000);
expect(success).not.toHaveBeenCalled();
outcome = { status: "redeemed", maybe_failure_type: null, maybe_user: USER };
await tick(5000);
expect(native).toHaveBeenCalledWith("storyteller_poll_login_challenge_command", { challengeId: CHALLENGE_ID });
expect(success).toHaveBeenCalledWith(USER);
expect(native).toHaveBeenCalledWith("storyteller_cancel_login_challenge_command", { challengeId: CHALLENGE_ID });
const count = calls("storyteller_poll_login_challenge_command");
await tick(30_000);
expect(calls("storyteller_poll_login_challenge_command")).toBe(count);
});
it("stops after decline", async () => {
const success = vi.fn();
outcome = { status: "failed", maybe_failure_type: "user_declined" };
render(<DesktopLoginBridge onSuccess={success} />);
await start("Scan to Login");
await tick(5000);
expect(screen.getByText("Login was declined on the website.")).toBeTruthy();
expect(success).not.toHaveBeenCalled();
await tick(60_000);
expect(calls("storyteller_poll_login_challenge_command")).toBe(1);
});
it("expires locally and cancels the native attempt without creating another", async () => {
expiresIn = 5000;
render(<DesktopLoginBridge onSuccess={vi.fn()} />);
await start("Scan to Login");
await tick(5000);
expect(screen.getByText("Login request expired. Start a new request.")).toBeTruthy();
expect(calls("storyteller_create_login_challenge_command")).toBe(1);
expect(calls("storyteller_poll_login_challenge_command")).toBe(0);
expect(calls("storyteller_cancel_login_challenge_command")).toBe(1);
});
it("backs off a native network failure and retries the same local handle", async () => {
render(<DesktopLoginBridge onSuccess={vi.fn()} />);
await start("Scan to Login");
native.mockRejectedValueOnce({ message: "Disconnected", status: null, retryable: true });
await tick(5000);
expect(screen.getByText("Connection interrupted. Retrying…")).toBeTruthy();
await tick(9999);
expect(calls("storyteller_poll_login_challenge_command")).toBe(1);
await tick(1);
expect(calls("storyteller_poll_login_challenge_command")).toBe(2);
});
it("cancels on unmount and ignores a late command result", async () => {
let resolve: (value: unknown) => void = () => {};
const success = vi.fn();
const view = render(<DesktopLoginBridge onSuccess={success} />);
await start("Scan to Login");
native.mockImplementationOnce(() => new Promise((done) => { resolve = done; }));
await tick(5000);
view.unmount();
expect(native).toHaveBeenCalledWith("storyteller_cancel_login_challenge_command", { challengeId: CHALLENGE_ID });
await act(async () => { resolve({ status: "redeemed", maybe_user: USER }); });
expect(success).not.toHaveBeenCalled();
});
it("ignores an in-flight redemption after Back and can start a new challenge", async () => {
let resolve: (value: unknown) => void = () => {};
const success = vi.fn();
render(<DesktopLoginBridge onSuccess={success} />);
await start("Scan to Login");
native.mockImplementationOnce(() => new Promise((done) => { resolve = done; }));
await tick(5000);
await start("Back");
expect(native).toHaveBeenCalledWith("storyteller_cancel_login_challenge_command", { challengeId: CHALLENGE_ID });
await act(async () => { resolve({ status: "redeemed", maybe_user: USER }); });
expect(success).not.toHaveBeenCalled();
expect(screen.queryByRole("img", { name: "Login QR" })).toBeNull();
await tick(30_000);
expect(calls("storyteller_poll_login_challenge_command")).toBe(1);
await start("Scan to Login");
expect(screen.getByRole("img", { name: "Login QR" })).toBeTruthy();
outcome = { status: "redeemed", maybe_user: USER };
await tick(5000);
expect(success).toHaveBeenCalledExactlyOnceWith(USER);
});
it("fails closed on a future status", async () => {
outcome = { status: "future_state", maybe_user: USER };
render(<DesktopLoginBridge onSuccess={vi.fn()} />);
await start("Scan to Login");
await tick(5000);
expect(screen.getByText("This login request could not be completed. Start a new request.")).toBeTruthy();
});
it("shows the native host/status diagnostic and stops on terminal HTTP errors", async () => {
render(<DesktopLoginBridge onSuccess={vi.fn()} />);
await start("Scan to Login");
native.mockRejectedValueOnce({ message: "http://localhost:12345: Login server rejected the request (HTTP 401)", status: 401, retryable: false });
await tick(5000);
expect(screen.getByText(/localhost:12345.*401/)).toBeTruthy();
await tick(60_000);
expect(calls("storyteller_poll_login_challenge_command")).toBe(1);
});
});
async function start(label: string) {
await act(async () => { fireEvent.click(screen.getByRole("button", { name: label })); });
}
async function tick(ms: number) {
await act(async () => { await vi.advanceTimersByTimeAsync(ms); });
}
function calls(command: string) {
return native.mock.calls.filter(([name]) => name === command).length;
}
@@ -0,0 +1,134 @@
import { useEffect, useRef, useState } from "react";
import { QRCodeSVG } from "qrcode.react";
import { invoke } from "@tauri-apps/api/core";
import { ArrowLeftIcon } from "lucide-react";
import type { UserInfo } from "@storyteller/api";
import { createDesktopLoginChallenge, pollDesktopLoginChallenge, cancelDesktopLoginChallenge, isDesktopLoginError, type DesktopLoginChallenge } from "./NativeLoginBridge";
const OpenUrl = (url: string) => invoke("plugin:opener|open_url", { url });
export function DesktopLoginBridge({ onSuccess, onStart, onActiveChange }: { onSuccess: (user: UserInfo) => void; onStart?: () => void; onActiveChange?: (active: boolean) => void }) {
const [challenge, setChallenge] = useState<DesktopLoginChallenge | null>(null);
const [busy, setBusy] = useState(false);
const [message, setMessage] = useState("");
const [now, setNow] = useState(Date.now);
const generation = useRef(0);
const success = useRef(onSuccess);
success.current = onSuccess;
const isActive = busy || challenge !== null;
useEffect(() => { onActiveChange?.(isActive); }, [isActive, onActiveChange]);
useEffect(() => () => { generation.current += 1; }, []);
useEffect(() => {
if (!challenge) return;
const timer = window.setInterval(() => setNow(Date.now()), 1000);
return () => window.clearInterval(timer);
}, [challenge]);
useEffect(() => {
if (!challenge) return;
let active = true;
const current = generation.current;
let timer: ReturnType<typeof setTimeout>;
let delay = Math.max(5, challenge.poll_interval_seconds) * 1000;
const deadline = Date.parse(challenge.expires_at);
const finish = (text: string) => {
setChallenge(null);
setMessage(text);
};
const poll = async () => {
if (!active || current !== generation.current) return;
if (Date.now() >= deadline) { finish("Login request expired. Start a new request."); return; }
try {
const result = await pollDesktopLoginChallenge(challenge.challenge_id);
if (!active || current !== generation.current) return;
if (result.status === "redeemed") {
if (!result.maybe_user) throw new Error("Native session verification did not return a user");
active = false;
setChallenge(null);
setMessage("Signed in successfully.");
success.current(result.maybe_user);
return;
}
if (result.status === "failed") {
finish(result.maybe_failure_type === "user_declined" ? "Login was declined on the website." : result.maybe_failure_type === "expired" ? "Login request expired. Start a new request." : "Login failed. Start a new request.");
return;
}
if (!["pending", "approved"].includes(result.status)) {
finish("This login request could not be completed. Start a new request.");
return;
}
delay = Math.max(5, challenge.poll_interval_seconds) * 1000;
setMessage("Waiting for your confirmation on the website…");
} catch (error) {
if (!active || current !== generation.current) return;
if (isDesktopLoginError(error) && !error.retryable) {
finish(error.message);
return;
}
delay = Math.min(delay * 2, 30_000);
setMessage("Connection interrupted. Retrying…");
}
if (active) timer = setTimeout(poll, Math.min(delay, Math.max(0, deadline - Date.now())));
};
timer = setTimeout(poll, Math.min(delay, Math.max(0, deadline - Date.now())));
return () => {
active = false;
clearTimeout(timer);
void cancelDesktopLoginChallenge(challenge.challenge_id).catch(() => {});
};
}, [challenge]);
const start = async (openBrowser: boolean) => {
if (busy) return;
onStart?.();
const current = ++generation.current;
setBusy(true);
setMessage("");
try {
const created = await createDesktopLoginChallenge();
if (current !== generation.current) {
void cancelDesktopLoginChallenge(created.challenge_id).catch(() => {});
return;
}
// Rust validates the approval URL against the configured API environment.
setNow(Date.now());
setChallenge(created);
setMessage("Waiting for your confirmation on the website…");
if (openBrowser) await OpenUrl(created.verification_url);
} catch (error) {
if (current === generation.current) setMessage(isDesktopLoginError(error) ? error.message : "Unable to open website login. Try again or scan the QR code.");
} finally {
if (current === generation.current) setBusy(false);
}
};
const back = () => {
generation.current += 1;
setChallenge(null);
setBusy(false);
setMessage("");
};
const remaining = challenge ? Math.max(0, Math.ceil((Date.parse(challenge.expires_at) - now) / 1000)) : 0;
return <section aria-label="Website login" className="mb-6 rounded-xl border border-white/15 p-4 text-center">
{isActive && <div className="mb-4 text-left">
<button type="button" className="inline-flex items-center gap-2 text-sm text-white/70 hover:text-white" onClick={back}>
<ArrowLeftIcon size={16} aria-hidden="true" /> Back
</button>
</div>}
{challenge ? <>
<p className="mb-3 text-sm text-white/70">Scan with your phone or approve in your browser.</p>
<QRCodeSVG value={challenge.verification_url} size={192} marginSize={4} title="Scan to approve desktop login" className="mx-auto rounded-lg" />
<p className="my-3 font-mono text-2xl tracking-widest">{challenge.confirmation_code.slice(0, 4)}-{challenge.confirmation_code.slice(4)}</p>
<p className="mb-3 text-xs text-white/60">Verify this code on the website. Expires in {Math.floor(remaining / 60)}:{String(remaining % 60).padStart(2, "0")}</p>
<button type="button" className="rounded-lg border border-white/30 px-4 py-2" onClick={() => OpenUrl(challenge.verification_url).catch(() => setMessage("Unable to open the browser. Scan the QR code instead."))}>Open website</button>
</> : busy ? <p className="text-sm text-white/70" role="status">Preparing login…</p> : <div className="flex flex-col gap-2">
<button type="button" className="rounded-lg bg-white px-4 py-3 font-medium text-black" onClick={() => start(true)}>Login with Website</button>
<button type="button" className="rounded-lg border border-white/30 px-4 py-2" onClick={() => start(false)}>Scan to Login</button>
<p className="text-xs text-white/50">Use Google or any account already signed in on the website.</p>
</div>}
{message && <p className="mt-3 text-sm text-white/70" role="status">{message}</p>}
</section>;
}
@@ -0,0 +1,86 @@
.panel {
position: relative;
isolation: isolate;
display: flex;
width: 100%;
flex-direction: column;
align-items: center;
overflow: hidden;
padding: 56px 32px;
text-align: center;
background: radial-gradient(ellipse at 50% 0%, rgb(94 234 212 / 9%), transparent 70%);
animation: arrive 450ms ease-out both;
}
.glow {
position: absolute;
z-index: -1;
top: -52px;
left: calc(50% - 144px);
width: 288px;
height: 288px;
border-radius: 50%;
background: radial-gradient(circle, rgb(94 234 212 / 24%), rgb(129 140 248 / 12%) 45%, transparent 70%);
filter: blur(24px);
pointer-events: none;
animation: glow 2400ms ease-in-out infinite;
}
.badge {
display: flex;
width: 76px;
height: 76px;
align-items: center;
justify-content: center;
margin-bottom: 28px;
border: 1px solid rgb(153 246 228 / 35%);
border-radius: 50%;
color: #b4f7de;
background: linear-gradient(145deg, rgb(153 246 228 / 16%), rgb(94 234 212 / 4%));
box-shadow: 0 0 0 8px rgb(94 234 212 / 4%), 0 0 44px rgb(94 234 212 / 18%), inset 0 1px 0 rgb(255 255 255 / 12%);
}
.heading {
margin: 0;
max-width: 100%;
color: rgb(255 255 255 / 80%);
font-size: 18px;
font-weight: 500;
line-height: 1.5;
}
.username {
display: block;
margin-top: 4px;
overflow-wrap: anywhere;
color: #b4f7de;
background: linear-gradient(100deg, #d4ffec, #99f6e4 55%, #c7d2fe);
background-clip: text;
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
font-size: 30px;
font-weight: 600;
letter-spacing: -0.025em;
line-height: 1.25;
}
.caption {
margin: 14px 0 0;
color: rgb(255 255 255 / 50%);
font-size: 14px;
line-height: 1.5;
}
@keyframes arrive {
from { opacity: 0; transform: translateY(8px) scale(0.98); }
to { opacity: 1; transform: translateY(0) scale(1); }
}
@keyframes glow {
0%, 100% { opacity: 0.7; transform: scale(0.95); }
50% { opacity: 1; transform: scale(1.06); }
}
@media (prefers-reduced-motion: reduce) {
.panel, .glow { animation: none; }
}
@@ -0,0 +1,18 @@
import { CheckIcon } from "lucide-react";
import styles from "./LoginSuccess.module.css";
export function LoginSuccess({ username }: { username: string }) {
return (
<div className={styles.panel} role="status" aria-live="polite" aria-atomic="true">
<div className={styles.glow} aria-hidden="true" />
<div className={styles.badge} aria-hidden="true">
<CheckIcon size={34} strokeWidth={2} />
</div>
<h2 className={styles.heading}>
Logged in as{" "}
<span className={styles.username}>{username}</span>
</h2>
<p className={styles.caption}>You're ready to create.</p>
</div>
);
}
@@ -0,0 +1,38 @@
import { invoke } from "@tauri-apps/api/core";
import type { UserInfo } from "@storyteller/api";
export interface DesktopLoginChallenge {
challenge_id: string;
verification_url: string;
confirmation_code: string;
expires_at: string;
poll_interval_seconds: number;
}
export interface DesktopLoginOutcome {
status: string;
maybe_failure_type: string | null;
maybe_user: UserInfo | null;
}
export interface DesktopLoginError {
status: number | null;
message: string;
retryable: boolean;
}
export const createDesktopLoginChallenge = () => invoke<DesktopLoginChallenge>("storyteller_create_login_challenge_command");
export const pollDesktopLoginChallenge = (challengeId: string) => invoke<DesktopLoginOutcome>("storyteller_poll_login_challenge_command", { challengeId });
export const cancelDesktopLoginChallenge = (challengeId: string) => invoke<void>("storyteller_cancel_login_challenge_command", { challengeId });
export function isDesktopLoginError(error: unknown): error is DesktopLoginError {
return typeof error === "object" && error !== null && "message" in error && "retryable" in error;
}
export const getNativeLoginSession = () => invoke<UserInfo | null>("storyteller_get_login_session_command");
export const passwordLogin = (usernameOrEmail: string, password: string) => invoke<UserInfo>("storyteller_password_login_command", {
request: { username_or_email: usernameOrEmail, password },
});
export const passwordSignup = (username: string, email: string, password: string, passwordConfirmation: string) => invoke<UserInfo>("storyteller_password_signup_command", {
request: { username, email_address: email, password, password_confirmation: passwordConfirmation, signup_source: "artcraft" },
});
@@ -1,12 +1,182 @@
import { render } from '@testing-library/react';
import { act, cleanup, fireEvent, render, screen } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { LoginModal } from "./login-modal";
import { useLoginModalStore } from "./useLoginModalStore";
import LoginModal from './login-modal';
const { native, forbiddenFetch } = vi.hoisted(() => ({ native: vi.fn(), forbiddenFetch: vi.fn(() => { throw new Error("Authentication HTTP must run in Rust"); }) }));
vi.mock("@tauri-apps/api/core", () => ({ invoke: native }));
vi.mock("@storyteller/api", () => { throw new Error("Authentication UI must not import API clients"); });
vi.mock("@storyteller/tauri-utils", () => ({ FetchProxy: forbiddenFetch }));
vi.mock("@headlessui/react", () => ({ Transition: ({ show, children }: any) => show ? children : null, TransitionChild: ({ children }: any) => children }));
vi.mock("@storyteller/icons", () => ({ DynamicIcon: () => null, DiscordIcon: () => null }));
vi.mock("@storyteller/ui-button", () => ({ Button: ({ children, variant, icon, iconFlip, ...props }: any) => <button {...props}>{children}</button> }));
vi.mock("@storyteller/ui-input", () => ({ Input: ({ inputClassName, ...props }: any) => <input {...props} /> }));
vi.mock("qrcode.react", () => ({ QRCodeSVG: () => <svg role="img" aria-label="Login QR" /> }));
describe('LoginModal', () => {
it('should render successfully', () => {
const { baseElement } = render(<LoginModal />);
expect(baseElement).toBeTruthy();
const USER = { username: "google_user", user_token: "u_test" };
beforeEach(() => {
vi.useFakeTimers();
vi.stubGlobal("fetch", forbiddenFetch);
forbiddenFetch.mockClear();
localStorage.clear();
useLoginModalStore.setState({ isOpen: true, recheckTrigger: 0 });
native.mockReset().mockImplementation(async (command: string) => {
if (command === "storyteller_get_login_session_command") return null;
if (command === "storyteller_create_login_challenge_command") return {
challenge_id: "native_handle", verification_url: `https://app.getartcraft.com/login/desktop#approval_token=${"A".repeat(43)}`,
confirmation_code: "WDJBMJHT", expires_at: new Date(Date.now() + 1_200_000).toISOString(), poll_interval_seconds: 5,
};
if (command === "storyteller_poll_login_challenge_command") return { status: "redeemed", maybe_user: USER };
if (command === "storyteller_password_login_command" || command === "storyteller_password_signup_command") return USER;
if (command === "storyteller_cancel_login_challenge_command" || command === "plugin:opener|open_url") return;
throw new Error(`Unexpected command: ${command}`);
});
});
afterEach(() => {
cleanup();
expect(forbiddenFetch).not.toHaveBeenCalled();
expect(localStorage.getItem("artcraft_signed_session")).toBeNull();
vi.unstubAllGlobals();
vi.useRealTimers();
});
describe("native login modal integration", () => {
it("shows website and QR login only on the login screen", async () => {
await act(async () => { render(<LoginModal />); });
expect(screen.getByText("Create your account")).toBeTruthy();
expect(screen.queryByRole("button", { name: "Login with Website" })).toBeNull();
expect(screen.queryByRole("button", { name: "Scan to Login" })).toBeNull();
fireEvent.click(screen.getByRole("button", { name: "Log in" }));
expect(screen.getByRole("button", { name: "Login with Website" })).toBeTruthy();
expect(screen.getByRole("button", { name: "Scan to Login" })).toBeTruthy();
fireEvent.click(screen.getByRole("button", { name: "Sign up" }));
expect(screen.queryByRole("button", { name: "Login with Website" })).toBeNull();
});
it.each(["Login with Website", "Scan to Login"])("hides password login during %s and restores it with Back", async (label) => {
const success = vi.fn();
await act(async () => { render(<LoginModal isSignUp={false} onArtCraftAuthSuccess={success} />); });
expect(screen.getByPlaceholderText("you@example.com or username")).toBeTruthy();
await act(async () => { fireEvent.click(screen.getByRole("button", { name: label })); });
expect(screen.getByRole("img", { name: "Login QR" })).toBeTruthy();
expect(screen.queryByPlaceholderText("you@example.com or username")).toBeNull();
expect(screen.queryByPlaceholderText("Min. 8 characters")).toBeNull();
expect(screen.queryByRole("button", { name: "Sign up" })).toBeNull();
await act(async () => { fireEvent.click(screen.getByRole("button", { name: "Back" })); });
expect(screen.getByPlaceholderText("you@example.com or username")).toBeTruthy();
expect(screen.getByPlaceholderText("Min. 8 characters")).toBeTruthy();
expect(screen.getByRole("button", { name: "Login with Website" })).toBeTruthy();
expect(screen.getByRole("button", { name: "Scan to Login" })).toBeTruthy();
expect(screen.queryByRole("img", { name: "Login QR" })).toBeNull();
expect(native).toHaveBeenCalledWith("storyteller_cancel_login_challenge_command", { challengeId: "native_handle" });
await act(async () => { await vi.advanceTimersByTimeAsync(30_000); });
expect(native.mock.calls.filter(([command]) => command === "storyteller_poll_login_challenge_command")).toHaveLength(0);
expect(success).not.toHaveBeenCalled();
});
it("hides password login while preparing a challenge and cancels a late creation after Back", async () => {
let resolve: (value: unknown) => void = () => {};
await act(async () => { render(<LoginModal isSignUp={false} />); });
native.mockImplementationOnce(() => new Promise((done) => { resolve = done; }));
await act(async () => { fireEvent.click(screen.getByRole("button", { name: "Login with Website" })); });
expect(screen.getByText("Preparing login…")).toBeTruthy();
expect(screen.queryByPlaceholderText("Min. 8 characters")).toBeNull();
await act(async () => { fireEvent.click(screen.getByRole("button", { name: "Back" })); });
await act(async () => { resolve({ challenge_id: "late_handle" }); });
expect(screen.getByPlaceholderText("Min. 8 characters")).toBeTruthy();
expect(screen.queryByRole("img", { name: "Login QR" })).toBeNull();
expect(native).toHaveBeenCalledWith("storyteller_cancel_login_challenge_command", { challengeId: "late_handle" });
expect(native.mock.calls.filter(([command]) => command === "plugin:opener|open_url")).toHaveLength(0);
});
it.each([true, false])("keeps the completed native login when a stale session check resolves (before completion: %s)", async (beforeCompletion) => {
let resolveSession: (value: unknown) => void = () => {};
native.mockImplementationOnce(() => new Promise((resolve) => { resolveSession = resolve; }));
const success = vi.fn();
await act(async () => { render(<LoginModal isSignUp={false} onArtCraftAuthSuccess={success} />); });
await act(async () => { fireEvent.click(screen.getByRole("button", { name: "Scan to Login" })); });
if (beforeCompletion) await act(async () => { resolveSession(null); });
expect(screen.getByRole("img", { name: "Login QR" })).toBeTruthy();
await act(async () => { await vi.advanceTimersByTimeAsync(5000); });
expect(success).toHaveBeenCalledExactlyOnceWith(USER);
if (!beforeCompletion) await act(async () => { resolveSession(null); });
expect(screen.getByRole("heading", { name: "Logged in as google_user" })).toBeTruthy();
expect(screen.queryByRole("img", { name: "Login QR" })).toBeNull();
expect(useLoginModalStore.getState().isOpen).toBe(true);
await act(async () => { await vi.advanceTimersByTimeAsync(2999); });
expect(screen.getByRole("heading", { name: "Logged in as google_user" })).toBeTruthy();
await act(async () => { await vi.advanceTimersByTimeAsync(1); });
expect(useLoginModalStore.getState().isOpen).toBe(false);
expect(screen.queryByRole("heading", { name: "Logged in as google_user" })).toBeNull();
expect(screen.queryByText("Create your account")).toBeNull();
expect(native).toHaveBeenCalledWith("storyteller_poll_login_challenge_command", { challengeId: "native_handle" });
});
it.each([false, true])("submits password authentication only through Rust (signup: %s)", async (signup) => {
const success = vi.fn();
await act(async () => { render(<LoginModal isSignUp={signup} onArtCraftAuthSuccess={success} />); });
if (signup) {
fireEvent.change(screen.getByPlaceholderText("Username"), { target: { value: "native_user" } });
fireEvent.change(screen.getByPlaceholderText("you@example.com"), { target: { value: "user@example.com" } });
fireEvent.change(screen.getByPlaceholderText("Re-enter password"), { target: { value: "password123" } });
} else {
fireEvent.change(screen.getByPlaceholderText("you@example.com or username"), { target: { value: "native_user" } });
}
fireEvent.change(screen.getByPlaceholderText("Min. 8 characters"), { target: { value: "password123" } });
const submit = screen.getAllByRole("button", { name: signup ? "Sign up" : "Log in" }).find((button) => button.getAttribute("type") === "submit")!;
await act(async () => { fireEvent.click(submit); });
expect(success).toHaveBeenCalledExactlyOnceWith(USER);
expect(native).toHaveBeenCalledWith(signup ? "storyteller_password_signup_command" : "storyteller_password_login_command", {
request: signup ? { username: "native_user", email_address: "user@example.com", password: "password123", password_confirmation: "password123", signup_source: "artcraft" } : { username_or_email: "native_user", password: "password123" },
});
if (!signup) {
expect(screen.getByRole("heading", { name: "Logged in as google_user" })).toBeTruthy();
expect(screen.queryByText("Join Our Community")).toBeNull();
await act(async () => { await vi.advanceTimersByTimeAsync(3000); });
expect(useLoginModalStore.getState().isOpen).toBe(false);
}
});
it("dismisses the confirmation once even when callbacks change", async () => {
const firstClose = vi.fn();
const latestClose = vi.fn();
const success = vi.fn();
const view = render(<LoginModal isSignUp={false} onClose={firstClose} onArtCraftAuthSuccess={success} />);
await act(async () => {});
await act(async () => { fireEvent.click(screen.getByRole("button", { name: "Login with Website" })); });
await act(async () => { await vi.advanceTimersByTimeAsync(5000); });
expect(screen.getByRole("status").textContent).toContain("Logged in as google_user");
await act(async () => { await vi.advanceTimersByTimeAsync(1500); });
view.rerender(<LoginModal isSignUp={false} onClose={latestClose} onArtCraftAuthSuccess={success} />);
await act(async () => { await vi.advanceTimersByTimeAsync(1500); });
expect(useLoginModalStore.getState().isOpen).toBe(false);
expect(firstClose).not.toHaveBeenCalled();
expect(latestClose).toHaveBeenCalledTimes(1);
expect(success).toHaveBeenCalledExactlyOnceWith(USER);
await act(async () => { await vi.advanceTimersByTimeAsync(10_000); });
expect(latestClose).toHaveBeenCalledTimes(1);
});
it("cleans up the confirmation timer on unmount", async () => {
const onClose = vi.fn();
const view = render(<LoginModal isSignUp={false} onClose={onClose} />);
await act(async () => {});
await act(async () => { fireEvent.click(screen.getByRole("button", { name: "Scan to Login" })); });
await act(async () => { await vi.advanceTimersByTimeAsync(5000); });
expect(screen.getByRole("heading", { name: "Logged in as google_user" })).toBeTruthy();
view.unmount();
await act(async () => { await vi.advanceTimersByTimeAsync(10_000); });
expect(onClose).not.toHaveBeenCalled();
});
it("restores an existing session without showing the login confirmation", async () => {
native.mockResolvedValueOnce(USER);
const success = vi.fn();
await act(async () => { render(<LoginModal onArtCraftAuthSuccess={success} />); });
expect(success).toHaveBeenCalledExactlyOnceWith(USER);
expect(useLoginModalStore.getState().isOpen).toBe(false);
expect(screen.queryByRole("heading", { name: "Logged in as google_user" })).toBeNull();
});
});
@@ -1,17 +1,19 @@
import { Button } from "@storyteller/ui-button";
import { Transition, TransitionChild } from "@headlessui/react";
import { useState, useEffect } from "react";
import { useState, useEffect, useRef } from "react";
import { ArrowRightIcon } from "lucide-react";
import { DiscordIcon } from "@storyteller/icons";
import type { UserInfo } from "@storyteller/api";
import { DesktopLoginBridge } from "./DesktopLoginBridge";
import { LoginSuccess } from "./LoginSuccess";
import { ArtCraftSignUp } from "./artcraft-signup";
import { UsersApi } from "@storyteller/api";
import { getNativeLoginSession, passwordLogin, passwordSignup, isDesktopLoginError } from "./NativeLoginBridge";
import { useLoginModalStore } from "./useLoginModalStore";
const SIGNUP_SOURCE_ARTCRAFT = "artcraft";
// Webapp auth-showcase video (swap by passing `videoUrl`).
const DEFAULT_SHOWCASE_VIDEO =
"https://player.vimeo.com/video/1169289718?background=1&autoplay=1&loop=1&muted=1";
const LOGIN_SUCCESS_DURATION_MS = 3000;
interface LoginModalProps {
onClose?: () => void;
@@ -40,39 +42,56 @@ export function LoginModal({
const [errorMessage, setErrorMessage] = useState("");
const [showDiscord, setShowDiscord] = useState(false);
const [showSuccess, setShowSuccess] = useState(false);
const [isChallengeActive, setIsChallengeActive] = useState(false);
const [loggedInUsername, setLoggedInUsername] = useState<string | null>(null);
const checkArtCraftLogin = async () => {
const usersApi = new UsersApi();
const session = await usersApi.GetSession();
const loggedIn = session.data?.loggedIn;
return loggedIn;
};
const authGeneration = useRef(0);
const authSuccess = useRef(onArtCraftAuthSuccess);
authSuccess.current = onArtCraftAuthSuccess;
const afterClose = useRef(onClose);
afterClose.current = onClose;
// Check session on mount and when recheckTrigger changes.
// A stale startup/recheck response must never reopen the modal after login.
useEffect(() => {
checkArtCraftLogin().then((loggedIn) => {
if (loggedIn) {
const generation = ++authGeneration.current;
let active = true;
getNativeLoginSession().then((user) => {
if (!active || generation !== authGeneration.current) return;
if (user) {
setIsLoggedInArtCraft(true);
authSuccess.current?.(user);
closeModal();
} else {
// Reset modal state to initial values.
setIsLoading(false);
setIsSignUp(initialIsSignUp);
setErrorMessage("");
setShowDiscord(false);
setShowSuccess(false);
setLoggedInUsername(null);
setIsLoggedInArtCraft(false);
const { openModal } = useLoginModalStore.getState();
openModal();
useLoginModalStore.getState().openModal();
}
}).catch((error) => {
if (!active || generation !== authGeneration.current) return;
setErrorMessage(isDesktopLoginError(error) ? error.message : "Unable to check your account. Please sign in again.");
useLoginModalStore.getState().openModal();
});
return () => { active = false; };
}, [recheckTrigger, closeModal, initialIsSignUp]);
useEffect(() => {
if (onOpenChange) onOpenChange(isOpen);
}, [isOpen, onOpenChange]);
useEffect(() => {
if (loggedInUsername === null || !isOpen) return;
const timer = window.setTimeout(() => {
closeModal();
afterClose.current?.();
}, LOGIN_SUCCESS_DURATION_MS);
return () => window.clearTimeout(timer);
}, [loggedInUsername, isOpen, closeModal]);
const handleClose = () => {
closeModal();
onClose?.();
@@ -84,6 +103,15 @@ export function LoginModal({
setShowSuccess(true);
};
const handleLoginSuccess = (user: UserInfo) => {
authGeneration.current += 1;
setIsLoading(false);
setIsLoggedInArtCraft(true);
setIsChallengeActive(false);
setLoggedInUsername(user.username);
authSuccess.current?.(user);
};
const handleAuthSubmit = async (
username: string,
email: string,
@@ -91,56 +119,24 @@ export function LoginModal({
passwordConfirmation: string
) => {
setIsLoading(true);
const usersApi = new UsersApi();
setErrorMessage("");
const generation = ++authGeneration.current;
try {
let signupResponse, loginResponse;
const user = isSignUp
? await passwordSignup(username, email, password, passwordConfirmation)
: await passwordLogin(username || email, password);
if (generation !== authGeneration.current) return;
if (isSignUp) {
signupResponse = await usersApi.Signup({
username,
email,
password,
passwordConfirmation,
signupSource: SIGNUP_SOURCE_ARTCRAFT,
});
if (!signupResponse.success) {
setErrorMessage(
signupResponse.errorMessage || "Signup failed, please try again."
);
setIsLoading(false);
return;
}
loginResponse = await usersApi.Login({
usernameOrEmail: username || email,
password,
});
setIsLoggedInArtCraft(true);
authSuccess.current?.(user);
setShowDiscord(true);
} else {
loginResponse = await usersApi.Login({
usernameOrEmail: username || email,
password,
});
handleLoginSuccess(user);
}
if (!loginResponse.success) {
setErrorMessage(
loginResponse.errorMessage || "Login failed, please try again."
);
setIsLoading(false);
return;
}
setIsLoggedInArtCraft(true);
if (onArtCraftAuthSuccess) {
const session = await usersApi.GetSession();
const userInfo = session.data?.user;
if (userInfo) onArtCraftAuthSuccess(userInfo);
}
setShowDiscord(true); // Onboarding step after successful auth.
} catch (e) {
console.error(e);
setErrorMessage("An unexpected error occurred. Please try again.");
} catch (error) {
if (generation === authGeneration.current) setErrorMessage(isDesktopLoginError(error) ? error.message : "An unexpected error occurred. Please try again.");
} finally {
setIsLoading(false);
if (generation === authGeneration.current) setIsLoading(false);
}
};
@@ -204,7 +200,7 @@ export function LoginModal({
const inOnboarding = showDiscord || showSuccess;
return (
<Transition appear show={isOpen}>
<Transition appear show={isOpen} afterLeave={() => setLoggedInUsername(null)}>
<div className="fixed inset-0 z-[100]">
<TransitionChild
enter="ease-out duration-300"
@@ -226,10 +222,12 @@ export function LoginModal({
leaveTo="opacity-0 scale-95"
>
<div
className="relative flex w-full max-w-5xl overflow-hidden rounded-3xl border border-white/[4%] bg-[#1C1C20] text-white shadow-2xl lg:min-h-[640px]"
className={`relative flex w-full overflow-hidden rounded-3xl border bg-[#1C1C20] text-white shadow-2xl ${loggedInUsername !== null ? "max-w-md border-emerald-200/20" : "max-w-5xl border-white/[4%] lg:min-h-[640px]"}`}
onClick={(e) => e.stopPropagation()}
>
{inOnboarding ? (
{loggedInUsername !== null ? (
<LoginSuccess username={loggedInUsername} />
) : inOnboarding ? (
renderOnboarding()
) : (
<>
@@ -254,13 +252,14 @@ export function LoginModal({
</p>
</div>
<ArtCraftSignUp
{!isSignUp && <DesktopLoginBridge onActiveChange={setIsChallengeActive} onStart={() => { authGeneration.current += 1; }} onSuccess={handleLoginSuccess} />}
{!isChallengeActive && <ArtCraftSignUp
onSubmit={handleAuthSubmit}
isSignUp={isSignUp}
onToggleMode={() => setIsSignUp((prev) => !prev)}
errorMessage={errorMessage}
isLoading={isLoading}
/>
/>}
</div>
</div>
@@ -54,6 +54,9 @@
},
{
"path": "../input/tsconfig.lib.json"
},
{
"path": "../../tauri-api/tsconfig.lib.json"
}
]
}
+10
View File
@@ -49,6 +49,7 @@
"mediabunny": "^1.29.1",
"opencut-wasm": "^0.2.10",
"posthog-js": "^1.141.0",
"qrcode.react": "4.2.0",
"radix-ui": "^1.4.3",
"react": "18.3.1",
"react-copy-to-clipboard": "^5.1.0",
@@ -20479,6 +20480,15 @@
"node": ">=6"
}
},
"node_modules/qrcode.react": {
"version": "4.2.0",
"resolved": "https://registry.npmjs.org/qrcode.react/-/qrcode.react-4.2.0.tgz",
"integrity": "sha512-QpgqWi8rD9DsS9EP3z7BT+5lY5SFhsqGjpgW5DY/i3mK4M9DTBNz3ErMi8BWYEfI3L0d8GIbGmcdFAS1uIRGjA==",
"license": "ISC",
"peerDependencies": {
"react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"
}
},
"node_modules/qs": {
"version": "6.15.2",
"resolved": "https://registry.npmjs.org/qs/-/qs-6.15.2.tgz",
+1
View File
@@ -38,6 +38,7 @@
"mediabunny": "^1.29.1",
"opencut-wasm": "^0.2.10",
"posthog-js": "^1.141.0",
"qrcode.react": "4.2.0",
"radix-ui": "^1.4.3",
"react": "18.3.1",
"react-copy-to-clipboard": "^5.1.0",