Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
146afc1369 | ||
|
|
ba66755a29 | ||
|
|
25c95356a1 | ||
|
|
9cc6c8d958 |
@@ -35,6 +35,7 @@ import {
|
|||||||
} from "@cdnmanager/db";
|
} from "@cdnmanager/db";
|
||||||
import { AppError } from "../errors.js";
|
import { AppError } from "../errors.js";
|
||||||
import {
|
import {
|
||||||
|
buildDnsPreviewRecords,
|
||||||
buildHostname,
|
buildHostname,
|
||||||
isValidIpv4,
|
isValidIpv4,
|
||||||
isValidIpv6,
|
isValidIpv6,
|
||||||
@@ -322,15 +323,30 @@ export const fleetRoutes: FastifyPluginAsync = async (app) => {
|
|||||||
const loc = listLocations(app.db).find((l) => l.id === q.locationId);
|
const loc = listLocations(app.db).find((l) => l.id === q.locationId);
|
||||||
if (!loc) throw AppError.notFound("location not found");
|
if (!loc) throw AppError.notFound("location not found");
|
||||||
const indexNum = Number(q.indexNum ?? "1") || 1;
|
const indexNum = Number(q.indexNum ?? "1") || 1;
|
||||||
|
const hostname = buildHostname({
|
||||||
|
template: q.template || zone.namingTemplate,
|
||||||
|
locationCode: loc.code,
|
||||||
|
role: q.role,
|
||||||
|
indexNum,
|
||||||
|
zoneName: zone.name,
|
||||||
|
providerTag: q.providerTag,
|
||||||
|
});
|
||||||
|
const aliases = q.nodeId
|
||||||
|
? listAliases(app.db, { zoneId: zone.id }).filter(
|
||||||
|
(a) => a.targetNodeId === q.nodeId,
|
||||||
|
)
|
||||||
|
: [];
|
||||||
|
const records = buildDnsPreviewRecords({
|
||||||
|
hostname,
|
||||||
|
ttl: zone.defaultTtl,
|
||||||
|
ipv4: q.ipv4,
|
||||||
|
ipv6: q.ipv6,
|
||||||
|
aliases: aliases.map((a) => ({ name: a.name, purpose: a.purpose })),
|
||||||
|
});
|
||||||
return {
|
return {
|
||||||
hostname: buildHostname({
|
hostname,
|
||||||
template: q.template || zone.namingTemplate,
|
ttl: zone.defaultTtl,
|
||||||
locationCode: loc.code,
|
records,
|
||||||
role: q.role,
|
|
||||||
indexNum,
|
|
||||||
zoneName: zone.name,
|
|
||||||
providerTag: q.providerTag,
|
|
||||||
}),
|
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -24,6 +24,56 @@ export function buildHostname(opts: {
|
|||||||
return host.replace(/\.$/, "");
|
return host.replace(/\.$/, "");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export type DnsPreviewRecord = {
|
||||||
|
type: "A" | "AAAA" | "CNAME";
|
||||||
|
name: string;
|
||||||
|
content: string;
|
||||||
|
ttl: number;
|
||||||
|
/** purpose / note (e.g. alias purpose) */
|
||||||
|
note?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
/** Desired-state DNS for node form preview (A/AAAA + CNAME aliases → hostname). */
|
||||||
|
export function buildDnsPreviewRecords(opts: {
|
||||||
|
hostname: string;
|
||||||
|
ttl: number;
|
||||||
|
ipv4?: string | null;
|
||||||
|
ipv6?: string | null;
|
||||||
|
aliases?: Array<{ name: string; purpose?: string | null }>;
|
||||||
|
}): DnsPreviewRecord[] {
|
||||||
|
const records: DnsPreviewRecord[] = [];
|
||||||
|
const ipv4 = opts.ipv4?.trim();
|
||||||
|
const ipv6 = opts.ipv6?.trim();
|
||||||
|
if (ipv4) {
|
||||||
|
records.push({
|
||||||
|
type: "A",
|
||||||
|
name: opts.hostname,
|
||||||
|
content: ipv4,
|
||||||
|
ttl: opts.ttl,
|
||||||
|
note: "dns-only",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if (ipv6) {
|
||||||
|
records.push({
|
||||||
|
type: "AAAA",
|
||||||
|
name: opts.hostname,
|
||||||
|
content: ipv6,
|
||||||
|
ttl: opts.ttl,
|
||||||
|
note: "dns-only",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
for (const alias of opts.aliases ?? []) {
|
||||||
|
records.push({
|
||||||
|
type: "CNAME",
|
||||||
|
name: alias.name,
|
||||||
|
content: opts.hostname,
|
||||||
|
ttl: opts.ttl,
|
||||||
|
note: alias.purpose ?? undefined,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return records;
|
||||||
|
}
|
||||||
|
|
||||||
export function normalizeFqdn(name: string): string {
|
export function normalizeFqdn(name: string): string {
|
||||||
return name.trim().toLowerCase().replace(/\.$/, "");
|
return name.trim().toLowerCase().replace(/\.$/, "");
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -112,5 +112,44 @@ describe("fleet api", () => {
|
|||||||
});
|
});
|
||||||
expect(topo.statusCode).toBe(200);
|
expect(topo.statusCode).toBe(200);
|
||||||
expect(topo.json().nodes).toHaveLength(1);
|
expect(topo.json().nodes).toHaveLength(1);
|
||||||
|
|
||||||
|
const preview = await app.inject({
|
||||||
|
method: "GET",
|
||||||
|
url: `/api/v1/naming/preview?${new URLSearchParams({
|
||||||
|
zoneId: zone.id,
|
||||||
|
locationId: msk.id,
|
||||||
|
role: "gw",
|
||||||
|
indexNum: "2",
|
||||||
|
ipv4: "198.51.100.10",
|
||||||
|
ipv6: "2001:db8::10",
|
||||||
|
nodeId: node.id,
|
||||||
|
})}`,
|
||||||
|
headers: authHeader,
|
||||||
|
});
|
||||||
|
expect(preview.statusCode).toBe(200);
|
||||||
|
const body = preview.json() as {
|
||||||
|
hostname: string;
|
||||||
|
records: Array<{ type: string; name: string; content: string }>;
|
||||||
|
};
|
||||||
|
expect(body.hostname).toBe("msk-gw02.rtnt.top");
|
||||||
|
expect(body.records).toEqual(
|
||||||
|
expect.arrayContaining([
|
||||||
|
expect.objectContaining({
|
||||||
|
type: "A",
|
||||||
|
name: "msk-gw02.rtnt.top",
|
||||||
|
content: "198.51.100.10",
|
||||||
|
}),
|
||||||
|
expect.objectContaining({
|
||||||
|
type: "AAAA",
|
||||||
|
name: "msk-gw02.rtnt.top",
|
||||||
|
content: "2001:db8::10",
|
||||||
|
}),
|
||||||
|
expect.objectContaining({
|
||||||
|
type: "CNAME",
|
||||||
|
name: "msk.rtnt.top",
|
||||||
|
content: "msk-gw02.rtnt.top",
|
||||||
|
}),
|
||||||
|
]),
|
||||||
|
);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -0,0 +1,134 @@
|
|||||||
|
'use client'
|
||||||
|
|
||||||
|
import * as React from 'react'
|
||||||
|
import { CheckIcon } from 'lucide-react'
|
||||||
|
|
||||||
|
import { cn } from '@cdnmanager/ui/lib/utils'
|
||||||
|
import {
|
||||||
|
Autocomplete,
|
||||||
|
AutocompleteContent,
|
||||||
|
AutocompleteEmpty,
|
||||||
|
AutocompleteInput,
|
||||||
|
AutocompleteItem,
|
||||||
|
AutocompleteList,
|
||||||
|
} from '@/components/reui/autocomplete'
|
||||||
|
import { TruncatedText } from '@/components/truncated-text'
|
||||||
|
|
||||||
|
export interface AutoCompleteOption {
|
||||||
|
value: string
|
||||||
|
label: string
|
||||||
|
/** Левый префикс (например флаг страны). */
|
||||||
|
leading?: React.ReactNode
|
||||||
|
}
|
||||||
|
|
||||||
|
interface AutoCompleteInputProps {
|
||||||
|
id?: string
|
||||||
|
value: string
|
||||||
|
onChange: (value: string) => void
|
||||||
|
options: AutoCompleteOption[]
|
||||||
|
placeholder?: string
|
||||||
|
searchPlaceholder?: string
|
||||||
|
emptyText?: string
|
||||||
|
className?: string
|
||||||
|
/** Показывать ли выбранный leading в поле (например флаг). */
|
||||||
|
showLeadingInInput?: boolean
|
||||||
|
/** Разрешать ли произвольный ввод (не только из списка). По умолчанию true. */
|
||||||
|
allowFreeText?: boolean
|
||||||
|
disabled?: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
export function AutoCompleteInput({
|
||||||
|
id,
|
||||||
|
value,
|
||||||
|
onChange,
|
||||||
|
options,
|
||||||
|
placeholder = 'Выбрать…',
|
||||||
|
searchPlaceholder,
|
||||||
|
emptyText = 'Ничего не найдено',
|
||||||
|
className,
|
||||||
|
showLeadingInInput = true,
|
||||||
|
allowFreeText = true,
|
||||||
|
disabled = false,
|
||||||
|
}: AutoCompleteInputProps) {
|
||||||
|
const trimmedValue = value.trim()
|
||||||
|
|
||||||
|
const selected = React.useMemo(
|
||||||
|
() => options.find((o) => o.value.toLowerCase() === trimmedValue.toLowerCase()),
|
||||||
|
[options, trimmedValue],
|
||||||
|
)
|
||||||
|
const leading = showLeadingInInput ? selected?.leading : undefined
|
||||||
|
|
||||||
|
const inputPlaceholder = searchPlaceholder ?? placeholder
|
||||||
|
|
||||||
|
const handleValueChange = React.useCallback(
|
||||||
|
(inputVal: string) => {
|
||||||
|
const q = inputVal.trim()
|
||||||
|
const match = options.find(
|
||||||
|
(o) =>
|
||||||
|
o.label.toLowerCase() === q.toLowerCase() ||
|
||||||
|
o.value.toLowerCase() === q.toLowerCase(),
|
||||||
|
)
|
||||||
|
if (match) {
|
||||||
|
onChange(match.value)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (allowFreeText) {
|
||||||
|
onChange(inputVal)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[options, onChange, allowFreeText],
|
||||||
|
)
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Autocomplete
|
||||||
|
items={options}
|
||||||
|
value={value}
|
||||||
|
onValueChange={handleValueChange}
|
||||||
|
itemToStringValue={(item) => item.label}
|
||||||
|
mode="list"
|
||||||
|
autoHighlight
|
||||||
|
openOnInputClick
|
||||||
|
disabled={disabled}
|
||||||
|
>
|
||||||
|
<div className="relative w-full">
|
||||||
|
{leading ? (
|
||||||
|
<span className="pointer-events-none absolute start-2.5 top-1/2 z-10 size-4 -translate-y-1/2 [&_svg]:size-full">
|
||||||
|
{leading}
|
||||||
|
</span>
|
||||||
|
) : null}
|
||||||
|
<AutocompleteInput
|
||||||
|
id={id}
|
||||||
|
placeholder={trimmedValue ? undefined : inputPlaceholder}
|
||||||
|
showTrigger
|
||||||
|
showClear={Boolean(trimmedValue)}
|
||||||
|
className={cn(leading && 'ps-8', className)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<AutocompleteContent>
|
||||||
|
<AutocompleteEmpty>{emptyText}</AutocompleteEmpty>
|
||||||
|
<AutocompleteList>
|
||||||
|
{(item) => {
|
||||||
|
const isSelected = item.value.toLowerCase() === trimmedValue.toLowerCase()
|
||||||
|
return (
|
||||||
|
<AutocompleteItem
|
||||||
|
key={item.value}
|
||||||
|
value={item}
|
||||||
|
className="gap-2.5 px-2 py-1.5"
|
||||||
|
>
|
||||||
|
{item.leading ? (
|
||||||
|
<span className="relative z-1 size-4 shrink-0">{item.leading}</span>
|
||||||
|
) : null}
|
||||||
|
<span className="relative z-1 min-w-0 flex-1">
|
||||||
|
<TruncatedText>{item.label}</TruncatedText>
|
||||||
|
</span>
|
||||||
|
{isSelected ? (
|
||||||
|
<CheckIcon className="relative z-1 size-4 shrink-0 opacity-60" />
|
||||||
|
) : null}
|
||||||
|
</AutocompleteItem>
|
||||||
|
)
|
||||||
|
}}
|
||||||
|
</AutocompleteList>
|
||||||
|
</AutocompleteContent>
|
||||||
|
</Autocomplete>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
import { cn } from '@cdnmanager/ui/lib/utils'
|
||||||
|
import { countryCodeFromName, getCountryFlagUrl } from '@/lib/country-labels'
|
||||||
|
|
||||||
|
interface CountryFlagProps {
|
||||||
|
code?: string
|
||||||
|
country?: string
|
||||||
|
className?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export function CountryFlag({ code, country, className }: CountryFlagProps) {
|
||||||
|
const resolvedCode = code ?? (country ? countryCodeFromName(country) : undefined)
|
||||||
|
const url = getCountryFlagUrl(resolvedCode)
|
||||||
|
if (!url) return null
|
||||||
|
|
||||||
|
return (
|
||||||
|
<img
|
||||||
|
src={url}
|
||||||
|
alt=""
|
||||||
|
className={cn('size-4 shrink-0 rounded-full object-cover', className)}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -30,6 +30,13 @@ async function handoffOnUnauthorized(): Promise<void> {
|
|||||||
redirectToPortalLogin(`${window.location.origin}/auth/callback`)
|
redirectToPortalLogin(`${window.location.origin}/auth/callback`)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
// Cooldown / recent handoff — stop SSO storm (wrong JWT secret / issuer).
|
||||||
|
if (cfg.required || isAuthEnabled()) {
|
||||||
|
window.location.assign(
|
||||||
|
`${window.location.origin}/auth/callback?error=jwt_rejected`,
|
||||||
|
)
|
||||||
|
return
|
||||||
|
}
|
||||||
if (!cfg.required && !isAuthEnabled()) {
|
if (!cfg.required && !isAuthEnabled()) {
|
||||||
window.location.href = '/login'
|
window.location.href = '/login'
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -62,5 +62,11 @@ export function getAppUrl(
|
|||||||
export function getCurrentApp(
|
export function getCurrentApp(
|
||||||
config: AppSwitcherConfig = DEFAULT_APP_SWITCHER_CONFIG,
|
config: AppSwitcherConfig = DEFAULT_APP_SWITCHER_CONFIG,
|
||||||
): AppSwitcherEntry {
|
): AppSwitcherEntry {
|
||||||
return config.apps.find((app) => app.id === CURRENT_APP_ID) ?? config.apps[0]!
|
const current = config.apps.find((app) => app.id === CURRENT_APP_ID)
|
||||||
|
if (current) return current
|
||||||
|
if (config.apps[0]) return config.apps[0]
|
||||||
|
return (
|
||||||
|
DEFAULT_APP_SWITCHER_CONFIG.apps.find((a) => a.id === CURRENT_APP_ID) ??
|
||||||
|
DEFAULT_APP_SWITCHER_CONFIG.apps[0]!
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -255,5 +255,5 @@ export function firstAllowedPath(): string {
|
|||||||
const perm = permissionForPath(path)
|
const perm = permissionForPath(path)
|
||||||
if (!perm || can(perm)) return path
|
if (!perm || can(perm)) return path
|
||||||
}
|
}
|
||||||
return '/'
|
return '/access-denied'
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,29 @@
|
|||||||
|
/** ISO → русское название (seed fleet locations). */
|
||||||
|
const COUNTRY_NAME_BY_CODE: Record<string, string> = {
|
||||||
|
RU: 'Россия',
|
||||||
|
DE: 'Германия',
|
||||||
|
NL: 'Нидерланды',
|
||||||
|
FI: 'Финляндия',
|
||||||
|
FR: 'Франция',
|
||||||
|
}
|
||||||
|
|
||||||
|
const COUNTRY_CODE_BY_NAME: Record<string, string> = Object.fromEntries(
|
||||||
|
Object.entries(COUNTRY_NAME_BY_CODE).map(([code, name]) => [name.toLowerCase(), code]),
|
||||||
|
)
|
||||||
|
|
||||||
|
export function countryNameFromCode(code: string | null | undefined): string {
|
||||||
|
if (!code) return ''
|
||||||
|
return COUNTRY_NAME_BY_CODE[code.toUpperCase()] ?? code
|
||||||
|
}
|
||||||
|
|
||||||
|
export function countryCodeFromName(name: string | null | undefined): string {
|
||||||
|
if (!name?.trim()) return ''
|
||||||
|
const trimmed = name.trim()
|
||||||
|
if (trimmed.length === 2) return trimmed.toUpperCase()
|
||||||
|
return COUNTRY_CODE_BY_NAME[trimmed.toLowerCase()] ?? ''
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getCountryFlagUrl(code?: string): string | undefined {
|
||||||
|
if (!code || code.length !== 2) return undefined
|
||||||
|
return `https://flagcdn.com/${code.toLowerCase()}.svg`
|
||||||
|
}
|
||||||
@@ -180,6 +180,9 @@ export async function previewHostname(params: {
|
|||||||
role: string
|
role: string
|
||||||
indexNum?: number
|
indexNum?: number
|
||||||
providerTag?: string
|
providerTag?: string
|
||||||
|
ipv4?: string
|
||||||
|
ipv6?: string
|
||||||
|
nodeId?: string
|
||||||
}) {
|
}) {
|
||||||
const p = new URLSearchParams({
|
const p = new URLSearchParams({
|
||||||
zoneId: params.zoneId,
|
zoneId: params.zoneId,
|
||||||
@@ -188,5 +191,18 @@ export async function previewHostname(params: {
|
|||||||
indexNum: String(params.indexNum ?? 1),
|
indexNum: String(params.indexNum ?? 1),
|
||||||
})
|
})
|
||||||
if (params.providerTag) p.set('providerTag', params.providerTag)
|
if (params.providerTag) p.set('providerTag', params.providerTag)
|
||||||
return api.get<{ hostname: string }>(`/api/v1/naming/preview?${p}`)
|
if (params.ipv4) p.set('ipv4', params.ipv4)
|
||||||
|
if (params.ipv6) p.set('ipv6', params.ipv6)
|
||||||
|
if (params.nodeId) p.set('nodeId', params.nodeId)
|
||||||
|
return api.get<{
|
||||||
|
hostname: string
|
||||||
|
ttl: number
|
||||||
|
records: Array<{
|
||||||
|
type: 'A' | 'AAAA' | 'CNAME'
|
||||||
|
name: string
|
||||||
|
content: string
|
||||||
|
ttl: number
|
||||||
|
note?: string
|
||||||
|
}>
|
||||||
|
}>(`/api/v1/naming/preview?${p}`)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -10,6 +10,7 @@
|
|||||||
|
|
||||||
import { Route as rootRouteImport } from './routes/__root'
|
import { Route as rootRouteImport } from './routes/__root'
|
||||||
import { Route as LoginRouteImport } from './routes/login'
|
import { Route as LoginRouteImport } from './routes/login'
|
||||||
|
import { Route as AccessDeniedRouteImport } from './routes/access-denied'
|
||||||
import { Route as AuthRouteImport } from './routes/_auth'
|
import { Route as AuthRouteImport } from './routes/_auth'
|
||||||
import { Route as AuthIndexRouteImport } from './routes/_auth/index'
|
import { Route as AuthIndexRouteImport } from './routes/_auth/index'
|
||||||
import { Route as AuthCallbackRouteImport } from './routes/auth.callback'
|
import { Route as AuthCallbackRouteImport } from './routes/auth.callback'
|
||||||
@@ -28,6 +29,11 @@ const LoginRoute = LoginRouteImport.update({
|
|||||||
path: '/login',
|
path: '/login',
|
||||||
getParentRoute: () => rootRouteImport,
|
getParentRoute: () => rootRouteImport,
|
||||||
} as any)
|
} as any)
|
||||||
|
const AccessDeniedRoute = AccessDeniedRouteImport.update({
|
||||||
|
id: '/access-denied',
|
||||||
|
path: '/access-denied',
|
||||||
|
getParentRoute: () => rootRouteImport,
|
||||||
|
} as any)
|
||||||
const AuthRoute = AuthRouteImport.update({
|
const AuthRoute = AuthRouteImport.update({
|
||||||
id: '/_auth',
|
id: '/_auth',
|
||||||
getParentRoute: () => rootRouteImport,
|
getParentRoute: () => rootRouteImport,
|
||||||
@@ -91,6 +97,7 @@ const AuthSettingsAppearanceRoute = AuthSettingsAppearanceRouteImport.update({
|
|||||||
|
|
||||||
export interface FileRoutesByFullPath {
|
export interface FileRoutesByFullPath {
|
||||||
'/': typeof AuthIndexRoute
|
'/': typeof AuthIndexRoute
|
||||||
|
'/access-denied': typeof AccessDeniedRoute
|
||||||
'/login': typeof LoginRoute
|
'/login': typeof LoginRoute
|
||||||
'/settings': typeof AuthSettingsRouteRouteWithChildren
|
'/settings': typeof AuthSettingsRouteRouteWithChildren
|
||||||
'/aliases': typeof AuthAliasesRoute
|
'/aliases': typeof AuthAliasesRoute
|
||||||
@@ -104,6 +111,7 @@ export interface FileRoutesByFullPath {
|
|||||||
'/settings/': typeof AuthSettingsIndexRoute
|
'/settings/': typeof AuthSettingsIndexRoute
|
||||||
}
|
}
|
||||||
export interface FileRoutesByTo {
|
export interface FileRoutesByTo {
|
||||||
|
'/access-denied': typeof AccessDeniedRoute
|
||||||
'/login': typeof LoginRoute
|
'/login': typeof LoginRoute
|
||||||
'/aliases': typeof AuthAliasesRoute
|
'/aliases': typeof AuthAliasesRoute
|
||||||
'/nodes': typeof AuthNodesRoute
|
'/nodes': typeof AuthNodesRoute
|
||||||
@@ -119,6 +127,7 @@ export interface FileRoutesByTo {
|
|||||||
export interface FileRoutesById {
|
export interface FileRoutesById {
|
||||||
__root__: typeof rootRouteImport
|
__root__: typeof rootRouteImport
|
||||||
'/_auth': typeof AuthRouteWithChildren
|
'/_auth': typeof AuthRouteWithChildren
|
||||||
|
'/access-denied': typeof AccessDeniedRoute
|
||||||
'/login': typeof LoginRoute
|
'/login': typeof LoginRoute
|
||||||
'/_auth/settings': typeof AuthSettingsRouteRouteWithChildren
|
'/_auth/settings': typeof AuthSettingsRouteRouteWithChildren
|
||||||
'/_auth/aliases': typeof AuthAliasesRoute
|
'/_auth/aliases': typeof AuthAliasesRoute
|
||||||
@@ -136,6 +145,7 @@ export interface FileRouteTypes {
|
|||||||
fileRoutesByFullPath: FileRoutesByFullPath
|
fileRoutesByFullPath: FileRoutesByFullPath
|
||||||
fullPaths:
|
fullPaths:
|
||||||
| '/'
|
| '/'
|
||||||
|
| '/access-denied'
|
||||||
| '/login'
|
| '/login'
|
||||||
| '/settings'
|
| '/settings'
|
||||||
| '/aliases'
|
| '/aliases'
|
||||||
@@ -149,6 +159,7 @@ export interface FileRouteTypes {
|
|||||||
| '/settings/'
|
| '/settings/'
|
||||||
fileRoutesByTo: FileRoutesByTo
|
fileRoutesByTo: FileRoutesByTo
|
||||||
to:
|
to:
|
||||||
|
| '/access-denied'
|
||||||
| '/login'
|
| '/login'
|
||||||
| '/aliases'
|
| '/aliases'
|
||||||
| '/nodes'
|
| '/nodes'
|
||||||
@@ -163,6 +174,7 @@ export interface FileRouteTypes {
|
|||||||
id:
|
id:
|
||||||
| '__root__'
|
| '__root__'
|
||||||
| '/_auth'
|
| '/_auth'
|
||||||
|
| '/access-denied'
|
||||||
| '/login'
|
| '/login'
|
||||||
| '/_auth/settings'
|
| '/_auth/settings'
|
||||||
| '/_auth/aliases'
|
| '/_auth/aliases'
|
||||||
@@ -179,6 +191,7 @@ export interface FileRouteTypes {
|
|||||||
}
|
}
|
||||||
export interface RootRouteChildren {
|
export interface RootRouteChildren {
|
||||||
AuthRoute: typeof AuthRouteWithChildren
|
AuthRoute: typeof AuthRouteWithChildren
|
||||||
|
AccessDeniedRoute: typeof AccessDeniedRoute
|
||||||
LoginRoute: typeof LoginRoute
|
LoginRoute: typeof LoginRoute
|
||||||
AuthCallbackRoute: typeof AuthCallbackRoute
|
AuthCallbackRoute: typeof AuthCallbackRoute
|
||||||
}
|
}
|
||||||
@@ -192,6 +205,13 @@ declare module '@tanstack/react-router' {
|
|||||||
preLoaderRoute: typeof LoginRouteImport
|
preLoaderRoute: typeof LoginRouteImport
|
||||||
parentRoute: typeof rootRouteImport
|
parentRoute: typeof rootRouteImport
|
||||||
}
|
}
|
||||||
|
'/access-denied': {
|
||||||
|
id: '/access-denied'
|
||||||
|
path: '/access-denied'
|
||||||
|
fullPath: '/access-denied'
|
||||||
|
preLoaderRoute: typeof AccessDeniedRouteImport
|
||||||
|
parentRoute: typeof rootRouteImport
|
||||||
|
}
|
||||||
'/_auth': {
|
'/_auth': {
|
||||||
id: '/_auth'
|
id: '/_auth'
|
||||||
path: ''
|
path: ''
|
||||||
@@ -318,6 +338,7 @@ const AuthRouteWithChildren = AuthRoute._addFileChildren(AuthRouteChildren)
|
|||||||
|
|
||||||
const rootRouteChildren: RootRouteChildren = {
|
const rootRouteChildren: RootRouteChildren = {
|
||||||
AuthRoute: AuthRouteWithChildren,
|
AuthRoute: AuthRouteWithChildren,
|
||||||
|
AccessDeniedRoute: AccessDeniedRoute,
|
||||||
LoginRoute: LoginRoute,
|
LoginRoute: LoginRoute,
|
||||||
AuthCallbackRoute: AuthCallbackRoute,
|
AuthCallbackRoute: AuthCallbackRoute,
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -16,7 +16,8 @@ export const Route = createRootRouteWithContext<RouterContext>()({
|
|||||||
beforeLoad: async ({ location }) => {
|
beforeLoad: async ({ location }) => {
|
||||||
const isLogin = location.pathname === '/login'
|
const isLogin = location.pathname === '/login'
|
||||||
const isCallback = location.pathname === '/auth/callback'
|
const isCallback = location.pathname === '/auth/callback'
|
||||||
if (isCallback) return
|
const isAccessDenied = location.pathname === '/access-denied'
|
||||||
|
if (isCallback || isAccessDenied) return
|
||||||
|
|
||||||
const cfg = await ensureAuthConfig()
|
const cfg = await ensureAuthConfig()
|
||||||
const token = getToken()
|
const token = getToken()
|
||||||
|
|||||||
@@ -30,16 +30,19 @@ export const Route = createFileRoute('/_auth')({
|
|||||||
await new Promise(() => {})
|
await new Promise(() => {})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
// NEVER redirect to `/` here — `/` is under `_auth` and causes an infinite loop
|
||||||
|
// (browser: «Страница не отвечает»).
|
||||||
if (!claims.apps.includes('cdn')) {
|
if (!claims.apps.includes('cdn')) {
|
||||||
throw redirect({ to: '/' })
|
throw redirect({ to: '/access-denied' })
|
||||||
}
|
}
|
||||||
|
|
||||||
const perm = permissionForPath(location.pathname)
|
const perm = permissionForPath(location.pathname)
|
||||||
if (perm && !can(perm)) {
|
if (perm && !can(perm)) {
|
||||||
const fallback = firstAllowedPath()
|
const fallback = firstAllowedPath()
|
||||||
if (fallback !== location.pathname) {
|
if (fallback === '/access-denied' || fallback === location.pathname) {
|
||||||
throw redirect({ to: fallback as '/' })
|
throw redirect({ to: '/access-denied' })
|
||||||
}
|
}
|
||||||
|
throw redirect({ to: fallback as '/' })
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
component: () => (
|
component: () => (
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { createFileRoute, Link } from '@tanstack/react-router'
|
import { createFileRoute, Link } from '@tanstack/react-router'
|
||||||
import { useMemo, useState } from 'react'
|
import { useEffect, useMemo, useState } from 'react'
|
||||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||||
import { useForm } from 'react-hook-form'
|
import { useForm } from 'react-hook-form'
|
||||||
import { zodResolver } from '@hookform/resolvers/zod'
|
import { zodResolver } from '@hookform/resolvers/zod'
|
||||||
@@ -25,6 +25,13 @@ import { Button } from '@cdnmanager/ui/components/button'
|
|||||||
import { Input } from '@cdnmanager/ui/components/input'
|
import { Input } from '@cdnmanager/ui/components/input'
|
||||||
import { Label } from '@cdnmanager/ui/components/label'
|
import { Label } from '@cdnmanager/ui/components/label'
|
||||||
import { SelectField } from '@/components/select-field'
|
import { SelectField } from '@/components/select-field'
|
||||||
|
import { AutoCompleteInput } from '@/components/auto-complete-input'
|
||||||
|
import { CountryFlag } from '@/components/country-flag'
|
||||||
|
import { FormFieldSimple } from '@/components/form-field'
|
||||||
|
import {
|
||||||
|
countryCodeFromName,
|
||||||
|
countryNameFromCode,
|
||||||
|
} from '@/lib/country-labels'
|
||||||
import { queryClient } from '@/lib/query-client'
|
import { queryClient } from '@/lib/query-client'
|
||||||
import {
|
import {
|
||||||
createNode,
|
createNode,
|
||||||
@@ -79,7 +86,18 @@ function NodesPage() {
|
|||||||
const [sheetOpen, setSheetOpen] = useState(false)
|
const [sheetOpen, setSheetOpen] = useState(false)
|
||||||
const [editing, setEditing] = useState<Node | null>(null)
|
const [editing, setEditing] = useState<Node | null>(null)
|
||||||
const [deleteId, setDeleteId] = useState<string | null>(null)
|
const [deleteId, setDeleteId] = useState<string | null>(null)
|
||||||
const [preview, setPreview] = useState('')
|
const [previewHost, setPreviewHost] = useState('')
|
||||||
|
const [previewRecords, setPreviewRecords] = useState<
|
||||||
|
Array<{
|
||||||
|
type: 'A' | 'AAAA' | 'CNAME'
|
||||||
|
name: string
|
||||||
|
content: string
|
||||||
|
ttl: number
|
||||||
|
note?: string
|
||||||
|
}>
|
||||||
|
>([])
|
||||||
|
const [countryName, setCountryName] = useState('')
|
||||||
|
const [locationQuery, setLocationQuery] = useState('')
|
||||||
|
|
||||||
const form = useForm<FormValues>({
|
const form = useForm<FormValues>({
|
||||||
resolver: zodResolver(formSchema),
|
resolver: zodResolver(formSchema),
|
||||||
@@ -101,23 +119,112 @@ function NodesPage() {
|
|||||||
const watchRole = form.watch('role')
|
const watchRole = form.watch('role')
|
||||||
const watchIndex = form.watch('indexNum')
|
const watchIndex = form.watch('indexNum')
|
||||||
const watchProvider = form.watch('providerTag')
|
const watchProvider = form.watch('providerTag')
|
||||||
|
const watchIpv4 = form.watch('ipv4')
|
||||||
|
const watchIpv6 = form.watch('ipv6')
|
||||||
|
|
||||||
async function refreshPreview() {
|
const countryCode = countryCodeFromName(countryName)
|
||||||
if (!watchZone || !watchLoc || !watchRole) return
|
|
||||||
|
const countryOptions = useMemo(() => {
|
||||||
|
const codes = new Set<string>()
|
||||||
|
for (const loc of locations) {
|
||||||
|
if (loc.country) codes.add(loc.country)
|
||||||
|
}
|
||||||
|
return [...codes]
|
||||||
|
.map((code) => {
|
||||||
|
const name = countryNameFromCode(code)
|
||||||
|
return {
|
||||||
|
value: name,
|
||||||
|
label: name,
|
||||||
|
leading: <CountryFlag code={code} country={name} />,
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.sort((a, b) => a.label.localeCompare(b.label, 'ru'))
|
||||||
|
}, [locations])
|
||||||
|
|
||||||
|
const locationOptions = useMemo(() => {
|
||||||
|
if (!countryCode) return []
|
||||||
|
return locations
|
||||||
|
.filter((l) => l.country === countryCode)
|
||||||
|
.map((l) => ({
|
||||||
|
value: `${l.code} — ${l.name}`,
|
||||||
|
label: `${l.code} — ${l.name}`,
|
||||||
|
}))
|
||||||
|
}, [locations, countryCode])
|
||||||
|
|
||||||
|
function locationLabel(locationId: string): string {
|
||||||
|
const loc = locations.find((l) => l.id === locationId)
|
||||||
|
return loc ? `${loc.code} — ${loc.name}` : ''
|
||||||
|
}
|
||||||
|
|
||||||
|
function countryNameForLocationId(locationId: string): string {
|
||||||
|
const code = locations.find((l) => l.id === locationId)?.country
|
||||||
|
return countryNameFromCode(code)
|
||||||
|
}
|
||||||
|
|
||||||
|
function locationIdFromDisplay(display: string): string {
|
||||||
|
const q = display.trim().toLowerCase()
|
||||||
|
if (!q) return ''
|
||||||
|
const match = locations.find((l) => {
|
||||||
|
if (countryCode && l.country !== countryCode) return false
|
||||||
|
const label = `${l.code} — ${l.name}`.toLowerCase()
|
||||||
|
return label === q || l.code.toLowerCase() === q || l.name.toLowerCase() === q
|
||||||
|
})
|
||||||
|
return match?.id ?? ''
|
||||||
|
}
|
||||||
|
|
||||||
|
async function refreshPreview(
|
||||||
|
overrides?: Partial<{
|
||||||
|
zoneId: string
|
||||||
|
locationId: string
|
||||||
|
role: NodeRole
|
||||||
|
indexNum: number
|
||||||
|
providerTag: string
|
||||||
|
ipv4: string
|
||||||
|
ipv6: string
|
||||||
|
}>,
|
||||||
|
) {
|
||||||
|
const values = { ...form.getValues(), ...overrides }
|
||||||
|
if (!values.zoneId || !values.locationId || !values.role) {
|
||||||
|
setPreviewHost('')
|
||||||
|
setPreviewRecords([])
|
||||||
|
return
|
||||||
|
}
|
||||||
try {
|
try {
|
||||||
const res = await previewHostname({
|
const res = await previewHostname({
|
||||||
zoneId: watchZone,
|
zoneId: values.zoneId,
|
||||||
locationId: watchLoc,
|
locationId: values.locationId,
|
||||||
role: watchRole,
|
role: values.role,
|
||||||
indexNum: Number(watchIndex) || 1,
|
indexNum: Number(values.indexNum) || 1,
|
||||||
providerTag: watchProvider || undefined,
|
providerTag: values.providerTag || undefined,
|
||||||
|
ipv4: values.ipv4 || undefined,
|
||||||
|
ipv6: values.ipv6 || undefined,
|
||||||
|
nodeId: editing?.id,
|
||||||
})
|
})
|
||||||
setPreview(res.hostname)
|
setPreviewHost(res.hostname)
|
||||||
|
setPreviewRecords(res.records ?? [])
|
||||||
} catch {
|
} catch {
|
||||||
setPreview('')
|
setPreviewHost('')
|
||||||
|
setPreviewRecords([])
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!sheetOpen) return
|
||||||
|
void refreshPreview()
|
||||||
|
// form + editing captured via refreshPreview closures; watches drive re-run
|
||||||
|
// eslint-disable-next-line react-hooks/exhaustive-deps -- intentional field watches
|
||||||
|
}, [
|
||||||
|
sheetOpen,
|
||||||
|
watchZone,
|
||||||
|
watchLoc,
|
||||||
|
watchRole,
|
||||||
|
watchIndex,
|
||||||
|
watchProvider,
|
||||||
|
watchIpv4,
|
||||||
|
watchIpv6,
|
||||||
|
editing?.id,
|
||||||
|
])
|
||||||
|
|
||||||
const saveMutation = useMutation({
|
const saveMutation = useMutation({
|
||||||
mutationFn: async (values: FormValues) => {
|
mutationFn: async (values: FormValues) => {
|
||||||
if (editing) {
|
if (editing) {
|
||||||
@@ -148,6 +255,8 @@ function NodesPage() {
|
|||||||
toast.success(editing ? 'Нода обновлена' : 'Нода создана')
|
toast.success(editing ? 'Нода обновлена' : 'Нода создана')
|
||||||
setSheetOpen(false)
|
setSheetOpen(false)
|
||||||
setEditing(null)
|
setEditing(null)
|
||||||
|
setCountryName('')
|
||||||
|
setLocationQuery('')
|
||||||
form.reset()
|
form.reset()
|
||||||
void qc.invalidateQueries({ queryKey: ['fleet'] })
|
void qc.invalidateQueries({ queryKey: ['fleet'] })
|
||||||
},
|
},
|
||||||
@@ -267,6 +376,8 @@ function NodesPage() {
|
|||||||
onClick={() => {
|
onClick={() => {
|
||||||
const n = row.original
|
const n = row.original
|
||||||
setEditing(n)
|
setEditing(n)
|
||||||
|
setCountryName(countryNameForLocationId(n.locationId))
|
||||||
|
setLocationQuery(locationLabel(n.locationId))
|
||||||
form.reset({
|
form.reset({
|
||||||
zoneId: n.zoneId,
|
zoneId: n.zoneId,
|
||||||
locationId: n.locationId,
|
locationId: n.locationId,
|
||||||
@@ -278,7 +389,8 @@ function NodesPage() {
|
|||||||
notes: n.notes ?? '',
|
notes: n.notes ?? '',
|
||||||
hostname: n.hostname,
|
hostname: n.hostname,
|
||||||
})
|
})
|
||||||
setPreview(n.hostname)
|
setPreviewHost(n.hostname)
|
||||||
|
setPreviewRecords([])
|
||||||
setSheetOpen(true)
|
setSheetOpen(true)
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
@@ -306,9 +418,12 @@ function NodesPage() {
|
|||||||
size="sm"
|
size="sm"
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
setEditing(null)
|
setEditing(null)
|
||||||
|
const firstLoc = locations[0]
|
||||||
|
setCountryName(countryNameFromCode(firstLoc?.country))
|
||||||
|
setLocationQuery(firstLoc ? `${firstLoc.code} — ${firstLoc.name}` : '')
|
||||||
form.reset({
|
form.reset({
|
||||||
zoneId: zones[0]?.id ?? '',
|
zoneId: zones[0]?.id ?? '',
|
||||||
locationId: locations[0]?.id ?? '',
|
locationId: firstLoc?.id ?? '',
|
||||||
role: 'gw',
|
role: 'gw',
|
||||||
indexNum: 1,
|
indexNum: 1,
|
||||||
ipv4: '',
|
ipv4: '',
|
||||||
@@ -317,9 +432,9 @@ function NodesPage() {
|
|||||||
notes: '',
|
notes: '',
|
||||||
hostname: '',
|
hostname: '',
|
||||||
})
|
})
|
||||||
setPreview('')
|
setPreviewHost('')
|
||||||
|
setPreviewRecords([])
|
||||||
setSheetOpen(true)
|
setSheetOpen(true)
|
||||||
void refreshPreview()
|
|
||||||
}}
|
}}
|
||||||
disabled={zones.length === 0}
|
disabled={zones.length === 0}
|
||||||
>
|
>
|
||||||
@@ -387,8 +502,7 @@ function NodesPage() {
|
|||||||
<SelectField
|
<SelectField
|
||||||
value={form.watch('zoneId')}
|
value={form.watch('zoneId')}
|
||||||
onValueChange={(v) => {
|
onValueChange={(v) => {
|
||||||
form.setValue('zoneId', v ?? '')
|
form.setValue('zoneId', v ?? '', { shouldDirty: true })
|
||||||
void refreshPreview()
|
|
||||||
}}
|
}}
|
||||||
placeholder="Зона"
|
placeholder="Зона"
|
||||||
options={zones.map((z) => ({ value: z.id, label: z.name }))}
|
options={zones.map((z) => ({ value: z.id, label: z.name }))}
|
||||||
@@ -396,21 +510,51 @@ function NodesPage() {
|
|||||||
</div>
|
</div>
|
||||||
) : null}
|
) : null}
|
||||||
|
|
||||||
<div className="flex flex-col gap-2">
|
<FormFieldSimple label="Страна" htmlFor="node-country">
|
||||||
<Label>Локация</Label>
|
<AutoCompleteInput
|
||||||
<SelectField
|
id="node-country"
|
||||||
value={form.watch('locationId')}
|
placeholder="Любая"
|
||||||
onValueChange={(v) => {
|
value={countryName}
|
||||||
form.setValue('locationId', v ?? '')
|
onChange={(v) => {
|
||||||
void refreshPreview()
|
setCountryName(v)
|
||||||
|
const nextCode = countryCodeFromName(v)
|
||||||
|
const currentLoc = locations.find((l) => l.id === form.getValues('locationId'))
|
||||||
|
if (!nextCode || !currentLoc || currentLoc.country !== nextCode) {
|
||||||
|
form.setValue('locationId', '')
|
||||||
|
setLocationQuery('')
|
||||||
|
setPreviewHost('')
|
||||||
|
setPreviewRecords([])
|
||||||
|
}
|
||||||
}}
|
}}
|
||||||
placeholder="Локация"
|
options={countryOptions}
|
||||||
options={locations.map((l) => ({
|
searchPlaceholder="Поиск страны…"
|
||||||
value: l.id,
|
emptyText="Нет вариантов"
|
||||||
label: `${l.code} — ${l.name}`,
|
|
||||||
}))}
|
|
||||||
/>
|
/>
|
||||||
</div>
|
</FormFieldSimple>
|
||||||
|
<FormFieldSimple label="Локация" htmlFor="node-location">
|
||||||
|
<AutoCompleteInput
|
||||||
|
id="node-location"
|
||||||
|
placeholder="Любая"
|
||||||
|
value={locationQuery}
|
||||||
|
onChange={(v) => {
|
||||||
|
setLocationQuery(v)
|
||||||
|
const id = locationIdFromDisplay(v)
|
||||||
|
form.setValue('locationId', id)
|
||||||
|
const loc = locations.find((l) => l.id === id)
|
||||||
|
if (loc?.country) setCountryName(countryNameFromCode(loc.country))
|
||||||
|
if (id) void refreshPreview({ locationId: id })
|
||||||
|
else {
|
||||||
|
setPreviewHost('')
|
||||||
|
setPreviewRecords([])
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
options={locationOptions}
|
||||||
|
searchPlaceholder="Поиск локации…"
|
||||||
|
emptyText={countryCode ? 'Нет вариантов' : 'Сначала выберите страну'}
|
||||||
|
showLeadingInInput={false}
|
||||||
|
disabled={!countryCode}
|
||||||
|
/>
|
||||||
|
</FormFieldSimple>
|
||||||
|
|
||||||
<div className="grid grid-cols-2 gap-3">
|
<div className="grid grid-cols-2 gap-3">
|
||||||
<div className="flex flex-col gap-2">
|
<div className="flex flex-col gap-2">
|
||||||
@@ -418,8 +562,9 @@ function NodesPage() {
|
|||||||
<SelectField
|
<SelectField
|
||||||
value={form.watch('role')}
|
value={form.watch('role')}
|
||||||
onValueChange={(v) => {
|
onValueChange={(v) => {
|
||||||
form.setValue('role', (v as NodeRole) ?? 'gw')
|
const role = (v as NodeRole) ?? 'gw'
|
||||||
void refreshPreview()
|
form.setValue('role', role)
|
||||||
|
void refreshPreview({ role })
|
||||||
}}
|
}}
|
||||||
options={ROLES.map((r) => ({ value: r.value, label: r.label }))}
|
options={ROLES.map((r) => ({ value: r.value, label: r.label }))}
|
||||||
/>
|
/>
|
||||||
@@ -430,27 +575,17 @@ function NodesPage() {
|
|||||||
type="number"
|
type="number"
|
||||||
min={1}
|
min={1}
|
||||||
max={99}
|
max={99}
|
||||||
{...form.register('indexNum', { valueAsNumber: true })}
|
{...form.register('indexNum', {
|
||||||
onBlur={() => void refreshPreview()}
|
valueAsNumber: true,
|
||||||
|
onChange: (e) => {
|
||||||
|
const n = Number(e.target.value) || 1
|
||||||
|
void refreshPreview({ indexNum: n })
|
||||||
|
},
|
||||||
|
})}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="bg-muted/40 flex items-center gap-2 rounded-lg border px-3 py-2 text-sm">
|
|
||||||
<CloudIcon className="size-4 shrink-0" />
|
|
||||||
<span className="text-muted-foreground">Preview:</span>
|
|
||||||
<code className="font-medium">{preview || '—'}</code>
|
|
||||||
<Button
|
|
||||||
type="button"
|
|
||||||
variant="ghost"
|
|
||||||
size="sm"
|
|
||||||
className="ml-auto"
|
|
||||||
onClick={() => void refreshPreview()}
|
|
||||||
>
|
|
||||||
<RefreshCwIcon className="size-3.5" />
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="flex flex-col gap-2">
|
<div className="flex flex-col gap-2">
|
||||||
<Label>IPv4</Label>
|
<Label>IPv4</Label>
|
||||||
<Input {...form.register('ipv4')} placeholder="198.51.100.10" />
|
<Input {...form.register('ipv4')} placeholder="198.51.100.10" />
|
||||||
@@ -467,6 +602,48 @@ function NodesPage() {
|
|||||||
<Label>Заметки</Label>
|
<Label>Заметки</Label>
|
||||||
<Input {...form.register('notes')} />
|
<Input {...form.register('notes')} />
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<div className="bg-muted/40 flex flex-col gap-2 rounded-lg border px-3 py-2 text-sm">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<CloudIcon className="size-4 shrink-0" />
|
||||||
|
<span className="text-muted-foreground">Preview FQDN:</span>
|
||||||
|
<code className="font-medium">{previewHost || '—'}</code>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="ghost"
|
||||||
|
size="sm"
|
||||||
|
className="ml-auto"
|
||||||
|
onClick={() => void refreshPreview()}
|
||||||
|
>
|
||||||
|
<RefreshCwIcon className="size-3.5" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
{previewRecords.length > 0 ? (
|
||||||
|
<ul className="flex flex-col gap-1 font-mono text-xs tabular-nums">
|
||||||
|
{previewRecords.map((r) => (
|
||||||
|
<li
|
||||||
|
key={`${r.type}:${r.name}:${r.content}`}
|
||||||
|
className="text-muted-foreground flex flex-wrap items-baseline gap-x-2"
|
||||||
|
>
|
||||||
|
<span className="text-foreground w-12 shrink-0 font-semibold">
|
||||||
|
{r.type}
|
||||||
|
</span>
|
||||||
|
<span className="min-w-0 break-all">
|
||||||
|
{r.name} → {r.content}
|
||||||
|
</span>
|
||||||
|
{r.note ? (
|
||||||
|
<span className="opacity-70">({r.note})</span>
|
||||||
|
) : null}
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
) : previewHost ? (
|
||||||
|
<p className="text-muted-foreground text-xs">
|
||||||
|
Укажите IPv4/IPv6 — появятся A/AAAA. При редактировании — CNAME
|
||||||
|
алиасов на эту ноду.
|
||||||
|
</p>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</FormSheet>
|
</FormSheet>
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,47 @@
|
|||||||
|
import { createFileRoute } from '@tanstack/react-router'
|
||||||
|
import {
|
||||||
|
authPortalUrl,
|
||||||
|
clearToken,
|
||||||
|
ensureAuthConfig,
|
||||||
|
redirectToPortalLogout,
|
||||||
|
} from '@/lib/auth'
|
||||||
|
import { Button } from '@cdnmanager/ui/components/button'
|
||||||
|
|
||||||
|
export const Route = createFileRoute('/access-denied')({
|
||||||
|
beforeLoad: async () => {
|
||||||
|
await ensureAuthConfig()
|
||||||
|
},
|
||||||
|
component: AccessDeniedPage,
|
||||||
|
})
|
||||||
|
|
||||||
|
function AccessDeniedPage() {
|
||||||
|
return (
|
||||||
|
<div className="flex min-h-svh flex-col items-center justify-center gap-4 p-6 text-center">
|
||||||
|
<h1 className="text-lg font-semibold">Нет доступа к CDN Manager</h1>
|
||||||
|
<p className="text-muted-foreground max-w-md text-sm">
|
||||||
|
В JWT нет приложения <code className="text-xs">cdn</code> или нужных прав{' '}
|
||||||
|
<code className="text-xs">cdn:*</code>. Выдайте доступ в Auth Portal →
|
||||||
|
Админка → пользователи, затем войдите снова.
|
||||||
|
</p>
|
||||||
|
<div className="flex flex-wrap items-center justify-center gap-2">
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="outline"
|
||||||
|
render={<a href={`${authPortalUrl().replace(/\/$/, '')}/admin`} />}
|
||||||
|
>
|
||||||
|
Открыть портал
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="default"
|
||||||
|
onClick={() => {
|
||||||
|
clearToken()
|
||||||
|
redirectToPortalLogout()
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
Выйти
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -7,11 +7,24 @@ import {
|
|||||||
firstAllowedPath,
|
firstAllowedPath,
|
||||||
getClaims,
|
getClaims,
|
||||||
getToken,
|
getToken,
|
||||||
|
markPortalHandoff,
|
||||||
parseHashToken,
|
parseHashToken,
|
||||||
redirectToPortalLogin,
|
redirectToPortalLogin,
|
||||||
setToken,
|
setToken,
|
||||||
} from '@/lib/auth'
|
} from '@/lib/auth'
|
||||||
|
|
||||||
|
async function verifyTokenAccepted(token: string): Promise<boolean> {
|
||||||
|
try {
|
||||||
|
const res = await fetch('/api/v1/locations', {
|
||||||
|
headers: { Authorization: `Bearer ${token}` },
|
||||||
|
})
|
||||||
|
// 401 = JWT rejected (secret/issuer). 403 = JWT ok, RBAC — still accepted.
|
||||||
|
return res.status !== 401
|
||||||
|
} catch {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
export const Route = createFileRoute('/auth/callback')({
|
export const Route = createFileRoute('/auth/callback')({
|
||||||
validateSearch: (search: Record<string, unknown>) => ({
|
validateSearch: (search: Record<string, unknown>) => ({
|
||||||
error: typeof search.error === 'string' ? search.error : undefined,
|
error: typeof search.error === 'string' ? search.error : undefined,
|
||||||
@@ -19,25 +32,49 @@ export const Route = createFileRoute('/auth/callback')({
|
|||||||
beforeLoad: async ({ search }) => {
|
beforeLoad: async ({ search }) => {
|
||||||
await ensureAuthConfig()
|
await ensureAuthConfig()
|
||||||
|
|
||||||
if (search.error === 'sso_loop') {
|
if (search.error === 'sso_loop' || search.error === 'jwt_rejected') {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
const { accessToken } = parseHashToken(window.location.hash)
|
const { accessToken } = parseHashToken(window.location.hash)
|
||||||
if (accessToken) {
|
if (accessToken) {
|
||||||
setToken(accessToken)
|
setToken(accessToken)
|
||||||
|
// Start cooldown so a following API 401 cannot re-enter portal SSO storm.
|
||||||
|
markPortalHandoff()
|
||||||
clearPortalHandoffFlag()
|
clearPortalHandoffFlag()
|
||||||
|
|
||||||
const claims = getClaims()
|
const claims = getClaims()
|
||||||
if (!claims) {
|
if (!claims) {
|
||||||
clearToken()
|
clearToken()
|
||||||
window.location.assign(authPortalUrl())
|
throw redirect({
|
||||||
await new Promise(() => {})
|
to: '/auth/callback',
|
||||||
return
|
search: { error: 'jwt_rejected' },
|
||||||
|
})
|
||||||
}
|
}
|
||||||
throw redirect({ to: firstAllowedPath() as '/' })
|
if (!claims.apps.includes('cdn')) {
|
||||||
|
throw redirect({ to: '/access-denied' })
|
||||||
|
}
|
||||||
|
|
||||||
|
const ok = await verifyTokenAccepted(accessToken)
|
||||||
|
if (!ok) {
|
||||||
|
clearToken()
|
||||||
|
throw redirect({
|
||||||
|
to: '/auth/callback',
|
||||||
|
search: { error: 'jwt_rejected' },
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
const next = firstAllowedPath()
|
||||||
|
if (next === '/access-denied') {
|
||||||
|
throw redirect({ to: '/access-denied' })
|
||||||
|
}
|
||||||
|
throw redirect({ to: next as '/' })
|
||||||
}
|
}
|
||||||
if (getToken() && getClaims()) {
|
if (getToken() && getClaims()) {
|
||||||
clearPortalHandoffFlag()
|
clearPortalHandoffFlag()
|
||||||
|
if (!getClaims()!.apps.includes('cdn')) {
|
||||||
|
throw redirect({ to: '/access-denied' })
|
||||||
|
}
|
||||||
throw redirect({ to: firstAllowedPath() as '/' })
|
throw redirect({ to: firstAllowedPath() as '/' })
|
||||||
}
|
}
|
||||||
const ok = redirectToPortalLogin(`${window.location.origin}/auth/callback`)
|
const ok = redirectToPortalLogin(`${window.location.origin}/auth/callback`)
|
||||||
@@ -51,13 +88,14 @@ export const Route = createFileRoute('/auth/callback')({
|
|||||||
|
|
||||||
function AuthCallbackPage() {
|
function AuthCallbackPage() {
|
||||||
const { error } = Route.useSearch()
|
const { error } = Route.useSearch()
|
||||||
if (error === 'sso_loop') {
|
if (error === 'sso_loop' || error === 'jwt_rejected') {
|
||||||
return (
|
return (
|
||||||
<div className="flex min-h-svh flex-col items-center justify-center gap-3 p-6 text-center">
|
<div className="flex min-h-svh flex-col items-center justify-center gap-3 p-6 text-center">
|
||||||
<h1 className="text-lg font-semibold">Сессия не принята</h1>
|
<h1 className="text-lg font-semibold">Сессия не принята</h1>
|
||||||
<p className="text-muted-foreground max-w-md text-sm">
|
<p className="text-muted-foreground max-w-md text-sm">
|
||||||
Повторный вход через portal остановлен (защита от цикла редиректов).
|
{error === 'jwt_rejected'
|
||||||
Обычно это несовпадение JWT_SECRET / ISSUER или просроченный токен.
|
? 'API отклонил JWT (обычно разный AUTH_JWT_SECRET / AUTH_ISSUER с portal). Проверьте .env контейнера CDN Manager.'
|
||||||
|
: 'Повторный вход через portal остановлен (защита от цикла редиректов). Обычно это несовпадение JWT_SECRET / ISSUER или просроченный токен.'}{' '}
|
||||||
Войдите заново на portal, затем откройте CDN Manager.
|
Войдите заново на portal, затем откройте CDN Manager.
|
||||||
</p>
|
</p>
|
||||||
<a className="text-primary text-sm underline" href={authPortalUrl()}>
|
<a className="text-primary text-sm underline" href={authPortalUrl()}>
|
||||||
|
|||||||
@@ -100,6 +100,8 @@ nano .env # заполнить секреты
|
|||||||
|
|
||||||
На стороне портала добавьте origin в `RETURN_TO_ALLOWLIST` (`https://cdn.shnt.top`) и выдайте app **`cdn`** + права `cdn:*`. App Switcher URL: тот же origin.
|
На стороне портала добавьте origin в `RETURN_TO_ALLOWLIST` (`https://cdn.shnt.top`) и выдайте app **`cdn`** + права `cdn:*`. App Switcher URL: тот же origin.
|
||||||
|
|
||||||
|
**Важно:** `AUTH_JWT_SECRET` в CDN Manager **должен совпадать** с `JWT_SECRET` auth-portal, `AUTH_ISSUER` — с `ISSUER` портала. Иначе после SSO UI зацикливается / «Страница не отвечает».
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 3. Запуск
|
## 3. Запуск
|
||||||
|
|||||||
Reference in New Issue
Block a user