@anievo-id/rbac-evolution-prisma 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +159 -2
- package/dist/index.cjs +246 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +161 -0
- package/dist/index.d.ts +161 -0
- package/dist/index.js +244 -0
- package/dist/index.js.map +1 -0
- package/package.json +69 -3
- package/schema/rbac.prisma +77 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 AniEvo-ID
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,160 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @anievo-id/rbac-evolution-prisma
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
[Prisma](https://www.prisma.io) storage adapter for [rbac-evolution](../../README.md), a TypeScript port of spatie/laravel-permission.
|
|
4
|
+
|
|
5
|
+
It stores roles and permissions in the same five tables spatie uses: `permissions`, `roles`, `role_has_permissions`, `model_has_roles` and `model_has_permissions`.
|
|
6
|
+
|
|
7
|
+
## Install
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
npm i @anievo-id/rbac-evolution @anievo-id/rbac-evolution-prisma
|
|
11
|
+
# you already have these in a Prisma project:
|
|
12
|
+
npm i @prisma/client && npm i -D prisma
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
Requires `@prisma/client` 5.12 or later. Earlier versions do not support `createMany` on SQLite.
|
|
16
|
+
|
|
17
|
+
## 1. Add the models to your schema
|
|
18
|
+
|
|
19
|
+
Copy the models below into your `schema.prisma`. If you use a multi-file schema folder, you can copy the shipped file `node_modules/@anievo-id/rbac-evolution-prisma/schema/rbac.prisma` in as-is. Keep the model names, because the adapter talks to `prisma.rbacPermission`, `prisma.rbacRole` and the other delegates by name. Table and column names (`@@map` / `@map`) can be changed.
|
|
20
|
+
|
|
21
|
+
```prisma
|
|
22
|
+
model RbacPermission {
|
|
23
|
+
id Int @id @default(autoincrement())
|
|
24
|
+
name String
|
|
25
|
+
guardName String @map("guard_name")
|
|
26
|
+
createdAt DateTime @default(now()) @map("created_at")
|
|
27
|
+
updatedAt DateTime @default(now()) @updatedAt @map("updated_at")
|
|
28
|
+
|
|
29
|
+
roles RbacRoleHasPermission[]
|
|
30
|
+
subjects RbacModelHasPermission[]
|
|
31
|
+
|
|
32
|
+
@@unique([name, guardName])
|
|
33
|
+
@@map("permissions")
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
model RbacRole {
|
|
37
|
+
id Int @id @default(autoincrement())
|
|
38
|
+
teamId String @default("") @map("team_id")
|
|
39
|
+
name String
|
|
40
|
+
guardName String @map("guard_name")
|
|
41
|
+
createdAt DateTime @default(now()) @map("created_at")
|
|
42
|
+
updatedAt DateTime @default(now()) @updatedAt @map("updated_at")
|
|
43
|
+
|
|
44
|
+
permissions RbacRoleHasPermission[]
|
|
45
|
+
subjects RbacModelHasRole[]
|
|
46
|
+
|
|
47
|
+
@@unique([name, guardName, teamId])
|
|
48
|
+
@@index([teamId])
|
|
49
|
+
@@map("roles")
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
model RbacRoleHasPermission {
|
|
53
|
+
permissionId Int @map("permission_id")
|
|
54
|
+
roleId Int @map("role_id")
|
|
55
|
+
|
|
56
|
+
permission RbacPermission @relation(fields: [permissionId], references: [id], onDelete: Cascade)
|
|
57
|
+
role RbacRole @relation(fields: [roleId], references: [id], onDelete: Cascade)
|
|
58
|
+
|
|
59
|
+
@@id([roleId, permissionId])
|
|
60
|
+
@@index([permissionId])
|
|
61
|
+
@@map("role_has_permissions")
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
model RbacModelHasRole {
|
|
65
|
+
roleId Int @map("role_id")
|
|
66
|
+
subjectType String @map("subject_type")
|
|
67
|
+
subjectId String @map("subject_id")
|
|
68
|
+
teamId String @default("") @map("team_id")
|
|
69
|
+
|
|
70
|
+
role RbacRole @relation(fields: [roleId], references: [id], onDelete: Cascade)
|
|
71
|
+
|
|
72
|
+
@@id([roleId, subjectType, subjectId, teamId])
|
|
73
|
+
@@index([subjectType, subjectId, teamId])
|
|
74
|
+
@@map("model_has_roles")
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
model RbacModelHasPermission {
|
|
78
|
+
permissionId Int @map("permission_id")
|
|
79
|
+
subjectType String @map("subject_type")
|
|
80
|
+
subjectId String @map("subject_id")
|
|
81
|
+
teamId String @default("") @map("team_id")
|
|
82
|
+
|
|
83
|
+
permission RbacPermission @relation(fields: [permissionId], references: [id], onDelete: Cascade)
|
|
84
|
+
|
|
85
|
+
@@id([permissionId, subjectType, subjectId, teamId])
|
|
86
|
+
@@index([subjectType, subjectId, teamId])
|
|
87
|
+
@@map("model_has_permissions")
|
|
88
|
+
}
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
Then create the tables:
|
|
92
|
+
|
|
93
|
+
```bash
|
|
94
|
+
npx prisma migrate dev --name rbac # or: npx prisma db push
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
## 2. Use it
|
|
98
|
+
|
|
99
|
+
```ts
|
|
100
|
+
import { PrismaClient } from '@prisma/client'
|
|
101
|
+
import { createRbac } from '@anievo-id/rbac-evolution'
|
|
102
|
+
import { PrismaAdapter } from '@anievo-id/rbac-evolution-prisma'
|
|
103
|
+
|
|
104
|
+
const prisma = new PrismaClient()
|
|
105
|
+
export const rbac = createRbac({ adapter: new PrismaAdapter(prisma) })
|
|
106
|
+
|
|
107
|
+
await rbac.createPermission('edit articles')
|
|
108
|
+
await rbac.createRole('writer')
|
|
109
|
+
await rbac.role('writer').givePermissionTo('edit articles')
|
|
110
|
+
|
|
111
|
+
const user = rbac.for({ type: 'user', id: currentUser.id })
|
|
112
|
+
await user.assignRole('writer')
|
|
113
|
+
await user.can('edit articles') // true
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
The adapter does not import your generated client. It accepts any object with the five delegates plus `$transaction`, so it works with a custom generator `output`, extra models and `$extends(...)`-extended clients.
|
|
117
|
+
|
|
118
|
+
### Teams
|
|
119
|
+
|
|
120
|
+
```ts
|
|
121
|
+
const rbac = createRbac({ adapter: new PrismaAdapter(prisma), teams: true })
|
|
122
|
+
await rbac.for(user, { team: org.id }).assignRole('admin')
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
## How data is stored
|
|
126
|
+
|
|
127
|
+
| Concept | Column(s) | Notes |
|
|
128
|
+
| ------------------ | --------------------------------- | ----- |
|
|
129
|
+
| Role / permission id | `id` autoincrement `Int` | Returned as a `number`. Numeric strings (`'42'`) are accepted as input. |
|
|
130
|
+
| Subject | `subject_type` + `subject_id` (text) | Any id type works: number, UUID or cuid. `1` and `'1'` are the same subject. Reverse lookups (`getSubjectIdsWithRoles` / `...WithPermissions`) return ids as **strings**. |
|
|
131
|
+
| Team | `team_id` text, NOT NULL | `''` (empty string) means global / no team. This keeps composite primary keys and unique constraints working, because `NULL`s never collide. `Role.teamId` comes back as `null` for global roles, otherwise as a string (`'7'`). Do not use `''` as a real team id. |
|
|
132
|
+
|
|
133
|
+
Deleting a role or permission removes its links in the same transaction, so the `onDelete: Cascade` relations are a safety net and are not required. This means it also works with `relationMode = "prisma"`.
|
|
134
|
+
|
|
135
|
+
## Database notes
|
|
136
|
+
|
|
137
|
+
- **PostgreSQL / CockroachDB / MySQL / MariaDB**: pass `{ skipDuplicates: true }` so each attach is a single race-free `INSERT ... ON CONFLICT DO NOTHING` / `INSERT IGNORE`:
|
|
138
|
+
|
|
139
|
+
```ts
|
|
140
|
+
new PrismaAdapter(prisma, { skipDuplicates: true })
|
|
141
|
+
```
|
|
142
|
+
|
|
143
|
+
The default (`false`) works on every connector. It reads the existing links, inserts only the missing ones, and retries if a concurrent request inserted the same link first.
|
|
144
|
+
- **SQLite / SQL Server**: keep the default. These connectors do not support `skipDuplicates`.
|
|
145
|
+
- **MySQL**: `String` maps to `VARCHAR(191)`, so the composite keys stay under InnoDB's 3072-byte index limit with `utf8mb4`. Do not widen these columns to `@db.Text`, because MySQL cannot index a full `TEXT` column.
|
|
146
|
+
- **PostgreSQL**: `String` maps to `text`, which needs no changes.
|
|
147
|
+
- **MongoDB** is not supported: the schema relies on autoincrement ids and composite primary keys.
|
|
148
|
+
- Name uniqueness is checked by the engine and enforced by the unique constraints. A duplicate that slips through a race raises Prisma's `P2002` error.
|
|
149
|
+
|
|
150
|
+
## Development
|
|
151
|
+
|
|
152
|
+
```bash
|
|
153
|
+
pnpm --filter @anievo-id/rbac-evolution-prisma test
|
|
154
|
+
```
|
|
155
|
+
|
|
156
|
+
`node test/prepare.mjs` builds a SQLite test schema from `schema/rbac.prisma`. It generates the client into `test/generated` and recreates `test/.tmp/test.db`. The script then runs the shared `runAdapterTests` conformance suite plus the adapter-specific tests.
|
|
157
|
+
|
|
158
|
+
## License
|
|
159
|
+
|
|
160
|
+
MIT
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,246 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// src/index.ts
|
|
4
|
+
var GLOBAL_TEAM = "";
|
|
5
|
+
var teamKey = (teamId) => teamId === null ? GLOBAL_TEAM : String(teamId);
|
|
6
|
+
var teamFromKey = (key) => key === GLOBAL_TEAM ? null : key;
|
|
7
|
+
var subjectKey = (subject) => String(subject.id);
|
|
8
|
+
var toIntId = (id) => {
|
|
9
|
+
if (typeof id === "number") return Number.isSafeInteger(id) ? id : void 0;
|
|
10
|
+
if (!/^-?\d+$/.test(id.trim())) return void 0;
|
|
11
|
+
const n = Number(id);
|
|
12
|
+
return Number.isSafeInteger(n) ? n : void 0;
|
|
13
|
+
};
|
|
14
|
+
var toIntIds = (ids) => {
|
|
15
|
+
const out = /* @__PURE__ */ new Set();
|
|
16
|
+
for (const id of ids) {
|
|
17
|
+
const n = toIntId(id);
|
|
18
|
+
if (n !== void 0) out.add(n);
|
|
19
|
+
}
|
|
20
|
+
return [...out];
|
|
21
|
+
};
|
|
22
|
+
var requireIntIds = (ids, what) => {
|
|
23
|
+
const out = /* @__PURE__ */ new Set();
|
|
24
|
+
for (const id of ids) {
|
|
25
|
+
const n = toIntId(id);
|
|
26
|
+
if (n === void 0) throw new TypeError(`PrismaAdapter: invalid ${what} id ${JSON.stringify(id)} (expected an integer).`);
|
|
27
|
+
out.add(n);
|
|
28
|
+
}
|
|
29
|
+
return [...out];
|
|
30
|
+
};
|
|
31
|
+
var isUniqueViolation = (error) => typeof error === "object" && error !== null && error.code === "P2002";
|
|
32
|
+
var toPermission = (row) => ({
|
|
33
|
+
id: row.id,
|
|
34
|
+
name: row.name,
|
|
35
|
+
guardName: row.guardName
|
|
36
|
+
});
|
|
37
|
+
var toRole = (row) => ({
|
|
38
|
+
id: row.id,
|
|
39
|
+
name: row.name,
|
|
40
|
+
guardName: row.guardName,
|
|
41
|
+
teamId: teamFromKey(row.teamId)
|
|
42
|
+
});
|
|
43
|
+
var unique = (values) => [...new Set(values)];
|
|
44
|
+
var PrismaAdapter = class {
|
|
45
|
+
#db;
|
|
46
|
+
#skipDuplicates;
|
|
47
|
+
constructor(prisma, options = {}) {
|
|
48
|
+
this.#db = prisma;
|
|
49
|
+
this.#skipDuplicates = options.skipDuplicates ?? false;
|
|
50
|
+
}
|
|
51
|
+
// ---------------------------------------------------------------- permissions
|
|
52
|
+
async createPermission(data) {
|
|
53
|
+
const row = await this.#db.rbacPermission.create({ data: { name: data.name, guardName: data.guardName } });
|
|
54
|
+
return toPermission(row);
|
|
55
|
+
}
|
|
56
|
+
async findPermissions(query = {}) {
|
|
57
|
+
const where = {};
|
|
58
|
+
if (query.ids !== void 0) {
|
|
59
|
+
const ids = toIntIds(query.ids);
|
|
60
|
+
if (ids.length === 0) return [];
|
|
61
|
+
where.id = { in: ids };
|
|
62
|
+
}
|
|
63
|
+
if (query.names !== void 0) {
|
|
64
|
+
if (query.names.length === 0) return [];
|
|
65
|
+
where.name = { in: unique(query.names) };
|
|
66
|
+
}
|
|
67
|
+
if (query.guardName !== void 0) where.guardName = query.guardName;
|
|
68
|
+
const rows = await this.#db.rbacPermission.findMany({ where, orderBy: { id: "asc" } });
|
|
69
|
+
return rows.map(toPermission);
|
|
70
|
+
}
|
|
71
|
+
async deletePermission(id) {
|
|
72
|
+
const permissionId = toIntId(id);
|
|
73
|
+
if (permissionId === void 0) return;
|
|
74
|
+
await this.#db.$transaction([
|
|
75
|
+
this.#db.rbacRoleHasPermission.deleteMany({ where: { permissionId } }),
|
|
76
|
+
this.#db.rbacModelHasPermission.deleteMany({ where: { permissionId } }),
|
|
77
|
+
this.#db.rbacPermission.deleteMany({ where: { id: permissionId } })
|
|
78
|
+
]);
|
|
79
|
+
}
|
|
80
|
+
// ---------------------------------------------------------------------- roles
|
|
81
|
+
async createRole(data) {
|
|
82
|
+
const row = await this.#db.rbacRole.create({
|
|
83
|
+
data: { name: data.name, guardName: data.guardName, teamId: teamKey(data.teamId) }
|
|
84
|
+
});
|
|
85
|
+
return toRole(row);
|
|
86
|
+
}
|
|
87
|
+
async findRoles(query = {}) {
|
|
88
|
+
const where = {};
|
|
89
|
+
if (query.ids !== void 0) {
|
|
90
|
+
const ids = toIntIds(query.ids);
|
|
91
|
+
if (ids.length === 0) return [];
|
|
92
|
+
where.id = { in: ids };
|
|
93
|
+
}
|
|
94
|
+
if (query.names !== void 0) {
|
|
95
|
+
if (query.names.length === 0) return [];
|
|
96
|
+
where.name = { in: unique(query.names) };
|
|
97
|
+
}
|
|
98
|
+
if (query.guardName !== void 0) where.guardName = query.guardName;
|
|
99
|
+
if (query.teamIds !== void 0) {
|
|
100
|
+
if (query.teamIds.length === 0) return [];
|
|
101
|
+
where.teamId = { in: unique(query.teamIds.map(teamKey)) };
|
|
102
|
+
}
|
|
103
|
+
const rows = await this.#db.rbacRole.findMany({ where, orderBy: { id: "asc" } });
|
|
104
|
+
return rows.map(toRole);
|
|
105
|
+
}
|
|
106
|
+
async deleteRole(id) {
|
|
107
|
+
const roleId = toIntId(id);
|
|
108
|
+
if (roleId === void 0) return;
|
|
109
|
+
await this.#db.$transaction([
|
|
110
|
+
this.#db.rbacRoleHasPermission.deleteMany({ where: { roleId } }),
|
|
111
|
+
this.#db.rbacModelHasRole.deleteMany({ where: { roleId } }),
|
|
112
|
+
this.#db.rbacRole.deleteMany({ where: { id: roleId } })
|
|
113
|
+
]);
|
|
114
|
+
}
|
|
115
|
+
// ---------------------------------------------------------- role ↔ permission
|
|
116
|
+
async getRolePermissionLinks(roleIds) {
|
|
117
|
+
const ids = toIntIds(roleIds);
|
|
118
|
+
if (ids.length === 0) return [];
|
|
119
|
+
const rows = await this.#db.rbacRoleHasPermission.findMany({ where: { roleId: { in: ids } } });
|
|
120
|
+
return rows.map((r) => ({ roleId: r.roleId, permissionId: r.permissionId }));
|
|
121
|
+
}
|
|
122
|
+
async attachRolePermissions(roleId, permissionIds) {
|
|
123
|
+
const [role] = requireIntIds([roleId], "role");
|
|
124
|
+
const ids = requireIntIds(permissionIds, "permission");
|
|
125
|
+
if (role === void 0 || ids.length === 0) return;
|
|
126
|
+
const delegate = this.#db.rbacRoleHasPermission;
|
|
127
|
+
await this.#insertMissing(
|
|
128
|
+
ids,
|
|
129
|
+
async () => (await delegate.findMany({ where: { roleId: role, permissionId: { in: ids } } })).map((r) => r.permissionId),
|
|
130
|
+
(data) => delegate.createMany({ data: data.map((permissionId) => ({ roleId: role, permissionId })), ...this.#skip() })
|
|
131
|
+
);
|
|
132
|
+
}
|
|
133
|
+
async detachRolePermissions(roleId, permissionIds) {
|
|
134
|
+
const role = toIntId(roleId);
|
|
135
|
+
if (role === void 0) return;
|
|
136
|
+
if (permissionIds === void 0) {
|
|
137
|
+
await this.#db.rbacRoleHasPermission.deleteMany({ where: { roleId: role } });
|
|
138
|
+
return;
|
|
139
|
+
}
|
|
140
|
+
const ids = toIntIds(permissionIds);
|
|
141
|
+
if (ids.length === 0) return;
|
|
142
|
+
await this.#db.rbacRoleHasPermission.deleteMany({ where: { roleId: role, permissionId: { in: ids } } });
|
|
143
|
+
}
|
|
144
|
+
// ------------------------------------------------------------- subject ↔ role
|
|
145
|
+
async getSubjectRoleIds(subject, teamId) {
|
|
146
|
+
const rows = await this.#db.rbacModelHasRole.findMany({ where: this.#subjectWhere(subject, teamId) });
|
|
147
|
+
return rows.map((r) => r.roleId);
|
|
148
|
+
}
|
|
149
|
+
async attachSubjectRoles(subject, roleIds, teamId) {
|
|
150
|
+
const ids = requireIntIds(roleIds, "role");
|
|
151
|
+
if (ids.length === 0) return;
|
|
152
|
+
const base = this.#subjectWhere(subject, teamId);
|
|
153
|
+
const delegate = this.#db.rbacModelHasRole;
|
|
154
|
+
await this.#insertMissing(
|
|
155
|
+
ids,
|
|
156
|
+
async () => (await delegate.findMany({ where: { ...base, roleId: { in: ids } } })).map((r) => r.roleId),
|
|
157
|
+
(data) => delegate.createMany({ data: data.map((roleId) => ({ ...base, roleId })), ...this.#skip() })
|
|
158
|
+
);
|
|
159
|
+
}
|
|
160
|
+
async detachSubjectRoles(subject, roleIds, teamId) {
|
|
161
|
+
const base = this.#subjectWhere(subject, teamId);
|
|
162
|
+
if (roleIds === void 0) {
|
|
163
|
+
await this.#db.rbacModelHasRole.deleteMany({ where: base });
|
|
164
|
+
return;
|
|
165
|
+
}
|
|
166
|
+
const ids = toIntIds(roleIds);
|
|
167
|
+
if (ids.length === 0) return;
|
|
168
|
+
await this.#db.rbacModelHasRole.deleteMany({ where: { ...base, roleId: { in: ids } } });
|
|
169
|
+
}
|
|
170
|
+
// ------------------------------------------------------- subject ↔ permission
|
|
171
|
+
async getSubjectPermissionIds(subject, teamId) {
|
|
172
|
+
const rows = await this.#db.rbacModelHasPermission.findMany({ where: this.#subjectWhere(subject, teamId) });
|
|
173
|
+
return rows.map((r) => r.permissionId);
|
|
174
|
+
}
|
|
175
|
+
async attachSubjectPermissions(subject, permissionIds, teamId) {
|
|
176
|
+
const ids = requireIntIds(permissionIds, "permission");
|
|
177
|
+
if (ids.length === 0) return;
|
|
178
|
+
const base = this.#subjectWhere(subject, teamId);
|
|
179
|
+
const delegate = this.#db.rbacModelHasPermission;
|
|
180
|
+
await this.#insertMissing(
|
|
181
|
+
ids,
|
|
182
|
+
async () => (await delegate.findMany({ where: { ...base, permissionId: { in: ids } } })).map((r) => r.permissionId),
|
|
183
|
+
(data) => delegate.createMany({ data: data.map((permissionId) => ({ ...base, permissionId })), ...this.#skip() })
|
|
184
|
+
);
|
|
185
|
+
}
|
|
186
|
+
async detachSubjectPermissions(subject, permissionIds, teamId) {
|
|
187
|
+
const base = this.#subjectWhere(subject, teamId);
|
|
188
|
+
if (permissionIds === void 0) {
|
|
189
|
+
await this.#db.rbacModelHasPermission.deleteMany({ where: base });
|
|
190
|
+
return;
|
|
191
|
+
}
|
|
192
|
+
const ids = toIntIds(permissionIds);
|
|
193
|
+
if (ids.length === 0) return;
|
|
194
|
+
await this.#db.rbacModelHasPermission.deleteMany({ where: { ...base, permissionId: { in: ids } } });
|
|
195
|
+
}
|
|
196
|
+
// ------------------------------------------------------------ reverse lookups
|
|
197
|
+
async getSubjectIdsWithRoles(subjectType, roleIds, teamId) {
|
|
198
|
+
const ids = toIntIds(roleIds);
|
|
199
|
+
if (ids.length === 0) return [];
|
|
200
|
+
const rows = await this.#db.rbacModelHasRole.findMany({
|
|
201
|
+
where: { subjectType, teamId: teamKey(teamId), roleId: { in: ids } }
|
|
202
|
+
});
|
|
203
|
+
return unique(rows.map((r) => r.subjectId));
|
|
204
|
+
}
|
|
205
|
+
async getSubjectIdsWithPermissions(subjectType, permissionIds, teamId) {
|
|
206
|
+
const ids = toIntIds(permissionIds);
|
|
207
|
+
if (ids.length === 0) return [];
|
|
208
|
+
const rows = await this.#db.rbacModelHasPermission.findMany({
|
|
209
|
+
where: { subjectType, teamId: teamKey(teamId), permissionId: { in: ids } }
|
|
210
|
+
});
|
|
211
|
+
return unique(rows.map((r) => r.subjectId));
|
|
212
|
+
}
|
|
213
|
+
// -------------------------------------------------------------------- helpers
|
|
214
|
+
#subjectWhere(subject, teamId) {
|
|
215
|
+
return { subjectType: subject.type, subjectId: subjectKey(subject), teamId: teamKey(teamId) };
|
|
216
|
+
}
|
|
217
|
+
#skip() {
|
|
218
|
+
return this.#skipDuplicates ? { skipDuplicates: true } : {};
|
|
219
|
+
}
|
|
220
|
+
/**
|
|
221
|
+
* Idempotent insert. With `skipDuplicates` it is a single `createMany`; otherwise the existing
|
|
222
|
+
* links are read first and only the missing ones inserted. A concurrent insert of the same link
|
|
223
|
+
* (unique violation P2002) is retried once, re-reading what now exists.
|
|
224
|
+
*/
|
|
225
|
+
async #insertMissing(ids, existing, insert) {
|
|
226
|
+
if (this.#skipDuplicates) {
|
|
227
|
+
await insert(ids);
|
|
228
|
+
return;
|
|
229
|
+
}
|
|
230
|
+
for (let attempt = 0; ; attempt++) {
|
|
231
|
+
const have = new Set(await existing());
|
|
232
|
+
const missing = ids.filter((id) => !have.has(id));
|
|
233
|
+
if (missing.length === 0) return;
|
|
234
|
+
try {
|
|
235
|
+
await insert(missing);
|
|
236
|
+
return;
|
|
237
|
+
} catch (error) {
|
|
238
|
+
if (attempt >= 2 || !isUniqueViolation(error)) throw error;
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
};
|
|
243
|
+
|
|
244
|
+
exports.PrismaAdapter = PrismaAdapter;
|
|
245
|
+
//# sourceMappingURL=index.cjs.map
|
|
246
|
+
//# sourceMappingURL=index.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"names":[],"mappings":";;;AAkIA,IAAM,WAAA,GAAc,EAAA;AAGpB,IAAM,UAAU,CAAC,MAAA,KAA4B,WAAW,IAAA,GAAO,WAAA,GAAc,OAAO,MAAM,CAAA;AAC1F,IAAM,WAAA,GAAc,CAAC,GAAA,KAAyB,GAAA,KAAQ,cAAc,IAAA,GAAO,GAAA;AAC3E,IAAM,UAAA,GAAa,CAAC,OAAA,KAA6B,MAAA,CAAO,QAAQ,EAAE,CAAA;AAGlE,IAAM,OAAA,GAAU,CAAC,EAAA,KAA+B;AAC9C,EAAA,IAAI,OAAO,OAAO,QAAA,EAAU,OAAO,OAAO,aAAA,CAAc,EAAE,IAAI,EAAA,GAAK,MAAA;AACnE,EAAA,IAAI,CAAC,SAAA,CAAU,IAAA,CAAK,GAAG,IAAA,EAAM,GAAG,OAAO,MAAA;AACvC,EAAA,MAAM,CAAA,GAAI,OAAO,EAAE,CAAA;AACnB,EAAA,OAAO,MAAA,CAAO,aAAA,CAAc,CAAC,CAAA,GAAI,CAAA,GAAI,MAAA;AACvC,CAAA;AAEA,IAAM,QAAA,GAAW,CAAC,G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,WAAW,CAAA,EAAG;AAC1B,MAAA,IAAI;AACF,QAAA,MAAM,OAAO,OAAO,CAAA;AACpB,QAAA;AAAA,MACF,SAAS,KAAA,EAAO;AACd,QAAA,IAAI,WAAW,CAAA,IAAK,CAAC,iBAAA,CAAkB,KAAK,GAAG,MAAM,KAAA;AAAA,MACvD;AAAA,IACF;AAAA,EACF;AACF","file":"index.cjs","sourcesContent":["/**\n * @anievo-id/rbac-evolution-prisma\n *\n * Prisma storage adapter for rbac-evolution. Copy the models from `schema/rbac.prisma`\n * into your schema, run `prisma generate`, then:\n *\n * ```ts\n * import { createRbac } from '@anievo-id/rbac-evolution'\n * import { PrismaAdapter } from '@anievo-id/rbac-evolution-prisma'\n *\n * const rbac = createRbac({ adapter: new PrismaAdapter(prisma) })\n * ```\n */\nimport type {\n FindPermissionsQuery,\n FindRolesQuery,\n Id,\n Permission,\n RbacAdapter,\n Role,\n RolePermissionLink,\n Subject,\n TeamId,\n} from '@anievo-id/rbac-evolution'\n\n// ------------------------------------------------------------------ structural client types\n// Minimal shapes of the delegates generated from `schema/rbac.prisma`. They are structural so the\n// adapter works with any generated client (any output path, extra models, client extensions).\n\ntype IntFilter = number | { in: number[] }\ntype StringFilter = string | { in: string[] }\n\nexport interface PrismaRbacPermissionRow {\n id: number\n name: string\n guardName: string\n}\n\nexport interface PrismaRbacRoleRow {\n id: number\n name: string\n guardName: string\n teamId: string\n}\n\nexport interface PrismaRbacRoleHasPermissionRow {\n roleId: number\n permissionId: number\n}\n\nexport interface PrismaRbacModelHasRoleRow {\n roleId: number\n subjectType: string\n subjectId: string\n teamId: string\n}\n\nexport interface PrismaRbacModelHasPermissionRow {\n permissionId: number\n subjectType: string\n subjectId: string\n teamId: string\n}\n\ninterface BatchPayload {\n count: number\n}\n\n/** Generic subset of a Prisma model delegate used by the adapter. */\nexport interface PrismaRbacDelegate<Row, Where, Create, OrderBy = never> {\n findMany(args: { where?: Where; orderBy?: OrderBy }): PromiseLike<Row[]>\n create(args: { data: Create }): PromiseLike<Row>\n /** `skipDuplicates` is passed only when enabled (SQLite clients type it as `never`). */\n createMany(args: { data: Create[] }): PromiseLike<BatchPayload>\n deleteMany(args: { where: Where }): PromiseLike<BatchPayload>\n}\n\nexport type PrismaRbacPermissionDelegate = PrismaRbacDelegate<\n PrismaRbacPermissionRow,\n { id?: IntFilter; name?: StringFilter; guardName?: string },\n { name: string; guardName: string },\n { id: 'asc' }\n>\n\nexport type PrismaRbacRoleDelegate = PrismaRbacDelegate<\n PrismaRbacRoleRow,\n { id?: IntFilter; name?: StringFilter; guardName?: string; teamId?: StringFilter },\n { name: string; guardName: string; teamId: string },\n { id: 'asc' }\n>\n\nexport type PrismaRbacRoleHasPermissionDelegate = PrismaRbacDelegate<\n PrismaRbacRoleHasPermissionRow,\n { roleId?: IntFilter; permissionId?: IntFilter },\n PrismaRbacRoleHasPermissionRow\n>\n\nexport type PrismaRbacModelHasRoleDelegate = PrismaRbacDelegate<\n PrismaRbacModelHasRoleRow,\n { roleId?: IntFilter; subjectType?: string; subjectId?: string; teamId?: string },\n PrismaRbacModelHasRoleRow\n>\n\nexport type PrismaRbacModelHasPermissionDelegate = PrismaRbacDelegate<\n PrismaRbacModelHasPermissionRow,\n { permissionId?: IntFilter; subjectType?: string; subjectId?: string; teamId?: string },\n PrismaRbacModelHasPermissionRow\n>\n\n/** The part of a `PrismaClient` (with the rbac models) that the adapter needs. */\nexport interface PrismaRbacClient {\n rbacPermission: PrismaRbacPermissionDelegate\n rbacRole: PrismaRbacRoleDelegate\n rbacRoleHasPermission: PrismaRbacRoleHasPermissionDelegate\n rbacModelHasRole: PrismaRbacModelHasRoleDelegate\n rbacModelHasPermission: PrismaRbacModelHasPermissionDelegate\n $transaction(queries: PromiseLike<unknown>[]): PromiseLike<unknown>\n}\n\nexport interface PrismaAdapterOptions {\n /**\n * Use `createMany({ skipDuplicates: true })` for attach operations (one query, race-free).\n * Supported by PostgreSQL, MySQL/MariaDB and CockroachDB — NOT by SQLite, SQL Server or MongoDB.\n * Default: `false` (portable: reads existing links first, inserts only the missing ones).\n */\n skipDuplicates?: boolean\n}\n\n// ------------------------------------------------------------------------------- helpers\n\nconst GLOBAL_TEAM = ''\n\n/** `null` (global) is stored as `''`; every other team id as text. */\nconst teamKey = (teamId: TeamId): string => (teamId === null ? GLOBAL_TEAM : String(teamId))\nconst teamFromKey = (key: string): TeamId => (key === GLOBAL_TEAM ? null : key)\nconst subjectKey = (subject: Subject): string => String(subject.id)\n\n/** Converts an engine id (number or numeric string) into the Int primary key. */\nconst toIntId = (id: Id): number | undefined => {\n if (typeof id === 'number') return Number.isSafeInteger(id) ? id : undefined\n if (!/^-?\\d+$/.test(id.trim())) return undefined\n const n = Number(id)\n return Number.isSafeInteger(n) ? n : undefined\n}\n\nconst toIntIds = (ids: readonly Id[]): number[] => {\n const out = new Set<number>()\n for (const id of ids) {\n const n = toIntId(id)\n if (n !== undefined) out.add(n)\n }\n return [...out]\n}\n\nconst requireIntIds = (ids: readonly Id[], what: string): number[] => {\n const out = new Set<number>()\n for (const id of ids) {\n const n = toIntId(id)\n if (n === undefined) throw new TypeError(`PrismaAdapter: invalid ${what} id ${JSON.stringify(id)} (expected an integer).`)\n out.add(n)\n }\n return [...out]\n}\n\nconst isUniqueViolation = (error: unknown): boolean =>\n typeof error === 'object' && error !== null && (error as { code?: unknown }).code === 'P2002'\n\nconst toPermission = (row: PrismaRbacPermissionRow): Permission => ({\n id: row.id,\n name: row.name,\n guardName: row.guardName,\n})\n\nconst toRole = (row: PrismaRbacRoleRow): Role => ({\n id: row.id,\n name: row.name,\n guardName: row.guardName,\n teamId: teamFromKey(row.teamId),\n})\n\nconst unique = (values: readonly string[]): string[] => [...new Set(values)]\n\n// ------------------------------------------------------------------------------- adapter\n\n/**\n * `RbacAdapter` backed by Prisma. Requires the models from `schema/rbac.prisma`.\n *\n * - Role / permission ids are returned as numbers (numeric strings are accepted as input).\n * - Subject ids are stored as text; reverse lookups return them as strings.\n * - `Role.teamId` is `null` for global roles, otherwise the team id as a string.\n */\nexport class PrismaAdapter implements RbacAdapter {\n readonly #db: PrismaRbacClient\n readonly #skipDuplicates: boolean\n\n constructor(prisma: PrismaRbacClient, options: PrismaAdapterOptions = {}) {\n this.#db = prisma\n this.#skipDuplicates = options.skipDuplicates ?? false\n }\n\n // ---------------------------------------------------------------- permissions\n\n async createPermission(data: { name: string; guardName: string }): Promise<Permission> {\n const row = await this.#db.rbacPermission.create({ data: { name: data.name, guardName: data.guardName } })\n return toPermission(row)\n }\n\n async findPermissions(query: FindPermissionsQuery = {}): Promise<Permission[]> {\n const where: { id?: IntFilter; name?: StringFilter; guardName?: string } = {}\n if (query.ids !== undefined) {\n const ids = toIntIds(query.ids)\n if (ids.length === 0) return []\n where.id = { in: ids }\n }\n if (query.names !== undefined) {\n if (query.names.length === 0) return []\n where.name = { in: unique(query.names) }\n }\n if (query.guardName !== undefined) where.guardName = query.guardName\n\n const rows = await this.#db.rbacPermission.findMany({ where, orderBy: { id: 'asc' } })\n return rows.map(toPermission)\n }\n\n async deletePermission(id: Id): Promise<void> {\n const permissionId = toIntId(id)\n if (permissionId === undefined) return\n await this.#db.$transaction([\n this.#db.rbacRoleHasPermission.deleteMany({ where: { permissionId } }),\n this.#db.rbacModelHasPermission.deleteMany({ where: { permissionId } }),\n this.#db.rbacPermission.deleteMany({ where: { id: permissionId } }),\n ])\n }\n\n // ---------------------------------------------------------------------- roles\n\n async createRole(data: { name: string; guardName: string; teamId: TeamId }): Promise<Role> {\n const row = await this.#db.rbacRole.create({\n data: { name: data.name, guardName: data.guardName, teamId: teamKey(data.teamId) },\n })\n return toRole(row)\n }\n\n async findRoles(query: FindRolesQuery = {}): Promise<Role[]> {\n const where: { id?: IntFilter; name?: StringFilter; guardName?: string; teamId?: StringFilter } = {}\n if (query.ids !== undefined) {\n const ids = toIntIds(query.ids)\n if (ids.length === 0) return []\n where.id = { in: ids }\n }\n if (query.names !== undefined) {\n if (query.names.length === 0) return []\n where.name = { in: unique(query.names) }\n }\n if (query.guardName !== undefined) where.guardName = query.guardName\n if (query.teamIds !== undefined) {\n if (query.teamIds.length === 0) return []\n where.teamId = { in: unique(query.teamIds.map(teamKey)) }\n }\n\n const rows = await this.#db.rbacRole.findMany({ where, orderBy: { id: 'asc' } })\n return rows.map(toRole)\n }\n\n async deleteRole(id: Id): Promise<void> {\n const roleId = toIntId(id)\n if (roleId === undefined) return\n await this.#db.$transaction([\n this.#db.rbacRoleHasPermission.deleteMany({ where: { roleId } }),\n this.#db.rbacModelHasRole.deleteMany({ where: { roleId } }),\n this.#db.rbacRole.deleteMany({ where: { id: roleId } }),\n ])\n }\n\n // ---------------------------------------------------------- role ↔ permission\n\n async getRolePermissionLinks(roleIds: readonly Id[]): Promise<RolePermissionLink[]> {\n const ids = toIntIds(roleIds)\n if (ids.length === 0) return []\n const rows = await this.#db.rbacRoleHasPermission.findMany({ where: { roleId: { in: ids } } })\n return rows.map((r) => ({ roleId: r.roleId, permissionId: r.permissionId }))\n }\n\n async attachRolePermissions(roleId: Id, permissionIds: readonly Id[]): Promise<void> {\n const [role] = requireIntIds([roleId], 'role')\n const ids = requireIntIds(permissionIds, 'permission')\n if (role === undefined || ids.length === 0) return\n const delegate = this.#db.rbacRoleHasPermission\n await this.#insertMissing(\n ids,\n async () => (await delegate.findMany({ where: { roleId: role, permissionId: { in: ids } } })).map((r) => r.permissionId),\n (data) => delegate.createMany({ data: data.map((permissionId) => ({ roleId: role, permissionId })), ...this.#skip() }),\n )\n }\n\n async detachRolePermissions(roleId: Id, permissionIds?: readonly Id[]): Promise<void> {\n const role = toIntId(roleId)\n if (role === undefined) return\n if (permissionIds === undefined) {\n await this.#db.rbacRoleHasPermission.deleteMany({ where: { roleId: role } })\n return\n }\n const ids = toIntIds(permissionIds)\n if (ids.length === 0) return\n await this.#db.rbacRoleHasPermission.deleteMany({ where: { roleId: role, permissionId: { in: ids } } })\n }\n\n // ------------------------------------------------------------- subject ↔ role\n\n async getSubjectRoleIds(subject: Subject, teamId: TeamId): Promise<Id[]> {\n const rows = await this.#db.rbacModelHasRole.findMany({ where: this.#subjectWhere(subject, teamId) })\n return rows.map((r) => r.roleId)\n }\n\n async attachSubjectRoles(subject: Subject, roleIds: readonly Id[], teamId: TeamId): Promise<void> {\n const ids = requireIntIds(roleIds, 'role')\n if (ids.length === 0) return\n const base = this.#subjectWhere(subject, teamId)\n const delegate = this.#db.rbacModelHasRole\n await this.#insertMissing(\n ids,\n async () => (await delegate.findMany({ where: { ...base, roleId: { in: ids } } })).map((r) => r.roleId),\n (data) => delegate.createMany({ data: data.map((roleId) => ({ ...base, roleId })), ...this.#skip() }),\n )\n }\n\n async detachSubjectRoles(subject: Subject, roleIds: readonly Id[] | undefined, teamId: TeamId): Promise<void> {\n const base = this.#subjectWhere(subject, teamId)\n if (roleIds === undefined) {\n await this.#db.rbacModelHasRole.deleteMany({ where: base })\n return\n }\n const ids = toIntIds(roleIds)\n if (ids.length === 0) return\n await this.#db.rbacModelHasRole.deleteMany({ where: { ...base, roleId: { in: ids } } })\n }\n\n // ------------------------------------------------------- subject ↔ permission\n\n async getSubjectPermissionIds(subject: Subject, teamId: TeamId): Promise<Id[]> {\n const rows = await this.#db.rbacModelHasPermission.findMany({ where: this.#subjectWhere(subject, teamId) })\n return rows.map((r) => r.permissionId)\n }\n\n async attachSubjectPermissions(subject: Subject, permissionIds: readonly Id[], teamId: TeamId): Promise<void> {\n const ids = requireIntIds(permissionIds, 'permission')\n if (ids.length === 0) return\n const base = this.#subjectWhere(subject, teamId)\n const delegate = this.#db.rbacModelHasPermission\n await this.#insertMissing(\n ids,\n async () =>\n (await delegate.findMany({ where: { ...base, permissionId: { in: ids } } })).map((r) => r.permissionId),\n (data) => delegate.createMany({ data: data.map((permissionId) => ({ ...base, permissionId })), ...this.#skip() }),\n )\n }\n\n async detachSubjectPermissions(\n subject: Subject,\n permissionIds: readonly Id[] | undefined,\n teamId: TeamId,\n ): Promise<void> {\n const base = this.#subjectWhere(subject, teamId)\n if (permissionIds === undefined) {\n await this.#db.rbacModelHasPermission.deleteMany({ where: base })\n return\n }\n const ids = toIntIds(permissionIds)\n if (ids.length === 0) return\n await this.#db.rbacModelHasPermission.deleteMany({ where: { ...base, permissionId: { in: ids } } })\n }\n\n // ------------------------------------------------------------ reverse lookups\n\n async getSubjectIdsWithRoles(subjectType: string, roleIds: readonly Id[], teamId: TeamId): Promise<Id[]> {\n const ids = toIntIds(roleIds)\n if (ids.length === 0) return []\n const rows = await this.#db.rbacModelHasRole.findMany({\n where: { subjectType, teamId: teamKey(teamId), roleId: { in: ids } },\n })\n return unique(rows.map((r) => r.subjectId))\n }\n\n async getSubjectIdsWithPermissions(subjectType: string, permissionIds: readonly Id[], teamId: TeamId): Promise<Id[]> {\n const ids = toIntIds(permissionIds)\n if (ids.length === 0) return []\n const rows = await this.#db.rbacModelHasPermission.findMany({\n where: { subjectType, teamId: teamKey(teamId), permissionId: { in: ids } },\n })\n return unique(rows.map((r) => r.subjectId))\n }\n\n // -------------------------------------------------------------------- helpers\n\n #subjectWhere(subject: Subject, teamId: TeamId): { subjectType: string; subjectId: string; teamId: string } {\n return { subjectType: subject.type, subjectId: subjectKey(subject), teamId: teamKey(teamId) }\n }\n\n #skip(): { skipDuplicates?: boolean } {\n return this.#skipDuplicates ? { skipDuplicates: true } : {}\n }\n\n /**\n * Idempotent insert. With `skipDuplicates` it is a single `createMany`; otherwise the existing\n * links are read first and only the missing ones inserted. A concurrent insert of the same link\n * (unique violation P2002) is retried once, re-reading what now exists.\n */\n async #insertMissing(\n ids: number[],\n existing: () => Promise<number[]>,\n insert: (ids: number[]) => PromiseLike<BatchPayload>,\n ): Promise<void> {\n if (this.#skipDuplicates) {\n await insert(ids)\n return\n }\n for (let attempt = 0; ; attempt++) {\n const have = new Set(await existing())\n const missing = ids.filter((id) => !have.has(id))\n if (missing.length === 0) return\n try {\n await insert(missing)\n return\n } catch (error) {\n if (attempt >= 2 || !isUniqueViolation(error)) throw error\n }\n }\n }\n}\n"]}
|
package/dist/index.d.cts
ADDED
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
import { RbacAdapter, Permission, FindPermissionsQuery, Id, TeamId, Role, FindRolesQuery, RolePermissionLink, Subject } from '@anievo-id/rbac-evolution';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* @anievo-id/rbac-evolution-prisma
|
|
5
|
+
*
|
|
6
|
+
* Prisma storage adapter for rbac-evolution. Copy the models from `schema/rbac.prisma`
|
|
7
|
+
* into your schema, run `prisma generate`, then:
|
|
8
|
+
*
|
|
9
|
+
* ```ts
|
|
10
|
+
* import { createRbac } from '@anievo-id/rbac-evolution'
|
|
11
|
+
* import { PrismaAdapter } from '@anievo-id/rbac-evolution-prisma'
|
|
12
|
+
*
|
|
13
|
+
* const rbac = createRbac({ adapter: new PrismaAdapter(prisma) })
|
|
14
|
+
* ```
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
type IntFilter = number | {
|
|
18
|
+
in: number[];
|
|
19
|
+
};
|
|
20
|
+
type StringFilter = string | {
|
|
21
|
+
in: string[];
|
|
22
|
+
};
|
|
23
|
+
interface PrismaRbacPermissionRow {
|
|
24
|
+
id: number;
|
|
25
|
+
name: string;
|
|
26
|
+
guardName: string;
|
|
27
|
+
}
|
|
28
|
+
interface PrismaRbacRoleRow {
|
|
29
|
+
id: number;
|
|
30
|
+
name: string;
|
|
31
|
+
guardName: string;
|
|
32
|
+
teamId: string;
|
|
33
|
+
}
|
|
34
|
+
interface PrismaRbacRoleHasPermissionRow {
|
|
35
|
+
roleId: number;
|
|
36
|
+
permissionId: number;
|
|
37
|
+
}
|
|
38
|
+
interface PrismaRbacModelHasRoleRow {
|
|
39
|
+
roleId: number;
|
|
40
|
+
subjectType: string;
|
|
41
|
+
subjectId: string;
|
|
42
|
+
teamId: string;
|
|
43
|
+
}
|
|
44
|
+
interface PrismaRbacModelHasPermissionRow {
|
|
45
|
+
permissionId: number;
|
|
46
|
+
subjectType: string;
|
|
47
|
+
subjectId: string;
|
|
48
|
+
teamId: string;
|
|
49
|
+
}
|
|
50
|
+
interface BatchPayload {
|
|
51
|
+
count: number;
|
|
52
|
+
}
|
|
53
|
+
/** Generic subset of a Prisma model delegate used by the adapter. */
|
|
54
|
+
interface PrismaRbacDelegate<Row, Where, Create, OrderBy = never> {
|
|
55
|
+
findMany(args: {
|
|
56
|
+
where?: Where;
|
|
57
|
+
orderBy?: OrderBy;
|
|
58
|
+
}): PromiseLike<Row[]>;
|
|
59
|
+
create(args: {
|
|
60
|
+
data: Create;
|
|
61
|
+
}): PromiseLike<Row>;
|
|
62
|
+
/** `skipDuplicates` is passed only when enabled (SQLite clients type it as `never`). */
|
|
63
|
+
createMany(args: {
|
|
64
|
+
data: Create[];
|
|
65
|
+
}): PromiseLike<BatchPayload>;
|
|
66
|
+
deleteMany(args: {
|
|
67
|
+
where: Where;
|
|
68
|
+
}): PromiseLike<BatchPayload>;
|
|
69
|
+
}
|
|
70
|
+
type PrismaRbacPermissionDelegate = PrismaRbacDelegate<PrismaRbacPermissionRow, {
|
|
71
|
+
id?: IntFilter;
|
|
72
|
+
name?: StringFilter;
|
|
73
|
+
guardName?: string;
|
|
74
|
+
}, {
|
|
75
|
+
name: string;
|
|
76
|
+
guardName: string;
|
|
77
|
+
}, {
|
|
78
|
+
id: 'asc';
|
|
79
|
+
}>;
|
|
80
|
+
type PrismaRbacRoleDelegate = PrismaRbacDelegate<PrismaRbacRoleRow, {
|
|
81
|
+
id?: IntFilter;
|
|
82
|
+
name?: StringFilter;
|
|
83
|
+
guardName?: string;
|
|
84
|
+
teamId?: StringFilter;
|
|
85
|
+
}, {
|
|
86
|
+
name: string;
|
|
87
|
+
guardName: string;
|
|
88
|
+
teamId: string;
|
|
89
|
+
}, {
|
|
90
|
+
id: 'asc';
|
|
91
|
+
}>;
|
|
92
|
+
type PrismaRbacRoleHasPermissionDelegate = PrismaRbacDelegate<PrismaRbacRoleHasPermissionRow, {
|
|
93
|
+
roleId?: IntFilter;
|
|
94
|
+
permissionId?: IntFilter;
|
|
95
|
+
}, PrismaRbacRoleHasPermissionRow>;
|
|
96
|
+
type PrismaRbacModelHasRoleDelegate = PrismaRbacDelegate<PrismaRbacModelHasRoleRow, {
|
|
97
|
+
roleId?: IntFilter;
|
|
98
|
+
subjectType?: string;
|
|
99
|
+
subjectId?: string;
|
|
100
|
+
teamId?: string;
|
|
101
|
+
}, PrismaRbacModelHasRoleRow>;
|
|
102
|
+
type PrismaRbacModelHasPermissionDelegate = PrismaRbacDelegate<PrismaRbacModelHasPermissionRow, {
|
|
103
|
+
permissionId?: IntFilter;
|
|
104
|
+
subjectType?: string;
|
|
105
|
+
subjectId?: string;
|
|
106
|
+
teamId?: string;
|
|
107
|
+
}, PrismaRbacModelHasPermissionRow>;
|
|
108
|
+
/** The part of a `PrismaClient` (with the rbac models) that the adapter needs. */
|
|
109
|
+
interface PrismaRbacClient {
|
|
110
|
+
rbacPermission: PrismaRbacPermissionDelegate;
|
|
111
|
+
rbacRole: PrismaRbacRoleDelegate;
|
|
112
|
+
rbacRoleHasPermission: PrismaRbacRoleHasPermissionDelegate;
|
|
113
|
+
rbacModelHasRole: PrismaRbacModelHasRoleDelegate;
|
|
114
|
+
rbacModelHasPermission: PrismaRbacModelHasPermissionDelegate;
|
|
115
|
+
$transaction(queries: PromiseLike<unknown>[]): PromiseLike<unknown>;
|
|
116
|
+
}
|
|
117
|
+
interface PrismaAdapterOptions {
|
|
118
|
+
/**
|
|
119
|
+
* Use `createMany({ skipDuplicates: true })` for attach operations (one query, race-free).
|
|
120
|
+
* Supported by PostgreSQL, MySQL/MariaDB and CockroachDB — NOT by SQLite, SQL Server or MongoDB.
|
|
121
|
+
* Default: `false` (portable: reads existing links first, inserts only the missing ones).
|
|
122
|
+
*/
|
|
123
|
+
skipDuplicates?: boolean;
|
|
124
|
+
}
|
|
125
|
+
/**
|
|
126
|
+
* `RbacAdapter` backed by Prisma. Requires the models from `schema/rbac.prisma`.
|
|
127
|
+
*
|
|
128
|
+
* - Role / permission ids are returned as numbers (numeric strings are accepted as input).
|
|
129
|
+
* - Subject ids are stored as text; reverse lookups return them as strings.
|
|
130
|
+
* - `Role.teamId` is `null` for global roles, otherwise the team id as a string.
|
|
131
|
+
*/
|
|
132
|
+
declare class PrismaAdapter implements RbacAdapter {
|
|
133
|
+
#private;
|
|
134
|
+
constructor(prisma: PrismaRbacClient, options?: PrismaAdapterOptions);
|
|
135
|
+
createPermission(data: {
|
|
136
|
+
name: string;
|
|
137
|
+
guardName: string;
|
|
138
|
+
}): Promise<Permission>;
|
|
139
|
+
findPermissions(query?: FindPermissionsQuery): Promise<Permission[]>;
|
|
140
|
+
deletePermission(id: Id): Promise<void>;
|
|
141
|
+
createRole(data: {
|
|
142
|
+
name: string;
|
|
143
|
+
guardName: string;
|
|
144
|
+
teamId: TeamId;
|
|
145
|
+
}): Promise<Role>;
|
|
146
|
+
findRoles(query?: FindRolesQuery): Promise<Role[]>;
|
|
147
|
+
deleteRole(id: Id): Promise<void>;
|
|
148
|
+
getRolePermissionLinks(roleIds: readonly Id[]): Promise<RolePermissionLink[]>;
|
|
149
|
+
attachRolePermissions(roleId: Id, permissionIds: readonly Id[]): Promise<void>;
|
|
150
|
+
detachRolePermissions(roleId: Id, permissionIds?: readonly Id[]): Promise<void>;
|
|
151
|
+
getSubjectRoleIds(subject: Subject, teamId: TeamId): Promise<Id[]>;
|
|
152
|
+
attachSubjectRoles(subject: Subject, roleIds: readonly Id[], teamId: TeamId): Promise<void>;
|
|
153
|
+
detachSubjectRoles(subject: Subject, roleIds: readonly Id[] | undefined, teamId: TeamId): Promise<void>;
|
|
154
|
+
getSubjectPermissionIds(subject: Subject, teamId: TeamId): Promise<Id[]>;
|
|
155
|
+
attachSubjectPermissions(subject: Subject, permissionIds: readonly Id[], teamId: TeamId): Promise<void>;
|
|
156
|
+
detachSubjectPermissions(subject: Subject, permissionIds: readonly Id[] | undefined, teamId: TeamId): Promise<void>;
|
|
157
|
+
getSubjectIdsWithRoles(subjectType: string, roleIds: readonly Id[], teamId: TeamId): Promise<Id[]>;
|
|
158
|
+
getSubjectIdsWithPermissions(subjectType: string, permissionIds: readonly Id[], teamId: TeamId): Promise<Id[]>;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
export { PrismaAdapter, type PrismaAdapterOptions, type PrismaRbacClient, type PrismaRbacDelegate, type PrismaRbacModelHasPermissionDelegate, type PrismaRbacModelHasPermissionRow, type PrismaRbacModelHasRoleDelegate, type PrismaRbacModelHasRoleRow, type PrismaRbacPermissionDelegate, type PrismaRbacPermissionRow, type PrismaRbacRoleDelegate, type PrismaRbacRoleHasPermissionDelegate, type PrismaRbacRoleHasPermissionRow, type PrismaRbacRoleRow };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
import { RbacAdapter, Permission, FindPermissionsQuery, Id, TeamId, Role, FindRolesQuery, RolePermissionLink, Subject } from '@anievo-id/rbac-evolution';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* @anievo-id/rbac-evolution-prisma
|
|
5
|
+
*
|
|
6
|
+
* Prisma storage adapter for rbac-evolution. Copy the models from `schema/rbac.prisma`
|
|
7
|
+
* into your schema, run `prisma generate`, then:
|
|
8
|
+
*
|
|
9
|
+
* ```ts
|
|
10
|
+
* import { createRbac } from '@anievo-id/rbac-evolution'
|
|
11
|
+
* import { PrismaAdapter } from '@anievo-id/rbac-evolution-prisma'
|
|
12
|
+
*
|
|
13
|
+
* const rbac = createRbac({ adapter: new PrismaAdapter(prisma) })
|
|
14
|
+
* ```
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
type IntFilter = number | {
|
|
18
|
+
in: number[];
|
|
19
|
+
};
|
|
20
|
+
type StringFilter = string | {
|
|
21
|
+
in: string[];
|
|
22
|
+
};
|
|
23
|
+
interface PrismaRbacPermissionRow {
|
|
24
|
+
id: number;
|
|
25
|
+
name: string;
|
|
26
|
+
guardName: string;
|
|
27
|
+
}
|
|
28
|
+
interface PrismaRbacRoleRow {
|
|
29
|
+
id: number;
|
|
30
|
+
name: string;
|
|
31
|
+
guardName: string;
|
|
32
|
+
teamId: string;
|
|
33
|
+
}
|
|
34
|
+
interface PrismaRbacRoleHasPermissionRow {
|
|
35
|
+
roleId: number;
|
|
36
|
+
permissionId: number;
|
|
37
|
+
}
|
|
38
|
+
interface PrismaRbacModelHasRoleRow {
|
|
39
|
+
roleId: number;
|
|
40
|
+
subjectType: string;
|
|
41
|
+
subjectId: string;
|
|
42
|
+
teamId: string;
|
|
43
|
+
}
|
|
44
|
+
interface PrismaRbacModelHasPermissionRow {
|
|
45
|
+
permissionId: number;
|
|
46
|
+
subjectType: string;
|
|
47
|
+
subjectId: string;
|
|
48
|
+
teamId: string;
|
|
49
|
+
}
|
|
50
|
+
interface BatchPayload {
|
|
51
|
+
count: number;
|
|
52
|
+
}
|
|
53
|
+
/** Generic subset of a Prisma model delegate used by the adapter. */
|
|
54
|
+
interface PrismaRbacDelegate<Row, Where, Create, OrderBy = never> {
|
|
55
|
+
findMany(args: {
|
|
56
|
+
where?: Where;
|
|
57
|
+
orderBy?: OrderBy;
|
|
58
|
+
}): PromiseLike<Row[]>;
|
|
59
|
+
create(args: {
|
|
60
|
+
data: Create;
|
|
61
|
+
}): PromiseLike<Row>;
|
|
62
|
+
/** `skipDuplicates` is passed only when enabled (SQLite clients type it as `never`). */
|
|
63
|
+
createMany(args: {
|
|
64
|
+
data: Create[];
|
|
65
|
+
}): PromiseLike<BatchPayload>;
|
|
66
|
+
deleteMany(args: {
|
|
67
|
+
where: Where;
|
|
68
|
+
}): PromiseLike<BatchPayload>;
|
|
69
|
+
}
|
|
70
|
+
type PrismaRbacPermissionDelegate = PrismaRbacDelegate<PrismaRbacPermissionRow, {
|
|
71
|
+
id?: IntFilter;
|
|
72
|
+
name?: StringFilter;
|
|
73
|
+
guardName?: string;
|
|
74
|
+
}, {
|
|
75
|
+
name: string;
|
|
76
|
+
guardName: string;
|
|
77
|
+
}, {
|
|
78
|
+
id: 'asc';
|
|
79
|
+
}>;
|
|
80
|
+
type PrismaRbacRoleDelegate = PrismaRbacDelegate<PrismaRbacRoleRow, {
|
|
81
|
+
id?: IntFilter;
|
|
82
|
+
name?: StringFilter;
|
|
83
|
+
guardName?: string;
|
|
84
|
+
teamId?: StringFilter;
|
|
85
|
+
}, {
|
|
86
|
+
name: string;
|
|
87
|
+
guardName: string;
|
|
88
|
+
teamId: string;
|
|
89
|
+
}, {
|
|
90
|
+
id: 'asc';
|
|
91
|
+
}>;
|
|
92
|
+
type PrismaRbacRoleHasPermissionDelegate = PrismaRbacDelegate<PrismaRbacRoleHasPermissionRow, {
|
|
93
|
+
roleId?: IntFilter;
|
|
94
|
+
permissionId?: IntFilter;
|
|
95
|
+
}, PrismaRbacRoleHasPermissionRow>;
|
|
96
|
+
type PrismaRbacModelHasRoleDelegate = PrismaRbacDelegate<PrismaRbacModelHasRoleRow, {
|
|
97
|
+
roleId?: IntFilter;
|
|
98
|
+
subjectType?: string;
|
|
99
|
+
subjectId?: string;
|
|
100
|
+
teamId?: string;
|
|
101
|
+
}, PrismaRbacModelHasRoleRow>;
|
|
102
|
+
type PrismaRbacModelHasPermissionDelegate = PrismaRbacDelegate<PrismaRbacModelHasPermissionRow, {
|
|
103
|
+
permissionId?: IntFilter;
|
|
104
|
+
subjectType?: string;
|
|
105
|
+
subjectId?: string;
|
|
106
|
+
teamId?: string;
|
|
107
|
+
}, PrismaRbacModelHasPermissionRow>;
|
|
108
|
+
/** The part of a `PrismaClient` (with the rbac models) that the adapter needs. */
|
|
109
|
+
interface PrismaRbacClient {
|
|
110
|
+
rbacPermission: PrismaRbacPermissionDelegate;
|
|
111
|
+
rbacRole: PrismaRbacRoleDelegate;
|
|
112
|
+
rbacRoleHasPermission: PrismaRbacRoleHasPermissionDelegate;
|
|
113
|
+
rbacModelHasRole: PrismaRbacModelHasRoleDelegate;
|
|
114
|
+
rbacModelHasPermission: PrismaRbacModelHasPermissionDelegate;
|
|
115
|
+
$transaction(queries: PromiseLike<unknown>[]): PromiseLike<unknown>;
|
|
116
|
+
}
|
|
117
|
+
interface PrismaAdapterOptions {
|
|
118
|
+
/**
|
|
119
|
+
* Use `createMany({ skipDuplicates: true })` for attach operations (one query, race-free).
|
|
120
|
+
* Supported by PostgreSQL, MySQL/MariaDB and CockroachDB — NOT by SQLite, SQL Server or MongoDB.
|
|
121
|
+
* Default: `false` (portable: reads existing links first, inserts only the missing ones).
|
|
122
|
+
*/
|
|
123
|
+
skipDuplicates?: boolean;
|
|
124
|
+
}
|
|
125
|
+
/**
|
|
126
|
+
* `RbacAdapter` backed by Prisma. Requires the models from `schema/rbac.prisma`.
|
|
127
|
+
*
|
|
128
|
+
* - Role / permission ids are returned as numbers (numeric strings are accepted as input).
|
|
129
|
+
* - Subject ids are stored as text; reverse lookups return them as strings.
|
|
130
|
+
* - `Role.teamId` is `null` for global roles, otherwise the team id as a string.
|
|
131
|
+
*/
|
|
132
|
+
declare class PrismaAdapter implements RbacAdapter {
|
|
133
|
+
#private;
|
|
134
|
+
constructor(prisma: PrismaRbacClient, options?: PrismaAdapterOptions);
|
|
135
|
+
createPermission(data: {
|
|
136
|
+
name: string;
|
|
137
|
+
guardName: string;
|
|
138
|
+
}): Promise<Permission>;
|
|
139
|
+
findPermissions(query?: FindPermissionsQuery): Promise<Permission[]>;
|
|
140
|
+
deletePermission(id: Id): Promise<void>;
|
|
141
|
+
createRole(data: {
|
|
142
|
+
name: string;
|
|
143
|
+
guardName: string;
|
|
144
|
+
teamId: TeamId;
|
|
145
|
+
}): Promise<Role>;
|
|
146
|
+
findRoles(query?: FindRolesQuery): Promise<Role[]>;
|
|
147
|
+
deleteRole(id: Id): Promise<void>;
|
|
148
|
+
getRolePermissionLinks(roleIds: readonly Id[]): Promise<RolePermissionLink[]>;
|
|
149
|
+
attachRolePermissions(roleId: Id, permissionIds: readonly Id[]): Promise<void>;
|
|
150
|
+
detachRolePermissions(roleId: Id, permissionIds?: readonly Id[]): Promise<void>;
|
|
151
|
+
getSubjectRoleIds(subject: Subject, teamId: TeamId): Promise<Id[]>;
|
|
152
|
+
attachSubjectRoles(subject: Subject, roleIds: readonly Id[], teamId: TeamId): Promise<void>;
|
|
153
|
+
detachSubjectRoles(subject: Subject, roleIds: readonly Id[] | undefined, teamId: TeamId): Promise<void>;
|
|
154
|
+
getSubjectPermissionIds(subject: Subject, teamId: TeamId): Promise<Id[]>;
|
|
155
|
+
attachSubjectPermissions(subject: Subject, permissionIds: readonly Id[], teamId: TeamId): Promise<void>;
|
|
156
|
+
detachSubjectPermissions(subject: Subject, permissionIds: readonly Id[] | undefined, teamId: TeamId): Promise<void>;
|
|
157
|
+
getSubjectIdsWithRoles(subjectType: string, roleIds: readonly Id[], teamId: TeamId): Promise<Id[]>;
|
|
158
|
+
getSubjectIdsWithPermissions(subjectType: string, permissionIds: readonly Id[], teamId: TeamId): Promise<Id[]>;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
export { PrismaAdapter, type PrismaAdapterOptions, type PrismaRbacClient, type PrismaRbacDelegate, type PrismaRbacModelHasPermissionDelegate, type PrismaRbacModelHasPermissionRow, type PrismaRbacModelHasRoleDelegate, type PrismaRbacModelHasRoleRow, type PrismaRbacPermissionDelegate, type PrismaRbacPermissionRow, type PrismaRbacRoleDelegate, type PrismaRbacRoleHasPermissionDelegate, type PrismaRbacRoleHasPermissionRow, type PrismaRbacRoleRow };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,244 @@
|
|
|
1
|
+
// src/index.ts
|
|
2
|
+
var GLOBAL_TEAM = "";
|
|
3
|
+
var teamKey = (teamId) => teamId === null ? GLOBAL_TEAM : String(teamId);
|
|
4
|
+
var teamFromKey = (key) => key === GLOBAL_TEAM ? null : key;
|
|
5
|
+
var subjectKey = (subject) => String(subject.id);
|
|
6
|
+
var toIntId = (id) => {
|
|
7
|
+
if (typeof id === "number") return Number.isSafeInteger(id) ? id : void 0;
|
|
8
|
+
if (!/^-?\d+$/.test(id.trim())) return void 0;
|
|
9
|
+
const n = Number(id);
|
|
10
|
+
return Number.isSafeInteger(n) ? n : void 0;
|
|
11
|
+
};
|
|
12
|
+
var toIntIds = (ids) => {
|
|
13
|
+
const out = /* @__PURE__ */ new Set();
|
|
14
|
+
for (const id of ids) {
|
|
15
|
+
const n = toIntId(id);
|
|
16
|
+
if (n !== void 0) out.add(n);
|
|
17
|
+
}
|
|
18
|
+
return [...out];
|
|
19
|
+
};
|
|
20
|
+
var requireIntIds = (ids, what) => {
|
|
21
|
+
const out = /* @__PURE__ */ new Set();
|
|
22
|
+
for (const id of ids) {
|
|
23
|
+
const n = toIntId(id);
|
|
24
|
+
if (n === void 0) throw new TypeError(`PrismaAdapter: invalid ${what} id ${JSON.stringify(id)} (expected an integer).`);
|
|
25
|
+
out.add(n);
|
|
26
|
+
}
|
|
27
|
+
return [...out];
|
|
28
|
+
};
|
|
29
|
+
var isUniqueViolation = (error) => typeof error === "object" && error !== null && error.code === "P2002";
|
|
30
|
+
var toPermission = (row) => ({
|
|
31
|
+
id: row.id,
|
|
32
|
+
name: row.name,
|
|
33
|
+
guardName: row.guardName
|
|
34
|
+
});
|
|
35
|
+
var toRole = (row) => ({
|
|
36
|
+
id: row.id,
|
|
37
|
+
name: row.name,
|
|
38
|
+
guardName: row.guardName,
|
|
39
|
+
teamId: teamFromKey(row.teamId)
|
|
40
|
+
});
|
|
41
|
+
var unique = (values) => [...new Set(values)];
|
|
42
|
+
var PrismaAdapter = class {
|
|
43
|
+
#db;
|
|
44
|
+
#skipDuplicates;
|
|
45
|
+
constructor(prisma, options = {}) {
|
|
46
|
+
this.#db = prisma;
|
|
47
|
+
this.#skipDuplicates = options.skipDuplicates ?? false;
|
|
48
|
+
}
|
|
49
|
+
// ---------------------------------------------------------------- permissions
|
|
50
|
+
async createPermission(data) {
|
|
51
|
+
const row = await this.#db.rbacPermission.create({ data: { name: data.name, guardName: data.guardName } });
|
|
52
|
+
return toPermission(row);
|
|
53
|
+
}
|
|
54
|
+
async findPermissions(query = {}) {
|
|
55
|
+
const where = {};
|
|
56
|
+
if (query.ids !== void 0) {
|
|
57
|
+
const ids = toIntIds(query.ids);
|
|
58
|
+
if (ids.length === 0) return [];
|
|
59
|
+
where.id = { in: ids };
|
|
60
|
+
}
|
|
61
|
+
if (query.names !== void 0) {
|
|
62
|
+
if (query.names.length === 0) return [];
|
|
63
|
+
where.name = { in: unique(query.names) };
|
|
64
|
+
}
|
|
65
|
+
if (query.guardName !== void 0) where.guardName = query.guardName;
|
|
66
|
+
const rows = await this.#db.rbacPermission.findMany({ where, orderBy: { id: "asc" } });
|
|
67
|
+
return rows.map(toPermission);
|
|
68
|
+
}
|
|
69
|
+
async deletePermission(id) {
|
|
70
|
+
const permissionId = toIntId(id);
|
|
71
|
+
if (permissionId === void 0) return;
|
|
72
|
+
await this.#db.$transaction([
|
|
73
|
+
this.#db.rbacRoleHasPermission.deleteMany({ where: { permissionId } }),
|
|
74
|
+
this.#db.rbacModelHasPermission.deleteMany({ where: { permissionId } }),
|
|
75
|
+
this.#db.rbacPermission.deleteMany({ where: { id: permissionId } })
|
|
76
|
+
]);
|
|
77
|
+
}
|
|
78
|
+
// ---------------------------------------------------------------------- roles
|
|
79
|
+
async createRole(data) {
|
|
80
|
+
const row = await this.#db.rbacRole.create({
|
|
81
|
+
data: { name: data.name, guardName: data.guardName, teamId: teamKey(data.teamId) }
|
|
82
|
+
});
|
|
83
|
+
return toRole(row);
|
|
84
|
+
}
|
|
85
|
+
async findRoles(query = {}) {
|
|
86
|
+
const where = {};
|
|
87
|
+
if (query.ids !== void 0) {
|
|
88
|
+
const ids = toIntIds(query.ids);
|
|
89
|
+
if (ids.length === 0) return [];
|
|
90
|
+
where.id = { in: ids };
|
|
91
|
+
}
|
|
92
|
+
if (query.names !== void 0) {
|
|
93
|
+
if (query.names.length === 0) return [];
|
|
94
|
+
where.name = { in: unique(query.names) };
|
|
95
|
+
}
|
|
96
|
+
if (query.guardName !== void 0) where.guardName = query.guardName;
|
|
97
|
+
if (query.teamIds !== void 0) {
|
|
98
|
+
if (query.teamIds.length === 0) return [];
|
|
99
|
+
where.teamId = { in: unique(query.teamIds.map(teamKey)) };
|
|
100
|
+
}
|
|
101
|
+
const rows = await this.#db.rbacRole.findMany({ where, orderBy: { id: "asc" } });
|
|
102
|
+
return rows.map(toRole);
|
|
103
|
+
}
|
|
104
|
+
async deleteRole(id) {
|
|
105
|
+
const roleId = toIntId(id);
|
|
106
|
+
if (roleId === void 0) return;
|
|
107
|
+
await this.#db.$transaction([
|
|
108
|
+
this.#db.rbacRoleHasPermission.deleteMany({ where: { roleId } }),
|
|
109
|
+
this.#db.rbacModelHasRole.deleteMany({ where: { roleId } }),
|
|
110
|
+
this.#db.rbacRole.deleteMany({ where: { id: roleId } })
|
|
111
|
+
]);
|
|
112
|
+
}
|
|
113
|
+
// ---------------------------------------------------------- role ↔ permission
|
|
114
|
+
async getRolePermissionLinks(roleIds) {
|
|
115
|
+
const ids = toIntIds(roleIds);
|
|
116
|
+
if (ids.length === 0) return [];
|
|
117
|
+
const rows = await this.#db.rbacRoleHasPermission.findMany({ where: { roleId: { in: ids } } });
|
|
118
|
+
return rows.map((r) => ({ roleId: r.roleId, permissionId: r.permissionId }));
|
|
119
|
+
}
|
|
120
|
+
async attachRolePermissions(roleId, permissionIds) {
|
|
121
|
+
const [role] = requireIntIds([roleId], "role");
|
|
122
|
+
const ids = requireIntIds(permissionIds, "permission");
|
|
123
|
+
if (role === void 0 || ids.length === 0) return;
|
|
124
|
+
const delegate = this.#db.rbacRoleHasPermission;
|
|
125
|
+
await this.#insertMissing(
|
|
126
|
+
ids,
|
|
127
|
+
async () => (await delegate.findMany({ where: { roleId: role, permissionId: { in: ids } } })).map((r) => r.permissionId),
|
|
128
|
+
(data) => delegate.createMany({ data: data.map((permissionId) => ({ roleId: role, permissionId })), ...this.#skip() })
|
|
129
|
+
);
|
|
130
|
+
}
|
|
131
|
+
async detachRolePermissions(roleId, permissionIds) {
|
|
132
|
+
const role = toIntId(roleId);
|
|
133
|
+
if (role === void 0) return;
|
|
134
|
+
if (permissionIds === void 0) {
|
|
135
|
+
await this.#db.rbacRoleHasPermission.deleteMany({ where: { roleId: role } });
|
|
136
|
+
return;
|
|
137
|
+
}
|
|
138
|
+
const ids = toIntIds(permissionIds);
|
|
139
|
+
if (ids.length === 0) return;
|
|
140
|
+
await this.#db.rbacRoleHasPermission.deleteMany({ where: { roleId: role, permissionId: { in: ids } } });
|
|
141
|
+
}
|
|
142
|
+
// ------------------------------------------------------------- subject ↔ role
|
|
143
|
+
async getSubjectRoleIds(subject, teamId) {
|
|
144
|
+
const rows = await this.#db.rbacModelHasRole.findMany({ where: this.#subjectWhere(subject, teamId) });
|
|
145
|
+
return rows.map((r) => r.roleId);
|
|
146
|
+
}
|
|
147
|
+
async attachSubjectRoles(subject, roleIds, teamId) {
|
|
148
|
+
const ids = requireIntIds(roleIds, "role");
|
|
149
|
+
if (ids.length === 0) return;
|
|
150
|
+
const base = this.#subjectWhere(subject, teamId);
|
|
151
|
+
const delegate = this.#db.rbacModelHasRole;
|
|
152
|
+
await this.#insertMissing(
|
|
153
|
+
ids,
|
|
154
|
+
async () => (await delegate.findMany({ where: { ...base, roleId: { in: ids } } })).map((r) => r.roleId),
|
|
155
|
+
(data) => delegate.createMany({ data: data.map((roleId) => ({ ...base, roleId })), ...this.#skip() })
|
|
156
|
+
);
|
|
157
|
+
}
|
|
158
|
+
async detachSubjectRoles(subject, roleIds, teamId) {
|
|
159
|
+
const base = this.#subjectWhere(subject, teamId);
|
|
160
|
+
if (roleIds === void 0) {
|
|
161
|
+
await this.#db.rbacModelHasRole.deleteMany({ where: base });
|
|
162
|
+
return;
|
|
163
|
+
}
|
|
164
|
+
const ids = toIntIds(roleIds);
|
|
165
|
+
if (ids.length === 0) return;
|
|
166
|
+
await this.#db.rbacModelHasRole.deleteMany({ where: { ...base, roleId: { in: ids } } });
|
|
167
|
+
}
|
|
168
|
+
// ------------------------------------------------------- subject ↔ permission
|
|
169
|
+
async getSubjectPermissionIds(subject, teamId) {
|
|
170
|
+
const rows = await this.#db.rbacModelHasPermission.findMany({ where: this.#subjectWhere(subject, teamId) });
|
|
171
|
+
return rows.map((r) => r.permissionId);
|
|
172
|
+
}
|
|
173
|
+
async attachSubjectPermissions(subject, permissionIds, teamId) {
|
|
174
|
+
const ids = requireIntIds(permissionIds, "permission");
|
|
175
|
+
if (ids.length === 0) return;
|
|
176
|
+
const base = this.#subjectWhere(subject, teamId);
|
|
177
|
+
const delegate = this.#db.rbacModelHasPermission;
|
|
178
|
+
await this.#insertMissing(
|
|
179
|
+
ids,
|
|
180
|
+
async () => (await delegate.findMany({ where: { ...base, permissionId: { in: ids } } })).map((r) => r.permissionId),
|
|
181
|
+
(data) => delegate.createMany({ data: data.map((permissionId) => ({ ...base, permissionId })), ...this.#skip() })
|
|
182
|
+
);
|
|
183
|
+
}
|
|
184
|
+
async detachSubjectPermissions(subject, permissionIds, teamId) {
|
|
185
|
+
const base = this.#subjectWhere(subject, teamId);
|
|
186
|
+
if (permissionIds === void 0) {
|
|
187
|
+
await this.#db.rbacModelHasPermission.deleteMany({ where: base });
|
|
188
|
+
return;
|
|
189
|
+
}
|
|
190
|
+
const ids = toIntIds(permissionIds);
|
|
191
|
+
if (ids.length === 0) return;
|
|
192
|
+
await this.#db.rbacModelHasPermission.deleteMany({ where: { ...base, permissionId: { in: ids } } });
|
|
193
|
+
}
|
|
194
|
+
// ------------------------------------------------------------ reverse lookups
|
|
195
|
+
async getSubjectIdsWithRoles(subjectType, roleIds, teamId) {
|
|
196
|
+
const ids = toIntIds(roleIds);
|
|
197
|
+
if (ids.length === 0) return [];
|
|
198
|
+
const rows = await this.#db.rbacModelHasRole.findMany({
|
|
199
|
+
where: { subjectType, teamId: teamKey(teamId), roleId: { in: ids } }
|
|
200
|
+
});
|
|
201
|
+
return unique(rows.map((r) => r.subjectId));
|
|
202
|
+
}
|
|
203
|
+
async getSubjectIdsWithPermissions(subjectType, permissionIds, teamId) {
|
|
204
|
+
const ids = toIntIds(permissionIds);
|
|
205
|
+
if (ids.length === 0) return [];
|
|
206
|
+
const rows = await this.#db.rbacModelHasPermission.findMany({
|
|
207
|
+
where: { subjectType, teamId: teamKey(teamId), permissionId: { in: ids } }
|
|
208
|
+
});
|
|
209
|
+
return unique(rows.map((r) => r.subjectId));
|
|
210
|
+
}
|
|
211
|
+
// -------------------------------------------------------------------- helpers
|
|
212
|
+
#subjectWhere(subject, teamId) {
|
|
213
|
+
return { subjectType: subject.type, subjectId: subjectKey(subject), teamId: teamKey(teamId) };
|
|
214
|
+
}
|
|
215
|
+
#skip() {
|
|
216
|
+
return this.#skipDuplicates ? { skipDuplicates: true } : {};
|
|
217
|
+
}
|
|
218
|
+
/**
|
|
219
|
+
* Idempotent insert. With `skipDuplicates` it is a single `createMany`; otherwise the existing
|
|
220
|
+
* links are read first and only the missing ones inserted. A concurrent insert of the same link
|
|
221
|
+
* (unique violation P2002) is retried once, re-reading what now exists.
|
|
222
|
+
*/
|
|
223
|
+
async #insertMissing(ids, existing, insert) {
|
|
224
|
+
if (this.#skipDuplicates) {
|
|
225
|
+
await insert(ids);
|
|
226
|
+
return;
|
|
227
|
+
}
|
|
228
|
+
for (let attempt = 0; ; attempt++) {
|
|
229
|
+
const have = new Set(await existing());
|
|
230
|
+
const missing = ids.filter((id) => !have.has(id));
|
|
231
|
+
if (missing.length === 0) return;
|
|
232
|
+
try {
|
|
233
|
+
await insert(missing);
|
|
234
|
+
return;
|
|
235
|
+
} catch (error) {
|
|
236
|
+
if (attempt >= 2 || !isUniqueViolation(error)) throw error;
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
};
|
|
241
|
+
|
|
242
|
+
export { PrismaAdapter };
|
|
243
|
+
//# sourceMappingURL=index.js.map
|
|
244
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"names":[],"mappings":";AAkIA,IAAM,WAAA,GAAc,EAAA;AAGpB,IAA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,EAAG,MAAA,EAAQ,OAAA,CAAQ,MAAM,CAAA,EAAE;AAAA,EAC9F;AAAA,EAEA,KAAA,GAAsC;AACpC,IAAA,OAAO,KAAK,eAAA,GAAkB,EAAE,cAAA,EAAgB,IAAA,KAAS,EAAC;AAAA,EAC5D;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,MAAM,cAAA,CACJ,GAAA,EACA,QAAA,EACA,MAAA,EACe;AACf,IAAA,IAAI,KAAK,eAAA,EAAiB;AACxB,MAAA,MAAM,OAAO,GAAG,CAAA;AAChB,MAAA;AAAA,IACF;AACA,IAAA,KAAA,IAAS,OAAA,GAAU,KAAK,OAAA,EAAA,EAAW;AACjC,MAAA,MAAM,IAAA,GAAO,IAAI,GAAA,CAAI,MAAM,UAAU,CAAA;AACrC,MAAA,MAAM,OAAA,GAAU,IAAI,MAAA,CAAO,CAAC,OAAO,CAAC,IAAA,CAAK,GAAA,CAAI,EAAE,CAAC,CAAA;AAChD,MAAA,IAAI,OAAA,CAAQ,WAAW,CAAA,EAAG;AAC1B,MAAA,IAAI;AACF,QAAA,MAAM,OAAO,OAAO,CAAA;AACpB,QAAA;AAAA,MACF,SAAS,KAAA,EAAO;AACd,QAAA,IAAI,WAAW,CAAA,IAAK,CAAC,iBAAA,CAAkB,KAAK,GAAG,MAAM,KAAA;AAAA,MACvD;AAAA,IACF;AAAA,EACF;AACF","file":"index.js","sourcesContent":["/**\n * @anievo-id/rbac-evolution-prisma\n *\n * Prisma storage adapter for rbac-evolution. Copy the models from `schema/rbac.prisma`\n * into your schema, run `prisma generate`, then:\n *\n * ```ts\n * import { createRbac } from '@anievo-id/rbac-evolution'\n * import { PrismaAdapter } from '@anievo-id/rbac-evolution-prisma'\n *\n * const rbac = createRbac({ adapter: new PrismaAdapter(prisma) })\n * ```\n */\nimport type {\n FindPermissionsQuery,\n FindRolesQuery,\n Id,\n Permission,\n RbacAdapter,\n Role,\n RolePermissionLink,\n Subject,\n TeamId,\n} from '@anievo-id/rbac-evolution'\n\n// ------------------------------------------------------------------ structural client types\n// Minimal shapes of the delegates generated from `schema/rbac.prisma`. They are structural so the\n// adapter works with any generated client (any output path, extra models, client extensions).\n\ntype IntFilter = number | { in: number[] }\ntype StringFilter = string | { in: string[] }\n\nexport interface PrismaRbacPermissionRow {\n id: number\n name: string\n guardName: string\n}\n\nexport interface PrismaRbacRoleRow {\n id: number\n name: string\n guardName: string\n teamId: string\n}\n\nexport interface PrismaRbacRoleHasPermissionRow {\n roleId: number\n permissionId: number\n}\n\nexport interface PrismaRbacModelHasRoleRow {\n roleId: number\n subjectType: string\n subjectId: string\n teamId: string\n}\n\nexport interface PrismaRbacModelHasPermissionRow {\n permissionId: number\n subjectType: string\n subjectId: string\n teamId: string\n}\n\ninterface BatchPayload {\n count: number\n}\n\n/** Generic subset of a Prisma model delegate used by the adapter. */\nexport interface PrismaRbacDelegate<Row, Where, Create, OrderBy = never> {\n findMany(args: { where?: Where; orderBy?: OrderBy }): PromiseLike<Row[]>\n create(args: { data: Create }): PromiseLike<Row>\n /** `skipDuplicates` is passed only when enabled (SQLite clients type it as `never`). */\n createMany(args: { data: Create[] }): PromiseLike<BatchPayload>\n deleteMany(args: { where: Where }): PromiseLike<BatchPayload>\n}\n\nexport type PrismaRbacPermissionDelegate = PrismaRbacDelegate<\n PrismaRbacPermissionRow,\n { id?: IntFilter; name?: StringFilter; guardName?: string },\n { name: string; guardName: string },\n { id: 'asc' }\n>\n\nexport type PrismaRbacRoleDelegate = PrismaRbacDelegate<\n PrismaRbacRoleRow,\n { id?: IntFilter; name?: StringFilter; guardName?: string; teamId?: StringFilter },\n { name: string; guardName: string; teamId: string },\n { id: 'asc' }\n>\n\nexport type PrismaRbacRoleHasPermissionDelegate = PrismaRbacDelegate<\n PrismaRbacRoleHasPermissionRow,\n { roleId?: IntFilter; permissionId?: IntFilter },\n PrismaRbacRoleHasPermissionRow\n>\n\nexport type PrismaRbacModelHasRoleDelegate = PrismaRbacDelegate<\n PrismaRbacModelHasRoleRow,\n { roleId?: IntFilter; subjectType?: string; subjectId?: string; teamId?: string },\n PrismaRbacModelHasRoleRow\n>\n\nexport type PrismaRbacModelHasPermissionDelegate = PrismaRbacDelegate<\n PrismaRbacModelHasPermissionRow,\n { permissionId?: IntFilter; subjectType?: string; subjectId?: string; teamId?: string },\n PrismaRbacModelHasPermissionRow\n>\n\n/** The part of a `PrismaClient` (with the rbac models) that the adapter needs. */\nexport interface PrismaRbacClient {\n rbacPermission: PrismaRbacPermissionDelegate\n rbacRole: PrismaRbacRoleDelegate\n rbacRoleHasPermission: PrismaRbacRoleHasPermissionDelegate\n rbacModelHasRole: PrismaRbacModelHasRoleDelegate\n rbacModelHasPermission: PrismaRbacModelHasPermissionDelegate\n $transaction(queries: PromiseLike<unknown>[]): PromiseLike<unknown>\n}\n\nexport interface PrismaAdapterOptions {\n /**\n * Use `createMany({ skipDuplicates: true })` for attach operations (one query, race-free).\n * Supported by PostgreSQL, MySQL/MariaDB and CockroachDB — NOT by SQLite, SQL Server or MongoDB.\n * Default: `false` (portable: reads existing links first, inserts only the missing ones).\n */\n skipDuplicates?: boolean\n}\n\n// ------------------------------------------------------------------------------- helpers\n\nconst GLOBAL_TEAM = ''\n\n/** `null` (global) is stored as `''`; every other team id as text. */\nconst teamKey = (teamId: TeamId): string => (teamId === null ? GLOBAL_TEAM : String(teamId))\nconst teamFromKey = (key: string): TeamId => (key === GLOBAL_TEAM ? null : key)\nconst subjectKey = (subject: Subject): string => String(subject.id)\n\n/** Converts an engine id (number or numeric string) into the Int primary key. */\nconst toIntId = (id: Id): number | undefined => {\n if (typeof id === 'number') return Number.isSafeInteger(id) ? id : undefined\n if (!/^-?\\d+$/.test(id.trim())) return undefined\n const n = Number(id)\n return Number.isSafeInteger(n) ? n : undefined\n}\n\nconst toIntIds = (ids: readonly Id[]): number[] => {\n const out = new Set<number>()\n for (const id of ids) {\n const n = toIntId(id)\n if (n !== undefined) out.add(n)\n }\n return [...out]\n}\n\nconst requireIntIds = (ids: readonly Id[], what: string): number[] => {\n const out = new Set<number>()\n for (const id of ids) {\n const n = toIntId(id)\n if (n === undefined) throw new TypeError(`PrismaAdapter: invalid ${what} id ${JSON.stringify(id)} (expected an integer).`)\n out.add(n)\n }\n return [...out]\n}\n\nconst isUniqueViolation = (error: unknown): boolean =>\n typeof error === 'object' && error !== null && (error as { code?: unknown }).code === 'P2002'\n\nconst toPermission = (row: PrismaRbacPermissionRow): Permission => ({\n id: row.id,\n name: row.name,\n guardName: row.guardName,\n})\n\nconst toRole = (row: PrismaRbacRoleRow): Role => ({\n id: row.id,\n name: row.name,\n guardName: row.guardName,\n teamId: teamFromKey(row.teamId),\n})\n\nconst unique = (values: readonly string[]): string[] => [...new Set(values)]\n\n// ------------------------------------------------------------------------------- adapter\n\n/**\n * `RbacAdapter` backed by Prisma. Requires the models from `schema/rbac.prisma`.\n *\n * - Role / permission ids are returned as numbers (numeric strings are accepted as input).\n * - Subject ids are stored as text; reverse lookups return them as strings.\n * - `Role.teamId` is `null` for global roles, otherwise the team id as a string.\n */\nexport class PrismaAdapter implements RbacAdapter {\n readonly #db: PrismaRbacClient\n readonly #skipDuplicates: boolean\n\n constructor(prisma: PrismaRbacClient, options: PrismaAdapterOptions = {}) {\n this.#db = prisma\n this.#skipDuplicates = options.skipDuplicates ?? false\n }\n\n // ---------------------------------------------------------------- permissions\n\n async createPermission(data: { name: string; guardName: string }): Promise<Permission> {\n const row = await this.#db.rbacPermission.create({ data: { name: data.name, guardName: data.guardName } })\n return toPermission(row)\n }\n\n async findPermissions(query: FindPermissionsQuery = {}): Promise<Permission[]> {\n const where: { id?: IntFilter; name?: StringFilter; guardName?: string } = {}\n if (query.ids !== undefined) {\n const ids = toIntIds(query.ids)\n if (ids.length === 0) return []\n where.id = { in: ids }\n }\n if (query.names !== undefined) {\n if (query.names.length === 0) return []\n where.name = { in: unique(query.names) }\n }\n if (query.guardName !== undefined) where.guardName = query.guardName\n\n const rows = await this.#db.rbacPermission.findMany({ where, orderBy: { id: 'asc' } })\n return rows.map(toPermission)\n }\n\n async deletePermission(id: Id): Promise<void> {\n const permissionId = toIntId(id)\n if (permissionId === undefined) return\n await this.#db.$transaction([\n this.#db.rbacRoleHasPermission.deleteMany({ where: { permissionId } }),\n this.#db.rbacModelHasPermission.deleteMany({ where: { permissionId } }),\n this.#db.rbacPermission.deleteMany({ where: { id: permissionId } }),\n ])\n }\n\n // ---------------------------------------------------------------------- roles\n\n async createRole(data: { name: string; guardName: string; teamId: TeamId }): Promise<Role> {\n const row = await this.#db.rbacRole.create({\n data: { name: data.name, guardName: data.guardName, teamId: teamKey(data.teamId) },\n })\n return toRole(row)\n }\n\n async findRoles(query: FindRolesQuery = {}): Promise<Role[]> {\n const where: { id?: IntFilter; name?: StringFilter; guardName?: string; teamId?: StringFilter } = {}\n if (query.ids !== undefined) {\n const ids = toIntIds(query.ids)\n if (ids.length === 0) return []\n where.id = { in: ids }\n }\n if (query.names !== undefined) {\n if (query.names.length === 0) return []\n where.name = { in: unique(query.names) }\n }\n if (query.guardName !== undefined) where.guardName = query.guardName\n if (query.teamIds !== undefined) {\n if (query.teamIds.length === 0) return []\n where.teamId = { in: unique(query.teamIds.map(teamKey)) }\n }\n\n const rows = await this.#db.rbacRole.findMany({ where, orderBy: { id: 'asc' } })\n return rows.map(toRole)\n }\n\n async deleteRole(id: Id): Promise<void> {\n const roleId = toIntId(id)\n if (roleId === undefined) return\n await this.#db.$transaction([\n this.#db.rbacRoleHasPermission.deleteMany({ where: { roleId } }),\n this.#db.rbacModelHasRole.deleteMany({ where: { roleId } }),\n this.#db.rbacRole.deleteMany({ where: { id: roleId } }),\n ])\n }\n\n // ---------------------------------------------------------- role ↔ permission\n\n async getRolePermissionLinks(roleIds: readonly Id[]): Promise<RolePermissionLink[]> {\n const ids = toIntIds(roleIds)\n if (ids.length === 0) return []\n const rows = await this.#db.rbacRoleHasPermission.findMany({ where: { roleId: { in: ids } } })\n return rows.map((r) => ({ roleId: r.roleId, permissionId: r.permissionId }))\n }\n\n async attachRolePermissions(roleId: Id, permissionIds: readonly Id[]): Promise<void> {\n const [role] = requireIntIds([roleId], 'role')\n const ids = requireIntIds(permissionIds, 'permission')\n if (role === undefined || ids.length === 0) return\n const delegate = this.#db.rbacRoleHasPermission\n await this.#insertMissing(\n ids,\n async () => (await delegate.findMany({ where: { roleId: role, permissionId: { in: ids } } })).map((r) => r.permissionId),\n (data) => delegate.createMany({ data: data.map((permissionId) => ({ roleId: role, permissionId })), ...this.#skip() }),\n )\n }\n\n async detachRolePermissions(roleId: Id, permissionIds?: readonly Id[]): Promise<void> {\n const role = toIntId(roleId)\n if (role === undefined) return\n if (permissionIds === undefined) {\n await this.#db.rbacRoleHasPermission.deleteMany({ where: { roleId: role } })\n return\n }\n const ids = toIntIds(permissionIds)\n if (ids.length === 0) return\n await this.#db.rbacRoleHasPermission.deleteMany({ where: { roleId: role, permissionId: { in: ids } } })\n }\n\n // ------------------------------------------------------------- subject ↔ role\n\n async getSubjectRoleIds(subject: Subject, teamId: TeamId): Promise<Id[]> {\n const rows = await this.#db.rbacModelHasRole.findMany({ where: this.#subjectWhere(subject, teamId) })\n return rows.map((r) => r.roleId)\n }\n\n async attachSubjectRoles(subject: Subject, roleIds: readonly Id[], teamId: TeamId): Promise<void> {\n const ids = requireIntIds(roleIds, 'role')\n if (ids.length === 0) return\n const base = this.#subjectWhere(subject, teamId)\n const delegate = this.#db.rbacModelHasRole\n await this.#insertMissing(\n ids,\n async () => (await delegate.findMany({ where: { ...base, roleId: { in: ids } } })).map((r) => r.roleId),\n (data) => delegate.createMany({ data: data.map((roleId) => ({ ...base, roleId })), ...this.#skip() }),\n )\n }\n\n async detachSubjectRoles(subject: Subject, roleIds: readonly Id[] | undefined, teamId: TeamId): Promise<void> {\n const base = this.#subjectWhere(subject, teamId)\n if (roleIds === undefined) {\n await this.#db.rbacModelHasRole.deleteMany({ where: base })\n return\n }\n const ids = toIntIds(roleIds)\n if (ids.length === 0) return\n await this.#db.rbacModelHasRole.deleteMany({ where: { ...base, roleId: { in: ids } } })\n }\n\n // ------------------------------------------------------- subject ↔ permission\n\n async getSubjectPermissionIds(subject: Subject, teamId: TeamId): Promise<Id[]> {\n const rows = await this.#db.rbacModelHasPermission.findMany({ where: this.#subjectWhere(subject, teamId) })\n return rows.map((r) => r.permissionId)\n }\n\n async attachSubjectPermissions(subject: Subject, permissionIds: readonly Id[], teamId: TeamId): Promise<void> {\n const ids = requireIntIds(permissionIds, 'permission')\n if (ids.length === 0) return\n const base = this.#subjectWhere(subject, teamId)\n const delegate = this.#db.rbacModelHasPermission\n await this.#insertMissing(\n ids,\n async () =>\n (await delegate.findMany({ where: { ...base, permissionId: { in: ids } } })).map((r) => r.permissionId),\n (data) => delegate.createMany({ data: data.map((permissionId) => ({ ...base, permissionId })), ...this.#skip() }),\n )\n }\n\n async detachSubjectPermissions(\n subject: Subject,\n permissionIds: readonly Id[] | undefined,\n teamId: TeamId,\n ): Promise<void> {\n const base = this.#subjectWhere(subject, teamId)\n if (permissionIds === undefined) {\n await this.#db.rbacModelHasPermission.deleteMany({ where: base })\n return\n }\n const ids = toIntIds(permissionIds)\n if (ids.length === 0) return\n await this.#db.rbacModelHasPermission.deleteMany({ where: { ...base, permissionId: { in: ids } } })\n }\n\n // ------------------------------------------------------------ reverse lookups\n\n async getSubjectIdsWithRoles(subjectType: string, roleIds: readonly Id[], teamId: TeamId): Promise<Id[]> {\n const ids = toIntIds(roleIds)\n if (ids.length === 0) return []\n const rows = await this.#db.rbacModelHasRole.findMany({\n where: { subjectType, teamId: teamKey(teamId), roleId: { in: ids } },\n })\n return unique(rows.map((r) => r.subjectId))\n }\n\n async getSubjectIdsWithPermissions(subjectType: string, permissionIds: readonly Id[], teamId: TeamId): Promise<Id[]> {\n const ids = toIntIds(permissionIds)\n if (ids.length === 0) return []\n const rows = await this.#db.rbacModelHasPermission.findMany({\n where: { subjectType, teamId: teamKey(teamId), permissionId: { in: ids } },\n })\n return unique(rows.map((r) => r.subjectId))\n }\n\n // -------------------------------------------------------------------- helpers\n\n #subjectWhere(subject: Subject, teamId: TeamId): { subjectType: string; subjectId: string; teamId: string } {\n return { subjectType: subject.type, subjectId: subjectKey(subject), teamId: teamKey(teamId) }\n }\n\n #skip(): { skipDuplicates?: boolean } {\n return this.#skipDuplicates ? { skipDuplicates: true } : {}\n }\n\n /**\n * Idempotent insert. With `skipDuplicates` it is a single `createMany`; otherwise the existing\n * links are read first and only the missing ones inserted. A concurrent insert of the same link\n * (unique violation P2002) is retried once, re-reading what now exists.\n */\n async #insertMissing(\n ids: number[],\n existing: () => Promise<number[]>,\n insert: (ids: number[]) => PromiseLike<BatchPayload>,\n ): Promise<void> {\n if (this.#skipDuplicates) {\n await insert(ids)\n return\n }\n for (let attempt = 0; ; attempt++) {\n const have = new Set(await existing())\n const missing = ids.filter((id) => !have.has(id))\n if (missing.length === 0) return\n try {\n await insert(missing)\n return\n } catch (error) {\n if (attempt >= 2 || !isUniqueViolation(error)) throw error\n }\n }\n }\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,72 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@anievo-id/rbac-evolution-prisma",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"description": "Prisma storage adapter for rbac-evolution.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"author": "AniEvo-ID (https://github.com/AniEvo-ID)",
|
|
7
|
+
"homepage": "https://github.com/AniEvo-ID/rbac-evolution/tree/main/packages/prisma#readme",
|
|
8
|
+
"bugs": {
|
|
9
|
+
"url": "https://github.com/AniEvo-ID/rbac-evolution/issues"
|
|
10
|
+
},
|
|
11
|
+
"type": "module",
|
|
12
|
+
"repository": {
|
|
13
|
+
"type": "git",
|
|
14
|
+
"url": "git+https://github.com/AniEvo-ID/rbac-evolution.git",
|
|
15
|
+
"directory": "packages/prisma"
|
|
16
|
+
},
|
|
17
|
+
"keywords": [
|
|
18
|
+
"rbac",
|
|
19
|
+
"permissions",
|
|
20
|
+
"roles",
|
|
21
|
+
"authorization",
|
|
22
|
+
"prisma"
|
|
23
|
+
],
|
|
24
|
+
"sideEffects": false,
|
|
25
|
+
"main": "./dist/index.cjs",
|
|
26
|
+
"module": "./dist/index.js",
|
|
27
|
+
"types": "./dist/index.d.ts",
|
|
28
|
+
"exports": {
|
|
29
|
+
".": {
|
|
30
|
+
"import": {
|
|
31
|
+
"types": "./dist/index.d.ts",
|
|
32
|
+
"default": "./dist/index.js"
|
|
33
|
+
},
|
|
34
|
+
"require": {
|
|
35
|
+
"types": "./dist/index.d.cts",
|
|
36
|
+
"default": "./dist/index.cjs"
|
|
37
|
+
}
|
|
38
|
+
},
|
|
39
|
+
"./package.json": "./package.json"
|
|
40
|
+
},
|
|
41
|
+
"files": [
|
|
42
|
+
"dist",
|
|
43
|
+
"schema"
|
|
44
|
+
],
|
|
45
|
+
"publishConfig": {
|
|
46
|
+
"access": "public"
|
|
47
|
+
},
|
|
48
|
+
"dependencies": {
|
|
49
|
+
"@anievo-id/rbac-evolution": "^0.1.1"
|
|
50
|
+
},
|
|
51
|
+
"peerDependencies": {
|
|
52
|
+
"@prisma/client": ">=5"
|
|
53
|
+
},
|
|
54
|
+
"devDependencies": {
|
|
55
|
+
"@prisma/client": "^6.19.0",
|
|
56
|
+
"prisma": "^6.19.0",
|
|
57
|
+
"tsup": "^8.3.0",
|
|
58
|
+
"typescript": "^5.7.0",
|
|
59
|
+
"vitest": "^2.1.0"
|
|
60
|
+
},
|
|
61
|
+
"engines": {
|
|
62
|
+
"node": ">=20"
|
|
63
|
+
},
|
|
64
|
+
"scripts": {
|
|
65
|
+
"build": "tsup",
|
|
66
|
+
"dev": "tsup --watch",
|
|
67
|
+
"typecheck": "node test/prepare.mjs --generate-only && tsc --noEmit",
|
|
68
|
+
"test:db": "node test/prepare.mjs",
|
|
69
|
+
"test": "node test/prepare.mjs && vitest run",
|
|
70
|
+
"clean": "rm -rf dist .turbo test/generated test/.tmp"
|
|
71
|
+
}
|
|
6
72
|
}
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
// rbac-evolution — Prisma models
|
|
2
|
+
// Copy these models into your schema.prisma (or into a file of a multi-file
|
|
3
|
+
// `prismaSchemaFolder` schema). Table and column names mirror spatie/laravel-permission.
|
|
4
|
+
//
|
|
5
|
+
// Conventions:
|
|
6
|
+
// - role / permission ids are autoincrement Int
|
|
7
|
+
// - subjects (users, API clients, ...) are stored as `subject_type` + `subject_id` (text),
|
|
8
|
+
// so any primary key type works (number, UUID, cuid, ...)
|
|
9
|
+
// - `team_id` is NOT NULL text; '' (empty string) means "global / no team"
|
|
10
|
+
|
|
11
|
+
model RbacPermission {
|
|
12
|
+
id Int @id @default(autoincrement())
|
|
13
|
+
name String
|
|
14
|
+
guardName String @map("guard_name")
|
|
15
|
+
createdAt DateTime @default(now()) @map("created_at")
|
|
16
|
+
updatedAt DateTime @default(now()) @updatedAt @map("updated_at")
|
|
17
|
+
|
|
18
|
+
roles RbacRoleHasPermission[]
|
|
19
|
+
subjects RbacModelHasPermission[]
|
|
20
|
+
|
|
21
|
+
@@unique([name, guardName])
|
|
22
|
+
@@map("permissions")
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
model RbacRole {
|
|
26
|
+
id Int @id @default(autoincrement())
|
|
27
|
+
teamId String @default("") @map("team_id")
|
|
28
|
+
name String
|
|
29
|
+
guardName String @map("guard_name")
|
|
30
|
+
createdAt DateTime @default(now()) @map("created_at")
|
|
31
|
+
updatedAt DateTime @default(now()) @updatedAt @map("updated_at")
|
|
32
|
+
|
|
33
|
+
permissions RbacRoleHasPermission[]
|
|
34
|
+
subjects RbacModelHasRole[]
|
|
35
|
+
|
|
36
|
+
@@unique([name, guardName, teamId])
|
|
37
|
+
@@index([teamId])
|
|
38
|
+
@@map("roles")
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
model RbacRoleHasPermission {
|
|
42
|
+
permissionId Int @map("permission_id")
|
|
43
|
+
roleId Int @map("role_id")
|
|
44
|
+
|
|
45
|
+
permission RbacPermission @relation(fields: [permissionId], references: [id], onDelete: Cascade)
|
|
46
|
+
role RbacRole @relation(fields: [roleId], references: [id], onDelete: Cascade)
|
|
47
|
+
|
|
48
|
+
@@id([roleId, permissionId])
|
|
49
|
+
@@index([permissionId])
|
|
50
|
+
@@map("role_has_permissions")
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
model RbacModelHasRole {
|
|
54
|
+
roleId Int @map("role_id")
|
|
55
|
+
subjectType String @map("subject_type")
|
|
56
|
+
subjectId String @map("subject_id")
|
|
57
|
+
teamId String @default("") @map("team_id")
|
|
58
|
+
|
|
59
|
+
role RbacRole @relation(fields: [roleId], references: [id], onDelete: Cascade)
|
|
60
|
+
|
|
61
|
+
@@id([roleId, subjectType, subjectId, teamId])
|
|
62
|
+
@@index([subjectType, subjectId, teamId])
|
|
63
|
+
@@map("model_has_roles")
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
model RbacModelHasPermission {
|
|
67
|
+
permissionId Int @map("permission_id")
|
|
68
|
+
subjectType String @map("subject_type")
|
|
69
|
+
subjectId String @map("subject_id")
|
|
70
|
+
teamId String @default("") @map("team_id")
|
|
71
|
+
|
|
72
|
+
permission RbacPermission @relation(fields: [permissionId], references: [id], onDelete: Cascade)
|
|
73
|
+
|
|
74
|
+
@@id([permissionId, subjectType, subjectId, teamId])
|
|
75
|
+
@@index([subjectType, subjectId, teamId])
|
|
76
|
+
@@map("model_has_permissions")
|
|
77
|
+
}
|