@rowstile/react 0.1.0-alpha.4 → 0.1.0-alpha.6

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.
Files changed (2) hide show
  1. package/README.md +58 -74
  2. package/package.json +4 -2
package/README.md CHANGED
@@ -1,83 +1,67 @@
1
- # rowstile for TypeScript
1
+ # @rowstile/react
2
2
 
3
- The SDK for TypeScript apps on a rowstile policy: every transaction signs in as whoever the request
4
- or the job acts for, refused writes become a 403 with the database's reason, rows the user can't see a 404,
5
- signed-in reads stay out of Next.js's caches, and the app refuses to start on a connection that skips
6
- row-level security. It holds no rowstile logic: it calls the `authz.*` functions the policy made, and
7
- translates their answers.
3
+ [rowstile](https://rowstile.dev) is a policy language for PostgreSQL. You write who may see and change each
4
+ row in one file, and it becomes row-level security: the database filters every read and refuses every write
5
+ the rules don't allow, whatever the code asks.
8
6
 
9
- Next.js with Prisma:
7
+ This package is the React kit: what the signed-in user may do, for buttons and menus. The database still
8
+ decides; these only ask it, so the page doesn't offer what would be refused. `usePerms` asks for a whole list
9
+ in one call, `<Can>` shows or hides, `<ShareDialog>` is a headless share dialog, `useAccessRequest` asks for
10
+ access, and all of them stay current over server-sent events.
10
11
 
11
- ```ts
12
- // src/db.ts
13
- import { PrismaPg } from "@prisma/adapter-pg";
14
- import { authz, signedIn } from "@rowstile/prisma";
15
- import "@rowstile/next"; // signed-in reads never land in a cache
16
- import "./authz.gen"; // the policy's names (rowstile client)
17
-
18
- const adapter = signedIn(new PrismaPg({ connectionString: process.env.DATABASE_URL }),
19
- { user: async () => (await auth())?.user.id });
20
- export const db = new PrismaClient({ adapter }).$extends(authz());
12
+ ```sh
13
+ # @next on each while only an alpha is published: a plain install gets an older one
14
+ npm install @rowstile/react@next @rowstile/next@next
15
+ ```
16
+
17
+ ```tsx
18
+ import { AuthzProvider, Can, ShareDialog, useAccessRequest, usePerms } from "@rowstile/react";
19
+
20
+ function Buttons() {
21
+ const perms = usePerms("project", [1, 2, 3]);
22
+ if (perms.loading) return <p>loading</p>;
23
+ return <ul>{[1, 2, 3].map((id) => <li key={id}>{id}:{perms(id).perms.join(",")}{perms(id).can("edit") && " [rename]"}</li>)}</ul>;
24
+ }
21
25
  ```
22
26
 
27
+ ```tsx
28
+ <Can type="project" id={1} perm="edit" fallback={<span>no edit on 1</span>}><span>edit on 1</span></Can>
29
+ ```
30
+
31
+ The server's side is one file, with `@rowstile/next`:
32
+
23
33
  ```ts
24
- // app/api/folders/[id]/route.ts: no checks; a hidden folder is 404, one the user may not rename 403
25
- export const PATCH = route(async (req: Request, { params }: { params: Promise<{ id: string }> }) => {
26
- await db.folder.update({ where: { id: Number((await params).id) }, data: await req.json() });
27
- return Response.json({ ok: true });
28
- });
34
+ // app/api/authz/[...authz]/route.ts
35
+ import { authzRoutes } from "@rowstile/next";
36
+ import { db, feed } from "@/db";
37
+
38
+ export const { GET, POST } = authzRoutes({ calls: db.$authz, changes: feed });
29
39
  ```
30
40
 
31
- | package | what |
41
+ ## Good to know
42
+
43
+ - Wrap the app in `<AuthzProvider>`. Give it `user={id}` if the user can change without a page load: the
44
+ hooks forget what they had and ask again.
45
+ - The answers are for the page only. A user who edits the page still meets the database, which refuses.
46
+ - React 18 or later.
47
+
48
+ ## More
49
+
50
+ - [Next.js with Prisma](https://rowstile.dev/stacks/nextjs): the whole setup, step by step, from an app the tests run.
51
+ - [The TypeScript SDK](https://rowstile.dev/sdk/typescript): every package, and the traps they handle.
52
+ - [Getting started](https://rowstile.dev/getting-started): a first policy, step by step.
53
+ - [Source and issues](https://github.com/rowstile/rowstile).
54
+
55
+ The other packages:
56
+
57
+ | package | for |
32
58
  |---|---|
33
- | `@rowstile/client` | `actingAs(who, fn)`, `job(who, fn)`, `current()`, `Refused`, `NotFound`, `NotSignedIn`, `translate(e)` and `problemResponse(e)` for any driver's error, `errorCode(e)` (rowstile's code: `AZ709`), `calls(queryable)` (the runtime's functions), the `Register` the generated names fill in |
34
- | `@rowstile/prisma` | `signedIn(adapter, { user })`: every transaction Prisma begins signs in; `authz()`: P2025 as `NotFound` or `Refused` with the reason, refused creates naming the rule, `db.$authz` (`can`, `ids`, `permsOf`, `share`, `check`, ...) |
35
- | `@rowstile/pg` | `authz(pool, { user })`: `transaction(fn)`, `query()`, the runtime's functions; `changes(pool)` for live updates |
36
- | `@rowstile/postgres` | `authz(sql, { user })`: `begin(fn)`, the runtime's functions |
37
- | `@rowstile/drizzle` | `withAuthz(db, { user })`: `transaction(fn)`; `inIds(column, type, perm)` and `ids()` for `where`; `expect(tx, result, ...)` for updates and deletes that changed nothing |
38
- | `@rowstile/next` | `route(handler)` (403 and 404 problem bodies), `action(fn)` (`{ ok, value }` or `{ ok: false, problem }`), `authzRoutes()` (what the React kit calls), `checkAtStart()` for `instrumentation.ts`; importing it keeps signed-in reads out of caches |
39
- | `@rowstile/react` | `<AuthzProvider>`, `usePerms(type, ids)` (one call for a list), `<Can>`, `useShares` and a headless `<ShareDialog>`, `useAccessRequest`; kept current over server-sent events |
40
- | `@rowstile/vitest` | `expect.extend(matchers)`: `toBeRefused(command, reason)`, `toBeNotFound()`; `asUser(who, fn)`; `databasePerWorker(url)`. Vitest 4 or 5 |
41
-
42
- Who a transaction acts for: `42` or `"42"` (a user), `["service", 3]` (another principal type of the policy),
43
- or `null` (nobody: only what `anyone` may see). A plain id is always a user's, whatever it holds: `"service:3"`
44
- is the user with that id, so an id from outside (a username, an identity provider's subject) can't name a
45
- service. `parsePrincipal("service:3")` reads back what `describe()` wrote, for text your own code wrote. Whoever the code acts for (`actingAs`, a `job`)
46
- comes first, else the `user` function, else nobody; a `who` given to one call (`transaction(fn, who)`) comes
47
- before all, and `null` there is nobody. Every transaction signs in, even as nobody, and nothing uses a
48
- session-level `SET`, so pools and poolers in transaction mode are safe; the change feed needs its own connection
49
- to Postgres ([Behind a pooler](../../docs/operations.md#behind-a-pooler)).
50
-
51
- Traps it handles:
52
-
53
- - **Next.js caching.** Before a transaction signs in as someone, `@rowstile/next` calls Next's `connection()`:
54
- the render is dynamic, and a signed-in read inside `"use cache"` or `unstable_cache` fails instead of being
55
- cached for the next user. Reads as nobody may be cached.
56
- - **Prisma answers some calls together.** It dispatches the `findUnique` calls of one tick, and array
57
- transactions, from the first caller's context. `authz()` runs each `findUnique` in a transaction of its own,
58
- and refuses `$transaction([...])` (use `$transaction(async (tx) => ...)`), so no query runs as someone else.
59
- Use the client `$extends(authz())` returns, and only that one: the client it was made from is refused
60
- whenever it is used, inside your own extensions too. An extension you add to the client `authz()` returns is
61
- placed before it, so `authz()` stays the last one: each of your query hooks runs once for a call, and sees
62
- the errors `authz()` makes (`Refused`, `NotFound`).
63
- - **Inserts that read the row back** (`RETURNING`, Prisma's `create`) also need the select rule: Postgres's own
64
- message comes back as `Refused` naming the select rule.
65
- - **Prisma's promises are lazy**: `actingAs` and `job` await what they return inside their scope.
66
- - **A connection that drops.** node-postgres stops the process when a client that is checked out loses its
67
- connection and nobody listens: `@rowstile/pg` listens while it holds one, so the transaction fails instead.
68
- `changes(pool)` listens again after its connection drops, and tells its subscribers once.
69
- - **An update that changed nothing** is `NotFound` when the user can't see the row, `Refused` when the database
70
- says no, and `NotFound` again when the rule allows it and the statement matched nothing for another reason
71
- (a `where` with more than the key).
72
- - **The answers in the browser are one user's.** Give `<AuthzProvider user={id}>` if the user can change
73
- without a page load: the hooks forget what they had and ask again.
74
-
75
- The types and permissions of the policy are generated names: with a `@rowstile/*` dependency in
76
- `package.json`, `rowstile client` writes only the names (`[clients] ts = "src/authz.gen.ts"`), registered with
77
- the SDK, so `db.$authz.can("note", 1, "edt")` doesn't type-check. Policy changes ship as migrations for your
78
- tool (`rowstile migrate`, with `tool = "prisma"` or `"drizzle"` in `rowstile.toml`).
79
-
80
- The packages are an npm workspace at the repository root (`npm ci`, then `npx tsc -b sdk/typescript`).
81
- `integrations/nextjs/` is the conformance suite: a small Next.js app on Prisma 7 and Prisma Migrate, and the
82
- checks every supported stack passes, with pg, postgres.js, Drizzle and the React kit
83
- (`integrations/nextjs/test.sh`).
59
+ | [`@rowstile/client`](https://www.npmjs.com/package/@rowstile/client) | who a transaction acts for, the errors, the runtime's calls |
60
+ | [`@rowstile/prisma`](https://www.npmjs.com/package/@rowstile/prisma) | Prisma |
61
+ | [`@rowstile/pg`](https://www.npmjs.com/package/@rowstile/pg) | node-postgres |
62
+ | [`@rowstile/postgres`](https://www.npmjs.com/package/@rowstile/postgres) | postgres.js |
63
+ | [`@rowstile/drizzle`](https://www.npmjs.com/package/@rowstile/drizzle) | Drizzle ORM |
64
+ | [`@rowstile/next`](https://www.npmjs.com/package/@rowstile/next) | Next.js: route handlers, server actions, caches |
65
+ | [`@rowstile/vitest`](https://www.npmjs.com/package/@rowstile/vitest) | Vitest: matchers, a database per worker |
66
+
67
+ rowstile is a 0.x preview: names may still change before 1.0. Apache-2.0.
package/package.json CHANGED
@@ -1,8 +1,10 @@
1
1
  {
2
2
  "name": "@rowstile/react",
3
- "version": "0.1.0-alpha.4",
3
+ "version": "0.1.0-alpha.6",
4
4
  "description": "rowstile for React: usePerms, <Can>, a headless share dialog, access requests, live updates",
5
5
  "license": "Apache-2.0",
6
+ "homepage": "https://rowstile.dev",
7
+ "keywords": ["rowstile", "postgres", "postgresql", "authorization", "row-level-security", "rls", "permissions", "access-control", "rbac", "rebac", "multi-tenant", "react", "hooks"],
6
8
  "repository": { "type": "git", "url": "git+https://github.com/rowstile/rowstile.git", "directory": "sdk/typescript/react" },
7
9
  "type": "module",
8
10
  "main": "./dist/index.js",
@@ -18,7 +20,7 @@
18
20
  ],
19
21
  "sideEffects": false,
20
22
  "dependencies": {
21
- "@rowstile/client": "0.1.0-alpha.4"
23
+ "@rowstile/client": "0.1.0-alpha.6"
22
24
  },
23
25
  "peerDependencies": {
24
26
  "react": ">=18"