diff --git a/apps/bear/src/bootstrap/bootstrap.client.ts b/apps/bear/src/bootstrap/bootstrap.client.ts index 8f745b7..b11fa21 100644 --- a/apps/bear/src/bootstrap/bootstrap.client.ts +++ b/apps/bear/src/bootstrap/bootstrap.client.ts @@ -2,9 +2,8 @@ import { configureErrorHandler } from '@lumina/libs/error-handler'; import { eventEmitter } from '@lumina/libs/event-emitter'; import { http } from '@lumina/libs/http'; import { mapApiErrorBody } from '@lumina/market/app/http'; -import { SESSION_REFRESH_ENDPOINT } from '@lumina/market/app/session'; import { setEnv as setMarketEnv } from '@lumina/market/env'; -import { AUTH_EVENTS } from '@lumina/market/features/auth'; +import { AUTH_ENDPOINTS, AUTH_EVENTS } from '@lumina/market/features/auth'; import { API_VERSION_PATH } from '../constants'; import { clientEnv } from '../env'; @@ -23,7 +22,7 @@ setMarketEnv({ http.configure({ baseUrl: `${clientEnv.NEXT_PUBLIC_API_ORIGIN}${API_VERSION_PATH}`, refresh: { - endpoint: SESSION_REFRESH_ENDPOINT, + endpoint: AUTH_ENDPOINTS.refresh, onFailure: () => eventEmitter.emit(AUTH_EVENTS.logout, { reason: 'session-ended' }), }, diff --git a/apps/bear/src/bootstrap/bootstrap.server.ts b/apps/bear/src/bootstrap/bootstrap.server.ts index 26a5dbf..1e1c316 100644 --- a/apps/bear/src/bootstrap/bootstrap.server.ts +++ b/apps/bear/src/bootstrap/bootstrap.server.ts @@ -7,7 +7,7 @@ import { mapApiErrorBody } from '@lumina/market/app/http'; import { setEnv as setMarketEnv } from '@lumina/market/env'; import { cookies } from 'next/headers'; -import { API_VERSION_PATH } from '../constants'; +import { API_VERSION_PATH, FORWARDED_COOKIES } from '../constants'; import { clientEnv } from '../env'; import { serverEnv } from '../env/server'; import { ERROR_HANDLER_CONFIG } from './error-reporting'; @@ -19,11 +19,17 @@ setMarketEnv({ telegramHandle: clientEnv.NEXT_PUBLIC_TELEGRAM_HANDLE, supportHours: clientEnv.NEXT_PUBLIC_SUPPORT_HOURS, }); -// Each server request forwards its own user's session cookies; nothing per user is kept in module -// state. The server never refreshes: proxy.ts already did, before rendering. +// Server requests forward only the allowlisted cookies, never the session: the server render is +// the same for every visitor, and the browser loads whatever depends on the viewer. Read on each +// request; nothing per visitor is kept in module state. configureServerHttp({ baseUrl: `${serverEnv.API_INTERNAL_ORIGIN}${API_VERSION_PATH}`, - getCookieHeader: async () => (await cookies()).toString(), + getCookieHeader: async () => + (await cookies()) + .getAll() + .filter(({ name }) => FORWARDED_COOKIES.has(name)) + .map(({ name, value }) => `${name}=${encodeURIComponent(value)}`) + .join('; '), }); http.configure({ mapErrorBody: mapApiErrorBody }); configureErrorHandler(ERROR_HANDLER_CONFIG); diff --git a/apps/bear/src/constants/cookies.ts b/apps/bear/src/constants/cookies.ts new file mode 100644 index 0000000..a434714 --- /dev/null +++ b/apps/bear/src/constants/cookies.ts @@ -0,0 +1,6 @@ +/** + * Cookies the server render may read, forwarded on every server-side API request. Only values + * every visitor can have, such as locale and theme; never the session cookies, so no server + * response depends on who the viewer is. Adding an auth cookie here needs a recorded decision. + */ +export const FORWARDED_COOKIES: ReadonlySet = new Set([]); diff --git a/apps/bear/src/constants/index.ts b/apps/bear/src/constants/index.ts index 80dfdd5..7e3ce17 100644 --- a/apps/bear/src/constants/index.ts +++ b/apps/bear/src/constants/index.ts @@ -1 +1,2 @@ export { API_VERSION_PATH } from './api'; +export { FORWARDED_COOKIES } from './cookies'; diff --git a/apps/bear/src/proxy.ts b/apps/bear/src/proxy.ts deleted file mode 100644 index 301ac7a..0000000 --- a/apps/bear/src/proxy.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { refreshSessionInProxy } from '@lumina/market/server'; -import type { NextRequest } from 'next/server'; - -import { API_VERSION_PATH } from './constants'; -import { serverEnv } from './env/server'; - -/** Refreshes an expired session before the page renders (see refreshSessionInProxy). */ -export function proxy(request: NextRequest) { - return refreshSessionInProxy(request, { - apiUrl: `${serverEnv.API_INTERNAL_ORIGIN}${API_VERSION_PATH}`, - }); -} - -export const config = { - // Pages and their data requests only: not build assets, images or files with an extension. - matcher: ['/((?!_next/static|_next/image|favicon.ico|.*\\.[a-zA-Z0-9]+$).*)'], -}; diff --git a/apps/bull/src/bootstrap/bootstrap.client.ts b/apps/bull/src/bootstrap/bootstrap.client.ts index 8f745b7..b11fa21 100644 --- a/apps/bull/src/bootstrap/bootstrap.client.ts +++ b/apps/bull/src/bootstrap/bootstrap.client.ts @@ -2,9 +2,8 @@ import { configureErrorHandler } from '@lumina/libs/error-handler'; import { eventEmitter } from '@lumina/libs/event-emitter'; import { http } from '@lumina/libs/http'; import { mapApiErrorBody } from '@lumina/market/app/http'; -import { SESSION_REFRESH_ENDPOINT } from '@lumina/market/app/session'; import { setEnv as setMarketEnv } from '@lumina/market/env'; -import { AUTH_EVENTS } from '@lumina/market/features/auth'; +import { AUTH_ENDPOINTS, AUTH_EVENTS } from '@lumina/market/features/auth'; import { API_VERSION_PATH } from '../constants'; import { clientEnv } from '../env'; @@ -23,7 +22,7 @@ setMarketEnv({ http.configure({ baseUrl: `${clientEnv.NEXT_PUBLIC_API_ORIGIN}${API_VERSION_PATH}`, refresh: { - endpoint: SESSION_REFRESH_ENDPOINT, + endpoint: AUTH_ENDPOINTS.refresh, onFailure: () => eventEmitter.emit(AUTH_EVENTS.logout, { reason: 'session-ended' }), }, diff --git a/apps/bull/src/bootstrap/bootstrap.server.ts b/apps/bull/src/bootstrap/bootstrap.server.ts index 26a5dbf..1e1c316 100644 --- a/apps/bull/src/bootstrap/bootstrap.server.ts +++ b/apps/bull/src/bootstrap/bootstrap.server.ts @@ -7,7 +7,7 @@ import { mapApiErrorBody } from '@lumina/market/app/http'; import { setEnv as setMarketEnv } from '@lumina/market/env'; import { cookies } from 'next/headers'; -import { API_VERSION_PATH } from '../constants'; +import { API_VERSION_PATH, FORWARDED_COOKIES } from '../constants'; import { clientEnv } from '../env'; import { serverEnv } from '../env/server'; import { ERROR_HANDLER_CONFIG } from './error-reporting'; @@ -19,11 +19,17 @@ setMarketEnv({ telegramHandle: clientEnv.NEXT_PUBLIC_TELEGRAM_HANDLE, supportHours: clientEnv.NEXT_PUBLIC_SUPPORT_HOURS, }); -// Each server request forwards its own user's session cookies; nothing per user is kept in module -// state. The server never refreshes: proxy.ts already did, before rendering. +// Server requests forward only the allowlisted cookies, never the session: the server render is +// the same for every visitor, and the browser loads whatever depends on the viewer. Read on each +// request; nothing per visitor is kept in module state. configureServerHttp({ baseUrl: `${serverEnv.API_INTERNAL_ORIGIN}${API_VERSION_PATH}`, - getCookieHeader: async () => (await cookies()).toString(), + getCookieHeader: async () => + (await cookies()) + .getAll() + .filter(({ name }) => FORWARDED_COOKIES.has(name)) + .map(({ name, value }) => `${name}=${encodeURIComponent(value)}`) + .join('; '), }); http.configure({ mapErrorBody: mapApiErrorBody }); configureErrorHandler(ERROR_HANDLER_CONFIG); diff --git a/apps/bull/src/constants/cookies.ts b/apps/bull/src/constants/cookies.ts new file mode 100644 index 0000000..a434714 --- /dev/null +++ b/apps/bull/src/constants/cookies.ts @@ -0,0 +1,6 @@ +/** + * Cookies the server render may read, forwarded on every server-side API request. Only values + * every visitor can have, such as locale and theme; never the session cookies, so no server + * response depends on who the viewer is. Adding an auth cookie here needs a recorded decision. + */ +export const FORWARDED_COOKIES: ReadonlySet = new Set([]); diff --git a/apps/bull/src/constants/index.ts b/apps/bull/src/constants/index.ts index 80dfdd5..7e3ce17 100644 --- a/apps/bull/src/constants/index.ts +++ b/apps/bull/src/constants/index.ts @@ -1 +1,2 @@ export { API_VERSION_PATH } from './api'; +export { FORWARDED_COOKIES } from './cookies'; diff --git a/apps/bull/src/proxy.ts b/apps/bull/src/proxy.ts deleted file mode 100644 index 301ac7a..0000000 --- a/apps/bull/src/proxy.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { refreshSessionInProxy } from '@lumina/market/server'; -import type { NextRequest } from 'next/server'; - -import { API_VERSION_PATH } from './constants'; -import { serverEnv } from './env/server'; - -/** Refreshes an expired session before the page renders (see refreshSessionInProxy). */ -export function proxy(request: NextRequest) { - return refreshSessionInProxy(request, { - apiUrl: `${serverEnv.API_INTERNAL_ORIGIN}${API_VERSION_PATH}`, - }); -} - -export const config = { - // Pages and their data requests only: not build assets, images or files with an extension. - matcher: ['/((?!_next/static|_next/image|favicon.ico|.*\\.[a-zA-Z0-9]+$).*)'], -}; diff --git a/platforms/market/src/app/app-shell/AppShell.tsx b/platforms/market/src/app/app-shell/AppShell.tsx index 2722652..c3b7893 100644 --- a/platforms/market/src/app/app-shell/AppShell.tsx +++ b/platforms/market/src/app/app-shell/AppShell.tsx @@ -5,16 +5,16 @@ import { QueryClientProvider } from '@tanstack/react-query'; import { I18nextProvider } from 'react-i18next'; import { NetworkBoundary } from './components/NetworkBoundary'; -import { useSessionEvents } from './hooks/use-session-events'; +import { useSession } from './hooks/use-session'; import type { AppShellProps } from './types'; /** * The provider shell shared by bull and bear: the query client, i18n, the connection bar, the - * one toast region, and the reactions to sign-in and sign-out. The app's root client component renders it after running the client + * one toast region, and the viewer's session (read once per load in the browser). The app's root client component renders it after running the client * bootstrap. */ export function AppShell({ queryClient, i18n, children }: AppShellProps) { - useSessionEvents(queryClient); + useSession(queryClient); return ( diff --git a/platforms/market/src/app/app-shell/hooks/use-session-events.ts b/platforms/market/src/app/app-shell/hooks/use-session-events.ts deleted file mode 100644 index 138bd82..0000000 --- a/platforms/market/src/app/app-shell/hooks/use-session-events.ts +++ /dev/null @@ -1,28 +0,0 @@ -import { eventEmitter } from '@lumina/libs/event-emitter'; -import type { QueryClient } from '@tanstack/react-query'; -import { useRouter } from 'next/navigation'; -import { useEffect } from 'react'; - -import { AUTH_EVENTS } from '../../../features/auth'; - -/** - * Keeps the page in step with the session. Signing in or up re-renders the server components for - * the new account; signing out, or a refresh that failed, drops every cached query (they belonged - * to the old account) and re-renders as a guest. - */ -export function useSessionEvents(queryClient: QueryClient): void { - const router = useRouter(); - - useEffect(() => { - const refresh = () => router.refresh(); - const unsubscribers = [ - eventEmitter.on(AUTH_EVENTS.login, refresh), - eventEmitter.on(AUTH_EVENTS.register, refresh), - eventEmitter.on(AUTH_EVENTS.logout, () => { - queryClient.clear(); - router.refresh(); - }), - ]; - return () => unsubscribers.forEach((unsubscribe) => unsubscribe()); - }, [router, queryClient]); -} diff --git a/platforms/market/src/app/app-shell/hooks/use-session.ts b/platforms/market/src/app/app-shell/hooks/use-session.ts new file mode 100644 index 0000000..61065b2 --- /dev/null +++ b/platforms/market/src/app/app-shell/hooks/use-session.ts @@ -0,0 +1,24 @@ +import { handleError } from '@lumina/libs/error-handler'; +import { eventEmitter } from '@lumina/libs/event-emitter'; +import type { QueryClient } from '@tanstack/react-query'; +import { useEffect } from 'react'; + +import { AUTH_EVENTS, restoreSession } from '../../../features/auth'; +import { useAuthStore } from '../../../stores/auth'; + +/** + * The browser learns who the viewer is once per page load; auth-dependent parts wait in their + * skeleton until then. When the session ends (sign-out, or a refresh that failed), the store goes + * back to guest and every cached query is dropped: it belonged to the old account. + */ +export function useSession(queryClient: QueryClient): void { + useEffect(() => { + restoreSession().catch((error: unknown) => + handleError(error, { where: 'app', name: 'restore-session' }), + ); + return eventEmitter.on(AUTH_EVENTS.logout, () => { + useAuthStore.getState().clearSession(); + queryClient.clear(); + }); + }, [queryClient]); +} diff --git a/platforms/market/src/app/error-boundaries/read-on-server/read-on-server.ts b/platforms/market/src/app/error-boundaries/read-on-server/read-on-server.ts index a399c06..945f496 100644 --- a/platforms/market/src/app/error-boundaries/read-on-server/read-on-server.ts +++ b/platforms/market/src/app/error-boundaries/read-on-server/read-on-server.ts @@ -1,21 +1,17 @@ import 'server-only'; import { classifyError } from '@lumina/libs/error-handler'; -import { isHttpError } from '@lumina/libs/http'; -import { redirect } from 'next/navigation'; -import { loginRoute } from '../../navigation'; -import type { ReadOnServerOptions, ServerRead } from './types'; +import type { ServerRead } from './types'; /** * Every server read of a page or a server part goes through it. A Server Component error reaches * the browser with only its digest, so the expected answers are classified here: 404 and 410 are - * `not-found`, 403 `no-access`, 401 redirects to login with `returnTo`, and the rest is rethrown - * to the nearest boundary. + * `not-found`, 403 `no-access`, and the rest is rethrown to the nearest boundary. Server reads + * carry no session, so only reads that are the same for every visitor happen here. */ export async function readOnServer( read: () => Promise, - { returnTo }: ReadOnServerOptions = {}, ): Promise> { try { return { status: 'ok', data: await read() }; @@ -24,9 +20,6 @@ export async function readOnServer( if (outcome === 'not-found' || outcome === 'no-access') { return { status: outcome }; } - if (returnTo && isHttpError(error) && error.status === 401) { - redirect(loginRoute(returnTo)); - } throw error; } } diff --git a/platforms/market/src/app/error-boundaries/read-on-server/server.ts b/platforms/market/src/app/error-boundaries/read-on-server/server.ts index 9ae150f..8925a62 100644 --- a/platforms/market/src/app/error-boundaries/read-on-server/server.ts +++ b/platforms/market/src/app/error-boundaries/read-on-server/server.ts @@ -1,4 +1,4 @@ import 'server-only'; export { readOnServer } from './read-on-server'; -export type { ReadOnServerOptions, ServerRead } from './types'; +export type { ServerRead } from './types'; diff --git a/platforms/market/src/app/error-boundaries/read-on-server/types.ts b/platforms/market/src/app/error-boundaries/read-on-server/types.ts index 1003949..9f1c606 100644 --- a/platforms/market/src/app/error-boundaries/read-on-server/types.ts +++ b/platforms/market/src/app/error-boundaries/read-on-server/types.ts @@ -2,8 +2,3 @@ export type ServerRead = | { status: 'ok'; data: T } | { status: 'not-found' | 'no-access' }; - -export type ReadOnServerOptions = { - /** The page's own path: a 401 redirects to login and comes back here. */ - returnTo?: string; -}; diff --git a/platforms/market/src/app/error-boundaries/server.ts b/platforms/market/src/app/error-boundaries/server.ts index 47c9f42..ac38dde 100644 --- a/platforms/market/src/app/error-boundaries/server.ts +++ b/platforms/market/src/app/error-boundaries/server.ts @@ -1,4 +1,4 @@ import 'server-only'; export { readOnServer } from './read-on-server/server'; -export type { ReadOnServerOptions, ServerRead } from './read-on-server/server'; +export type { ServerRead } from './read-on-server/server'; diff --git a/platforms/market/src/app/guards/auth-guard/AuthGuard.tsx b/platforms/market/src/app/guards/auth-guard/AuthGuard.tsx new file mode 100644 index 0000000..df99d0e --- /dev/null +++ b/platforms/market/src/app/guards/auth-guard/AuthGuard.tsx @@ -0,0 +1,33 @@ +'use client'; + +import { useRouter } from 'next/navigation'; +import { useEffect } from 'react'; + +import { useCurrentAccount, useViewerStatus } from '../../../stores/auth'; +import { StatusEmptyState } from '../../error-boundaries'; +import { loginRoute } from '../../navigation'; +import type { AuthGuardProps } from './types'; + +/** + * Wraps every page that needs a signed-in visitor (the route group's layout renders it). The + * server render and the first browser render show the page skeleton, because the server never + * knows the viewer. Then a guest goes to login with a return path, the other role sees the + * page-size no-access state, and a member sees the page. + */ +export function AuthGuard({ fallback, role, children }: AuthGuardProps) { + const status = useViewerStatus(); + const account = useCurrentAccount(); + const router = useRouter(); + + useEffect(() => { + if (status !== 'guest') return; + const { pathname, search } = window.location; + router.replace(loginRoute(`${pathname}${search}`)); + }, [status, router]); + + if (status !== 'member' || !account) return fallback; + if (role && account.role !== role) { + return ; + } + return children; +} diff --git a/platforms/market/src/app/guards/auth-guard/auth-guard.ts b/platforms/market/src/app/guards/auth-guard/auth-guard.ts deleted file mode 100644 index 6a9e8da..0000000 --- a/platforms/market/src/app/guards/auth-guard/auth-guard.ts +++ /dev/null @@ -1,27 +0,0 @@ -import 'server-only'; - -import { redirect } from 'next/navigation'; - -import { getSessionAccount } from '../../../features/auth/caches/server'; -import type { AccountPayload } from '../../../features/auth'; -import { loginRoute, ROUTES } from '../../navigation'; -import type { RequireAccountOptions } from './types'; - -/** - * For pages that need a signed-in visitor: the account, or a redirect to login that comes back to - * `returnTo`. proxy.ts has already refreshed an expired session, so `null` here means a guest. - */ -export async function requireAccount({ - returnTo, -}: RequireAccountOptions): Promise { - const account = await getSessionAccount(); - if (!account) redirect(loginRoute(returnTo)); - return account; -} - -/** For login and registration: a signed-in visitor goes straight to `to` (home by default). */ -export async function redirectIfSignedIn( - to: string = ROUTES.home, -): Promise { - if (await getSessionAccount()) redirect(to); -} diff --git a/platforms/market/src/app/guards/auth-guard/index.ts b/platforms/market/src/app/guards/auth-guard/index.ts new file mode 100644 index 0000000..29f927d --- /dev/null +++ b/platforms/market/src/app/guards/auth-guard/index.ts @@ -0,0 +1,2 @@ +export { AuthGuard } from './AuthGuard'; +export type { AuthGuardProps } from './types'; diff --git a/platforms/market/src/app/guards/auth-guard/server.ts b/platforms/market/src/app/guards/auth-guard/server.ts deleted file mode 100644 index c35a4fb..0000000 --- a/platforms/market/src/app/guards/auth-guard/server.ts +++ /dev/null @@ -1,4 +0,0 @@ -import 'server-only'; - -export { redirectIfSignedIn, requireAccount } from './auth-guard'; -export type { RequireAccountOptions } from './types'; diff --git a/platforms/market/src/app/guards/auth-guard/types.ts b/platforms/market/src/app/guards/auth-guard/types.ts index 7dc8ac4..30aee61 100644 --- a/platforms/market/src/app/guards/auth-guard/types.ts +++ b/platforms/market/src/app/guards/auth-guard/types.ts @@ -1,4 +1,11 @@ -export type RequireAccountOptions = { - /** The page's own path: login sends the visitor back here afterwards. */ - returnTo: string; +import type { ReactNode } from 'react'; + +import type { UserRole } from '../../../features/auth'; + +export type AuthGuardProps = { + /** The page's same-size skeleton, shown until the browser knows the viewer. */ + fallback: ReactNode; + /** Only this role may see the page; the other role gets the no-access state. */ + role?: UserRole; + children: ReactNode; }; diff --git a/platforms/market/src/app/guards/guest-guard/GuestGuard.tsx b/platforms/market/src/app/guards/guest-guard/GuestGuard.tsx new file mode 100644 index 0000000..518ad6f --- /dev/null +++ b/platforms/market/src/app/guards/guest-guard/GuestGuard.tsx @@ -0,0 +1,27 @@ +'use client'; + +import { useRouter } from 'next/navigation'; +import { useEffect } from 'react'; + +import { useViewerStatus } from '../../../stores/auth'; +import { safeReturnPath } from '../../navigation'; +import type { GuestGuardProps } from './types'; + +/** + * Wraps login and registration. A signed-in visitor goes on to `?redirect=` (a path on this site + * only) or home; a guest sees the page. The skeleton covers the moment before the viewer is known. + */ +export function GuestGuard({ fallback, children }: GuestGuardProps) { + const status = useViewerStatus(); + const router = useRouter(); + + useEffect(() => { + if (status !== 'member') return; + const redirect = new URLSearchParams(window.location.search).get( + 'redirect', + ); + router.replace(safeReturnPath(redirect)); + }, [status, router]); + + return status === 'guest' ? children : fallback; +} diff --git a/platforms/market/src/app/guards/guest-guard/index.ts b/platforms/market/src/app/guards/guest-guard/index.ts new file mode 100644 index 0000000..3686656 --- /dev/null +++ b/platforms/market/src/app/guards/guest-guard/index.ts @@ -0,0 +1,2 @@ +export { GuestGuard } from './GuestGuard'; +export type { GuestGuardProps } from './types'; diff --git a/platforms/market/src/app/guards/guest-guard/types.ts b/platforms/market/src/app/guards/guest-guard/types.ts new file mode 100644 index 0000000..b91faec --- /dev/null +++ b/platforms/market/src/app/guards/guest-guard/types.ts @@ -0,0 +1,7 @@ +import type { ReactNode } from 'react'; + +export type GuestGuardProps = { + /** The page's same-size skeleton, shown until the browser knows the viewer. */ + fallback: ReactNode; + children: ReactNode; +}; diff --git a/platforms/market/src/app/guards/role-guard/role-guard.ts b/platforms/market/src/app/guards/role-guard/role-guard.ts deleted file mode 100644 index 0b436f7..0000000 --- a/platforms/market/src/app/guards/role-guard/role-guard.ts +++ /dev/null @@ -1,19 +0,0 @@ -import 'server-only'; - -import { requireAccount } from '../auth-guard/server'; -import type { RequireRoleOptions, RoleCheck } from './types'; - -/** - * For pages of one role (the creator dashboard, the investor's subscriptions). A guest is sent to - * login; the other role gets `no-access`, which the page renders as its page-size - * StatusEmptyState (a 403, never a redirect loop). - */ -export async function requireRole({ - role, - returnTo, -}: RequireRoleOptions): Promise { - const account = await requireAccount({ returnTo }); - return account.role === role - ? { status: 'ok', account } - : { status: 'no-access' }; -} diff --git a/platforms/market/src/app/guards/role-guard/server.ts b/platforms/market/src/app/guards/role-guard/server.ts deleted file mode 100644 index efc868f..0000000 --- a/platforms/market/src/app/guards/role-guard/server.ts +++ /dev/null @@ -1,4 +0,0 @@ -import 'server-only'; - -export { requireRole } from './role-guard'; -export type { RequireRoleOptions, RoleCheck } from './types'; diff --git a/platforms/market/src/app/guards/role-guard/types.ts b/platforms/market/src/app/guards/role-guard/types.ts deleted file mode 100644 index 799760a..0000000 --- a/platforms/market/src/app/guards/role-guard/types.ts +++ /dev/null @@ -1,12 +0,0 @@ -import type { AccountPayload, UserRole } from '../../../features/auth'; - -export type RequireRoleOptions = { - role: UserRole; - /** The page's own path, for the login redirect. */ - returnTo: string; -}; - -/** The account when it has the role, `no-access` when it is the other role. */ -export type RoleCheck = - | { status: 'ok'; account: AccountPayload } - | { status: 'no-access' }; diff --git a/platforms/market/src/app/navigation/index.ts b/platforms/market/src/app/navigation/index.ts index 6603490..b96d541 100644 --- a/platforms/market/src/app/navigation/index.ts +++ b/platforms/market/src/app/navigation/index.ts @@ -1,2 +1,3 @@ export { CHANNEL_PREFIX } from './constants'; export { loginRoute, ROUTES } from './navigation'; +export { safeReturnPath } from './return-path'; diff --git a/platforms/market/src/app/navigation/return-path.ts b/platforms/market/src/app/navigation/return-path.ts new file mode 100644 index 0000000..88caec3 --- /dev/null +++ b/platforms/market/src/app/navigation/return-path.ts @@ -0,0 +1,17 @@ +import { ROUTES } from './navigation'; + +/** + * A `?redirect=` value is only followed when it is a path on this site: `/dashboard`, never + * `https://evil.example` or `//evil.example`, so login can't be turned into an open redirect. + */ +export function safeReturnPath(value: string | null | undefined): string { + if ( + !value || + !value.startsWith('/') || + value.startsWith('//') || + value.startsWith('/\\') + ) { + return ROUTES.home; + } + return value; +} diff --git a/platforms/market/src/app/session/constants.ts b/platforms/market/src/app/session/constants.ts deleted file mode 100644 index 3ef4861..0000000 --- a/platforms/market/src/app/session/constants.ts +++ /dev/null @@ -1,11 +0,0 @@ -/** The gateway's HttpOnly session cookies; JavaScript never reads their values. */ -export const SESSION_COOKIES = { - access: 'access_token', - refresh: 'refresh_token', -} as const; - -/** Rotates the session from the refresh cookie; relative to the API base URL (`…/v1`). */ -export const SESSION_REFRESH_ENDPOINT = '/auth/refresh'; - -/** A refresh before rendering must never hold the page up for long. */ -export const PROXY_REFRESH_TIMEOUT_MS = 3000; diff --git a/platforms/market/src/app/session/index.ts b/platforms/market/src/app/session/index.ts deleted file mode 100644 index d39010f..0000000 --- a/platforms/market/src/app/session/index.ts +++ /dev/null @@ -1 +0,0 @@ -export { SESSION_COOKIES, SESSION_REFRESH_ENDPOINT } from './constants'; diff --git a/platforms/market/src/app/session/refresh-in-proxy.ts b/platforms/market/src/app/session/refresh-in-proxy.ts deleted file mode 100644 index 123b3fc..0000000 --- a/platforms/market/src/app/session/refresh-in-proxy.ts +++ /dev/null @@ -1,77 +0,0 @@ -import { createHttpClient } from '@lumina/libs/http'; -import { NextResponse } from 'next/server'; -import type { NextRequest } from 'next/server'; - -import { - PROXY_REFRESH_TIMEOUT_MS, - SESSION_COOKIES, - SESSION_REFRESH_ENDPOINT, -} from './constants'; -import type { ProxySessionOptions, RefreshResponseDto } from './types'; - -/** `name=value; Path=/; …` → [name, value]. */ -function cookiePair(setCookie: string): [string, string] | undefined { - const pair = setCookie.split(';', 1)[0] ?? ''; - const index = pair.indexOf('='); - return index > 0 ? [pair.slice(0, index), pair.slice(index + 1)] : undefined; -} - -/** Copies the gateway's Set-Cookie headers to the browser's response. */ -function forwardCookies( - response: NextResponse, - setCookies: string[], -): NextResponse { - for (const setCookie of setCookies) - response.headers.append('set-cookie', setCookie); - return response; -} - -/** - * Refreshes an expired session before the page renders, so server components never render a - * signed-in visitor as a guest. It runs only when the access cookie is gone (it lives 15 minutes) - * and the refresh cookie is still there. The new cookies go to the browser, and into this - * request's Cookie header so this render's API calls already use them. - * - * A superseded refresh (a tab refreshed at the same moment) changes nothing. On any failure the - * page renders as a guest and the cookies stay as they are: the browser's next API call refreshes - * against the gateway itself, which clears a dead session's cookies on its own domain. Never - * throws: rendering goes on either way. - */ -export async function refreshSessionInProxy( - request: NextRequest, - { apiUrl }: ProxySessionOptions, -): Promise { - const refreshToken = request.cookies.get(SESSION_COOKIES.refresh)?.value; - if (!refreshToken || request.cookies.has(SESSION_COOKIES.access)) { - return NextResponse.next(); - } - - // A client of its own: the proxy runs before any bootstrap has configured the root client. - const client = createHttpClient({ - baseUrl: apiUrl, - retry: false, - timeout: PROXY_REFRESH_TIMEOUT_MS, - }); - try { - const response = await client.request({ - method: 'POST', - url: SESSION_REFRESH_ENDPOINT, - headers: { - cookie: `${SESSION_COOKIES.refresh}=${refreshToken}`, - 'user-agent': request.headers.get('user-agent') ?? '', - }, - skipRefresh: true, - }); - const setCookies = response.headers.getSetCookie(); - for (const setCookie of setCookies) { - const pair = cookiePair(setCookie); - if (pair) request.cookies.set(pair[0], pair[1]); - } - return forwardCookies( - NextResponse.next({ request: { headers: request.headers } }), - setCookies, - ); - } catch { - return NextResponse.next(); - } -} diff --git a/platforms/market/src/app/session/server.ts b/platforms/market/src/app/session/server.ts deleted file mode 100644 index 01ac205..0000000 --- a/platforms/market/src/app/session/server.ts +++ /dev/null @@ -1,4 +0,0 @@ -import 'server-only'; - -export { refreshSessionInProxy } from './refresh-in-proxy'; -export type { ProxySessionOptions } from './types'; diff --git a/platforms/market/src/app/session/types.ts b/platforms/market/src/app/session/types.ts deleted file mode 100644 index 797778b..0000000 --- a/platforms/market/src/app/session/types.ts +++ /dev/null @@ -1,7 +0,0 @@ -export type ProxySessionOptions = { - /** The API base URL as the server reaches it, with the version: `http://gateway:3000/v1`. */ - apiUrl: string; -}; - -/** `POST /auth/refresh` body: the user after a rotation, or `superseded` when another refresh won. */ -export type RefreshResponseDto = { superseded: true } | { user: unknown }; diff --git a/platforms/market/src/features/auth/actions/login/actions.ts b/platforms/market/src/features/auth/actions/login/actions.ts index 031382e..b05e39a 100644 --- a/platforms/market/src/features/auth/actions/login/actions.ts +++ b/platforms/market/src/features/auth/actions/login/actions.ts @@ -1,15 +1,20 @@ import { eventEmitter } from '@lumina/libs/event-emitter'; +import { useAuthStore } from '../../../../stores/auth'; import { AUTH_EVENTS } from '../../constants'; import { authRepository } from '../../repositories/auth'; import type { SessionPayload, VerifyOtpArgs } from '../../repositories/auth'; -/** Verifies the login code; the gateway sets the session cookies. Emits `auth.login`. */ +/** + * Verifies the login code; the gateway sets the session cookies and the auth store learns the + * account, so every auth-dependent part renders its member variant. Emits `auth.login`. + */ export async function login( args: VerifyOtpArgs, { emit = true }: { emit?: boolean } = {}, ): Promise { const session = await authRepository.verifyLoginOtp(args); + useAuthStore.getState().setSession({ account: session.account }); if (emit) { eventEmitter.emit(AUTH_EVENTS.login, { userId: session.account.id, diff --git a/platforms/market/src/features/auth/actions/logout/actions.ts b/platforms/market/src/features/auth/actions/logout/actions.ts index a205dc1..470e18f 100644 --- a/platforms/market/src/features/auth/actions/logout/actions.ts +++ b/platforms/market/src/features/auth/actions/logout/actions.ts @@ -1,13 +1,15 @@ import { eventEmitter } from '@lumina/libs/event-emitter'; +import { useAuthStore } from '../../../../stores/auth'; import { AUTH_EVENTS } from '../../constants'; import { authRepository } from '../../repositories/auth'; -/** Revokes the session and clears its cookies. Emits `auth.logout`. */ +/** Revokes the session, clears its cookies and the auth store. Emits `auth.logout`. */ export async function logout({ emit = true, }: { emit?: boolean } = {}): Promise<'ok'> { await authRepository.logout(); + useAuthStore.getState().clearSession(); if (emit) eventEmitter.emit(AUTH_EVENTS.logout, { reason: 'signed-out' }); return 'ok'; } diff --git a/platforms/market/src/features/auth/actions/register-creator/actions.ts b/platforms/market/src/features/auth/actions/register-creator/actions.ts index cbe4f93..c057fb6 100644 --- a/platforms/market/src/features/auth/actions/register-creator/actions.ts +++ b/platforms/market/src/features/auth/actions/register-creator/actions.ts @@ -1,5 +1,6 @@ import { eventEmitter } from '@lumina/libs/event-emitter'; +import { useAuthStore } from '../../../../stores/auth'; import { AUTH_EVENTS } from '../../constants'; import { authRepository } from '../../repositories/auth'; import type { @@ -7,12 +8,13 @@ import type { RegisterCreatorArgs, } from '../../repositories/auth'; -/** Creates a creator account with lite KYC and signs it in. Emits `auth.register`. */ +/** Creates a creator account with lite KYC and signs it in (cookies and auth store). Emits `auth.register`. */ export async function registerCreator( args: RegisterCreatorArgs, { emit = true }: { emit?: boolean } = {}, ): Promise { const registration = await authRepository.registerCreator(args); + useAuthStore.getState().setSession({ account: registration.account }); if (emit) { eventEmitter.emit(AUTH_EVENTS.register, { userId: registration.account.id, diff --git a/platforms/market/src/features/auth/actions/register-investor/actions.ts b/platforms/market/src/features/auth/actions/register-investor/actions.ts index 0f430d4..a5e104e 100644 --- a/platforms/market/src/features/auth/actions/register-investor/actions.ts +++ b/platforms/market/src/features/auth/actions/register-investor/actions.ts @@ -1,5 +1,6 @@ import { eventEmitter } from '@lumina/libs/event-emitter'; +import { useAuthStore } from '../../../../stores/auth'; import { AUTH_EVENTS } from '../../constants'; import { authRepository } from '../../repositories/auth'; import type { @@ -7,12 +8,13 @@ import type { SessionPayload, } from '../../repositories/auth'; -/** Creates an investor account and signs it in. Emits `auth.register`. */ +/** Creates an investor account and signs it in (cookies and auth store). Emits `auth.register`. */ export async function registerInvestor( args: RegisterInvestorArgs, { emit = true }: { emit?: boolean } = {}, ): Promise { const session = await authRepository.registerInvestor(args); + useAuthStore.getState().setSession({ account: session.account }); if (emit) { eventEmitter.emit(AUTH_EVENTS.register, { userId: session.account.id, diff --git a/platforms/market/src/features/auth/actions/restore-session/actions.ts b/platforms/market/src/features/auth/actions/restore-session/actions.ts new file mode 100644 index 0000000..47500f2 --- /dev/null +++ b/platforms/market/src/features/auth/actions/restore-session/actions.ts @@ -0,0 +1,30 @@ +import { eventEmitter } from '@lumina/libs/event-emitter'; + +import { useAuthStore } from '../../../../stores/auth'; +import type { ViewerStatus } from '../../../../stores/auth'; +import { AUTH_EVENTS } from '../../constants'; +import { authRepository } from '../../repositories/auth'; + +/** + * Learns who the viewer is, once per page load (the AppShell calls it). A guest is an empty + * session, not an error. An expired access cookie is refreshed by the HTTP client on the way. When + * the read still fails, the viewer is treated as a guest and the error is rethrown for reporting. + * Emits `auth.restore`. + */ +export async function restoreSession({ + emit = true, +}: { emit?: boolean } = {}): Promise { + const { setSession, clearSession } = useAuthStore.getState(); + let status: ViewerStatus; + try { + const { account } = await authRepository.getSession(); + if (account) setSession({ account }); + else clearSession(); + status = account ? 'member' : 'guest'; + } catch (error) { + clearSession(); + throw error; + } + if (emit) eventEmitter.emit(AUTH_EVENTS.restore, { status }); + return status; +} diff --git a/platforms/market/src/features/auth/actions/restore-session/index.ts b/platforms/market/src/features/auth/actions/restore-session/index.ts new file mode 100644 index 0000000..0a4bdf0 --- /dev/null +++ b/platforms/market/src/features/auth/actions/restore-session/index.ts @@ -0,0 +1 @@ +export { restoreSession } from './actions'; diff --git a/platforms/market/src/features/auth/caches/server.ts b/platforms/market/src/features/auth/caches/server.ts deleted file mode 100644 index 8e01f97..0000000 --- a/platforms/market/src/features/auth/caches/server.ts +++ /dev/null @@ -1,3 +0,0 @@ -import 'server-only'; - -export { getSessionAccount } from './session-account'; diff --git a/platforms/market/src/features/auth/caches/session-account.ts b/platforms/market/src/features/auth/caches/session-account.ts deleted file mode 100644 index 755b736..0000000 --- a/platforms/market/src/features/auth/caches/session-account.ts +++ /dev/null @@ -1,22 +0,0 @@ -import 'server-only'; - -import { isHttpError } from '@lumina/libs/http'; -import { cache } from 'react'; - -import { accountRepository } from '../repositories/account'; -import type { AccountPayload } from '../repositories/account'; - -/** - * The signed-in account for this request, or `null` for a guest. One request per render however - * many server components ask; the cookies are forwarded by the server HTTP configuration. - */ -export const getSessionAccount = cache( - async (): Promise => { - try { - return await accountRepository.getCurrent(); - } catch (error) { - if (isHttpError(error) && error.status === 401) return null; - throw error; - } - }, -); diff --git a/platforms/market/src/features/auth/constants.ts b/platforms/market/src/features/auth/constants.ts index f3fb1d0..d4b53a8 100644 --- a/platforms/market/src/features/auth/constants.ts +++ b/platforms/market/src/features/auth/constants.ts @@ -1,5 +1,6 @@ /** Events auth actions emit when they succeed; the AppShell reacts to them. */ export const AUTH_EVENTS = { + restore: 'auth.restore', login: 'auth.login', register: 'auth.register', logout: 'auth.logout', diff --git a/platforms/market/src/features/auth/index.ts b/platforms/market/src/features/auth/index.ts index 9e7c43a..d410726 100644 --- a/platforms/market/src/features/auth/index.ts +++ b/platforms/market/src/features/auth/index.ts @@ -4,6 +4,7 @@ export { login } from './actions/login'; export { logout } from './actions/logout'; export { registerCreator } from './actions/register-creator'; export { registerInvestor } from './actions/register-investor'; +export { restoreSession } from './actions/restore-session'; export { AUTH_EVENTS } from './constants'; export type { UserRole, UserStatus } from './entities/user'; export { accountKeys, accountRepository } from './repositories/account'; @@ -17,6 +18,7 @@ export type { RegistrationVerifiedPayload, SendOtpArgs, SessionPayload, + SessionStatePayload, VerifyOtpArgs, } from './repositories/auth'; export type { LogoutReason } from './types'; diff --git a/platforms/market/src/features/auth/repositories/auth/auth.ts b/platforms/market/src/features/auth/repositories/auth/auth.ts index 3c35775..a270dbd 100644 --- a/platforms/market/src/features/auth/repositories/auth/auth.ts +++ b/platforms/market/src/features/auth/repositories/auth/auth.ts @@ -9,6 +9,7 @@ import { toRegisterInvestorDto, toRegistrationVerifiedPayload, toSessionPayload, + toSessionStatePayload, toVerifyOtpDto, } from './mappers'; import type { @@ -23,6 +24,8 @@ import type { SendOtpArgs, SessionPayload, SessionResponseDto, + SessionStatePayload, + SessionStateResponseDto, VerifyOtpArgs, } from './types'; @@ -122,6 +125,20 @@ export const authRepository = { return toSessionPayload(response); }, + /** + * The viewer's session, read in the browser once per page load. No `skipRefresh`: an expired + * access cookie answers 401, the HTTP client refreshes, and this read replays. + */ + async getSession({ + signal, + }: { signal?: AbortSignal } = {}): Promise { + const response = await authHttp.get( + AUTH_ENDPOINTS.session, + { signal }, + ); + return toSessionStatePayload(response); + }, + /** Revokes the session and clears its cookies; succeeds even without one. */ async logout(): Promise { await authHttp.post(AUTH_ENDPOINTS.logout, undefined, { diff --git a/platforms/market/src/features/auth/repositories/auth/constants.ts b/platforms/market/src/features/auth/repositories/auth/constants.ts index 1977993..ed7d1cc 100644 --- a/platforms/market/src/features/auth/repositories/auth/constants.ts +++ b/platforms/market/src/features/auth/repositories/auth/constants.ts @@ -6,6 +6,10 @@ export const AUTH_ENDPOINTS = { registerCreator: '/auth/register/creator', requestLoginOtp: '/auth/login', verifyLoginOtp: '/auth/login/verify', + /** The viewer's session: the account, or `{ user: null }` for a guest. */ + session: '/auth/session', + /** Rotates the session from the refresh cookie; the HTTP client calls it on a 401. */ + refresh: '/auth/refresh', logout: '/auth/logout', } as const; diff --git a/platforms/market/src/features/auth/repositories/auth/index.ts b/platforms/market/src/features/auth/repositories/auth/index.ts index 36e7781..f161439 100644 --- a/platforms/market/src/features/auth/repositories/auth/index.ts +++ b/platforms/market/src/features/auth/repositories/auth/index.ts @@ -8,5 +8,6 @@ export type { RegistrationVerifiedPayload, SendOtpArgs, SessionPayload, + SessionStatePayload, VerifyOtpArgs, } from './types'; diff --git a/platforms/market/src/features/auth/repositories/auth/mappers.ts b/platforms/market/src/features/auth/repositories/auth/mappers.ts index fa7d8f7..0d49470 100644 --- a/platforms/market/src/features/auth/repositories/auth/mappers.ts +++ b/platforms/market/src/features/auth/repositories/auth/mappers.ts @@ -14,6 +14,8 @@ import type { SendOtpArgs, SessionPayload, SessionResponseDto, + SessionStatePayload, + SessionStateResponseDto, VerifyOtpArgs, VerifyOtpDto, } from './types'; @@ -69,6 +71,12 @@ export function toSessionPayload(dto: SessionResponseDto): SessionPayload { return { account: toAccountPayload(dto.user) }; } +export function toSessionStatePayload( + dto: SessionStateResponseDto, +): SessionStatePayload { + return { account: dto.user ? toAccountPayload(dto.user) : null }; +} + export function toCreatorRegisteredPayload( dto: CreatorRegisteredResponseDto, ): CreatorRegisteredPayload { diff --git a/platforms/market/src/features/auth/repositories/auth/types.ts b/platforms/market/src/features/auth/repositories/auth/types.ts index b544666..072d9f7 100644 --- a/platforms/market/src/features/auth/repositories/auth/types.ts +++ b/platforms/market/src/features/auth/repositories/auth/types.ts @@ -49,6 +49,12 @@ export type RegisterCreatorArgs = RegisterInvestorArgs & { export type SessionResponseDto = { user: UserEntity; userType: UserRole }; export type SessionPayload = { account: AccountPayload }; +/** A guest gets `{ user: null }`, never a 401, so a guest never starts a refresh. */ +export type SessionStateResponseDto = + | { user: UserEntity; userType: UserRole } + | { user: null }; +export type SessionStatePayload = { account: AccountPayload | null }; + export type CreatorRegisteredResponseDto = { account: UserEntity; onboarding: { nextStep: string; profileSetupRequired: boolean }; diff --git a/platforms/market/src/features/auth/types.ts b/platforms/market/src/features/auth/types.ts index 613288f..f383fbf 100644 --- a/platforms/market/src/features/auth/types.ts +++ b/platforms/market/src/features/auth/types.ts @@ -1,3 +1,4 @@ +import type { ViewerStatus } from '../../stores/auth'; import type { UserRole } from './entities/user'; /** Why the session ended: the user signed out, or the refresh token was dead. */ @@ -5,6 +6,7 @@ export type LogoutReason = 'signed-out' | 'session-ended'; declare module '@lumina/libs/event-emitter' { interface EventMap { + 'auth.restore': { status: ViewerStatus }; 'auth.login': { userId: string; role: UserRole }; 'auth.register': { userId: string; role: UserRole }; 'auth.logout': { reason: LogoutReason }; diff --git a/platforms/market/src/features/checkout/caches/checkout-screen.ts b/platforms/market/src/features/checkout/caches/checkout-screen.ts deleted file mode 100644 index fa2e774..0000000 --- a/platforms/market/src/features/checkout/caches/checkout-screen.ts +++ /dev/null @@ -1,15 +0,0 @@ -import 'server-only'; - -import { cache } from 'react'; - -import { checkoutRepository } from '../repositories/checkout'; -import type { CheckoutPayload } from '../repositories/checkout'; - -/** - * The signed-in investor's U9 checkout for a creator, once per render. Throws the API's error as - * is: 401 without a session, 403 for a non-investor or a creator who is not approved or suspended. - */ -export const getCheckoutScreen = cache( - (creatorId: string): Promise => - checkoutRepository.getScreen(creatorId), -); diff --git a/platforms/market/src/features/checkout/caches/server.ts b/platforms/market/src/features/checkout/caches/server.ts deleted file mode 100644 index 1a32894..0000000 --- a/platforms/market/src/features/checkout/caches/server.ts +++ /dev/null @@ -1,3 +0,0 @@ -import 'server-only'; - -export { getCheckoutScreen } from './checkout-screen'; diff --git a/platforms/market/src/features/feed/caches/feed.ts b/platforms/market/src/features/feed/caches/feed.ts deleted file mode 100644 index c11bb5f..0000000 --- a/platforms/market/src/features/feed/caches/feed.ts +++ /dev/null @@ -1,15 +0,0 @@ -import 'server-only'; - -import { cache } from 'react'; - -import { FEED_PAGE_LIMIT, feedRepository } from '../repositories/feed'; -import type { FeedPayload } from '../repositories/feed'; - -/** - * The signed-in investor's first feed page. Rejects with 401 for a guest and 403 for a creator; - * later pages load on the client with the same `FEED_PAGE_LIMIT`. - */ -export const getFeed = cache( - async (): Promise => - feedRepository.list({ page: 1, limit: FEED_PAGE_LIMIT }), -); diff --git a/platforms/market/src/features/feed/caches/server.ts b/platforms/market/src/features/feed/caches/server.ts deleted file mode 100644 index d4e965c..0000000 --- a/platforms/market/src/features/feed/caches/server.ts +++ /dev/null @@ -1,3 +0,0 @@ -import 'server-only'; - -export { getFeed } from './feed'; diff --git a/platforms/market/src/features/finance/caches/creator-payments.ts b/platforms/market/src/features/finance/caches/creator-payments.ts deleted file mode 100644 index d3a312d..0000000 --- a/platforms/market/src/features/finance/caches/creator-payments.ts +++ /dev/null @@ -1,11 +0,0 @@ -import 'server-only'; - -import { cache } from 'react'; - -import { creatorPaymentRepository } from '../repositories/creator-payment'; -import type { CreatorPaymentPayload } from '../repositories/creator-payment'; - -/** Payments the signed-in creator received, once per render. */ -export const getCreatorPayments = cache( - async (): Promise => creatorPaymentRepository.list(), -); diff --git a/platforms/market/src/features/finance/caches/server.ts b/platforms/market/src/features/finance/caches/server.ts deleted file mode 100644 index 73ae92f..0000000 --- a/platforms/market/src/features/finance/caches/server.ts +++ /dev/null @@ -1,3 +0,0 @@ -import 'server-only'; - -export { getCreatorPayments } from './creator-payments'; diff --git a/platforms/market/src/features/follow/caches/follow-status.ts b/platforms/market/src/features/follow/caches/follow-status.ts deleted file mode 100644 index d209f15..0000000 --- a/platforms/market/src/features/follow/caches/follow-status.ts +++ /dev/null @@ -1,15 +0,0 @@ -import 'server-only'; - -import { cache } from 'react'; - -import { followRepository } from '../repositories/follow'; -import type { FollowStatusPayload } from '../repositories/follow'; - -/** - * The signed-in investor's follow state for a creator, once per render per id. Ask only for an - * investor session: guests get 401 and creators 403. - */ -export const getFollowStatus = cache( - (creatorId: string): Promise => - followRepository.getStatus({ creatorId }), -); diff --git a/platforms/market/src/features/follow/caches/server.ts b/platforms/market/src/features/follow/caches/server.ts deleted file mode 100644 index 7642da9..0000000 --- a/platforms/market/src/features/follow/caches/server.ts +++ /dev/null @@ -1,3 +0,0 @@ -import 'server-only'; - -export { getFollowStatus } from './follow-status'; diff --git a/platforms/market/src/features/notification/caches/inbox.ts b/platforms/market/src/features/notification/caches/inbox.ts deleted file mode 100644 index 5e98749..0000000 --- a/platforms/market/src/features/notification/caches/inbox.ts +++ /dev/null @@ -1,11 +0,0 @@ -import 'server-only'; - -import { cache } from 'react'; - -import { notificationRepository } from '../repositories/notification'; -import type { InboxPayload } from '../repositories/notification'; - -/** The signed-in user's inbox, one request per render. 401 reaches the caller. */ -export const getNotificationInbox = cache( - (): Promise => notificationRepository.listInbox(), -); diff --git a/platforms/market/src/features/notification/caches/server.ts b/platforms/market/src/features/notification/caches/server.ts deleted file mode 100644 index d97593c..0000000 --- a/platforms/market/src/features/notification/caches/server.ts +++ /dev/null @@ -1,4 +0,0 @@ -import 'server-only'; - -export { getNotificationInbox } from './inbox'; -export { getUnreadNotificationCount } from './unread-count'; diff --git a/platforms/market/src/features/notification/caches/unread-count.ts b/platforms/market/src/features/notification/caches/unread-count.ts deleted file mode 100644 index 2131fef..0000000 --- a/platforms/market/src/features/notification/caches/unread-count.ts +++ /dev/null @@ -1,11 +0,0 @@ -import 'server-only'; - -import { cache } from 'react'; - -import { notificationRepository } from '../repositories/notification'; -import type { UnreadCountPayload } from '../repositories/notification'; - -/** The signed-in user's unread badge count, one request per render. 401 reaches the caller. */ -export const getUnreadNotificationCount = cache( - (): Promise => notificationRepository.getUnreadCount(), -); diff --git a/platforms/market/src/features/overview/caches/creator-dashboard.ts b/platforms/market/src/features/overview/caches/creator-dashboard.ts deleted file mode 100644 index fcda32c..0000000 --- a/platforms/market/src/features/overview/caches/creator-dashboard.ts +++ /dev/null @@ -1,12 +0,0 @@ -import 'server-only'; - -import { cache } from 'react'; - -import { creatorDashboardRepository } from '../repositories/creator-dashboard'; -import type { CreatorDashboardPayload } from '../repositories/creator-dashboard'; - -/** The signed-in creator's dashboard figures, once per render. */ -export const getCreatorDashboard = cache( - async (): Promise => - creatorDashboardRepository.get(), -); diff --git a/platforms/market/src/features/overview/caches/server.ts b/platforms/market/src/features/overview/caches/server.ts deleted file mode 100644 index d659e3b..0000000 --- a/platforms/market/src/features/overview/caches/server.ts +++ /dev/null @@ -1,3 +0,0 @@ -import 'server-only'; - -export { getCreatorDashboard } from './creator-dashboard'; diff --git a/platforms/market/src/features/pricing/caches/pricing-form.ts b/platforms/market/src/features/pricing/caches/pricing-form.ts deleted file mode 100644 index f26481c..0000000 --- a/platforms/market/src/features/pricing/caches/pricing-form.ts +++ /dev/null @@ -1,14 +0,0 @@ -import 'server-only'; - -import { cache } from 'react'; - -import { pricingRepository } from '../repositories/pricing'; -import type { PricingFormPayload } from '../repositories/pricing'; - -/** - * The signed-in creator's C7 pricing form, once per render. Throws the API's error as is: 401 - * without a session, 403 for a non-creator or an incomplete creator profile. - */ -export const getPricingForm = cache( - (): Promise => pricingRepository.getForm(), -); diff --git a/platforms/market/src/features/pricing/caches/server.ts b/platforms/market/src/features/pricing/caches/server.ts deleted file mode 100644 index 1d3c822..0000000 --- a/platforms/market/src/features/pricing/caches/server.ts +++ /dev/null @@ -1,3 +0,0 @@ -import 'server-only'; - -export { getPricingForm } from './pricing-form'; diff --git a/platforms/market/src/features/profile/caches/my-profile.ts b/platforms/market/src/features/profile/caches/my-profile.ts deleted file mode 100644 index a0e68bb..0000000 --- a/platforms/market/src/features/profile/caches/my-profile.ts +++ /dev/null @@ -1,14 +0,0 @@ -import 'server-only'; - -import { cache } from 'react'; - -import { profileRepository } from '../repositories/profile'; -import type { CreatorProfilePayload } from '../repositories/profile'; - -/** - * The signed-in creator's own profile for this request, one request per render. 401 and 403 reach - * the caller (`readOnServer` turns them into login and no-access). - */ -export const getMyCreatorProfile = cache( - (): Promise => profileRepository.getMine(), -); diff --git a/platforms/market/src/features/profile/caches/server.ts b/platforms/market/src/features/profile/caches/server.ts deleted file mode 100644 index 7a8bfc4..0000000 --- a/platforms/market/src/features/profile/caches/server.ts +++ /dev/null @@ -1,3 +0,0 @@ -import 'server-only'; - -export { getMyCreatorProfile } from './my-profile'; diff --git a/platforms/market/src/features/subscription/caches/server.ts b/platforms/market/src/features/subscription/caches/server.ts deleted file mode 100644 index ee9ec5c..0000000 --- a/platforms/market/src/features/subscription/caches/server.ts +++ /dev/null @@ -1,4 +0,0 @@ -import 'server-only'; - -export { getSubscriptionDashboard } from './subscription-dashboard'; -export { getSubscriptionDetail } from './subscription-detail'; diff --git a/platforms/market/src/features/subscription/caches/subscription-dashboard.ts b/platforms/market/src/features/subscription/caches/subscription-dashboard.ts deleted file mode 100644 index 97db942..0000000 --- a/platforms/market/src/features/subscription/caches/subscription-dashboard.ts +++ /dev/null @@ -1,12 +0,0 @@ -import 'server-only'; - -import { cache } from 'react'; - -import { subscriptionRepository } from '../repositories/subscription'; -import type { SubscriptionDashboardPayload } from '../repositories/subscription'; - -/** The signed-in investor's اشتراک‌ها, once per render. Errors reach the page's `readOnServer`. */ -export const getSubscriptionDashboard = cache( - async (): Promise => - subscriptionRepository.getDashboard(), -); diff --git a/platforms/market/src/features/subscription/caches/subscription-detail.ts b/platforms/market/src/features/subscription/caches/subscription-detail.ts deleted file mode 100644 index e1c6b7d..0000000 --- a/platforms/market/src/features/subscription/caches/subscription-detail.ts +++ /dev/null @@ -1,12 +0,0 @@ -import 'server-only'; - -import { cache } from 'react'; - -import { subscriptionRepository } from '../repositories/subscription'; -import type { SubscriptionDetailPayload } from '../repositories/subscription'; - -/** One subscription of the signed-in investor, once per render; someone else's is a 404. */ -export const getSubscriptionDetail = cache( - async (id: string): Promise => - subscriptionRepository.getDetail(id), -); diff --git a/platforms/market/src/features/transaction/caches/payment-detail.ts b/platforms/market/src/features/transaction/caches/payment-detail.ts deleted file mode 100644 index 2e48462..0000000 --- a/platforms/market/src/features/transaction/caches/payment-detail.ts +++ /dev/null @@ -1,15 +0,0 @@ -import 'server-only'; - -import { cache } from 'react'; - -import { transactionRepository } from '../repositories/transaction'; -import type { TransactionDetailPayload } from '../repositories/transaction'; - -/** - * One payment of the signed-in investor (جزئیات تراکنش, and the U10 result after the bank return), - * once per render; someone else's is a 404. - */ -export const getPaymentDetail = cache( - async (id: string): Promise => - transactionRepository.getDetail(id), -); diff --git a/platforms/market/src/features/transaction/caches/server.ts b/platforms/market/src/features/transaction/caches/server.ts deleted file mode 100644 index fafdd72..0000000 --- a/platforms/market/src/features/transaction/caches/server.ts +++ /dev/null @@ -1,4 +0,0 @@ -import 'server-only'; - -export { getPaymentDetail } from './payment-detail'; -export { getTransactionsFirstPage } from './transactions-first-page'; diff --git a/platforms/market/src/features/transaction/caches/transactions-first-page.ts b/platforms/market/src/features/transaction/caches/transactions-first-page.ts deleted file mode 100644 index 7820034..0000000 --- a/platforms/market/src/features/transaction/caches/transactions-first-page.ts +++ /dev/null @@ -1,15 +0,0 @@ -import 'server-only'; - -import { cache } from 'react'; - -import { transactionRepository } from '../repositories/transaction'; -import type { - TransactionFilter, - TransactionPagePayload, -} from '../repositories/transaction'; - -/** Page 1 of the signed-in investor's history for one status tab, once per render. */ -export const getTransactionsFirstPage = cache( - async (status: TransactionFilter = 'all'): Promise => - transactionRepository.list({ status, page: 1 }), -); diff --git a/platforms/market/src/index.ts b/platforms/market/src/index.ts index dd329d1..032347d 100644 --- a/platforms/market/src/index.ts +++ b/platforms/market/src/index.ts @@ -16,8 +16,16 @@ export type { } from './app/error-boundaries'; export { mapApiErrorBody } from './app/http'; export type { ApiErrorEnvelope } from './app/http'; -export { CHANNEL_PREFIX, loginRoute, ROUTES } from './app/navigation'; -export { SESSION_COOKIES, SESSION_REFRESH_ENDPOINT } from './app/session'; +export { AuthGuard } from './app/guards/auth-guard'; +export type { AuthGuardProps } from './app/guards/auth-guard'; +export { GuestGuard } from './app/guards/guest-guard'; +export type { GuestGuardProps } from './app/guards/guest-guard'; +export { + CHANNEL_PREFIX, + loginRoute, + ROUTES, + safeReturnPath, +} from './app/navigation'; export { getEnv, setEnv } from './env'; export type { MarketEnv } from './env'; export { @@ -36,6 +44,7 @@ export { logout, registerCreator, registerInvestor, + restoreSession, } from './features/auth'; export type { AccountPayload, @@ -47,6 +56,7 @@ export type { RegistrationVerifiedPayload, SendOtpArgs, SessionPayload, + SessionStatePayload, UpdateAccountArgs, UserRole, UserStatus, @@ -236,3 +246,9 @@ export type { } from './features/overview'; export { creatorPaymentRepository, financeKeys } from './features/finance'; export type { CreatorPaymentPayload } from './features/finance'; +export { + useAuthStore, + useCurrentAccount, + useViewerStatus, +} from './stores/auth'; +export type { AuthState, Session, ViewerStatus } from './stores/auth'; diff --git a/platforms/market/src/server.ts b/platforms/market/src/server.ts index 0f583c7..21a7ef8 100644 --- a/platforms/market/src/server.ts +++ b/platforms/market/src/server.ts @@ -1,46 +1,12 @@ import 'server-only'; // Public server-only API, exposed as the `/server` subpath. index.ts never imports this file. +// Server reads carry no session: only what is the same for every visitor is read here. export { readOnServer } from './app/error-boundaries/server'; -export type { - ReadOnServerOptions, - ServerRead, -} from './app/error-boundaries/server'; -export { refreshSessionInProxy } from './app/session/server'; -export type { ProxySessionOptions } from './app/session/server'; -export { getSessionAccount } from './features/auth/caches/server'; -export { - redirectIfSignedIn, - requireAccount, -} from './app/guards/auth-guard/server'; -export type { RequireAccountOptions } from './app/guards/auth-guard/server'; -export { requireRole } from './app/guards/role-guard/server'; -export type { - RequireRoleOptions, - RoleCheck, -} from './app/guards/role-guard/server'; -export { getMyCreatorProfile } from './features/profile/caches/server'; +export type { ServerRead } from './app/error-boundaries/server'; export { getPublicCreator, getPublicTiers, } from './features/channel/caches/server'; -export { getFollowStatus } from './features/follow/caches/server'; -export { - getNotificationInbox, - getUnreadNotificationCount, -} from './features/notification/caches/server'; export { getCreatorPosts, getPost } from './features/post/caches/server'; export { getPredictionStats } from './features/prediction/caches/server'; -export { getFeed } from './features/feed/caches/server'; -export { getPricingForm } from './features/pricing/caches/server'; -export { getCheckoutScreen } from './features/checkout/caches/server'; -export { - getSubscriptionDashboard, - getSubscriptionDetail, -} from './features/subscription/caches/server'; -export { - getPaymentDetail, - getTransactionsFirstPage, -} from './features/transaction/caches/server'; -export { getCreatorDashboard } from './features/overview/caches/server'; -export { getCreatorPayments } from './features/finance/caches/server'; diff --git a/platforms/market/src/stores/auth/.gitkeep b/platforms/market/src/stores/auth/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/platforms/market/src/stores/auth/auth-store.ts b/platforms/market/src/stores/auth/auth-store.ts new file mode 100644 index 0000000..d430416 --- /dev/null +++ b/platforms/market/src/stores/auth/auth-store.ts @@ -0,0 +1,30 @@ +import { create } from 'zustand'; +import { immer } from 'zustand/middleware/immer'; + +import type { AuthState } from './types'; + +/** + * Who the viewer is, in the browser only. It starts `unknown` on the server and in the first + * browser render, so auth-dependent parts show their skeleton until `restoreSession` has read the + * session; `unknown` never reads as a guest. Never written during a server render. + */ +export const useAuthStore = create()( + immer((set) => ({ + status: 'unknown', + session: null, + setSession: (session) => + set((state) => { + state.status = 'member'; + state.session = session; + }), + clearSession: () => + set((state) => { + state.status = 'guest'; + state.session = null; + }), + })), +); + +export const useViewerStatus = () => useAuthStore((state) => state.status); +export const useCurrentAccount = () => + useAuthStore((state) => state.session?.account ?? null); diff --git a/platforms/market/src/stores/auth/index.ts b/platforms/market/src/stores/auth/index.ts new file mode 100644 index 0000000..e73eaae --- /dev/null +++ b/platforms/market/src/stores/auth/index.ts @@ -0,0 +1,2 @@ +export { useAuthStore, useCurrentAccount, useViewerStatus } from './auth-store'; +export type { AuthState, Session, ViewerStatus } from './types'; diff --git a/platforms/market/src/stores/auth/types.ts b/platforms/market/src/stores/auth/types.ts new file mode 100644 index 0000000..5389711 --- /dev/null +++ b/platforms/market/src/stores/auth/types.ts @@ -0,0 +1,13 @@ +import type { AccountPayload } from '../../features/auth'; + +/** unknown: not read yet (the server render and the first browser render). */ +export type ViewerStatus = 'unknown' | 'guest' | 'member'; + +export type Session = { account: AccountPayload }; + +export type AuthState = { + status: ViewerStatus; + session: Session | null; + setSession: (session: Session) => void; + clearSession: () => void; +};