refactor(market,apps): drop the session proxy and restore auth in the browser
The server render no longer depends on auth: it reads no session and forwards only FORWARDED_COOKIES (none today), so every visitor of a URL gets the same HTML and the Next.js proxy is no longer needed. - Remove proxy.ts from bull and bear, the app/session module, the server auth and role guards, and the server caches that read the viewer's own data. Public caches stay: channel, post, prediction stats. - Add an auth store (status unknown | guest | member) filled by the restoreSession action, which reads GET /auth/session once per load from the AppShell's useSession hook. - Login and register actions set the store, logout clears it; the AppShell clears the query cache on auth.logout. No router.refresh. - Add client AuthGuard (fallback, optional role) and GuestGuard, with safeReturnPath limiting post-login redirects to same-site paths. - readOnServer no longer redirects on 401. - The browser HTTP client refreshes against AUTH_ENDPOINTS.refresh. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
9de000f3d2
commit
aafac927bf
|
|
@ -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' }),
|
||||
},
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
|
|
|
|||
|
|
@ -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<string> = new Set<string>([]);
|
||||
|
|
@ -1 +1,2 @@
|
|||
export { API_VERSION_PATH } from './api';
|
||||
export { FORWARDED_COOKIES } from './cookies';
|
||||
|
|
|
|||
|
|
@ -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]+$).*)'],
|
||||
};
|
||||
|
|
@ -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' }),
|
||||
},
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
|
|
|
|||
|
|
@ -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<string> = new Set<string>([]);
|
||||
|
|
@ -1 +1,2 @@
|
|||
export { API_VERSION_PATH } from './api';
|
||||
export { FORWARDED_COOKIES } from './cookies';
|
||||
|
|
|
|||
|
|
@ -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]+$).*)'],
|
||||
};
|
||||
|
|
@ -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 (
|
||||
<QueryClientProvider client={queryClient}>
|
||||
|
|
|
|||
|
|
@ -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]);
|
||||
}
|
||||
|
|
@ -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]);
|
||||
}
|
||||
|
|
@ -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<T>(
|
||||
read: () => Promise<T>,
|
||||
{ returnTo }: ReadOnServerOptions = {},
|
||||
): Promise<ServerRead<T>> {
|
||||
try {
|
||||
return { status: 'ok', data: await read() };
|
||||
|
|
@ -24,9 +20,6 @@ export async function readOnServer<T>(
|
|||
if (outcome === 'not-found' || outcome === 'no-access') {
|
||||
return { status: outcome };
|
||||
}
|
||||
if (returnTo && isHttpError(error) && error.status === 401) {
|
||||
redirect(loginRoute(returnTo));
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
import 'server-only';
|
||||
|
||||
export { readOnServer } from './read-on-server';
|
||||
export type { ReadOnServerOptions, ServerRead } from './types';
|
||||
export type { ServerRead } from './types';
|
||||
|
|
|
|||
|
|
@ -2,8 +2,3 @@
|
|||
export type ServerRead<T> =
|
||||
| { 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;
|
||||
};
|
||||
|
|
|
|||
|
|
@ -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';
|
||||
|
|
|
|||
|
|
@ -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 <StatusEmptyState variant="no-access" size="page" />;
|
||||
}
|
||||
return children;
|
||||
}
|
||||
|
|
@ -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<AccountPayload> {
|
||||
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<void> {
|
||||
if (await getSessionAccount()) redirect(to);
|
||||
}
|
||||
|
|
@ -0,0 +1,2 @@
|
|||
export { AuthGuard } from './AuthGuard';
|
||||
export type { AuthGuardProps } from './types';
|
||||
|
|
@ -1,4 +0,0 @@
|
|||
import 'server-only';
|
||||
|
||||
export { redirectIfSignedIn, requireAccount } from './auth-guard';
|
||||
export type { RequireAccountOptions } from './types';
|
||||
|
|
@ -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;
|
||||
};
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
}
|
||||
|
|
@ -0,0 +1,2 @@
|
|||
export { GuestGuard } from './GuestGuard';
|
||||
export type { GuestGuardProps } from './types';
|
||||
|
|
@ -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;
|
||||
};
|
||||
|
|
@ -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<RoleCheck> {
|
||||
const account = await requireAccount({ returnTo });
|
||||
return account.role === role
|
||||
? { status: 'ok', account }
|
||||
: { status: 'no-access' };
|
||||
}
|
||||
|
|
@ -1,4 +0,0 @@
|
|||
import 'server-only';
|
||||
|
||||
export { requireRole } from './role-guard';
|
||||
export type { RequireRoleOptions, RoleCheck } from './types';
|
||||
|
|
@ -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' };
|
||||
|
|
@ -1,2 +1,3 @@
|
|||
export { CHANNEL_PREFIX } from './constants';
|
||||
export { loginRoute, ROUTES } from './navigation';
|
||||
export { safeReturnPath } from './return-path';
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
}
|
||||
|
|
@ -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;
|
||||
|
|
@ -1 +0,0 @@
|
|||
export { SESSION_COOKIES, SESSION_REFRESH_ENDPOINT } from './constants';
|
||||
|
|
@ -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<NextResponse> {
|
||||
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<RefreshResponseDto>({
|
||||
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();
|
||||
}
|
||||
}
|
||||
|
|
@ -1,4 +0,0 @@
|
|||
import 'server-only';
|
||||
|
||||
export { refreshSessionInProxy } from './refresh-in-proxy';
|
||||
export type { ProxySessionOptions } from './types';
|
||||
|
|
@ -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 };
|
||||
|
|
@ -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<SessionPayload> {
|
||||
const session = await authRepository.verifyLoginOtp(args);
|
||||
useAuthStore.getState().setSession({ account: session.account });
|
||||
if (emit) {
|
||||
eventEmitter.emit(AUTH_EVENTS.login, {
|
||||
userId: session.account.id,
|
||||
|
|
|
|||
|
|
@ -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';
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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<CreatorRegisteredPayload> {
|
||||
const registration = await authRepository.registerCreator(args);
|
||||
useAuthStore.getState().setSession({ account: registration.account });
|
||||
if (emit) {
|
||||
eventEmitter.emit(AUTH_EVENTS.register, {
|
||||
userId: registration.account.id,
|
||||
|
|
|
|||
|
|
@ -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<SessionPayload> {
|
||||
const session = await authRepository.registerInvestor(args);
|
||||
useAuthStore.getState().setSession({ account: session.account });
|
||||
if (emit) {
|
||||
eventEmitter.emit(AUTH_EVENTS.register, {
|
||||
userId: session.account.id,
|
||||
|
|
|
|||
|
|
@ -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<ViewerStatus> {
|
||||
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;
|
||||
}
|
||||
|
|
@ -0,0 +1 @@
|
|||
export { restoreSession } from './actions';
|
||||
|
|
@ -1,3 +0,0 @@
|
|||
import 'server-only';
|
||||
|
||||
export { getSessionAccount } from './session-account';
|
||||
|
|
@ -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<AccountPayload | null> => {
|
||||
try {
|
||||
return await accountRepository.getCurrent();
|
||||
} catch (error) {
|
||||
if (isHttpError(error) && error.status === 401) return null;
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
);
|
||||
|
|
@ -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',
|
||||
|
|
|
|||
|
|
@ -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';
|
||||
|
|
|
|||
|
|
@ -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<SessionStatePayload> {
|
||||
const response = await authHttp.get<SessionStateResponseDto>(
|
||||
AUTH_ENDPOINTS.session,
|
||||
{ signal },
|
||||
);
|
||||
return toSessionStatePayload(response);
|
||||
},
|
||||
|
||||
/** Revokes the session and clears its cookies; succeeds even without one. */
|
||||
async logout(): Promise<void> {
|
||||
await authHttp.post(AUTH_ENDPOINTS.logout, undefined, {
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
|
||||
|
|
|
|||
|
|
@ -8,5 +8,6 @@ export type {
|
|||
RegistrationVerifiedPayload,
|
||||
SendOtpArgs,
|
||||
SessionPayload,
|
||||
SessionStatePayload,
|
||||
VerifyOtpArgs,
|
||||
} from './types';
|
||||
|
|
|
|||
|
|
@ -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 {
|
||||
|
|
|
|||
|
|
@ -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 };
|
||||
|
|
|
|||
|
|
@ -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 };
|
||||
|
|
|
|||
|
|
@ -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<CheckoutPayload> =>
|
||||
checkoutRepository.getScreen(creatorId),
|
||||
);
|
||||
|
|
@ -1,3 +0,0 @@
|
|||
import 'server-only';
|
||||
|
||||
export { getCheckoutScreen } from './checkout-screen';
|
||||
|
|
@ -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<FeedPayload> =>
|
||||
feedRepository.list({ page: 1, limit: FEED_PAGE_LIMIT }),
|
||||
);
|
||||
|
|
@ -1,3 +0,0 @@
|
|||
import 'server-only';
|
||||
|
||||
export { getFeed } from './feed';
|
||||
|
|
@ -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<CreatorPaymentPayload[]> => creatorPaymentRepository.list(),
|
||||
);
|
||||
|
|
@ -1,3 +0,0 @@
|
|||
import 'server-only';
|
||||
|
||||
export { getCreatorPayments } from './creator-payments';
|
||||
|
|
@ -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<FollowStatusPayload> =>
|
||||
followRepository.getStatus({ creatorId }),
|
||||
);
|
||||
|
|
@ -1,3 +0,0 @@
|
|||
import 'server-only';
|
||||
|
||||
export { getFollowStatus } from './follow-status';
|
||||
|
|
@ -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<InboxPayload> => notificationRepository.listInbox(),
|
||||
);
|
||||
|
|
@ -1,4 +0,0 @@
|
|||
import 'server-only';
|
||||
|
||||
export { getNotificationInbox } from './inbox';
|
||||
export { getUnreadNotificationCount } from './unread-count';
|
||||
|
|
@ -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<UnreadCountPayload> => notificationRepository.getUnreadCount(),
|
||||
);
|
||||
|
|
@ -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<CreatorDashboardPayload> =>
|
||||
creatorDashboardRepository.get(),
|
||||
);
|
||||
|
|
@ -1,3 +0,0 @@
|
|||
import 'server-only';
|
||||
|
||||
export { getCreatorDashboard } from './creator-dashboard';
|
||||
|
|
@ -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<PricingFormPayload> => pricingRepository.getForm(),
|
||||
);
|
||||
|
|
@ -1,3 +0,0 @@
|
|||
import 'server-only';
|
||||
|
||||
export { getPricingForm } from './pricing-form';
|
||||
|
|
@ -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<CreatorProfilePayload> => profileRepository.getMine(),
|
||||
);
|
||||
|
|
@ -1,3 +0,0 @@
|
|||
import 'server-only';
|
||||
|
||||
export { getMyCreatorProfile } from './my-profile';
|
||||
|
|
@ -1,4 +0,0 @@
|
|||
import 'server-only';
|
||||
|
||||
export { getSubscriptionDashboard } from './subscription-dashboard';
|
||||
export { getSubscriptionDetail } from './subscription-detail';
|
||||
|
|
@ -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<SubscriptionDashboardPayload> =>
|
||||
subscriptionRepository.getDashboard(),
|
||||
);
|
||||
|
|
@ -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<SubscriptionDetailPayload> =>
|
||||
subscriptionRepository.getDetail(id),
|
||||
);
|
||||
|
|
@ -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<TransactionDetailPayload> =>
|
||||
transactionRepository.getDetail(id),
|
||||
);
|
||||
|
|
@ -1,4 +0,0 @@
|
|||
import 'server-only';
|
||||
|
||||
export { getPaymentDetail } from './payment-detail';
|
||||
export { getTransactionsFirstPage } from './transactions-first-page';
|
||||
|
|
@ -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<TransactionPagePayload> =>
|
||||
transactionRepository.list({ status, page: 1 }),
|
||||
);
|
||||
|
|
@ -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';
|
||||
|
|
|
|||
|
|
@ -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';
|
||||
|
|
|
|||
|
|
@ -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<AuthState>()(
|
||||
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);
|
||||
|
|
@ -0,0 +1,2 @@
|
|||
export { useAuthStore, useCurrentAccount, useViewerStatus } from './auth-store';
|
||||
export type { AuthState, Session, ViewerStatus } from './types';
|
||||
|
|
@ -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;
|
||||
};
|
||||
Loading…
Reference in New Issue