Compare commits

..

24 Commits

Author SHA1 Message Date
ymy ab5e03823c chore: 误提交 .omo 会话文件,移出跟踪 2026-07-30 22:32:07 +08:00
ymy 02b46e2dcf Merge branch 'feat/filelib-always-independent' 2026-07-30 22:32:07 +08:00
ymy 834f4c380c chore: 误提交 .omo 会话文件,移出跟踪并加入 .gitignore 2026-07-30 22:31:08 +08:00
ymy 4c68c7db0b Merge branch 'feat/filelib-always-independent' 2026-07-30 22:27:46 +08:00
ymy 39a2be6347 feat(filelib): 项目级授权恒生效,移除独立权限开关(ADR-0030)
- permission.ts: effectiveRole 删除 D11 冻结分支,输入不再含开关字段
- treeService: 停止读 FileLibProjectSettings;建项目不再写默认行
- grantService/routes: 删 setIndependentPermission 与 PUT 路由;节点详情 DTO 去掉 independentPermission
- filelib-web: 概览 tab 移除开关;NodeDetail 类型同步
- 测试: 单测/集成改为断言恒生效语义;ADR-0030 废除契约 D11/P5
- FileLibProjectSettings 表保留(存量行忽略,不再读写),审计词表保留历史读取
2026-07-30 22:27:45 +08:00
ymy c72f8c7050 Merge branch 'chore/grants-panel-wider' 2026-07-27 17:00:42 +08:00
ymy 947f969967 chore(filelib-web): 详情容器加宽到 1400px,宽屏下授权表格全列无遮挡;仅文件预览挤压时出横向滚动条 2026-07-27 17:00:41 +08:00
ymy 60856d7cc1 Merge branch 'chore/grants-table-overflow' 2026-07-27 16:54:07 +08:00
ymy 2e08c0a734 chore(filelib-web): 授权表格外套横向滚动容器,修删除列贴边与文件预览打开时表格挤压 2026-07-27 16:54:07 +08:00
ymy 2225c6d43b Merge branch 'chore/grants-table-width' 2026-07-27 16:47:05 +08:00
ymy fc908eaf3b chore(filelib-web): 拉宽授权表格:容器 880→1120px,单元格留白/禁换行,长 id 截断+悬停全文 2026-07-27 16:47:05 +08:00
ymy 2395671693 Merge branch 'chore/grant-id-columns' 2026-07-27 16:40:26 +08:00
ymy cc4d9d907c chore(filelib-web): 授权成员单元格只留头像+名称,userId 与飞书 ID 拆为独立两列
GrantDto 增加 principalOpenId(USER 主体的 feishuOpenId),GROUP 行两列显示 —;
搜索过滤同步覆盖 openId。
2026-07-27 16:40:25 +08:00
ymy ef02428bb6 Merge branch 'chore/grant-avatar' 2026-07-27 16:22:03 +08:00
ymy ad1a464f22 chore(filelib-web): 授权成员单元格改用首字母圆形头像(复用 Avatar 组件) 2026-07-27 16:22:01 +08:00
ymy 2dfe72cd5e Merge branch 'chore/grant-modal-copy' 2026-07-27 16:16:17 +08:00
ymy 12a1246a7a chore(filelib-web): 移除添加授权弹窗底部的 8.1 规则提示语 2026-07-27 16:16:16 +08:00
ymy 405312b36b Merge branch 'chore/role-label-zh' 2026-07-27 15:57:42 +08:00
ymy be17f74fc2 chore(filelib-web): 文件库权限名称汉化(VIEW/EDIT/MANAGE → 只读/可编辑/可管理)
统一走新增共享常量 labels.ts ROLE_LABEL(与 OverviewPanel 既有文案一致);
覆盖授权表格与弹窗下拉、详情头 tag、树节点角标;API 传参仍用英文枚举。
2026-07-27 15:57:41 +08:00
ymy fccae5dacb Merge branch 'feat/grants-table' 2026-07-27 15:16:30 +08:00
ymy 0dd2ae347e feat(filelib-web): 授权面板表格化:搜索、添加弹窗、权限下拉与成员跳转
- GrantsPanel 重写为表格:顶部左侧授权成员搜索框(名称/id/类型过滤),
  右侧「添加授权」弹窗(类型 + 主体搜索选择 + 权限);行内权限下拉
  直接改级(复用 PUT upsert),操作列删除;成员单元格跳转用户管理
  (?q= 过滤)或 Group 管理(?select= 选中)。
- grantService: GrantDto 增加 principalName,list/put/force 三处统一
  批量回填(用户 displayName / 组 name),前端不再只显示裸 id。
- 用户管理页加过滤框并从 ?q= 初始化;GroupAdmin 支持 ?select= 直达。
- 测试:resetDb 补 MemberGroup 三表清理(全局表不被 org/user 级联清到,
  此前跨用例污染导致级联软删用例断言失败);cph_hub_test 补 migrate。
- 顺带合并 types.ts 里重复的 Grant 声明(interface 合并残留)。
2026-07-27 15:13:57 +08:00
ymy a4c07d1a5d Merge branch 'fix/filelib-tree-loading' 2026-07-27 14:09:48 +08:00
ymy 91afd3c1b1 fix(filelib-web): 文件库树加载失败时显示错误而非永久加载中 2026-07-27 14:09:35 +08:00
e6e23294a2 Merge branch 'feat/member-group-hierarchy'
MemberGroup 全局嵌套层级(ADR-0028)与 /database 前后端分离(ADR-0029)。
2026-07-26 20:43:59 +08:00
18 changed files with 453 additions and 266 deletions
+2
View File
@@ -15,3 +15,5 @@ node_modules/
# OS / editor
.DS_Store
.omo/
@@ -0,0 +1,43 @@
# ADR 0030: Project Grants Are Always Live; The Independent-Permission Toggle Is Removed
## Status
Accepted. Supersedes the file-library contract rule **D11 / P5** (《文件库-接口契约.md》,
since deleted; recoverable from git history) which introduced the per-project
"独立权限" (independent permission) switch.
## Context
D11 gave each PROJECT a toggle (`FileLibProjectSettings.independentPermissionsEnabled`,
default off). While off, project-level non-creator grants were **frozen** — present in
`FileLibGrant` but excluded from `effectiveRole`; ancestor-chain grants and the creator's
auto-grant were unaffected. The intent was to support two workflows: "project follows the
folder's ACL" (off) vs "project has its own ACL" (on).
In practice the toggle surprised operators twice: grants appeared to "not work" until
someone found and flipped a per-project switch buried in the 概览 tab, and the frozen state
was indistinguishable from missing grants in the UI. The product decision is that
project-level grants should simply always be live.
## Decision
- **Project-level grants always participate in `effectiveRole`.** The freeze branch in
`hub/src/database/filelib/permission.ts` is deleted; `EffectiveRoleInput` no longer
carries `independentPermissionsEnabled`.
- **The toggle surface is removed end-to-end**: `PUT /database/api/projects/:id/independent-permission`,
`grantService.setIndependentPermission`, the `independentPermission` field in the node
detail DTO, and the 概览 tab switch in `filelib-web`.
- **`FileLibProjectSettings` becomes vestigial.** The table stays (existing rows are
ignored, no data migration); new projects no longer get a default row. It may be dropped
in a future migration once nothing references it.
- Audit action vocabulary `independent_enable` / `independent_disable` is retained for
reading historical audit entries; no new entries are produced.
Behavior change for existing deployments: projects whose toggle was off now have their
project-level grants effective immediately — this is the intended effect of the decision.
## Consequences
- Permission semantics shrink to the single P6 rule: `effective = max(grants on self
ancestors for user resolved groups)`, no exceptions by node kind.
- One less state dimension in tests and in the admin UI.
+272 -82
View File
@@ -1,37 +1,70 @@
<script lang="ts">
/**
* 节点授权面板。迁自已删除的 routes/libraryBrowser.ts `renderGrantsTab`(ADR-0029)。
* 节点授权面板(表格化改版)。迁自已删除的 routes/libraryBrowser.ts
* `renderGrantsTab`(ADR-0029)。
*
* 迁移时整个「授权」tab 连同这四个端点一起漏掉了 —— 后端一直可用,只是前端没入口。
* 布局:顶部工具条(左:授权成员搜索框;右:「+ 添加授权」弹窗入口);
* 下方一行一条授权 —— 成员(名称+id,点击跳用户管理/Group 管理)、
* 类型(个人/Group)、权限(下拉可改)、加入时间、操作(删除)。
*
* 语义(契约 8.1 / ADR-0021):
* 语义(契约 8.1 / ADR-0021 / ADR-0028):
* - 创建者授权(isCreatorGrant)不可收回、不可改;
* - MANAGE 仅创建者可授,这里不做前端拦截 —— 后端 fail closed,报错原样呈现;
* - GROUP 主体走 in-hub MemberGroup(ADR-0028),用 /groups/search 选,不手敲 id。
* - MANAGE 仅创建者可授,前端不做矩阵拦截 —— 后端 fail closed,报错原样 toast;
* - GROUP 主体走 in-hub MemberGroup,/groups/search 搜索选(MANAGE 即可);
* USER 主体用 /users/search(仅网站管理员),老师端无此权限时回落手输 id。
*/
import { api } from "./api.js";
import { toastOk, toastErr } from "./stores.js";
import { currentNode } from "./browser.js";
import type { Grant, MemberGroupSearchResult, NodeDetail, Role } from "./types.js";
import { ROLE_LABEL } from "./labels.js";
import type { Grant, MemberGroupSearchResult, NodeDetail, Role, UserSearchResult } from "./types.js";
import Icon from "./Icon.svelte";
import Modal from "./Modal.svelte";
import Avatar from "./Avatar.svelte";
let { node }: { node: NodeDetail } = $props();
const ROLES: readonly Role[] = ["VIEW", "EDIT", "MANAGE"];
interface PrincipalOption {
readonly id: string;
readonly label: string;
readonly sub: string;
}
let grants = $state<Grant[] | null>(null);
let error = $state<string | null>(null);
let searchText = $state("");
// 添加授权弹窗
let showAdd = $state(false);
let principalType = $state<"USER" | "GROUP">("USER");
let userIdInput = $state("");
let groupId = $state("");
let groupOptions = $state<MemberGroupSearchResult[] | null>(null);
let principalQuery = $state("");
let principalOptions = $state<readonly PrincipalOption[] | null>(null);
let selectedPrincipal = $state<{ readonly id: string; readonly label: string } | null>(null);
let manualId = $state("");
let searchUnavailable = $state(false);
let role = $state<Role>("VIEW");
let saving = $state(false);
let searchSeq = 0;
let searchTimer: ReturnType<typeof setTimeout> | undefined;
const canManage = $derived(node.role === "MANAGE");
const errText = (e: unknown): string => (e instanceof Error ? e.message : String(e));
/** 工具条搜索:按名称 / id / 类型过滤当前授权行(纯前端过滤,数据已全量在手)。 */
const shown = $derived.by((): Grant[] | null => {
if (grants === null) return null;
const q = searchText.trim().toLowerCase();
if (q === "") return grants;
return grants.filter(
(g) =>
g.principalId.toLowerCase().includes(q) ||
(g.principalName ?? "").toLowerCase().includes(q) ||
(g.principalOpenId ?? "").toLowerCase().includes(q) ||
(g.principalType === "USER" ? "个人" : "group").includes(q),
);
});
$effect(() => {
void node.id;
void load();
@@ -48,33 +81,102 @@
}
}
/** 切到 GROUP 时懒加载候选组(活跃组 + breadcrumb)。 */
async function onTypeChange(): Promise<void> {
if (principalType !== "GROUP" || groupOptions !== null) return;
/** 成员单元格跳转:USER → 用户管理(带过滤词);GROUP → Group 管理(选中该组)。 */
function principalHref(g: Grant): string {
return g.principalType === "USER"
? `/database/dashboard/users?q=${encodeURIComponent(g.principalId)}`
: `/database/dashboard/groups?select=${encodeURIComponent(g.principalId)}`;
}
function fmtDate(iso: string): string {
try {
const r = await api<{ groups: MemberGroupSearchResult[] }>("/database/api/groups/search?q=");
groupOptions = r.groups;
if (r.groups.length > 0 && groupId === "") groupId = r.groups[0]!.id;
} catch (e) {
toastErr(errText(e));
return new Date(iso).toLocaleString("zh-CN", { dateStyle: "medium", timeStyle: "short" });
} catch {
return iso;
}
}
/* ------------------------------------------------------------ 添加授权弹窗 */
function openAdd(): void {
showAdd = true;
principalType = "USER";
principalQuery = "";
principalOptions = null;
selectedPrincipal = null;
manualId = "";
searchUnavailable = false;
role = "VIEW";
void searchPrincipals("");
}
function onTypeChange(): void {
principalQuery = "";
principalOptions = null;
selectedPrincipal = null;
manualId = "";
searchUnavailable = false;
void searchPrincipals("");
}
function onQueryInput(): void {
selectedPrincipal = null;
if (searchTimer !== undefined) clearTimeout(searchTimer);
const q = principalQuery.trim();
searchTimer = setTimeout(() => void searchPrincipals(q), 250);
}
async function searchPrincipals(q: string): Promise<void> {
// seq 防乱序:慢响应不覆盖新查询的结果。
const seq = ++searchSeq;
try {
if (principalType === "USER") {
const r = await api<{ users: UserSearchResult[] }>(
`/database/api/users/search?q=${encodeURIComponent(q)}`,
);
if (seq !== searchSeq) return;
principalOptions = r.users.map((u) => ({
id: u.userId,
label: u.displayName === "" ? u.userId : u.displayName,
sub: u.feishuOpenId,
}));
} else {
const r = await api<{ groups: MemberGroupSearchResult[] }>(
`/database/api/groups/search?q=${encodeURIComponent(q)}`,
);
if (seq !== searchSeq) return;
principalOptions = r.groups.map((g) => ({ id: g.id, label: g.name, sub: g.breadcrumb }));
}
searchUnavailable = false;
} catch {
if (seq !== searchSeq) return;
// 老师端 MANAGE 持有者没有 users/search 权限(403)——回落为手输 id。
principalOptions = null;
searchUnavailable = true;
}
}
function pick(option: PrincipalOption): void {
selectedPrincipal = { id: option.id, label: option.label };
principalQuery = option.label;
principalOptions = null;
}
async function addGrant(): Promise<void> {
const principalId = principalType === "GROUP" ? groupId : userIdInput.trim();
const principalId = selectedPrincipal?.id ?? manualId.trim();
if (principalId === "") {
toastErr("请填写主体");
toastErr("请选择或填写授权主体");
return;
}
saving = true;
try {
// PUT /grants 是增量语义(putGrants),不是整表替换
// PUT /grants 是 upsert 语义(putGrants):同主体已有授权则改级别,否则新建
await api(`/database/api/nodes/${node.id}/grants`, {
method: "PUT",
body: { grants: [{ principalType, principalId, role }] },
});
toastOk("已授予");
userIdInput = "";
showAdd = false;
await load();
} catch (e) {
toastErr(errText(e));
@@ -83,30 +185,29 @@
}
}
/** 权限下拉改级别:复用 PUT upsert;被 8.1 矩阵拒绝时 toast 并 reload 回显真实态。 */
async function changeRole(g: Grant, next: Role): Promise<void> {
if (next === g.role) return;
try {
await api(`/database/api/nodes/${node.id}/grants`, {
method: "PUT",
body: { grants: [{ principalType: g.principalType, principalId: g.principalId, role: next }] },
});
toastOk("权限已更新");
await load();
} catch (e) {
toastErr(errText(e));
await load();
}
}
async function revoke(g: Grant): Promise<void> {
if (!confirm(`收回${g.principalId}」的 ${g.role} 授权?`)) return;
if (!confirm(`删除${g.principalName ?? g.principalId}」的${ROLE_LABEL[g.role]}授权?`)) return;
try {
await api(`/database/api/nodes/${node.id}/grants/${encodeURIComponent(g.id)}`, {
method: "DELETE",
});
toastOk("已收回");
await load();
} catch (e) {
toastErr(errText(e));
}
}
/** 独立权限开关(仅 PROJECT;关闭时只继承父级,创建者除外)。 */
async function toggleIndependent(): Promise<void> {
try {
await api(`/database/api/projects/${node.id}/independent-permission`, {
method: "PUT",
body: { enabled: !node.independentPermission },
});
toastOk("已切换");
currentNode.update((n) =>
n !== null && n.id === node.id ? { ...n, independentPermission: !node.independentPermission } : n,
);
toastOk("已删除");
await load();
} catch (e) {
toastErr(errText(e));
@@ -115,34 +216,92 @@
</script>
<div class="panel">
<!-- 工具条:左侧授权成员搜索框,右侧添加授权入口 -->
<div class="mb-3 flex items-center gap-2">
<div class="relative min-w-0 flex-1">
<span class="pointer-events-none absolute left-2.5 top-1/2 -translate-y-1/2 text-ink-3">
<Icon name="search" size={14} />
</span>
<input
class="input w-full !pl-8"
placeholder="搜索授权成员(名称 / id / 类型)"
bind:value={searchText}
/>
</div>
{#if canManage}
<button class="btn btn-primary shrink-0" onclick={openAdd}>
<Icon name="plus" size={13} /> 添加授权
</button>
{/if}
</div>
{#if error !== null}
<div class="py-2 text-[12.5px] text-danger">{error}</div>
{:else if grants === null}
{:else if shown === null}
<div class="quiet py-[18px] text-center">加载中…</div>
{:else}
<!-- 内容不可断行(头像名/id/日期/下拉)可能超宽:溢出时横向滚动,
而不是把表格挤变形或顶出 panel 右边界(文件预览打开时主区变窄)。 -->
<div class="overflow-x-auto">
<table class="list">
<thead>
<tr><th>主体</th><th>级别</th><th></th></tr>
<tr>
<th class="whitespace-nowrap pr-4">成员</th>
<th class="whitespace-nowrap pr-4">userId</th>
<th class="whitespace-nowrap pr-4">飞书 ID</th>
<th class="whitespace-nowrap pr-4">类型</th>
<th class="whitespace-nowrap pr-4">权限</th>
<th class="whitespace-nowrap pr-4">加入时间</th>
<th></th>
</tr>
</thead>
<tbody>
{#if grants.length === 0}
<tr><td colspan="3" class="quiet !py-[18px] text-center">暂无显式授权</td></tr>
{:else}
{#each grants as g (g.id)}
{#if shown.length === 0}
<tr>
<td>
<span class="inline-flex items-center gap-2">
<span class="flex text-ink-3"><Icon name={g.principalType === "USER" ? "user" : "group"} size={14} /></span>
<span class="font-mono text-[12px]">{g.principalId}</span>
<td colspan="7" class="quiet !py-[18px] text-center">
{searchText.trim() === "" ? "暂无授权" : `无匹配「${searchText.trim()}」的授权`}
</td>
</tr>
{:else}
{#each shown as g (g.id)}
<tr>
<td class="whitespace-nowrap pr-4">
<a class="inline-flex items-center gap-2 text-ink hover:text-accent" href={principalHref(g)}>
<Avatar displayName={g.principalName} userId={g.principalId} size={26} />
<span class="flex items-center gap-1.5 text-[13px]">
{g.principalName ?? g.principalId}
{#if g.isCreatorGrant}<span class="quiet">(创建者)</span>{/if}
</span>
</a>
</td>
<td class="file-meta">{g.role}</td>
<td class="text-right">
<!-- 创建者授权不可动(契约 8.1);非 MANAGE 也不给收回入口。 -->
<td class="file-meta max-w-[230px] truncate pr-4 font-mono" title={g.principalType === "USER" ? g.principalId : ""}>
{g.principalType === "USER" ? g.principalId : "—"}
</td>
<td class="file-meta max-w-[230px] truncate pr-4 font-mono" title={g.principalOpenId ?? ""}>
{g.principalOpenId ?? "—"}
</td>
<td class="whitespace-nowrap pr-4"><span class="tag">{g.principalType === "USER" ? "个人" : "Group"}</span></td>
<td class="whitespace-nowrap pr-4">
<!-- 创建者授权不可动(契约 8.1);非 MANAGE 持有者只读。 -->
{#if !g.isCreatorGrant && canManage}
<select
class="select !w-[110px]"
value={g.role}
onchange={(e) => void changeRole(g, e.currentTarget.value as Role)}
>
{#each ROLES as r (r)}
<option value={r}>{ROLE_LABEL[r]}</option>
{/each}
</select>
{:else}
<span class="file-meta">{ROLE_LABEL[g.role]}</span>
{/if}
</td>
<td class="file-meta whitespace-nowrap pr-4">{fmtDate(g.createdAt)}</td>
<td class="whitespace-nowrap pr-2 text-right">
{#if !g.isCreatorGrant && canManage}
<button class="link-danger inline-flex items-center gap-1" onclick={() => void revoke(g)}>
<Icon name="minus" size={12} /> 收回
<Icon name="trash" size={12} /> 删除
</button>
{/if}
</td>
@@ -151,41 +310,72 @@
{/if}
</tbody>
</table>
</div>
{/if}
</div>
{#if canManage}
<div class="my-3.5 border-t border-line-soft"></div>
<div class="section-title mb-2.5">新增授权</div>
<div class="flex flex-wrap items-center gap-2">
<select class="select !w-[110px]" bind:value={principalType} onchange={onTypeChange}>
<option value="USER">用户</option>
{#if showAdd}
<Modal title="添加授权" onclose={() => (showAdd = false)}>
<div class="form-row">
<label class="form-label" for="grant-type">类型</label>
<select id="grant-type" class="select" bind:value={principalType} onchange={onTypeChange}>
<option value="USER">个人</option>
<option value="GROUP">Group</option>
</select>
{#if principalType === "USER"}
<input class="input min-w-0 flex-1" placeholder="用户 id" bind:value={userIdInput} />
{:else if groupOptions === null}
<span class="quiet flex-1">加载 Group 列表…</span>
{:else if groupOptions.length === 0}
<span class="quiet flex-1">暂无可选 Group · 先到「Group 管理」建一个</span>
{:else}
<select class="select min-w-0 flex-1" bind:value={groupId}>
{#each groupOptions as g (g.id)}
<option value={g.id}>{g.breadcrumb}</option>
{/each}
</select>
</div>
<div class="form-row">
<label class="form-label" for="grant-principal">{principalType === "USER" ? "用户" : "Group"}</label>
<input
id="grant-principal"
class="input"
placeholder={principalType === "USER" ? "搜索显示名 / openId" : "搜索组名"}
bind:value={principalQuery}
oninput={onQueryInput}
/>
</div>
{#if selectedPrincipal !== null}
<div class="form-row">
<span class="form-label">已选</span>
<span class="quiet self-center text-[12.5px]">
{selectedPrincipal.label}<span class="font-mono">({selectedPrincipal.id})</span>
</span>
</div>
{/if}
<select class="select !w-[110px]" bind:value={role}>
{#if principalOptions !== null && principalOptions.length > 0}
<div class="mb-3 max-h-[180px] overflow-y-auto rounded-lg border border-line-soft">
{#each principalOptions as o (o.id)}
<button class="block w-full px-3 py-2 text-left hover:bg-hover" onclick={() => pick(o)}>
<span class="block text-[13px] text-ink">{o.label}</span>
<span class="block font-mono text-[11px] text-ink-3">{o.sub}</span>
</button>
{/each}
</div>
{:else if searchUnavailable}
<div class="form-row">
<label class="form-label" for="grant-manual-id">主体 id</label>
<input
id="grant-manual-id"
class="input font-mono"
placeholder="无搜索权限,请直接填写 id"
bind:value={manualId}
/>
</div>
{:else if principalOptions !== null}
<div class="quiet mb-3 py-2 text-center text-[12px]">无匹配结果</div>
{/if}
<div class="form-row">
<label class="form-label" for="grant-role">权限</label>
<select id="grant-role" class="select" bind:value={role}>
{#each ROLES as r (r)}
<option value={r}>{r}</option>
<option value={r}>{ROLE_LABEL[r]}</option>
{/each}
</select>
</div>
<div class="mt-4 flex justify-end gap-2">
<button class="btn" onclick={() => (showAdd = false)}>取消</button>
<button class="btn btn-primary disabled:opacity-50" onclick={addGrant} disabled={saving}>
{saving ? "授予中…" : "授予"}
{saving ? "授予中…" : "添加"}
</button>
</div>
<div class="section-note mt-1.5">MANAGE 仅创建者可授;创建者授权不可动(契约 8.1)</div>
{/if}
</div>
</Modal>
{/if}
+8 -1
View File
@@ -5,6 +5,7 @@
* 归档组展示与恢复 / 右键菜单 / 面包屑 / 统计条 / 成员表(头像·openId·加入时间)。
*/
import { onMount } from "svelte";
import { page } from "$app/state";
import { api } from "./api.js";
import { toastErr, toastOk } from "./stores.js";
import type { MemberGroupNode, MemberGroupMember, UserSearchResult } from "./types.js";
@@ -172,7 +173,13 @@
}
}
onMount(loadGroups);
onMount(async () => {
await loadGroups();
// 授权面板「成员」单元格跳转:?select=<groupId> 直接选中该组。
// 组不在列表(已归档且未开归档展示)时不动作,停留默认态。
const target = page.url.searchParams.get("select");
if (target !== null && groups.some((g) => g.id === target)) select(target);
});
function select(id: string): void {
selectedId = id;
+3 -3
View File
@@ -79,10 +79,10 @@
</div>
<div class="flex-1 overflow-y-auto px-2 py-2 text-[13px]">
{#if roots === null}
<div class="px-3 py-6 text-center text-xs text-ink-3">加载中…</div>
{:else if treeError}
{#if treeError}
<div class="px-3 py-6 text-center text-xs text-danger">{treeError}</div>
{:else if roots === null}
<div class="px-3 py-6 text-center text-xs text-ink-3">加载中…</div>
{:else if roots.length === 0}
<div class="px-3 py-6 text-center text-xs text-ink-3">
{$me?.isWebsiteAdmin ? "空文件库 · 点上方「+ 根目录」开始" : "文件库为空,请联系管理员创建根目录"}
@@ -2,6 +2,7 @@
import { api } from "./api.js";
import { currentNode, breadcrumb, bumpTree, clearSelectedFile } from "./browser.js";
import { toastOk, toastErr } from "./stores.js";
import { ROLE_LABEL } from "./labels.js";
import OverviewPanel from "./OverviewPanel.svelte";
import FilesPanel from "./FilesPanel.svelte";
import GrantsPanel from "./GrantsPanel.svelte";
@@ -87,7 +88,7 @@
{#if node === null}
<div class="flex h-full items-center justify-center text-[13px] text-ink-3">从左侧选择一个文件夹或项目</div>
{:else}
<div class="mx-auto max-w-[880px] px-9 py-9">
<div class="mx-auto max-w-[1400px] px-9 py-9">
<div class="mb-2 text-[12.5px] text-ink-3">
{#each crumbs as c, i (i)}
{#if i > 0}<span class="mx-1 text-line">/</span>{/if}
@@ -99,7 +100,7 @@
<div class="flex items-center gap-2 text-[17px] font-semibold text-ink">
{node.name}
<span class="tag">{node.kind === "PROJECT" ? "项目" : "文件夹"}</span>
<span class="tag !border-line !text-ink-2">{node.role}</span>
<span class="tag !border-line !text-ink-2">{ROLE_LABEL[node.role]}</span>
</div>
<div class="flex gap-1.5">
{#if canEdit && node.kind === "FOLDER"}
+3 -29
View File
@@ -2,6 +2,7 @@
import { api } from "./api.js";
import { toastOk, toastErr } from "./stores.js";
import { currentNode } from "./browser.js";
import { ROLE_LABEL } from "./labels.js";
import type { ExportJob, NodeDetail } from "./types.js";
import Modal from "./Modal.svelte";
@@ -12,24 +13,7 @@
let exportJob = $state<ExportJob | null>(null);
const canEdit = $derived(node.role === "MANAGE" || node.role === "EDIT");
const canManage = $derived(node.role === "MANAGE");
const roleLabel = $derived(node.role === "MANAGE" ? "可管理" : node.role === "EDIT" ? "可编辑" : "只读");
/** 独立权限开关(仅 PROJECT;关闭时只继承父级权限,创建者除外)。 */
async function toggleIndependent(): Promise<void> {
try {
await api(`/database/api/projects/${node.id}/independent-permission`, {
method: "PUT",
body: { enabled: !node.independentPermission },
});
toastOk("已切换");
currentNode.update((n) =>
n !== null && n.id === node.id ? { ...n, independentPermission: !node.independentPermission } : n,
);
} catch (e) {
toastErr(e instanceof Error ? e.message : String(e));
}
}
const roleLabel = $derived(ROLE_LABEL[node.role]);
$effect(() => {
void node.id;
@@ -108,18 +92,8 @@
<div>更新时间 <b class="font-semibold text-ink">{new Date(node.updatedAt).toLocaleString("zh-CN")}</b></div>
</div>
<!-- 独立权限与导出只对 PROJECT 有意义(FOLDER 是透明组织节点,ADR-0021)。 -->
<!-- 导出只对 PROJECT 有意义(FOLDER 是透明组织节点,ADR-0021)。 -->
{#if node.kind === "PROJECT"}
<div class="my-4 border-t border-line-soft"></div>
<div class="flex flex-wrap items-center gap-2.5">
<span class="quiet">独立权限</span>
<b class="text-[13px]">{node.independentPermission ? "开启" : "关闭"}</b>
{#if canManage}
<button class="btn" onclick={toggleIndependent}>{node.independentPermission ? "关闭" : "开启"}</button>
{/if}
<span class="quiet">关闭时仅继承父级权限(创建者除外)</span>
</div>
<div class="my-4 border-t border-line-soft"></div>
<div class="section-title mb-2">导出</div>
+2 -1
View File
@@ -3,6 +3,7 @@
import { api } from "./api.js";
import { expanded, currentNode, breadcrumb, toggleExpanded, treeVersion } from "./browser.js";
import { toastErr } from "./stores.js";
import { ROLE_LABEL } from "./labels.js";
import type { BreadcrumbEntry, NodeChild, NodeDetail } from "./types.js";
let { node, depth }: { node: NodeChild; depth: number } = $props();
@@ -64,7 +65,7 @@
</span>
<span class="truncate">{node.name}</span>
{#if node.role !== "MANAGE"}
<span class="ml-auto pr-1 font-mono text-[10px] text-ink-3">{node.role}</span>
<span class="ml-auto pr-1 text-[10px] text-ink-3">{ROLE_LABEL[node.role]}</span>
{/if}
</div>
+10
View File
@@ -0,0 +1,10 @@
/** 展示层文案(与 API 枚举值解耦;传参仍用英文枚举)。 */
import type { Role } from "./types.js";
/** 文件库权限级(契约 8.1 MANAGE>EDIT>VIEW)的中文展示名。 */
export const ROLE_LABEL: Record<Role, string> = {
VIEW: "只读",
EDIT: "可编辑",
MANAGE: "可管理",
};
+4 -10
View File
@@ -28,7 +28,6 @@ export interface NodeDetail {
readonly description: string | null;
readonly role: Role;
readonly provisionStatus: "PROVISIONING" | "READY" | "FAILED";
readonly independentPermission: boolean;
readonly createdAt: string;
readonly updatedAt: string;
}
@@ -72,15 +71,6 @@ export interface ExportJob {
readonly createdAt: string;
}
export interface Grant {
readonly id: string;
readonly principalType: "USER" | "GROUP";
readonly principalId: string;
readonly role: Role;
readonly isCreatorGrant: boolean;
readonly createdAt: string;
}
export interface GroupSearchResult {
readonly id: string;
readonly name: string;
@@ -114,6 +104,10 @@ export interface Grant {
readonly id: string;
readonly principalType: "USER" | "GROUP";
readonly principalId: string;
/** 主体显示名(用户 displayName / 组 name);主体已删为 null,展示回落 principalId。 */
readonly principalName: string | null;
/** USER 主体的飞书 openId;GROUP 或主体已删为 null。 */
readonly principalOpenId: string | null;
readonly role: Role;
/** 创建者授权不可收回、不可改(契约 8.1)。 */
readonly isCreatorGrant: boolean;
@@ -7,10 +7,12 @@
* 这里管的是 org 成员与其角色。
*/
import { onMount } from "svelte";
import { page } from "$app/state";
import { api } from "$lib/api.js";
import { loadConfig } from "$lib/config.js";
import { toastOk, toastErr } from "$lib/stores.js";
import type { OrgMember, OrgRole } from "$lib/types.js";
import Icon from "$lib/Icon.svelte";
const ROLE_LABEL: Record<OrgRole, string> = {
OWNER: "所有者",
@@ -23,6 +25,9 @@
let members = $state<OrgMember[] | null>(null);
let error = $state<string | null>(null);
// 列表过滤;授权面板跳转会带 ?q=<userId>,以此为初始过滤词。
let filterText = $state(page.url.searchParams.get("q") ?? "");
let newOpenId = $state("");
let newName = $state("");
let newRole = $state<OrgRole>("MEMBER");
@@ -30,6 +35,19 @@
const base = $derived(orgSlug === null ? null : `/api/org/${encodeURIComponent(orgSlug)}`);
/** 按显示名 / userId / openId 过滤(纯前端;成员全量在手)。 */
const shown = $derived.by((): OrgMember[] | null => {
if (members === null) return null;
const q = filterText.trim().toLowerCase();
if (q === "") return members;
return members.filter(
(m) =>
m.displayName.toLowerCase().includes(q) ||
m.userId.toLowerCase().includes(q) ||
m.feishuOpenId.toLowerCase().includes(q),
);
});
async function load(): Promise<void> {
if (base === null) return;
try {
@@ -121,14 +139,28 @@
</div>
<div class="panel">
<div class="section-title mb-2.5">成员列表</div>
<div class="mb-2.5 flex items-center justify-between gap-2">
<div class="section-title">成员列表</div>
<div class="relative w-[260px] shrink-0">
<span class="pointer-events-none absolute left-2.5 top-1/2 -translate-y-1/2 text-ink-3">
<Icon name="search" size={13} />
</span>
<input
class="input w-full !py-[5px] !pl-8 !text-[12.5px]"
placeholder="过滤:名称 / userId / openId"
bind:value={filterText}
/>
</div>
</div>
{#if error}
<div class="py-3 text-[12.5px] text-danger">{error}</div>
{:else if members === null}
{:else if shown === null}
<div class="quiet py-[18px] text-center">加载中…</div>
{:else if members.length === 0}
<div class="quiet py-[18px] text-center">暂无成员</div>
{:else if shown.length === 0}
<div class="quiet py-[18px] text-center">
{filterText.trim() === "" ? "暂无成员" : `无匹配「${filterText.trim()}」的成员`}
</div>
{:else}
<table class="list">
<thead>
@@ -140,7 +172,7 @@
</tr>
</thead>
<tbody>
{#each members as m (m.userId)}
{#each shown as m (m.userId)}
<tr>
<td class="text-ink">{m.displayName || m.userId}</td>
<td class="file-meta">{m.userId}</td>
+37 -42
View File
@@ -25,6 +25,10 @@ export interface GrantDto {
readonly id: string;
readonly principalType: "USER" | "GROUP";
readonly principalId: string;
/** 主体显示名(用户 displayName / 组 name);主体已删时为 null,前端回落 principalId。 */
readonly principalName: string | null;
/** USER 主体的飞书 openId;GROUP 或主体已删时为 null。 */
readonly principalOpenId: string | null;
readonly role: FileLibRole;
readonly isCreatorGrant: boolean;
readonly createdAt: Date;
@@ -35,12 +39,42 @@ function toDto(grant: FileLibGrant): GrantDto {
id: grant.id,
principalType: grant.principalType,
principalId: grant.principalId,
principalName: null,
principalOpenId: null,
role: grant.role,
isCreatorGrant: grant.isCreatorGrant,
createdAt: grant.createdAt,
};
}
/** 批量回填主体显示名与飞书 openId(两次查询,不做 per-row 往返)。可在事务内调用。 */
async function withPrincipalNames(
prisma: Pick<PrismaClient, "user" | "memberGroup">,
grants: readonly GrantDto[],
): Promise<readonly GrantDto[]> {
const userIds = [...new Set(grants.filter((g) => g.principalType === "USER").map((g) => g.principalId))];
const groupIds = [...new Set(grants.filter((g) => g.principalType === "GROUP").map((g) => g.principalId))];
const users = userIds.length === 0
? []
: await prisma.user.findMany({
where: { id: { in: userIds } },
select: { id: true, displayName: true, feishuOpenId: true },
});
const groups = groupIds.length === 0
? []
: await prisma.memberGroup.findMany({ where: { id: { in: groupIds } }, select: { id: true, name: true } });
const nameById = new Map<string, string>([
...users.map((u) => [u.id, u.displayName] as const),
...groups.map((g) => [g.id, g.name] as const),
]);
const openIdById = new Map<string, string>(users.map((u) => [u.id, u.feishuOpenId] as const));
return grants.map((g) => ({
...g,
principalName: nameById.get(g.principalId) ?? null,
principalOpenId: g.principalType === "USER" ? openIdById.get(g.principalId) ?? null : null,
}));
}
type Tx = Prisma.TransactionClient;
type Deps = AccessDeps & { readonly prisma: PrismaClient };
@@ -66,7 +100,7 @@ export async function listGrants(
where: { organizationId: deps.organizationId, nodeId, revokedAt: null },
orderBy: [{ isCreatorGrant: "desc" }, { createdAt: "asc" }],
});
return grants.map(toDto);
return withPrincipalNames(deps.prisma, grants.map(toDto));
}
export interface PutGrantsResult {
@@ -137,7 +171,7 @@ export async function putGrants(
where: { organizationId: deps.organizationId, nodeId: node.id, revokedAt: null },
orderBy: [{ isCreatorGrant: "desc" }, { createdAt: "asc" }],
});
return { granted, updated, grants: grants.map(toDto) };
return { granted, updated, grants: await withPrincipalNames(tx, grants.map(toDto)) };
});
}
@@ -236,46 +270,7 @@ export async function forceAdjustGrants(
where: { organizationId: deps.organizationId, nodeId: node.id, revokedAt: null },
orderBy: [{ isCreatorGrant: "desc" }, { createdAt: "asc" }],
});
return { granted, updated, grants: grants.map(toDto) };
});
}
/** 项目独立权限开关(P5/D11):需 MANAGE;状态不变则空操作。 */
export async function setIndependentPermission(
deps: Deps,
actor: FileLibActor,
nodeId: string,
enabled: boolean,
): Promise<{ readonly enabled: boolean }> {
return deps.prisma.$transaction(async (tx) => {
const { node } = await requireManage(deps, actor, nodeId, tx);
if (node.kind !== "PROJECT") {
throw new FileLibError(400, "invalid_node_kind", "independent permission applies to projects only");
}
const current = await tx.fileLibProjectSettings.findUnique({
where: { nodeId: node.id },
select: { independentPermissionsEnabled: true },
});
if ((current?.independentPermissionsEnabled ?? false) === enabled) {
return { enabled }; // 状态未变:空操作,不产生审计
}
await tx.fileLibProjectSettings.upsert({
where: { nodeId: node.id },
update: { independentPermissionsEnabled: enabled },
create: { nodeId: node.id, independentPermissionsEnabled: enabled },
});
await writeFileLibAudit(tx, {
action: enabled
? FILE_LIB_AUDIT_ACTIONS.independentEnable
: FILE_LIB_AUDIT_ACTIONS.independentDisable,
actorUserId: actor.userId,
organizationId: deps.organizationId,
objectType: "project",
objectId: node.id,
objectPath: node.pathIds,
detail: { enabled },
});
return { enabled };
return { granted, updated, grants: await withPrincipalNames(tx, grants.map(toDto)) };
});
}
+3 -9
View File
@@ -1,5 +1,5 @@
/**
* 纯权限 reducer(契约 P6 / D11 / D8)。
* 纯权限 reducer(契约 P6 / D8)。
*
* 设计约束(Metis 评审):本文件是纯函数层 —— 输入是"已解析好的" grant、祖先链
* 与用户组集合,不碰 DB / 网络。数据获取在 treeService。这样权限代数可以脱离
@@ -23,8 +23,6 @@ export interface EffectiveRoleInput {
readonly nodeKind: "FOLDER" | "PROJECT";
/** 目标的全部祖先 id(不含 self,顺序无关)。 */
readonly ancestorIds: readonly string[];
/** 项目独立权限开关(D11/P5);文件夹忽略此值。 */
readonly independentPermissionsEnabled: boolean;
readonly userId: string;
/** C2 resolve 结果:用户直接所属 + 全部祖先 group 的 id 集合。 */
readonly groupIds: readonly string[];
@@ -37,20 +35,16 @@ export interface EffectiveRoleInput {
* r ∈ {R} ancestors(R) };无匹配 → null(无任何权限)。
* "个人权限不能降权"在 max 语义下天然成立 —— 只取最高,不做减法。
*
* D11:目标为 PROJECT 且独立权限关闭时,项目级(挂在 self 上)非创建者 grant
* 冻结不参与计算;创建者的自动 grant(isCreatorGrant)始终生效。祖先链上的
* grant 不受开关影响。
* 项目级 grant 恒参与计算(ADR-0030):原 D11 独立权限开关已废除,
* FileLibProjectSettings 不再被读取。
*/
export function effectiveRole(input: EffectiveRoleInput): FileLibRole | null {
const onChain = new Set<string>([input.nodeId, ...input.ancestorIds]);
const groups = new Set(input.groupIds);
const freezeProjectGrants =
input.nodeKind === "PROJECT" && !input.independentPermissionsEnabled;
let best: FileLibRole | null = null;
for (const grant of input.grants) {
if (!onChain.has(grant.nodeId)) continue;
if (freezeProjectGrants && grant.nodeId === input.nodeId && !grant.isCreatorGrant) continue;
if (grant.principalType === "USER" && grant.principalId !== input.userId) continue;
if (grant.principalType === "GROUP" && !groups.has(grant.principalId)) continue;
if (best === null || ROLE_RANK[grant.role] > ROLE_RANK[best]) best = grant.role;
+1 -32
View File
@@ -94,7 +94,7 @@ async function loadVisibleChain(
return { node, ancestors: ordered };
}
/** 数据获取层:把 chain、grants、groups、toggle 装配成纯 reducer 的输入。 */
/** 数据获取层:把 chain、grants、groups 装配成纯 reducer 的输入。 */
async function resolveRole(
tx: Tx,
deps: AccessDeps,
@@ -106,20 +106,11 @@ async function resolveRole(
where: { organizationId: deps.organizationId, revokedAt: null, nodeId: { in: chainIds } },
select: { nodeId: true, principalType: true, principalId: true, role: true, isCreatorGrant: true },
});
let independentPermissionsEnabled = false;
if (chain.node.kind === "PROJECT") {
const settings = await tx.fileLibProjectSettings.findUnique({
where: { nodeId: chain.node.id },
select: { independentPermissionsEnabled: true },
});
independentPermissionsEnabled = settings?.independentPermissionsEnabled ?? false;
}
const groupIds = await deps.groupResolver.resolveMemberGroupIds(actor.userId);
return effectiveRole({
nodeId: chain.node.id,
nodeKind: chain.node.kind,
ancestorIds: chain.ancestors.map((a) => a.id),
independentPermissionsEnabled,
userId: actor.userId,
groupIds,
grants,
@@ -278,11 +269,6 @@ export async function createNode(
},
});
}
if (input.kind === "PROJECT") {
await tx.fileLibProjectSettings.create({
data: { nodeId: id, independentPermissionsEnabled: false },
});
}
await writeFileLibAudit(tx, {
action: nodeAction(input.kind, "Create"),
@@ -482,20 +468,12 @@ export async function breadcrumb(
where: { organizationId: deps.organizationId, revokedAt: null, nodeId: { in: chainIds } },
select: { nodeId: true, principalType: true, principalId: true, role: true, isCreatorGrant: true },
});
const settings = chain.node.kind === "PROJECT"
? await tx.fileLibProjectSettings.findUnique({
where: { nodeId: chain.node.id },
select: { independentPermissionsEnabled: true },
})
: null;
return chainNodes.map((current, depth) => {
const role = effectiveRole({
nodeId: current.id,
nodeKind: current.kind,
ancestorIds: chainNodes.slice(0, depth).map((n) => n.id),
independentPermissionsEnabled:
current.id === chain.node.id ? settings?.independentPermissionsEnabled ?? false : false,
userId: actor.userId,
groupIds,
grants: allGrants,
@@ -545,14 +523,6 @@ export async function listChildren(
where: { organizationId: deps.organizationId, revokedAt: null, nodeId: { in: idsToFetch } },
select: { nodeId: true, principalType: true, principalId: true, role: true, isCreatorGrant: true },
});
const projectIds = children.filter((c) => c.kind === "PROJECT").map((c) => c.id);
const settingsRows = projectIds.length === 0
? []
: await tx.fileLibProjectSettings.findMany({
where: { nodeId: { in: projectIds } },
select: { nodeId: true, independentPermissionsEnabled: true },
});
const toggleByNode = new Map(settingsRows.map((s) => [s.nodeId, s.independentPermissionsEnabled]));
const groupIds = await deps.groupResolver.resolveMemberGroupIds(actor.userId);
const out: ChildNodeDto[] = [];
@@ -561,7 +531,6 @@ export async function listChildren(
nodeId: child.id,
nodeKind: child.kind,
ancestorIds: parentAncestorIds,
independentPermissionsEnabled: toggleByNode.get(child.id) ?? false,
userId: actor.userId,
groupIds,
grants: allGrants,
-20
View File
@@ -21,7 +21,6 @@ import {
listGrants,
putGrants,
revokeGrant,
setIndependentPermission,
} from "../filelib/grantService.js";
import { FileLibError } from "../filelib/model.js";
import {
@@ -114,9 +113,6 @@ export async function registerFileLibRoutes(
where: { id, organizationId: deps.organizationId },
});
if (node === null) throw new FileLibError(404, "node_not_found", "node not found");
const settings = node.kind === "PROJECT"
? await deps.prisma.fileLibProjectSettings.findUnique({ where: { nodeId: node.id } })
: null;
return {
node: {
id: node.id,
@@ -126,7 +122,6 @@ export async function registerFileLibRoutes(
description: node.description,
role,
provisionStatus: node.provisionStatus,
independentPermission: settings?.independentPermissionsEnabled ?? false,
createdAt: node.createdAt,
updatedAt: node.updatedAt,
},
@@ -258,21 +253,6 @@ export async function registerFileLibRoutes(
}
});
app.put("/database/api/projects/:id/independent-permission", async (request, reply) => {
const actor = await actorOrNull(request, reply, deps);
if (actor === null) return reply;
try {
const { id } = request.params as { id: string };
const body = bodyObject(request.body);
if (typeof body["enabled"] !== "boolean") {
throw new FileLibError(400, "invalid_request", "enabled must be a boolean");
}
return await setIndependentPermission(grantDeps, actor, id, body["enabled"]);
} catch (error) {
return sendRouteError(reply, error);
}
});
// Group 搜索(C2 /groups/search)已迁至 memberGroupRoutes.ts,读 in-hub
// MemberGroup 闭包(ADR-0028)。此处不再注册,避免重复。
}
+4 -9
View File
@@ -80,20 +80,15 @@ describe("treeService · 创建规则", () => {
});
});
describe("treeService · D11 独立权限开关", () => {
it("关闭时项目级非创建者 grant 冻结,创建者仍 MANAGE", async () => {
describe("treeService · 项目级 grant 恒生效(ADR-0030)", () => {
it("项目级非创建者 grant 创建即生效,创建者仍 MANAGE", async () => {
const project = await createNode(deps(), ADMIN, {
parentId: null, kind: "PROJECT", name: "TH-141",
grants: [{ principalType: "USER", principalId: "u_alice", role: "EDIT" }],
});
await expect(getEffectiveRole(deps(), ALICE, project.id))
.rejects.toMatchObject({ statusCode: 404 }); // 冻结 = 无权限 = D8 不可见
// 无开关、无冻结:alice 的项目级 EDIT 立即可见。
expect(await getEffectiveRole(deps(), ALICE, project.id)).toBe("EDIT");
expect(await getEffectiveRole(deps(), ADMIN, project.id)).toBe("MANAGE");
await prisma.fileLibProjectSettings.update({
where: { nodeId: project.id },
data: { independentPermissionsEnabled: true },
});
expect(await getEffectiveRole(deps(), ALICE, project.id)).toBe("EDIT"); // 恢复
});
});
+6
View File
@@ -45,6 +45,12 @@ export async function resetDb(): Promise<void> {
// two tables have no FK to Project and must be cleared explicitly.
prisma.permissionGrant.deleteMany(),
prisma.permissionSettings.deleteMany(),
// MemberGroup is global (ADR-0028): no FK to the org/user roots, so the
// cascade above never reaches it. Clear explicitly — closure/membership
// first (they FK into MemberGroup), groups last.
prisma.memberGroupClosure.deleteMany(),
prisma.memberGroupMembership.deleteMany(),
prisma.memberGroup.deleteMany(),
prisma.user.deleteMany(),
prisma.organization.deleteMany(),
]);
+11 -17
View File
@@ -1,6 +1,6 @@
/**
* 纯权限 reducer 单测(契约 P6 / D11 / 2.3)。
* 矩阵覆盖:个人/Group/祖先继承/max 取最高/不降权/空权限/toggle 冻结;
* 纯权限 reducer 单测(契约 P6 / 2.3)。
* 矩阵覆盖:个人/Group/祖先继承/max 取最高/不降权/空权限;
* 外加确定性随机化不变量(单调性:任何可用 grant 都不超过 effective)。
*/
import { describe, expect, it } from "vitest";
@@ -10,7 +10,6 @@ const base: EffectiveRoleInput = {
nodeId: "N",
nodeKind: "FOLDER",
ancestorIds: ["A", "R"], // N ⊂ A ⊂ R
independentPermissionsEnabled: false,
userId: "u1",
groupIds: ["g1"],
grants: [],
@@ -75,33 +74,28 @@ describe("effectiveRole · 契约 P6 矩阵", () => {
});
});
describe("effectiveRole · D11 独立权限开关", () => {
describe("effectiveRole · 项目级 grant 恒生效(ADR-0030)", () => {
const project: EffectiveRoleInput = { ...base, nodeKind: "PROJECT", nodeId: "P" };
it("开关关闭:项目级非创建者 grant 冻结", () => {
it("项目级非创建者 grant 直接参与(无开关、无冻结)", () => {
const grants = [grant({ nodeId: "P", role: "EDIT" })];
expect(effectiveRole({ ...project, grants })).toBeNull();
expect(effectiveRole({ ...project, grants })).toBe("EDIT");
});
it("开关关闭:创建者 grant 生效", () => {
it("创建者 grant 照常生效", () => {
const grants = [grant({ nodeId: "P", role: "MANAGE", isCreatorGrant: true })];
expect(effectiveRole({ ...project, grants })).toBe("MANAGE");
});
it("开关关闭:祖先链 grant 不受影响", () => {
it("项目级与祖先链 grant 同取 max", () => {
const grants = [
grant({ nodeId: "P", role: "MANAGE" }), // 冻结
grant({ nodeId: "A", role: "VIEW" }), // 生效
grant({ nodeId: "P", role: "VIEW" }),
grant({ nodeId: "A", role: "EDIT" }),
];
expect(effectiveRole({ ...project, grants })).toBe("VIEW");
expect(effectiveRole({ ...project, grants })).toBe("EDIT");
});
it("开关开启:项目级 grant 恢复参与", () => {
const grants = [grant({ nodeId: "P", role: "EDIT" })];
expect(effectiveRole({ ...project, independentPermissionsEnabled: true, grants })).toBe("EDIT");
});
it("文件夹忽略开关(self grant 照常参与)", () => {
it("文件夹与项目语义一致(self grant 照常参与)", () => {
const grants = [grant({ nodeId: "N", role: "EDIT" })];
expect(effectiveRole({ ...base, grants })).toBe("EDIT");
});