Compare commits

...

1 Commits

Author SHA1 Message Date
hongjr03 4e7b158ff9 feat(hub): drop redundant /admin/org/:slug path + release v0.0.35
Silo hostname already carries tenancy. Admin SPA routes become /admin/...,
legacy /admin/org/:slug/* bookmarks redirect, login lands on /admin.
2026-07-18 17:36:08 +00:00
25 changed files with 221 additions and 129 deletions
@@ -33,7 +33,7 @@
<div class="space-y-0.5"> <div class="space-y-0.5">
{#each childProjects as p (p.id)} {#each childProjects as p (p.id)}
<a <a
href={`/admin/org/${slug}/projects/${p.id}`} href={`/admin/projects/${p.id}`}
class="flex items-center gap-2.5 px-3 py-2.5 text-sm transition hover:bg-surface-100" class="flex items-center gap-2.5 px-3 py-2.5 text-sm transition hover:bg-surface-100"
> >
<span class="flex h-7 w-7 items-center justify-center border border-primary-200 bg-primary-50 text-primary-700"> <span class="flex h-7 w-7 items-center justify-center border border-primary-200 bg-primary-50 text-primary-700">
+40
View File
@@ -0,0 +1,40 @@
import type { MeResponse, OrgMembership } from './api';
/** Alpha Silo host prefix: <slug>.educraft[.dev].… */
export function hostOrgSlug(hostname: string = typeof window !== 'undefined' ? window.location.hostname : ''): string | null {
const host = hostname.toLowerCase();
const m = host.match(/^([a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)\.educraft(?:-dev)?\./);
return m?.[1] ?? null;
}
export function isOrgAdmin(org: OrgMembership | null | undefined): boolean {
if (!org) return false;
const role = String(org.role ?? '').toUpperCase();
return role === 'OWNER' || role === 'ADMIN';
}
/**
* Resolve the tenancy for this browser session.
* Prefers hostname slug (silo), then ?org=, then first admin membership, then first membership.
*/
export function resolveOrg(me: MeResponse | null | undefined, search: string = ''): OrgMembership | null {
if (!me || me.organizations.length === 0) return null;
const host = hostOrgSlug();
if (host) {
const byHost = me.organizations.find((o) => o.slug === host);
if (byHost) return byHost;
}
const q = new URLSearchParams(search).get('org')?.trim();
if (q) {
const byQuery = me.organizations.find((o) => o.slug === q);
if (byQuery) return byQuery;
}
const admin = me.organizations.find((o) => isOrgAdmin(o));
return admin ?? me.organizations[0] ?? null;
}
/** SPA paths no longer embed org slug (subdomain carries tenancy). */
export function adminPath(rest: string = ''): string {
const cleaned = rest.replace(/^\/+/, '');
return cleaned === '' ? '/admin' : `/admin/${cleaned}`;
}
+7 -4
View File
@@ -35,12 +35,9 @@ export async function loadSession(): Promise<void> {
/** /**
* Resolve org slug for org-scoped Feishu OAuth (`GET /auth/feishu/:orgSlug`). * Resolve org slug for org-scoped Feishu OAuth (`GET /auth/feishu/:orgSlug`).
* Unscoped `/auth/feishu` is disabled unless allowLegacyFeishuOAuth is on. * Unscoped `/auth/feishu` is disabled unless allowLegacyFeishuOAuth is on.
* Path no longer carries tenancy: prefer hostname silo slug, then ?org=.
*/ */
export function resolveLoginOrgSlug(): string | null { export function resolveLoginOrgSlug(): string | null {
const path = window.location.pathname.split('/').filter(Boolean);
if (path[0] === 'admin' && path[1] === 'org' && path[2]) {
return decodeURIComponent(path[2]);
}
const q = new URLSearchParams(window.location.search).get('org'); const q = new URLSearchParams(window.location.search).get('org');
if (q && q.trim() !== '') return q.trim(); if (q && q.trim() !== '') return q.trim();
@@ -48,6 +45,12 @@ export function resolveLoginOrgSlug(): string | null {
const host = window.location.hostname.toLowerCase(); const host = window.location.hostname.toLowerCase();
const m = host.match(/^([a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)\.educraft(?:-dev)?\./); const m = host.match(/^([a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)\.educraft(?:-dev)?\./);
if (m?.[1]) return m[1]; if (m?.[1]) return m[1];
// Legacy path while old bookmarks still land briefly before redirect.
const path = window.location.pathname.split('/').filter(Boolean);
if (path[0] === 'admin' && path[1] === 'org' && path[2]) {
return decodeURIComponent(path[2]);
}
return null; return null;
} }
+51 -76
View File
@@ -5,6 +5,7 @@
import { page } from '$app/state'; import { page } from '$app/state';
import { session, loadSession, logout, redirectToLogin } from '$lib/session'; import { session, loadSession, logout, redirectToLogin } from '$lib/session';
import type { OrgMembership } from '$lib/api'; import type { OrgMembership } from '$lib/api';
import { adminPath, isOrgAdmin, resolveOrg } from '$lib/org';
import { orgRoleLabel } from '$lib/format'; import { orgRoleLabel } from '$lib/format';
import Icon from '$lib/components/Icon.svelte'; import Icon from '$lib/components/Icon.svelte';
import ToastHost from '$lib/components/ToastHost.svelte'; import ToastHost from '$lib/components/ToastHost.svelte';
@@ -32,56 +33,36 @@
{ key: 'capabilities', label: '能力', icon: 'provider' as const }, { key: 'capabilities', label: '能力', icon: 'provider' as const },
]; ];
function isAdmin(org: OrgMembership): boolean {
const role = String(org.role ?? '').toUpperCase();
return role === 'OWNER' || role === 'ADMIN';
}
function orgSlugFromPath(): string | null {
const parts = page.url.pathname.split('/').filter(Boolean);
if (parts[0] === 'admin' && parts[1] === 'org' && parts[2]) {
return decodeURIComponent(parts[2]);
}
return null;
}
function isOnProjectRoute(): boolean {
const parts = page.url.pathname.split('/').filter(Boolean);
return parts[0] === 'admin' && parts[1] === 'org' && parts[3] === 'projects';
}
function memberships(): OrgMembership[] { function memberships(): OrgMembership[] {
return $session.me?.organizations ?? []; return $session.me?.organizations ?? [];
} }
function adminOrgs(): OrgMembership[] { function adminOrgs(): OrgMembership[] {
return memberships().filter(isAdmin); return memberships().filter((o) => isOrgAdmin(o));
} }
function currentOrg(): OrgMembership | null { function currentOrg(): OrgMembership | null {
const slug = orgSlugFromPath(); return resolveOrg($session.me, page.url.search);
if (!slug) return null;
return memberships().find((o) => o.slug === slug) ?? null;
} }
function pickHomeOrg(): OrgMembership | null { function isOnProjectRoute(): boolean {
const admin = adminOrgs()[0]; const parts = page.url.pathname.split('/').filter(Boolean);
if (admin) return admin; // /admin/projects or /admin/projects/:id
return memberships()[0] ?? null; return parts[0] === 'admin' && parts[1] === 'projects';
} }
function activeKey(): string { function activeKey(): string {
const parts = page.url.pathname.split('/').filter(Boolean); const parts = page.url.pathname.split('/').filter(Boolean);
if (parts[0] !== 'admin' || parts[1] !== 'org' || !parts[2]) return ''; if (parts[0] !== 'admin') return '';
return parts[3] ?? 'overview'; // /admin → overview; /admin/usage → usage; /admin/projects/x → projects
return parts[1] ?? 'overview';
} }
function navHref(key: string): string { function navHref(key: string): string {
const slug = currentOrg()?.slug ?? pickHomeOrg()?.slug; if (key === 'overview') return adminPath();
if (!slug) return '/'; return adminPath(key);
if (key === 'overview') return `/admin/org/${slug}`;
return `/admin/org/${slug}/${key}`;
} }
function pageTitle(): string { function pageTitle(): string {
const key = activeKey(); const key = activeKey();
if (key === 'overview' || key === '') return '概览'; if (key === 'overview' || key === '') return '概览';
@@ -91,7 +72,10 @@
function switchOrg(nextSlug: string) { function switchOrg(nextSlug: string) {
if (!nextSlug || nextSlug === currentOrg()?.slug) return; if (!nextSlug || nextSlug === currentOrg()?.slug) return;
void goto(`/admin/org/${nextSlug}`); // Path is tenancy-free; keep optional ?org= for local multi-membership debugging.
const url = new URL(page.url.href);
url.searchParams.set('org', nextSlug);
void goto(`${url.pathname}${url.search}`, { replaceState: true });
} }
function handleLogout(e: Event) { function handleLogout(e: Event) {
@@ -114,33 +98,23 @@
$effect(() => { $effect(() => {
if ($session.loading || !$session.me) return; if ($session.loading || !$session.me) return;
const slug = orgSlugFromPath(); const path = page.url.pathname;
const matched = slug ? memberships().find((o) => o.slug === slug) : null; // Legacy /admin/org/:slug… is handled by admin/org/[...path] page.
// Org admins: route to their first admin org if none matched as admin. const org = currentOrg();
const admins = adminOrgs(); const admins = adminOrgs();
if (matched && isAdmin(matched)) {
if (org && isOrgAdmin(org)) {
redirecting = false; redirecting = false;
return; return;
} }
if (!matched && admins.length > 0) {
const target = `/admin/org/${admins[0].slug}`;
if (page.url.pathname !== target && !page.url.pathname.startsWith(`${target}/`)) {
redirecting = true;
void goto(target, { replaceState: true });
}
return;
}
// Members (non-admin): project pages are open to project MANAGE holders; // Member only: allow project routes; bounce admin-only surfaces to projects.
// the org overview and other admin-only surfaces are not for them. if (org && !isOrgAdmin(org)) {
if (matched && !isAdmin(matched)) {
redirecting = false; redirecting = false;
const parts = page.url.pathname.split('/').filter(Boolean); if (!isOnProjectRoute()) {
const onOverview = parts.length === 3; // /admin/org/:slug const target = adminPath('projects');
if (onOverview) { if (path !== target) {
const target = `/admin/org/${matched.slug}/projects`;
if (page.url.pathname !== target) {
redirecting = true; redirecting = true;
void goto(target, { replaceState: true }); void goto(target, { replaceState: true });
} }
@@ -148,12 +122,11 @@
return; return;
} }
// No matched org and no admin orgs: route a member to their first org's // No org resolved but user has memberships → land on first org's projects/overview via resolveOrg next tick
// projects page so they can reach project MANAGE surfaces. if (!org && memberships().length > 0) {
if (!matched && memberships().length > 0) { const home = admins[0] ?? memberships()[0]!;
const home = memberships()[0]; const target = isOrgAdmin(home) ? adminPath() : adminPath('projects');
const target = `/admin/org/${home.slug}/projects`; if (path !== target && !path.startsWith(`${target}/`)) {
if (page.url.pathname !== target && !page.url.pathname.startsWith(`${target}/`)) {
redirecting = true; redirecting = true;
void goto(target, { replaceState: true }); void goto(target, { replaceState: true });
} }
@@ -174,14 +147,14 @@
d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
></path> ></path>
</svg> </svg>
<p class="text-sm">{redirecting ? '正在进入组织…' : '正在加载会话…'}</p> <p class="text-sm">加载中…</p>
</div> </div>
</div> </div>
{:else if $session.error} {:else if $session.error}
<div class="saas-status-panel"> <div class="saas-status-panel">
<div class="saas-status-card"> <div class="saas-status-card">
<div <div
class="mx-auto mb-4 flex h-12 w-12 items-center justify-center border border-error-300 bg-error-100 text-error-700 font-bold" class="mx-auto mb-3 flex h-12 w-12 items-center justify-center border border-error-200 bg-error-50 text-error-700"
> >
! !
</div> </div>
@@ -194,7 +167,7 @@
<div class="saas-status-panel"> <div class="saas-status-panel">
<div class="saas-status-card"> <div class="saas-status-card">
<div <div
class="mx-auto mb-5 flex h-12 w-12 items-center justify-center border border-primary-700 bg-primary-600 text-white font-bold" class="mx-auto mb-4 flex h-12 w-12 items-center justify-center border border-primary-700 bg-primary-600 text-sm font-bold text-white"
> >
CPH CPH
</div> </div>
@@ -203,7 +176,7 @@
<button class="saas-btn-primary w-full" onclick={() => redirectToLogin()}>使用飞书登录</button> <button class="saas-btn-primary w-full" onclick={() => redirectToLogin()}>使用飞书登录</button>
</div> </div>
</div> </div>
{:else if currentOrg() && isAdmin(currentOrg()!)} {:else if currentOrg() && isOrgAdmin(currentOrg()!)}
{@const org = currentOrg()!} {@const org = currentOrg()!}
{@const me = $session.me!} {@const me = $session.me!}
<div class="saas-shell"> <div class="saas-shell">
@@ -228,17 +201,19 @@
</div> </div>
<div class="min-w-0"> <div class="min-w-0">
<div class="truncate text-sm font-semibold text-surface-900">组织后台</div> <div class="truncate text-sm font-semibold text-surface-900">组织后台</div>
<div class="truncate text-xs text-surface-600">Curriculum Hub</div> <div class="truncate text-xs text-surface-600">{org.name}</div>
</div> </div>
</div> </div>
<div class="px-3 pb-3"> {#if me.organizations.length > 1}
<div class="mb-1.5 flex items-center gap-1.5 text-xs font-medium text-surface-700"> <div class="px-3 pb-3">
<Icon name="org" class="h-3.5 w-3.5" /> <div class="mb-1.5 flex items-center gap-1.5 text-xs font-medium text-surface-700">
组织 <Icon name="org" class="h-3.5 w-3.5" />
组织
</div>
<SelectField items={orgSelectItems(me.organizations)} value={org.slug} onchange={switchOrg} />
</div> </div>
<SelectField items={orgSelectItems(me.organizations)} value={org.slug} onchange={switchOrg} /> {/if}
</div>
<nav class="flex-1 space-y-0.5 overflow-y-auto px-2 pb-3"> <nav class="flex-1 space-y-0.5 overflow-y-auto px-2 pb-3">
<p class="px-3 pb-1 pt-2 text-[11px] font-semibold uppercase tracking-wider text-surface-600">工作台</p> <p class="px-3 pb-1 pt-2 text-[11px] font-semibold uppercase tracking-wider text-surface-600">工作台</p>
@@ -308,13 +283,13 @@
</main> </main>
</div> </div>
</div> </div>
{:else if currentOrg() && !isAdmin(currentOrg()!) && isOnProjectRoute()} {:else if currentOrg() && !isOrgAdmin(currentOrg()!) && isOnProjectRoute()}
{@const org = currentOrg()!} {@const org = currentOrg()!}
{@const me = $session.me!} {@const me = $session.me!}
<div class="saas-shell"> <div class="saas-shell">
<div class="saas-main"> <div class="saas-main">
<header class="saas-topbar"> <header class="saas-topbar">
<a href={`/admin/org/${org.slug}/projects`} class="saas-btn-ghost px-2!" aria-label="返回项目列表"> <a href={adminPath('projects')} class="saas-btn-ghost px-2!" aria-label="返回项目列表">
<Icon name="menu" class="h-5 w-5" /> <Icon name="menu" class="h-5 w-5" />
</a> </a>
<div class="min-w-0"> <div class="min-w-0">
@@ -343,7 +318,7 @@
</main> </main>
</div> </div>
</div> </div>
{:else if currentOrg() && !isAdmin(currentOrg()!)} {:else if currentOrg() && !isOrgAdmin(currentOrg()!)}
{@const denied = currentOrg()!} {@const denied = currentOrg()!}
<div class="saas-status-panel"> <div class="saas-status-panel">
<div class="saas-status-card"> <div class="saas-status-card">
@@ -352,7 +327,7 @@
组织 <strong>{denied.name}</strong>/{denied.slug})中你的角色是 组织 <strong>{denied.name}</strong>/{denied.slug})中你的角色是
<span class="saas-badge-neutral mx-1">{orgRoleLabel(denied.role)}</span>。普通成员仅可访问自己有授权的项目。 <span class="saas-badge-neutral mx-1">{orgRoleLabel(denied.role)}</span>。普通成员仅可访问自己有授权的项目。
</p> </p>
<a class="saas-btn-primary" href={`/admin/org/${denied.slug}/projects`}>查看我的项目</a> <a class="saas-btn-primary" href={adminPath('projects')}>查看我的项目</a>
{#if memberships().length > 1} {#if memberships().length > 1}
<p class="saas-label text-left mb-1.5 mt-3">切换到其他组织</p> <p class="saas-label text-left mb-1.5 mt-3">切换到其他组织</p>
<div class="mb-4"> <div class="mb-4">
@@ -363,14 +338,14 @@
</div> </div>
</div> </div>
{:else if memberships().length > 0} {:else if memberships().length > 0}
{@const denied = pickHomeOrg()!} {@const denied = resolveOrg($session.me) ?? memberships()[0]!}
<div class="saas-status-panel"> <div class="saas-status-panel">
<div class="saas-status-card"> <div class="saas-status-card">
<h2 class="mb-2 text-lg font-semibold">正在跳转…</h2> <h2 class="mb-2 text-lg font-semibold">正在跳转…</h2>
<p class="mb-5 text-sm text-surface-700"> <p class="mb-5 text-sm text-surface-700">
即将进入 <strong>{denied.name}</strong>/{denied.slug})的项目。 即将进入 <strong>{denied.name}</strong>/{denied.slug})的项目。
</p> </p>
<a class="saas-btn-primary" href={`/admin/org/${denied.slug}/projects`}>立即进入</a> <a class="saas-btn-primary" href={adminPath('projects')}>立即进入</a>
<button class="saas-btn-ghost mt-3" onclick={handleLogout}>退出登录</button> <button class="saas-btn-ghost mt-3" onclick={handleLogout}>退出登录</button>
</div> </div>
</div> </div>
+1 -1
View File
@@ -11,7 +11,7 @@
return r === 'OWNER' || r === 'ADMIN'; return r === 'OWNER' || r === 'ADMIN';
}); });
const target = admin ?? me.organizations[0]; const target = admin ?? me.organizations[0];
return target ? `/admin/org/${target.slug}` : null; return target ? `/admin` : null;
} }
onMount(() => { onMount(() => {
@@ -2,6 +2,7 @@
import { page } from '$app/state'; import { page } from '$app/state';
import { api, type OrgMembership } from '$lib/api'; import { api, type OrgMembership } from '$lib/api';
import { session } from '$lib/session'; import { session } from '$lib/session';
import { resolveOrg } from '$lib/org';
import { fmtCost, fmtNum, orgRoleLabel } from '$lib/format'; import { fmtCost, fmtNum, orgRoleLabel } from '$lib/format';
import PageHeader from '$lib/components/PageHeader.svelte'; import PageHeader from '$lib/components/PageHeader.svelte';
import StatCard from '$lib/components/StatCard.svelte'; import StatCard from '$lib/components/StatCard.svelte';
@@ -10,7 +11,8 @@
import SwitchControl from '$lib/components/SwitchControl.svelte'; import SwitchControl from '$lib/components/SwitchControl.svelte';
import { toastError, toastSuccess } from '$lib/toast'; import { toastError, toastSuccess } from '$lib/toast';
let orgSlug = $derived(page.params.slug ?? ''); const orgFromSession = $derived(resolveOrg($session.me, page.url.search));
let orgSlug = $derived(orgFromSession?.slug ?? '');
let org = $derived($session.me?.organizations.find((o) => o.slug === orgSlug) as OrgMembership | undefined); let org = $derived($session.me?.organizations.find((o) => o.slug === orgSlug) as OrgMembership | undefined);
let settings = $state<{ membersCanCreateProjects: boolean } | null>(null); let settings = $state<{ membersCanCreateProjects: boolean } | null>(null);
@@ -96,7 +98,7 @@
<h2 class="saas-section-title">用量概览</h2> <h2 class="saas-section-title">用量概览</h2>
<p class="saas-muted">totals 含全部 UsageFact;分账明细见用量页。</p> <p class="saas-muted">totals 含全部 UsageFact;分账明细见用量页。</p>
</div> </div>
<a class="saas-btn-secondary py-1.5! text-sm" href={`/admin/org/${orgSlug}/usage`}>完整用量报告</a> <a class="saas-btn-secondary py-1.5! text-sm" href={`/admin/usage`}>完整用量报告</a>
</div> </div>
<div class="mb-6 grid gap-3 sm:grid-cols-2 lg:grid-cols-3"> <div class="mb-6 grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
@@ -115,7 +117,7 @@
<h3 class="text-sm font-semibold text-surface-800">消费来源(Top</h3> <h3 class="text-sm font-semibold text-surface-800">消费来源(Top</h3>
<p class="saas-muted text-xs">模型完成 vs 外部能力,按成本降序前 5</p> <p class="saas-muted text-xs">模型完成 vs 外部能力,按成本降序前 5</p>
</div> </div>
<a class="text-sm text-primary-700 hover:underline" href={`/admin/org/${orgSlug}/usage`}>查看全部分账</a> <a class="text-sm text-primary-700 hover:underline" href={`/admin/usage`}>查看全部分账</a>
</div> </div>
<div class="overflow-x-auto"> <div class="overflow-x-auto">
<table class="data-table"> <table class="data-table">
@@ -167,7 +169,7 @@
{#each usage.projects as p} {#each usage.projects as p}
<tr> <tr>
<td class="font-medium"> <td class="font-medium">
<a class="hover:text-primary-700 hover:underline" href={`/admin/org/${orgSlug}/projects/${p.projectId}`}> <a class="hover:text-primary-700 hover:underline" href={`/admin/projects/${p.projectId}`}>
{p.projectName} {p.projectName}
</a> </a>
</td> </td>
@@ -1,6 +1,8 @@
<script lang="ts"> <script lang="ts">
import { page } from '$app/state'; import { page } from '$app/state';
import { api, type CapabilityConnection } from '$lib/api'; import { api, type CapabilityConnection } from '$lib/api';
import { session } from '$lib/session';
import { resolveOrg } from '$lib/org';
import { fmtDate } from '$lib/format'; import { fmtDate } from '$lib/format';
import { Label } from 'bits-ui'; import { Label } from 'bits-ui';
import PageHeader from '$lib/components/PageHeader.svelte'; import PageHeader from '$lib/components/PageHeader.svelte';
@@ -8,7 +10,8 @@
import ErrorBanner from '$lib/components/ErrorBanner.svelte'; import ErrorBanner from '$lib/components/ErrorBanner.svelte';
import { toastError, toastSuccess } from '$lib/toast'; import { toastError, toastSuccess } from '$lib/toast';
const slug = $derived(page.params.slug ?? ''); const org = $derived(resolveOrg($session.me, page.url.search));
const slug = $derived(org?.slug ?? '');
const KNOWN_CAPABILITIES = [ const KNOWN_CAPABILITIES = [
{ id: 'pdf_to_md_bundle', label: 'PDF → Markdown', description: '将 PDF 转换为带图片的 Markdown bundle(阿里云文档智能,含公式 LaTeX 识别)' }, { id: 'pdf_to_md_bundle', label: 'PDF → Markdown', description: '将 PDF 转换为带图片的 Markdown bundle(阿里云文档智能,含公式 LaTeX 识别)' },
@@ -1,13 +1,16 @@
<script lang="ts"> <script lang="ts">
import { page } from '$app/state'; import { page } from '$app/state';
import { api, type CapacityDimension, type CapacityDimensionRow, type CapacityPolicyView } from '$lib/api'; import { api, type CapacityDimension, type CapacityDimensionRow, type CapacityPolicyView } from '$lib/api';
import { session } from '$lib/session';
import { resolveOrg } from '$lib/org';
import PageHeader from '$lib/components/PageHeader.svelte'; import PageHeader from '$lib/components/PageHeader.svelte';
import LoadingState from '$lib/components/LoadingState.svelte'; import LoadingState from '$lib/components/LoadingState.svelte';
import ErrorBanner from '$lib/components/ErrorBanner.svelte'; import ErrorBanner from '$lib/components/ErrorBanner.svelte';
import EmptyState from '$lib/components/EmptyState.svelte'; import EmptyState from '$lib/components/EmptyState.svelte';
import { toastError, toastSuccess } from '$lib/toast'; import { toastError, toastSuccess } from '$lib/toast';
const slug = $derived(page.params.slug ?? ''); const org = $derived(resolveOrg($session.me, page.url.search));
const slug = $derived(org?.slug ?? '');
// Friendlier, user-facing labels. No spec jargon (墙钟 → 运行时长, etc.). // Friendlier, user-facing labels. No spec jargon (墙钟 → 运行时长, etc.).
const DIMENSION_LABELS: Record<CapacityDimension, string> = { const DIMENSION_LABELS: Record<CapacityDimension, string> = {
@@ -1,6 +1,8 @@
<script lang="ts"> <script lang="ts">
import { page } from '$app/state'; import { page } from '$app/state';
import { api, type FeishuApplicationConnection } from '$lib/api'; import { api, type FeishuApplicationConnection } from '$lib/api';
import { session } from '$lib/session';
import { resolveOrg } from '$lib/org';
import { fmtDate } from '$lib/format'; import { fmtDate } from '$lib/format';
import { Label } from 'bits-ui'; import { Label } from 'bits-ui';
import PageHeader from '$lib/components/PageHeader.svelte'; import PageHeader from '$lib/components/PageHeader.svelte';
@@ -8,7 +10,8 @@
import ErrorBanner from '$lib/components/ErrorBanner.svelte'; import ErrorBanner from '$lib/components/ErrorBanner.svelte';
import { toastError, toastSuccess } from '$lib/toast'; import { toastError, toastSuccess } from '$lib/toast';
const slug = $derived(page.params.slug ?? ''); const org = $derived(resolveOrg($session.me, page.url.search));
const slug = $derived(org?.slug ?? '');
let connection = $state<FeishuApplicationConnection | null>(null); let connection = $state<FeishuApplicationConnection | null>(null);
let loading = $state(true); let loading = $state(true);
@@ -1,6 +1,8 @@
<script lang="ts"> <script lang="ts">
import { page } from '$app/state'; import { page } from '$app/state';
import { api, type OrgMember } from '$lib/api'; import { api, type OrgMember } from '$lib/api';
import { session } from '$lib/session';
import { resolveOrg } from '$lib/org';
import { fmtDate } from '$lib/format'; import { fmtDate } from '$lib/format';
import { ORG_ROLES, ORG_ROLE_LABELS, PERMISSION_ROLE_LABELS } from '$lib/constants'; import { ORG_ROLES, ORG_ROLE_LABELS, PERMISSION_ROLE_LABELS } from '$lib/constants';
import PageHeader from '$lib/components/PageHeader.svelte'; import PageHeader from '$lib/components/PageHeader.svelte';
@@ -10,7 +12,8 @@
import SelectField from '$lib/components/SelectField.svelte'; import SelectField from '$lib/components/SelectField.svelte';
import { toastError, toastSuccess } from '$lib/toast'; import { toastError, toastSuccess } from '$lib/toast';
const slug = $derived(page.params.slug ?? ''); const org = $derived(resolveOrg($session.me, page.url.search));
const slug = $derived(org?.slug ?? '');
const roleItems = ORG_ROLES.map((r) => ({ value: r, label: ORG_ROLE_LABELS[r] })); const roleItems = ORG_ROLES.map((r) => ({ value: r, label: ORG_ROLE_LABELS[r] }));
const permHint = Object.values(PERMISSION_ROLE_LABELS).join(' / '); const permHint = Object.values(PERMISSION_ROLE_LABELS).join(' / ');
@@ -0,0 +1,23 @@
<script lang="ts">
/**
* Legacy bookmarks: /admin/org/:slug[/...] → /admin[/...]
* Tenancy lives on the silo host, not the path.
*/
import { onMount } from 'svelte';
import { goto } from '$app/navigation';
import { page } from '$app/state';
onMount(() => {
const raw = page.params.path ?? '';
const segments = raw.split('/').filter(Boolean);
// Drop the old org slug (first segment) when present.
const rest = segments.length > 0 ? segments.slice(1).join('/') : '';
const target = rest === '' ? '/admin' : `/admin/${rest}`;
const q = page.url.search;
void goto(`${target}${q}`, { replaceState: true });
});
</script>
<div class="saas-status-panel">
<p class="text-sm text-surface-600">正在重定向到新地址…</p>
</div>
@@ -2,6 +2,7 @@
import { page } from '$app/state'; import { page } from '$app/state';
import { api, type ExplorerData, type ExplorerFolder, type ExplorerProject, type OrgMembership } from '$lib/api'; import { api, type ExplorerData, type ExplorerFolder, type ExplorerProject, type OrgMembership } from '$lib/api';
import { session } from '$lib/session'; import { session } from '$lib/session';
import { resolveOrg } from '$lib/org';
import FolderTree from '$lib/components/FolderTree.svelte'; import FolderTree from '$lib/components/FolderTree.svelte';
import PageHeader from '$lib/components/PageHeader.svelte'; import PageHeader from '$lib/components/PageHeader.svelte';
import LoadingState from '$lib/components/LoadingState.svelte'; import LoadingState from '$lib/components/LoadingState.svelte';
@@ -13,8 +14,8 @@
import { fmtDate } from '$lib/format'; import { fmtDate } from '$lib/format';
import { toastError, toastSuccess } from '$lib/toast'; import { toastError, toastSuccess } from '$lib/toast';
const slug = $derived(page.params.slug ?? ''); const org = $derived(resolveOrg($session.me, page.url.search));
const org = $derived(($session.me?.organizations.find((o) => o.slug === slug) as OrgMembership | undefined) ?? null); const slug = $derived(org?.slug ?? '');
const isAdmin = $derived(!!org && (org.role === 'OWNER' || org.role === 'ADMIN')); const isAdmin = $derived(!!org && (org.role === 'OWNER' || org.role === 'ADMIN'));
let data = $state<ExplorerData | null>(null); let data = $state<ExplorerData | null>(null);
@@ -87,7 +88,7 @@
projectName = ''; projectName = '';
projectFolder = ''; projectFolder = '';
showProjectModal = false; showProjectModal = false;
window.location.href = `/admin/org/${slug}/projects/${res.id}`; window.location.href = `/admin/projects/${res.id}`;
} catch (err) { } catch (err) {
toastError(err instanceof Error ? err.message : String(err)); toastError(err instanceof Error ? err.message : String(err));
} }
@@ -207,7 +208,7 @@
</thead> </thead>
<tbody> <tbody>
{#each myProjects as p} {#each myProjects as p}
<tr class="cursor-pointer" onclick={() => (window.location.href = `/admin/org/${slug}/projects/${p.id}`)}> <tr class="cursor-pointer" onclick={() => (window.location.href = `/admin/projects/${p.id}`)}>
<td class="font-medium">{p.name}</td> <td class="font-medium">{p.name}</td>
<td class="font-mono text-xs">{p.binding ? `群 ${p.binding.chatId}` : '—'}</td> <td class="font-mono text-xs">{p.binding ? `群 ${p.binding.chatId}` : '—'}</td>
<td class="text-surface-700">{fmtDate(p.createdAt)}</td> <td class="text-surface-700">{fmtDate(p.createdAt)}</td>
@@ -9,6 +9,8 @@
type ExplorerData, type ExplorerData,
type ProjectUsageReport, type ProjectUsageReport,
} from '$lib/api'; } from '$lib/api';
import { session } from '$lib/session';
import { resolveOrg } from '$lib/org';
import { import {
fmtCost, fmtCost,
fmtDate, fmtDate,
@@ -27,7 +29,8 @@
import Icon from '$lib/components/Icon.svelte'; import Icon from '$lib/components/Icon.svelte';
import { toastError, toastSuccess } from '$lib/toast'; import { toastError, toastSuccess } from '$lib/toast';
const slug = $derived(page.params.slug ?? ''); const org = $derived(resolveOrg($session.me, page.url.search));
const slug = $derived(org?.slug ?? '');
const projectId = $derived(page.params.projectId ?? ''); const projectId = $derived(page.params.projectId ?? '');
const roleItems = PERMISSION_ROLES.map((r) => ({ value: r, label: PERMISSION_ROLE_LABELS[r] })); const roleItems = PERMISSION_ROLES.map((r) => ({ value: r, label: PERMISSION_ROLE_LABELS[r] }));
const roleChain = `${PERMISSION_ROLE_LABELS.READ} ⊂ ${PERMISSION_ROLE_LABELS.EDIT} ⊂ ${PERMISSION_ROLE_LABELS.MANAGE}`; const roleChain = `${PERMISSION_ROLE_LABELS.READ} ⊂ ${PERMISSION_ROLE_LABELS.EDIT} ⊂ ${PERMISSION_ROLE_LABELS.MANAGE}`;
@@ -109,7 +112,7 @@
if (!confirm(`归档项目 ${proj?.name}?`)) return; if (!confirm(`归档项目 ${proj?.name}?`)) return;
try { try {
await api.archiveProject(slug, projectId); await api.archiveProject(slug, projectId);
window.location.href = `/admin/org/${slug}/projects`; window.location.href = `/admin/projects`;
} catch (err) { } catch (err) {
toastError(err instanceof Error ? err.message : String(err)); toastError(err instanceof Error ? err.message : String(err));
} }
@@ -170,7 +173,7 @@
{:else if proj} {:else if proj}
<div class="mb-2"> <div class="mb-2">
<a <a
href={`/admin/org/${slug}/projects`} href={`/admin/projects`}
class="inline-flex items-center gap-1 text-sm text-surface-700 hover:text-primary-600" class="inline-flex items-center gap-1 text-sm text-surface-700 hover:text-primary-600"
> >
<Icon name="arrow-left" class="h-4 w-4" /> <Icon name="arrow-left" class="h-4 w-4" />
@@ -293,7 +296,7 @@
{fmtTokens(projectUsage.inputTokens, projectUsage.outputTokens)} {fmtTokens(projectUsage.inputTokens, projectUsage.outputTokens)}
</p> </p>
</div> </div>
<a class="text-sm text-primary-700 hover:underline" href={`/admin/org/${slug}/usage`}>组织报告</a> <a class="text-sm text-primary-700 hover:underline" href={`/admin/usage`}>组织报告</a>
</div> </div>
{#if projectUsage.breakdown.length === 0} {#if projectUsage.breakdown.length === 0}
<div class="px-5 py-4 text-sm text-surface-600">尚无 UsageFact。</div> <div class="px-5 py-4 text-sm text-surface-600">尚无 UsageFact。</div>
@@ -368,7 +371,7 @@
<td class="text-right"> <td class="text-right">
<a <a
class="text-sm text-primary-700 hover:underline" class="text-sm text-primary-700 hover:underline"
href={`/admin/org/${slug}/sessions/${s.id}`} href={`/admin/sessions/${s.id}`}
> >
详情 详情
</a> </a>
@@ -1,6 +1,8 @@
<script lang="ts"> <script lang="ts">
import { page } from '$app/state'; import { page } from '$app/state';
import { api, type ProviderConnectionRow } from '$lib/api'; import { api, type ProviderConnectionRow } from '$lib/api';
import { session } from '$lib/session';
import { resolveOrg } from '$lib/org';
import { fmtDate, providerModeLabel } from '$lib/format'; import { fmtDate, providerModeLabel } from '$lib/format';
import { Label } from 'bits-ui'; import { Label } from 'bits-ui';
import PageHeader from '$lib/components/PageHeader.svelte'; import PageHeader from '$lib/components/PageHeader.svelte';
@@ -8,7 +10,8 @@
import ErrorBanner from '$lib/components/ErrorBanner.svelte'; import ErrorBanner from '$lib/components/ErrorBanner.svelte';
import { toastError, toastSuccess } from '$lib/toast'; import { toastError, toastSuccess } from '$lib/toast';
const slug = $derived(page.params.slug ?? ''); const org = $derived(resolveOrg($session.me, page.url.search));
const slug = $derived(org?.slug ?? '');
let connections = $state<ProviderConnectionRow[]>([]); let connections = $state<ProviderConnectionRow[]>([]);
let loading = $state(true); let loading = $state(true);
@@ -1,6 +1,8 @@
<script lang="ts"> <script lang="ts">
import { page } from '$app/state'; import { page } from '$app/state';
import { api, type AgentRoleRow, type AgentModelRow, type AgentSkillRow } from '$lib/api'; import { api, type AgentRoleRow, type AgentModelRow, type AgentSkillRow } from '$lib/api';
import { session } from '$lib/session';
import { resolveOrg } from '$lib/org';
import PageHeader from '$lib/components/PageHeader.svelte'; import PageHeader from '$lib/components/PageHeader.svelte';
import LoadingState from '$lib/components/LoadingState.svelte'; import LoadingState from '$lib/components/LoadingState.svelte';
import ErrorBanner from '$lib/components/ErrorBanner.svelte'; import ErrorBanner from '$lib/components/ErrorBanner.svelte';
@@ -8,7 +10,8 @@
import RoleCard from '$lib/components/RoleCard.svelte'; import RoleCard from '$lib/components/RoleCard.svelte';
import { toastError, toastSuccess } from '$lib/toast'; import { toastError, toastSuccess } from '$lib/toast';
const slug = $derived(page.params.slug ?? ''); const org = $derived(resolveOrg($session.me, page.url.search));
const slug = $derived(org?.slug ?? '');
let roles = $state<AgentRoleRow[]>([]); let roles = $state<AgentRoleRow[]>([]);
let models = $state<AgentModelRow[]>([]); let models = $state<AgentModelRow[]>([]);
@@ -1,6 +1,8 @@
<script lang="ts"> <script lang="ts">
import { page } from '$app/state'; import { page } from '$app/state';
import { api, type SessionDetail, type SessionRunRow, type UsageFactRow } from '$lib/api'; import { api, type SessionDetail, type SessionRunRow, type UsageFactRow } from '$lib/api';
import { session } from '$lib/session';
import { resolveOrg } from '$lib/org';
import { import {
fmtCost, fmtCost,
fmtDate, fmtDate,
@@ -16,7 +18,8 @@
import EmptyState from '$lib/components/EmptyState.svelte'; import EmptyState from '$lib/components/EmptyState.svelte';
import Icon from '$lib/components/Icon.svelte'; import Icon from '$lib/components/Icon.svelte';
const slug = $derived(page.params.slug ?? ''); const org = $derived(resolveOrg($session.me, page.url.search));
const slug = $derived(org?.slug ?? '');
const sessionId = $derived(page.params.sessionId ?? ''); const sessionId = $derived(page.params.sessionId ?? '');
let detail = $state<SessionDetail | null>(null); let detail = $state<SessionDetail | null>(null);
@@ -92,7 +95,7 @@
<div class="mb-2"> <div class="mb-2">
<a <a
class="inline-flex items-center gap-1 text-sm text-surface-700 hover:text-primary-700" class="inline-flex items-center gap-1 text-sm text-surface-700 hover:text-primary-700"
href={`/admin/org/${slug}/projects/${detail.project.id}`} href={`/admin/projects/${detail.project.id}`}
> >
<Icon name="arrow-left" class="h-4 w-4" /> <Icon name="arrow-left" class="h-4 w-4" />
返回项目 {detail.project.name} 返回项目 {detail.project.name}
@@ -113,7 +116,7 @@
<div> <div>
<dt class="text-surface-600">项目</dt> <dt class="text-surface-600">项目</dt>
<dd class="mt-0.5"> <dd class="mt-0.5">
<a class="text-primary-700 hover:underline" href={`/admin/org/${slug}/projects/${detail.project.id}`}> <a class="text-primary-700 hover:underline" href={`/admin/projects/${detail.project.id}`}>
{detail.project.name} {detail.project.name}
</a> </a>
</dd> </dd>
@@ -1,6 +1,8 @@
<script lang="ts"> <script lang="ts">
import { page } from '$app/state'; import { page } from '$app/state';
import { api, type AgentSkillRow, type SkillFileEntry } from '$lib/api'; import { api, type AgentSkillRow, type SkillFileEntry } from '$lib/api';
import { session } from '$lib/session';
import { resolveOrg } from '$lib/org';
import PageHeader from '$lib/components/PageHeader.svelte'; import PageHeader from '$lib/components/PageHeader.svelte';
import LoadingState from '$lib/components/LoadingState.svelte'; import LoadingState from '$lib/components/LoadingState.svelte';
import ErrorBanner from '$lib/components/ErrorBanner.svelte'; import ErrorBanner from '$lib/components/ErrorBanner.svelte';
@@ -8,7 +10,8 @@
import SkillEditor from '$lib/components/SkillEditor.svelte'; import SkillEditor from '$lib/components/SkillEditor.svelte';
import { toastError, toastSuccess } from '$lib/toast'; import { toastError, toastSuccess } from '$lib/toast';
const slug = $derived(page.params.slug ?? ''); const org = $derived(resolveOrg($session.me, page.url.search));
const slug = $derived(org?.slug ?? '');
let skills = $state<AgentSkillRow[]>([]); let skills = $state<AgentSkillRow[]>([]);
let loading = $state(true); let loading = $state(true);
@@ -2,6 +2,8 @@
import { Collapsible } from 'bits-ui'; import { Collapsible } from 'bits-ui';
import { page } from '$app/state'; import { page } from '$app/state';
import { api, type TeamRow, type TeamMemberRow } from '$lib/api'; import { api, type TeamRow, type TeamMemberRow } from '$lib/api';
import { session } from '$lib/session';
import { resolveOrg } from '$lib/org';
import { fmtDate } from '$lib/format'; import { fmtDate } from '$lib/format';
import PageHeader from '$lib/components/PageHeader.svelte'; import PageHeader from '$lib/components/PageHeader.svelte';
import LoadingState from '$lib/components/LoadingState.svelte'; import LoadingState from '$lib/components/LoadingState.svelte';
@@ -9,7 +11,8 @@
import EmptyState from '$lib/components/EmptyState.svelte'; import EmptyState from '$lib/components/EmptyState.svelte';
import { toastError, toastSuccess } from '$lib/toast'; import { toastError, toastSuccess } from '$lib/toast';
const slug = $derived(page.params.slug ?? ''); const org = $derived(resolveOrg($session.me, page.url.search));
const slug = $derived(org?.slug ?? '');
let teams = $state<TeamRow[]>([]); let teams = $state<TeamRow[]>([]);
let loading = $state(true); let loading = $state(true);
@@ -1,6 +1,8 @@
<script lang="ts"> <script lang="ts">
import { page } from '$app/state'; import { page } from '$app/state';
import { api, type UsageReport, type UsageBreakdownRow } from '$lib/api'; import { api, type UsageReport, type UsageBreakdownRow } from '$lib/api';
import { session } from '$lib/session';
import { resolveOrg } from '$lib/org';
import { import {
fmtCost, fmtCost,
fmtDateOnly, fmtDateOnly,
@@ -15,7 +17,8 @@
import ErrorBanner from '$lib/components/ErrorBanner.svelte'; import ErrorBanner from '$lib/components/ErrorBanner.svelte';
import EmptyState from '$lib/components/EmptyState.svelte'; import EmptyState from '$lib/components/EmptyState.svelte';
const slug = $derived(page.params.slug ?? ''); const org = $derived(resolveOrg($session.me, page.url.search));
const slug = $derived(org?.slug ?? '');
let usage = $state<UsageReport | null>(null); let usage = $state<UsageReport | null>(null);
let loading = $state(true); let loading = $state(true);
@@ -224,7 +227,7 @@
<td class="tabular-nums text-surface-600">{fmtTokens(p.inputTokens, p.outputTokens)}</td> <td class="tabular-nums text-surface-600">{fmtTokens(p.inputTokens, p.outputTokens)}</td>
<td class="tabular-nums">{fmtCost(p.costUsd)}</td> <td class="tabular-nums">{fmtCost(p.costUsd)}</td>
<td class="text-right"> <td class="text-right">
<a class="text-sm text-primary-700 hover:underline" href={`/admin/org/${slug}/projects/${p.projectId}`}> <a class="text-sm text-primary-700 hover:underline" href={`/admin/projects/${p.projectId}`}>
查看项目 查看项目
</a> </a>
</td> </td>
+2 -2
View File
@@ -1,12 +1,12 @@
{ {
"name": "@paradigm/hub", "name": "@paradigm/hub",
"version": "0.0.34", "version": "0.0.35",
"lockfileVersion": 3, "lockfileVersion": 3,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "@paradigm/hub", "name": "@paradigm/hub",
"version": "0.0.34", "version": "0.0.35",
"dependencies": { "dependencies": {
"@alicloud/credentials": "^2.4.5", "@alicloud/credentials": "^2.4.5",
"@alicloud/docmind-api20220711": "^1.4.15", "@alicloud/docmind-api20220711": "^1.4.15",
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "@paradigm/hub", "name": "@paradigm/hub",
"version": "0.0.34", "version": "0.0.35",
"private": true, "private": true,
"type": "module", "type": "module",
"engines": { "engines": {
+17 -6
View File
@@ -432,16 +432,16 @@ async function resolvePostLoginRedirect(
select: { organization: { select: { slug: true, name: true } } }, select: { organization: { select: { slug: true, name: true } } },
}); });
if (intended === null) return "/admin?error=not_an_active_org_member"; if (intended === null) return "/admin?error=not_an_active_org_member";
const orgRoot = `/admin/org/${intended.organization.slug}`; const orgRoot = "/admin";
// Default / missing returnTo sanitizes to "/admin". Always land in the org // Default / missing returnTo sanitizes to "/admin". Always land in the org
// admin SPA (not the legacy static "close this tab" complete page). // admin SPA (not the legacy static "close this tab" complete page).
if (returnTo === "/admin") { if (returnTo === "/admin") {
return orgRoot; return orgRoot;
} }
return returnTo === orgRoot || returnTo.startsWith(`${orgRoot}/`) ? returnTo : orgRoot; return normalizeAdminReturnTo(returnTo) ?? orgRoot;
} }
if (returnTo !== "/admin" && returnTo.startsWith("/admin")) { if (returnTo !== "/admin" && returnTo.startsWith("/admin")) {
return returnTo; return normalizeAdminReturnTo(returnTo) ?? "/admin";
} }
const membership = await prisma.organizationMembership.findFirst({ const membership = await prisma.organizationMembership.findFirst({
where: { where: {
@@ -454,7 +454,7 @@ async function resolvePostLoginRedirect(
orderBy: { createdAt: "asc" }, orderBy: { createdAt: "asc" },
}); });
if (membership !== null) { if (membership !== null) {
return `/admin/org/${membership.organization.slug}`; return "/admin";
} }
// Member-only or no org: still land on a shell page (SPA will explain). // Member-only or no org: still land on a shell page (SPA will explain).
const any = await prisma.organizationMembership.findFirst({ const any = await prisma.organizationMembership.findFirst({
@@ -463,7 +463,7 @@ async function resolvePostLoginRedirect(
orderBy: { createdAt: "asc" }, orderBy: { createdAt: "asc" },
}); });
if (any !== null) { if (any !== null) {
return `/admin/org/${any.organization.slug}`; return "/admin/projects";
} }
return "/admin/login?error=no_organization"; return "/admin/login?error=no_organization";
} }
@@ -489,7 +489,18 @@ export function sanitizeReturnTo(raw: string): string {
if (!raw.startsWith("/admin")) { if (!raw.startsWith("/admin")) {
return "/admin"; return "/admin";
} }
return raw; return normalizeAdminReturnTo(raw) ?? "/admin";
}
/** Map legacy `/admin/org/:slug[...]` bookmarks onto slugless `/admin[...]` paths. */
export function normalizeAdminReturnTo(path: string): string | null {
if (!path.startsWith("/admin")) return null;
const legacy = path.match(/^\/admin\/org\/[^/]+(\/.*)?$/);
if (legacy) {
const rest = legacy[1] ?? "";
return rest === "" ? "/admin" : `/admin${rest}`;
}
return path;
} }
function trimTrailingSlash(url: string): string { function trimTrailingSlash(url: string): string {
+6 -6
View File
@@ -170,7 +170,7 @@ describe("admin auth + org API guards", () => {
try { try {
const res = await app.inject({ const res = await app.inject({
method: "GET", method: "GET",
url: "/auth/feishu?returnTo=/admin/org/test-default", url: "/auth/feishu?returnTo=/admin",
}); });
expect(res.statusCode).toBe(302); expect(res.statusCode).toBe(302);
const location = res.headers.location; const location = res.headers.location;
@@ -233,7 +233,7 @@ describe("admin auth + org API guards", () => {
try { try {
const nonce = "nonce-test-1"; const nonce = "nonce-test-1";
const state = signOAuthState( const state = signOAuthState(
{ nonce, returnTo: "/admin/org/test-default" }, { nonce, returnTo: "/admin" },
SESSION_SECRET, SESSION_SECRET,
); );
const res = await app.inject({ const res = await app.inject({
@@ -242,7 +242,7 @@ describe("admin auth + org API guards", () => {
headers: { cookie: `${OAUTH_STATE_COOKIE_NAME}=${nonce}` }, headers: { cookie: `${OAUTH_STATE_COOKIE_NAME}=${nonce}` },
}); });
expect(res.statusCode).toBe(302); expect(res.statusCode).toBe(302);
expect(res.headers.location).toBe("/admin/org/test-default"); expect(res.headers.location).toBe("/admin");
expect(JSON.stringify(res.headers["set-cookie"])).toContain("cph_session="); expect(JSON.stringify(res.headers["set-cookie"])).toContain("cph_session=");
const user = await prisma.user.findUnique({ where: { feishuOpenId: "ou_new" } }); const user = await prisma.user.findUnique({ where: { feishuOpenId: "ou_new" } });
@@ -293,7 +293,7 @@ describe("admin auth + org API guards", () => {
try { try {
const start = await app.inject({ const start = await app.inject({
method: "GET", method: "GET",
url: "/auth/feishu/test-default?returnTo=/admin/org/test-default/settings", url: "/auth/feishu/test-default?returnTo=/admin/settings",
}); });
expect(start.statusCode).toBe(302); expect(start.statusCode).toBe(302);
const authorize = new URL(String(start.headers.location)); const authorize = new URL(String(start.headers.location));
@@ -308,7 +308,7 @@ describe("admin auth + org API guards", () => {
headers: { cookie: nonceCookie }, headers: { cookie: nonceCookie },
}); });
expect(callback.statusCode).toBe(302); expect(callback.statusCode).toBe(302);
expect(callback.headers.location).toBe("/admin/org/test-default/settings"); expect(callback.headers.location).toBe("/admin/settings");
const sessionCookie = cookiePair(callback.headers["set-cookie"], "cph_session"); const sessionCookie = cookiePair(callback.headers["set-cookie"], "cph_session");
const me = await app.inject({ method: "GET", url: "/api/me", headers: { cookie: sessionCookie } }); const me = await app.inject({ method: "GET", url: "/api/me", headers: { cookie: sessionCookie } });
expect(me.statusCode).toBe(200); expect(me.statusCode).toBe(200);
@@ -346,7 +346,7 @@ describe("admin auth + org API guards", () => {
headers: { cookie: cookiePair(defaultStart.headers["set-cookie"], OAUTH_STATE_COOKIE_NAME) }, headers: { cookie: cookiePair(defaultStart.headers["set-cookie"], OAUTH_STATE_COOKIE_NAME) },
}); });
expect(defaultCallback.statusCode).toBe(302); expect(defaultCallback.statusCode).toBe(302);
expect(defaultCallback.headers.location).toBe("/admin/org/test-default"); expect(defaultCallback.headers.location).toBe("/admin");
await connections.disable({ organizationId: DEFAULT_ORG_ID, actorUserId: "scoped-owner" }); await connections.disable({ organizationId: DEFAULT_ORG_ID, actorUserId: "scoped-owner" });
const revoked = await app.inject({ method: "GET", url: "/api/me", headers: { cookie: sessionCookie } }); const revoked = await app.inject({ method: "GET", url: "/api/me", headers: { cookie: sessionCookie } });
+9 -6
View File
@@ -68,14 +68,14 @@ describe("session cookie signing", () => {
describe("oauth state signing", () => { describe("oauth state signing", () => {
it("round-trips state with returnTo", () => { it("round-trips state with returnTo", () => {
const token = signOAuthState( const token = signOAuthState(
{ nonce: "abc", returnTo: "/admin/org/acme" }, { nonce: "abc", returnTo: "/admin" },
SECRET, SECRET,
600, 600,
1_700_000_000, 1_700_000_000,
); );
expect(verifyOAuthState(token, SECRET, 1_700_000_100)).toEqual({ expect(verifyOAuthState(token, SECRET, 1_700_000_100)).toEqual({
nonce: "abc", nonce: "abc",
returnTo: "/admin/org/acme", returnTo: "/admin",
exp: 1_700_000_600, exp: 1_700_000_600,
}); });
}); });
@@ -83,13 +83,13 @@ describe("oauth state signing", () => {
it("binds state to an Organization and connection as one inseparable scope", () => { it("binds state to an Organization and connection as one inseparable scope", () => {
const token = signOAuthState({ const token = signOAuthState({
nonce: "scoped", nonce: "scoped",
returnTo: "/admin/org/acme", returnTo: "/admin",
organizationId: "org-acme", organizationId: "org-acme",
connectionId: "connection-acme", connectionId: "connection-acme",
}, SECRET, 600, 1_700_000_000); }, SECRET, 600, 1_700_000_000);
expect(verifyOAuthState(token, SECRET, 1_700_000_100)).toEqual({ expect(verifyOAuthState(token, SECRET, 1_700_000_100)).toEqual({
nonce: "scoped", nonce: "scoped",
returnTo: "/admin/org/acme", returnTo: "/admin",
organizationId: "org-acme", organizationId: "org-acme",
connectionId: "connection-acme", connectionId: "connection-acme",
exp: 1_700_000_600, exp: 1_700_000_600,
@@ -98,8 +98,11 @@ describe("oauth state signing", () => {
}); });
describe("sanitizeReturnTo", () => { describe("sanitizeReturnTo", () => {
it("allows admin paths", () => { it("allows admin paths and rewrites legacy org slug prefixes", () => {
expect(sanitizeReturnTo("/admin/org/acme")).toBe("/admin/org/acme"); expect(sanitizeReturnTo("/admin")).toBe("/admin");
expect(sanitizeReturnTo("/admin/usage")).toBe("/admin/usage");
expect(sanitizeReturnTo("/admin/org/acme")).toBe("/admin");
expect(sanitizeReturnTo("/admin/org/acme/usage")).toBe("/admin/usage");
}); });
it("blocks open redirects", () => { it("blocks open redirects", () => {
+1
View File
@@ -23,6 +23,7 @@ describe("isSiloHttpRateLimitExempt", () => {
expect(isSiloHttpRateLimitExempt("/favicon.svg")).toBe(true); expect(isSiloHttpRateLimitExempt("/favicon.svg")).toBe(true);
expect(isSiloHttpRateLimitExempt("/robots.txt")).toBe(true); expect(isSiloHttpRateLimitExempt("/robots.txt")).toBe(true);
expect(isSiloHttpRateLimitExempt("/admin")).toBe(true); expect(isSiloHttpRateLimitExempt("/admin")).toBe(true);
expect(isSiloHttpRateLimitExempt("/admin/members")).toBe(true);
expect(isSiloHttpRateLimitExempt("/admin/org/para-26071100/members")).toBe(true); expect(isSiloHttpRateLimitExempt("/admin/org/para-26071100/members")).toBe(true);
}); });