@rowstile/client 0.1.0-alpha.2
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 +202 -0
- package/README.md +81 -0
- package/dist/index.d.ts +190 -0
- package/dist/index.js +339 -0
- package/package.json +15 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
# rowstile for TypeScript
|
|
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.
|
|
8
|
+
|
|
9
|
+
Next.js with Prisma:
|
|
10
|
+
|
|
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());
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
```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
|
+
});
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
| package | what |
|
|
32
|
+
|---|---|
|
|
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.
|
|
61
|
+
- **Inserts that read the row back** (`RETURNING`, Prisma's `create`) also need the select rule: Postgres's own
|
|
62
|
+
message comes back as `Refused` naming the select rule.
|
|
63
|
+
- **Prisma's promises are lazy**: `actingAs` and `job` await what they return inside their scope.
|
|
64
|
+
- **A connection that drops.** node-postgres stops the process when a client that is checked out loses its
|
|
65
|
+
connection and nobody listens: `@rowstile/pg` listens while it holds one, so the transaction fails instead.
|
|
66
|
+
`changes(pool)` listens again after its connection drops, and tells its subscribers once.
|
|
67
|
+
- **An update that changed nothing** is `NotFound` when the user can't see the row, `Refused` when the database
|
|
68
|
+
says no, and `NotFound` again when the rule allows it and the statement matched nothing for another reason
|
|
69
|
+
(a `where` with more than the key).
|
|
70
|
+
- **The answers in the browser are one user's.** Give `<AuthzProvider user={id}>` if the user can change
|
|
71
|
+
without a page load: the hooks forget what they had and ask again.
|
|
72
|
+
|
|
73
|
+
The types and permissions of the policy are generated names: with a `@rowstile/*` dependency in
|
|
74
|
+
`package.json`, `rowstile client` writes only the names (`[clients] ts = "src/authz.gen.ts"`), registered with
|
|
75
|
+
the SDK, so `db.$authz.can("note", 1, "edt")` doesn't type-check. Policy changes ship as migrations for your
|
|
76
|
+
tool (`rowstile migrate`, with `tool = "prisma"` or `"drizzle"` in `rowstile.toml`).
|
|
77
|
+
|
|
78
|
+
The packages are an npm workspace at the repository root (`npm ci`, then `npx tsc -b sdk/typescript`).
|
|
79
|
+
`integrations/nextjs/` is the conformance suite: a small Next.js app on Prisma 7 and Prisma Migrate, and the
|
|
80
|
+
checks every supported stack passes, with pg, postgres.js, Drizzle and the React kit
|
|
81
|
+
(`integrations/nextjs/test.sh`).
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
/** Filled in by the generated file: `declare module "@rowstile/client" { interface Register { ... } }`. */
|
|
2
|
+
export interface Register {
|
|
3
|
+
}
|
|
4
|
+
type Registered = Register extends {
|
|
5
|
+
permissions: infer P;
|
|
6
|
+
} ? P : {
|
|
7
|
+
readonly [type: string]: readonly string[];
|
|
8
|
+
};
|
|
9
|
+
type RegisteredShared = Register extends {
|
|
10
|
+
sharedRelations: infer S;
|
|
11
|
+
} ? S : {
|
|
12
|
+
readonly [type: string]: {
|
|
13
|
+
readonly [relation: string]: readonly string[];
|
|
14
|
+
};
|
|
15
|
+
};
|
|
16
|
+
/** A type the policy declares ("folder"). */
|
|
17
|
+
export type ObjectType = Extract<keyof Registered, string>;
|
|
18
|
+
/** A permission type T has ("edit"). */
|
|
19
|
+
export type Permission<T extends ObjectType = ObjectType> = Registered[T] extends readonly (infer P)[] ? Extract<P, string> : string;
|
|
20
|
+
/** A type with relations people may share. */
|
|
21
|
+
export type SharedType = Extract<keyof RegisteredShared, string>;
|
|
22
|
+
/** A relation of T people may share ("editor"). */
|
|
23
|
+
export type SharedRelation<T extends SharedType = SharedType> = Extract<keyof RegisteredShared[T], string>;
|
|
24
|
+
/** An object's id; for a composite key, its columns in order: [orgId, id]. */
|
|
25
|
+
export type Id = string | number | bigint | readonly (string | number | bigint)[];
|
|
26
|
+
/** An id as the database compares it: a composite key as Postgres writes a row (every field quoted); a key of
|
|
27
|
+
* one column given as an array is that value. */
|
|
28
|
+
export declare function idText(id: Id): string;
|
|
29
|
+
/** A user (type "user"), another principal type the policy declares (a service, a bot), or nobody (id null:
|
|
30
|
+
* only what `anyone` may see). */
|
|
31
|
+
export interface Principal {
|
|
32
|
+
readonly type: string;
|
|
33
|
+
readonly id: string | null;
|
|
34
|
+
}
|
|
35
|
+
/** 42, "42", ["service", 3], a Principal, or null / undefined (nobody). A plain id is a user's, whatever it holds:
|
|
36
|
+
* "service:3" is the user whose id that is (ids often come from outside: a username, an identity provider's
|
|
37
|
+
* subject), never service 3. Another principal type is named: ["service", 3]. */
|
|
38
|
+
export type Who = Principal | string | number | bigint | readonly [string, string | number | bigint | null] | null | undefined;
|
|
39
|
+
export declare const NOBODY: Principal;
|
|
40
|
+
export declare function principal(who: Who): Principal;
|
|
41
|
+
/** What describe() wrote, read back: "service:3" is service 3, "42" user 42, "nobody" nobody. For text your own
|
|
42
|
+
* code wrote (a job's argument, the audit trail's `by`), not for an id that came from outside. */
|
|
43
|
+
export declare function parsePrincipal(text: string): Principal;
|
|
44
|
+
/** "42", "service:3" or "nobody". */
|
|
45
|
+
export declare function describe(p: Principal): string;
|
|
46
|
+
/** Who the code running now acts for (set by actingAs, a job, or a web integration), or undefined if unset. */
|
|
47
|
+
export declare function current(): Principal | undefined;
|
|
48
|
+
/** Runs fn acting for `who`: every transaction it begins (the drivers' packages) signs in as them. */
|
|
49
|
+
export declare function actingAs<R>(who: Who, fn: () => R): R;
|
|
50
|
+
/** A background job (BullMQ, Next.js `after()`, a cron handler) that acts for `who`, whatever started it:
|
|
51
|
+
* job(["service", 3], async (payload) => { ... }). */
|
|
52
|
+
export declare function job<A extends unknown[], R>(who: Who, fn: (...args: A) => R): (...args: A) => R;
|
|
53
|
+
/** Who the request is, when nothing set it with actingAs: e.g. async () => (await auth())?.user.id */
|
|
54
|
+
export type UserResolver = () => Who | Promise<Who>;
|
|
55
|
+
/** Something to run before a transaction signs in (the Next.js integration keeps signed-in reads out of caches). */
|
|
56
|
+
export declare function beforeSignIn(hook: (p: Principal) => unknown): void;
|
|
57
|
+
/** Whom the next transaction signs in as: `who` if the call was given one (null: nobody), else whoever the
|
|
58
|
+
* code acts for, else user(), else nobody. The hooks run for each: a transaction told who it acts for is
|
|
59
|
+
* kept out of caches like any other. */
|
|
60
|
+
export declare function signingIn(user?: UserResolver, who?: Who): Promise<Principal>;
|
|
61
|
+
/** The statement that signs a transaction in, with its parameters. */
|
|
62
|
+
export declare function actAs(p: Principal): {
|
|
63
|
+
text: string;
|
|
64
|
+
values: (string | null)[];
|
|
65
|
+
};
|
|
66
|
+
/** A SQL string literal (standard_conforming_strings, as every supported Postgres has it). */
|
|
67
|
+
export declare function literal(value: string | null): string;
|
|
68
|
+
/** The same statement with its values written in, for APIs that take no parameters. */
|
|
69
|
+
export declare function actAsSql(p: Principal): string;
|
|
70
|
+
/** An RFC 9457 problem body. */
|
|
71
|
+
export interface Problem {
|
|
72
|
+
type: string;
|
|
73
|
+
title: string;
|
|
74
|
+
status: number;
|
|
75
|
+
detail: string;
|
|
76
|
+
[field: string]: unknown;
|
|
77
|
+
}
|
|
78
|
+
/** The database refused a write, and said why: the rule (table and command), and the explanation. */
|
|
79
|
+
export declare class Refused extends Error {
|
|
80
|
+
table?: string | undefined;
|
|
81
|
+
command?: string | undefined;
|
|
82
|
+
why: string[];
|
|
83
|
+
readonly status = 403;
|
|
84
|
+
readonly code = "AZ709";
|
|
85
|
+
constructor(message: string, table?: string | undefined, command?: string | undefined, why?: string[], options?: {
|
|
86
|
+
cause?: unknown;
|
|
87
|
+
});
|
|
88
|
+
problem(): Problem;
|
|
89
|
+
}
|
|
90
|
+
/** The row isn't there, or whoever the transaction acts for can't see it. */
|
|
91
|
+
export declare class NotFound extends Error {
|
|
92
|
+
table?: string | undefined;
|
|
93
|
+
id?: string | undefined;
|
|
94
|
+
readonly status = 404;
|
|
95
|
+
constructor(table?: string | undefined, id?: string | undefined, options?: {
|
|
96
|
+
cause?: unknown;
|
|
97
|
+
});
|
|
98
|
+
problem(): Problem;
|
|
99
|
+
}
|
|
100
|
+
/** A query that needs to know who is asking ran in a transaction nobody signed in to (strict sign-in). */
|
|
101
|
+
export declare class NotSignedIn extends Error {
|
|
102
|
+
readonly code = "AZ701";
|
|
103
|
+
constructor(message: string, options?: {
|
|
104
|
+
cause?: unknown;
|
|
105
|
+
});
|
|
106
|
+
}
|
|
107
|
+
/** authz.connection_check() found that the app's connection skips row-level security (or worse). */
|
|
108
|
+
export declare class ConnectionProblem extends Error {
|
|
109
|
+
problems: string[];
|
|
110
|
+
constructor(problems: string[]);
|
|
111
|
+
}
|
|
112
|
+
interface DbError {
|
|
113
|
+
code: string;
|
|
114
|
+
message: string;
|
|
115
|
+
detail?: string;
|
|
116
|
+
hint?: string;
|
|
117
|
+
schema?: string;
|
|
118
|
+
table?: string;
|
|
119
|
+
constraint?: string;
|
|
120
|
+
}
|
|
121
|
+
/** The Postgres error in e, if there is one: its SQLSTATE and fields, whichever driver raised it. */
|
|
122
|
+
export declare function dbError(e: unknown): DbError | null;
|
|
123
|
+
/** rowstile's code for a database error (AZ709; `rowstile help AZ709` says what it means): from its HINT, where
|
|
124
|
+
* the runtime puts it, or its message. Undefined for an error rowstile didn't raise. */
|
|
125
|
+
export declare function errorCode(e: unknown): string | undefined;
|
|
126
|
+
export declare function sqlstate(e: unknown): string | undefined;
|
|
127
|
+
/** A Refused for an error that is the database refusing a write (SQLSTATE 42501, raised by rowstile's
|
|
128
|
+
* policies with the rule and why), else null. `schemaOf` qualifies a bare table name (Prisma knows it).
|
|
129
|
+
* Another 42501 (a table the app role was never granted) is the app's mistake, not a refusal: null. */
|
|
130
|
+
export declare function refusal(e: unknown, schemaOf?: (table: string) => string | undefined): Refused | null;
|
|
131
|
+
/** Whether e is strict sign-in's error: a query that needs to know who is asking, and nobody signed in. */
|
|
132
|
+
export declare function notSignedIn(e: unknown): boolean;
|
|
133
|
+
/** e as rowstile's error: Refused, NotFound or NotSignedIn as they are, a database refusal as Refused, strict
|
|
134
|
+
* sign-in's error as NotSignedIn; null for anything else. */
|
|
135
|
+
export declare function translate(e: unknown, schemaOf?: (table: string) => string | undefined): Refused | NotFound | NotSignedIn | null;
|
|
136
|
+
/** The problem body and status for e (Refused: 403, NotFound: 404), or null. */
|
|
137
|
+
export declare function problemOf(e: unknown): Problem | null;
|
|
138
|
+
/** A Response (application/problem+json) for e, or null: for route handlers. */
|
|
139
|
+
export declare function problemResponse(e: unknown): Response | null;
|
|
140
|
+
/** The errors among authz.connection_check()'s rows. */
|
|
141
|
+
export declare function checkProblems(rows: {
|
|
142
|
+
severity: string;
|
|
143
|
+
problem: string;
|
|
144
|
+
}[]): string[];
|
|
145
|
+
/** Anything that runs one statement with $1, $2 parameters and returns its rows. */
|
|
146
|
+
export interface Queryable {
|
|
147
|
+
query(text: string, values?: unknown[]): Promise<{
|
|
148
|
+
rows: any[];
|
|
149
|
+
rowCount?: number | null;
|
|
150
|
+
}>;
|
|
151
|
+
}
|
|
152
|
+
/** A share, as authz.list_shares returns it. */
|
|
153
|
+
export interface Share {
|
|
154
|
+
relation: string;
|
|
155
|
+
subject_type: string;
|
|
156
|
+
subject_id: string;
|
|
157
|
+
subject_relation: string;
|
|
158
|
+
[column: string]: unknown;
|
|
159
|
+
}
|
|
160
|
+
/** What the React kit's routes need; each driver's package gives it (Prisma: db.$authz). */
|
|
161
|
+
export interface AuthzCalls {
|
|
162
|
+
can<T extends ObjectType>(type: T, id: Id, perm: Permission<T>): Promise<boolean>;
|
|
163
|
+
perms<T extends ObjectType>(type: T, id: Id): Promise<Permission<T>[]>;
|
|
164
|
+
permsOf<T extends ObjectType>(type: T, ids: readonly Id[]): Promise<Record<string, Permission<T>[]>>;
|
|
165
|
+
list<T extends ObjectType>(type: T, perm: Permission<T>, page?: {
|
|
166
|
+
after?: Id;
|
|
167
|
+
limit?: number;
|
|
168
|
+
}): Promise<string[]>;
|
|
169
|
+
listShares<T extends ObjectType>(type: T, id: Id): Promise<Share[]>;
|
|
170
|
+
share<T extends SharedType>(type: T, id: Id, relation: SharedRelation<T>, subjectType: string, subjectId: Id, subjectRelation?: string): Promise<void>;
|
|
171
|
+
unshare<T extends SharedType>(type: T, id: Id, relation: SharedRelation<T>, subjectType: string, subjectId: Id, subjectRelation?: string): Promise<void>;
|
|
172
|
+
requestAccess<T extends SharedType>(type: T, id: Id, relation: SharedRelation<T>, reason: string): Promise<string>;
|
|
173
|
+
explainRule(table: string, command: "insert" | "update" | "delete", id?: Id, row?: object): Promise<string[] | null>;
|
|
174
|
+
connectionCheck(): Promise<{
|
|
175
|
+
severity: string;
|
|
176
|
+
problem: string;
|
|
177
|
+
}[]>;
|
|
178
|
+
}
|
|
179
|
+
/** The runtime's functions over q (a signed-in transaction, or something that signs each query in). */
|
|
180
|
+
export declare function calls(q: Queryable): AuthzCalls & {
|
|
181
|
+
expect<R>(result: R, table: string, command: "update" | "delete", id: Id, row?: object): Promise<R>;
|
|
182
|
+
check(): Promise<void>;
|
|
183
|
+
};
|
|
184
|
+
/** Whether an UPDATE or DELETE's result changed anything: rows, a count, {count}, {rowCount}, postgres.js's .count. */
|
|
185
|
+
export declare function changed(result: unknown): boolean;
|
|
186
|
+
/** What an UPDATE or DELETE that changed nothing was: NotFound when the row isn't there for this user (why is
|
|
187
|
+
* null), or when the rule allows the write (its first line says yes: the statement matched nothing for
|
|
188
|
+
* another reason, such as a where with more than the key); Refused with the reason otherwise. */
|
|
189
|
+
export declare function verdict(table: string, command: string, id: Id, why: string[] | null): NotFound | Refused;
|
|
190
|
+
export {};
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,339 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* rowstile for TypeScript apps.
|
|
3
|
+
*
|
|
4
|
+
* Every transaction signs in as whoever the request (or the job) acts for, with `authz.act_as()`; the
|
|
5
|
+
* database's refusals become `Refused` (a 403 with the reason), rows the user can't see become `NotFound`
|
|
6
|
+
* (a 404). This package holds no rowstile logic: it calls the `authz.*` functions the policy made, and
|
|
7
|
+
* translates their answers. The drivers' packages (`@rowstile/pg`, `/postgres`, `/prisma`, `/drizzle`) use it.
|
|
8
|
+
*
|
|
9
|
+
* import { actingAs } from "@rowstile/client";
|
|
10
|
+
* await actingAs(42, async () => { ... }); // every transaction in here signs in as user 42
|
|
11
|
+
*
|
|
12
|
+
* The names the policy declares come from the generated file (`rowstile client`, e.g. `src/authz.gen.ts`),
|
|
13
|
+
* which registers them here, so a misspelled type or permission doesn't type-check.
|
|
14
|
+
*/
|
|
15
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
16
|
+
/** An id as the database compares it: a composite key as Postgres writes a row (every field quoted); a key of
|
|
17
|
+
* one column given as an array is that value. */
|
|
18
|
+
export function idText(id) {
|
|
19
|
+
if (Array.isArray(id)) {
|
|
20
|
+
if (id.length === 1)
|
|
21
|
+
return String(id[0]);
|
|
22
|
+
return "(" + id.map((v) => '"' + String(v).replace(/["\\]/g, (c) => "\\" + c) + '"').join(",") + ")";
|
|
23
|
+
}
|
|
24
|
+
return String(id);
|
|
25
|
+
}
|
|
26
|
+
export const NOBODY = Object.freeze({ type: "user", id: null });
|
|
27
|
+
export function principal(who) {
|
|
28
|
+
if (who === null || who === undefined)
|
|
29
|
+
return NOBODY;
|
|
30
|
+
if (Array.isArray(who)) {
|
|
31
|
+
const [type, id] = who;
|
|
32
|
+
return Object.freeze({ type: String(type), id: id === null || id === undefined ? null : String(id) });
|
|
33
|
+
}
|
|
34
|
+
if (typeof who === "object") {
|
|
35
|
+
const p = who;
|
|
36
|
+
return Object.freeze({ type: p.type ?? "user", id: p.id === null || p.id === undefined ? null : String(p.id) });
|
|
37
|
+
}
|
|
38
|
+
return Object.freeze({ type: "user", id: String(who) });
|
|
39
|
+
}
|
|
40
|
+
/** What describe() wrote, read back: "service:3" is service 3, "42" user 42, "nobody" nobody. For text your own
|
|
41
|
+
* code wrote (a job's argument, the audit trail's `by`), not for an id that came from outside. */
|
|
42
|
+
export function parsePrincipal(text) {
|
|
43
|
+
if (text === "nobody")
|
|
44
|
+
return NOBODY;
|
|
45
|
+
const colon = text.indexOf(":");
|
|
46
|
+
if (colon > 0 && !text.startsWith("("))
|
|
47
|
+
return Object.freeze({ type: text.slice(0, colon), id: text.slice(colon + 1) });
|
|
48
|
+
return Object.freeze({ type: "user", id: text });
|
|
49
|
+
}
|
|
50
|
+
/** "42", "service:3" or "nobody". */
|
|
51
|
+
export function describe(p) {
|
|
52
|
+
return p.id === null ? "nobody" : p.type === "user" ? p.id : `${p.type}:${p.id}`;
|
|
53
|
+
}
|
|
54
|
+
const KEY = Symbol.for("rowstile.context");
|
|
55
|
+
const shared = globalThis[KEY] ??
|
|
56
|
+
(globalThis[KEY] = { store: new AsyncLocalStorage(), hooks: [] });
|
|
57
|
+
/** Who the code running now acts for (set by actingAs, a job, or a web integration), or undefined if unset. */
|
|
58
|
+
export function current() {
|
|
59
|
+
return shared.store.getStore();
|
|
60
|
+
}
|
|
61
|
+
/** Runs fn in p's scope; a promise it returns is awaited in the scope too, as Prisma's queries only start when
|
|
62
|
+
* they are awaited. */
|
|
63
|
+
function inScope(p, fn) {
|
|
64
|
+
return shared.store.run(p, () => {
|
|
65
|
+
const r = fn();
|
|
66
|
+
if (r && typeof r.then === "function")
|
|
67
|
+
return (async () => await r)();
|
|
68
|
+
return r;
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
/** Runs fn acting for `who`: every transaction it begins (the drivers' packages) signs in as them. */
|
|
72
|
+
export function actingAs(who, fn) {
|
|
73
|
+
return inScope(principal(who), fn);
|
|
74
|
+
}
|
|
75
|
+
/** A background job (BullMQ, Next.js `after()`, a cron handler) that acts for `who`, whatever started it:
|
|
76
|
+
* job(["service", 3], async (payload) => { ... }). */
|
|
77
|
+
export function job(who, fn) {
|
|
78
|
+
const p = principal(who);
|
|
79
|
+
return (...args) => inScope(p, () => fn(...args));
|
|
80
|
+
}
|
|
81
|
+
/** Something to run before a transaction signs in (the Next.js integration keeps signed-in reads out of caches). */
|
|
82
|
+
export function beforeSignIn(hook) {
|
|
83
|
+
if (!shared.hooks.includes(hook))
|
|
84
|
+
shared.hooks.push(hook);
|
|
85
|
+
}
|
|
86
|
+
/** Whom the next transaction signs in as: `who` if the call was given one (null: nobody), else whoever the
|
|
87
|
+
* code acts for, else user(), else nobody. The hooks run for each: a transaction told who it acts for is
|
|
88
|
+
* kept out of caches like any other. */
|
|
89
|
+
export async function signingIn(user, who) {
|
|
90
|
+
let p = who !== undefined ? principal(who) : current();
|
|
91
|
+
if (p === undefined)
|
|
92
|
+
p = user ? principal(await user()) : NOBODY;
|
|
93
|
+
for (const hook of shared.hooks)
|
|
94
|
+
await hook(p);
|
|
95
|
+
return p;
|
|
96
|
+
}
|
|
97
|
+
/** The statement that signs a transaction in, with its parameters. */
|
|
98
|
+
export function actAs(p) {
|
|
99
|
+
return { text: "SELECT authz.act_as($1, $2)", values: p.id === null ? [null, null] : [p.type, p.id] };
|
|
100
|
+
}
|
|
101
|
+
/** A SQL string literal (standard_conforming_strings, as every supported Postgres has it). */
|
|
102
|
+
export function literal(value) {
|
|
103
|
+
return value === null ? "NULL" : "'" + value.replace(/'/g, "''") + "'";
|
|
104
|
+
}
|
|
105
|
+
/** The same statement with its values written in, for APIs that take no parameters. */
|
|
106
|
+
export function actAsSql(p) {
|
|
107
|
+
return p.id === null ? "SELECT authz.act_as(NULL, NULL)" : `SELECT authz.act_as(${literal(p.type)}, ${literal(p.id)})`;
|
|
108
|
+
}
|
|
109
|
+
/** The database refused a write, and said why: the rule (table and command), and the explanation. */
|
|
110
|
+
export class Refused extends Error {
|
|
111
|
+
table;
|
|
112
|
+
command;
|
|
113
|
+
why;
|
|
114
|
+
status = 403;
|
|
115
|
+
code = "AZ709"; // rowstile help AZ709
|
|
116
|
+
constructor(message, table, command, why = [], options) {
|
|
117
|
+
super(message, options);
|
|
118
|
+
this.table = table;
|
|
119
|
+
this.command = command;
|
|
120
|
+
this.why = why;
|
|
121
|
+
this.name = "Refused";
|
|
122
|
+
}
|
|
123
|
+
problem() {
|
|
124
|
+
return { type: "https://rowstile.dev/problems/refused", title: "Forbidden", status: 403, detail: this.message,
|
|
125
|
+
table: this.table ?? null, command: this.command ?? null, why: this.why, code: this.code };
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
/** The row isn't there, or whoever the transaction acts for can't see it. */
|
|
129
|
+
export class NotFound extends Error {
|
|
130
|
+
table;
|
|
131
|
+
id;
|
|
132
|
+
status = 404;
|
|
133
|
+
constructor(table, id, options) {
|
|
134
|
+
super(`${table ?? "the row"}${id === undefined ? "" : " " + id} not found`, options);
|
|
135
|
+
this.table = table;
|
|
136
|
+
this.id = id;
|
|
137
|
+
this.name = "NotFound";
|
|
138
|
+
}
|
|
139
|
+
problem() {
|
|
140
|
+
return { type: "https://rowstile.dev/problems/not-found", title: "Not Found", status: 404, detail: this.message };
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
/** A query that needs to know who is asking ran in a transaction nobody signed in to (strict sign-in). */
|
|
144
|
+
export class NotSignedIn extends Error {
|
|
145
|
+
code = "AZ701"; // rowstile help AZ701
|
|
146
|
+
constructor(message, options) {
|
|
147
|
+
super(message, options);
|
|
148
|
+
this.name = "NotSignedIn";
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
/** authz.connection_check() found that the app's connection skips row-level security (or worse). */
|
|
152
|
+
export class ConnectionProblem extends Error {
|
|
153
|
+
problems;
|
|
154
|
+
constructor(problems) {
|
|
155
|
+
super("the app's database connection can't be used with rowstile: " + problems.join("; "));
|
|
156
|
+
this.problems = problems;
|
|
157
|
+
this.name = "ConnectionProblem";
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
/** The error and the driver's errors inside it: pg's and postgres.js's are the error itself, Drizzle keeps
|
|
161
|
+
* the driver's as the cause, Prisma's driver adapters in meta.driverAdapterError.cause. */
|
|
162
|
+
function chain(e) {
|
|
163
|
+
const out = [];
|
|
164
|
+
const todo = [e];
|
|
165
|
+
while (todo.length) {
|
|
166
|
+
const x = todo.shift();
|
|
167
|
+
if (!x || typeof x !== "object" || out.includes(x))
|
|
168
|
+
continue;
|
|
169
|
+
const o = x;
|
|
170
|
+
out.push(o);
|
|
171
|
+
todo.push(o.cause, o.meta, o.driverAdapterError, o.originalError);
|
|
172
|
+
}
|
|
173
|
+
return out;
|
|
174
|
+
}
|
|
175
|
+
const str = (v) => (typeof v === "string" && v ? v : undefined);
|
|
176
|
+
/** The Postgres error in e, if there is one: its SQLSTATE and fields, whichever driver raised it. */
|
|
177
|
+
export function dbError(e) {
|
|
178
|
+
for (const o of chain(e)) {
|
|
179
|
+
if (o.clientVersion !== undefined)
|
|
180
|
+
continue; // Prisma's own error: its code is Prisma's
|
|
181
|
+
const code = str(o.originalCode) ?? str(o.sqlState) ?? str(o.code);
|
|
182
|
+
// five characters, and not Node's own (EPIPE, EPERM: no SQLSTATE class begins with E)
|
|
183
|
+
if (!code || !/^[0-9A-Z]{5}$/.test(code) || code.startsWith("E"))
|
|
184
|
+
continue;
|
|
185
|
+
return {
|
|
186
|
+
code,
|
|
187
|
+
message: str(o.originalMessage) ?? str(o.message) ?? "",
|
|
188
|
+
detail: str(o.detail), hint: str(o.hint),
|
|
189
|
+
schema: str(o.schema) ?? str(o.schema_name), table: str(o.table) ?? str(o.table_name),
|
|
190
|
+
constraint: str(o.constraint) ?? str(o.constraint_name),
|
|
191
|
+
};
|
|
192
|
+
}
|
|
193
|
+
return null;
|
|
194
|
+
}
|
|
195
|
+
/** rowstile's code for a database error (AZ709; `rowstile help AZ709` says what it means): from its HINT, where
|
|
196
|
+
* the runtime puts it, or its message. Undefined for an error rowstile didn't raise. */
|
|
197
|
+
export function errorCode(e) {
|
|
198
|
+
const err = dbError(e);
|
|
199
|
+
for (const text of [err?.hint, err?.message]) {
|
|
200
|
+
const m = /(?:rowstile|rowfence) help (AZ\d{3})|\[(AZ\d{3})\]/.exec(text ?? "");
|
|
201
|
+
if (m)
|
|
202
|
+
return m[1] ?? m[2];
|
|
203
|
+
}
|
|
204
|
+
return undefined;
|
|
205
|
+
}
|
|
206
|
+
export function sqlstate(e) {
|
|
207
|
+
return dbError(e)?.code;
|
|
208
|
+
}
|
|
209
|
+
const RLS_GENERIC = /^new row violates row-level security policy (\(USING expression\) )?for table "([^"]+)"/;
|
|
210
|
+
const OURS = /may not (insert|update|delete) this row (?:into|of) (\S+?)(?: to these values)?$/;
|
|
211
|
+
/** A Refused for an error that is the database refusing a write (SQLSTATE 42501, raised by rowstile's
|
|
212
|
+
* policies with the rule and why), else null. `schemaOf` qualifies a bare table name (Prisma knows it).
|
|
213
|
+
* Another 42501 (a table the app role was never granted) is the app's mistake, not a refusal: null. */
|
|
214
|
+
export function refusal(e, schemaOf) {
|
|
215
|
+
const err = dbError(e);
|
|
216
|
+
if (!err || err.code !== "42501")
|
|
217
|
+
return null;
|
|
218
|
+
const generic = RLS_GENERIC.exec(err.message);
|
|
219
|
+
if (generic) {
|
|
220
|
+
const schema = err.schema ?? schemaOf?.(generic[2]);
|
|
221
|
+
const table = schema ? `${schema}.${generic[2]}` : generic[2];
|
|
222
|
+
if (generic[1]) {
|
|
223
|
+
// an upsert (INSERT ... ON CONFLICT DO UPDATE) whose existing row this user may not update, or not see
|
|
224
|
+
return new Refused(`${err.message}: the row is there already, and the update rule (or the select rule) doesn't ` +
|
|
225
|
+
"let this user change it (ON CONFLICT DO UPDATE)", table, "update", [], { cause: e });
|
|
226
|
+
}
|
|
227
|
+
// Postgres's own words, not rowstile's: the row was allowed in, but may not be read back (INSERT ...
|
|
228
|
+
// RETURNING, or an ORM that reads the new row, as Prisma's create does), which the select rule decides
|
|
229
|
+
return new Refused(`${err.message}: the write was allowed, but the select rule doesn't let this user read the row ` +
|
|
230
|
+
"back (RETURNING); read it back only if the select rule allows it", table, "select", [], { cause: e });
|
|
231
|
+
}
|
|
232
|
+
const ours = OURS.exec(err.message);
|
|
233
|
+
if (!ours && !err.constraint?.startsWith("authz_") && errorCode(e) === undefined)
|
|
234
|
+
return null;
|
|
235
|
+
const table = err.schema && err.table ? `${err.schema}.${err.table}` : err.table ?? ours?.[2];
|
|
236
|
+
const command = err.constraint?.startsWith("authz_") ? err.constraint.slice(6) : ours?.[1];
|
|
237
|
+
return new Refused(err.message, table, command, err.detail ? err.detail.split("\n") : [], { cause: e });
|
|
238
|
+
}
|
|
239
|
+
/** Whether e is strict sign-in's error: a query that needs to know who is asking, and nobody signed in. */
|
|
240
|
+
export function notSignedIn(e) {
|
|
241
|
+
return sqlstate(e) === "28000";
|
|
242
|
+
}
|
|
243
|
+
/** e as rowstile's error: Refused, NotFound or NotSignedIn as they are, a database refusal as Refused, strict
|
|
244
|
+
* sign-in's error as NotSignedIn; null for anything else. */
|
|
245
|
+
export function translate(e, schemaOf) {
|
|
246
|
+
if (e instanceof Refused || e instanceof NotFound || e instanceof NotSignedIn)
|
|
247
|
+
return e;
|
|
248
|
+
const r = refusal(e, schemaOf);
|
|
249
|
+
if (r)
|
|
250
|
+
return r;
|
|
251
|
+
if (notSignedIn(e)) {
|
|
252
|
+
return new NotSignedIn("nobody signed in in this transaction: every transaction must begin with authz.act_as() " +
|
|
253
|
+
"(the drivers' packages do it; is this query outside them?)", { cause: e });
|
|
254
|
+
}
|
|
255
|
+
return null;
|
|
256
|
+
}
|
|
257
|
+
/** The problem body and status for e (Refused: 403, NotFound: 404), or null. */
|
|
258
|
+
export function problemOf(e) {
|
|
259
|
+
const t = translate(e);
|
|
260
|
+
return t instanceof Refused || t instanceof NotFound ? t.problem() : null;
|
|
261
|
+
}
|
|
262
|
+
/** A Response (application/problem+json) for e, or null: for route handlers. */
|
|
263
|
+
export function problemResponse(e) {
|
|
264
|
+
const p = problemOf(e);
|
|
265
|
+
return p ? new Response(JSON.stringify(p), { status: p.status, headers: { "content-type": "application/problem+json" } }) : null;
|
|
266
|
+
}
|
|
267
|
+
/** The errors among authz.connection_check()'s rows. */
|
|
268
|
+
export function checkProblems(rows) {
|
|
269
|
+
return rows.filter((r) => r.severity === "error").map((r) => r.problem);
|
|
270
|
+
}
|
|
271
|
+
// The policy names tables with their schema; a table named without one (a model that names no schema) is
|
|
272
|
+
// looked up on the search_path
|
|
273
|
+
const EXPLAIN_RULE = "SELECT authz.explain_rule(coalesce((SELECT n.nspname || '.' || c.relname FROM pg_catalog.pg_class c " +
|
|
274
|
+
"JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace WHERE position('.' in $1::text) = 0 " +
|
|
275
|
+
"AND c.oid = pg_catalog.to_regclass(pg_catalog.quote_ident($1::text))), $1::text), $2, $3, $4::jsonb) AS e";
|
|
276
|
+
/** The runtime's functions over q (a signed-in transaction, or something that signs each query in). */
|
|
277
|
+
export function calls(q) {
|
|
278
|
+
const one = async (text, values) => (await q.query(text, values)).rows[0];
|
|
279
|
+
const c = {
|
|
280
|
+
can: async (type, id, perm) => Boolean((await one("SELECT authz.can($1, $2::text, $3) AS ok", [type, idText(id), perm])).ok),
|
|
281
|
+
perms: async (type, id) => ((await one("SELECT authz.perms($1, $2::text) AS p", [type, idText(id)])).p ?? []),
|
|
282
|
+
permsOf: async (type, ids) => {
|
|
283
|
+
const rows = (await q.query("SELECT id, perms FROM authz.perms_of($1, $2::text[])", [type, ids.map(idText)])).rows;
|
|
284
|
+
return Object.fromEntries(rows.map((r) => [r.id, r.perms ?? []]));
|
|
285
|
+
},
|
|
286
|
+
list: async (type, perm, page = {}) => (await q.query("SELECT x FROM authz.list($1, $2, $3, $4) x", [type, perm, page.after === undefined ? null : idText(page.after), page.limit ?? null])).rows.map((r) => r.x),
|
|
287
|
+
listShares: async (type, id) => (await q.query("SELECT * FROM authz.list_shares($1, $2::text)", [type, idText(id)])).rows,
|
|
288
|
+
share: async (type, id, relation, subjectType, subjectId, subjectRelation = "") => {
|
|
289
|
+
// void functions in FROM: some drivers (Prisma) can't read a void column
|
|
290
|
+
await q.query("SELECT 1 AS ok FROM authz.share($1, $2::text, $3, $4, $5::text, $6)", [type, idText(id), relation, subjectType, idText(subjectId), subjectRelation]);
|
|
291
|
+
},
|
|
292
|
+
unshare: async (type, id, relation, subjectType, subjectId, subjectRelation = "") => {
|
|
293
|
+
await q.query("SELECT 1 AS ok FROM authz.unshare($1, $2::text, $3, $4, $5::text, $6)", [type, idText(id), relation, subjectType, idText(subjectId), subjectRelation]);
|
|
294
|
+
},
|
|
295
|
+
requestAccess: async (type, id, relation, reason) => String((await one("SELECT authz.request_access($1, $2::text, $3, $4) AS id", [type, idText(id), relation, reason])).id),
|
|
296
|
+
explainRule: async (table, command, id, row) => ((await one(EXPLAIN_RULE, [table, command, id === undefined ? null : idText(id), row === undefined ? null : JSON.stringify(row)])).e ?? null),
|
|
297
|
+
connectionCheck: async () => (await q.query("SELECT severity, problem FROM authz.connection_check()", [])).rows,
|
|
298
|
+
/** The result of an UPDATE or DELETE (rows, a count, or a driver's result): returned if it changed a row,
|
|
299
|
+
* otherwise NotFound (the user can't see the row) or Refused (they may not, and why). */
|
|
300
|
+
expect: async (result, table, command, id, row) => {
|
|
301
|
+
if (changed(result))
|
|
302
|
+
return result;
|
|
303
|
+
throw verdict(table, command, id, await c.explainRule(table, command, id, row));
|
|
304
|
+
},
|
|
305
|
+
/** Throws ConnectionProblem if this connection skips row-level security. As nobody: it runs at start-up,
|
|
306
|
+
* where there is no request to ask who is signed in. */
|
|
307
|
+
check: () => actingAs(null, async () => {
|
|
308
|
+
const problems = checkProblems(await c.connectionCheck());
|
|
309
|
+
if (problems.length)
|
|
310
|
+
throw new ConnectionProblem(problems);
|
|
311
|
+
}),
|
|
312
|
+
};
|
|
313
|
+
return c;
|
|
314
|
+
}
|
|
315
|
+
/** Whether an UPDATE or DELETE's result changed anything: rows, a count, {count}, {rowCount}, postgres.js's .count. */
|
|
316
|
+
export function changed(result) {
|
|
317
|
+
if (typeof result === "number" || typeof result === "bigint")
|
|
318
|
+
return Number(result) > 0;
|
|
319
|
+
if (result && typeof result === "object") {
|
|
320
|
+
const o = result;
|
|
321
|
+
for (const k of ["rowCount", "count", "rowsAffected", "affectedRows"]) {
|
|
322
|
+
if (typeof o[k] === "number")
|
|
323
|
+
return o[k] > 0;
|
|
324
|
+
}
|
|
325
|
+
if (Array.isArray(result))
|
|
326
|
+
return result.length > 0;
|
|
327
|
+
if (Array.isArray(o.rows))
|
|
328
|
+
return o.rows.length > 0;
|
|
329
|
+
}
|
|
330
|
+
return Boolean(result);
|
|
331
|
+
}
|
|
332
|
+
/** What an UPDATE or DELETE that changed nothing was: NotFound when the row isn't there for this user (why is
|
|
333
|
+
* null), or when the rule allows the write (its first line says yes: the statement matched nothing for
|
|
334
|
+
* another reason, such as a where with more than the key); Refused with the reason otherwise. */
|
|
335
|
+
export function verdict(table, command, id, why) {
|
|
336
|
+
if (why === null || /^\s*yes\b/.test(why[0] ?? ""))
|
|
337
|
+
return new NotFound(table, idText(id));
|
|
338
|
+
return new Refused(`permission denied: may not ${command} ${table} ${idText(id)}`, table, command, why);
|
|
339
|
+
}
|
package/package.json
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@rowstile/client",
|
|
3
|
+
"version": "0.1.0-alpha.2",
|
|
4
|
+
"description": "rowstile for TypeScript apps: who each transaction acts for, refusals as errors, generated names",
|
|
5
|
+
"license": "Apache-2.0",
|
|
6
|
+
"repository": { "type": "git", "url": "git+https://github.com/rowstile/rowstile.git", "directory": "sdk/typescript/client" },
|
|
7
|
+
"type": "module",
|
|
8
|
+
"main": "./dist/index.js",
|
|
9
|
+
"types": "./dist/index.d.ts",
|
|
10
|
+
"exports": { ".": { "types": "./dist/index.d.ts", "default": "./dist/index.js" } },
|
|
11
|
+
"files": ["dist"],
|
|
12
|
+
"sideEffects": false,
|
|
13
|
+
"dependencies": {},
|
|
14
|
+
"peerDependencies": {}
|
|
15
|
+
}
|