@anievo-id/rbac-evolution-sveltekit 0.0.0-stage → 1.4.0
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 +69 -3
- package/dist/Can.svelte +29 -0
- package/dist/Can.svelte.d.ts +18 -0
- package/dist/Can.svelte.d.ts.map +1 -0
- package/dist/HasRole.svelte +26 -0
- package/dist/HasRole.svelte.d.ts +15 -0
- package/dist/HasRole.svelte.d.ts.map +1 -0
- package/dist/checker.d.ts +45 -0
- package/dist/checker.d.ts.map +1 -0
- package/dist/checker.js +65 -0
- package/dist/context.svelte.d.ts +65 -0
- package/dist/context.svelte.d.ts.map +1 -0
- package/dist/context.svelte.js +60 -0
- package/dist/index.d.ts +21 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +17 -0
- package/dist/props.d.ts +48 -0
- package/dist/props.d.ts.map +1 -0
- package/dist/props.js +1 -0
- package/dist/server/guards.d.ts +138 -0
- package/dist/server/guards.d.ts.map +1 -0
- package/dist/server/guards.js +125 -0
- package/dist/server/handle.d.ts +105 -0
- package/dist/server/handle.d.ts.map +1 -0
- package/dist/server/handle.js +71 -0
- package/dist/server/index.d.ts +13 -0
- package/dist/server/index.d.ts.map +1 -0
- package/dist/server/index.js +9 -0
- package/dist/types.d.ts +11 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +1 -0
- package/package.json +74 -3
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,69 @@
|
|
|
1
|
-
#
|
|
2
|
-
|
|
3
|
-
|
|
1
|
+
# @anievo-id/rbac-evolution-sveltekit
|
|
2
|
+
|
|
3
|
+
SvelteKit 2 and 3 (Svelte 5) integration for [RBAC Evolution](https://github.com/AniEvo-ID/rbac-evolution): a
|
|
4
|
+
`handle` hook, guards for `load` functions, form actions and `+server.ts` endpoints, and `<Can>` / `<HasRole>`
|
|
5
|
+
components with a runes-based context.
|
|
6
|
+
|
|
7
|
+
## Install
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
npm i @anievo-id/rbac-evolution @anievo-id/rbac-evolution-sveltekit
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
## Usage
|
|
14
|
+
|
|
15
|
+
```ts
|
|
16
|
+
// src/hooks.server.ts
|
|
17
|
+
import { sequence } from '@sveltejs/kit/hooks'
|
|
18
|
+
import { rbacHandle } from '@anievo-id/rbac-evolution-sveltekit/server'
|
|
19
|
+
import { rbac } from '$lib/server/rbac' // createRbac({ adapter })
|
|
20
|
+
|
|
21
|
+
export const handle = sequence(
|
|
22
|
+
authHandle, // yours: sets event.locals.user
|
|
23
|
+
rbacHandle({ rbac, getSubject: (event) => (event.locals.user ? { type: 'user', id: event.locals.user.id } : null) }),
|
|
24
|
+
)
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
```ts
|
|
28
|
+
// src/routes/+layout.server.ts
|
|
29
|
+
import { getSnapshot } from '@anievo-id/rbac-evolution-sveltekit/server'
|
|
30
|
+
export const load = async (event) => ({ rbac: await getSnapshot(event) })
|
|
31
|
+
|
|
32
|
+
// src/routes/admin/+page.server.ts
|
|
33
|
+
import { requireRole } from '@anievo-id/rbac-evolution-sveltekit/server'
|
|
34
|
+
export const load = async (event) => {
|
|
35
|
+
await requireRole(event, 'admin') // error(401) for guests, error(403) without the role
|
|
36
|
+
}
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
```svelte
|
|
40
|
+
<!-- src/routes/+layout.svelte -->
|
|
41
|
+
<script lang="ts">
|
|
42
|
+
import { setRbacContext } from '@anievo-id/rbac-evolution-sveltekit'
|
|
43
|
+
let { data, children } = $props()
|
|
44
|
+
setRbacContext(() => data.rbac, { superAdminRoles: ['super-admin'] })
|
|
45
|
+
</script>
|
|
46
|
+
|
|
47
|
+
{@render children()}
|
|
48
|
+
|
|
49
|
+
<!-- any component below it -->
|
|
50
|
+
<script lang="ts">
|
|
51
|
+
import { Can, HasRole } from '@anievo-id/rbac-evolution-sveltekit'
|
|
52
|
+
</script>
|
|
53
|
+
|
|
54
|
+
<Can permission="articles.publish">
|
|
55
|
+
<button>Publish</button>
|
|
56
|
+
{#snippet fallback()}Ask an editor.{/snippet}
|
|
57
|
+
</Can>
|
|
58
|
+
<HasRole role="admin|editor">Staff tools</HasRole>
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
> Client checks only decide what the UI shows. Enforce access on the server with the guards of `/server`.
|
|
62
|
+
|
|
63
|
+
## Documentation
|
|
64
|
+
|
|
65
|
+
https://creation.anievo.id/rbac-evolution/frameworks/sveltekit
|
|
66
|
+
|
|
67
|
+
## License
|
|
68
|
+
|
|
69
|
+
MIT
|
package/dist/Can.svelte
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
<!--
|
|
2
|
+
@component
|
|
3
|
+
Renders `children` when the user has the permission(s), otherwise the `fallback` snippet.
|
|
4
|
+
Conditions are ANDed; without any condition nothing passes (deny by default). `not` inverts the result.
|
|
5
|
+
|
|
6
|
+
```svelte
|
|
7
|
+
<Can permission="articles.edit">...</Can>
|
|
8
|
+
<Can anyOf={['articles.edit', 'articles.delete']}>
|
|
9
|
+
...
|
|
10
|
+
{#snippet fallback()}No access{/snippet}
|
|
11
|
+
</Can>
|
|
12
|
+
<Can allOf={['a', 'b']}>...</Can>
|
|
13
|
+
```
|
|
14
|
+
-->
|
|
15
|
+
<script lang="ts">import { getRbacContext } from "./context.svelte.js";
|
|
16
|
+
let { permission, anyOf, allOf, not = false, children, fallback } = $props();
|
|
17
|
+
const rbac = getRbacContext();
|
|
18
|
+
const hasCondition = $derived(permission !== void 0 || anyOf !== void 0 || allOf !== void 0);
|
|
19
|
+
const allowed = $derived(
|
|
20
|
+
(permission === void 0 || rbac.canAll(permission)) && (anyOf === void 0 || rbac.canAny(anyOf)) && (allOf === void 0 || rbac.canAll(allOf))
|
|
21
|
+
);
|
|
22
|
+
const pass = $derived(hasCondition && allowed !== not);
|
|
23
|
+
</script>
|
|
24
|
+
|
|
25
|
+
{#if pass}
|
|
26
|
+
{@render children?.()}
|
|
27
|
+
{:else}
|
|
28
|
+
{@render fallback?.()}
|
|
29
|
+
{/if}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { CanProps } from './props.js';
|
|
2
|
+
/**
|
|
3
|
+
* Renders `children` when the user has the permission(s), otherwise the `fallback` snippet.
|
|
4
|
+
* Conditions are ANDed; without any condition nothing passes (deny by default). `not` inverts the result.
|
|
5
|
+
*
|
|
6
|
+
* ```svelte
|
|
7
|
+
* <Can permission="articles.edit">...</Can>
|
|
8
|
+
* <Can anyOf={['articles.edit', 'articles.delete']}>
|
|
9
|
+
* ...
|
|
10
|
+
* {#snippet fallback()}No access{/snippet}
|
|
11
|
+
* </Can>
|
|
12
|
+
* <Can allOf={['a', 'b']}>...</Can>
|
|
13
|
+
* ```
|
|
14
|
+
*/
|
|
15
|
+
declare const Can: import("svelte").Component<CanProps, {}, "">;
|
|
16
|
+
type Can = ReturnType<typeof Can>;
|
|
17
|
+
export default Can;
|
|
18
|
+
//# sourceMappingURL=Can.svelte.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"Can.svelte.d.ts","sourceRoot":"","sources":["../src/Can.svelte"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AA4B3C;;;;;;;;;;;;GAYG;AACH,QAAA,MAAM,GAAG,8CAAwC,CAAC;AAClD,KAAK,GAAG,GAAG,UAAU,CAAC,OAAO,GAAG,CAAC,CAAC;AAClC,eAAe,GAAG,CAAC"}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
<!--
|
|
2
|
+
@component
|
|
3
|
+
Renders `children` when the user has the role(s), otherwise the `fallback` snippet.
|
|
4
|
+
Conditions are ANDed; without any condition nothing passes (deny by default). `not` inverts the result.
|
|
5
|
+
|
|
6
|
+
```svelte
|
|
7
|
+
<HasRole role="admin">...</HasRole>
|
|
8
|
+
<HasRole role="writer|editor">...</HasRole>
|
|
9
|
+
<HasRole allOf={['writer', 'editor']}>...</HasRole>
|
|
10
|
+
```
|
|
11
|
+
-->
|
|
12
|
+
<script lang="ts">import { getRbacContext } from "./context.svelte.js";
|
|
13
|
+
let { role, anyOf, allOf, not = false, children, fallback } = $props();
|
|
14
|
+
const rbac = getRbacContext();
|
|
15
|
+
const hasCondition = $derived(role !== void 0 || anyOf !== void 0 || allOf !== void 0);
|
|
16
|
+
const allowed = $derived(
|
|
17
|
+
(role === void 0 || rbac.hasAnyRole(role)) && (anyOf === void 0 || rbac.hasAnyRole(anyOf)) && (allOf === void 0 || rbac.hasAllRoles(allOf))
|
|
18
|
+
);
|
|
19
|
+
const pass = $derived(hasCondition && allowed !== not);
|
|
20
|
+
</script>
|
|
21
|
+
|
|
22
|
+
{#if pass}
|
|
23
|
+
{@render children?.()}
|
|
24
|
+
{:else}
|
|
25
|
+
{@render fallback?.()}
|
|
26
|
+
{/if}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { HasRoleProps } from './props.js';
|
|
2
|
+
/**
|
|
3
|
+
* Renders `children` when the user has the role(s), otherwise the `fallback` snippet.
|
|
4
|
+
* Conditions are ANDed; without any condition nothing passes (deny by default). `not` inverts the result.
|
|
5
|
+
*
|
|
6
|
+
* ```svelte
|
|
7
|
+
* <HasRole role="admin">...</HasRole>
|
|
8
|
+
* <HasRole role="writer|editor">...</HasRole>
|
|
9
|
+
* <HasRole allOf={['writer', 'editor']}>...</HasRole>
|
|
10
|
+
* ```
|
|
11
|
+
*/
|
|
12
|
+
declare const HasRole: import("svelte").Component<HasRoleProps, {}, "">;
|
|
13
|
+
type HasRole = ReturnType<typeof HasRole>;
|
|
14
|
+
export default HasRole;
|
|
15
|
+
//# sourceMappingURL=HasRole.svelte.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"HasRole.svelte.d.ts","sourceRoot":"","sources":["../src/HasRole.svelte"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AA4B/C;;;;;;;;;GASG;AACH,QAAA,MAAM,OAAO,kDAAwC,CAAC;AACtD,KAAK,OAAO,GAAG,UAAU,CAAC,OAAO,OAAO,CAAC,CAAC;AAC1C,eAAe,OAAO,CAAC"}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { type RbacSnapshot } from '@anievo-id/rbac-evolution';
|
|
2
|
+
/** A permission or role name, or a list of them. `N` is `string` without typed names. */
|
|
3
|
+
export type NameList<N extends string = string> = N | readonly N[];
|
|
4
|
+
export interface RbacCheckerOptions {
|
|
5
|
+
/** Match permissions with wildcard semantics (`articles.*` covers `articles.edit`). Must mirror `createRbac({ wildcard })`. Default: `false`. */
|
|
6
|
+
wildcard?: boolean | undefined;
|
|
7
|
+
/** Roles that pass every permission check, like a `Gate::before` super-admin rule. Default: `[]`. */
|
|
8
|
+
superAdminRoles?: readonly string[] | undefined;
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* Synchronous checks against a {@link RbacSnapshot}, with the same rules as the Vue package:
|
|
12
|
+
*
|
|
13
|
+
* - `can(list)` / `canAll(list)` need ALL of the permissions, `canAny(list)` ANY of them;
|
|
14
|
+
* - `hasRole('a|b')` / `hasRole(['a', 'b'])` / `hasAnyRole` need ANY of the roles, `hasAllRoles` ALL of them;
|
|
15
|
+
* - a name in the snapshot's `denied` (`snapshot({ checkBefore })`) is never allowed, super-admins included;
|
|
16
|
+
* - an empty list is never allowed (deny by default).
|
|
17
|
+
*
|
|
18
|
+
* This is for UI only: the server must always enforce authorization.
|
|
19
|
+
*/
|
|
20
|
+
export interface RbacChecker {
|
|
21
|
+
/** The snapshot the checks run against. A guest's is empty. */
|
|
22
|
+
readonly snapshot: Readonly<RbacSnapshot>;
|
|
23
|
+
/** `true` when there is no subject (a `null` / `undefined` snapshot). */
|
|
24
|
+
readonly isGuest: boolean;
|
|
25
|
+
/** `true` if the subject has the permission (or, for a list, ALL of them). */
|
|
26
|
+
can(permission: NameList): boolean;
|
|
27
|
+
/** `!can(permission)`. */
|
|
28
|
+
cannot(permission: NameList): boolean;
|
|
29
|
+
/** `true` if the subject has ANY of the permissions. */
|
|
30
|
+
canAny(permissions: NameList): boolean;
|
|
31
|
+
/** `true` if the subject has ALL of the permissions. */
|
|
32
|
+
canAll(permissions: NameList): boolean;
|
|
33
|
+
/** `true` if the subject has the role, or ANY of the roles. Supports `'writer|editor'`. */
|
|
34
|
+
hasRole(roles: NameList): boolean;
|
|
35
|
+
hasAnyRole(roles: NameList): boolean;
|
|
36
|
+
hasAllRoles(roles: NameList): boolean;
|
|
37
|
+
/** `true` if the subject has one of the configured `superAdminRoles`. */
|
|
38
|
+
isSuperAdmin(): boolean;
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Builds a pure checker for a snapshot (as returned by `getSnapshot(event)` / `rbac.for(user).snapshot()`).
|
|
42
|
+
* `setRbacContext()` uses it; use it on its own in a universal `load` (`+page.ts`) with the layout's data.
|
|
43
|
+
*/
|
|
44
|
+
export declare function createRbacChecker(snapshot: RbacSnapshot | null | undefined, options?: RbacCheckerOptions): RbacChecker;
|
|
45
|
+
//# sourceMappingURL=checker.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"checker.d.ts","sourceRoot":"","sources":["../src/checker.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,YAAY,EAAmB,MAAM,2BAA2B,CAAA;AAE9E,yFAAyF;AACzF,MAAM,MAAM,QAAQ,CAAC,CAAC,SAAS,MAAM,GAAG,MAAM,IAAI,CAAC,GAAG,SAAS,CAAC,EAAE,CAAA;AAElE,MAAM,WAAW,kBAAkB;IACjC,iJAAiJ;IACjJ,QAAQ,CAAC,EAAE,OAAO,GAAG,SAAS,CAAA;IAC9B,qGAAqG;IACrG,eAAe,CAAC,EAAE,SAAS,MAAM,EAAE,GAAG,SAAS,CAAA;CAChD;AAED;;;;;;;;;GASG;AACH,MAAM,WAAW,WAAW;IAC1B,+DAA+D;IAC/D,QAAQ,CAAC,QAAQ,EAAE,QAAQ,CAAC,YAAY,CAAC,CAAA;IACzC,yEAAyE;IACzE,QAAQ,CAAC,OAAO,EAAE,OAAO,CAAA;IACzB,8EAA8E;IAC9E,GAAG,CAAC,UAAU,EAAE,QAAQ,GAAG,OAAO,CAAA;IAClC,0BAA0B;IAC1B,MAAM,CAAC,UAAU,EAAE,QAAQ,GAAG,OAAO,CAAA;IACrC,wDAAwD;IACxD,MAAM,CAAC,WAAW,EAAE,QAAQ,GAAG,OAAO,CAAA;IACtC,wDAAwD;IACxD,MAAM,CAAC,WAAW,EAAE,QAAQ,GAAG,OAAO,CAAA;IACtC,2FAA2F;IAC3F,OAAO,CAAC,KAAK,EAAE,QAAQ,GAAG,OAAO,CAAA;IACjC,UAAU,CAAC,KAAK,EAAE,QAAQ,GAAG,OAAO,CAAA;IACpC,WAAW,CAAC,KAAK,EAAE,QAAQ,GAAG,OAAO,CAAA;IACrC,yEAAyE;IACzE,YAAY,IAAI,OAAO,CAAA;CACxB;AAqBD;;;GAGG;AACH,wBAAgB,iBAAiB,CAAC,QAAQ,EAAE,YAAY,GAAG,IAAI,GAAG,SAAS,EAAE,OAAO,GAAE,kBAAuB,GAAG,WAAW,CA6C1H"}
|
package/dist/checker.js
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { wildcardImplies } from '@anievo-id/rbac-evolution';
|
|
2
|
+
const EMPTY = Object.freeze({ roles: [], permissions: [] });
|
|
3
|
+
// `null` / `undefined` (e.g. a typo in a prop binding) is an empty list, so every check fails.
|
|
4
|
+
const toList = (value) => (value == null ? [] : typeof value === 'string' ? [value] : [...value]).map((v) => v.trim()).filter((v) => v !== '');
|
|
5
|
+
/** Like {@link toList}, but also splits spatie-style pipes: `'writer|editor'`. */
|
|
6
|
+
const toRoleList = (value) => toList(value).flatMap((v) => toList(v.split('|')));
|
|
7
|
+
function normalize(snapshot) {
|
|
8
|
+
if (!snapshot)
|
|
9
|
+
return EMPTY;
|
|
10
|
+
return Object.freeze({
|
|
11
|
+
roles: snapshot.roles.map((r) => r.trim()),
|
|
12
|
+
permissions: snapshot.permissions.map((p) => p.trim()),
|
|
13
|
+
// Names the server's `before` hook denies (`snapshot({ checkBefore })`). Kept absent for older snapshots.
|
|
14
|
+
...(snapshot.denied ? { denied: snapshot.denied.map((d) => d.trim()) } : {}),
|
|
15
|
+
});
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* Builds a pure checker for a snapshot (as returned by `getSnapshot(event)` / `rbac.for(user).snapshot()`).
|
|
19
|
+
* `setRbacContext()` uses it; use it on its own in a universal `load` (`+page.ts`) with the layout's data.
|
|
20
|
+
*/
|
|
21
|
+
export function createRbacChecker(snapshot, options = {}) {
|
|
22
|
+
const state = normalize(snapshot);
|
|
23
|
+
const wildcard = options.wildcard ?? false;
|
|
24
|
+
const roles = new Set(state.roles);
|
|
25
|
+
const denied = new Set(state.denied ?? []);
|
|
26
|
+
const superAdmin = toList(options.superAdminRoles ?? []).some((r) => roles.has(r));
|
|
27
|
+
const matches = (required) => {
|
|
28
|
+
if (state.permissions.includes(required))
|
|
29
|
+
return true;
|
|
30
|
+
if (!wildcard)
|
|
31
|
+
return false;
|
|
32
|
+
return state.permissions.some((pattern) => {
|
|
33
|
+
try {
|
|
34
|
+
return wildcardImplies(pattern, required);
|
|
35
|
+
}
|
|
36
|
+
catch {
|
|
37
|
+
return false;
|
|
38
|
+
}
|
|
39
|
+
});
|
|
40
|
+
};
|
|
41
|
+
/** One permission. Like the server, a `before` denial wins over super-admin and stored grants. */
|
|
42
|
+
const allows = (permission) => !denied.has(permission) && (superAdmin || matches(permission));
|
|
43
|
+
const canAny = (permissions) => toList(permissions).some(allows);
|
|
44
|
+
const canAll = (permissions) => {
|
|
45
|
+
const wanted = toList(permissions);
|
|
46
|
+
return wanted.length > 0 && wanted.every(allows);
|
|
47
|
+
};
|
|
48
|
+
const hasAnyRole = (list) => toRoleList(list).some((r) => roles.has(r));
|
|
49
|
+
const hasAllRoles = (list) => {
|
|
50
|
+
const wanted = toRoleList(list);
|
|
51
|
+
return wanted.length > 0 && wanted.every((r) => roles.has(r));
|
|
52
|
+
};
|
|
53
|
+
return {
|
|
54
|
+
snapshot: state,
|
|
55
|
+
isGuest: !snapshot,
|
|
56
|
+
can: canAll,
|
|
57
|
+
cannot: (permission) => !canAll(permission),
|
|
58
|
+
canAny,
|
|
59
|
+
canAll,
|
|
60
|
+
hasRole: hasAnyRole,
|
|
61
|
+
hasAnyRole,
|
|
62
|
+
hasAllRoles,
|
|
63
|
+
isSuperAdmin: () => superAdmin,
|
|
64
|
+
};
|
|
65
|
+
}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import type { DefaultGuardName, DefaultRbacTypes, PermissionName, Rbac, RbacSnapshot, RbacTypeConfig, RoleName } from '@anievo-id/rbac-evolution';
|
|
2
|
+
import { type NameList, type RbacCheckerOptions } from './checker.js';
|
|
3
|
+
import type { CheckNames, TypesOf } from './types.js';
|
|
4
|
+
/**
|
|
5
|
+
* The snapshot to check against: the value itself, or a getter such as `() => data.rbac`. With a getter, every
|
|
6
|
+
* check re-runs when the data changes (e.g. after `invalidateAll()` on login or logout).
|
|
7
|
+
*/
|
|
8
|
+
export type RbacSnapshotSource = RbacSnapshot | null | undefined | (() => RbacSnapshot | null | undefined);
|
|
9
|
+
export type RbacStateOptions = RbacCheckerOptions;
|
|
10
|
+
/**
|
|
11
|
+
* The reactive RBAC state of `setRbacContext()` / `getRbacContext()`. Every check reads rune state, so calling it in
|
|
12
|
+
* markup, `$derived` or `$effect` re-runs when the snapshot changes.
|
|
13
|
+
*
|
|
14
|
+
* `T` (a names type like `AppRbac`, or `typeof rbac`) types the names; without it, any string. With per-guard
|
|
15
|
+
* names, `G` is the guard the snapshot was made in (the default guard by default).
|
|
16
|
+
*
|
|
17
|
+
* This is for UI only: the server must always enforce authorization.
|
|
18
|
+
*/
|
|
19
|
+
export interface SvelteRbac<T extends RbacTypeConfig | Rbac<RbacTypeConfig> = DefaultRbacTypes, G extends string = DefaultGuardName<TypesOf<T>>> {
|
|
20
|
+
/** The current snapshot (reactive). A guest's is empty. */
|
|
21
|
+
readonly snapshot: Readonly<RbacSnapshot>;
|
|
22
|
+
/** `true` when the snapshot is `null` / `undefined`: no subject (reactive). */
|
|
23
|
+
readonly isGuest: boolean;
|
|
24
|
+
/** `true` if the user has the permission (or, for a list, ALL of them). */
|
|
25
|
+
can(permission: NameList<PermissionName<TypesOf<T>, G>>): boolean;
|
|
26
|
+
cannot(permission: NameList<PermissionName<TypesOf<T>, G>>): boolean;
|
|
27
|
+
canAny(permissions: NameList<PermissionName<TypesOf<T>, G>>): boolean;
|
|
28
|
+
canAll(permissions: NameList<PermissionName<TypesOf<T>, G>>): boolean;
|
|
29
|
+
/** `true` if the user has the role, or ANY of the roles. Supports `'writer|editor'`. */
|
|
30
|
+
hasRole<const S extends NameList>(roles: S & CheckNames<S, RoleName<TypesOf<T>, G>>): boolean;
|
|
31
|
+
hasAnyRole<const S extends NameList>(roles: S & CheckNames<S, RoleName<TypesOf<T>, G>>): boolean;
|
|
32
|
+
hasAllRoles<const S extends NameList>(roles: S & CheckNames<S, RoleName<TypesOf<T>, G>>): boolean;
|
|
33
|
+
/** `true` if the user has one of the configured `superAdminRoles`. */
|
|
34
|
+
isSuperAdmin(): boolean;
|
|
35
|
+
}
|
|
36
|
+
/** The context key `setRbacContext()` uses. Pass it in a test's `context` map with `createRbacState()`. */
|
|
37
|
+
export declare const RBAC_KEY: unique symbol;
|
|
38
|
+
/**
|
|
39
|
+
* Creates the reactive state without putting it in the context (`setRbacContext()` does both). Useful in tests:
|
|
40
|
+
* `render(Component, { context: new Map([[RBAC_KEY, createRbacState(snapshot)]]) })`.
|
|
41
|
+
*/
|
|
42
|
+
export declare function createRbacState<T extends RbacTypeConfig | Rbac<RbacTypeConfig> = DefaultRbacTypes, G extends string = DefaultGuardName<TypesOf<T>>>(snapshot: RbacSnapshotSource, options?: RbacStateOptions): SvelteRbac<T, G>;
|
|
43
|
+
/**
|
|
44
|
+
* Puts the current user's roles & permissions in the component context, for `getRbacContext()`, `<Can>` and
|
|
45
|
+
* `<HasRole>` below it. Call it in the root `+layout.svelte`, with a getter so it follows the layout data:
|
|
46
|
+
*
|
|
47
|
+
* ```svelte
|
|
48
|
+
* <script lang="ts">
|
|
49
|
+
* import { setRbacContext } from '@anievo-id/rbac-evolution-sveltekit'
|
|
50
|
+
* let { data, children } = $props()
|
|
51
|
+
* setRbacContext(() => data.rbac, { superAdminRoles: ['super-admin'] })
|
|
52
|
+
* </script>
|
|
53
|
+
* ```
|
|
54
|
+
*
|
|
55
|
+
* Must be called during component initialisation (like Svelte's `setContext`).
|
|
56
|
+
*/
|
|
57
|
+
export declare function setRbacContext<T extends RbacTypeConfig | Rbac<RbacTypeConfig> = DefaultRbacTypes, G extends string = DefaultGuardName<TypesOf<T>>>(snapshot: RbacSnapshotSource, options?: RbacStateOptions): SvelteRbac<T, G>;
|
|
58
|
+
/**
|
|
59
|
+
* Returns the state set by `setRbacContext()` in a parent component. Call it in a component's `<script>` (during
|
|
60
|
+
* initialisation), then use it anywhere in the component: `{#if rbac.can('articles.edit')}`.
|
|
61
|
+
*
|
|
62
|
+
* Pass your names type to check names at compile time: `getRbacContext<AppRbac>()`.
|
|
63
|
+
*/
|
|
64
|
+
export declare function getRbacContext<T extends RbacTypeConfig | Rbac<RbacTypeConfig> = DefaultRbacTypes, G extends string = DefaultGuardName<TypesOf<T>>>(): SvelteRbac<T, G>;
|
|
65
|
+
//# sourceMappingURL=context.svelte.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"context.svelte.d.ts","sourceRoot":"","sources":["../src/context.svelte.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,gBAAgB,EAChB,gBAAgB,EAChB,cAAc,EACd,IAAI,EACJ,YAAY,EACZ,cAAc,EACd,QAAQ,EACT,MAAM,2BAA2B,CAAA;AAElC,OAAO,EAAqB,KAAK,QAAQ,EAAE,KAAK,kBAAkB,EAAE,MAAM,cAAc,CAAA;AACxF,OAAO,KAAK,EAAE,UAAU,EAAE,OAAO,EAAE,MAAM,YAAY,CAAA;AAErD;;;GAGG;AACH,MAAM,MAAM,kBAAkB,GAAG,YAAY,GAAG,IAAI,GAAG,SAAS,GAAG,CAAC,MAAM,YAAY,GAAG,IAAI,GAAG,SAAS,CAAC,CAAA;AAE1G,MAAM,MAAM,gBA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setRbacContext()` uses. Pass it in a test's `context` map with `createRbacState()`. */
|
|
4
|
+
export const RBAC_KEY = Symbol('rbac-evolution');
|
|
5
|
+
/**
|
|
6
|
+
* Creates the reactive state without putting it in the context (`setRbacContext()` does both). Useful in tests:
|
|
7
|
+
* `render(Component, { context: new Map([[RBAC_KEY, createRbacState(snapshot)]]) })`.
|
|
8
|
+
*/
|
|
9
|
+
export function createRbacState(snapshot, options = {}) {
|
|
10
|
+
const read = typeof snapshot === 'function' ? snapshot : () => snapshot;
|
|
11
|
+
// Recomputed (lazily) whenever the getter's dependencies change, e.g. `data.rbac` after `invalidateAll()`.
|
|
12
|
+
const checker = $derived(createRbacChecker(read(), options));
|
|
13
|
+
const state = {
|
|
14
|
+
get snapshot() {
|
|
15
|
+
return checker.snapshot;
|
|
16
|
+
},
|
|
17
|
+
get isGuest() {
|
|
18
|
+
return checker.isGuest;
|
|
19
|
+
},
|
|
20
|
+
can: (permission) => checker.can(permission),
|
|
21
|
+
cannot: (permission) => checker.cannot(permission),
|
|
22
|
+
canAny: (permissions) => checker.canAny(permissions),
|
|
23
|
+
canAll: (permissions) => checker.canAll(permissions),
|
|
24
|
+
hasRole: (roles) => checker.hasRole(roles),
|
|
25
|
+
hasAnyRole: (roles) => checker.hasAnyRole(roles),
|
|
26
|
+
hasAllRoles: (roles) => checker.hasAllRoles(roles),
|
|
27
|
+
isSuperAdmin: () => checker.isSuperAdmin(),
|
|
28
|
+
};
|
|
29
|
+
// `T` only narrows the accepted names; the checks are the same.
|
|
30
|
+
return state;
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Puts the current user's roles & permissions in the component context, for `getRbacContext()`, `<Can>` and
|
|
34
|
+
* `<HasRole>` below it. Call it in the root `+layout.svelte`, with a getter so it follows the layout data:
|
|
35
|
+
*
|
|
36
|
+
* ```svelte
|
|
37
|
+
* <script lang="ts">
|
|
38
|
+
* import { setRbacContext } from '@anievo-id/rbac-evolution-sveltekit'
|
|
39
|
+
* let { data, children } = $props()
|
|
40
|
+
* setRbacContext(() => data.rbac, { superAdminRoles: ['super-admin'] })
|
|
41
|
+
* </script>
|
|
42
|
+
* ```
|
|
43
|
+
*
|
|
44
|
+
* Must be called during component initialisation (like Svelte's `setContext`).
|
|
45
|
+
*/
|
|
46
|
+
export function setRbacContext(snapshot, options = {}) {
|
|
47
|
+
return setContext(RBAC_KEY, createRbacState(snapshot, options));
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Returns the state set by `setRbacContext()` in a parent component. Call it in a component's `<script>` (during
|
|
51
|
+
* initialisation), then use it anywhere in the component: `{#if rbac.can('articles.edit')}`.
|
|
52
|
+
*
|
|
53
|
+
* Pass your names type to check names at compile time: `getRbacContext<AppRbac>()`.
|
|
54
|
+
*/
|
|
55
|
+
export function getRbacContext() {
|
|
56
|
+
if (!hasContext(RBAC_KEY)) {
|
|
57
|
+
throw new Error('[rbac-evolution] No RBAC context found. Call `setRbacContext(() => data.rbac)` in your root +layout.svelte.');
|
|
58
|
+
}
|
|
59
|
+
return getContext(RBAC_KEY);
|
|
60
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @anievo-id/rbac-evolution-sveltekit
|
|
3
|
+
*
|
|
4
|
+
* Client side of the SvelteKit integration: the RBAC context (Svelte 5 runes), `<Can>` and `<HasRole>`.
|
|
5
|
+
* Client-side checks are for UI only — enforce authorization on the server with
|
|
6
|
+
* `@anievo-id/rbac-evolution-sveltekit/server`.
|
|
7
|
+
*/
|
|
8
|
+
import type { Component } from 'svelte';
|
|
9
|
+
import type { CanProps, HasRoleProps } from './props.js';
|
|
10
|
+
export { createRbacChecker } from './checker.js';
|
|
11
|
+
export type { NameList, RbacChecker, RbacCheckerOptions } from './checker.js';
|
|
12
|
+
export { createRbacState, getRbacContext, RBAC_KEY, setRbacContext } from './context.svelte.js';
|
|
13
|
+
export type { RbacSnapshotSource, RbacStateOptions, SvelteRbac } from './context.svelte.js';
|
|
14
|
+
export type { CheckNames, TypesOf } from './types.js';
|
|
15
|
+
export type { CanProps, HasRoleProps } from './props.js';
|
|
16
|
+
/** Renders `children` when the user has the permission(s), otherwise the `fallback` snippet. See {@link CanProps}. */
|
|
17
|
+
export declare const Can: Component<CanProps>;
|
|
18
|
+
/** Renders `children` when the user has the role(s), otherwise the `fallback` snippet. See {@link HasRoleProps}. */
|
|
19
|
+
export declare const HasRole: Component<HasRoleProps>;
|
|
20
|
+
export type { RbacSnapshot } from '@anievo-id/rbac-evolution';
|
|
21
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,QAAQ,CAAA;AAGvC,OAAO,KAAK,EAAE,QAAQ,EAAE,YAAY,EAAE,MAAM,YAAY,CAAA;AAExD,OAAO,EAAE,iBAAiB,EAAE,MAAM,cAAc,CAAA;AAChD,YAAY,EAAE,QAAQ,EAAE,WAAW,EAAE,kBAAkB,EAAE,MAAM,cAAc,CAAA;AAE7E,OAAO,EAAE,eAAe,EAAE,cAAc,EAAE,QAAQ,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAA;AAC/F,YAAY,EAAE,kBAAkB,EAAE,gBAAgB,EAAE,UAAU,EAAE,MAAM,qBAAqB,CAAA;AAE3F,YAAY,EAAE,UAAU,EAAE,OAAO,EAAE,MAAM,YAAY,CAAA;AACrD,YAAY,EAAE,QAAQ,EAAE,YAAY,EAAE,MAAM,YAAY,CAAA;AAIxD,sHAAsH;AACtH,eAAO,MAAM,GAAG,EAAE,SAAS,CAAC,QAAQ,CAAgB,CAAA;AACpD,oHAAoH;AACpH,eAAO,MAAM,OAAO,EAAE,SAAS,CAAC,YAAY,CAAoB,CAAA;AAEhE,YAAY,EAAE,YAAY,EAAE,MAAM,2BAA2B,CAAA"}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @anievo-id/rbac-evolution-sveltekit
|
|
3
|
+
*
|
|
4
|
+
* Client side of the SvelteKit integration: the RBAC context (Svelte 5 runes), `<Can>` and `<HasRole>`.
|
|
5
|
+
* Client-side checks are for UI only — enforce authorization on the server with
|
|
6
|
+
* `@anievo-id/rbac-evolution-sveltekit/server`.
|
|
7
|
+
*/
|
|
8
|
+
import CanComponent from './Can.svelte';
|
|
9
|
+
import HasRoleComponent from './HasRole.svelte';
|
|
10
|
+
export { createRbacChecker } from './checker.js';
|
|
11
|
+
export { createRbacState, getRbacContext, RBAC_KEY, setRbacContext } from './context.svelte.js';
|
|
12
|
+
// Typed through `CanProps` / `HasRoleProps`, so the declaration files (and the API reference) state the props
|
|
13
|
+
// without a `.svelte` type resolver.
|
|
14
|
+
/** Renders `children` when the user has the permission(s), otherwise the `fallback` snippet. See {@link CanProps}. */
|
|
15
|
+
export const Can = CanComponent;
|
|
16
|
+
/** Renders `children` when the user has the role(s), otherwise the `fallback` snippet. See {@link HasRoleProps}. */
|
|
17
|
+
export const HasRole = HasRoleComponent;
|
package/dist/props.d.ts
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import type { Snippet } from 'svelte';
|
|
2
|
+
import type { NameList } from './checker.js';
|
|
3
|
+
/**
|
|
4
|
+
* Props of `<Can>`. Conditions are ANDed; without any condition nothing passes (deny by default).
|
|
5
|
+
*
|
|
6
|
+
* ```svelte
|
|
7
|
+
* <Can permission="articles.edit">...</Can>
|
|
8
|
+
* <Can anyOf={['articles.edit', 'articles.delete']}>
|
|
9
|
+
* ...
|
|
10
|
+
* {#snippet fallback()}No access{/snippet}
|
|
11
|
+
* </Can>
|
|
12
|
+
* ```
|
|
13
|
+
*/
|
|
14
|
+
export interface CanProps {
|
|
15
|
+
/** The permission, or a list of permissions that are ALL required. */
|
|
16
|
+
permission?: NameList | undefined;
|
|
17
|
+
/** Passes with ANY of these permissions. */
|
|
18
|
+
anyOf?: NameList | undefined;
|
|
19
|
+
/** Passes with ALL of these permissions. */
|
|
20
|
+
allOf?: NameList | undefined;
|
|
21
|
+
/** Invert the check (render `children` when the user does NOT have the permissions). */
|
|
22
|
+
not?: boolean | undefined;
|
|
23
|
+
children?: Snippet | undefined;
|
|
24
|
+
/** Rendered when the check fails. */
|
|
25
|
+
fallback?: Snippet | undefined;
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Props of `<HasRole>`. Conditions are ANDed; without any condition nothing passes (deny by default).
|
|
29
|
+
*
|
|
30
|
+
* ```svelte
|
|
31
|
+
* <HasRole role="admin|editor">...</HasRole>
|
|
32
|
+
* <HasRole allOf={['writer', 'editor']}>...</HasRole>
|
|
33
|
+
* ```
|
|
34
|
+
*/
|
|
35
|
+
export interface HasRoleProps {
|
|
36
|
+
/** The role, or ANY of the roles (`'writer|editor'` or a list). */
|
|
37
|
+
role?: NameList | undefined;
|
|
38
|
+
/** Passes with ANY of these roles. */
|
|
39
|
+
anyOf?: NameList | undefined;
|
|
40
|
+
/** Passes with ALL of these roles. */
|
|
41
|
+
allOf?: NameList | undefined;
|
|
42
|
+
/** Invert the check (render `children` when the user does NOT have the roles). */
|
|
43
|
+
not?: boolean | undefined;
|
|
44
|
+
children?: Snippet | undefined;
|
|
45
|
+
/** Rendered when the check fails. */
|
|
46
|
+
fallback?: Snippet | undefined;
|
|
47
|
+
}
|
|
48
|
+
//# sourceMappingURL=props.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"props.d.ts","sourceRoot":"","sources":["../src/props.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,QAAQ,CAAA;AACrC,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAA;AAE5C;;;;;;;;;;GAUG;AACH,MAAM,WAAW,QAAQ;IACvB,sEAAsE;IACtE,UAAU,CAAC,EAAE,QAAQ,GAAG,SAAS,CAAA;IACjC,4CAA4C;IAC5C,KAAK,CAAC,EAAE,QAAQ,GAAG,SAAS,CAAA;IAC5B,4CAA4C;IAC5C,KAAK,CAAC,EAAE,QAAQ,GAAG,SAAS,CAAA;IAC5B,wFAAwF;IACxF,GAAG,CAAC,EAAE,OAAO,GAAG,SAAS,CAAA;IACzB,QAAQ,CAAC,EAAE,OAAO,GAAG,SAAS,CAAA;IAC9B,qCAAqC;IACrC,QAAQ,CAAC,EAAE,OAAO,GAAG,SAAS,CAAA;CAC/B;AAED;;;;;;;GAOG;AACH,MAAM,WAAW,YAAY;IAC3B,mEAAmE;IACnE,IAAI,CAAC,EAAE,QAAQ,GAAG,SAAS,CAAA;IAC3B,sCAAsC;IACtC,KAAK,CAAC,EAAE,QAAQ,GAAG,SAAS,CAAA;IAC5B,sCAAsC;IACtC,KAAK,CAAC,EAAE,QAAQ,GAAG,SAAS,CAAA;IAC5B,kFAAkF;IAClF,GAAG,CAAC,EAAE,OAAO,GAAG,SAAS,CAAA;IACzB,QAAQ,CAAC,EAAE,OAAO,GAAG,SAAS,CAAA;IAC9B,qCAAqC;IACrC,QAAQ,CAAC,EAAE,OAAO,GAAG,SAAS,CAAA;CAC/B"}
|
package/dist/props.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
import { type DefaultGuardName, type DefaultRbacTypes, type GuardName, type GuardRequirementArgs, type PermissionName, type Rbac, type RbacTypeConfig, type RequirementArgs, type RequirementGuard, type RequirementKind, type RequirementNames, type RoleName, type ScopedGuardName, type SubjectRbac } from '@anievo-id/rbac-evolution';
|
|
2
|
+
import { type RequestEvent } from '@sveltejs/kit';
|
|
3
|
+
import type { TypesOf } from '../types.js';
|
|
4
|
+
export type GuardKind = RequirementKind;
|
|
5
|
+
/** A name, a pipe-separated list (`'edit|delete'` = any of), or an array of names. */
|
|
6
|
+
export type GuardNames = RequirementNames;
|
|
7
|
+
/** Details about a failed check, passed to `onUnauthenticated` / `onForbidden`. */
|
|
8
|
+
export interface GuardContext {
|
|
9
|
+
kind: GuardKind;
|
|
10
|
+
/** Groups of names: every group must pass, a group passes when ANY of its names matches. */
|
|
11
|
+
requirements: string[][];
|
|
12
|
+
}
|
|
13
|
+
/** The body of a failed check: the same as the Express, Hono, Fastify and NestJS packages send. */
|
|
14
|
+
export type RbacErrorBody = {
|
|
15
|
+
error: 'UNAUTHENTICATED';
|
|
16
|
+
message: string;
|
|
17
|
+
} | {
|
|
18
|
+
error: 'FORBIDDEN';
|
|
19
|
+
reason: RequirementKind;
|
|
20
|
+
message: string;
|
|
21
|
+
required?: string[][];
|
|
22
|
+
};
|
|
23
|
+
/**
|
|
24
|
+
* Handles a failed check. It must throw, with SvelteKit's `redirect()` or `error()`:
|
|
25
|
+
* `(event) => redirect(303, `/login?redirectTo=${event.url.pathname}`)`.
|
|
26
|
+
*/
|
|
27
|
+
export type GuardHandler = (event: RequestEvent, context: GuardContext) => never | Promise<never>;
|
|
28
|
+
export interface GuardHandlers {
|
|
29
|
+
/**
|
|
30
|
+
* Called when there is no subject (`event.locals.rbac` is `null`). Wins over `unauthenticatedRedirect`.
|
|
31
|
+
* Default: `error(401, { error: 'UNAUTHENTICATED', message })`.
|
|
32
|
+
*/
|
|
33
|
+
onUnauthenticated?: GuardHandler | undefined;
|
|
34
|
+
/**
|
|
35
|
+
* Called when the subject lacks access. Wins over `forbiddenRedirect`.
|
|
36
|
+
* Default: `error(403, { error: 'FORBIDDEN', reason, message })`.
|
|
37
|
+
*/
|
|
38
|
+
onForbidden?: GuardHandler | undefined;
|
|
39
|
+
/** Redirect guests here (`redirect(303, url)`) instead of the 401 error. Handy for page loads: `'/login'`. */
|
|
40
|
+
unauthenticatedRedirect?: string | undefined;
|
|
41
|
+
/** Redirect users without access here (`redirect(303, url)`) instead of the 403 error. */
|
|
42
|
+
forbiddenRedirect?: string | undefined;
|
|
43
|
+
/**
|
|
44
|
+
* Include the required roles/permissions in the default 403 body (`required`).
|
|
45
|
+
* Default: `false` (like spatie's `display_permission_in_exception`).
|
|
46
|
+
*/
|
|
47
|
+
exposeRequirements?: boolean | undefined;
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* The options every guard takes as its last argument: the handlers plus `guard`. A guard's own handlers win over
|
|
51
|
+
* the defaults of `createGuards()`.
|
|
52
|
+
*/
|
|
53
|
+
export interface RouteGuardOptions extends GuardHandlers {
|
|
54
|
+
/**
|
|
55
|
+
* Check in this guard instead of the request's (`subject.withScope({ guard })`), like spatie's
|
|
56
|
+
* `role:admin,api`. Default: the guard of `rbacHandle()`.
|
|
57
|
+
*/
|
|
58
|
+
guard?: string | undefined;
|
|
59
|
+
}
|
|
60
|
+
export interface PermissionGuardOptions extends RouteGuardOptions {
|
|
61
|
+
/** Pass when the subject has ANY of the permissions (instead of all). Default: `false`. */
|
|
62
|
+
any?: boolean | undefined;
|
|
63
|
+
}
|
|
64
|
+
export interface RoleGuardOptions extends RouteGuardOptions {
|
|
65
|
+
/** Require ALL of the roles (instead of any). Default: `false`. */
|
|
66
|
+
all?: boolean | undefined;
|
|
67
|
+
}
|
|
68
|
+
export type RoleOrPermissionGuardOptions = RouteGuardOptions;
|
|
69
|
+
/**
|
|
70
|
+
* A guard typed with the names `N` it accepts and its options `O`: `(event, ...names, options?)`. It resolves to the
|
|
71
|
+
* subject (`R`) when the check passes, and throws (SvelteKit's `error()` / `redirect()`, or your handler) when it
|
|
72
|
+
* does not. Every name (each part of a `'a|b'` list, each array item) must be one of `N`; with `N = string`, any name
|
|
73
|
+
* is. A call without names, or with options that are not the last argument, is a type error.
|
|
74
|
+
*/
|
|
75
|
+
export type Guard<N extends string, O, R = SubjectRbac> = <const A extends readonly (GuardNames | O)[]>(event: RequestEvent, ...args: A & RequirementArgs<A, N, O>) => Promise<R>;
|
|
76
|
+
/** The guards returned by `createGuards<T>()`, with names narrowed by `T` (see `RbacTypeConfig`). */
|
|
77
|
+
export interface Guards<T extends RbacTypeConfig = DefaultRbacTypes> {
|
|
78
|
+
/** All arguments are required, pipes mean any, `{ any: true }` means any of them. */
|
|
79
|
+
requirePermission: Guard<PermissionName<T>, PermissionGuardOptions, SubjectRbac<T>>;
|
|
80
|
+
/** Any of the roles, `{ all: true }` for all of them. */
|
|
81
|
+
requireRole: Guard<RoleName<T>, RoleGuardOptions, SubjectRbac<T>>;
|
|
82
|
+
/** Any of the names, as a role OR a permission. */
|
|
83
|
+
requireRoleOrPermission: Guard<PermissionName<T> | RoleName<T>, RoleOrPermissionGuardOptions, SubjectRbac<T>>;
|
|
84
|
+
/** spatie v8.5 `canAny()`: requires ANY of the listed permissions. */
|
|
85
|
+
canAny: Guard<PermissionName<T>, RouteGuardOptions, SubjectRbac<T>>;
|
|
86
|
+
/** spatie v8.5 `canAll()`: requires EVERY listed entry; a `'a|b'` entry still means "a or b". */
|
|
87
|
+
canAll: Guard<PermissionName<T>, RouteGuardOptions, SubjectRbac<T>>;
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* A guard of `createGuards<T, G>()` when `T` has per-guard names (`RbacTypeConfig['guards']`): like {@link Guard},
|
|
91
|
+
* but the names are those of the guard the call checks in, its `{ guard }` option or else `G` (the guard of
|
|
92
|
+
* `rbacHandle()`), and the subject it returns is typed for that guard.
|
|
93
|
+
*/
|
|
94
|
+
export type ScopedGuard<T extends RbacTypeConfig, G extends string, K extends GuardKind, O> = <const A extends readonly (GuardNames | O)[]>(event: RequestEvent, ...args: A & GuardRequirementArgs<A, T, K, G, O>) => Promise<SubjectRbac<T, ScopedGuardName<T, RequirementGuard<A, G>>>>;
|
|
95
|
+
/** The guards returned by `createGuards<T, G>()` when `T` has per-guard names (see {@link ScopedGuard}). */
|
|
96
|
+
export interface ScopedGuards<T extends RbacTypeConfig, G extends string = DefaultGuardName<T>> {
|
|
97
|
+
requirePermission: ScopedGuard<T, G, 'permission', PermissionGuardOptions>;
|
|
98
|
+
requireRole: ScopedGuard<T, G, 'role', RoleGuardOptions>;
|
|
99
|
+
requireRoleOrPermission: ScopedGuard<T, G, 'role_or_permission', RoleOrPermissionGuardOptions>;
|
|
100
|
+
canAny: ScopedGuard<T, G, 'permission', RouteGuardOptions>;
|
|
101
|
+
canAll: ScopedGuard<T, G, 'permission', RouteGuardOptions>;
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* What `createGuards<T, G>()` returns: {@link Guards} for a config without per-guard names, and
|
|
105
|
+
* {@link ScopedGuards} for one with `guards`.
|
|
106
|
+
*/
|
|
107
|
+
export type GuardsFor<T extends RbacTypeConfig = DefaultRbacTypes, G extends string = DefaultGuardName<T>> = T extends {
|
|
108
|
+
guards: object;
|
|
109
|
+
} ? ScopedGuards<T, G> : Guards<T>;
|
|
110
|
+
/**
|
|
111
|
+
* Builds the guards with shared defaults, e.g. redirects for page loads:
|
|
112
|
+
*
|
|
113
|
+
* ```ts
|
|
114
|
+
* // src/lib/server/guards.ts
|
|
115
|
+
* export const { requirePermission, requireRole } = createGuards<AppRbac>({ unauthenticatedRedirect: '/login' })
|
|
116
|
+
*
|
|
117
|
+
* // src/routes/admin/+page.server.ts
|
|
118
|
+
* export const load = async (event) => {
|
|
119
|
+
* await requireRole(event, 'admin')
|
|
120
|
+
* }
|
|
121
|
+
* ```
|
|
122
|
+
*
|
|
123
|
+
* Pass the same type argument as `createRbac<AppRbac>()` (or `typeof rbac`) to check names at compile time. With
|
|
124
|
+
* per-guard names, `G` is the guard of `rbacHandle()` (default: the default guard): `createGuards<AppRbac, 'api'>()`.
|
|
125
|
+
* It is a type only; the hook's `guard` still decides at runtime.
|
|
126
|
+
*/
|
|
127
|
+
export declare function createGuards<T extends RbacTypeConfig | Rbac<RbacTypeConfig> = DefaultRbacTypes, G extends GuardName<TypesOf<T>> = DefaultGuardName<TypesOf<T>> & GuardName<TypesOf<T>>>(defaults?: GuardHandlers): GuardsFor<TypesOf<T>, G>;
|
|
128
|
+
/** {@link Guards.requirePermission} with the default handlers (401 / 403 errors). Any name. */
|
|
129
|
+
export declare const requirePermission: Guard<string, PermissionGuardOptions>;
|
|
130
|
+
/** {@link Guards.requireRole} with the default handlers (401 / 403 errors). Any name. */
|
|
131
|
+
export declare const requireRole: Guard<string, RoleGuardOptions>;
|
|
132
|
+
/** {@link Guards.requireRoleOrPermission} with the default handlers (401 / 403 errors). Any name. */
|
|
133
|
+
export declare const requireRoleOrPermission: Guard<string, RoleOrPermissionGuardOptions>;
|
|
134
|
+
/** {@link Guards.canAny} with the default handlers (401 / 403 errors). Any name. */
|
|
135
|
+
export declare const canAny: Guard<string, RouteGuardOptions>;
|
|
136
|
+
/** {@link Guards.canAll} with the default handlers (401 / 403 errors). Any name. */
|
|
137
|
+
export declare const canAll: Guard<string, RouteGuardOptions>;
|
|
138
|
+
//# sourceMappingURL=guards.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"guards.d.ts","sourceRoot":"","sources":["../../src/server/guards.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,KAAK,gBAAgB,EACrB,KAAK,gBAAgB,EACrB,KAAK,SAAS,EACd,KAAK,oBAAoB,EACzB,KAAK,cAAc,EAEnB,KAAK,IAAI,EAET,KAAK,cAAc,EACnB,KAAK,eAAe,EACpB,KAAK,gBAAgB,EACrB,KAAK,eAAe,EACpB,KAAK,gBAAgB,EAErB,KAAK,QAAQ,EAIb,KAAK,eAAe,EAEpB,KAAK,WAAW,EAEjB,MAAM,2BAA2B,CAAA;AAClC,OAAO,EAAgC,KAAK,YAAY,EAAE,MAAM,eAAe,CAAA;AAC/E,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,aAAa,CAAA;AAG1C,MAAM,MAAM,SAAS,GAAG,eAAe,CAAA;AAEvC,sFAAsF;AACtF,MAAM,MAAM,UAAU,GAAG,gBAAgB,CAAA;AAEzC,mFAAmF;AACnF,MAAM,WAAW,YAAY;IAC3B,IAAI,EAAE,SAAS,CAAA;IACf,4FAA4F;IAC5F,YA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,CAAC,SAAS,SAAS,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,GAAG,gBAAgB,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,GAAG,SAAS,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,EACtF,QAAQ,GAAE,aAAkB,GAAG,SAAS,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CA2DxD;AAID,+FAA+F;AAC/F,eAAO,MAAM,iBAAiB,EAAE,KAAK,CAAC,MAAM,EAAE,sBAAsB,CAAmC,CAAA;AACvG,yFAAyF;AACzF,eAAO,MAAM,WAAW,EAAE,KAAK,CAAC,MAAM,EAAE,gBAAgB,CAA6B,CAAA;AACrF,qGAAqG;AACrG,eAAO,MAAM,uBAAuB,EAAE,KAAK,CAAC,MAAM,EAAE,4BAA4B,CAAyC,CAAA;AACzH,oFAAoF;AACpF,eAAO,MAAM,MAAM,EAAE,KAAK,CAAC,MAAM,EAAE,iBAAiB,CAAwB,CAAA;AAC5E,oFAAoF;AACpF,eAAO,MAAM,MAAM,EAAE,KAAK,CAAC,MAAM,EAAE,iBAAiB,CAAwB,CAAA"}
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
import { permissionRequirement, REQUIREMENT_MESSAGES, roleOrPermissionRequirement, roleRequirement, satisfiesRequirement, splitRequirementArgs, UNAUTHENTICATED_MESSAGE, } from '@anievo-id/rbac-evolution';
|
|
2
|
+
import { error, isHttpError, redirect } from '@sveltejs/kit';
|
|
3
|
+
import { getRbac } from './handle.js';
|
|
4
|
+
/**
|
|
5
|
+
* Throws SvelteKit's `error()` with `body`. SvelteKit 3 takes `error(status, message, properties)` (and deprecates
|
|
6
|
+
* the body form); SvelteKit 2 only `error(status, body)`, and would drop the properties of the 3-argument form. So
|
|
7
|
+
* try that form first, and keep its error only when the properties made it into the body.
|
|
8
|
+
*/
|
|
9
|
+
function fail(status, body) {
|
|
10
|
+
const { message, ...properties } = body;
|
|
11
|
+
try {
|
|
12
|
+
;
|
|
13
|
+
error(status, message, properties);
|
|
14
|
+
}
|
|
15
|
+
catch (thrown) {
|
|
16
|
+
if (isHttpError(thrown) && thrown.body.error === body.error)
|
|
17
|
+
throw thrown;
|
|
18
|
+
}
|
|
19
|
+
// `App.Error` may be extended by the app with required fields; the body is ours.
|
|
20
|
+
return error(status, body);
|
|
21
|
+
}
|
|
22
|
+
/** The first layer (a guard's own options, then the defaults) that handles the failure decides. */
|
|
23
|
+
async function handleFailure(event, context, layers, unauthenticated) {
|
|
24
|
+
for (const layer of layers) {
|
|
25
|
+
const handler = unauthenticated ? layer.onUnauthenticated : layer.onForbidden;
|
|
26
|
+
if (handler) {
|
|
27
|
+
await handler(event, context);
|
|
28
|
+
break; // A handler that returned instead of throwing: fall back to the error below.
|
|
29
|
+
}
|
|
30
|
+
const location = unauthenticated ? layer.unauthenticatedRedirect : layer.forbiddenRedirect;
|
|
31
|
+
if (location !== undefined)
|
|
32
|
+
redirect(303, location);
|
|
33
|
+
}
|
|
34
|
+
if (unauthenticated)
|
|
35
|
+
return fail(401, { error: 'UNAUTHENTICATED', message: UNAUTHENTICATED_MESSAGE });
|
|
36
|
+
const expose = layers.map((layer) => layer.exposeRequirements).find((value) => value !== undefined) ?? false;
|
|
37
|
+
return fail(403, {
|
|
38
|
+
error: 'FORBIDDEN',
|
|
39
|
+
reason: context.kind,
|
|
40
|
+
message: REQUIREMENT_MESSAGES[context.kind],
|
|
41
|
+
...(expose && { required: context.requirements }),
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Builds the guards with shared defaults, e.g. redirects for page loads:
|
|
46
|
+
*
|
|
47
|
+
* ```ts
|
|
48
|
+
* // src/lib/server/guards.ts
|
|
49
|
+
* export const { requirePermission, requireRole } = createGuards<AppRbac>({ unauthenticatedRedirect: '/login' })
|
|
50
|
+
*
|
|
51
|
+
* // src/routes/admin/+page.server.ts
|
|
52
|
+
* export const load = async (event) => {
|
|
53
|
+
* await requireRole(event, 'admin')
|
|
54
|
+
* }
|
|
55
|
+
* ```
|
|
56
|
+
*
|
|
57
|
+
* Pass the same type argument as `createRbac<AppRbac>()` (or `typeof rbac`) to check names at compile time. With
|
|
58
|
+
* per-guard names, `G` is the guard of `rbacHandle()` (default: the default guard): `createGuards<AppRbac, 'api'>()`.
|
|
59
|
+
* It is a type only; the hook's `guard` still decides at runtime.
|
|
60
|
+
*/
|
|
61
|
+
export function createGuards(defaults = {}) {
|
|
62
|
+
// Async, so an empty requirement (TypeError) rejects the returned promise instead of throwing synchronously.
|
|
63
|
+
async function enforce(event, build, options = {}) {
|
|
64
|
+
const requirement = build();
|
|
65
|
+
const context = { kind: requirement.kind, requirements: requirement.requirements };
|
|
66
|
+
const layers = [options, defaults];
|
|
67
|
+
const subject = getRbac(event);
|
|
68
|
+
if (subject === null)
|
|
69
|
+
return handleFailure(event, context, layers, true);
|
|
70
|
+
const scoped = options.guard === undefined ? subject : subject.withScope({ guard: options.guard });
|
|
71
|
+
if (await satisfiesRequirement(scoped, requirement))
|
|
72
|
+
return scoped;
|
|
73
|
+
return handleFailure(event, context, layers, false);
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* Requires permissions, like spatie's `permission:` middleware.
|
|
77
|
+
*
|
|
78
|
+
* - `requirePermission(event, 'articles.edit')`
|
|
79
|
+
* - `requirePermission(event, 'articles.edit|articles.delete')` — any of them
|
|
80
|
+
* - `requirePermission(event, 'articles.edit', 'articles.publish')` — all of them
|
|
81
|
+
* - `requirePermission(event, 'a', 'b', { any: true })` — any of them
|
|
82
|
+
*/
|
|
83
|
+
function requirePermission(event, ...args) {
|
|
84
|
+
const { names, options } = splitRequirementArgs(args);
|
|
85
|
+
return enforce(event, () => permissionRequirement(names, options), options);
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* Requires roles, like spatie's `role:` middleware.
|
|
89
|
+
*
|
|
90
|
+
* - `requireRole(event, 'admin')`, `requireRole(event, 'admin|editor')`, `requireRole(event, 'admin', 'editor')` — any
|
|
91
|
+
* - `requireRole(event, 'admin', 'editor', { all: true })` — all of them
|
|
92
|
+
*/
|
|
93
|
+
function requireRole(event, ...args) {
|
|
94
|
+
const { names, options } = splitRequirementArgs(args);
|
|
95
|
+
return enforce(event, () => roleRequirement(names, options), options);
|
|
96
|
+
}
|
|
97
|
+
/** Passes with ANY of the names as a role OR a permission, like spatie's `role_or_permission:` middleware. */
|
|
98
|
+
function requireRoleOrPermission(event, ...args) {
|
|
99
|
+
const { names, options } = splitRequirementArgs(args);
|
|
100
|
+
return enforce(event, () => roleOrPermissionRequirement(names), options);
|
|
101
|
+
}
|
|
102
|
+
/** spatie v8.5 `canAny()`: passes with ANY of the listed permissions. */
|
|
103
|
+
function canAny(event, ...args) {
|
|
104
|
+
const { names, options } = splitRequirementArgs(args);
|
|
105
|
+
return enforce(event, () => permissionRequirement(names, { any: true }), options);
|
|
106
|
+
}
|
|
107
|
+
/** spatie v8.5 `canAll()`: requires EVERY listed entry. A `'a|b'` entry still means "a or b". */
|
|
108
|
+
function canAll(event, ...args) {
|
|
109
|
+
const { names, options } = splitRequirementArgs(args);
|
|
110
|
+
return enforce(event, () => permissionRequirement(names), options);
|
|
111
|
+
}
|
|
112
|
+
// The untyped functions above take any spread of names; the typed signature is only the public face.
|
|
113
|
+
return { requirePermission, requireRole, requireRoleOrPermission, canAny, canAll };
|
|
114
|
+
}
|
|
115
|
+
const defaultGuards = createGuards();
|
|
116
|
+
/** {@link Guards.requirePermission} with the default handlers (401 / 403 errors). Any name. */
|
|
117
|
+
export const requirePermission = defaultGuards.requirePermission;
|
|
118
|
+
/** {@link Guards.requireRole} with the default handlers (401 / 403 errors). Any name. */
|
|
119
|
+
export const requireRole = defaultGuards.requireRole;
|
|
120
|
+
/** {@link Guards.requireRoleOrPermission} with the default handlers (401 / 403 errors). Any name. */
|
|
121
|
+
export const requireRoleOrPermission = defaultGuards.requireRoleOrPermission;
|
|
122
|
+
/** {@link Guards.canAny} with the default handlers (401 / 403 errors). Any name. */
|
|
123
|
+
export const canAny = defaultGuards.canAny;
|
|
124
|
+
/** {@link Guards.canAll} with the default handlers (401 / 403 errors). Any name. */
|
|
125
|
+
export const canAll = defaultGuards.canAll;
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
import type { CheckGuard, DefaultGuardName, DefaultRbacTypes, GuardOptions, PermissionName, Rbac, RbacSnapshot, RbacTypeConfig, ScopedGuardName, Subject, SubjectRbac, TeamId } from '@anievo-id/rbac-evolution';
|
|
2
|
+
import type { RequestEvent } from '@sveltejs/kit';
|
|
3
|
+
import type { TypesOf } from '../types.js';
|
|
4
|
+
type MaybePromise<T> = T | Promise<T>;
|
|
5
|
+
/**
|
|
6
|
+
* The `handle` hook `rbacHandle()` returns. It fits SvelteKit's `Handle` (exported by `@sveltejs/kit` in SvelteKit 2
|
|
7
|
+
* and by `@sveltejs/kit/hooks` in SvelteKit 3), so export it as `handle` or pass it to `sequence()`.
|
|
8
|
+
*/
|
|
9
|
+
export type RbacHandle = (input: {
|
|
10
|
+
event: RequestEvent;
|
|
11
|
+
resolve: (event: RequestEvent) => MaybePromise<Response>;
|
|
12
|
+
}) => Promise<Response>;
|
|
13
|
+
/**
|
|
14
|
+
* What `rbacHandle()` puts on `event.locals`. Extend `App.Locals` with it in `src/app.d.ts`:
|
|
15
|
+
*
|
|
16
|
+
* ```ts
|
|
17
|
+
* import type { RbacLocals } from '@anievo-id/rbac-evolution-sveltekit/server'
|
|
18
|
+
* import type { AppRbac } from '../lib/server/rbac'
|
|
19
|
+
*
|
|
20
|
+
* declare global {
|
|
21
|
+
* namespace App {
|
|
22
|
+
* interface Locals extends RbacLocals<AppRbac> {}
|
|
23
|
+
* }
|
|
24
|
+
* }
|
|
25
|
+
* ```
|
|
26
|
+
*
|
|
27
|
+
* `T` is a names type like `AppRbac` (or `typeof rbac`); without it, any name. With per-guard names, `G` is the
|
|
28
|
+
* guard of the hook (its `guard` option): the default guard's names by default.
|
|
29
|
+
*/
|
|
30
|
+
export interface RbacLocals<T extends RbacTypeConfig | Rbac<RbacTypeConfig> = DefaultRbacTypes, G extends string = DefaultGuardName<TypesOf<T>>> {
|
|
31
|
+
/** Roles & permissions of the current subject. `null` for guests. */
|
|
32
|
+
rbac: SubjectRbac<TypesOf<T>, ScopedGuardName<TypesOf<T>, G>> | null;
|
|
33
|
+
}
|
|
34
|
+
/** The part of a SvelteKit `RequestEvent` the server helpers read. Every `load`, action and endpoint event has it. */
|
|
35
|
+
export interface RbacEvent {
|
|
36
|
+
locals: object;
|
|
37
|
+
}
|
|
38
|
+
export interface RbacHandleOptions<T extends RbacTypeConfig = DefaultRbacTypes, G extends string = DefaultGuardName<T>> {
|
|
39
|
+
/** The RBAC engine created with `createRbac(...)`. Its typed names flow into `event.locals.rbac`. */
|
|
40
|
+
rbac: Rbac<T>;
|
|
41
|
+
/**
|
|
42
|
+
* Resolves the authenticated subject for this request (e.g. from `event.locals.user` set by your auth hook, or a
|
|
43
|
+
* session cookie). Return `null` / `undefined` for guests.
|
|
44
|
+
*/
|
|
45
|
+
getSubject: (event: RequestEvent) => MaybePromise<Subject | null | undefined>;
|
|
46
|
+
/**
|
|
47
|
+
* Guard name (e.g. `web` or `api`). Defaults to the engine's `defaultGuard`. With per-guard names, it must be one
|
|
48
|
+
* of the typed guards (checked by `rbacHandle()`).
|
|
49
|
+
*/
|
|
50
|
+
guard?: G | undefined;
|
|
51
|
+
/** Resolves the current team (only when the engine was created with `teams: true`). */
|
|
52
|
+
team?: ((event: RequestEvent) => MaybePromise<TeamId | undefined>) | undefined;
|
|
53
|
+
}
|
|
54
|
+
/** Thrown when a helper runs without `rbacHandle()` in `src/hooks.server.ts`. */
|
|
55
|
+
export declare class RbacHandleMissingError extends Error {
|
|
56
|
+
readonly code = "RBAC_HANDLE_MISSING";
|
|
57
|
+
constructor();
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* A SvelteKit `handle` hook that resolves the current subject once per request and sets `event.locals.rbac`
|
|
61
|
+
* (a `SubjectRbac`, or `null` for guests).
|
|
62
|
+
*
|
|
63
|
+
* ```ts
|
|
64
|
+
* // src/hooks.server.ts
|
|
65
|
+
* import { sequence } from '@sveltejs/kit/hooks'
|
|
66
|
+
* import { rbacHandle } from '@anievo-id/rbac-evolution-sveltekit/server'
|
|
67
|
+
*
|
|
68
|
+
* export const handle = sequence(
|
|
69
|
+
* authHandle, // yours: sets event.locals.user
|
|
70
|
+
* rbacHandle({ rbac, getSubject: (event) => (event.locals.user ? { type: 'user', id: event.locals.user.id } : null) }),
|
|
71
|
+
* )
|
|
72
|
+
* ```
|
|
73
|
+
*
|
|
74
|
+
* Nothing is loaded from the database here: `rbac.for(subject)` is lazy, so only the checks a request makes hit
|
|
75
|
+
* the adapter (or the cache).
|
|
76
|
+
*/
|
|
77
|
+
export declare function rbacHandle<T extends RbacTypeConfig = DefaultRbacTypes, G extends string = DefaultGuardName<T>>(options: RbacHandleOptions<T, G> & (T extends {
|
|
78
|
+
guards: object;
|
|
79
|
+
} ? GuardOptions<CheckGuard<T, G>> : unknown)): RbacHandle;
|
|
80
|
+
/** Reads `event.locals.rbac`, set by `rbacHandle()`. Throws {@link RbacHandleMissingError} when the hook is missing. */
|
|
81
|
+
export declare function getRbac<T extends RbacTypeConfig | Rbac<RbacTypeConfig> = DefaultRbacTypes, G extends string = DefaultGuardName<TypesOf<T>>>(event: RbacEvent): SubjectRbac<TypesOf<T>, ScopedGuardName<TypesOf<T>, G>> | null;
|
|
82
|
+
/** Options of {@link getSnapshot}. */
|
|
83
|
+
export interface GetSnapshotOptions<N extends string = string> {
|
|
84
|
+
/**
|
|
85
|
+
* Permission names to run the engine's `before` hook for. Those it denies are sent as `denied`, and the client
|
|
86
|
+
* (`setRbacContext()`, `<Can>`) treats them as not allowed, super-admins included.
|
|
87
|
+
*/
|
|
88
|
+
checkBefore?: readonly N[] | undefined;
|
|
89
|
+
/** Make the snapshot in this guard instead of the hook's (`subject.withScope({ guard })`). */
|
|
90
|
+
guard?: string | undefined;
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* The current subject's `{ roles, permissions }` (plus `denied` with `checkBefore`), or `null` for guests. Return it
|
|
94
|
+
* from the root `+layout.server.ts` and pass it to `setRbacContext()`:
|
|
95
|
+
*
|
|
96
|
+
* ```ts
|
|
97
|
+
* // src/routes/+layout.server.ts
|
|
98
|
+
* export const load = async (event) => ({ rbac: await getSnapshot(event, { checkBefore: ['billing.manage'] }) })
|
|
99
|
+
* ```
|
|
100
|
+
*
|
|
101
|
+
* `getSnapshot<AppRbac>(event, ...)` checks the `checkBefore` names.
|
|
102
|
+
*/
|
|
103
|
+
export declare function getSnapshot<T extends RbacTypeConfig | Rbac<RbacTypeConfig> = DefaultRbacTypes, G extends string = DefaultGuardName<TypesOf<T>>>(event: RbacEvent, options?: GetSnapshotOptions<PermissionName<TypesOf<T>, G>>): Promise<RbacSnapshot | null>;
|
|
104
|
+
export {};
|
|
105
|
+
//# sourceMappingURL=handle.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"handle.d.ts","sourceRoot":"","sources":["../../src/server/handle.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,UAAU,EACV,gBAAgB,EAChB,gBAAgB,EAChB,YAAY,EACZ,cAAc,EACd,IAAI,EACJ,YAAY,EACZ,cAAc,EACd,eAAe,EACf,OAAO,EACP,WAAW,EACX,MAAM,EACP,MAAM,2BAA2B,CAAA;AAClC,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,eAAe,CAAA;AACjD,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,aAAa,CAAA;AAE1C,KAAK,YAAY,CAAC,CAAC,IAAI,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,CAAA;AAErC;;;GAGG;AACH,MAAM,MAAM,UAAU,GAAG,CAAC,KAAK,EAAE;IAC/B,KAAK,EAAE,YAAY,CAAA;IACnB,OAAO,EAAE,CAAC,KAAK,EAAE,YAAY,KAAK,YAAY,CAAC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issingError extends Error {
|
|
3
|
+
code = 'RBAC_HANDLE_MISSING';
|
|
4
|
+
constructor() {
|
|
5
|
+
super('`event.locals.rbac` is not set. Add `rbacHandle()` to `handle` in src/hooks.server.ts.');
|
|
6
|
+
this.name = 'RbacHandleMissingError';
|
|
7
|
+
}
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* A SvelteKit `handle` hook that resolves the current subject once per request and sets `event.locals.rbac`
|
|
11
|
+
* (a `SubjectRbac`, or `null` for guests).
|
|
12
|
+
*
|
|
13
|
+
* ```ts
|
|
14
|
+
* // src/hooks.server.ts
|
|
15
|
+
* import { sequence } from '@sveltejs/kit/hooks'
|
|
16
|
+
* import { rbacHandle } from '@anievo-id/rbac-evolution-sveltekit/server'
|
|
17
|
+
*
|
|
18
|
+
* export const handle = sequence(
|
|
19
|
+
* authHandle, // yours: sets event.locals.user
|
|
20
|
+
* rbacHandle({ rbac, getSubject: (event) => (event.locals.user ? { type: 'user', id: event.locals.user.id } : null) }),
|
|
21
|
+
* )
|
|
22
|
+
* ```
|
|
23
|
+
*
|
|
24
|
+
* Nothing is loaded from the database here: `rbac.for(subject)` is lazy, so only the checks a request makes hit
|
|
25
|
+
* the adapter (or the cache).
|
|
26
|
+
*/
|
|
27
|
+
export function rbacHandle(options) {
|
|
28
|
+
const { getSubject, team } = options;
|
|
29
|
+
const guard = options.guard;
|
|
30
|
+
// `T` only narrows the names on `event.locals.rbac`; the subject is the same object either way.
|
|
31
|
+
const rbac = options.rbac;
|
|
32
|
+
return async ({ event, resolve }) => {
|
|
33
|
+
const subject = await getSubject(event);
|
|
34
|
+
let value = null;
|
|
35
|
+
if (subject) {
|
|
36
|
+
const teamId = team ? await team(event) : undefined;
|
|
37
|
+
value = rbac.for(subject, {
|
|
38
|
+
...(guard !== undefined && { guard }),
|
|
39
|
+
...(teamId !== undefined && { team: teamId }),
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
;
|
|
43
|
+
event.locals.rbac = value;
|
|
44
|
+
return resolve(event);
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
/** Reads `event.locals.rbac`, set by `rbacHandle()`. Throws {@link RbacHandleMissingError} when the hook is missing. */
|
|
48
|
+
export function getRbac(event) {
|
|
49
|
+
const value = event.locals.rbac;
|
|
50
|
+
if (value === undefined)
|
|
51
|
+
throw new RbacHandleMissingError();
|
|
52
|
+
return value;
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* The current subject's `{ roles, permissions }` (plus `denied` with `checkBefore`), or `null` for guests. Return it
|
|
56
|
+
* from the root `+layout.server.ts` and pass it to `setRbacContext()`:
|
|
57
|
+
*
|
|
58
|
+
* ```ts
|
|
59
|
+
* // src/routes/+layout.server.ts
|
|
60
|
+
* export const load = async (event) => ({ rbac: await getSnapshot(event, { checkBefore: ['billing.manage'] }) })
|
|
61
|
+
* ```
|
|
62
|
+
*
|
|
63
|
+
* `getSnapshot<AppRbac>(event, ...)` checks the `checkBefore` names.
|
|
64
|
+
*/
|
|
65
|
+
export async function getSnapshot(event, options = {}) {
|
|
66
|
+
const subject = getRbac(event);
|
|
67
|
+
if (subject === null)
|
|
68
|
+
return null;
|
|
69
|
+
const scoped = options.guard === undefined ? subject : subject.withScope({ guard: options.guard });
|
|
70
|
+
return scoped.snapshot(options.checkBefore === undefined ? {} : { checkBefore: options.checkBefore });
|
|
71
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @anievo-id/rbac-evolution-sveltekit/server
|
|
3
|
+
*
|
|
4
|
+
* Server side of the SvelteKit integration: the `handle` hook, the guards for `load` functions, form actions and
|
|
5
|
+
* `+server.ts` endpoints, and the snapshot for the client. Import it from server-only modules
|
|
6
|
+
* (`hooks.server.ts`, `+page.server.ts`, `+layout.server.ts`, `+server.ts`, `$lib/server/*`).
|
|
7
|
+
*/
|
|
8
|
+
export { getRbac, getSnapshot, RbacHandleMissingError, rbacHandle } from './handle.js';
|
|
9
|
+
export type { GetSnapshotOptions, RbacEvent, RbacHandle, RbacHandleOptions, RbacLocals } from './handle.js';
|
|
10
|
+
export { canAll, canAny, createGuards, requirePermission, requireRole, requireRoleOrPermission, } from './guards.js';
|
|
11
|
+
export type { Guard, GuardContext, GuardHandler, GuardHandlers, GuardKind, GuardNames, Guards, GuardsFor, PermissionGuardOptions, RbacErrorBody, RoleGuardOptions, RoleOrPermissionGuardOptions, RouteGuardOptions, ScopedGuard, ScopedGuards, } from './guards.js';
|
|
12
|
+
export type { TypesOf } from '../types.js';
|
|
13
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/server/index.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,EAAE,OAAO,EAAE,WAAW,EAAE,sBAAsB,EAAE,UAAU,EAAE,MAAM,aAAa,CAAA;AACtF,YAAY,EAAE,kBAAkB,EAAE,SAAS,EAAE,UAAU,EAAE,iBAAiB,EAAE,UAAU,EAAE,MAAM,aAAa,CAAA;AAE3G,OAAO,EACL,MAAM,EACN,MAAM,EACN,YAAY,EACZ,iBAAiB,EACjB,WAAW,EACX,uBAAuB,GACxB,MAAM,aAAa,CAAA;AACpB,YAAY,EACV,KAAK,EACL,YAAY,EACZ,YAAY,EACZ,aAAa,EACb,SAAS,EACT,UAAU,EACV,MAAM,EACN,SAAS,EACT,sBAAsB,EACtB,aAAa,EACb,gBAAgB,EAChB,4BAA4B,EAC5B,iBAAiB,EACjB,WAAW,EACX,YAAY,GACb,MAAM,aAAa,CAAA;AAEpB,YAAY,EAAE,OAAO,EAAE,MAAM,aAAa,CAAA"}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @anievo-id/rbac-evolution-sveltekit/server
|
|
3
|
+
*
|
|
4
|
+
* Server side of the SvelteKit integration: the `handle` hook, the guards for `load` functions, form actions and
|
|
5
|
+
* `+server.ts` endpoints, and the snapshot for the client. Import it from server-only modules
|
|
6
|
+
* (`hooks.server.ts`, `+page.server.ts`, `+layout.server.ts`, `+server.ts`, `$lib/server/*`).
|
|
7
|
+
*/
|
|
8
|
+
export { getRbac, getSnapshot, RbacHandleMissingError, rbacHandle } from './handle.js';
|
|
9
|
+
export { canAll, canAny, createGuards, requirePermission, requireRole, requireRoleOrPermission, } from './guards.js';
|
package/dist/types.d.ts
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { CheckRequirementName, Rbac, RbacTypeConfig } from '@anievo-id/rbac-evolution';
|
|
2
|
+
/** The type configuration of `T`: `T` itself, or the `X` of an `Rbac<X>` engine (`typeof rbac`). */
|
|
3
|
+
export type TypesOf<T> = T extends Rbac<infer X> ? X : T extends RbacTypeConfig ? T : never;
|
|
4
|
+
/**
|
|
5
|
+
* Checks a name, a `'a|b'` pipe list or an array of them against the names `N`.
|
|
6
|
+
* Any name passes when `N` is `string` (an untyped engine).
|
|
7
|
+
*/
|
|
8
|
+
export type CheckNames<S, N extends string> = S extends string ? CheckRequirementName<S, N> : S extends readonly string[] ? {
|
|
9
|
+
[K in keyof S]: S[K] extends string ? CheckRequirementName<S[K], N> : S[K];
|
|
10
|
+
} : S;
|
|
11
|
+
//# sourceMappingURL=types.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,oBAAoB,EAAE,IAAI,EAAE,cAAc,EAAE,MAAM,2BAA2B,CAAA;AAE3F,oGAAoG;AACpG,MAAM,MAAM,OAAO,CAAC,CAAC,IAAI,CAAC,SAAS,IAAI,CAAC,MAAM,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC,SAAS,cAAc,GAAG,CAAC,GAAG,KAAK,CAAA;AAE3F;;;GAGG;AACH,MAAM,MAAM,UAAU,CAAC,CAAC,EAAE,CAAC,SAAS,MAAM,IAAI,CAAC,SAAS,MAAM,GAC1D,oBAAoB,CAAC,CAAC,EAAE,CAAC,CAAC,GAC1B,CAAC,SAAS,SAAS,MAAM,EAAE,GACzB;KAAG,CAAC,IAAI,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,SAAS,MAAM,GAAG,oBAAoB,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;CAAE,GAC9E,CAAC,CAAA"}
|
package/dist/types.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
package/package.json
CHANGED
|
@@ -1,6 +1,77 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@anievo-id/rbac-evolution-sveltekit",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "1.4.0",
|
|
4
|
+
"description": "SvelteKit integration for rbac-evolution: a handle hook, guards for loads, form actions & endpoints, and Svelte 5 components.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"author": "AniEvo-ID (https://github.com/AniEvo-ID)",
|
|
7
|
+
"homepage": "https://creation.anievo.id/rbac-evolution/frameworks/sveltekit",
|
|
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/sveltekit"
|
|
16
|
+
},
|
|
17
|
+
"keywords": [
|
|
18
|
+
"rbac",
|
|
19
|
+
"permissions",
|
|
20
|
+
"roles",
|
|
21
|
+
"authorization",
|
|
22
|
+
"svelte",
|
|
23
|
+
"sveltekit",
|
|
24
|
+
"svelte5",
|
|
25
|
+
"runes"
|
|
26
|
+
],
|
|
27
|
+
"sideEffects": false,
|
|
28
|
+
"svelte": "./dist/index.js",
|
|
29
|
+
"types": "./dist/index.d.ts",
|
|
30
|
+
"exports": {
|
|
31
|
+
".": {
|
|
32
|
+
"types": "./dist/index.d.ts",
|
|
33
|
+
"svelte": "./dist/index.js",
|
|
34
|
+
"default": "./dist/index.js"
|
|
35
|
+
},
|
|
36
|
+
"./server": {
|
|
37
|
+
"types": "./dist/server/index.d.ts",
|
|
38
|
+
"default": "./dist/server/index.js"
|
|
39
|
+
},
|
|
40
|
+
"./package.json": "./package.json"
|
|
41
|
+
},
|
|
42
|
+
"files": [
|
|
43
|
+
"dist"
|
|
44
|
+
],
|
|
45
|
+
"publishConfig": {
|
|
46
|
+
"access": "public"
|
|
47
|
+
},
|
|
48
|
+
"dependencies": {
|
|
49
|
+
"@anievo-id/rbac-evolution": "^1.4.0"
|
|
50
|
+
},
|
|
51
|
+
"peerDependencies": {
|
|
52
|
+
"@sveltejs/kit": ">=2",
|
|
53
|
+
"svelte": ">=5"
|
|
54
|
+
},
|
|
55
|
+
"devDependencies": {
|
|
56
|
+
"@sveltejs/kit": "^2.70.4",
|
|
57
|
+
"@sveltejs/package": "^2.5.8",
|
|
58
|
+
"@sveltejs/vite-plugin-svelte": "^4.0.4",
|
|
59
|
+
"@testing-library/svelte": "^5.4.2",
|
|
60
|
+
"jsdom": "^25.0.0",
|
|
61
|
+
"svelte": "^5.57.3",
|
|
62
|
+
"svelte-check": "^4.7.8",
|
|
63
|
+
"typescript": "^5.7.0",
|
|
64
|
+
"vite": "^5.4.21",
|
|
65
|
+
"vitest": "^2.1.0"
|
|
66
|
+
},
|
|
67
|
+
"engines": {
|
|
68
|
+
"node": ">=20"
|
|
69
|
+
},
|
|
70
|
+
"scripts": {
|
|
71
|
+
"build": "svelte-package -i src -o dist",
|
|
72
|
+
"dev": "svelte-package -i src -o dist --watch",
|
|
73
|
+
"typecheck": "svelte-check --tsconfig ./tsconfig.json --fail-on-warnings",
|
|
74
|
+
"test": "vitest run --passWithNoTests",
|
|
75
|
+
"clean": "rm -rf dist .svelte-kit .turbo"
|
|
76
|
+
}
|
|
6
77
|
}
|