GithubHelp home page GithubHelp logo

zenstackhq / zenstack Goto Github PK

View Code? Open in Web Editor NEW
1.6K 13.0 69.0 5.87 MB

Typescript toolkit on top of Prisma ORM, offering flexible and declarative Access Control Policy(Authorization/Permission) for RBAC/ABAC/PBAC/ReBAC with auto-generated type-safe APIs and frontend hooks.

Home Page: https://zenstack.dev

License: MIT License

JavaScript 0.36% TypeScript 99.26% Kotlin 0.25% CSS 0.13%
fullstack nextjs orm typescript authorization crud prisma access-control trpc api

zenstack's Introduction

ZenStack

What it is

ZenStack is a Node.js/TypeScript toolkit that simplifies the development of a web app's backend. It supercharges Prisma ORM with a powerful access control layer and unleashes its full potential for full-stack development.

Our goal is to let you save time writing boilerplate code and focus on building real features!

How it works

Read full documentation at ๐Ÿ‘‰๐Ÿป zenstack.dev. Join Discord for feedback and questions.

ZenStack incrementally extends Prisma's power with the following four layers:

1. ZModel - an extended Prisma schema language

ZenStack introduces a data modeling language called "ZModel" - a superset of Prisma schema language. It extended Prisma schema with custom attributes and functions and, based on that, implemented a flexible access control layer around Prisma.

// base.zmodel
abstract model Base {
    id String @id
    author User @relation(fields: [authorId], references: [id])
    authorId String

    // ๐Ÿ” allow full CRUD by author
    @@allow('all', author == auth())
}
// schema.zmodel
import "base"
model Post extends Base {
    title String
    published Boolean @default(false)

    // ๐Ÿ” allow logged-in users to read published posts
    @@allow('read', auth() != null && published)
}

The zenstack CLI transpiles the ZModel into a standard Prisma schema, which you can use with the regular Prisma workflows.

2. Runtime enhancements to Prisma client

At runtime, transparent proxies are created around Prisma clients for intercepting queries and mutations to enforce access policies.

import { enhance } from '@zenstackhq/runtime';

// a regular Prisma client
const prisma = new PrismaClient();

async function getPosts(userId: string) {
    // create an enhanced Prisma client that has access control enabled
    const enhanced = enhance(prisma, { user: userId });

    // only posts that're visible to the user will be returned
    return enhanced.post.findMany();
}

3. Automatic RESTful APIs through server adapters

Server adapter packages help you wrap an access-control-enabled Prisma client into backend CRUD APIs that can be safely called from the frontend. Here's an example for Next.js:

// pages/api/model/[...path].ts

import { requestHandler } from '@zenstackhq/next';
import { enhance } from '@zenstackhq/runtime';
import { getSessionUser } from '@lib/auth';
import { prisma } from '@lib/db';

// Mount Prisma-style APIs: "/api/model/post/findMany", "/api/model/post/create", etc.
// Can be configured to provide standard RESTful APIs (using JSON:API) instead.
export default requestHandler({
    getPrisma: (req, res) => enhance(prisma, { user: getSessionUser(req, res) }),
});

4. Generated client libraries (hooks) for data access

Plugins can generate strong-typed client libraries that talk to the aforementioned APIs. Here's an example for React:

// components/MyPosts.tsx

import { useFindManyPost } from '@lib/hooks';

const MyPosts = () => {
    // list all posts that're visible to the current user, together with their authors
    const { data: posts } = useFindManyPost({
        include: { author: true },
        orderBy: { createdAt: 'desc' },
    });

    return (
        <ul>
            {posts?.map((post) => (
                <li key={post.id}>
                    {post.title} by {post.author.name}
                </li>
            ))}
        </ul>
    );
};

Architecture

The following diagram gives a high-level architecture overview of ZenStack.

Architecture

Links

Features

  • Access control and data validation rules right inside your Prisma schema
  • Auto-generated OpenAPI (RESTful) specifications, services, and client libraries
  • End-to-end type safety
  • Extensible: custom attributes, functions, and a plugin system
  • A framework-agnostic core with framework-specific adapters
  • Uncompromised performance

Plugins

Framework adapters

Prisma schema extensions

Examples

Schema Samples

The sample repo includes the following patterns:

  • ACL
  • RBAC
  • ABAC
  • Multi-Tenancy

You can use this blog post as an introduction.

Multi-Tenant Todo App

Check out the Multi-tenant Todo App for a running example. You can find different implementations below:

Blog App

Community

Join our discord server for chat and updates!

Contributing

If you like ZenStack, join us to make it a better tool! Please use the Contributing Guide for details on how to get started, and don't hesitate to join Discord to share your thoughts.

Please also consider sponsoring our work to speed up the development. Your contribution will be 100% used as a bounty reward to encourage community members to help fix bugs, add features, and improve documentation.

Sponsors

Thank you for your support!

Johann Rohn
Johann Rohn
Benjamin Zecirovic
Benjamin Zecirovic
Fabian Jocks
Fabian Jocks

Contributors

Thanks to all the contributors who have helped make ZenStack better!

Source

Docs

License

MIT

zenstack's People

Contributors

abdullahahmeda avatar azzerty23 avatar bbozzay avatar chemitaxis avatar chunkerchunker avatar dikyarga avatar elsantoalcielo avatar erikmcm avatar jasonmacdonald avatar jbruxelle avatar jiashengguo avatar krist7599555 avatar lordfirespeed avatar mateus-p avatar neon0x avatar potion-cellar avatar sakgoyal avatar simonedelmann avatar sitch avatar tgtgamer avatar tlancina avatar ustice avatar ymc9 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

zenstack's Issues

User without 'name' property will get error when generating

node_modules/.zenstack/src/auth/authorize.ts:32:21 - error TS2322: Type '{ id: true; email: true; password: true; name: true; }' is not assignable to type 'UserSelect'.
Object literal may only specify known properties, and 'name' does not exist in type 'UserSelect'.

32 name: true,

Missing @unique attribute is not properly checked

One-to-one relation requires one side of reference to be marked @unique. It's not checked today.

repro:

model User {
    id String @id @default(cuid())
    data UserData?
}

model UserData {
    id String @id @default(cuid())
    user User  @relation(fields: [userId], references: [id])
    userId String
}

Error:
Error parsing attribute "@relation": A one-to-one relation must use unique fields on the defining side. Either add an @unique attribute to the field userId, or change the relation to one-to-many.

Inaccurate log message for policy rejection

When a read request is reject, log message is incorrect:

GET Post: Request handler error: DENIED_BY_POLICY, the request was denied due to access policy violation: denied by policy before update: entities failed 'read' check, User#[cla8yyvto0001vh8hy4cxeura]

VS Code extension occasionally reports errors

Describe the bug
VS Code extension occasionally reports errors with a stack like:

An error occurred during validation: Error: AST node has no document.
at Mb (/Users/yiming/.vscode/extensions/zenstack.zenstack-1.0.4/bundle/language-server/main.js:36:5802)
at get ref [as ref] (/Users/yiming/.vscode/extensions/zenstack.zenstack-1.0.4/bundle/language-server/main.js:3736:24701)
at rM (/Users/yiming/.vscode/extensions/zenstack.zenstack-1.0.4/bundle/language-server/main.js:6630:26281)
at tc.validate (/Users/yiming/.vscode/extensions/zenstack.zenstack-1.0.4/bundle/language-server/main.js:6630:32491)
at ch.checkExpression (/Users/yiming/.vscode/extensions/zenstack.zenstack-1.0.4/bundle/language-server/main.js:6630:33668)
at /Users/yiming/.vscode/extensions/zenstack.zenstack-1.0.4/bundle/language-server/main.js:3736:29142
at /Users/yiming/.vscode/extensions/zenstack.zenstack-1.0.4/bundle/language-server/main.js:3582:26330
at async Promise.all (index 8)
at async eg.validateAst (/Users/yiming/.vscode/extensions/zenstack.zenstack-1.0.4/bundle/language-server/main.js:3582:26175)
at async eg.validateDocument (/Users/yiming/.vscode/extensions/zenstack.zenstack-1.0.4/bundle/language-server/main.js:3582:25876)

To Reproduce
Can't reproduce consistently.

Expected behavior
No error.

Environment (please complete the following information):

  • OS: Mac OS
  • Node version: 16.15
  • NPM version: 8.9.2
  • Database type: Sqlite

@@unique with multiple fields cause error when findUnique()

Describe the bug

model Model {
        id String @id @default(uuid())
        a String
        b String
        @@unique([a, b])
        @@allow('all', true)
}
await withPresets(prisma).model.findUnique({ where: { a_b: { a: 'a', b: 'b' } } }));

Error

Invalid prisma.model.findMany() invocation:

{
  where: {
    AND: [
      {
        a_b: {
        ~~~
          a: 'a1',
          b: 'b1'
        }
      },
      {
        x: {
          gt: 0
        }
      }
    ]
  }
}

Make sure auth()'s type is properly resolved

Currently, result type of auth() function is weakly resolved because it needs to refer to the User model defined by user. We should actually let it resolve to the user-defined User model.

Issue warning if no policy is found in a model

If a model doesn't have any policy, by default, no operation is permitted, so no hooks are generated. However, this can be confusing to new users. We should issue a warning during generation.

User model with non-string id doesn't work with auth() policy check

Describe the bug
A clear and concise description of what the bug is.

To Reproduce
Steps to reproduce the behavior:
1.
2.
3.

Expected behavior
A clear and concise description of what you expected to happen.

Screenshots
If applicable, add screenshots to help explain your problem.

Environment (please complete the following information):

  • OS: [e.g. Mac OS 13.0]
  • Node version: [e.g. 16.15.0]
  • NPM version: [e.g. 8.19.2]
  • Database type: [e.g. Postgresql]

Additional context
Add any other context about the problem here.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.