Compare commits

..

1 Commits

Author SHA1 Message Date
hongjr03 9834181506 feat(hub): usage fact breakdown API + admin usage/session UI + release v0.0.34
Expose UsageFact kind/capability rollups on org and project usage reports,
and add admin pages that separate model tokens from external-capability meters.
2026-07-18 17:19:22 +00:00
25 changed files with 129 additions and 221 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/projects/${p.id}`} href={`/admin/org/${slug}/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
@@ -1,40 +0,0 @@
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}`;
}
+4 -7
View File
@@ -35,9 +35,12 @@ 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();
@@ -45,12 +48,6 @@ 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;
} }
+76 -51
View File
@@ -5,7 +5,6 @@
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';
@@ -33,36 +32,56 @@
{ 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((o) => isOrgAdmin(o)); return memberships().filter(isAdmin);
} }
function currentOrg(): OrgMembership | null { function currentOrg(): OrgMembership | null {
return resolveOrg($session.me, page.url.search); const slug = orgSlugFromPath();
if (!slug) return null;
return memberships().find((o) => o.slug === slug) ?? null;
} }
function isOnProjectRoute(): boolean { function pickHomeOrg(): OrgMembership | null {
const parts = page.url.pathname.split('/').filter(Boolean); const admin = adminOrgs()[0];
// /admin/projects or /admin/projects/:id if (admin) return admin;
return parts[0] === 'admin' && parts[1] === 'projects'; return memberships()[0] ?? null;
} }
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') return ''; if (parts[0] !== 'admin' || parts[1] !== 'org' || !parts[2]) return '';
// /admin → overview; /admin/usage → usage; /admin/projects/x → projects return parts[3] ?? 'overview';
return parts[1] ?? 'overview';
} }
function navHref(key: string): string { function navHref(key: string): string {
if (key === 'overview') return adminPath(); const slug = currentOrg()?.slug ?? pickHomeOrg()?.slug;
return adminPath(key); if (!slug) return '/';
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 '概览';
@@ -72,10 +91,7 @@
function switchOrg(nextSlug: string) { function switchOrg(nextSlug: string) {
if (!nextSlug || nextSlug === currentOrg()?.slug) return; if (!nextSlug || nextSlug === currentOrg()?.slug) return;
// Path is tenancy-free; keep optional ?org= for local multi-membership debugging. void goto(`/admin/org/${nextSlug}`);
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) {
@@ -98,23 +114,33 @@
$effect(() => { $effect(() => {
if ($session.loading || !$session.me) return; if ($session.loading || !$session.me) return;
const path = page.url.pathname; const slug = orgSlugFromPath();
// Legacy /admin/org/:slug… is handled by admin/org/[...path] page. const matched = slug ? memberships().find((o) => o.slug === slug) : null;
const org = currentOrg(); // Org admins: route to their first admin org if none matched as admin.
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;
}
// Member only: allow project routes; bounce admin-only surfaces to projects. // Members (non-admin): project pages are open to project MANAGE holders;
if (org && !isOrgAdmin(org)) { // the org overview and other admin-only surfaces are not for them.
if (matched && !isAdmin(matched)) {
redirecting = false; redirecting = false;
if (!isOnProjectRoute()) { const parts = page.url.pathname.split('/').filter(Boolean);
const target = adminPath('projects'); const onOverview = parts.length === 3; // /admin/org/:slug
if (path !== target) { if (onOverview) {
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 });
} }
@@ -122,11 +148,12 @@
return; return;
} }
// No org resolved but user has memberships → land on first org's projects/overview via resolveOrg next tick // No matched org and no admin orgs: route a member to their first org's
if (!org && memberships().length > 0) { // projects page so they can reach project MANAGE surfaces.
const home = admins[0] ?? memberships()[0]!; if (!matched && memberships().length > 0) {
const target = isOrgAdmin(home) ? adminPath() : adminPath('projects'); const home = memberships()[0];
if (path !== target && !path.startsWith(`${target}/`)) { const target = `/admin/org/${home.slug}/projects`;
if (page.url.pathname !== target && !page.url.pathname.startsWith(`${target}/`)) {
redirecting = true; redirecting = true;
void goto(target, { replaceState: true }); void goto(target, { replaceState: true });
} }
@@ -147,14 +174,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">加载中…</p> <p class="text-sm">{redirecting ? '正在进入组织…' : '正在加载会话…'}</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-3 flex h-12 w-12 items-center justify-center border border-error-200 bg-error-50 text-error-700" 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"
> >
! !
</div> </div>
@@ -167,7 +194,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-4 flex h-12 w-12 items-center justify-center border border-primary-700 bg-primary-600 text-sm font-bold text-white" 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"
> >
CPH CPH
</div> </div>
@@ -176,7 +203,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() && isOrgAdmin(currentOrg()!)} {:else if currentOrg() && isAdmin(currentOrg()!)}
{@const org = currentOrg()!} {@const org = currentOrg()!}
{@const me = $session.me!} {@const me = $session.me!}
<div class="saas-shell"> <div class="saas-shell">
@@ -201,19 +228,17 @@
</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">{org.name}</div> <div class="truncate text-xs text-surface-600">Curriculum Hub</div>
</div> </div>
</div> </div>
{#if me.organizations.length > 1} <div class="px-3 pb-3">
<div class="px-3 pb-3"> <div class="mb-1.5 flex items-center gap-1.5 text-xs font-medium text-surface-700">
<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" />
<Icon name="org" class="h-3.5 w-3.5" /> 组织
组织
</div>
<SelectField items={orgSelectItems(me.organizations)} value={org.slug} onchange={switchOrg} />
</div> </div>
{/if} <SelectField items={orgSelectItems(me.organizations)} value={org.slug} onchange={switchOrg} />
</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>
@@ -283,13 +308,13 @@
</main> </main>
</div> </div>
</div> </div>
{:else if currentOrg() && !isOrgAdmin(currentOrg()!) && isOnProjectRoute()} {:else if currentOrg() && !isAdmin(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={adminPath('projects')} class="saas-btn-ghost px-2!" aria-label="返回项目列表"> <a href={`/admin/org/${org.slug}/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">
@@ -318,7 +343,7 @@
</main> </main>
</div> </div>
</div> </div>
{:else if currentOrg() && !isOrgAdmin(currentOrg()!)} {:else if currentOrg() && !isAdmin(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">
@@ -327,7 +352,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={adminPath('projects')}>查看我的项目</a> <a class="saas-btn-primary" href={`/admin/org/${denied.slug}/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">
@@ -338,14 +363,14 @@
</div> </div>
</div> </div>
{:else if memberships().length > 0} {:else if memberships().length > 0}
{@const denied = resolveOrg($session.me) ?? memberships()[0]!} {@const denied = pickHomeOrg()!}
<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={adminPath('projects')}>立即进入</a> <a class="saas-btn-primary" href={`/admin/org/${denied.slug}/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` : null; return target ? `/admin/org/${target.slug}` : null;
} }
onMount(() => { onMount(() => {
@@ -1,23 +0,0 @@
<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,7 +2,6 @@
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';
@@ -11,8 +10,7 @@
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';
const orgFromSession = $derived(resolveOrg($session.me, page.url.search)); let orgSlug = $derived(page.params.slug ?? '');
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);
@@ -98,7 +96,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/usage`}>完整用量报告</a> <a class="saas-btn-secondary py-1.5! text-sm" href={`/admin/org/${orgSlug}/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">
@@ -117,7 +115,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/usage`}>查看全部分账</a> <a class="text-sm text-primary-700 hover:underline" href={`/admin/org/${orgSlug}/usage`}>查看全部分账</a>
</div> </div>
<div class="overflow-x-auto"> <div class="overflow-x-auto">
<table class="data-table"> <table class="data-table">
@@ -169,7 +167,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/projects/${p.projectId}`}> <a class="hover:text-primary-700 hover:underline" href={`/admin/org/${orgSlug}/projects/${p.projectId}`}>
{p.projectName} {p.projectName}
</a> </a>
</td> </td>
@@ -1,8 +1,6 @@
<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';
@@ -10,8 +8,7 @@
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 org = $derived(resolveOrg($session.me, page.url.search)); const slug = $derived(page.params.slug ?? '');
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,16 +1,13 @@
<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 org = $derived(resolveOrg($session.me, page.url.search)); const slug = $derived(page.params.slug ?? '');
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,8 +1,6 @@
<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';
@@ -10,8 +8,7 @@
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 org = $derived(resolveOrg($session.me, page.url.search)); const slug = $derived(page.params.slug ?? '');
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,8 +1,6 @@
<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';
@@ -12,8 +10,7 @@
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 org = $derived(resolveOrg($session.me, page.url.search)); const slug = $derived(page.params.slug ?? '');
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(' / ');
@@ -2,7 +2,6 @@
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';
@@ -14,8 +13,8 @@
import { fmtDate } from '$lib/format'; import { fmtDate } from '$lib/format';
import { toastError, toastSuccess } from '$lib/toast'; import { toastError, toastSuccess } from '$lib/toast';
const org = $derived(resolveOrg($session.me, page.url.search)); const slug = $derived(page.params.slug ?? '');
const slug = $derived(org?.slug ?? ''); const org = $derived(($session.me?.organizations.find((o) => o.slug === slug) as OrgMembership | undefined) ?? null);
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);
@@ -88,7 +87,7 @@
projectName = ''; projectName = '';
projectFolder = ''; projectFolder = '';
showProjectModal = false; showProjectModal = false;
window.location.href = `/admin/projects/${res.id}`; window.location.href = `/admin/org/${slug}/projects/${res.id}`;
} catch (err) { } catch (err) {
toastError(err instanceof Error ? err.message : String(err)); toastError(err instanceof Error ? err.message : String(err));
} }
@@ -208,7 +207,7 @@
</thead> </thead>
<tbody> <tbody>
{#each myProjects as p} {#each myProjects as p}
<tr class="cursor-pointer" onclick={() => (window.location.href = `/admin/projects/${p.id}`)}> <tr class="cursor-pointer" onclick={() => (window.location.href = `/admin/org/${slug}/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,8 +9,6 @@
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,
@@ -29,8 +27,7 @@
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 org = $derived(resolveOrg($session.me, page.url.search)); const slug = $derived(page.params.slug ?? '');
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}`;
@@ -112,7 +109,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/projects`; window.location.href = `/admin/org/${slug}/projects`;
} catch (err) { } catch (err) {
toastError(err instanceof Error ? err.message : String(err)); toastError(err instanceof Error ? err.message : String(err));
} }
@@ -173,7 +170,7 @@
{:else if proj} {:else if proj}
<div class="mb-2"> <div class="mb-2">
<a <a
href={`/admin/projects`} href={`/admin/org/${slug}/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" />
@@ -296,7 +293,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/usage`}>组织报告</a> <a class="text-sm text-primary-700 hover:underline" href={`/admin/org/${slug}/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>
@@ -371,7 +368,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/sessions/${s.id}`} href={`/admin/org/${slug}/sessions/${s.id}`}
> >
详情 详情
</a> </a>
@@ -1,8 +1,6 @@
<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';
@@ -10,8 +8,7 @@
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 org = $derived(resolveOrg($session.me, page.url.search)); const slug = $derived(page.params.slug ?? '');
const slug = $derived(org?.slug ?? '');
let connections = $state<ProviderConnectionRow[]>([]); let connections = $state<ProviderConnectionRow[]>([]);
let loading = $state(true); let loading = $state(true);
@@ -1,8 +1,6 @@
<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';
@@ -10,8 +8,7 @@
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 org = $derived(resolveOrg($session.me, page.url.search)); const slug = $derived(page.params.slug ?? '');
const slug = $derived(org?.slug ?? '');
let roles = $state<AgentRoleRow[]>([]); let roles = $state<AgentRoleRow[]>([]);
let models = $state<AgentModelRow[]>([]); let models = $state<AgentModelRow[]>([]);
@@ -1,8 +1,6 @@
<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,
@@ -18,8 +16,7 @@
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 org = $derived(resolveOrg($session.me, page.url.search)); const slug = $derived(page.params.slug ?? '');
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);
@@ -95,7 +92,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/projects/${detail.project.id}`} href={`/admin/org/${slug}/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}
@@ -116,7 +113,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/projects/${detail.project.id}`}> <a class="text-primary-700 hover:underline" href={`/admin/org/${slug}/projects/${detail.project.id}`}>
{detail.project.name} {detail.project.name}
</a> </a>
</dd> </dd>
@@ -1,8 +1,6 @@
<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';
@@ -10,8 +8,7 @@
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 org = $derived(resolveOrg($session.me, page.url.search)); const slug = $derived(page.params.slug ?? '');
const slug = $derived(org?.slug ?? '');
let skills = $state<AgentSkillRow[]>([]); let skills = $state<AgentSkillRow[]>([]);
let loading = $state(true); let loading = $state(true);
@@ -2,8 +2,6 @@
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';
@@ -11,8 +9,7 @@
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 org = $derived(resolveOrg($session.me, page.url.search)); const slug = $derived(page.params.slug ?? '');
const slug = $derived(org?.slug ?? '');
let teams = $state<TeamRow[]>([]); let teams = $state<TeamRow[]>([]);
let loading = $state(true); let loading = $state(true);
@@ -1,8 +1,6 @@
<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,
@@ -17,8 +15,7 @@
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 org = $derived(resolveOrg($session.me, page.url.search)); const slug = $derived(page.params.slug ?? '');
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);
@@ -227,7 +224,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/projects/${p.projectId}`}> <a class="text-sm text-primary-700 hover:underline" href={`/admin/org/${slug}/projects/${p.projectId}`}>
查看项目 查看项目
</a> </a>
</td> </td>
+2 -2
View File
@@ -1,12 +1,12 @@
{ {
"name": "@paradigm/hub", "name": "@paradigm/hub",
"version": "0.0.35", "version": "0.0.34",
"lockfileVersion": 3, "lockfileVersion": 3,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "@paradigm/hub", "name": "@paradigm/hub",
"version": "0.0.35", "version": "0.0.34",
"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.35", "version": "0.0.34",
"private": true, "private": true,
"type": "module", "type": "module",
"engines": { "engines": {
+6 -17
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"; const orgRoot = `/admin/org/${intended.organization.slug}`;
// 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 normalizeAdminReturnTo(returnTo) ?? orgRoot; return returnTo === orgRoot || returnTo.startsWith(`${orgRoot}/`) ? returnTo : orgRoot;
} }
if (returnTo !== "/admin" && returnTo.startsWith("/admin")) { if (returnTo !== "/admin" && returnTo.startsWith("/admin")) {
return normalizeAdminReturnTo(returnTo) ?? "/admin"; return returnTo;
} }
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"; return `/admin/org/${membership.organization.slug}`;
} }
// 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/projects"; return `/admin/org/${any.organization.slug}`;
} }
return "/admin/login?error=no_organization"; return "/admin/login?error=no_organization";
} }
@@ -489,18 +489,7 @@ export function sanitizeReturnTo(raw: string): string {
if (!raw.startsWith("/admin")) { if (!raw.startsWith("/admin")) {
return "/admin"; return "/admin";
} }
return normalizeAdminReturnTo(raw) ?? "/admin"; return raw;
}
/** 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", url: "/auth/feishu?returnTo=/admin/org/test-default",
}); });
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" }, { nonce, returnTo: "/admin/org/test-default" },
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"); expect(res.headers.location).toBe("/admin/org/test-default");
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/settings", url: "/auth/feishu/test-default?returnTo=/admin/org/test-default/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/settings"); expect(callback.headers.location).toBe("/admin/org/test-default/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"); expect(defaultCallback.headers.location).toBe("/admin/org/test-default");
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 } });
+6 -9
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" }, { nonce: "abc", returnTo: "/admin/org/acme" },
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", returnTo: "/admin/org/acme",
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", returnTo: "/admin/org/acme",
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", returnTo: "/admin/org/acme",
organizationId: "org-acme", organizationId: "org-acme",
connectionId: "connection-acme", connectionId: "connection-acme",
exp: 1_700_000_600, exp: 1_700_000_600,
@@ -98,11 +98,8 @@ describe("oauth state signing", () => {
}); });
describe("sanitizeReturnTo", () => { describe("sanitizeReturnTo", () => {
it("allows admin paths and rewrites legacy org slug prefixes", () => { it("allows admin paths", () => {
expect(sanitizeReturnTo("/admin")).toBe("/admin"); expect(sanitizeReturnTo("/admin/org/acme")).toBe("/admin/org/acme");
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,7 +23,6 @@ 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);
}); });