@avallone-io/rls

中文文档
2.0.4发布于 2023/03/01ISCTypeScriptCommonJS近 30 天下载 3943

Row level security package for TypeORM and NestJS

此软件包已被标记为弃用

Package has moved to type-rls

原始使用文档

Build And Test .github/workflows/release.yml

Description

Row level security utilitary package to apply to NestJS and TypeORM.

This solution does not work by having multiple connections to database (eg: one connection / tenant). Instead, this solution works by applying the database policies for RLS as described in this aws blog post (under the Alternative approach).

Install

$ npm install @avallone-io/rls

Usage

To create a RLSConnection instance you'll need the original connection to db. Setup the typeorm config as usual, then wrap its connection into a RLSConnection instance, for each request.

This will run a set "rls.tenant_id" and set "rls.actor_id" for each request and will reset them after the query is executed.


RLS Policies

Your database policies will have to make use of rls.tenant_id and rls.actor_id in order to apply the isolation. Policy example:

CREATE POLICY tenant_isolation ON public."category" for ALL
USING ("tenant_id" = current_setting('rls.tenant_id'))
with check ("tenant_id" = current_setting('rls.tenant_id'));

Express/KOA

For example, assuming an express application:

app.use((req, res, next) => {
  const dataSource = await new DataSource({...}).initialize(); // create a datasource and initialize it

  // get tenantId and actorId from somewhere (headers/token etc)
  const rlsConnection = new RLSConnection(dataSource, {
    actorId,
    tenantId,
  });

  res.locals.connection = rlsConnection;
  next();
});

// your handlers
const userRepo = res.locals.connection.getRepository(User);
await userRepo.find(); // will return only the results where the db rls policy applies

In the above example, you'll have to work with the supplied connection. Calling TypeORM function directly will work with the original DataSource object which is not RLS aware.

NestJS integration

If you are using NestJS, this library provides helpers for making your connections and queries tenant aware.

Create your TypeORM config and load the TypeORM module using .forRoot. Then you'll need to load the RLSModule with .forRoot where you'll define where to take the tenantId and actorId from. The second part is that you now need to replace the TypeOrmModule.forFeature with RLSModule.forFeature. This should be a 1-to-1 replacement. You can inject non-entity dependent Modules and Providers. First array imports modules, second array injects providers.

When using RLSModule.forRoot it will set your scope to REQUEST! Be sure you understand the implications of this and especially read about the request-scoped authentication strategy on Nestjs docs.

The RLSModule.forRoot accepts the factory funtion as async or non-async function.

app.controller.ts

@Module({
  imports: [
    TypeOrmModule.forRoot(...),
    RLSModule.forRoot([/*Module*/], [/*Service*/], async (req: Request, /*serviceInstance*/) => {
      // You can take the tenantId and actorId from headers/tokens etc
      const tenantId = req.headers['tenant_id'];
      const actorId = req.headers['actor_id'];

      return {
        actorId,
        tenantId,
      };
    }),
    RLSModule.forFeature([Post, Category]) // <- this
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

Now you can use the normal module injection for repositories, services etc.

To inject the RLS connection within a service, you can do by using @Inject(TENANT_CONNECTION) where TENANT_CONNECTION is imported from @avallone-io/rls.

export class AppService {
  constructor(
    @InjectRepository(Category)
    private categoryRepo: Repository<Category>,
    @Inject(TENANT_CONNECTION)
    private connection: RLSConnection,
  ) {}

  // you can now use categoryRepo as normal but it will
  // be scoped for RLS. Same with the connection.
}

Same as before, do not use the TypeORM functions directly from the dataSource as that will give you the default connection to the database, not the wrapped instance.

For more specific examples, check the test/nestjs/src.

Typeorm >v0.3.0

Since typeorm v0.3.0, the Connection class has been replaced by DataSource. This module still uses Connection as its language which is also helpful now to differenciate between the actual database connection (typeorm DataSource) and RLS wrapper (RLSConnection). However, if you want to be on par with typeorm terminalogy, there is an alias for RLSConnection called RLSDataSource.

版本与发布记录

@avallone-io/rls 共发布 21 个版本,首次发布于 2021/06/04;过去 12 个月发布了 0 个版本。

版本发布日期距今
2.0.4latest2023/03/013 年前
2.0.32022/11/223 年前
1.4.12022/11/223 年前
2.0.12022/11/223 年前
2.0.02022/08/234 年前
1.4.02022/08/084 年前

关于 @avallone-io/rls 的常见问题

@avallone-io/rls 是什么?

Row level security package for TypeORM and NestJS注意:该包已被作者标记为弃用——Package has moved to type-rls

如何安装 @avallone-io/rls?

在项目目录运行 npm install @avallone-io/rls,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:typeorm(~0.3.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@avallone-io/rls 支持 TypeScript 吗?

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

@avallone-io/rls 支持 ESM 还是 CommonJS?

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

@avallone-io/rls 可以商用吗?

@avallone-io/rls 使用 ISC 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@avallone-io/rls 的下载量有多少?

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

@avallone-io/rls 还在维护吗?

最新版本 2.0.4 发布于 2023/03/01(3 年前);至今共发布 21 个版本,其中过去 12 个月发布了 0 个;首次发布于 2021/06/04。作者已将其标记为弃用,新项目建议寻找替代方案。