153 lines
6.4 KiB
TypeScript
153 lines
6.4 KiB
TypeScript
import { randomUUID } from "node:crypto";
|
|
|
|
import { useActionData, useLoaderData, useNavigation } from "react-router";
|
|
import { ActionFunction, LoaderFunctionArgs, redirect } from "react-router";
|
|
import { CreateWorkspacePage } from "~/components/screens/auth/CreateWorkspacePage";
|
|
import { getMyTenants, TenantSimple, TenantSlugCollisionError } from "~/utils/db/tenants.db.server";
|
|
import { getUser } from "~/utils/db/users.db.server";
|
|
import { getUserInfo, validateCSRFToken } from "~/utils/session.server";
|
|
import { TenantsApi } from "~/utils/api/.server/TenantsApi";
|
|
import { useRootData } from "~/utils/data/useRootData";
|
|
import { withMetrics } from "~/lib/metrics/ssr";
|
|
import { appPath } from "~/utils/app/CanonicalUrlUtils";
|
|
import { getTranslations } from "~/locale/i18next.server";
|
|
import { CatalogError } from "@hivegrid/foundation";
|
|
import { checkAuthRateLimit } from "~/services/auth/auth-rate-limit.server";
|
|
import { isExactOwnedTenantCreationReplay } from "~/domain/tenant-bootstrap/tenantBootstrapService.server";
|
|
|
|
type LoaderData = {
|
|
myTenants: TenantSimple[];
|
|
creationRequestKey: string;
|
|
};
|
|
|
|
const CREATION_REQUEST_KEY_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
|
|
const WORKSPACE_CREATION_RATE_LIMIT = 3;
|
|
const WORKSPACE_CREATION_RATE_WINDOW_MS = 24 * 60 * 60 * 1000;
|
|
const WORKSPACE_CREATION_ATTEMPT_RATE_LIMIT = 30;
|
|
const WORKSPACE_CREATION_ATTEMPT_RATE_WINDOW_MS = 15 * 60 * 1000;
|
|
const WORKSPACE_REPLAY_RATE_LIMIT = 20;
|
|
const WORKSPACE_REPLAY_RATE_WINDOW_MS = 15 * 60 * 1000;
|
|
|
|
export const loader = withMetrics("new-account", async ({ request }: LoaderFunctionArgs) => {
|
|
const userInfo = await getUserInfo(request);
|
|
const user = await getUser(userInfo.userId);
|
|
if (!user) {
|
|
throw redirect(`/login`);
|
|
}
|
|
const url = new URL(request.url);
|
|
const requestedCreationKey = url.searchParams.get("creationRequestKey") ?? "";
|
|
if (!CREATION_REQUEST_KEY_PATTERN.test(requestedCreationKey)) {
|
|
url.searchParams.set("creationRequestKey", randomUUID());
|
|
throw redirect(`${url.pathname}${url.search}`);
|
|
}
|
|
const myTenants = await getMyTenants(userInfo.userId);
|
|
const data: LoaderData = {
|
|
myTenants,
|
|
creationRequestKey: requestedCreationKey,
|
|
};
|
|
return data;
|
|
});
|
|
|
|
export function newAccountDashboardPath(tenantSlug: string) {
|
|
return appPath({ tenantSlug, path: "dashboard", mode: "host-aware" });
|
|
}
|
|
|
|
type ActionData = {
|
|
error?: string;
|
|
creationRequestKey?: string;
|
|
};
|
|
export const action: ActionFunction = async ({ request }) => {
|
|
const { t } = await getTranslations(request);
|
|
let creationRequestKey: string | undefined;
|
|
try {
|
|
await validateCSRFToken(request);
|
|
const form = await request.formData();
|
|
const name = form.get("name")?.toString().trim() ?? "";
|
|
const slug = form.get("slug")?.toString();
|
|
const submittedCreationRequestKey = form.get("creationRequestKey")?.toString() ?? "";
|
|
if (!CREATION_REQUEST_KEY_PATTERN.test(submittedCreationRequestKey)) {
|
|
return Response.json({ error: t("app.tenants.create.errors.invalidRequest") }, { status: 400 });
|
|
}
|
|
creationRequestKey = submittedCreationRequestKey;
|
|
if (!name) {
|
|
return Response.json({ error: t("app.tenants.create.errors.nameRequired"), creationRequestKey }, { status: 400 });
|
|
}
|
|
const userInfo = await getUserInfo(request);
|
|
const attemptRateLimit = await checkAuthRateLimit({
|
|
request,
|
|
action: "workspace-create-attempt",
|
|
identifier: userInfo.userId,
|
|
limit: WORKSPACE_CREATION_ATTEMPT_RATE_LIMIT,
|
|
windowMs: WORKSPACE_CREATION_ATTEMPT_RATE_WINDOW_MS,
|
|
});
|
|
if (!attemptRateLimit.allowed) {
|
|
return Response.json(
|
|
{ error: t("app.tenants.create.errors.tooManyRequests"), creationRequestKey },
|
|
{
|
|
status: 429,
|
|
headers: {
|
|
"Cache-Control": "no-store",
|
|
"Retry-After": String(attemptRateLimit.retryAfterSeconds),
|
|
},
|
|
}
|
|
);
|
|
}
|
|
const exactReplay = await isExactOwnedTenantCreationReplay({
|
|
userId: userInfo.userId,
|
|
name,
|
|
slug,
|
|
creationRequestKey,
|
|
});
|
|
const rateLimit = await checkAuthRateLimit({
|
|
request,
|
|
action: exactReplay ? "workspace-create-replay" : "workspace-create",
|
|
identifier: userInfo.userId,
|
|
limit: exactReplay ? WORKSPACE_REPLAY_RATE_LIMIT : WORKSPACE_CREATION_RATE_LIMIT,
|
|
windowMs: exactReplay ? WORKSPACE_REPLAY_RATE_WINDOW_MS : WORKSPACE_CREATION_RATE_WINDOW_MS,
|
|
});
|
|
if (!rateLimit.allowed) {
|
|
return Response.json(
|
|
{ error: t("app.tenants.create.errors.tooManyRequests"), creationRequestKey },
|
|
{
|
|
status: 429,
|
|
headers: {
|
|
"Cache-Control": "no-store",
|
|
"Retry-After": String(rateLimit.retryAfterSeconds),
|
|
},
|
|
}
|
|
);
|
|
}
|
|
const { tenant } = await TenantsApi.create({ request, name, slug, creationRequestKey });
|
|
return redirect(newAccountDashboardPath(tenant.slug));
|
|
} catch (error: unknown) {
|
|
if (error instanceof TenantSlugCollisionError) {
|
|
return Response.json({ error: t("app.tenants.create.errors.slugTaken"), ...(creationRequestKey ? { creationRequestKey } : {}) }, { status: 409 });
|
|
}
|
|
if (error instanceof CatalogError) {
|
|
return Response.json({ error: t(error.i18nKey), ...(creationRequestKey ? { creationRequestKey } : {}) }, { status: error.status });
|
|
}
|
|
return Response.json({ error: t("app.tenants.create.errors.failed"), ...(creationRequestKey ? { creationRequestKey } : {}) }, { status: 400 });
|
|
}
|
|
};
|
|
|
|
// Interim-UI (AD-28): renders the ~/ui preview screen behind the stable loader/action boundary;
|
|
// final Subframe optics land as a tracked design-nachzug once David's D-P2 delta ships.
|
|
export default function AppNewAccountRoute() {
|
|
const { myTenants, creationRequestKey: loaderCreationRequestKey } = useLoaderData<LoaderData>();
|
|
const actionData = useActionData<ActionData>();
|
|
const navigation = useNavigation();
|
|
const { csrf } = useRootData();
|
|
const creationRequestKey = actionData?.creationRequestKey ?? loaderCreationRequestKey;
|
|
// Back target: return to the tenant picker when the user already has workspaces, else login.
|
|
const backHref = myTenants.length > 0 ? "/select-tenant" : "/login";
|
|
return (
|
|
<CreateWorkspacePage
|
|
csrf={csrf ?? ""}
|
|
creationRequestKey={creationRequestKey}
|
|
error={navigation.state === "idle" ? actionData?.error : undefined}
|
|
isSubmitting={navigation.state === "submitting"}
|
|
backHref={backHref}
|
|
/>
|
|
);
|
|
}
|