@rowstile/pg 0.0.0-stage → 0.1.0-alpha.3
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 +80 -2
- package/dist/index.d.ts +54 -0
- package/dist/index.js +140 -0
- package/package.json +13 -4
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
CHANGED
|
@@ -1,3 +1,81 @@
|
|
|
1
|
-
#
|
|
1
|
+
# rowstile for TypeScript
|
|
2
2
|
|
|
3
|
-
|
|
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,54 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* rowstile with node-postgres (pg).
|
|
3
|
+
*
|
|
4
|
+
* const db = authz(new Pool({ connectionString }), { user: async () => (await auth())?.user.id });
|
|
5
|
+
* await db.transaction(async (client) => client.query("UPDATE app.notes SET body = $1 WHERE id = $2", [b, id]));
|
|
6
|
+
* await db.query("SELECT * FROM app.notes"); // one statement, in its own signed-in transaction
|
|
7
|
+
*
|
|
8
|
+
* Every transaction signs in with authz.act_as() as whoever the code acts for (actingAs, a job), else user(),
|
|
9
|
+
* else nobody. Nothing uses a session-level SET, so pools and poolers in transaction mode are safe. A refused write
|
|
10
|
+
* throws Refused (with the rule and why), strict sign-in's error NotSignedIn.
|
|
11
|
+
*/
|
|
12
|
+
import type { Pool, PoolClient, QueryResult, QueryResultRow } from "pg";
|
|
13
|
+
import { calls, type UserResolver, type Who } from "@rowstile/client";
|
|
14
|
+
export interface Options {
|
|
15
|
+
/** Who the request is, when nothing set it with actingAs. */
|
|
16
|
+
user?: UserResolver;
|
|
17
|
+
}
|
|
18
|
+
export declare function authz(pool: Pool, options?: Options): {
|
|
19
|
+
can<T extends import("@rowstile/client").ObjectType>(type: T, id: import("@rowstile/client").Id, perm: import("@rowstile/client").Permission<T>): Promise<boolean>;
|
|
20
|
+
perms<T extends import("@rowstile/client").ObjectType>(type: T, id: import("@rowstile/client").Id): Promise<import("@rowstile/client").Permission<T>[]>;
|
|
21
|
+
permsOf<T extends import("@rowstile/client").ObjectType>(type: T, ids: readonly import("@rowstile/client").Id[]): Promise<Record<string, import("@rowstile/client").Permission<T>[]>>;
|
|
22
|
+
list<T extends import("@rowstile/client").ObjectType>(type: T, perm: import("@rowstile/client").Permission<T>, page?: {
|
|
23
|
+
after?: import("@rowstile/client").Id;
|
|
24
|
+
limit?: number;
|
|
25
|
+
}): Promise<string[]>;
|
|
26
|
+
listShares<T extends import("@rowstile/client").ObjectType>(type: T, id: import("@rowstile/client").Id): Promise<import("@rowstile/client").Share[]>;
|
|
27
|
+
share<T extends import("@rowstile/client").SharedType>(type: T, id: import("@rowstile/client").Id, relation: import("@rowstile/client").SharedRelation<T>, subjectType: string, subjectId: import("@rowstile/client").Id, subjectRelation?: string): Promise<void>;
|
|
28
|
+
unshare<T extends import("@rowstile/client").SharedType>(type: T, id: import("@rowstile/client").Id, relation: import("@rowstile/client").SharedRelation<T>, subjectType: string, subjectId: import("@rowstile/client").Id, subjectRelation?: string): Promise<void>;
|
|
29
|
+
requestAccess<T extends import("@rowstile/client").SharedType>(type: T, id: import("@rowstile/client").Id, relation: import("@rowstile/client").SharedRelation<T>, reason: string): Promise<string>;
|
|
30
|
+
explainRule(table: string, command: "insert" | "update" | "delete", id?: import("@rowstile/client").Id, row?: object): Promise<string[] | null>;
|
|
31
|
+
connectionCheck(): Promise<{
|
|
32
|
+
severity: string;
|
|
33
|
+
problem: string;
|
|
34
|
+
}[]>;
|
|
35
|
+
expect<R>(result: R, table: string, command: "update" | "delete", id: import("@rowstile/client").Id, row?: object): Promise<R>;
|
|
36
|
+
check(): Promise<void>;
|
|
37
|
+
pool: Pool;
|
|
38
|
+
/** Runs fn in a transaction signed in as whoever the code acts for (or `who`, if given). */
|
|
39
|
+
transaction: <R>(fn: (client: PoolClient) => Promise<R>, who?: Who) => Promise<R>;
|
|
40
|
+
/** One statement in its own signed-in transaction. */
|
|
41
|
+
query: <T extends QueryResultRow = any>(text: string, values?: unknown[]) => Promise<QueryResult<T>>;
|
|
42
|
+
};
|
|
43
|
+
/** The runtime's functions over a client in a signed-in transaction: calls(client).can("note", 1, "edit"). */
|
|
44
|
+
export { calls };
|
|
45
|
+
/** A function for the React kit's live updates: calls onChange whenever access may have changed (the policy's
|
|
46
|
+
* change feed, NOTIFY authz_changes). It is off until an administrator turns it on, as the owner, in a
|
|
47
|
+
* migration: INSERT INTO authz.settings VALUES ('notify_changes', 'on'), the one table of rowstile's that is
|
|
48
|
+
* written by hand (the reference's "Using it from app code"); the app role can't.
|
|
49
|
+
* One connection listens for every subscriber. Each time it begins to listen, the first time too, it tells
|
|
50
|
+
* every subscriber once: what changed while the connection was being opened was notified to nobody. If it
|
|
51
|
+
* drops, the feed listens again (after half a second, then longer). Give it a pool of its own, straight to
|
|
52
|
+
* Postgres or through a pooler in session mode: LISTEN lasts the session, and through a pooler in transaction
|
|
53
|
+
* mode it hears nothing. */
|
|
54
|
+
export declare function changes(pool: Pool): (onChange: () => void) => () => void;
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
import { actAs, calls, signingIn, translate, } from "@rowstile/client";
|
|
2
|
+
async function signedIn(pool, who, options, fn) {
|
|
3
|
+
const p = await signingIn(options.user, who);
|
|
4
|
+
const client = await pool.connect();
|
|
5
|
+
let broken;
|
|
6
|
+
// node-postgres listens for a lost connection only on idle clients: while this one is out, an error with
|
|
7
|
+
// nobody listening would stop the process. The transaction fails at its next query instead.
|
|
8
|
+
const lost = (e) => { broken = e; };
|
|
9
|
+
client.on("error", lost);
|
|
10
|
+
try {
|
|
11
|
+
await client.query("BEGIN");
|
|
12
|
+
const a = actAs(p);
|
|
13
|
+
await client.query(a.text, a.values);
|
|
14
|
+
const out = await fn(client);
|
|
15
|
+
await client.query("COMMIT");
|
|
16
|
+
return out;
|
|
17
|
+
}
|
|
18
|
+
catch (e) {
|
|
19
|
+
try {
|
|
20
|
+
await client.query("ROLLBACK");
|
|
21
|
+
}
|
|
22
|
+
catch (r) {
|
|
23
|
+
broken = r; // the connection is gone: don't give it back to the pool
|
|
24
|
+
}
|
|
25
|
+
throw translate(e) ?? e;
|
|
26
|
+
}
|
|
27
|
+
finally {
|
|
28
|
+
client.removeListener("error", lost);
|
|
29
|
+
client.release(broken);
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
export function authz(pool, options = {}) {
|
|
33
|
+
const each = { query: (text, values) => signedIn(pool, undefined, options, (c) => c.query(text, values)) };
|
|
34
|
+
return {
|
|
35
|
+
pool,
|
|
36
|
+
/** Runs fn in a transaction signed in as whoever the code acts for (or `who`, if given). */
|
|
37
|
+
transaction: (fn, who) => signedIn(pool, who, options, fn),
|
|
38
|
+
/** One statement in its own signed-in transaction. */
|
|
39
|
+
query: (text, values) => signedIn(pool, undefined, options, (c) => c.query(text, values)),
|
|
40
|
+
/** The runtime's functions (can, permsOf, list, share, ...), each in its own signed-in transaction; inside
|
|
41
|
+
* a transaction, use calls(client) instead. */
|
|
42
|
+
...calls(each),
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
/** The runtime's functions over a client in a signed-in transaction: calls(client).can("note", 1, "edit"). */
|
|
46
|
+
export { calls };
|
|
47
|
+
/** A function for the React kit's live updates: calls onChange whenever access may have changed (the policy's
|
|
48
|
+
* change feed, NOTIFY authz_changes). It is off until an administrator turns it on, as the owner, in a
|
|
49
|
+
* migration: INSERT INTO authz.settings VALUES ('notify_changes', 'on'), the one table of rowstile's that is
|
|
50
|
+
* written by hand (the reference's "Using it from app code"); the app role can't.
|
|
51
|
+
* One connection listens for every subscriber. Each time it begins to listen, the first time too, it tells
|
|
52
|
+
* every subscriber once: what changed while the connection was being opened was notified to nobody. If it
|
|
53
|
+
* drops, the feed listens again (after half a second, then longer). Give it a pool of its own, straight to
|
|
54
|
+
* Postgres or through a pooler in session mode: LISTEN lasts the session, and through a pooler in transaction
|
|
55
|
+
* mode it hears nothing. */
|
|
56
|
+
export function changes(pool) {
|
|
57
|
+
const subscribers = new Set();
|
|
58
|
+
let listening = null;
|
|
59
|
+
let starting = false;
|
|
60
|
+
let retry = null;
|
|
61
|
+
let wait = 500; // before listening again, doubled up to 30 s
|
|
62
|
+
const tell = () => subscribers.forEach((s) => s());
|
|
63
|
+
const again = () => {
|
|
64
|
+
if (retry || subscribers.size === 0)
|
|
65
|
+
return;
|
|
66
|
+
retry = setTimeout(() => { retry = null; start(); }, wait);
|
|
67
|
+
retry.unref?.();
|
|
68
|
+
wait = Math.min(wait * 2, 30_000);
|
|
69
|
+
};
|
|
70
|
+
const start = () => {
|
|
71
|
+
if (listening || starting)
|
|
72
|
+
return;
|
|
73
|
+
starting = true;
|
|
74
|
+
pool.connect().then(async (client) => {
|
|
75
|
+
let gone = false;
|
|
76
|
+
// the connection dropped (the database restarted, say): give the client back as broken, listen again
|
|
77
|
+
const lost = (e) => {
|
|
78
|
+
if (gone)
|
|
79
|
+
return;
|
|
80
|
+
gone = true;
|
|
81
|
+
client.removeAllListeners("notification");
|
|
82
|
+
if (listening === client)
|
|
83
|
+
listening = null;
|
|
84
|
+
client.release(e ?? new Error("the connection ended"));
|
|
85
|
+
again();
|
|
86
|
+
};
|
|
87
|
+
client.on("error", lost);
|
|
88
|
+
client.on("end", () => lost());
|
|
89
|
+
client.on("notification", tell);
|
|
90
|
+
try {
|
|
91
|
+
await client.query("LISTEN authz_changes");
|
|
92
|
+
}
|
|
93
|
+
catch (e) {
|
|
94
|
+
starting = false;
|
|
95
|
+
lost(e);
|
|
96
|
+
return;
|
|
97
|
+
}
|
|
98
|
+
starting = false;
|
|
99
|
+
if (gone)
|
|
100
|
+
return;
|
|
101
|
+
listening = client;
|
|
102
|
+
wait = 500;
|
|
103
|
+
if (subscribers.size === 0)
|
|
104
|
+
stop();
|
|
105
|
+
else
|
|
106
|
+
tell(); // what changed while nobody was listening
|
|
107
|
+
}, () => {
|
|
108
|
+
starting = false;
|
|
109
|
+
again();
|
|
110
|
+
});
|
|
111
|
+
};
|
|
112
|
+
const stop = () => {
|
|
113
|
+
const client = listening;
|
|
114
|
+
if (!client)
|
|
115
|
+
return;
|
|
116
|
+
listening = null;
|
|
117
|
+
for (const event of ["notification", "end", "error"])
|
|
118
|
+
client.removeAllListeners(event);
|
|
119
|
+
const quiet = () => undefined; // until it is back in the pool, which listens itself
|
|
120
|
+
client.on("error", quiet);
|
|
121
|
+
const back = (e) => {
|
|
122
|
+
client.removeListener("error", quiet);
|
|
123
|
+
client.release(e);
|
|
124
|
+
};
|
|
125
|
+
client.query("UNLISTEN authz_changes").then(() => back(), (e) => back(e));
|
|
126
|
+
};
|
|
127
|
+
return (onChange) => {
|
|
128
|
+
subscribers.add(onChange);
|
|
129
|
+
start();
|
|
130
|
+
return () => {
|
|
131
|
+
subscribers.delete(onChange);
|
|
132
|
+
if (subscribers.size === 0) {
|
|
133
|
+
if (retry)
|
|
134
|
+
clearTimeout(retry);
|
|
135
|
+
retry = null;
|
|
136
|
+
stop();
|
|
137
|
+
}
|
|
138
|
+
};
|
|
139
|
+
};
|
|
140
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,15 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@rowstile/pg",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
}
|
|
3
|
+
"version": "0.1.0-alpha.3",
|
|
4
|
+
"description": "rowstile with node-postgres (pg): transactions signed in as the request's user",
|
|
5
|
+
"license": "Apache-2.0",
|
|
6
|
+
"repository": { "type": "git", "url": "git+https://github.com/rowstile/rowstile.git", "directory": "sdk/typescript/pg" },
|
|
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": { "@rowstile/client": "0.1.0-alpha.3" },
|
|
14
|
+
"peerDependencies": { "pg": ">=8" }
|
|
15
|
+
}
|