Reorganize repo structure and standards references
This commit is contained in:
1 parent
3cb93a81be
commit
be2054274d
5885 files changed
+2588
-195
No files matched your search
@@ -0,0 +1,18 @@
|
||||
import { Colors } from "~/application/enums/shared/Colors";
|
||||
|
||||
function getMethodColor(method: string) {
|
||||
if (method === "POST") {
|
||||
return Colors.GREEN;
|
||||
} else if (method === "GET") {
|
||||
return Colors.BLUE;
|
||||
} else if (method === "PUT") {
|
||||
return Colors.ORANGE;
|
||||
} else if (method === "DELETE") {
|
||||
return Colors.RED;
|
||||
}
|
||||
return Colors.GRAY;
|
||||
}
|
||||
|
||||
export default {
|
||||
getMethodColor,
|
||||
};
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
import { subscriptionRequiredCheckoutPath } from "./SubscriptionUrlUtils";
|
||||
|
||||
export function appTenantSubscriptionRequiredPath(params: { tenant?: string }) {
|
||||
return subscriptionRequiredCheckoutPath(params.tenant ?? "");
|
||||
}
|
||||
|
||||
export function appTenantPlanRequiredPath(params: { tenant?: string }) {
|
||||
return `/plan-required/${encodeURIComponent(params.tenant ?? "")}`;
|
||||
}
|
||||
|
||||
export function appTenantDeactivatedPath(params: { tenant?: string }) {
|
||||
return `/deactivated/${encodeURIComponent(params.tenant ?? "")}`;
|
||||
}
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
import { describe, expect, test } from "vitest";
|
||||
import packageCanonicalUrlUtils, { adminPath as packageAdminPath, appPath as packageAppPath } from "@toolctrl/url";
|
||||
import CanonicalUrlUtils, { adminPath, apiPath, appPath, appUrl, type AppPathOptions } from "./CanonicalUrlUtils";
|
||||
|
||||
describe("CanonicalUrlUtils compatibility shim", () => {
|
||||
test("re-exports named helpers from @toolctrl/url", () => {
|
||||
const appOptions: AppPathOptions = { tenantSlug: "acme/team", path: "/settings?tab=billing#plan", mode: "host-aware" };
|
||||
|
||||
expect(appPath(appOptions)).toBe(packageAppPath(appOptions));
|
||||
expect(adminPath("/users", { mode: "host-aware" })).toBe(packageAdminPath("/users", { mode: "host-aware" }));
|
||||
expect(apiPath("events", { mode: "host-aware", version: "v1" })).toBe(packageCanonicalUrlUtils.apiPath("events", { mode: "host-aware", version: "v1" }));
|
||||
expect(appUrl({ rootDomain: "localhost:3000", protocol: "http", appSubdomain: "app", tenantSlug: "acme", path: "dashboard", mode: "host-aware" })).toBe(
|
||||
packageCanonicalUrlUtils.appUrl({ rootDomain: "localhost:3000", protocol: "http", appSubdomain: "app", tenantSlug: "acme", path: "dashboard", mode: "host-aware" })
|
||||
);
|
||||
});
|
||||
|
||||
test("preserves the default export object for existing app imports", () => {
|
||||
expect(CanonicalUrlUtils).toBe(packageCanonicalUrlUtils);
|
||||
expect(CanonicalUrlUtils.appPath({ tenantSlug: "acme", path: "dashboard" })).toBe(packageCanonicalUrlUtils.appPath({ tenantSlug: "acme", path: "dashboard" }));
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,23 @@
|
||||
export {
|
||||
adminPath,
|
||||
adminUrl,
|
||||
apiPath,
|
||||
apiUrl,
|
||||
appPath,
|
||||
appUrl,
|
||||
default,
|
||||
} from "@toolctrl/url";
|
||||
|
||||
export type {
|
||||
AbsoluteUrlOptions,
|
||||
AdminPathOptions,
|
||||
AdminUrlOptions,
|
||||
ApiPathOptions,
|
||||
ApiUrlOptions,
|
||||
ApiVersion,
|
||||
AppPathOptions,
|
||||
AppUrlOptions,
|
||||
CanonicalPathOptions,
|
||||
CanonicalUrlMode,
|
||||
PathInput,
|
||||
} from "@toolctrl/url";
|
||||
@@ -0,0 +1,32 @@
|
||||
import type { DomainRoutingConfig } from "@toolctrl/config";
|
||||
import { adminPath, appPath, type PathInput } from "./CanonicalUrlUtils";
|
||||
|
||||
export type PublicDomainRoutingConfig = Pick<DomainRoutingConfig, "protocol" | "webAppHost" | "adminAppHost" | "apiHost" | "appBaseDomain">;
|
||||
|
||||
function absoluteHostPath(host: string, path: string, protocol: DomainRoutingConfig["protocol"]) {
|
||||
return `${protocol}://${host}${path}`;
|
||||
}
|
||||
|
||||
export function absoluteAdminPath(routing: PublicDomainRoutingConfig | undefined, path?: PathInput) {
|
||||
const targetPath = adminPath(path, { mode: "host-aware" });
|
||||
return routing ? absoluteHostPath(routing.adminAppHost, targetPath, routing.protocol) : targetPath;
|
||||
}
|
||||
|
||||
export function absoluteAppPath(routing: PublicDomainRoutingConfig | undefined, tenantSlug: string, path?: PathInput) {
|
||||
const targetPath = appPath({ tenantSlug, path, mode: "host-aware" });
|
||||
return routing ? absoluteHostPath(routing.webAppHost, targetPath, routing.protocol) : targetPath;
|
||||
}
|
||||
|
||||
export function absoluteAppRootPath(routing: PublicDomainRoutingConfig | undefined) {
|
||||
return routing ? absoluteHostPath(routing.webAppHost, "/", routing.protocol) : "/";
|
||||
}
|
||||
|
||||
export function absolutePublicAppPath(routing: PublicDomainRoutingConfig | undefined, path: string) {
|
||||
const normalizedPath = path.startsWith("/") ? path : `/${path}`;
|
||||
const appRoot = absoluteAppRootPath(routing);
|
||||
return isAbsoluteHttpUrl(appRoot) ? new URL(normalizedPath, appRoot).toString() : normalizedPath;
|
||||
}
|
||||
|
||||
export function isAbsoluteHttpUrl(value: string) {
|
||||
return /^https?:\/\//i.test(value);
|
||||
}
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
import {describe, test, expect} from 'vitest'
|
||||
import { getStatChangePercentage, getStatChangeType } from "./DashboardUtils";
|
||||
import { StatChange } from "~/application/dtos/stats/StatChange";
|
||||
|
||||
describe("getStatChangePercentage", () => {
|
||||
test("returns 100 when total is less than or equal to zero", () => {
|
||||
expect(getStatChangePercentage(5, 0)).toBe(100);
|
||||
expect(getStatChangePercentage(5, -1)).toBe(100);
|
||||
});
|
||||
|
||||
test("returns the correct percentage when total is greater than zero", () => {
|
||||
expect(getStatChangePercentage(5, 10)).toBe(50);
|
||||
expect(getStatChangePercentage(1, 4)).toBe(25);
|
||||
expect(getStatChangePercentage(0, 5)).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("getStatChangeType", () => {
|
||||
test("returns StatChange.Equal when change is zero", () => {
|
||||
expect(getStatChangeType(0, 5)).toBe(StatChange.Equal);
|
||||
});
|
||||
|
||||
test("returns StatChange.Increase when change is positive", () => {
|
||||
expect(getStatChangeType(5, 10)).toBe(StatChange.Increase);
|
||||
expect(getStatChangeType(2, 1)).toBe(StatChange.Increase);
|
||||
expect(getStatChangeType(-2, -1)).toBe(StatChange.Increase);
|
||||
});
|
||||
|
||||
test("returns StatChange.Decrease when change is negative", () => {
|
||||
expect(getStatChangeType(-5, 10)).toBe(StatChange.Decrease);
|
||||
expect(getStatChangeType(-2, 2)).toBe(StatChange.Decrease);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,16 @@
|
||||
import { StatChange } from "~/application/dtos/stats/StatChange";
|
||||
|
||||
export function getStatChangePercentage(added: number, total: number): number {
|
||||
if (total <= 0) {
|
||||
return 100;
|
||||
}
|
||||
return Math.round((added * 100) / total);
|
||||
}
|
||||
|
||||
export function getStatChangeType(added: number, total: number): StatChange {
|
||||
const change = getStatChangePercentage(added, total);
|
||||
if (change === 0) {
|
||||
return StatChange.Equal;
|
||||
}
|
||||
return change > 0 ? StatChange.Increase : StatChange.Decrease;
|
||||
}
|
||||
+59
@@ -0,0 +1,59 @@
|
||||
import { describe, expect, test } from "vitest";
|
||||
import { isAdminSurface, isAppOrAdminSurface, isAppSurface } from "./HostAwareSurface";
|
||||
|
||||
const routing = {
|
||||
appBaseDomain: "example.test",
|
||||
webAppHost: "app.example.test",
|
||||
adminAppHost: "admin.example.test",
|
||||
apiHost: "api.example.test",
|
||||
protocol: "https",
|
||||
} as const;
|
||||
|
||||
describe("HostAwareSurface", () => {
|
||||
test("classifies canonical app and admin hosts by request origin", () => {
|
||||
expect(
|
||||
isAppSurface(
|
||||
{
|
||||
serverUrl: "https://app.example.test",
|
||||
publicBaseUrl: "https://example.test",
|
||||
routing,
|
||||
},
|
||||
"/acme/dashboard"
|
||||
)
|
||||
).toBe(true);
|
||||
|
||||
expect(
|
||||
isAdminSurface(
|
||||
{
|
||||
serverUrl: "https://admin.example.test",
|
||||
publicBaseUrl: "https://example.test",
|
||||
routing,
|
||||
},
|
||||
"/dashboard"
|
||||
)
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
test("keeps public routes on the web app host out of app chrome", () => {
|
||||
const input = {
|
||||
serverUrl: "https://app.example.test",
|
||||
publicBaseUrl: "https://example.test",
|
||||
routing,
|
||||
};
|
||||
|
||||
expect(isAppSurface(input, "/docs/getting-started")).toBe(false);
|
||||
expect(isAppOrAdminSurface(input, "/docs/getting-started")).toBe(false);
|
||||
expect(isAppSurface(input, "/acme/dashboard")).toBe(true);
|
||||
});
|
||||
|
||||
test("keeps admin host settings classified as admin chrome", () => {
|
||||
const input = {
|
||||
serverUrl: "https://admin.example.test",
|
||||
publicBaseUrl: "https://example.test",
|
||||
routing,
|
||||
};
|
||||
|
||||
expect(isAdminSurface(input, "/settings/profile")).toBe(true);
|
||||
expect(isAppOrAdminSurface(input, "/settings/profile")).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,38 @@
|
||||
import type { PublicDomainRoutingConfig } from "./CrossHostUrls";
|
||||
import { isPublicWebRoutePath } from "./PublicRouteSegments";
|
||||
|
||||
type SurfaceInput = {
|
||||
publicBaseUrl?: string;
|
||||
serverUrl?: string;
|
||||
routing?: PublicDomainRoutingConfig;
|
||||
};
|
||||
|
||||
function hostFromUrl(value?: string) {
|
||||
if (!value) {
|
||||
return undefined;
|
||||
}
|
||||
try {
|
||||
return new URL(value).host;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
function currentHost(input: SurfaceInput) {
|
||||
return hostFromUrl(input.serverUrl) ?? hostFromUrl(input.publicBaseUrl);
|
||||
}
|
||||
|
||||
export function isAdminSurface(input: SurfaceInput, pathname: string) {
|
||||
return currentHost(input) === input.routing?.adminAppHost;
|
||||
}
|
||||
|
||||
export function isAppSurface(input: SurfaceInput, pathname: string) {
|
||||
if (isPublicWebRoutePath(pathname)) {
|
||||
return false;
|
||||
}
|
||||
return currentHost(input) === input.routing?.webAppHost;
|
||||
}
|
||||
|
||||
export function isAppOrAdminSurface(input: SurfaceInput, pathname: string) {
|
||||
return isAppSurface(input, pathname) || isAdminSurface(input, pathname);
|
||||
}
|
||||
+321
@@ -0,0 +1,321 @@
|
||||
import { describe, expect, test } from "vitest";
|
||||
import {
|
||||
getCanonicalHostRedirectUrl,
|
||||
getHostAwareInternalPath,
|
||||
getHostAwareInternalUrlPath,
|
||||
getHostRoutingContext,
|
||||
getHostRoutingContextFromRequest,
|
||||
} from "./HostRouting.server";
|
||||
import type { DomainRoutingConfig } from "@toolctrl/config";
|
||||
|
||||
const config: DomainRoutingConfig = {
|
||||
appBaseDomain: "localhost:3000",
|
||||
webAppHost: "app.localhost:3000",
|
||||
adminAppHost: "admin.localhost:3000",
|
||||
apiHost: "api.localhost:3000",
|
||||
protocol: "http",
|
||||
};
|
||||
|
||||
const env = {
|
||||
APP_BASE_DOMAIN: config.appBaseDomain,
|
||||
WEB_APP_HOST: config.webAppHost,
|
||||
ADMIN_APP_HOST: config.adminAppHost,
|
||||
API_HOST: config.apiHost,
|
||||
APP_PROTOCOL: config.protocol,
|
||||
};
|
||||
|
||||
describe("HostRouting", () => {
|
||||
test("classifies canonical local hosts", () => {
|
||||
expect(getHostRoutingContext("app.localhost:3000", config)).toBe("app");
|
||||
expect(getHostRoutingContext("admin.localhost:3000", config)).toBe("admin");
|
||||
expect(getHostRoutingContext("api.localhost:3000", config)).toBe("api");
|
||||
expect(getHostRoutingContext("localhost:3000", config)).toBe("root");
|
||||
});
|
||||
|
||||
test("maps host-aware app paths to canonical internal route paths", () => {
|
||||
expect(getHostAwareInternalPath("/acme/dashboard", "app")).toBe("/acme/dashboard");
|
||||
expect(getHostAwareInternalPath("/", "app")).toBe("/app");
|
||||
});
|
||||
|
||||
test("maps app host request URLs without adding removed prefixes", () => {
|
||||
expect(getHostAwareInternalUrlPath("http://app.localhost:3000/acme/dashboard?tab=activity#events", config)).toBe("/acme/dashboard?tab=activity#events");
|
||||
expect(getHostAwareInternalUrlPath("http://app.localhost:3000/app/acme/dashboard?tab=activity#events", config)).toBe(
|
||||
"/acme/dashboard?tab=activity#events"
|
||||
);
|
||||
expect(getHostAwareInternalUrlPath("http://app.localhost:3000/app/acme/dashboard.data?_routes=routes%2Fapp.%24tenant%2Fdashboard", config)).toBe(
|
||||
"/acme/dashboard.data?_routes=routes%2Fapp.%24tenant%2Fdashboard"
|
||||
);
|
||||
});
|
||||
|
||||
test("keeps public auth routes on app and admin hosts from becoming tenant routes", () => {
|
||||
expect(getHostAwareInternalUrlPath("http://app.localhost:3000/login?redirectTo=%2Facme%2Fdashboard", config)).toBe(
|
||||
"/login?redirectTo=%2Facme%2Fdashboard"
|
||||
);
|
||||
expect(getHostAwareInternalUrlPath("http://app.localhost:3000/auth/magic-link", config)).toBe("/auth/magic-link");
|
||||
expect(getHostAwareInternalUrlPath("http://app.localhost:3000/plan-required/acme", config)).toBe("/plan-required/acme");
|
||||
expect(getHostAwareInternalUrlPath("http://app.localhost:3000/subscribe/acme?plan=pro", config)).toBe("/subscribe/acme?plan=pro");
|
||||
expect(getHostAwareInternalUrlPath("http://app.localhost:3000/new-account", config)).toBe("/new-account");
|
||||
expect(getHostAwareInternalUrlPath("http://app.localhost:3000/preferences", config)).toBe("/preferences");
|
||||
expect(getHostAwareInternalUrlPath("http://app.localhost:3000/onboarding/session_123", config)).toBe("/onboarding/session_123");
|
||||
expect(getHostAwareInternalUrlPath("http://app.localhost:3000/feature-disabled?feature=summary", config)).toBe("/feature-disabled?feature=summary");
|
||||
expect(getHostAwareInternalUrlPath("http://app.localhost:3000/postman_collection.json", config)).toBe("/postman_collection.json");
|
||||
expect(getHostAwareInternalUrlPath("http://app.localhost:3000/sitemap.xml", config)).toBe("/sitemap.xml");
|
||||
expect(getHostAwareInternalUrlPath("http://app.localhost:3000/docs/en", config)).toBe("/docs/en");
|
||||
expect(getHostAwareInternalUrlPath("http://app.localhost:3000/healthcheck", config)).toBe("/healthcheck");
|
||||
expect(getHostAwareInternalUrlPath("http://app.localhost:3000/healthz", config)).toBe("/healthz");
|
||||
expect(getHostAwareInternalUrlPath("http://app.localhost:3000/readyz", config)).toBe("/readyz");
|
||||
expect(getHostAwareInternalUrlPath("http://app.localhost:3000/swagger", config)).toBe("/swagger");
|
||||
expect(getHostAwareInternalUrlPath("http://app.localhost:3000/unauthorized/app.settings.members", config)).toBe("/unauthorized/app.settings.members");
|
||||
expect(getHostAwareInternalUrlPath("http://app.localhost:3000/404", config)).toBe("/404");
|
||||
expect(getHostAwareInternalUrlPath("http://admin.localhost:3000/login", config)).toBe("/login");
|
||||
expect(getHostAwareInternalUrlPath("http://admin.localhost:3000/preferences", config)).toBe("/preferences");
|
||||
expect(getHostAwareInternalUrlPath("http://admin.localhost:3000/onboarding/session_123", config)).toBe("/onboarding/session_123");
|
||||
expect(getHostAwareInternalUrlPath("http://admin.localhost:3000/feature-disabled?feature=summary", config)).toBe("/feature-disabled?feature=summary");
|
||||
expect(getHostAwareInternalUrlPath("http://admin.localhost:3000/postman_collection.json", config)).toBe("/postman_collection.json");
|
||||
expect(getHostAwareInternalUrlPath("http://admin.localhost:3000/sitemap.xml", config)).toBe("/sitemap.xml");
|
||||
});
|
||||
|
||||
test("keeps React Router manifest discovery on canonical hosts", () => {
|
||||
expect(getHostAwareInternalUrlPath("http://admin.localhost:3000/__manifest?paths=%2Fmfa-challenge&version=abc", config)).toBe(
|
||||
"/__manifest?paths=%2Fmfa-challenge&version=abc"
|
||||
);
|
||||
expect(getHostAwareInternalUrlPath("http://app.localhost:3000/__manifest?paths=%2Facme%2Fdashboard&version=abc", config)).toBe(
|
||||
"/__manifest?paths=%2Facme%2Fdashboard&version=abc"
|
||||
);
|
||||
});
|
||||
|
||||
test("keeps canonical admin host routes on the admin host", () => {
|
||||
expect(getHostAwareInternalUrlPath("http://admin.localhost:3000/dashboard?tab=users#active", config)).toBe("/dashboard?tab=users#active");
|
||||
expect(getHostAwareInternalUrlPath("http://admin.localhost:3000/dashboard.data?_routes=routes%2Fdashboard", config)).toBe(
|
||||
"/dashboard.data?_routes=routes%2Fdashboard"
|
||||
);
|
||||
expect(getHostAwareInternalUrlPath("http://admin.localhost:3000/mfa-challenge?redirectTo=%2Fdashboard", config)).toBe(
|
||||
"/mfa-challenge?redirectTo=%2Fdashboard"
|
||||
);
|
||||
expect(getHostAwareInternalUrlPath("http://admin.localhost:3000/mfa-challenge.data?_routes=routes%2Fmfa-challenge", config)).toBe(
|
||||
"/mfa-challenge.data?_routes=routes%2Fmfa-challenge"
|
||||
);
|
||||
expect(getHostAwareInternalUrlPath("http://admin.localhost:3000/internal/ai/chat", config)).toBe("/internal/ai/chat");
|
||||
});
|
||||
|
||||
test("maps host-aware admin and API paths", () => {
|
||||
expect(getHostAwareInternalPath("/accounts", "admin")).toBe("/accounts");
|
||||
expect(getHostAwareInternalPath("/users", "admin")).toBe("/users");
|
||||
expect(getHostAwareInternalPath("/health", "api")).toBe("/v1/health");
|
||||
expect(getHostAwareInternalPath("/healthz", "api")).toBe("/healthz");
|
||||
expect(getHostAwareInternalPath("/readyz", "api")).toBe("/readyz");
|
||||
expect(getHostAwareInternalPath("/v1/health", "api")).toBe("/v1/health");
|
||||
expect(getHostAwareInternalPath("/api/v1/health", "api")).toBe("/v1/health");
|
||||
});
|
||||
|
||||
test("maps API host request URLs without path double-prefixing and preserves suffixes", () => {
|
||||
expect(getHostAwareInternalUrlPath("http://api.localhost:3000/health?check=deep#status", config)).toBe(
|
||||
"/v1/health?check=deep#status"
|
||||
);
|
||||
expect(getHostAwareInternalUrlPath("http://api.localhost:3000/v1/health?check=deep#status", config)).toBe(
|
||||
"/v1/health?check=deep#status"
|
||||
);
|
||||
expect(getHostAwareInternalUrlPath("http://api.localhost:3000/api/v1/health?check=deep#status", config)).toBe(
|
||||
"/v1/health?check=deep#status"
|
||||
);
|
||||
});
|
||||
|
||||
test("maps admin host request URLs without double-prefixing", () => {
|
||||
expect(getHostAwareInternalUrlPath("http://admin.localhost:3000/accounts?tab=users#active", config)).toBe("/accounts?tab=users#active");
|
||||
expect(getHostAwareInternalUrlPath("http://admin.localhost:3000/users?tab=users#active", config)).toBe("/users?tab=users#active");
|
||||
});
|
||||
|
||||
test("uses forwarded host when deriving request context behind a proxy", () => {
|
||||
const request = new Request("http://localhost:3000/acme/dashboard", {
|
||||
headers: {
|
||||
host: "localhost:3000",
|
||||
"x-forwarded-host": " app.localhost:3000 , api.localhost:3000",
|
||||
},
|
||||
});
|
||||
|
||||
expect(getHostRoutingContextFromRequest(request, env)).toBe("app");
|
||||
});
|
||||
|
||||
test("uses forwarded host for internal URL mapping behind a proxy", () => {
|
||||
const request = new Request("http://localhost:3000/acme/dashboard?tab=activity#events", {
|
||||
headers: {
|
||||
host: "localhost:3000",
|
||||
"x-forwarded-host": " app.localhost:3000 , api.localhost:3000",
|
||||
},
|
||||
});
|
||||
|
||||
expect(getHostAwareInternalUrlPath(request, config)).toBe("/acme/dashboard?tab=activity#events");
|
||||
});
|
||||
|
||||
test("uses forwarded host for canonical redirects behind a proxy", () => {
|
||||
const request = new Request("http://localhost:3000/settings?tab=users#active", {
|
||||
headers: {
|
||||
host: "localhost:3000",
|
||||
"x-forwarded-host": " admin.localhost:3000 , app.localhost:3000",
|
||||
},
|
||||
});
|
||||
|
||||
expect(getCanonicalHostRedirectUrl(request, config)).toBeNull();
|
||||
});
|
||||
|
||||
test("uses the first forwarded host value for routing", () => {
|
||||
const request = new Request("http://localhost:3000/acme/dashboard?tab=activity#events", {
|
||||
headers: {
|
||||
host: "localhost:3000",
|
||||
"x-forwarded-host": " admin.localhost:3000 , api.localhost:3000",
|
||||
},
|
||||
});
|
||||
|
||||
expect(getHostRoutingContextFromRequest(request, env)).toBe("admin");
|
||||
expect(getCanonicalHostRedirectUrl(request, config)).toBe("http://app.localhost:3000/acme/dashboard?tab=activity#events");
|
||||
});
|
||||
|
||||
test("does not let forwarded host spoof an already canonical direct host", () => {
|
||||
const request = new Request("http://app.localhost:3000/dashboard?tab=activity#events", {
|
||||
headers: {
|
||||
host: "app.localhost:3000",
|
||||
"x-forwarded-host": "admin.localhost:3000",
|
||||
},
|
||||
});
|
||||
|
||||
expect(getHostRoutingContextFromRequest(request, env)).toBe("app");
|
||||
expect(getCanonicalHostRedirectUrl(request, config)).toBe("http://admin.localhost:3000/dashboard?tab=activity#events");
|
||||
});
|
||||
|
||||
test("redirects root-host canonical admin and tenant paths to their canonical hosts", () => {
|
||||
expect(getCanonicalHostRedirectUrl("http://localhost:3000/dashboard?tab=activity#events", config)).toBe(
|
||||
"http://admin.localhost:3000/dashboard?tab=activity#events"
|
||||
);
|
||||
expect(getCanonicalHostRedirectUrl("http://localhost:3000/accounts", config)).toBe("http://admin.localhost:3000/accounts");
|
||||
expect(getCanonicalHostRedirectUrl("http://localhost:3000/acme/dashboard?tab=activity#events", config)).toBe(
|
||||
"http://app.localhost:3000/acme/dashboard?tab=activity#events"
|
||||
);
|
||||
expect(getCanonicalHostRedirectUrl("http://localhost:3000/app/acme/dashboard?tab=activity#events", config)).toBe(
|
||||
"http://app.localhost:3000/acme/dashboard?tab=activity#events"
|
||||
);
|
||||
expect(getCanonicalHostRedirectUrl("http://localhost:3000/api/v1/health?check=deep#status", config)).toBe(
|
||||
"http://api.localhost:3000/v1/health?check=deep#status"
|
||||
);
|
||||
expect(getCanonicalHostRedirectUrl("http://localhost:3000/admin/settings?tab=users#active", config)).toBeNull();
|
||||
expect(getCanonicalHostRedirectUrl("http://localhost:3000/admin", config)).toBeNull();
|
||||
});
|
||||
|
||||
test("does not redirect a canonical route to itself when adminAppHost equals webAppHost (no 308 loop)", () => {
|
||||
// Single-Host-Staging / Fehlkonfig: adminAppHost == webAppHost. /dashboard (Admin-Surface) wuerde sonst
|
||||
// kanonisch auf denselben Host+Pfad umgeleitet -> 308-Endlosschleife. Der Self-Redirect-Guard liefert null.
|
||||
const sameHostConfig: DomainRoutingConfig = { ...config, adminAppHost: config.webAppHost };
|
||||
expect(getCanonicalHostRedirectUrl("http://app.localhost:3000/dashboard?tab=activity#events", sameHostConfig)).toBeNull();
|
||||
expect(getCanonicalHostRedirectUrl("http://app.localhost:3000/accounts/users", sameHostConfig)).toBeNull();
|
||||
// Getrennte Hosts (Prod) bleiben unveraendert -> Redirect feuert weiterhin.
|
||||
expect(getCanonicalHostRedirectUrl("http://app.localhost:3000/dashboard?tab=activity#events", config)).toBe(
|
||||
"http://admin.localhost:3000/dashboard?tab=activity#events"
|
||||
);
|
||||
});
|
||||
|
||||
test("redirects canonical route paths off the wrong canonical host", () => {
|
||||
expect(getCanonicalHostRedirectUrl("http://app.localhost:3000/dashboard?tab=activity#events", config)).toBe(
|
||||
"http://admin.localhost:3000/dashboard?tab=activity#events"
|
||||
);
|
||||
expect(getCanonicalHostRedirectUrl("http://app.localhost:3000/accounts/users?filter=active", config)).toBe(
|
||||
"http://admin.localhost:3000/accounts/users?filter=active"
|
||||
);
|
||||
expect(getCanonicalHostRedirectUrl("http://app.localhost:3000/internal/imports/dry-run", config)).toBeNull();
|
||||
expect(getCanonicalHostRedirectUrl("http://api.localhost:3000/dashboard?tab=activity#events", config)).toBe(
|
||||
"http://admin.localhost:3000/dashboard?tab=activity#events"
|
||||
);
|
||||
expect(getCanonicalHostRedirectUrl("http://admin.localhost:3000/acme/dashboard?tab=activity#events", config)).toBe(
|
||||
"http://app.localhost:3000/acme/dashboard?tab=activity#events"
|
||||
);
|
||||
expect(getCanonicalHostRedirectUrl("http://admin.localhost:3000/acme", config)).toBe("http://app.localhost:3000/acme");
|
||||
expect(getCanonicalHostRedirectUrl("http://api.localhost:3000/acme", config)).toBe("http://app.localhost:3000/acme");
|
||||
expect(getCanonicalHostRedirectUrl("http://api.localhost:3000/acme/dashboard?tab=activity#events", config)).toBe(
|
||||
"http://app.localhost:3000/acme/dashboard?tab=activity#events"
|
||||
);
|
||||
expect(getCanonicalHostRedirectUrl("http://admin.localhost:3000/acme/portals/customer", config)).toBeNull();
|
||||
expect(getCanonicalHostRedirectUrl("http://admin.localhost:3000/acme/widgets", config)).toBeNull();
|
||||
expect(getCanonicalHostRedirectUrl("http://admin.localhost:3000/acme/workflow-engine", config)).toBeNull();
|
||||
expect(getCanonicalHostRedirectUrl("http://admin.localhost:3000/acme/contact", config)).toBe("http://app.localhost:3000/acme/contact");
|
||||
expect(getCanonicalHostRedirectUrl("http://admin.localhost:3000/v1/users?cursor=next", config)).toBe("http://api.localhost:3000/v1/users?cursor=next");
|
||||
expect(getCanonicalHostRedirectUrl("http://app.localhost:3000/v1/users?cursor=next", config)).toBe("http://api.localhost:3000/v1/users?cursor=next");
|
||||
expect(getCanonicalHostRedirectUrl("http://app.localhost:3000/api/v1/health?check=deep#status", config)).toBe(
|
||||
"http://api.localhost:3000/v1/health?check=deep#status"
|
||||
);
|
||||
expect(getCanonicalHostRedirectUrl("http://app.localhost:3000/app/acme/dashboard?tab=activity#events", config)).toBe(
|
||||
"http://app.localhost:3000/acme/dashboard?tab=activity#events"
|
||||
);
|
||||
expect(getCanonicalHostRedirectUrl("http://admin.localhost:3000/api/v1/health?check=deep#status", config)).toBe(
|
||||
"http://api.localhost:3000/v1/health?check=deep#status"
|
||||
);
|
||||
expect(getCanonicalHostRedirectUrl("http://app.localhost:3000/admin/settings?tab=users#active", config)).toBeNull();
|
||||
});
|
||||
|
||||
test("redirects API host unversioned aliases to canonical v1 paths", () => {
|
||||
expect(getCanonicalHostRedirectUrl("http://api.localhost:3000/health?check=deep#status", config)).toBe(
|
||||
"http://api.localhost:3000/v1/health?check=deep#status"
|
||||
);
|
||||
expect(getCanonicalHostRedirectUrl("http://api.localhost:3000/accounts?cursor=next", config)).toBe(
|
||||
"http://api.localhost:3000/v1/accounts?cursor=next"
|
||||
);
|
||||
expect(getCanonicalHostRedirectUrl("http://api.localhost:3000/auth/login", config)).toBe("http://api.localhost:3000/v1/auth/login");
|
||||
expect(getCanonicalHostRedirectUrl("http://api.localhost:3000/analytics/events", config)).toBe("http://api.localhost:3000/v1/analytics/events");
|
||||
expect(getCanonicalHostRedirectUrl("http://api.localhost:3000/entities/contact/rows", config)).toBe(
|
||||
"http://api.localhost:3000/v1/entities/contact/rows"
|
||||
);
|
||||
expect(getCanonicalHostRedirectUrl("http://api.localhost:3000/api-keys/validate", config)).toBe(
|
||||
"http://api.localhost:3000/v1/api-keys/validate"
|
||||
);
|
||||
});
|
||||
|
||||
test("does not canonicalize unsupported API host aliases", () => {
|
||||
expect(getCanonicalHostRedirectUrl("http://api.localhost:3000/webhooks/inbound", config)).toBe("http://app.localhost:3000/webhooks/inbound");
|
||||
expect(getCanonicalHostRedirectUrl("http://api.localhost:3000/imports/dry-run", config)).toBe("http://app.localhost:3000/imports/dry-run");
|
||||
expect(getCanonicalHostRedirectUrl("http://api.localhost:3000/workflows/run/workflow_1", config)).toBeNull();
|
||||
});
|
||||
|
||||
test("keeps public root-host routes on the root host", () => {
|
||||
expect(getCanonicalHostRedirectUrl("http://localhost:3000/login?redirectTo=%2Facme%2Fdashboard", config)).toBeNull();
|
||||
});
|
||||
|
||||
test("redirects public web routes away from the API host", () => {
|
||||
expect(getCanonicalHostRedirectUrl("http://api.localhost:3000/login?redirectTo=%2Facme%2Fdashboard", config)).toBe(
|
||||
"http://app.localhost:3000/login?redirectTo=%2Facme%2Fdashboard"
|
||||
);
|
||||
expect(getCanonicalHostRedirectUrl("http://api.localhost:3000/healthcheck", config)).toBe("http://app.localhost:3000/healthcheck");
|
||||
});
|
||||
|
||||
test("redirects app-host reserved admin slugs instead of treating them as tenants", () => {
|
||||
expect(getCanonicalHostRedirectUrl("http://app.localhost:3000/crm/dashboard", config)).toBeNull();
|
||||
expect(getCanonicalHostRedirectUrl("http://app.localhost:3000/accounts/users", config)).toBe("http://admin.localhost:3000/accounts/users");
|
||||
});
|
||||
|
||||
test("does not canonicalize disabled plugin route trees to active hosts", () => {
|
||||
expect(getCanonicalHostRedirectUrl("http://localhost:3000/crm/dashboard", config)).toBeNull();
|
||||
expect(getCanonicalHostRedirectUrl("http://localhost:3000/internal/ai/chat", config)).toBeNull();
|
||||
expect(getCanonicalHostRedirectUrl("http://localhost:3000/internal/api/__workflows/jobs", config)).toBeNull();
|
||||
expect(getCanonicalHostRedirectUrl("http://localhost:3000/internal/api/workflows/run/workflow_1", config)).toBeNull();
|
||||
expect(getCanonicalHostRedirectUrl("http://localhost:3000/workflows/run/workflow_1", config)).toBeNull();
|
||||
expect(getCanonicalHostRedirectUrl("http://localhost:3000/admin/internal/ai/chat", config)).toBeNull();
|
||||
expect(getCanonicalHostRedirectUrl("http://localhost:3000/admin/__workflows/jobs", config)).toBeNull();
|
||||
expect(getCanonicalHostRedirectUrl("http://localhost:3000/knowledge-base/articles", config)).toBeNull();
|
||||
expect(getCanonicalHostRedirectUrl("http://localhost:3000/help/getting-started", config)).toBeNull();
|
||||
expect(getCanonicalHostRedirectUrl("http://localhost:3000/mcp", config)).toBeNull();
|
||||
expect(getCanonicalHostRedirectUrl("http://api.localhost:3000/help/getting-started", config)).toBeNull();
|
||||
expect(getCanonicalHostRedirectUrl("http://api.localhost:3000/mcp", config)).toBeNull();
|
||||
expect(getCanonicalHostRedirectUrl("http://api.localhost:3000/internal/ai/chat", config)).toBeNull();
|
||||
expect(getCanonicalHostRedirectUrl("http://api.localhost:3000/__workflows/jobs", config)).toBeNull();
|
||||
expect(getCanonicalHostRedirectUrl("http://app.localhost:3000/knowledge-base/articles", config)).toBeNull();
|
||||
expect(getCanonicalHostRedirectUrl("http://app.localhost:3000/acme/internal/ai/chat", config)).toBeNull();
|
||||
expect(getCanonicalHostRedirectUrl("http://admin.localhost:3000/acme/crm", config)).toBeNull();
|
||||
expect(getCanonicalHostRedirectUrl("http://admin.localhost:3000/acme/__widgets/widget_1", config)).toBeNull();
|
||||
expect(getCanonicalHostRedirectUrl("http://admin.localhost:3000/acme/internal/ai/chat", config)).toBeNull();
|
||||
expect(getCanonicalHostRedirectUrl("http://admin.localhost:3000/__workflows/jobs", config)).toBeNull();
|
||||
expect(getCanonicalHostRedirectUrl("http://localhost:3000/acme/internal/ai/chat", config)).toBeNull();
|
||||
});
|
||||
|
||||
test("builds canonical redirect URLs for versioned API paths", () => {
|
||||
expect(getCanonicalHostRedirectUrl("http://api.localhost:3000/v1/health?check=deep#status", config)).toBeNull();
|
||||
expect(getCanonicalHostRedirectUrl("http://localhost:3000/v1/health?check=deep#status", config)).toBe(
|
||||
"http://api.localhost:3000/v1/health?check=deep#status"
|
||||
);
|
||||
});
|
||||
});
|
||||
+497
@@ -0,0 +1,497 @@
|
||||
import { getDomainRoutingConfig, hostMatches, normalizeHost, type DomainRoutingConfig, type DomainRoutingEnv } from "@toolctrl/config";
|
||||
import { adminPath, apiPath, appPath } from "./CanonicalUrlUtils";
|
||||
import {
|
||||
canonicalAdminRouteSlugs,
|
||||
disabledPluginRouteSlugs,
|
||||
isPublicWebRoutePath,
|
||||
isWebRoutePath,
|
||||
normalizeRoutePath,
|
||||
pathMatchesRoutePrefix,
|
||||
reservedTenantChildRouteSlugs,
|
||||
reservedTenantRouteSlugs,
|
||||
} from "./PublicRouteSegments";
|
||||
|
||||
export type HostRoutingContext = "app" | "admin" | "api" | "root" | "unknown";
|
||||
type UrlInput = string | URL | Request;
|
||||
|
||||
export function getHostRoutingContext(host: string | undefined, config: DomainRoutingConfig = getDomainRoutingConfig()): HostRoutingContext {
|
||||
if (hostMatches(host, config.webAppHost)) {
|
||||
return "app";
|
||||
}
|
||||
if (hostMatches(host, config.adminAppHost)) {
|
||||
return "admin";
|
||||
}
|
||||
if (hostMatches(host, config.apiHost)) {
|
||||
return "api";
|
||||
}
|
||||
if (hostMatches(host, config.appBaseDomain)) {
|
||||
return "root";
|
||||
}
|
||||
return "unknown";
|
||||
}
|
||||
|
||||
export function getHostRoutingContextFromRequest(request: Request, env?: DomainRoutingEnv): HostRoutingContext {
|
||||
const config = getDomainRoutingConfig(env);
|
||||
return getHostRoutingContext(getRequestRoutingHost(request, new URL(request.url), config), config);
|
||||
}
|
||||
|
||||
export function getHostAwareInternalPath(pathname: string, context: HostRoutingContext): string {
|
||||
if (isFrameworkInternalRoute(pathname)) {
|
||||
return pathname.startsWith("/") ? pathname : `/${pathname}`;
|
||||
}
|
||||
|
||||
if (context === "admin" && isCanonicalAdminHostRoute(pathname)) {
|
||||
return pathname.startsWith("/") ? pathname : `/${pathname}`;
|
||||
}
|
||||
|
||||
if ((context === "app" || context === "admin") && isPublicWebRoute(pathname)) {
|
||||
return pathname.startsWith("/") ? pathname : `/${pathname}`;
|
||||
}
|
||||
|
||||
if (context === "app") {
|
||||
const [tenantSlug, ...rest] = trimPath(pathname).split("/").filter(Boolean);
|
||||
if (!tenantSlug) {
|
||||
return "/app";
|
||||
}
|
||||
return appPath({ tenantSlug, path: rest.join("/"), mode: "host-aware" });
|
||||
}
|
||||
|
||||
if (context === "admin") {
|
||||
return adminPath(trimPath(pathname), { mode: "host-aware" });
|
||||
}
|
||||
|
||||
if (context === "api") {
|
||||
const normalized = trimPath(pathname);
|
||||
if (normalized === "healthz" || normalized === "readyz") {
|
||||
return `/${normalized}`;
|
||||
}
|
||||
return normalized.startsWith("v1/") || normalized === "v1" ? `/${normalized}` : apiPath(normalized, { mode: "host-aware" });
|
||||
}
|
||||
|
||||
return pathname.startsWith("/") ? pathname : `/${pathname}`;
|
||||
}
|
||||
|
||||
export function getHostAwareInternalUrlPath(input: UrlInput, config: DomainRoutingConfig = getDomainRoutingConfig()): string {
|
||||
const url = toUrl(input);
|
||||
const context = getHostRoutingContext(getHostFromInput(input, url, config), config);
|
||||
const internalPath = getHostAwareInternalPathWithoutDoublePrefix(url.pathname, context);
|
||||
|
||||
return `${internalPath}${url.search}${url.hash}`;
|
||||
}
|
||||
|
||||
export function getCanonicalHostRedirectUrl(input: UrlInput, config: DomainRoutingConfig = getDomainRoutingConfig()): string | null {
|
||||
const url = toUrl(input);
|
||||
const currentHost = getHostFromInput(input, url, config);
|
||||
const context = getHostRoutingContext(currentHost, config);
|
||||
|
||||
// Self-Redirect-Guard: Zeigt der kanonische Redirect auf denselben Host UND denselben Pfad, waere es eine
|
||||
// 308-Endlosschleife (passiert z.B. wenn adminAppHost == webAppHost — Single-Host-Staging/Dev oder eine
|
||||
// Fehlkonfiguration). In dem Fall NICHT umleiten. In getrennten Prod-Hosts (app. != admin.) greift der
|
||||
// Guard nie, das Verhalten bleibt unveraendert.
|
||||
const isSelfRedirect = (origin: string, pathname: string) => {
|
||||
let targetHost: string;
|
||||
try {
|
||||
targetHost = new URL(origin).host;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
return hostMatches(currentHost, targetHost) && pathname === url.pathname;
|
||||
};
|
||||
|
||||
const crossHostRedirect = getCrossHostCanonicalRedirect(url.pathname, context, config);
|
||||
if (crossHostRedirect && !isSelfRedirect(crossHostRedirect.origin, crossHostRedirect.pathname)) {
|
||||
return `${crossHostRedirect.origin}${crossHostRedirect.pathname}${url.search}${url.hash}`;
|
||||
}
|
||||
|
||||
const rootHostRedirect = getRootHostCanonicalRedirect(url.pathname, context, config);
|
||||
if (rootHostRedirect && !isSelfRedirect(rootHostRedirect.origin, rootHostRedirect.pathname)) {
|
||||
return `${rootHostRedirect.origin}${rootHostRedirect.pathname}${url.search}${url.hash}`;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
export function isCanonicalHostForContext(
|
||||
host: string | undefined,
|
||||
context: Exclude<HostRoutingContext, "unknown">,
|
||||
config: DomainRoutingConfig = getDomainRoutingConfig()
|
||||
) {
|
||||
const normalizedHost = normalizeHost(host);
|
||||
if (!normalizedHost) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return getHostRoutingContext(normalizedHost, config) === context;
|
||||
}
|
||||
|
||||
function trimPath(pathname: string) {
|
||||
return pathname.replace(/^\/+|\/+$/g, "");
|
||||
}
|
||||
|
||||
function isPublicWebRoute(pathname: string) {
|
||||
return isWebRoutePath(pathname);
|
||||
}
|
||||
|
||||
function isFrameworkInternalRoute(pathname: string) {
|
||||
const normalizedPathname = pathname.startsWith("/") ? pathname : `/${pathname}`;
|
||||
return normalizedPathname === "/__manifest";
|
||||
}
|
||||
|
||||
const activeWebInternalRoutePrefixes = ["/internal/imports/dry-run"] as const;
|
||||
|
||||
function isActiveWebInternalRoute(pathname: string) {
|
||||
const routePathname = normalizeRoutePath(pathname);
|
||||
return activeWebInternalRoutePrefixes.some((prefix) => pathMatchesRoutePrefix(routePathname, prefix));
|
||||
}
|
||||
|
||||
export function isCanonicalAdminHostRoute(pathname: string) {
|
||||
const routePathname = normalizeRoutePath(pathname);
|
||||
if (isActiveWebInternalRoute(routePathname)) {
|
||||
return false;
|
||||
}
|
||||
if (isDisabledAdminHostRoute(routePathname)) {
|
||||
return false;
|
||||
}
|
||||
const firstSegment = trimPath(routePathname).split("/")[0];
|
||||
return Boolean(firstSegment && (canonicalAdminRouteSlugs as readonly string[]).includes(firstSegment));
|
||||
}
|
||||
|
||||
function isCanonicalApiHostRoute(pathname: string) {
|
||||
const normalizedPathname = pathname.startsWith("/") ? pathname : `/${pathname}`;
|
||||
const routePathname = normalizedPathname.replace(/\.data$/, "");
|
||||
|
||||
return routePathname === "/v1" || routePathname.startsWith("/v1/");
|
||||
}
|
||||
|
||||
function isLegacyApiV1HostRoute(pathname: string) {
|
||||
const normalizedPathname = pathname.startsWith("/") ? pathname : `/${pathname}`;
|
||||
const routePathname = normalizedPathname.replace(/\.data$/, "");
|
||||
|
||||
return routePathname === "/api/v1" || routePathname.startsWith("/api/v1/");
|
||||
}
|
||||
|
||||
function isLegacyAppHostRoute(pathname: string) {
|
||||
const normalizedPathname = pathname.startsWith("/") ? pathname : `/${pathname}`;
|
||||
const routePathname = normalizedPathname.replace(/\.data$/, "");
|
||||
|
||||
return routePathname.startsWith("/app/") && routePathname.split("/").filter(Boolean).length >= 2;
|
||||
}
|
||||
|
||||
function isRemovedAdminPrefixRoute(pathname: string) {
|
||||
const routePathname = normalizeRoutePath(pathname);
|
||||
return trimPath(routePathname).split("/").filter(Boolean)[0] === "admin";
|
||||
}
|
||||
|
||||
function canonicalTenantPathFromLegacyApp(pathname: string) {
|
||||
const normalizedPathname = pathname.startsWith("/") ? pathname : `/${pathname}`;
|
||||
const routePathname = normalizedPathname.replace(/\.data$/, "");
|
||||
const canonicalPathname = routePathname.replace(/^\/app(?=\/)/, "");
|
||||
|
||||
return normalizedPathname.endsWith(".data") ? `${canonicalPathname}.data` : canonicalPathname;
|
||||
}
|
||||
|
||||
function canonicalApiPathFromLegacyApiV1(pathname: string) {
|
||||
const normalizedPathname = pathname.startsWith("/") ? pathname : `/${pathname}`;
|
||||
const routePathname = normalizedPathname.replace(/\.data$/, "");
|
||||
const canonicalPathname = routePathname.replace(/^\/api(?=\/v1(?:\/|$))/, "");
|
||||
|
||||
return normalizedPathname.endsWith(".data") ? `${canonicalPathname}.data` : canonicalPathname;
|
||||
}
|
||||
|
||||
function isApiOperationalRoute(pathname: string) {
|
||||
const normalizedPathname = pathname.startsWith("/") ? pathname : `/${pathname}`;
|
||||
const routePathname = normalizedPathname.replace(/\.data$/, "");
|
||||
|
||||
return routePathname === "/healthz" || routePathname === "/readyz";
|
||||
}
|
||||
|
||||
function getRootHostCanonicalRedirect(pathname: string, context: HostRoutingContext, config: DomainRoutingConfig) {
|
||||
if (context !== "root") {
|
||||
return null;
|
||||
}
|
||||
|
||||
const normalizedPathname = pathname.startsWith("/") ? pathname : `/${pathname}`;
|
||||
if (isLegacyApiV1HostRoute(normalizedPathname)) {
|
||||
return {
|
||||
origin: `${config.protocol}://${config.apiHost}`,
|
||||
pathname: canonicalApiPathFromLegacyApiV1(normalizedPathname),
|
||||
};
|
||||
}
|
||||
|
||||
if (isLegacyAppHostRoute(normalizedPathname)) {
|
||||
const canonicalPathname = canonicalTenantPathFromLegacyApp(normalizedPathname);
|
||||
if (isDisabledTenantHostRoute(canonicalPathname)) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
origin: `${config.protocol}://${config.webAppHost}`,
|
||||
pathname: canonicalPathname,
|
||||
};
|
||||
}
|
||||
|
||||
if (isRemovedAdminPrefixRoute(normalizedPathname)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (normalizedPathname === "/" || isPublicWebRoutePath(normalizedPathname) || isFrameworkInternalRoute(normalizedPathname)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (isDisabledPluginHostRoute(normalizedPathname)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (isActiveWebInternalRoute(normalizedPathname)) {
|
||||
return {
|
||||
origin: `${config.protocol}://${config.webAppHost}`,
|
||||
pathname: normalizedPathname,
|
||||
};
|
||||
}
|
||||
|
||||
if (isCanonicalAdminHostRoute(normalizedPathname)) {
|
||||
return {
|
||||
origin: `${config.protocol}://${config.adminAppHost}`,
|
||||
pathname: normalizedPathname,
|
||||
};
|
||||
}
|
||||
|
||||
if (isCanonicalApiHostRoute(normalizedPathname)) {
|
||||
return {
|
||||
origin: `${config.protocol}://${config.apiHost}`,
|
||||
pathname: normalizedPathname,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
origin: `${config.protocol}://${config.webAppHost}`,
|
||||
pathname: normalizedPathname,
|
||||
};
|
||||
}
|
||||
|
||||
function isDisabledPluginHostRoute(pathname: string) {
|
||||
return isDisabledAdminHostRoute(pathname) || isDisabledTenantHostRoute(pathname);
|
||||
}
|
||||
|
||||
const disabledAdminHostRoutePrefixes = ["/__workflows", "/internal/ai", "/internal/api/__workflows", "/internal/api/workflows", "/workflows"] as const;
|
||||
|
||||
const disabledTenantHostRouteChildPrefixes = [
|
||||
"/__portals",
|
||||
"/__widgets",
|
||||
"/__workflows",
|
||||
"/chat",
|
||||
"/crm",
|
||||
"/email-marketing",
|
||||
"/internal/ai",
|
||||
"/portals",
|
||||
"/sites",
|
||||
"/widgets",
|
||||
"/workflow-engine",
|
||||
] as const;
|
||||
|
||||
function isDisabledAdminHostRoute(pathname: string) {
|
||||
const routePathname = normalizeRoutePath(pathname);
|
||||
const firstSegment = trimPath(routePathname).split("/")[0];
|
||||
if (firstSegment && (disabledPluginRouteSlugs as readonly string[]).includes(firstSegment)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return disabledAdminHostRoutePrefixes.some((prefix) => pathMatchesRoutePrefix(routePathname, prefix));
|
||||
}
|
||||
|
||||
function isDisabledTenantHostRoute(pathname: string) {
|
||||
const routePathname = normalizeRoutePath(pathname);
|
||||
const [, ...childSegments] = trimPath(routePathname).split("/").filter(Boolean);
|
||||
if (childSegments.length === 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const childPathname = `/${childSegments.join("/")}`;
|
||||
return disabledTenantHostRouteChildPrefixes.some((prefix) => pathMatchesRoutePrefix(childPathname, prefix));
|
||||
}
|
||||
|
||||
function getCrossHostCanonicalRedirect(pathname: string, context: HostRoutingContext, config: DomainRoutingConfig) {
|
||||
const normalizedPathname = pathname.startsWith("/") ? pathname : `/${pathname}`;
|
||||
if (isLegacyApiV1HostRoute(normalizedPathname)) {
|
||||
return {
|
||||
origin: `${config.protocol}://${config.apiHost}`,
|
||||
pathname: canonicalApiPathFromLegacyApiV1(normalizedPathname),
|
||||
};
|
||||
}
|
||||
|
||||
if (isLegacyAppHostRoute(normalizedPathname)) {
|
||||
const canonicalPathname = canonicalTenantPathFromLegacyApp(normalizedPathname);
|
||||
if (isDisabledTenantHostRoute(canonicalPathname)) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
origin: `${config.protocol}://${config.webAppHost}`,
|
||||
pathname: canonicalPathname,
|
||||
};
|
||||
}
|
||||
|
||||
if (context === "api" && isUnversionedApiHostAlias(normalizedPathname)) {
|
||||
return {
|
||||
origin: `${config.protocol}://${config.apiHost}`,
|
||||
pathname: apiPath(normalizedPathname, { mode: "host-aware" }),
|
||||
};
|
||||
}
|
||||
|
||||
if ((normalizedPathname === "/" || isPublicWebRoutePath(normalizedPathname)) && context === "api" && !isApiOperationalRoute(normalizedPathname)) {
|
||||
return {
|
||||
origin: `${config.protocol}://${config.webAppHost}`,
|
||||
pathname: normalizedPathname,
|
||||
};
|
||||
}
|
||||
|
||||
if (normalizedPathname === "/" || isPublicWebRoutePath(normalizedPathname) || isFrameworkInternalRoute(normalizedPathname)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (isDisabledPluginHostRoute(normalizedPathname)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (isActiveWebInternalRoute(normalizedPathname)) {
|
||||
return context === "app"
|
||||
? null
|
||||
: {
|
||||
origin: `${config.protocol}://${config.webAppHost}`,
|
||||
pathname: normalizedPathname,
|
||||
};
|
||||
}
|
||||
|
||||
if (isCanonicalApiHostRoute(normalizedPathname) && context !== "api") {
|
||||
return {
|
||||
origin: `${config.protocol}://${config.apiHost}`,
|
||||
pathname: normalizedPathname,
|
||||
};
|
||||
}
|
||||
|
||||
if (isCanonicalAdminHostRoute(normalizedPathname) && context !== "admin") {
|
||||
return {
|
||||
origin: `${config.protocol}://${config.adminAppHost}`,
|
||||
pathname: normalizedPathname,
|
||||
};
|
||||
}
|
||||
|
||||
if ((context === "admin" || context === "api") && isCanonicalTenantHostRoute(normalizedPathname)) {
|
||||
return {
|
||||
origin: `${config.protocol}://${config.webAppHost}`,
|
||||
pathname: normalizedPathname,
|
||||
};
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function getHostAwareInternalPathWithoutDoublePrefix(pathname: string, context: HostRoutingContext): string {
|
||||
const normalizedPathname = pathname.startsWith("/") ? pathname : `/${pathname}`;
|
||||
if (context === "app" && isLegacyAppHostRoute(normalizedPathname)) {
|
||||
return getHostAwareInternalPath(canonicalTenantPathFromLegacyApp(normalizedPathname), context);
|
||||
}
|
||||
|
||||
return getHostAwareInternalPath(normalizedPathname, context);
|
||||
}
|
||||
|
||||
function isCanonicalTenantHostRoute(pathname: string) {
|
||||
const routePathname = normalizeRoutePath(pathname);
|
||||
const [, firstSegment, secondSegment] = routePathname.match(/^\/([^/?#]+)(?:\/([^/?#]+))?/) ?? [];
|
||||
if (isDisabledTenantHostRoute(routePathname)) {
|
||||
return false;
|
||||
}
|
||||
if (!firstSegment || isCanonicalAdminHostRoute(routePathname) || isWebRoutePath(routePathname) || firstSegment === "v1") {
|
||||
return false;
|
||||
}
|
||||
if ((reservedTenantRouteSlugs as readonly string[]).includes(firstSegment)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!secondSegment) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const canonicalTenantSegments = new Set([
|
||||
"$entity",
|
||||
"apps",
|
||||
"dashboard",
|
||||
"g",
|
||||
"internal",
|
||||
"notifications",
|
||||
"settings",
|
||||
]);
|
||||
if ((reservedTenantChildRouteSlugs as readonly string[]).includes(secondSegment) && !canonicalTenantSegments.has(secondSegment)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return Boolean(secondSegment && (canonicalTenantSegments.has(secondSegment) || !secondSegment.startsWith("__")));
|
||||
}
|
||||
|
||||
function isUnversionedApiHostAlias(pathname: string) {
|
||||
if (isApiOperationalRoute(pathname) || isCanonicalApiHostRoute(pathname) || isFrameworkInternalRoute(pathname)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const normalizedPathname = pathname.startsWith("/") ? pathname : `/${pathname}`;
|
||||
const firstSegment = trimPath(normalizedPathname).split("/")[0];
|
||||
if (!firstSegment) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return [
|
||||
"accounts",
|
||||
"ai",
|
||||
"analytics",
|
||||
"api-keys",
|
||||
"auth",
|
||||
"billing",
|
||||
"docs",
|
||||
"entities",
|
||||
"events",
|
||||
"exports",
|
||||
"health",
|
||||
"maintenance",
|
||||
"notifications",
|
||||
"openapi.json",
|
||||
"relationships",
|
||||
"session",
|
||||
"usage",
|
||||
"workspaces",
|
||||
].includes(firstSegment);
|
||||
}
|
||||
|
||||
function toUrl(input: UrlInput) {
|
||||
if (input instanceof URL) {
|
||||
return input;
|
||||
}
|
||||
if (input instanceof Request) {
|
||||
return new URL(input.url);
|
||||
}
|
||||
|
||||
return new URL(input);
|
||||
}
|
||||
|
||||
function getHostFromInput(input: UrlInput, url: URL, config: DomainRoutingConfig) {
|
||||
if (input instanceof Request) {
|
||||
return getRequestRoutingHost(input, url, config);
|
||||
}
|
||||
|
||||
return url.host;
|
||||
}
|
||||
|
||||
export function getRequestRoutingHost(request: Request, url: URL = new URL(request.url), config: DomainRoutingConfig = getDomainRoutingConfig()) {
|
||||
const directHost = request.headers.get("host") ?? url.host;
|
||||
const directContext = getHostRoutingContext(directHost, config);
|
||||
if (directContext === "app" || directContext === "admin" || directContext === "api") {
|
||||
return directHost;
|
||||
}
|
||||
|
||||
const forwardedHost = request.headers
|
||||
.get("x-forwarded-host")
|
||||
?.split(",")
|
||||
.map((value) => value.trim())
|
||||
.find(Boolean);
|
||||
if (forwardedHost) {
|
||||
return forwardedHost;
|
||||
}
|
||||
return directHost;
|
||||
}
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
import { describe, expect, test } from "vitest";
|
||||
import {
|
||||
isAbsoluteWebHostPath,
|
||||
isPublicWebRoutePath,
|
||||
isWebRoutePath,
|
||||
reservedTenantChildRouteSlugs,
|
||||
reservedTenantRouteSlugs,
|
||||
} from "./PublicRouteSegments";
|
||||
|
||||
describe("public route segments", () => {
|
||||
test("classifies top-level public routes that must not become tenant slugs", () => {
|
||||
for (const pathname of [
|
||||
"/docs",
|
||||
"/healthcheck",
|
||||
"/healthz",
|
||||
"/readyz",
|
||||
"/mfa-challenge",
|
||||
"/unauthorized/foo",
|
||||
"/401",
|
||||
"/403",
|
||||
"/404",
|
||||
"/500",
|
||||
]) {
|
||||
expect(isPublicWebRoutePath(pathname), pathname).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
test("keeps protected top-level web routes routable without classifying them public", () => {
|
||||
for (const pathname of ["/swagger", "/postman_collection.json"]) {
|
||||
expect(isWebRoutePath(pathname), pathname).toBe(true);
|
||||
expect(isPublicWebRoutePath(pathname), pathname).toBe(false);
|
||||
}
|
||||
});
|
||||
|
||||
test("does not classify disabled or plugin-owned route trees as routable web paths", () => {
|
||||
for (const pathname of ["/mcp", "/help/getting-started", "/webhooks/events/accounts/created", "/public/contact/row_1"]) {
|
||||
expect(isWebRoutePath(pathname), pathname).toBe(false);
|
||||
expect(isPublicWebRoutePath(pathname), pathname).toBe(false);
|
||||
expect(isAbsoluteWebHostPath(pathname), pathname).toBe(false);
|
||||
}
|
||||
});
|
||||
|
||||
test("requires segment boundaries for public prefixes", () => {
|
||||
for (const pathname of ["/login-extra", "/settingsx", "/api/workflows/run/workflow_1", "/api/workflowsx/run"]) {
|
||||
expect(isPublicWebRoutePath(pathname), pathname).toBe(false);
|
||||
}
|
||||
});
|
||||
|
||||
test("classifies settings as a canonical host route, not a public web route", () => {
|
||||
expect(isPublicWebRoutePath("/settings/profile")).toBe(false);
|
||||
expect(isAbsoluteWebHostPath("/settings/profile")).toBe(false);
|
||||
});
|
||||
|
||||
test("exports reserved slugs for route collision checks", () => {
|
||||
expect(reservedTenantRouteSlugs).toEqual(expect.arrayContaining(["accounts", "analytics", "api", "crm", "docs", "help", "healthcheck", "healthz", "readyz", "swagger", "mcp", "mfa-challenge"]));
|
||||
expect(reservedTenantChildRouteSlugs).toEqual(expect.arrayContaining(["settings", "crm", "email-marketing", "workflow-engine", "g", "chat", "internal", "widgets"]));
|
||||
});
|
||||
});
|
||||
+147
@@ -0,0 +1,147 @@
|
||||
export const publicWebRouteExactPaths = ["/sitemap.xml"] as const;
|
||||
export const protectedWebRouteExactPaths = ["/postman_collection.json"] as const;
|
||||
|
||||
export const publicWebRoutePrefixes = [
|
||||
"/401",
|
||||
"/403",
|
||||
"/404",
|
||||
"/500",
|
||||
"/auth/",
|
||||
"/deactivated/",
|
||||
"/docs",
|
||||
"/feature-disabled",
|
||||
"/forgot-password",
|
||||
"/healthcheck",
|
||||
"/healthz",
|
||||
"/invitation/",
|
||||
"/login",
|
||||
"/logout",
|
||||
"/mfa-challenge",
|
||||
"/new-account",
|
||||
"/oauth/",
|
||||
"/onboarding/",
|
||||
"/plan-required/",
|
||||
"/preferences",
|
||||
"/privacy-policy",
|
||||
"/readyz",
|
||||
"/register",
|
||||
"/reset",
|
||||
"/select-tenant",
|
||||
"/sitemap.xml",
|
||||
"/subscribe/",
|
||||
"/terms-and-conditions",
|
||||
"/unauthorized",
|
||||
"/verify/",
|
||||
] as const;
|
||||
|
||||
export const protectedWebRoutePrefixes = ["/swagger"] as const;
|
||||
export const absoluteWebHostRoutePrefixes = publicWebRoutePrefixes;
|
||||
|
||||
export const canonicalAdminRouteSlugs = [
|
||||
"accounts",
|
||||
"analytics",
|
||||
"api",
|
||||
"audit-trails",
|
||||
"dashboard",
|
||||
"email-sequences",
|
||||
"entities",
|
||||
"events",
|
||||
"feature-flags",
|
||||
"internal",
|
||||
"marketing-funnels",
|
||||
"marketing-integrations",
|
||||
"marketing-leads",
|
||||
"metrics",
|
||||
"mfa-challenge",
|
||||
"navigation",
|
||||
"notifications",
|
||||
"onboarding",
|
||||
"settings",
|
||||
"setup",
|
||||
] as const;
|
||||
|
||||
export const disabledPluginRouteSlugs = [
|
||||
"ai",
|
||||
"chat",
|
||||
"crm",
|
||||
"email-marketing",
|
||||
"help",
|
||||
"help-desk",
|
||||
"knowledge-base",
|
||||
"mcp",
|
||||
"portals",
|
||||
"prompts",
|
||||
"workflow-engine",
|
||||
] as const;
|
||||
|
||||
export const reservedTenantRouteSlugs = [
|
||||
"admin",
|
||||
"api",
|
||||
"app",
|
||||
"null",
|
||||
"undefined",
|
||||
"v1",
|
||||
...canonicalAdminRouteSlugs,
|
||||
...disabledPluginRouteSlugs,
|
||||
...new Set(
|
||||
[...publicWebRoutePrefixes, ...protectedWebRoutePrefixes]
|
||||
.flatMap((prefix) => prefix.split("/").filter(Boolean).slice(0, 1))
|
||||
.concat(protectedWebRouteExactPaths.flatMap((path) => path.split("/").filter(Boolean).slice(0, 1)))
|
||||
.filter(Boolean)
|
||||
),
|
||||
] as const;
|
||||
|
||||
export const reservedTenantChildRouteSlugs = [
|
||||
"__portals",
|
||||
"__widgets",
|
||||
"__workflows",
|
||||
"chat",
|
||||
"crm",
|
||||
"dashboard",
|
||||
"email-marketing",
|
||||
"g",
|
||||
"internal",
|
||||
"notifications",
|
||||
"portals",
|
||||
"settings",
|
||||
"sites",
|
||||
"widgets",
|
||||
"workflow-engine",
|
||||
] as const;
|
||||
|
||||
export function pathMatchesRoutePrefix(pathname: string, prefix: string) {
|
||||
const normalizedPrefix = prefix.replace(/\/$/, "");
|
||||
return pathname === normalizedPrefix || pathname.startsWith(`${normalizedPrefix}/`);
|
||||
}
|
||||
|
||||
export function normalizeRoutePath(pathname: string) {
|
||||
const normalizedPathname = pathname.startsWith("/") ? pathname : `/${pathname}`;
|
||||
return normalizedPathname.replace(/\.data$/, "");
|
||||
}
|
||||
|
||||
export function isPublicWebRoutePath(pathname: string) {
|
||||
const routePathname = normalizeRoutePath(pathname);
|
||||
if ((publicWebRouteExactPaths as readonly string[]).includes(routePathname)) {
|
||||
return true;
|
||||
}
|
||||
return publicWebRoutePrefixes.some((prefix) => pathMatchesRoutePrefix(routePathname, prefix));
|
||||
}
|
||||
|
||||
export function isWebRoutePath(pathname: string) {
|
||||
const routePathname = normalizeRoutePath(pathname);
|
||||
if (isPublicWebRoutePath(routePathname)) {
|
||||
return true;
|
||||
}
|
||||
if ((protectedWebRouteExactPaths as readonly string[]).includes(routePathname)) {
|
||||
return true;
|
||||
}
|
||||
return protectedWebRoutePrefixes.some((prefix) => pathMatchesRoutePrefix(routePathname, prefix));
|
||||
}
|
||||
|
||||
export function isAbsoluteWebHostPath(pathname: string) {
|
||||
const routePathname = normalizeRoutePath(pathname);
|
||||
if ((publicWebRouteExactPaths as readonly string[]).includes(routePathname)) {
|
||||
return true;
|
||||
}
|
||||
return absoluteWebHostRoutePrefixes.some((prefix) => pathMatchesRoutePrefix(routePathname, prefix));
|
||||
}
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { safeRedirectPath } from "./RedirectSafety.server";
|
||||
|
||||
describe("safeRedirectPath", () => {
|
||||
it("rejects removed route aliases and canonical API paths", () => {
|
||||
expect(safeRedirectPath("/app/acme/dashboard")).toBe("/");
|
||||
expect(safeRedirectPath("/admin/settings")).toBe("/");
|
||||
expect(safeRedirectPath("/api/v1/health")).toBe("/");
|
||||
expect(safeRedirectPath("/v1/health")).toBe("/");
|
||||
});
|
||||
|
||||
it("keeps same-host application paths", () => {
|
||||
expect(safeRedirectPath("/dashboard?tab=activity#top")).toBe("/dashboard?tab=activity#top");
|
||||
});
|
||||
|
||||
it("rejects control characters and encoded slash or backslash redirects", () => {
|
||||
expect(safeRedirectPath("/dashboard%0d%0aLocation:%20//evil.example")).toBe("/");
|
||||
expect(safeRedirectPath("/%2f%2fevil.example")).toBe("/");
|
||||
expect(safeRedirectPath("/%5c%5cevil.example")).toBe("/");
|
||||
expect(safeRedirectPath("/dashboard\u0000")).toBe("/");
|
||||
});
|
||||
});
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
type SafeRedirectOptions = {
|
||||
fallbackPath?: string;
|
||||
};
|
||||
|
||||
export function safeRedirectPath(value: string | null | undefined, options: SafeRedirectOptions = {}) {
|
||||
const fallbackPath = options.fallbackPath ?? "/";
|
||||
if (!value) {
|
||||
return fallbackPath;
|
||||
}
|
||||
|
||||
const trimmed = value.trim();
|
||||
if (
|
||||
!trimmed ||
|
||||
!trimmed.startsWith("/") ||
|
||||
trimmed.startsWith("//") ||
|
||||
trimmed.includes("\\") ||
|
||||
/[\u0000-\u001f\u007f]/.test(trimmed) ||
|
||||
/%(?:2f|5c|00|0a|0d)/i.test(trimmed)
|
||||
) {
|
||||
return fallbackPath;
|
||||
}
|
||||
|
||||
try {
|
||||
const parsed = new URL(trimmed, "http://local.invalid");
|
||||
if (isRemovedRoutePath(parsed.pathname)) {
|
||||
return fallbackPath;
|
||||
}
|
||||
return `${parsed.pathname}${parsed.search}${parsed.hash}`;
|
||||
} catch {
|
||||
return fallbackPath;
|
||||
}
|
||||
}
|
||||
|
||||
export function safeRedirectPathFromRequest(request: Request, value: string | null | undefined) {
|
||||
const url = new URL(request.url);
|
||||
return safeRedirectPath(value, { fallbackPath: `${url.pathname}${url.search}${url.hash}` });
|
||||
}
|
||||
|
||||
export function isRemovedRoutePath(pathname: string) {
|
||||
const normalizedPathname = pathname.replace(/\/+$/g, "") || "/";
|
||||
return (
|
||||
normalizedPathname === "/app" ||
|
||||
normalizedPathname.startsWith("/app/") ||
|
||||
normalizedPathname === "/admin" ||
|
||||
normalizedPathname.startsWith("/admin/") ||
|
||||
normalizedPathname === "/api" ||
|
||||
normalizedPathname.startsWith("/api/") ||
|
||||
normalizedPathname === "/v1" ||
|
||||
normalizedPathname.startsWith("/v1/")
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
const validateEmail = (value: string | undefined) => {
|
||||
if (!value) {
|
||||
return false;
|
||||
}
|
||||
return /^\w+([\\.-]?\w+)*@\w+([\\.-]?\w+)*(\.\w{2,3})+$/.test(value);
|
||||
};
|
||||
|
||||
const validateUrl = (value: string | undefined) => {
|
||||
if (!value) {
|
||||
return false;
|
||||
}
|
||||
return /^(?:(ftp|http|https)?:\/\/)?(?:[\w-]+\.)+([a-z]|[A-Z]|[0-9]){2,}(?:\/.*)?$/gi.test(value);
|
||||
};
|
||||
|
||||
const validatePhone = (value: string | undefined) => {
|
||||
if (!value) {
|
||||
return false;
|
||||
}
|
||||
return /^\+?(\d{1,3}[-.\s]?)?\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}$/.test(value);
|
||||
};
|
||||
|
||||
export default {
|
||||
validateEmail,
|
||||
validateUrl,
|
||||
validatePhone,
|
||||
};
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { subscriptionCheckoutPath, subscriptionRequiredCheckoutPath } from "./SubscriptionUrlUtils";
|
||||
|
||||
describe("subscription URL helpers", () => {
|
||||
it("builds canonical public checkout routes", () => {
|
||||
expect(subscriptionCheckoutPath("acme")).toBe("/subscribe/acme");
|
||||
expect(subscriptionCheckoutPath("acme", "{CHECKOUT_SESSION_ID}/success")).toBe("/subscribe/acme/{CHECKOUT_SESSION_ID}/success");
|
||||
expect(subscriptionRequiredCheckoutPath("acme")).toBe("/subscribe/acme?error=subscription_required");
|
||||
});
|
||||
|
||||
it("encodes tenant slugs as one route segment", () => {
|
||||
expect(subscriptionCheckoutPath(" Acme Team/West ")).toBe("/subscribe/Acme%20Team%2FWest");
|
||||
expect(() => subscriptionCheckoutPath(" ")).toThrow("tenantSlug is required");
|
||||
});
|
||||
});
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
export function subscriptionCheckoutPath(tenantSlug: string, path?: string) {
|
||||
const tenantSegment = tenantSlug.trim();
|
||||
if (!tenantSegment) {
|
||||
throw new Error("tenantSlug is required");
|
||||
}
|
||||
|
||||
const encodedTenant = encodeURIComponent(tenantSegment);
|
||||
const normalizedPath = path?.trim();
|
||||
|
||||
if (!normalizedPath) {
|
||||
return `/subscribe/${encodedTenant}`;
|
||||
}
|
||||
|
||||
if (normalizedPath.startsWith("?") || normalizedPath.startsWith("#")) {
|
||||
return `/subscribe/${encodedTenant}${normalizedPath}`;
|
||||
}
|
||||
|
||||
return `/subscribe/${encodedTenant}/${normalizedPath.replace(/^\/+|\/+$/g, "")}`;
|
||||
}
|
||||
|
||||
export function subscriptionRequiredCheckoutPath(tenantSlug: string) {
|
||||
return subscriptionCheckoutPath(tenantSlug, "?error=subscription_required");
|
||||
}
|
||||
+67
@@ -0,0 +1,67 @@
|
||||
import { vi, describe, it, expect } from "vitest";
|
||||
import SubscriptionUtils from "./SubscriptionUtils";
|
||||
import { SubscriptionBillingPeriod } from "~/application/enums/subscriptions/SubscriptionBillingPeriod";
|
||||
import { Prisma } from "@toolctrl/db/prisma-browser";
|
||||
import DateUtils from "../shared/DateUtils";
|
||||
|
||||
describe("getProductTitle", () => {
|
||||
const t = vi.fn().mockImplementation((v: string, options?: Record<string, unknown>) => {
|
||||
if (v === "settings.subscription.endsRelative") {
|
||||
return `Ends ${options?.date}`;
|
||||
}
|
||||
return v;
|
||||
}) as any;
|
||||
const item = {
|
||||
subscriptionProduct: { title: "Product 1" },
|
||||
prices: [{ subscriptionPrice: { price: new Prisma.Decimal(10), billingPeriod: SubscriptionBillingPeriod.MONTHLY } }],
|
||||
endsAt: new Date(),
|
||||
} as unknown as any;
|
||||
|
||||
it("returns expected product title", () => {
|
||||
const expectedTitle = "Product 1 $10.00 - pricing.MONTHLY (Ends 1 day ago)";
|
||||
|
||||
DateUtils.dateAgo = vi.fn().mockImplementation(() => "1 day ago");
|
||||
const title = SubscriptionUtils.getProductTitle({ t, item });
|
||||
expect(title).toEqual(expectedTitle);
|
||||
expect(t).toHaveBeenCalledWith("settings.subscription.endsRelative", { date: "1 day ago" });
|
||||
});
|
||||
});
|
||||
|
||||
describe("getPriceDescription", () => {
|
||||
const t = vi.fn().mockImplementation((v: string) => v) as any;
|
||||
const item = {
|
||||
subscriptionProduct: { title: "Product 1" },
|
||||
price: new Prisma.Decimal(10),
|
||||
billingPeriod: SubscriptionBillingPeriod.MONTHLY,
|
||||
} as unknown as any;
|
||||
|
||||
it("returns expected price description", () => {
|
||||
const expectedDescription = "Product 1 - $10.00 - pricing.MONTHLY";
|
||||
// @ts-ignore
|
||||
const description = SubscriptionUtils.getPriceDescription(t, item);
|
||||
expect(description).toEqual(expectedDescription);
|
||||
});
|
||||
});
|
||||
|
||||
describe("getBillingPeriodDescription", () => {
|
||||
const billingPeriod = SubscriptionBillingPeriod.MONTHLY;
|
||||
|
||||
it("returns expected billing period description", () => {
|
||||
const expectedDescription = "pricing.MONTHLY";
|
||||
const t = vi.fn().mockImplementation((v: string) => v) as any;
|
||||
const description = SubscriptionUtils.getBillingPeriodDescription(t, billingPeriod);
|
||||
expect(description).toEqual(expectedDescription);
|
||||
});
|
||||
});
|
||||
|
||||
describe("getBillingPeriodShortDescription", () => {
|
||||
const t = vi.fn().mockImplementation((v: string) => v) as any;
|
||||
|
||||
it("maps all supported period labels through pricing keys", () => {
|
||||
expect(SubscriptionUtils.getBillingPeriodShortDescription(t, SubscriptionBillingPeriod.ONCE)).toEqual("pricing.once");
|
||||
expect(SubscriptionUtils.getBillingPeriodShortDescription(t, SubscriptionBillingPeriod.MONTHLY)).toEqual("pricing.MONTHLYShort");
|
||||
expect(SubscriptionUtils.getBillingPeriodShortDescription(t, SubscriptionBillingPeriod.YEARLY)).toEqual("pricing.YEARLYShort");
|
||||
expect(SubscriptionUtils.getBillingPeriodShortDescription(t, SubscriptionBillingPeriod.QUARTERLY)).toEqual("pricing.QUARTERLYShort");
|
||||
expect(SubscriptionUtils.getBillingPeriodShortDescription(t, SubscriptionBillingPeriod.SEMI_ANNUAL)).toEqual("pricing.SEMIANNUALShort");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,61 @@
|
||||
import { TFunction } from "i18next";
|
||||
import { SubscriptionBillingPeriod } from "~/application/enums/subscriptions/SubscriptionBillingPeriod";
|
||||
import { SubscriptionPriceWithProduct } from "../db/subscriptionProducts.db.server";
|
||||
import DateUtils from "../shared/DateUtils";
|
||||
import { getFormattedPriceInCurrency } from "../helpers/PricingHelper";
|
||||
import { TenantSubscriptionProductWithDetails } from "../db/subscriptions/tenantSubscriptionProducts.db.server";
|
||||
|
||||
function formatSubscriptionPrice(price: number, currency?: string | null) {
|
||||
return getFormattedPriceInCurrency({ price, currency: currency ?? "usd" });
|
||||
}
|
||||
|
||||
function getProductTitle({ t, item }: { t: TFunction; item: TenantSubscriptionProductWithDetails }) {
|
||||
let title =
|
||||
t(item.subscriptionProduct.title) +
|
||||
" " +
|
||||
item.prices
|
||||
.map(
|
||||
(f) =>
|
||||
`${formatSubscriptionPrice(Number(f.subscriptionPrice?.price ?? 0), f.subscriptionPrice?.currency)} - ${getBillingPeriodDescription(
|
||||
t,
|
||||
f.subscriptionPrice!.billingPeriod
|
||||
)}`
|
||||
)
|
||||
.join(", ");
|
||||
if (item.endsAt) {
|
||||
title += ` (${t("settings.subscription.endsRelative", { date: DateUtils.dateAgo(item.endsAt) })})`;
|
||||
}
|
||||
return title;
|
||||
}
|
||||
|
||||
function getPriceDescription(t: TFunction, item: SubscriptionPriceWithProduct) {
|
||||
return `${t(item.subscriptionProduct.title)} - ${formatSubscriptionPrice(Number(item.price), item.currency)} - ${getBillingPeriodDescription(t, item.billingPeriod)}`;
|
||||
}
|
||||
|
||||
function getBillingPeriodDescription(t: TFunction, billingPeriod: SubscriptionBillingPeriod) {
|
||||
return t("pricing." + SubscriptionBillingPeriod[billingPeriod].toString()).toString();
|
||||
}
|
||||
|
||||
function getBillingPeriodShortDescription(t: TFunction, billingPeriod: SubscriptionBillingPeriod) {
|
||||
switch (billingPeriod) {
|
||||
case SubscriptionBillingPeriod.MONTHLY:
|
||||
return t("pricing.MONTHLYShort").toString();
|
||||
case SubscriptionBillingPeriod.YEARLY:
|
||||
return t("pricing.YEARLYShort").toString();
|
||||
case SubscriptionBillingPeriod.QUARTERLY:
|
||||
return t("pricing.QUARTERLYShort").toString();
|
||||
case SubscriptionBillingPeriod.SEMI_ANNUAL:
|
||||
return t("pricing.SEMIANNUALShort").toString();
|
||||
case SubscriptionBillingPeriod.ONCE:
|
||||
return t("pricing.once").toString();
|
||||
default:
|
||||
return getBillingPeriodDescription(t, billingPeriod);
|
||||
}
|
||||
}
|
||||
|
||||
export default {
|
||||
getProductTitle,
|
||||
getPriceDescription,
|
||||
getBillingPeriodDescription,
|
||||
getBillingPeriodShortDescription,
|
||||
};
|
||||
@@ -0,0 +1,14 @@
|
||||
import { TFunction } from "i18next";
|
||||
import { TenantWithUsage } from "../db/tenants.db.server";
|
||||
import SubscriptionUtils from "./SubscriptionUtils";
|
||||
|
||||
function getProducts({ t, item }: { t: TFunction; item: TenantWithUsage }) {
|
||||
if (item.subscription?.products) {
|
||||
return item.subscription.products.map((item) => SubscriptionUtils.getProductTitle({ t, item })).join(", ");
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
export default {
|
||||
getProducts,
|
||||
};
|
||||
@@ -0,0 +1,77 @@
|
||||
import { describe, test, expect } from "vitest";
|
||||
import UrlUtils from "./UrlUtils";
|
||||
|
||||
describe("UrlUtils", () => {
|
||||
test("stripTrailingSlash should remove the trailing slash from a string", () => {
|
||||
const input = "foo/bar/";
|
||||
const expectedOutput = "foo/bar";
|
||||
const actualOutput = UrlUtils.stripTrailingSlash(input);
|
||||
expect(actualOutput).toEqual(expectedOutput);
|
||||
});
|
||||
|
||||
test("currentTenantUrl should return a URL with the tenant parameter", () => {
|
||||
const params = { tenant: "foo" };
|
||||
const expectedOutput = "/foo/";
|
||||
const actualOutput = UrlUtils.currentTenantUrl(params);
|
||||
expect(actualOutput).toEqual(expectedOutput);
|
||||
});
|
||||
|
||||
test("currentTenantUrl should normalize child paths through canonical legacy builder", () => {
|
||||
expect(UrlUtils.currentTenantUrl({ tenant: "foo" }, "/settings/profile/")).toEqual("/foo/settings/profile");
|
||||
});
|
||||
|
||||
test("currentEntityUrl should return a URL with the tenant and entity parameters", () => {
|
||||
const params = { tenant: "foo", entity: "bar" };
|
||||
const expectedOutput = "/foo/bar";
|
||||
const actualOutput = UrlUtils.currentEntityUrl(params);
|
||||
expect(actualOutput).toEqual(expectedOutput);
|
||||
});
|
||||
|
||||
test("replaceVariables should replace the :tenant variable in a URL with the tenant parameter", () => {
|
||||
const params = { tenant: "foo" };
|
||||
const input = "/api/:tenant/foo";
|
||||
const expectedOutput = "/api/foo/foo";
|
||||
const actualOutput = UrlUtils.replaceVariables(params, input);
|
||||
expect(actualOutput).toEqual(expectedOutput);
|
||||
});
|
||||
|
||||
test("slugify should convert a string into a URL-friendly slug", () => {
|
||||
const input = "Hello, world!";
|
||||
const expectedOutput = "hello-world";
|
||||
const actualOutput = UrlUtils.slugify(input);
|
||||
expect(actualOutput).toEqual(expectedOutput);
|
||||
});
|
||||
|
||||
test("getParentRoute should return the parent route of a given URL", () => {
|
||||
const input = "/foo/bar/baz";
|
||||
const expectedOutput = "/foo/bar";
|
||||
const actualOutput = UrlUtils.getParentRoute(input);
|
||||
expect(actualOutput).toEqual(expectedOutput);
|
||||
});
|
||||
|
||||
test("getModulePath should keep legacy tenant module rules through canonical builders", () => {
|
||||
expect(UrlUtils.getModulePath({ tenant: "foo" }, "entities/contact")).toEqual("/foo/settings/entities/contact");
|
||||
expect(UrlUtils.getModulePath({ tenant: "foo" }, "api/keys")).toEqual("/foo/settings/api/keys");
|
||||
expect(UrlUtils.getModulePath({ tenant: "foo" }, "workflow-engine/workflows")).toEqual("/foo/workflow-engine/workflows");
|
||||
expect(UrlUtils.getModulePath({}, "accounts")).toEqual("/accounts");
|
||||
});
|
||||
|
||||
describe("feature URL contracts", () => {
|
||||
const tenantParams = { tenant: "acme" };
|
||||
|
||||
test("Rows and Groups keep tenant and grouped entity paths", () => {
|
||||
expect(UrlUtils.currentTenantUrl(tenantParams, "contacts")).toEqual("/acme/contacts");
|
||||
expect(UrlUtils.currentTenantUrl(tenantParams, "g/sales/contacts")).toEqual("/acme/g/sales/contacts");
|
||||
expect(UrlUtils.currentEntityUrl({ ...tenantParams, entity: "contacts" })).toEqual("/acme/contacts");
|
||||
});
|
||||
|
||||
test("Workflow Engine remains a direct tenant module instead of settings", () => {
|
||||
expect(UrlUtils.getModulePath(tenantParams, "workflow-engine/workflows")).toEqual("/acme/workflow-engine/workflows");
|
||||
});
|
||||
|
||||
test("Portals and Sites remain direct tenant modules", () => {
|
||||
expect(UrlUtils.getModulePath(tenantParams, "portals/customer/pages")).toEqual("/acme/portals/customer/pages");
|
||||
expect(UrlUtils.getModulePath(tenantParams, "sites/storefront/site_123/settings")).toEqual("/acme/sites/storefront/site_123/settings");
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,105 @@
|
||||
import { Params } from "react-router";
|
||||
import slugify from "@sindresorhus/slugify";
|
||||
import { adminPath, appPath } from "./CanonicalUrlUtils";
|
||||
|
||||
const stripTrailingSlash = (str: string) => {
|
||||
return str.endsWith("/") ? str.slice(0, -1) : str;
|
||||
};
|
||||
|
||||
const currentTenantUrl = (params: Params, path?: string) => {
|
||||
const { tenant } = params;
|
||||
if (!tenant) {
|
||||
return "/";
|
||||
}
|
||||
return path ? appPath({ tenantSlug: tenant, path, mode: "host-aware" }) : `${appPath({ tenantSlug: tenant, mode: "host-aware" })}/`;
|
||||
};
|
||||
|
||||
const currentEntityUrl = (params: Params) => {
|
||||
const currentTenant = stripTrailingSlash(currentTenantUrl(params));
|
||||
return `${currentTenant}/${params.entity}`;
|
||||
};
|
||||
|
||||
const replaceVariables = (params: Params, path?: string) => {
|
||||
return path?.replace(":tenant", params.tenant ?? "");
|
||||
};
|
||||
|
||||
// https://mhagemann.medium.com/the-ultimate-way-to-slugify-a-url-string-in-javascript-b8e4a0d849e1
|
||||
// const slugify = (str: string, max: number = 100) => {
|
||||
// const a = "àáâäæãåāăąçćčđďèéêëēėęěğǵḧîïíīįìıİłḿñńǹňôöòóœøōõőṕŕřßśšşșťțûüùúūǘůűųẃẍÿýžźż·/_,:;";
|
||||
// const b = "aaaaaaaaaacccddeeeeeeeegghiiiiiiiilmnnnnoooooooooprrsssssttuuuuuuuuuwxyyzzz------";
|
||||
// const p = new RegExp(a.split("").join("|"), "g");
|
||||
|
||||
// return (
|
||||
// str
|
||||
// .toString()
|
||||
// .toLowerCase()
|
||||
// .replace(/\s+/g, "-") // Replace spaces with -
|
||||
// .replace(p, (c) => b.charAt(a.indexOf(c))) // Replace special characters
|
||||
// .replace(/&/g, "-and-") // Replace & with 'and'
|
||||
// // .replace(/[^\w\-]+/g, "") // Remove all non-word characters
|
||||
// // eslint-disable-next-line no-useless-escape
|
||||
// .replace(/\-\-+/g, "-") // Replace multiple - with single -
|
||||
// .replace(/^-+/, "") // Trim - from start of text
|
||||
// .replace(/-+$/, "")
|
||||
// ); // Trim - from end of text
|
||||
// };
|
||||
|
||||
function getParentRoute(pathname: string) {
|
||||
const url = stripTrailingSlash(pathname);
|
||||
const parentRoute = url.substring(0, url.lastIndexOf("/"));
|
||||
return parentRoute;
|
||||
}
|
||||
|
||||
function getModulePath(params: Params, path: string) {
|
||||
if (params.tenant) {
|
||||
let modulePath = path;
|
||||
if (path.startsWith("entities")) {
|
||||
modulePath = `settings/${path}`;
|
||||
} else if (path.startsWith("api")) {
|
||||
modulePath = `settings/${path}`;
|
||||
} else if (path.startsWith("workflow-engine")) {
|
||||
modulePath = path;
|
||||
} else if (path.startsWith("logs")) {
|
||||
modulePath = `settings/${path}`;
|
||||
}
|
||||
return appPath({ tenantSlug: params.tenant, path: modulePath, mode: "host-aware" });
|
||||
}
|
||||
return adminPath(path, { mode: "host-aware" });
|
||||
}
|
||||
|
||||
function join(...paths: string[]) {
|
||||
return paths.join("/").replace(/\/+/g, "/");
|
||||
}
|
||||
|
||||
function searchParamsToString({ type, searchParams }: { type: "string" | "object"; searchParams: URLSearchParams }) {
|
||||
searchParams.delete("entity");
|
||||
searchParams.delete("id");
|
||||
function paramsToObject(entries: any) {
|
||||
const result: any = {};
|
||||
for (const [key, value] of entries) {
|
||||
// each 'entry' is a [key, value] tupple
|
||||
result[key] = value;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
const entries = searchParams.entries();
|
||||
if (type === "object") {
|
||||
//{abc:"foo",def:"[asf]",xyz:"5"}
|
||||
const asObject = paramsToObject(entries);
|
||||
return JSON.stringify(asObject);
|
||||
}
|
||||
// abc=foo&def=[asf]&xyz=5
|
||||
return searchParams.toString();
|
||||
}
|
||||
|
||||
export default {
|
||||
currentTenantUrl,
|
||||
currentEntityUrl,
|
||||
stripTrailingSlash,
|
||||
slugify,
|
||||
replaceVariables,
|
||||
getParentRoute,
|
||||
getModulePath,
|
||||
join,
|
||||
searchParamsToString,
|
||||
};
|
||||
@@ -0,0 +1,82 @@
|
||||
import type { TenantUser } from "@toolctrl/db/prisma-browser";
|
||||
import { TenantUserType } from "~/application/enums/tenants/TenantUserType";
|
||||
|
||||
export const avatarText = (user: { firstName: string | null; lastName: string | null; email: string }): string => {
|
||||
if (user) {
|
||||
if (user.firstName && user.lastName) {
|
||||
if (user.firstName.length > 0 && user.lastName.length > 0) {
|
||||
return (user.firstName[0] + user.lastName[0]).toUpperCase();
|
||||
} else if (user.firstName.length > 1) {
|
||||
return user.firstName.substring(0, 2).toUpperCase();
|
||||
} else if (user.email.length > 1) {
|
||||
return user.email.substring(0, 2).toUpperCase();
|
||||
}
|
||||
} else if (user.firstName) {
|
||||
return user.firstName.substring(0, 2).toUpperCase();
|
||||
} else if (user.email) {
|
||||
return user.email.substring(0, 2).toUpperCase();
|
||||
}
|
||||
}
|
||||
return "--";
|
||||
};
|
||||
|
||||
export function getTenantPrefix(item: { name: string }) {
|
||||
const words = item.name.split(" ");
|
||||
if (words.length > 1) {
|
||||
return (words[0].substring(0, 1) + words[1].substring(0, 1)).toUpperCase();
|
||||
}
|
||||
if (item.name.length > 1) {
|
||||
return item.name.substring(0, 2).toUpperCase();
|
||||
}
|
||||
return item.name.substring(0, 1).toUpperCase();
|
||||
}
|
||||
|
||||
export const profileName = (
|
||||
user: { firstName: string | null; lastName: string | null; email: string | null } | null | undefined,
|
||||
options: { email?: boolean } = {}
|
||||
): string => {
|
||||
let profile = "";
|
||||
if (user) {
|
||||
if (user.firstName && user.lastName) {
|
||||
profile = user.firstName + " " + user.lastName;
|
||||
} else if (user.firstName) {
|
||||
profile = user.firstName;
|
||||
} else {
|
||||
profile = user.email || "";
|
||||
}
|
||||
}
|
||||
if (options.email && (user?.firstName || user?.lastName) && user?.email) {
|
||||
return profile + " (" + user?.email + ")";
|
||||
}
|
||||
return profile;
|
||||
};
|
||||
|
||||
export const getUserRoleClass = (item: TenantUser) => {
|
||||
switch (item.type as TenantUserType) {
|
||||
case TenantUserType.OWNER:
|
||||
return "bg-secondary text-foreground border border-border";
|
||||
case TenantUserType.ADMIN:
|
||||
return "bg-rose-50 border border-rose-200";
|
||||
case TenantUserType.MEMBER:
|
||||
return "bg-blue-50 border border-blue-200";
|
||||
}
|
||||
};
|
||||
|
||||
export const fullName = (user: { firstName: string | null; lastName: string | null; email: string } | null): string => {
|
||||
if (user) {
|
||||
if (user.firstName && user.lastName) {
|
||||
return user.firstName + " " + user.lastName;
|
||||
} else {
|
||||
return user.firstName ?? "";
|
||||
}
|
||||
}
|
||||
return "";
|
||||
};
|
||||
|
||||
export default {
|
||||
avatarText,
|
||||
profileName,
|
||||
getTenantPrefix,
|
||||
getUserRoleClass,
|
||||
fullName,
|
||||
};
|
||||
@@ -0,0 +1,8 @@
|
||||
export {
|
||||
avatarText,
|
||||
fullName,
|
||||
getTenantPrefix,
|
||||
getUserRoleClass,
|
||||
profileName,
|
||||
} from "./UserDisplayUtils";
|
||||
export { default } from "./UserDisplayUtils";
|
||||
+93
@@ -0,0 +1,93 @@
|
||||
import type { TFunction } from "i18next";
|
||||
import MailChecker from "mailchecker";
|
||||
import { validatePassword as validatePolicyPassword } from "~/services/auth/password-policy.server";
|
||||
|
||||
export const validateEmail = (email: unknown) => {
|
||||
const regexp = new RegExp(
|
||||
// eslint-disable-next-line no-useless-escape
|
||||
/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
|
||||
);
|
||||
if (typeof email !== "string" || email.length < 5 || !regexp.test(email) || email.length > 100) {
|
||||
return false;
|
||||
}
|
||||
if (!MailChecker.isValid(email)) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
};
|
||||
|
||||
/**
|
||||
* Presence-only check used by the login form to short-circuit before the
|
||||
* password-verify call. NOT a strength check — strength is enforced by
|
||||
* validatePolicyPassword() at password-write time so legacy users with
|
||||
* pre-policy passwords can still sign in. Anything outside the login form
|
||||
* MUST use {@link validatePasswords} or the underlying policy directly.
|
||||
*/
|
||||
export const validatePassword = (password: unknown) => {
|
||||
if (typeof password !== "string" || password.length < 4) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
};
|
||||
|
||||
/**
|
||||
* Confirm-then-validate helper for password-WRITE endpoints (register,
|
||||
* password reset, invitation acceptance). Runs the central policy; returns
|
||||
* undefined when the password is acceptable, or the first translated error
|
||||
* string when it isn't. Async because the policy may consult HIBP.
|
||||
*/
|
||||
export const validatePasswords = async ({
|
||||
password,
|
||||
passwordConfirm,
|
||||
email,
|
||||
t,
|
||||
}: {
|
||||
password?: string;
|
||||
passwordConfirm?: string;
|
||||
email?: string;
|
||||
t: TFunction;
|
||||
}): Promise<string | undefined> => {
|
||||
if (!password || !passwordConfirm) {
|
||||
return t("shared.isRequired", { 0: t("account.shared.password") });
|
||||
}
|
||||
if (password !== passwordConfirm) {
|
||||
return t("account.shared.passwordMismatch");
|
||||
}
|
||||
const result = await validatePolicyPassword(password, email ? { email } : {});
|
||||
if (!result.valid) {
|
||||
const firstError = result.errors[0];
|
||||
if (firstError) {
|
||||
return t(firstError.code, firstError.args ?? {});
|
||||
}
|
||||
return t("auth:errors.invalidPassword");
|
||||
}
|
||||
return undefined;
|
||||
};
|
||||
|
||||
export const isSuspicious = ({
|
||||
email,
|
||||
firstName,
|
||||
lastName,
|
||||
honeypot,
|
||||
}: {
|
||||
email: string;
|
||||
firstName?: string;
|
||||
lastName?: string;
|
||||
honeypot?: string;
|
||||
}): string | undefined => {
|
||||
if (honeypot) {
|
||||
return "Honeypot";
|
||||
} else if (email === firstName) {
|
||||
return "Email as first name";
|
||||
} else if (email === lastName) {
|
||||
return "Email as last name";
|
||||
}
|
||||
return undefined;
|
||||
};
|
||||
|
||||
export default {
|
||||
validateEmail,
|
||||
validatePassword,
|
||||
validatePasswords,
|
||||
isSuspicious,
|
||||
};
|
||||
Reference in new issue
Block a user