Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
25c95356a1 | ||
|
|
9cc6c8d958 |
@@ -30,6 +30,13 @@ async function handoffOnUnauthorized(): Promise<void> {
|
||||
redirectToPortalLogin(`${window.location.origin}/auth/callback`)
|
||||
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()) {
|
||||
window.location.href = '/login'
|
||||
}
|
||||
|
||||
@@ -62,5 +62,11 @@ export function getAppUrl(
|
||||
export function getCurrentApp(
|
||||
config: AppSwitcherConfig = DEFAULT_APP_SWITCHER_CONFIG,
|
||||
): 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)
|
||||
if (!perm || can(perm)) return path
|
||||
}
|
||||
return '/'
|
||||
return '/access-denied'
|
||||
}
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
/** ISO country codes from fleet locations seed → RU labels for selects. */
|
||||
const COUNTRY_LABELS: Record<string, string> = {
|
||||
RU: 'Россия',
|
||||
DE: 'Германия',
|
||||
NL: 'Нидерланды',
|
||||
FI: 'Финляндия',
|
||||
FR: 'Франция',
|
||||
}
|
||||
|
||||
export function countrySelectLabel(code: string): string {
|
||||
const name = COUNTRY_LABELS[code]
|
||||
return name ? `${code} — ${name}` : code
|
||||
}
|
||||
@@ -10,6 +10,7 @@
|
||||
|
||||
import { Route as rootRouteImport } from './routes/__root'
|
||||
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 AuthIndexRouteImport } from './routes/_auth/index'
|
||||
import { Route as AuthCallbackRouteImport } from './routes/auth.callback'
|
||||
@@ -28,6 +29,11 @@ const LoginRoute = LoginRouteImport.update({
|
||||
path: '/login',
|
||||
getParentRoute: () => rootRouteImport,
|
||||
} as any)
|
||||
const AccessDeniedRoute = AccessDeniedRouteImport.update({
|
||||
id: '/access-denied',
|
||||
path: '/access-denied',
|
||||
getParentRoute: () => rootRouteImport,
|
||||
} as any)
|
||||
const AuthRoute = AuthRouteImport.update({
|
||||
id: '/_auth',
|
||||
getParentRoute: () => rootRouteImport,
|
||||
@@ -91,6 +97,7 @@ const AuthSettingsAppearanceRoute = AuthSettingsAppearanceRouteImport.update({
|
||||
|
||||
export interface FileRoutesByFullPath {
|
||||
'/': typeof AuthIndexRoute
|
||||
'/access-denied': typeof AccessDeniedRoute
|
||||
'/login': typeof LoginRoute
|
||||
'/settings': typeof AuthSettingsRouteRouteWithChildren
|
||||
'/aliases': typeof AuthAliasesRoute
|
||||
@@ -104,6 +111,7 @@ export interface FileRoutesByFullPath {
|
||||
'/settings/': typeof AuthSettingsIndexRoute
|
||||
}
|
||||
export interface FileRoutesByTo {
|
||||
'/access-denied': typeof AccessDeniedRoute
|
||||
'/login': typeof LoginRoute
|
||||
'/aliases': typeof AuthAliasesRoute
|
||||
'/nodes': typeof AuthNodesRoute
|
||||
@@ -119,6 +127,7 @@ export interface FileRoutesByTo {
|
||||
export interface FileRoutesById {
|
||||
__root__: typeof rootRouteImport
|
||||
'/_auth': typeof AuthRouteWithChildren
|
||||
'/access-denied': typeof AccessDeniedRoute
|
||||
'/login': typeof LoginRoute
|
||||
'/_auth/settings': typeof AuthSettingsRouteRouteWithChildren
|
||||
'/_auth/aliases': typeof AuthAliasesRoute
|
||||
@@ -136,6 +145,7 @@ export interface FileRouteTypes {
|
||||
fileRoutesByFullPath: FileRoutesByFullPath
|
||||
fullPaths:
|
||||
| '/'
|
||||
| '/access-denied'
|
||||
| '/login'
|
||||
| '/settings'
|
||||
| '/aliases'
|
||||
@@ -149,6 +159,7 @@ export interface FileRouteTypes {
|
||||
| '/settings/'
|
||||
fileRoutesByTo: FileRoutesByTo
|
||||
to:
|
||||
| '/access-denied'
|
||||
| '/login'
|
||||
| '/aliases'
|
||||
| '/nodes'
|
||||
@@ -163,6 +174,7 @@ export interface FileRouteTypes {
|
||||
id:
|
||||
| '__root__'
|
||||
| '/_auth'
|
||||
| '/access-denied'
|
||||
| '/login'
|
||||
| '/_auth/settings'
|
||||
| '/_auth/aliases'
|
||||
@@ -179,6 +191,7 @@ export interface FileRouteTypes {
|
||||
}
|
||||
export interface RootRouteChildren {
|
||||
AuthRoute: typeof AuthRouteWithChildren
|
||||
AccessDeniedRoute: typeof AccessDeniedRoute
|
||||
LoginRoute: typeof LoginRoute
|
||||
AuthCallbackRoute: typeof AuthCallbackRoute
|
||||
}
|
||||
@@ -192,6 +205,13 @@ declare module '@tanstack/react-router' {
|
||||
preLoaderRoute: typeof LoginRouteImport
|
||||
parentRoute: typeof rootRouteImport
|
||||
}
|
||||
'/access-denied': {
|
||||
id: '/access-denied'
|
||||
path: '/access-denied'
|
||||
fullPath: '/access-denied'
|
||||
preLoaderRoute: typeof AccessDeniedRouteImport
|
||||
parentRoute: typeof rootRouteImport
|
||||
}
|
||||
'/_auth': {
|
||||
id: '/_auth'
|
||||
path: ''
|
||||
@@ -318,6 +338,7 @@ const AuthRouteWithChildren = AuthRoute._addFileChildren(AuthRouteChildren)
|
||||
|
||||
const rootRouteChildren: RootRouteChildren = {
|
||||
AuthRoute: AuthRouteWithChildren,
|
||||
AccessDeniedRoute: AccessDeniedRoute,
|
||||
LoginRoute: LoginRoute,
|
||||
AuthCallbackRoute: AuthCallbackRoute,
|
||||
}
|
||||
|
||||
@@ -16,7 +16,8 @@ export const Route = createRootRouteWithContext<RouterContext>()({
|
||||
beforeLoad: async ({ location }) => {
|
||||
const isLogin = location.pathname === '/login'
|
||||
const isCallback = location.pathname === '/auth/callback'
|
||||
if (isCallback) return
|
||||
const isAccessDenied = location.pathname === '/access-denied'
|
||||
if (isCallback || isAccessDenied) return
|
||||
|
||||
const cfg = await ensureAuthConfig()
|
||||
const token = getToken()
|
||||
|
||||
@@ -30,16 +30,19 @@ export const Route = createFileRoute('/_auth')({
|
||||
await new Promise(() => {})
|
||||
return
|
||||
}
|
||||
// NEVER redirect to `/` here — `/` is under `_auth` and causes an infinite loop
|
||||
// (browser: «Страница не отвечает»).
|
||||
if (!claims.apps.includes('cdn')) {
|
||||
throw redirect({ to: '/' })
|
||||
throw redirect({ to: '/access-denied' })
|
||||
}
|
||||
|
||||
const perm = permissionForPath(location.pathname)
|
||||
if (perm && !can(perm)) {
|
||||
const fallback = firstAllowedPath()
|
||||
if (fallback !== location.pathname) {
|
||||
throw redirect({ to: fallback as '/' })
|
||||
if (fallback === '/access-denied' || fallback === location.pathname) {
|
||||
throw redirect({ to: '/access-denied' })
|
||||
}
|
||||
throw redirect({ to: fallback as '/' })
|
||||
}
|
||||
},
|
||||
component: () => (
|
||||
|
||||
@@ -25,6 +25,7 @@ import { Button } from '@cdnmanager/ui/components/button'
|
||||
import { Input } from '@cdnmanager/ui/components/input'
|
||||
import { Label } from '@cdnmanager/ui/components/label'
|
||||
import { SelectField } from '@/components/select-field'
|
||||
import { countrySelectLabel } from '@/lib/country-labels'
|
||||
import { queryClient } from '@/lib/query-client'
|
||||
import {
|
||||
createNode,
|
||||
@@ -80,6 +81,7 @@ function NodesPage() {
|
||||
const [editing, setEditing] = useState<Node | null>(null)
|
||||
const [deleteId, setDeleteId] = useState<string | null>(null)
|
||||
const [preview, setPreview] = useState('')
|
||||
const [countryCode, setCountryCode] = useState('')
|
||||
|
||||
const form = useForm<FormValues>({
|
||||
resolver: zodResolver(formSchema),
|
||||
@@ -102,6 +104,30 @@ function NodesPage() {
|
||||
const watchIndex = form.watch('indexNum')
|
||||
const watchProvider = form.watch('providerTag')
|
||||
|
||||
const countryOptions = useMemo(() => {
|
||||
const codes = new Set<string>()
|
||||
for (const loc of locations) {
|
||||
if (loc.country) codes.add(loc.country)
|
||||
}
|
||||
return [...codes]
|
||||
.sort((a, b) => a.localeCompare(b))
|
||||
.map((code) => ({ value: code, label: countrySelectLabel(code) }))
|
||||
}, [locations])
|
||||
|
||||
const locationOptions = useMemo(() => {
|
||||
if (!countryCode) return []
|
||||
return locations
|
||||
.filter((l) => l.country === countryCode)
|
||||
.map((l) => ({
|
||||
value: l.id,
|
||||
label: `${l.code} — ${l.name}`,
|
||||
}))
|
||||
}, [locations, countryCode])
|
||||
|
||||
function countryForLocationId(locationId: string): string {
|
||||
return locations.find((l) => l.id === locationId)?.country ?? ''
|
||||
}
|
||||
|
||||
async function refreshPreview() {
|
||||
if (!watchZone || !watchLoc || !watchRole) return
|
||||
try {
|
||||
@@ -148,6 +174,7 @@ function NodesPage() {
|
||||
toast.success(editing ? 'Нода обновлена' : 'Нода создана')
|
||||
setSheetOpen(false)
|
||||
setEditing(null)
|
||||
setCountryCode('')
|
||||
form.reset()
|
||||
void qc.invalidateQueries({ queryKey: ['fleet'] })
|
||||
},
|
||||
@@ -267,6 +294,7 @@ function NodesPage() {
|
||||
onClick={() => {
|
||||
const n = row.original
|
||||
setEditing(n)
|
||||
setCountryCode(countryForLocationId(n.locationId))
|
||||
form.reset({
|
||||
zoneId: n.zoneId,
|
||||
locationId: n.locationId,
|
||||
@@ -306,9 +334,11 @@ function NodesPage() {
|
||||
size="sm"
|
||||
onClick={() => {
|
||||
setEditing(null)
|
||||
const firstLoc = locations[0]
|
||||
setCountryCode(firstLoc?.country ?? '')
|
||||
form.reset({
|
||||
zoneId: zones[0]?.id ?? '',
|
||||
locationId: locations[0]?.id ?? '',
|
||||
locationId: firstLoc?.id ?? '',
|
||||
role: 'gw',
|
||||
indexNum: 1,
|
||||
ipv4: '',
|
||||
@@ -396,20 +426,41 @@ function NodesPage() {
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<div className="flex flex-col gap-2">
|
||||
<Label>Локация</Label>
|
||||
<SelectField
|
||||
value={form.watch('locationId')}
|
||||
onValueChange={(v) => {
|
||||
form.setValue('locationId', v ?? '')
|
||||
void refreshPreview()
|
||||
}}
|
||||
placeholder="Локация"
|
||||
options={locations.map((l) => ({
|
||||
value: l.id,
|
||||
label: `${l.code} — ${l.name}`,
|
||||
}))}
|
||||
/>
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<div className="flex flex-col gap-2">
|
||||
<Label>Страна</Label>
|
||||
<SelectField
|
||||
value={countryCode || null}
|
||||
onValueChange={(v) => {
|
||||
const next = v ?? ''
|
||||
setCountryCode(next)
|
||||
const currentLoc = locations.find((l) => l.id === form.getValues('locationId'))
|
||||
if (!next || !currentLoc || currentLoc.country !== next) {
|
||||
form.setValue('locationId', '')
|
||||
setPreview('')
|
||||
}
|
||||
void refreshPreview()
|
||||
}}
|
||||
placeholder="Страна"
|
||||
options={countryOptions}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex flex-col gap-2">
|
||||
<Label>Локация</Label>
|
||||
<SelectField
|
||||
value={form.watch('locationId') || null}
|
||||
disabled={!countryCode}
|
||||
onValueChange={(v) => {
|
||||
const id = v ?? ''
|
||||
form.setValue('locationId', id)
|
||||
const loc = locations.find((l) => l.id === id)
|
||||
if (loc?.country) setCountryCode(loc.country)
|
||||
void refreshPreview()
|
||||
}}
|
||||
placeholder={countryCode ? 'Локация' : 'Сначала страна'}
|
||||
options={locationOptions}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
|
||||
@@ -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,
|
||||
getClaims,
|
||||
getToken,
|
||||
markPortalHandoff,
|
||||
parseHashToken,
|
||||
redirectToPortalLogin,
|
||||
setToken,
|
||||
} 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')({
|
||||
validateSearch: (search: Record<string, unknown>) => ({
|
||||
error: typeof search.error === 'string' ? search.error : undefined,
|
||||
@@ -19,25 +32,49 @@ export const Route = createFileRoute('/auth/callback')({
|
||||
beforeLoad: async ({ search }) => {
|
||||
await ensureAuthConfig()
|
||||
|
||||
if (search.error === 'sso_loop') {
|
||||
if (search.error === 'sso_loop' || search.error === 'jwt_rejected') {
|
||||
return
|
||||
}
|
||||
|
||||
const { accessToken } = parseHashToken(window.location.hash)
|
||||
if (accessToken) {
|
||||
setToken(accessToken)
|
||||
// Start cooldown so a following API 401 cannot re-enter portal SSO storm.
|
||||
markPortalHandoff()
|
||||
clearPortalHandoffFlag()
|
||||
|
||||
const claims = getClaims()
|
||||
if (!claims) {
|
||||
clearToken()
|
||||
window.location.assign(authPortalUrl())
|
||||
await new Promise(() => {})
|
||||
return
|
||||
throw redirect({
|
||||
to: '/auth/callback',
|
||||
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()) {
|
||||
clearPortalHandoffFlag()
|
||||
if (!getClaims()!.apps.includes('cdn')) {
|
||||
throw redirect({ to: '/access-denied' })
|
||||
}
|
||||
throw redirect({ to: firstAllowedPath() as '/' })
|
||||
}
|
||||
const ok = redirectToPortalLogin(`${window.location.origin}/auth/callback`)
|
||||
@@ -51,13 +88,14 @@ export const Route = createFileRoute('/auth/callback')({
|
||||
|
||||
function AuthCallbackPage() {
|
||||
const { error } = Route.useSearch()
|
||||
if (error === 'sso_loop') {
|
||||
if (error === 'sso_loop' || error === 'jwt_rejected') {
|
||||
return (
|
||||
<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>
|
||||
<p className="text-muted-foreground max-w-md text-sm">
|
||||
Повторный вход через portal остановлен (защита от цикла редиректов).
|
||||
Обычно это несовпадение JWT_SECRET / ISSUER или просроченный токен.
|
||||
{error === 'jwt_rejected'
|
||||
? 'API отклонил JWT (обычно разный AUTH_JWT_SECRET / AUTH_ISSUER с portal). Проверьте .env контейнера CDN Manager.'
|
||||
: 'Повторный вход через portal остановлен (защита от цикла редиректов). Обычно это несовпадение JWT_SECRET / ISSUER или просроченный токен.'}{' '}
|
||||
Войдите заново на portal, затем откройте CDN Manager.
|
||||
</p>
|
||||
<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.
|
||||
|
||||
**Важно:** `AUTH_JWT_SECRET` в CDN Manager **должен совпадать** с `JWT_SECRET` auth-portal, `AUTH_ISSUER` — с `ISSUER` портала. Иначе после SSO UI зацикливается / «Страница не отвечает».
|
||||
|
||||
---
|
||||
|
||||
## 3. Запуск
|
||||
|
||||
Reference in New Issue
Block a user