@haneinfo/rbac

中文文档
8.3.1发布于 2026/11/17UNLICENSEDTypeScriptCommonJS近 30 天下载 5831
原始使用文档
文档目录5 节
  1. Upgrade each App from 7.x
  2. Seed grants
  3. Instance access lists
  4. Authenticated role label lookup
  5. App-declared default roles

Role permissions

Version 8 stores RolePermission.permission as text. The App's Prisma Permission enum is optional and serves only as a catalog of App-owned IDs. Colon-separated business IDs can also be provided as constants.

RbacPermissionCatalog loads .haneinfo/generated/permissions.json relative to process.cwd() once at startup. Run the backend with its plugin build directory as the working directory (normally backend/) and deploy this generated artifact with the App. Only active desired entries are grantable; freshInstallPlan is never applied. ENOENT logs the absolute missing path and exposes only App permissions. Invalid JSON, an unsupported schema, duplicate IDs or I/O errors fail startup.

By default App permissions come from the consuming App's generated @prisma/client Permission export, resolved from the working directory. For constants or a different artifact location, export this provider from an App-owned global module:

{
  provide: RBAC_PERMISSION_CATALOG_OPTIONS,
  useValue: {
    appPermissions: [...Object.values(Permission), 'equipment-loan:loan:return'],
    permissionsPath: '/app/backend/.haneinfo/generated/permissions.json',
  } satisfies PermissionCatalogOptions,
}

GET /roles/permission-catalog is read-only and uses the same interactive authentication and ADMIN guard as role management. It returns { permissions: [{ id, displayName, source, pluginId? }] }. RolesService rejects unknown IDs on create, update and replace, returning unknownPermissionIds. Existing IDs absent from the active catalog are retired: replacement preserves their grants, and they cannot be newly granted to another role.

Pass this response as permissionCatalog to RolesTable. Use permissionGroups() to prepare CreateRoleDialog choices. App labels still use Permission.* translations; plugin labels use displayName. permissionLabels customizes the App heading and retired marker (defaults: App 權限, 已停用). frontend-admin fetches the catalog itself.

Upgrade each App from 7.x

  1. After release, install rbac 8.0.0 and the matching frontend-admin update in every workspace. Update optional m2m-api-key peers to a version accepting rbac 8.

  2. Run haneinfo build to regenerate plugin artifacts and the composed schema. If the App uses backend/prisma/schema/ as its active schema, also copy the reviewed node_modules/@haneinfo/rbac/prisma/role.prisma there; build does not overwrite that folder.

  3. Add one App-owned migration before deploying the new backend:

    ALTER TABLE role_permissions ALTER COLUMN permission TYPE text USING permission::text;
    
  4. Keep the old enum if it still supplies App catalog values. Do not drop its PostgreSQL type while any other column uses it. Existing grant values remain unchanged.

  5. Regenerate Prisma Client, deploy the migration, then seed and run App integration tests. Deploy permissions.json and use the same backend working directory at runtime.

  6. Grant a non-ADMIN designer <kind>:definition:write and :read (or READ_ALL). Publishing additionally requires <kind>:definition:publish and remains human-only.

Seed grants

Seeds bypass RolesService, so validate constants against the same catalog before writing:

import { RbacPermissionCatalog } from '@haneinfo/rbac';
const catalog = new RbacPermissionCatalog(); // run from backend/, after haneinfo build
const grants: string[] = [Permission.USERS_READ, 'timer:definition:write'];
catalog.assertGrantable(grants);
await prisma.rolePermission.createMany({
  data: grants.map((permission) => ({ roleId, permission })),
  skipDuplicates: true,
});

Do not type a mixed catalog as Permission[]. Existing seeds may continue to use App enum constants, but should validate every grant and preserve retired grants rather than deleting all role permissions during upgrades.

Instance access lists

Implemented against approved decision 202610-c8e3.

RbacPolicyPort.findRolesByNames(names, transaction?) is an optional batch lookup for existing role machine names and nullable display labels. It joins a supplied transaction and omits missing names. Existing rolesForUser/authorizationOfUser already supplies current role names; consumers pass those names into their own queries and never join RBAC tables. The state-machine manifest declares the new state-machine:instance:admin permission. Regenerate App permissions.json and grant it through RbacPermissionCatalog; a grantee's WRITE alone cannot manage access. API engine floor is 1.14.0.

Upgrade the affected mechanisms together after applying the App migration. The maintained model, HTTP routes, read-only list_instance_access MCP tool, errors and permission contract are documented in @haneinfo/state-machine/agent-guide.md. Its prisma/instance-access.sql migrates the existing reader table to USER/ROLE, READ/WRITE and ASSIGNED/DELEGATED/GRANTED rows while retaining timestamps. The maintainer selected (instanceId, principalType, principalId, source) uniqueness. Manual grants are limited to 100 by default; permanent READ entries survive manual removal. See the package repository validation/equipment-loan/instance-access/report.md for SQL, tests and App restoration evidence.

Authenticated role label lookup

GET /rbac/roles/lookup?q= uses InteractiveAuthGuard without administrative permissions. q is optional, trimmed and at most 200 characters. The response is an array of at most twenty { name, displayName } entries, ordered by machine name then id. LIKE metacharacters are literal. Permission content and membership are never included. Existing administrative /roles routes retain their guards. No new MCP tool or plugin-api contract is needed.

App-declared default roles

defaultRoleIds() no longer falls back to SYSTEM_USER_ROLE (USER) automatically. By default, newly created users receive no roles ([]). Apps that want new users (via manual creation, JIT, or CSV import with an empty roles cell) to receive default roles must configure rbac (configRef: "rbac"):

{
  "defaultRoleNames": ["EDITOR"]
}

To preserve the previous behavior of assigning USER automatically, configure defaultRoleNames: ["USER"]. Duplicate role names and ADMIN (SYSTEM_ADMIN_ROLE) are rejected at startup. Missing declared role names throw NotFoundException listing the missing names when defaultRoleIds() runs.

RbacPolicyService also implements RbacPolicyPort.resolveImportRoleIds(names, transaction?) for CSV user import: machine names are trimmed and deduplicated, ADMIN is rejected with system-admin, and missing roles are rejected with unknown.

版本与发布记录

@haneinfo/rbac 共发布 39 个版本,首次发布于 2026/10/02;过去 12 个月发布了 39 个版本。

版本发布日期距今
8.3.1latest2026/11/17今天
8.3.02026/11/161 天前
8.2.212026/11/0412 天前
8.2.202026/11/0214 天前
8.2.192026/11/0115 天前
8.2.182026/10/3017 天前

关于 @haneinfo/rbac 的常见问题

如何安装 @haneinfo/rbac?

在项目目录运行 npm install @haneinfo/rbac,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:zod(^4.4.0)、@nestjs/core(^11.0.0 || ^12.0.0)、@nestjs/common(^11.0.0 || ^12.0.0)、@prisma/client(^6.19.0 || ^7.10.1)、@haneinfo/common(^0.6.1 || ^0.7.0)、@haneinfo/plugin-host-nest(^2.0.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@haneinfo/rbac 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@haneinfo/rbac 支持 ESM 还是 CommonJS?

以 CommonJS 形式发布,可以直接 require();在 ES Module 项目中也可以用 import 引入(Node.js 会把 module.exports 作为默认导出)。

@haneinfo/rbac 可以商用吗?

@haneinfo/rbac 使用 UNLICENSED 许可。作者声明为 UNLICENSED,即不授予公开使用许可(与公共领域的 Unlicense 不同)。使用前需获得作者授权。以上为概括,不构成法律意见,请以许可原文为准。

@haneinfo/rbac 的下载量有多少?

根据 npm 官方下载统计,@haneinfo/rbac 在 2026/10/17 – 2026/11/15 这 30 天内被下载 5,831 次,日均约 194 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@haneinfo/rbac 还在维护吗?

最新版本 8.3.1 发布于 2026/11/17(今天);至今共发布 39 个版本,其中过去 12 个月发布了 39 个;首次发布于 2026/10/02。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。