@shivaedev/access 0.0.0-stage → 0.1.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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 ShivaeDev
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,85 @@
1
- # Temporary Holding Version
1
+ # @shivaedev/access
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Declare which permissions each application role grants and use that policy in server enforcement and browser interfaces. Store one role string per user, with a Schema that rejects names the application does not declare.
4
+
5
+ ## One policy for each application
6
+
7
+ Applications need to check what a user can do wherever the action appears. Explicit grants keep those decisions together, including the difference between acting on your own records and acting on anyone's.
8
+
9
+ ```ts
10
+ import { permission } from "@shivaedev/access/permission.ts";
11
+ import { role } from "@shivaedev/access/role.ts";
12
+ import { roleSet } from "@shivaedev/access/roleSet.ts";
13
+
14
+ const ReadUsers = permission("users.read");
15
+ const Member = role("member", [ReadUsers]);
16
+ const Operator = role("operator", [ReadUsers.any]);
17
+ const Access = roleSet(Member, Operator);
18
+
19
+ Access.canAccess({ id: "alice", role: "member" }, ReadUsers, "alice");
20
+ Access.canAccess({ id: "alice", role: "operator" }, ReadUsers, "bob");
21
+ ```
22
+
23
+ Both checks return `true`: the member owns the first record, and the operator holds the explicit override.
24
+
25
+ ## Declare and use access
26
+
27
+ ### Permissions and roles
28
+
29
+ A permission names the domain and action, such as `users.read`, `roles.assign` or `jobs.read`. `permission(name)` declares the default strength and exposes a separate override value as `.any`. Each role receives an explicit list of grants. There are no wildcard, prefix or implied grants: holding `users.read.any` does not add `users.read` to the role's list. The ownership check accepts either strength as appropriate for the record.
30
+
31
+ ```ts
32
+ const AssignRoles = permission("roles.assign");
33
+ const ReadJobs = permission("jobs.read");
34
+ const Operator = role("operator", [ReadUsers.any, AssignRoles, ReadJobs]);
35
+ const Guest = role("guest", []);
36
+ const Access = roleSet(Member, Operator, Guest);
37
+ ```
38
+
39
+ Keep these declarations in application code. The package provides no persistence or runtime role editor.
40
+
41
+ ### Store and decode the role string
42
+
43
+ The role set exposes `Role`, a native Schema whose type and encoded value are the closed union of the declared names. Use it in the application's user Schema and decode database values before authorization.
44
+
45
+ ```ts
46
+ import { Schema } from "effect";
47
+
48
+ type AppRole = typeof Access.Role.Type;
49
+ const AppUser = Schema.Struct({ id: Schema.String, role: Access.Role });
50
+ const decodeUser = Schema.decodeUnknownEffect(AppUser);
51
+ const decodeRole = Schema.decodeUnknownEffect(Access.Role);
52
+ ```
53
+
54
+ `AppRole` is `"member" | "operator" | "guest"`. An unknown stored name fails in the typed `SchemaError` channel. `yield* Access.resolve(stored)` decodes the same Schema and returns `{ role, permissions }`, with only the grants declared for that role. Platform accepts the role set through its existing session policy or Better Auth mount configuration.
55
+
56
+ ### Check grants and enforce actions
57
+
58
+ `hasPermission(role, permission)` checks the exact listed grant. `requirePermission(user, permission)` enforces that same check. A user supplies `{ id, role }`; a `null` or `undefined` user fails with `Unauthorized`, and a missing grant fails with `Forbidden`. These are the shared failures from `@shivaedev/effect-contract/errors/taxonomy.ts`.
59
+
60
+ ```ts
61
+ const user = { id: "alice", role: "operator" } as const;
62
+ const showAssignment = Access.hasPermission(user.role, AssignRoles);
63
+ const enforceAssignment = Access.requirePermission(user, AssignRoles);
64
+ ```
65
+
66
+ Use permissions in application decisions instead of comparing role names.
67
+
68
+ ### Check record ownership
69
+
70
+ `canAccess(user, permission, ownerId)` returns a boolean for a record. Pass the default permission and the record's owner ID: the default grant requires the acting user's ID to match, while its `.any` override permits either owner. Ownership alone grants nothing. Signed-out callers get `false`.
71
+
72
+ `requireAccess(user, permission, ownerId)` enforces that same ownership policy as an Effect. Signed-out callers fail with `Unauthorized`; signed-in callers without access fail with `Forbidden`.
73
+
74
+ ```ts
75
+ const canRead = Access.canAccess(user, ReadUsers, "bob");
76
+ const enforceRead = Access.requireAccess(user, ReadUsers, "bob");
77
+ ```
78
+
79
+ Use the ownership APIs when an action targets a record; the exact grant APIs do not check an owner.
80
+
81
+ ### Install
82
+
83
+ ```sh
84
+ pnpm add @shivaedev/access effect
85
+ ```
@@ -0,0 +1,17 @@
1
+ export interface Permission {
2
+ readonly name: string;
3
+ readonly strength: "own" | "any";
4
+ }
5
+ export interface OwnPermission extends Permission {
6
+ readonly any: Permission;
7
+ readonly strength: "own";
8
+ }
9
+ export declare function permission<const TName extends `${string}.${string}`>(name: TName): {
10
+ readonly any: {
11
+ readonly name: TName;
12
+ readonly strength: "any";
13
+ };
14
+ readonly name: TName;
15
+ readonly strength: "own";
16
+ };
17
+ //# sourceMappingURL=permission.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"permission.d.ts","sourceRoot":"","sources":["../src/permission.ts"],"names":[],"mappings":"AAAA,MAAM,WAAW,UAAU;IAC1B,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,QAAQ,EAAE,KAAK,GAAG,KAAK,CAAC;CACjC;AAED,MAAM,WAAW,aAAc,SAAQ,UAAU;IAChD,QAAQ,CAAC,GAAG,EAAE,UAAU,CAAC;IACzB,QAAQ,CAAC,QAAQ,EAAE,KAAK,CAAC;CACzB;AAED,wBAAgB,UAAU,CAAC,KAAK,CAAC,KAAK,SAAS,GAAG,MAAM,IAAI,MAAM,EAAE,EAAE,IAAI,EAAE,KAAK;;;2BAChD,KAAK;;;uBAAoB,KAAK;EAC9D"}
@@ -0,0 +1,4 @@
1
+ export function permission(name) {
2
+ return { any: { name, strength: "any" }, name, strength: "own" };
3
+ }
4
+ //# sourceMappingURL=permission.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"permission.js","sourceRoot":"","sources":["../src/permission.ts"],"names":[],"mappings":"AAUA,MAAM,UAAU,UAAU,CAA4C,IAAW;IAChF,OAAO,EAAE,GAAG,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE,KAAK,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE,KAAK,EAAW,CAAC;AAC3E,CAAC"}
package/dist/role.d.ts ADDED
@@ -0,0 +1,7 @@
1
+ import type { Permission } from "#permission.ts";
2
+ export interface Role<TName extends string = string> {
3
+ readonly name: TName;
4
+ readonly permissions: readonly Permission[];
5
+ }
6
+ export declare function role<const TName extends string>(name: TName, permissions: readonly Permission[]): Role<TName>;
7
+ //# sourceMappingURL=role.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"role.d.ts","sourceRoot":"","sources":["../src/role.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAEjD,MAAM,WAAW,IAAI,CAAC,KAAK,SAAS,MAAM,GAAG,MAAM;IAClD,QAAQ,CAAC,IAAI,EAAE,KAAK,CAAC;IACrB,QAAQ,CAAC,WAAW,EAAE,SAAS,UAAU,EAAE,CAAC;CAC5C;AAED,wBAAgB,IAAI,CAAC,KAAK,CAAC,KAAK,SAAS,MAAM,EAAE,IAAI,EAAE,KAAK,EAAE,WAAW,EAAE,SAAS,UAAU,EAAE,GAAG,IAAI,CAAC,KAAK,CAAC,CAE7G"}
package/dist/role.js ADDED
@@ -0,0 +1,4 @@
1
+ export function role(name, permissions) {
2
+ return { name, permissions };
3
+ }
4
+ //# sourceMappingURL=role.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"role.js","sourceRoot":"","sources":["../src/role.ts"],"names":[],"mappings":"AAOA,MAAM,UAAU,IAAI,CAA6B,IAAW,EAAE,WAAkC;IAC/F,OAAO,EAAE,IAAI,EAAE,WAAW,EAAE,CAAC;AAC9B,CAAC"}
@@ -0,0 +1,24 @@
1
+ import { Effect, Schema } from "effect";
2
+ import { Forbidden, Unauthorized } from "@shivaedev/effect-contract/errors/taxonomy.ts";
3
+ import type { OwnPermission, Permission } from "#permission.ts";
4
+ import type { Role as RoleDefinition } from "#role.ts";
5
+ export interface User<TName extends string> {
6
+ readonly id: string;
7
+ readonly role: TName;
8
+ }
9
+ export declare function roleSet<const TName extends string>(...roles: readonly [RoleDefinition<TName>, ...RoleDefinition<TName>[]]): {
10
+ canAccess: (user: User<TName> | null | undefined, permission: OwnPermission, ownerId: string) => boolean;
11
+ hasPermission: (name: TName, permission: Permission) => boolean;
12
+ Role: Schema.Literals<TName[]>;
13
+ requireAccess: (user: User<TName> | null | undefined, permission: OwnPermission, ownerId: string) => Effect.Effect<void, Forbidden | Unauthorized>;
14
+ requirePermission: (user: User<TName> | null | undefined, permission: Permission) => Effect.Effect<void, Forbidden | Unauthorized>;
15
+ resolve: (stored: unknown) => Effect.Effect<{
16
+ permissions: {
17
+ name: string;
18
+ strength: "any" | "own";
19
+ }[];
20
+ role: TName;
21
+ }, Schema.SchemaError, never>;
22
+ };
23
+ export type RoleSet = Pick<ReturnType<typeof roleSet>, "resolve">;
24
+ //# sourceMappingURL=roleSet.d.ts.map
@@ -0,0 +1 @@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den, Unauthorized } from "@shivaedev/effect-contract/errors/taxonomy.ts";
3
+ export function roleSet(...roles) {
4
+ const Role = Schema.Literals(roles.map((role) => role.name));
5
+ function hasPermission(name, permission) {
6
+ return roles.some((role) => role.name === name && role.permissions.some((granted) => granted.name === permission.name && granted.strength === permission.strength));
7
+ }
8
+ function canAccess(user, permission, ownerId) {
9
+ return (user !== null
10
+ && user !== undefined
11
+ && (hasPermission(user.role, permission.any) || (user.id === ownerId && hasPermission(user.role, permission))));
12
+ }
13
+ function requirePermission(user, permission) {
14
+ if (user === null || user === undefined) {
15
+ return Effect.fail(new Unauthorized({ message: "Sign in to continue" }));
16
+ }
17
+ return hasPermission(user.role, permission)
18
+ ? Effect.void
19
+ : Effect.fail(new Forbidden({
20
+ message: `Permission required: ${permission.name} (${permission.strength})`,
21
+ }));
22
+ }
23
+ function requireAccess(user, permission, ownerId) {
24
+ if (user === null || user === undefined) {
25
+ return Effect.fail(new Unauthorized({ message: "Sign in to continue" }));
26
+ }
27
+ return canAccess(user, permission, ownerId) ? Effect.void : Effect.fail(new Forbidden({ message: `Access denied: ${permission.name}` }));
28
+ }
29
+ function resolve(stored) {
30
+ return Effect.map(Schema.decodeUnknownEffect(Role)(stored), (roleName) => ({
31
+ permissions: (roles.find((candidate) => candidate.name === roleName)?.permissions ?? []).map(({ name, strength }) => ({ name, strength })),
32
+ role: roleName,
33
+ }));
34
+ }
35
+ return {
36
+ canAccess,
37
+ hasPermission,
38
+ Role,
39
+ requireAccess,
40
+ requirePermission,
41
+ resolve,
42
+ };
43
+ }
44
+ //# sourceMappingURL=roleSet.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"roleSet.js","sourceRoot":"","sources":["../src/roleSet.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AACxC,OAAO,EAAE,SAAS,EAAE,YAAY,EAAE,MAAM,+CAA+C,CAAC;AASxF,MAAM,UAAU,OAAO,CAA6B,G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4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0",
4
+ "description": "Browser-safe role declarations and permission checks for Effect applications",
5
+ "homepage": "https://github.com/ShivaeDev/platform/tree/main/packages/access#readme",
6
+ "bugs": {
7
+ "url": "https://github.com/ShivaeDev/platform/issues"
8
+ },
9
+ "repository": {
10
+ "type": "git",
11
+ "url": "git+https://github.com/ShivaeDev/platform.git",
12
+ "directory": "packages/access"
13
+ },
14
+ "license": "MIT",
15
+ "sideEffects": false,
16
+ "type": "module",
17
+ "imports": {
18
+ "#test/*": "./src/test-support/*",
19
+ "#*.ts": {
20
+ "source": "./src/*.ts",
21
+ "types": "./dist/*.d.ts",
22
+ "default": "./dist/*.js"
23
+ }
24
+ },
25
+ "exports": {
26
+ "./*.ts": {
27
+ "source": "./src/*.ts",
28
+ "types": "./dist/*.d.ts",
29
+ "default": "./dist/*.js"
30
+ },
31
+ "./package.json": "./package.json"
32
+ },
33
+ "files": [
34
+ "dist",
35
+ "src",
36
+ "!src/**/*.test.ts",
37
+ "!src/**/*.test.tsx",
38
+ "!src/**/*.spec.ts",
39
+ "!src/**/*.spec.tsx",
40
+ "!src/**/test-support",
41
+ "README.md"
42
+ ],
43
+ "dependencies": {
44
+ "@shivaedev/effect-contract": "0.16.0"
45
+ },
46
+ "devDependencies": {
47
+ "@shivaedev/quality": "0.41.1",
48
+ "@shivaedev/test-story": "0.20.1",
49
+ "@types/node": "24.19.2",
50
+ "effect": "4.0.5",
51
+ "typescript": "7.0.2",
52
+ "vitest": "5.0.5"
53
+ },
54
+ "peerDependencies": {
55
+ "effect": "4.0.5"
56
+ },
57
+ "engines": {
58
+ "node": ">=24"
59
+ },
60
+ "publishConfig": {
61
+ "access": "public",
62
+ "provenance": true
63
+ },
64
+ "scripts": {
65
+ "build": "node --eval \"import('node:fs').then(({ rmSync }) => rmSync('dist', { force: true, recursive: true }))\" && tsc --project tsconfig.build.json",
66
+ "ready": "pnpm typecheck && pnpm test && pnpm build",
67
+ "test": "vitest run",
68
+ "typecheck": "tsc --noEmit"
69
+ }
6
70
  }
@@ -0,0 +1,13 @@
1
+ export interface Permission {
2
+ readonly name: string;
3
+ readonly strength: "own" | "any";
4
+ }
5
+
6
+ export interface OwnPermission extends Permission {
7
+ readonly any: Permission;
8
+ readonly strength: "own";
9
+ }
10
+
11
+ export function permission<const TName extends `${string}.${string}`>(name: TName) {
12
+ return { any: { name, strength: "any" }, name, strength: "own" } as const;
13
+ }
package/src/role.ts ADDED
@@ -0,0 +1,10 @@
1
+ import type { Permission } from "#permission.ts";
2
+
3
+ export interface Role<TName extends string = string> {
4
+ readonly name: TName;
5
+ readonly permissions: readonly Permission[];
6
+ }
7
+
8
+ export function role<const TName extends string>(name: TName, permissions: readonly Permission[]): Role<TName> {
9
+ return { name, permissions };
10
+ }
package/src/roleSet.ts ADDED
@@ -0,0 +1,64 @@
1
+ import { Effect, Schema } from "effect";
2
+ import { Forbidden, Unauthorized } from "@shivaedev/effect-contract/errors/taxonomy.ts";
3
+ import type { OwnPermission, Permission } from "#permission.ts";
4
+ import type { Role as RoleDefinition } from "#role.ts";
5
+
6
+ export interface User<TName extends string> {
7
+ readonly id: string;
8
+ readonly role: TName;
9
+ }
10
+
11
+ export function roleSet<const TName extends string>(...roles: readonly [RoleDefinition<TName>, ...RoleDefinition<TName>[]]) {
12
+ const Role = Schema.Literals(roles.map((role) => role.name));
13
+ function hasPermission(name: TName, permission: Permission): boolean {
14
+ return roles.some(
15
+ (role) =>
16
+ role.name === name && role.permissions.some((granted) => granted.name === permission.name && granted.strength === permission.strength),
17
+ );
18
+ }
19
+ function canAccess(user: User<TName> | null | undefined, permission: OwnPermission, ownerId: string): boolean {
20
+ return (
21
+ user !== null
22
+ && user !== undefined
23
+ && (hasPermission(user.role, permission.any) || (user.id === ownerId && hasPermission(user.role, permission)))
24
+ );
25
+ }
26
+ function requirePermission(user: User<TName> | null | undefined, permission: Permission): Effect.Effect<void, Forbidden | Unauthorized> {
27
+ if (user === null || user === undefined) {
28
+ return Effect.fail(new Unauthorized({ message: "Sign in to continue" }));
29
+ }
30
+ return hasPermission(user.role, permission)
31
+ ? Effect.void
32
+ : Effect.fail(
33
+ new Forbidden({
34
+ message: `Permission required: ${permission.name} (${permission.strength})`,
35
+ }),
36
+ );
37
+ }
38
+ function requireAccess(
39
+ user: User<TName> | null | undefined,
40
+ permission: OwnPermission,
41
+ ownerId: string,
42
+ ): Effect.Effect<void, Forbidden | Unauthorized> {
43
+ if (user === null || user === undefined) {
44
+ return Effect.fail(new Unauthorized({ message: "Sign in to continue" }));
45
+ }
46
+ return canAccess(user, permission, ownerId) ? Effect.void : Effect.fail(new Forbidden({ message: `Access denied: ${permission.name}` }));
47
+ }
48
+ function resolve(stored: unknown) {
49
+ return Effect.map(Schema.decodeUnknownEffect(Role)(stored), (roleName) => ({
50
+ permissions: (roles.find((candidate) => candidate.name === roleName)?.permissions ?? []).map(({ name, strength }) => ({ name, strength })),
51
+ role: roleName,
52
+ }));
53
+ }
54
+ return {
55
+ canAccess,
56
+ hasPermission,
57
+ Role,
58
+ requireAccess,
59
+ requirePermission,
60
+ resolve,
61
+ };
62
+ }
63
+
64
+ export type RoleSet = Pick<ReturnType<typeof roleSet>, "resolve">;