@nuptechs/tenant-data 0.0.0-stage → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +111 -2
- package/dist/index.cjs +538 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +499 -0
- package/dist/index.d.ts +499 -0
- package/dist/index.js +498 -0
- package/dist/index.js.map +1 -0
- package/package.json +47 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 NuPtechs
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,112 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @nuptechs/tenant-data
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
A small, dependency-free multi-tenant **data wall** for PostgreSQL + Node.js.
|
|
4
|
+
|
|
5
|
+
It makes tenant isolation a property of the **database**, not of every query
|
|
6
|
+
you remember to filter. You generate Row-Level Security (RLS) policies from one
|
|
7
|
+
audited source, bind the current tenant/user per transaction, and fail **closed**
|
|
8
|
+
when there is no tenant in context.
|
|
9
|
+
|
|
10
|
+
- **Two axes**: isolate by organization (`organization_id`) and/or by individual
|
|
11
|
+
user (`user_id`) — including both as a single `AND` predicate.
|
|
12
|
+
- **Transitive isolation**: child tables whose owner lives on a parent table.
|
|
13
|
+
- **Shared rows**: a `NULL` owner can mean a shared/built-in row (read by all,
|
|
14
|
+
written by none).
|
|
15
|
+
- **Fail-closed**: an empty/unset GUC matches zero rows; a boot guard refuses to
|
|
16
|
+
start on a superuser/`BYPASSRLS` connection.
|
|
17
|
+
- **Zero runtime dependencies.** ESM + CJS. TypeScript types included.
|
|
18
|
+
|
|
19
|
+
## Install
|
|
20
|
+
|
|
21
|
+
```bash
|
|
22
|
+
npm install @nuptechs/tenant-data
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
## How it works
|
|
26
|
+
|
|
27
|
+
Isolation rests on three pieces you wire once:
|
|
28
|
+
|
|
29
|
+
1. **Policies** — generate the RLS wall per table (`ENABLE` + `FORCE` + one
|
|
30
|
+
policy per command), comparing the owner column to a GUC
|
|
31
|
+
(`current_setting('app.current_user_id', true)`).
|
|
32
|
+
2. **Binding** — on each request/job, set that GUC on the connection for the
|
|
33
|
+
duration of the unit of work, inside your transaction.
|
|
34
|
+
3. **Boot guard** — assert the app connects as a non-superuser role without
|
|
35
|
+
`BYPASSRLS`, so the policies are actually enforced.
|
|
36
|
+
|
|
37
|
+
## Quick start
|
|
38
|
+
|
|
39
|
+
### 1. Generate the policy SQL (run in a migration)
|
|
40
|
+
|
|
41
|
+
```ts
|
|
42
|
+
import { buildPrincipalRlsPolicySql, buildTransitiveRlsPolicySql } from "@nuptechs/tenant-data";
|
|
43
|
+
|
|
44
|
+
// Table owned directly by a user (has a user_id column):
|
|
45
|
+
const materialsWall = buildPrincipalRlsPolicySql({ schema: "app", table: "materials" });
|
|
46
|
+
|
|
47
|
+
// Child table with no owner column — owner lives on the parent:
|
|
48
|
+
const topicsWall = buildTransitiveRlsPolicySql({
|
|
49
|
+
schema: "app",
|
|
50
|
+
table: "topics",
|
|
51
|
+
foreignKeyColumn: "subject_id",
|
|
52
|
+
parentTable: "subjects",
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
await db.execute(materialsWall);
|
|
56
|
+
await db.execute(topicsWall);
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
The per-user predicate is
|
|
60
|
+
`user_id = NULLIF(current_setting('app.current_user_id', true), '')` — the
|
|
61
|
+
`NULLIF` makes an empty GUC behave like an unset one, so a recycled pooled
|
|
62
|
+
connection never leaks the previous owner's rows.
|
|
63
|
+
|
|
64
|
+
### 2. Bind the current principal per unit of work
|
|
65
|
+
|
|
66
|
+
```ts
|
|
67
|
+
import { withTenantAndPrincipalTransaction } from "@nuptechs/tenant-data";
|
|
68
|
+
|
|
69
|
+
await withTenantAndPrincipalTransaction(pool, { principal: userId }, async (conn) => {
|
|
70
|
+
// Every statement here sees only this user's rows — enforced by the database.
|
|
71
|
+
await conn.query("update materials set title = $1 where id = $2", [title, id]);
|
|
72
|
+
});
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
### 3. Guard the connection role at boot
|
|
76
|
+
|
|
77
|
+
```ts
|
|
78
|
+
import { assertConnectionRole } from "@nuptechs/tenant-data";
|
|
79
|
+
|
|
80
|
+
await assertConnectionRole(conn); // throws if the role is superuser / BYPASSRLS
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
## API
|
|
84
|
+
|
|
85
|
+
The public surface is the package barrel (`index`). Highlights:
|
|
86
|
+
|
|
87
|
+
| Area | Exports |
|
|
88
|
+
| --- | --- |
|
|
89
|
+
| Policy generation | `buildTenantRlsPolicySql`, `buildPrincipalRlsPolicySql`, `buildTenantAndPrincipalRlsPolicySql`, `buildTransitiveRlsPolicySql` |
|
|
90
|
+
| Context | `runWithTenant`, `runWithTenantAndPrincipal`, `getCurrentTenant`, `getCurrentPrincipal`, `requireCurrentTenant`, `requireCurrentPrincipal` |
|
|
91
|
+
| Transactions | `withTenantTransaction`, `withTenantAndPrincipalTransaction` |
|
|
92
|
+
| Boot guard | `assertConnectionRole`, `assertAppRole`, `readCurrentRole` |
|
|
93
|
+
| Migration helper | `planAddTenantColumn`, `assertRlsCoverage`, `withMigrationLock` |
|
|
94
|
+
| Storage / cache scoping | `createTenantObjectStore`, `createTenantCache` |
|
|
95
|
+
| Identity seam | `TenantIdentityReader`, `runWithResolvedTenant`, `runWithResolvedTenantAndPrincipal` |
|
|
96
|
+
| Keys | `PRINCIPAL_GUC_KEY`, `TENANT_GUC_KEY` |
|
|
97
|
+
|
|
98
|
+
The database seam is driver-agnostic: a connection only needs `query()` /
|
|
99
|
+
`connect()` / `release()`, which node-postgres and most drivers already provide.
|
|
100
|
+
|
|
101
|
+
## Development
|
|
102
|
+
|
|
103
|
+
```bash
|
|
104
|
+
npm install
|
|
105
|
+
npm run build # tsup → dist (ESM + CJS + d.ts)
|
|
106
|
+
npm test # vitest
|
|
107
|
+
npm run typecheck
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
## License
|
|
111
|
+
|
|
112
|
+
[MIT](./LICENSE)
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,538 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var async_hooks = require('async_hooks');
|
|
4
|
+
|
|
5
|
+
// src/errors.ts
|
|
6
|
+
var NupError = class extends Error {
|
|
7
|
+
constructor(message, code, statusCode = 500) {
|
|
8
|
+
super(message);
|
|
9
|
+
this.code = code;
|
|
10
|
+
this.statusCode = statusCode;
|
|
11
|
+
this.name = this.constructor.name;
|
|
12
|
+
}
|
|
13
|
+
code;
|
|
14
|
+
statusCode;
|
|
15
|
+
};
|
|
16
|
+
var ValidationError = class extends NupError {
|
|
17
|
+
constructor(message) {
|
|
18
|
+
super(message, "VALIDATION_ERROR", 400);
|
|
19
|
+
}
|
|
20
|
+
};
|
|
21
|
+
var MissingTenantContextError = class extends NupError {
|
|
22
|
+
constructor(message = "no organization_id in context \u2014 refusing to touch tenant-scoped data (fail-closed)") {
|
|
23
|
+
super(message, "MISSING_TENANT_CONTEXT", 500);
|
|
24
|
+
}
|
|
25
|
+
};
|
|
26
|
+
var MissingPrincipalContextError = class extends NupError {
|
|
27
|
+
constructor(message = "no principal (user) in context \u2014 refusing to touch per-user data (fail-closed)") {
|
|
28
|
+
super(message, "MISSING_PRINCIPAL_CONTEXT", 500);
|
|
29
|
+
}
|
|
30
|
+
};
|
|
31
|
+
var RlsRoleViolationError = class extends NupError {
|
|
32
|
+
constructor(message) {
|
|
33
|
+
super(message, "RLS_ROLE_VIOLATION", 500);
|
|
34
|
+
}
|
|
35
|
+
};
|
|
36
|
+
var TenantKeyEscapeError = class extends NupError {
|
|
37
|
+
constructor(key) {
|
|
38
|
+
super(`object key "${key}" escapes the tenant prefix (absolute path or ".." segment)`, "TENANT_KEY_ESCAPE", 400);
|
|
39
|
+
}
|
|
40
|
+
};
|
|
41
|
+
var RlsCoverageError = class extends NupError {
|
|
42
|
+
constructor(message) {
|
|
43
|
+
super(message, "RLS_COVERAGE_INCOMPLETE", 500);
|
|
44
|
+
}
|
|
45
|
+
};
|
|
46
|
+
var MigrationError = class extends NupError {
|
|
47
|
+
constructor(message) {
|
|
48
|
+
super(message, "MIGRATION_FAILED", 500);
|
|
49
|
+
}
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
// src/tenant-id.ts
|
|
53
|
+
function makeOrganizationId(raw) {
|
|
54
|
+
const trimmed = raw.trim();
|
|
55
|
+
if (trimmed.length === 0) {
|
|
56
|
+
throw new ValidationError("organizationId must be a non-empty string");
|
|
57
|
+
}
|
|
58
|
+
return trimmed;
|
|
59
|
+
}
|
|
60
|
+
function isOrganizationId(value) {
|
|
61
|
+
return typeof value === "string" && value.trim().length > 0;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
// src/principal-id.ts
|
|
65
|
+
function makePrincipalId(raw) {
|
|
66
|
+
const trimmed = raw.trim();
|
|
67
|
+
if (trimmed.length === 0) {
|
|
68
|
+
throw new ValidationError("principalId must be a non-empty string");
|
|
69
|
+
}
|
|
70
|
+
return trimmed;
|
|
71
|
+
}
|
|
72
|
+
function isPrincipalId(value) {
|
|
73
|
+
return typeof value === "string" && value.trim().length > 0;
|
|
74
|
+
}
|
|
75
|
+
var storage = new async_hooks.AsyncLocalStorage();
|
|
76
|
+
function runWithTenant(organizationId, fn) {
|
|
77
|
+
return storage.run({ organizationId }, fn);
|
|
78
|
+
}
|
|
79
|
+
function runWithTenantAndPrincipal(organizationId, principalId, fn) {
|
|
80
|
+
return storage.run({ organizationId, principalId }, fn);
|
|
81
|
+
}
|
|
82
|
+
function getCurrentTenant() {
|
|
83
|
+
return storage.getStore()?.organizationId ?? null;
|
|
84
|
+
}
|
|
85
|
+
function requireCurrentTenant() {
|
|
86
|
+
const organizationId = storage.getStore()?.organizationId;
|
|
87
|
+
if (organizationId == null) {
|
|
88
|
+
throw new MissingTenantContextError();
|
|
89
|
+
}
|
|
90
|
+
return organizationId;
|
|
91
|
+
}
|
|
92
|
+
function getCurrentPrincipal() {
|
|
93
|
+
return storage.getStore()?.principalId ?? null;
|
|
94
|
+
}
|
|
95
|
+
function requireCurrentPrincipal() {
|
|
96
|
+
const principalId = storage.getStore()?.principalId;
|
|
97
|
+
if (principalId == null) {
|
|
98
|
+
throw new MissingPrincipalContextError();
|
|
99
|
+
}
|
|
100
|
+
return principalId;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
// src/identity.ts
|
|
104
|
+
function runWithResolvedTenant(reader, fn) {
|
|
105
|
+
const organizationId = reader.readOrganizationId();
|
|
106
|
+
if (organizationId == null) {
|
|
107
|
+
throw new MissingTenantContextError();
|
|
108
|
+
}
|
|
109
|
+
return runWithTenant(organizationId, fn);
|
|
110
|
+
}
|
|
111
|
+
function runWithResolvedTenantAndPrincipal(reader, fn) {
|
|
112
|
+
const organizationId = reader.readOrganizationId();
|
|
113
|
+
if (organizationId == null) {
|
|
114
|
+
throw new MissingTenantContextError();
|
|
115
|
+
}
|
|
116
|
+
const principalId = reader.readPrincipalId?.() ?? null;
|
|
117
|
+
if (principalId == null) {
|
|
118
|
+
throw new MissingPrincipalContextError();
|
|
119
|
+
}
|
|
120
|
+
return runWithTenantAndPrincipal(organizationId, principalId, fn);
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
// src/sql.ts
|
|
124
|
+
var TENANT_GUC_KEY = "app.current_organization_id";
|
|
125
|
+
var PRINCIPAL_GUC_KEY = "app.current_user_id";
|
|
126
|
+
|
|
127
|
+
// src/transaction.ts
|
|
128
|
+
async function withTenantTransaction(pool, work) {
|
|
129
|
+
const organizationId = requireCurrentTenant();
|
|
130
|
+
const conn = await pool.connect();
|
|
131
|
+
try {
|
|
132
|
+
await conn.query("BEGIN");
|
|
133
|
+
await conn.query("SELECT set_config($1, $2, true)", [TENANT_GUC_KEY, organizationId]);
|
|
134
|
+
const result = await work(conn);
|
|
135
|
+
await conn.query("COMMIT");
|
|
136
|
+
return result;
|
|
137
|
+
} catch (err) {
|
|
138
|
+
try {
|
|
139
|
+
await conn.query("ROLLBACK");
|
|
140
|
+
} catch {
|
|
141
|
+
}
|
|
142
|
+
throw err;
|
|
143
|
+
} finally {
|
|
144
|
+
await conn.release();
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
async function withTenantAndPrincipalTransaction(pool, work) {
|
|
148
|
+
const organizationId = requireCurrentTenant();
|
|
149
|
+
const principalId = requireCurrentPrincipal();
|
|
150
|
+
const conn = await pool.connect();
|
|
151
|
+
try {
|
|
152
|
+
await conn.query("BEGIN");
|
|
153
|
+
await conn.query("SELECT set_config($1, $2, true)", [TENANT_GUC_KEY, organizationId]);
|
|
154
|
+
await conn.query("SELECT set_config($1, $2, true)", [PRINCIPAL_GUC_KEY, principalId]);
|
|
155
|
+
const result = await work(conn);
|
|
156
|
+
await conn.query("COMMIT");
|
|
157
|
+
return result;
|
|
158
|
+
} catch (err) {
|
|
159
|
+
try {
|
|
160
|
+
await conn.query("ROLLBACK");
|
|
161
|
+
} catch {
|
|
162
|
+
}
|
|
163
|
+
throw err;
|
|
164
|
+
} finally {
|
|
165
|
+
await conn.release();
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
// src/rls-policy.ts
|
|
170
|
+
var IDENT = /^[a-z_][a-z0-9_]*$/;
|
|
171
|
+
var GUC_KEY = /^[a-z_][a-z0-9_]*\.[a-z_][a-z0-9_]*$/;
|
|
172
|
+
function assertIdent(value, label) {
|
|
173
|
+
if (!IDENT.test(value)) {
|
|
174
|
+
throw new ValidationError(`${label} "${value}" is not a valid lowercase SQL identifier`);
|
|
175
|
+
}
|
|
176
|
+
return value;
|
|
177
|
+
}
|
|
178
|
+
function assertGucKey(value) {
|
|
179
|
+
if (!GUC_KEY.test(value)) {
|
|
180
|
+
throw new ValidationError(`GUC key "${value}" is not a valid namespaced identifier (e.g. app.current_user_id)`);
|
|
181
|
+
}
|
|
182
|
+
return value;
|
|
183
|
+
}
|
|
184
|
+
var COMMAND_SUFFIXES = ["select", "insert", "update", "delete"];
|
|
185
|
+
var DEFAULT_RLS_PREFIXES = [
|
|
186
|
+
"tenant_isolation",
|
|
187
|
+
"principal_isolation",
|
|
188
|
+
"tenant_principal_isolation",
|
|
189
|
+
"transitive_isolation"
|
|
190
|
+
];
|
|
191
|
+
function siblingDropPrefixes(ownPrefix, custom) {
|
|
192
|
+
const customValidated = (custom ?? []).map((p) => assertIdent(p, "dropPolicyPrefix"));
|
|
193
|
+
const all = [...DEFAULT_RLS_PREFIXES, ...customValidated].filter((p) => p !== ownPrefix);
|
|
194
|
+
return [...new Set(all)];
|
|
195
|
+
}
|
|
196
|
+
function renderPolicySql(params) {
|
|
197
|
+
const { schema, table, prefix, match, indexColumns, createIndex, extraDropPrefixes = [] } = params;
|
|
198
|
+
const qualified = `${schema}.${table}`;
|
|
199
|
+
const selectUsing = params.selectUsing ?? match;
|
|
200
|
+
const insertCheck = params.insertCheck ?? match;
|
|
201
|
+
const updateUsing = params.updateUsing ?? match;
|
|
202
|
+
const updateCheck = params.updateCheck ?? match;
|
|
203
|
+
const deleteUsing = params.deleteUsing ?? match;
|
|
204
|
+
const statements = [
|
|
205
|
+
`ALTER TABLE ${qualified} ENABLE ROW LEVEL SECURITY;`,
|
|
206
|
+
`ALTER TABLE ${qualified} FORCE ROW LEVEL SECURITY;`,
|
|
207
|
+
...extraDropPrefixes.flatMap(
|
|
208
|
+
(p) => COMMAND_SUFFIXES.map((cmd) => `DROP POLICY IF EXISTS ${p}_${cmd} ON ${qualified};`)
|
|
209
|
+
),
|
|
210
|
+
`DROP POLICY IF EXISTS ${prefix}_select ON ${qualified};`,
|
|
211
|
+
`CREATE POLICY ${prefix}_select ON ${qualified} FOR SELECT USING (${selectUsing});`,
|
|
212
|
+
`DROP POLICY IF EXISTS ${prefix}_insert ON ${qualified};`,
|
|
213
|
+
`CREATE POLICY ${prefix}_insert ON ${qualified} FOR INSERT WITH CHECK (${insertCheck});`,
|
|
214
|
+
`DROP POLICY IF EXISTS ${prefix}_update ON ${qualified};`,
|
|
215
|
+
`CREATE POLICY ${prefix}_update ON ${qualified} FOR UPDATE USING (${updateUsing}) WITH CHECK (${updateCheck});`,
|
|
216
|
+
`DROP POLICY IF EXISTS ${prefix}_delete ON ${qualified};`,
|
|
217
|
+
`CREATE POLICY ${prefix}_delete ON ${qualified} FOR DELETE USING (${deleteUsing});`
|
|
218
|
+
];
|
|
219
|
+
if (createIndex && indexColumns.length > 0) {
|
|
220
|
+
const cols = indexColumns.join(", ");
|
|
221
|
+
const idxName = `${table}_${indexColumns.join("_")}_idx`;
|
|
222
|
+
statements.push(`CREATE INDEX IF NOT EXISTS ${idxName} ON ${qualified} (${cols});`);
|
|
223
|
+
}
|
|
224
|
+
return `${statements.join("\n")}
|
|
225
|
+
`;
|
|
226
|
+
}
|
|
227
|
+
function buildTenantRlsPolicySql(options) {
|
|
228
|
+
const schema = assertIdent(options.schema ?? "public", "schema");
|
|
229
|
+
const table = assertIdent(options.table, "table");
|
|
230
|
+
const column = assertIdent(options.tenantColumn ?? "organization_id", "tenantColumn");
|
|
231
|
+
const prefix = assertIdent(options.policyPrefix ?? "tenant_isolation", "policyPrefix");
|
|
232
|
+
const createIndex = options.createIndex ?? true;
|
|
233
|
+
const cast = options.tenantColumnType ? `::${assertIdent(options.tenantColumnType, "tenantColumnType")}` : "";
|
|
234
|
+
const match = `${column} = current_setting('${TENANT_GUC_KEY}', true)${cast}`;
|
|
235
|
+
const extraDropPrefixes = (options.dropPolicyPrefixes ?? []).map((p) => assertIdent(p, "dropPolicyPrefix"));
|
|
236
|
+
return renderPolicySql({ schema, table, prefix, match, indexColumns: [column], createIndex, extraDropPrefixes });
|
|
237
|
+
}
|
|
238
|
+
function buildPrincipalRlsPolicySql(options) {
|
|
239
|
+
const schema = assertIdent(options.schema ?? "public", "schema");
|
|
240
|
+
const table = assertIdent(options.table, "table");
|
|
241
|
+
const column = assertIdent(options.principalColumn ?? "user_id", "principalColumn");
|
|
242
|
+
const prefix = assertIdent(options.policyPrefix ?? "principal_isolation", "policyPrefix");
|
|
243
|
+
const createIndex = options.createIndex ?? true;
|
|
244
|
+
const cast = options.principalColumnType ? `::${assertIdent(options.principalColumnType, "principalColumnType")}` : "";
|
|
245
|
+
const own = `${column} = NULLIF(current_setting('${PRINCIPAL_GUC_KEY}', true), '')${cast}`;
|
|
246
|
+
const readPredicate = options.allowSharedNullOwner ? `(${own}) OR ${column} IS NULL` : own;
|
|
247
|
+
return renderPolicySql({
|
|
248
|
+
schema,
|
|
249
|
+
table,
|
|
250
|
+
prefix,
|
|
251
|
+
match: own,
|
|
252
|
+
selectUsing: readPredicate,
|
|
253
|
+
indexColumns: [column],
|
|
254
|
+
createIndex,
|
|
255
|
+
extraDropPrefixes: siblingDropPrefixes(prefix, options.dropPolicyPrefixes)
|
|
256
|
+
});
|
|
257
|
+
}
|
|
258
|
+
function buildTenantAndPrincipalRlsPolicySql(options) {
|
|
259
|
+
const schema = assertIdent(options.schema ?? "public", "schema");
|
|
260
|
+
const table = assertIdent(options.table, "table");
|
|
261
|
+
const tenantColumn = assertIdent(options.tenantColumn ?? "organization_id", "tenantColumn");
|
|
262
|
+
const principalColumn = assertIdent(options.principalColumn ?? "user_id", "principalColumn");
|
|
263
|
+
const prefix = assertIdent(options.policyPrefix ?? "tenant_principal_isolation", "policyPrefix");
|
|
264
|
+
const createIndex = options.createIndex ?? true;
|
|
265
|
+
const tenantCast = options.tenantColumnType ? `::${assertIdent(options.tenantColumnType, "tenantColumnType")}` : "";
|
|
266
|
+
const principalCast = options.principalColumnType ? `::${assertIdent(options.principalColumnType, "principalColumnType")}` : "";
|
|
267
|
+
const tenantMatch = `${tenantColumn} = NULLIF(current_setting('${TENANT_GUC_KEY}', true), '')${tenantCast}`;
|
|
268
|
+
const principalMatch = `${principalColumn} = NULLIF(current_setting('${PRINCIPAL_GUC_KEY}', true), '')${principalCast}`;
|
|
269
|
+
const match = `(${tenantMatch}) AND (${principalMatch})`;
|
|
270
|
+
return renderPolicySql({
|
|
271
|
+
schema,
|
|
272
|
+
table,
|
|
273
|
+
prefix,
|
|
274
|
+
match,
|
|
275
|
+
indexColumns: [tenantColumn, principalColumn],
|
|
276
|
+
createIndex,
|
|
277
|
+
extraDropPrefixes: siblingDropPrefixes(prefix, options.dropPolicyPrefixes)
|
|
278
|
+
});
|
|
279
|
+
}
|
|
280
|
+
function buildTransitiveRlsPolicySql(options) {
|
|
281
|
+
const schema = assertIdent(options.schema ?? "public", "schema");
|
|
282
|
+
const table = assertIdent(options.table, "table");
|
|
283
|
+
const fk = assertIdent(options.foreignKeyColumn, "foreignKeyColumn");
|
|
284
|
+
const parentSchema = assertIdent(options.parentSchema ?? options.schema ?? "public", "parentSchema");
|
|
285
|
+
const parentTable = assertIdent(options.parentTable, "parentTable");
|
|
286
|
+
const parentKey = assertIdent(options.parentKeyColumn ?? "id", "parentKeyColumn");
|
|
287
|
+
const ownerColumn = assertIdent(options.parentOwnerColumn ?? "user_id", "parentOwnerColumn");
|
|
288
|
+
const gucKey = assertGucKey(options.ownerGucKey ?? PRINCIPAL_GUC_KEY);
|
|
289
|
+
const prefix = assertIdent(options.policyPrefix ?? "transitive_isolation", "policyPrefix");
|
|
290
|
+
const createIndex = options.createIndex ?? true;
|
|
291
|
+
const childFk = `${table}.${fk}`;
|
|
292
|
+
const parentQualified = `${parentSchema}.${parentTable}`;
|
|
293
|
+
const ownerMatch = `p.${ownerColumn} = NULLIF(current_setting('${gucKey}', true), '')`;
|
|
294
|
+
const existsOwned = `EXISTS (SELECT 1 FROM ${parentQualified} p WHERE p.${parentKey} = ${childFk} AND ${ownerMatch})`;
|
|
295
|
+
const existsOwnedOrShared = `EXISTS (SELECT 1 FROM ${parentQualified} p WHERE p.${parentKey} = ${childFk} AND (${ownerMatch} OR p.${ownerColumn} IS NULL))`;
|
|
296
|
+
const readPredicate = options.parentAllowSharedNullOwner ? existsOwnedOrShared : existsOwned;
|
|
297
|
+
return renderPolicySql({
|
|
298
|
+
schema,
|
|
299
|
+
table,
|
|
300
|
+
prefix,
|
|
301
|
+
match: existsOwned,
|
|
302
|
+
// writes always require an OWNED parent
|
|
303
|
+
selectUsing: readPredicate,
|
|
304
|
+
indexColumns: [fk],
|
|
305
|
+
createIndex,
|
|
306
|
+
extraDropPrefixes: siblingDropPrefixes(prefix, options.dropPolicyPrefixes)
|
|
307
|
+
});
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
// src/boot-check.ts
|
|
311
|
+
async function readCurrentRole(conn) {
|
|
312
|
+
const result = await conn.query(
|
|
313
|
+
"SELECT current_user, rolsuper, rolbypassrls FROM pg_roles WHERE rolname = current_user"
|
|
314
|
+
);
|
|
315
|
+
const row = result.rows[0];
|
|
316
|
+
if (row === void 0) {
|
|
317
|
+
throw new RlsRoleViolationError("could not resolve the current database role from pg_roles");
|
|
318
|
+
}
|
|
319
|
+
return {
|
|
320
|
+
rolname: row.current_user,
|
|
321
|
+
isSuperuser: row.rolsuper === true,
|
|
322
|
+
bypassRls: row.rolbypassrls === true
|
|
323
|
+
};
|
|
324
|
+
}
|
|
325
|
+
function assertAppRole(caps) {
|
|
326
|
+
if (caps.isSuperuser) {
|
|
327
|
+
throw new RlsRoleViolationError(
|
|
328
|
+
`database role "${caps.rolname}" is a superuser and bypasses RLS \u2014 use a dedicated non-owner app role`
|
|
329
|
+
);
|
|
330
|
+
}
|
|
331
|
+
if (caps.bypassRls) {
|
|
332
|
+
throw new RlsRoleViolationError(`database role "${caps.rolname}" has BYPASSRLS \u2014 use a role with NOBYPASSRLS`);
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
async function assertConnectionRole(conn) {
|
|
336
|
+
const caps = await readCurrentRole(conn);
|
|
337
|
+
assertAppRole(caps);
|
|
338
|
+
return caps;
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
// src/storage.ts
|
|
342
|
+
function tenantObjectPrefix(organizationId) {
|
|
343
|
+
return `org/${organizationId}/`;
|
|
344
|
+
}
|
|
345
|
+
function assertSafeKey(key) {
|
|
346
|
+
if (key.startsWith("/") || key.split("/").some((segment) => segment === "..")) {
|
|
347
|
+
throw new TenantKeyEscapeError(key);
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
function createTenantObjectStore(backend) {
|
|
351
|
+
const scopedKey = (key) => {
|
|
352
|
+
assertSafeKey(key);
|
|
353
|
+
return `${tenantObjectPrefix(requireCurrentTenant())}${key}`;
|
|
354
|
+
};
|
|
355
|
+
return {
|
|
356
|
+
put: async (key, body, opts) => (
|
|
357
|
+
// exactOptionalPropertyTypes: only forward contentType when it is set.
|
|
358
|
+
backend.put(scopedKey(key), body, opts?.contentType !== void 0 ? { contentType: opts.contentType } : {})
|
|
359
|
+
),
|
|
360
|
+
get: async (key) => backend.get(scopedKey(key)),
|
|
361
|
+
delete: async (key) => backend.delete(scopedKey(key)),
|
|
362
|
+
list: async (prefix) => {
|
|
363
|
+
const tenantPrefix = tenantObjectPrefix(requireCurrentTenant());
|
|
364
|
+
const callerPrefix = prefix ?? "";
|
|
365
|
+
assertSafeKey(callerPrefix);
|
|
366
|
+
const keys = await backend.list(`${tenantPrefix}${callerPrefix}`);
|
|
367
|
+
return keys.map((key) => key.startsWith(tenantPrefix) ? key.slice(tenantPrefix.length) : key);
|
|
368
|
+
}
|
|
369
|
+
};
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
// src/cache.ts
|
|
373
|
+
function tenantCacheNamespace(organizationId) {
|
|
374
|
+
return `org:${organizationId}:`;
|
|
375
|
+
}
|
|
376
|
+
function createTenantCache(backend) {
|
|
377
|
+
const scopedKey = (key) => `${tenantCacheNamespace(requireCurrentTenant())}${key}`;
|
|
378
|
+
return {
|
|
379
|
+
get: async (key) => backend.get(scopedKey(key)),
|
|
380
|
+
set: async (key, value, opts) => (
|
|
381
|
+
// exactOptionalPropertyTypes: only forward ttlSeconds when it is set.
|
|
382
|
+
backend.set(scopedKey(key), value, opts?.ttlSeconds !== void 0 ? { ttlSeconds: opts.ttlSeconds } : {})
|
|
383
|
+
),
|
|
384
|
+
delete: async (key) => backend.delete(scopedKey(key))
|
|
385
|
+
};
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
// src/migration.ts
|
|
389
|
+
var IDENT2 = /^[a-z_][a-z0-9_]*$/;
|
|
390
|
+
function assertIdent2(value, label) {
|
|
391
|
+
if (!IDENT2.test(value)) {
|
|
392
|
+
throw new ValidationError(`${label} "${value}" is not a valid lowercase SQL identifier`);
|
|
393
|
+
}
|
|
394
|
+
return value;
|
|
395
|
+
}
|
|
396
|
+
function planAddTenantColumn(options) {
|
|
397
|
+
const schema = assertIdent2(options.schema ?? "public", "schema");
|
|
398
|
+
const table = assertIdent2(options.table, "table");
|
|
399
|
+
const column = assertIdent2(options.tenantColumn ?? "organization_id", "tenantColumn");
|
|
400
|
+
const type = assertIdent2(options.tenantColumnType ?? "text", "tenantColumnType");
|
|
401
|
+
const qualified = `${schema}.${table}`;
|
|
402
|
+
const expandSql = [
|
|
403
|
+
`ALTER TABLE ${qualified} ADD COLUMN IF NOT EXISTS ${column} ${type};`,
|
|
404
|
+
`CREATE INDEX IF NOT EXISTS ${table}_${column}_idx ON ${qualified} (${column});`
|
|
405
|
+
].join("\n");
|
|
406
|
+
const steps = [
|
|
407
|
+
{
|
|
408
|
+
id: `${table}.expand`,
|
|
409
|
+
phase: "expand",
|
|
410
|
+
description: `add nullable ${column} and its index to ${qualified} (compat with the running version)`,
|
|
411
|
+
sql: `${expandSql}
|
|
412
|
+
`
|
|
413
|
+
}
|
|
414
|
+
];
|
|
415
|
+
if (options.backfillValue !== void 0) {
|
|
416
|
+
const backfillValue = options.backfillValue;
|
|
417
|
+
steps.push({
|
|
418
|
+
id: `${table}.migrate`,
|
|
419
|
+
phase: "migrate",
|
|
420
|
+
description: `backfill ${column} on existing rows of ${qualified} (run as a Job, out of boot)`,
|
|
421
|
+
sql: `UPDATE ${qualified} SET ${column} = ${backfillValue} WHERE ${column} IS NULL;
|
|
422
|
+
`
|
|
423
|
+
});
|
|
424
|
+
}
|
|
425
|
+
const contractSql = [
|
|
426
|
+
`ALTER TABLE ${qualified} ALTER COLUMN ${column} SET NOT NULL;`,
|
|
427
|
+
buildTenantRlsPolicySql({
|
|
428
|
+
schema,
|
|
429
|
+
table,
|
|
430
|
+
tenantColumn: column,
|
|
431
|
+
// exactOptionalPropertyTypes: forward the cast only for a non-text column.
|
|
432
|
+
...type !== "text" ? { tenantColumnType: type } : {}
|
|
433
|
+
})
|
|
434
|
+
].join("\n");
|
|
435
|
+
steps.push({
|
|
436
|
+
id: `${table}.contract`,
|
|
437
|
+
phase: "contract",
|
|
438
|
+
description: `enforce NOT NULL and the full RLS wall on ${qualified} (after a stable deploy)`,
|
|
439
|
+
sql: `${contractSql}`
|
|
440
|
+
});
|
|
441
|
+
return steps;
|
|
442
|
+
}
|
|
443
|
+
function buildAdvisoryLockSql(lockKey) {
|
|
444
|
+
return `SELECT pg_advisory_xact_lock(${lockKey});`;
|
|
445
|
+
}
|
|
446
|
+
async function withMigrationLock(conn, lockKey, run) {
|
|
447
|
+
try {
|
|
448
|
+
await conn.query("BEGIN");
|
|
449
|
+
await conn.query(buildAdvisoryLockSql(lockKey));
|
|
450
|
+
const result = await run();
|
|
451
|
+
await conn.query("COMMIT");
|
|
452
|
+
return result;
|
|
453
|
+
} catch (err) {
|
|
454
|
+
try {
|
|
455
|
+
await conn.query("ROLLBACK");
|
|
456
|
+
} catch {
|
|
457
|
+
}
|
|
458
|
+
throw err;
|
|
459
|
+
}
|
|
460
|
+
}
|
|
461
|
+
var REQUIRED_COMMANDS = ["SELECT", "INSERT", "UPDATE", "DELETE"];
|
|
462
|
+
async function assertRlsCoverage(conn, tables) {
|
|
463
|
+
for (const ref of tables) {
|
|
464
|
+
const schema = assertIdent2(ref.schema ?? "public", "schema");
|
|
465
|
+
const table = assertIdent2(ref.table, "table");
|
|
466
|
+
const qualified = `${schema}.${table}`;
|
|
467
|
+
const flags = await conn.query(
|
|
468
|
+
"SELECT c.relrowsecurity, c.relforcerowsecurity FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = $1 AND c.relname = $2",
|
|
469
|
+
[schema, table]
|
|
470
|
+
);
|
|
471
|
+
const row = flags.rows[0];
|
|
472
|
+
if (row === void 0) {
|
|
473
|
+
throw new RlsCoverageError(`table ${qualified} was not found in pg_class \u2014 cannot verify its RLS wall`);
|
|
474
|
+
}
|
|
475
|
+
const missing = [];
|
|
476
|
+
if (row.relrowsecurity !== true) {
|
|
477
|
+
missing.push("ENABLE ROW LEVEL SECURITY");
|
|
478
|
+
}
|
|
479
|
+
if (row.relforcerowsecurity !== true) {
|
|
480
|
+
missing.push("FORCE ROW LEVEL SECURITY");
|
|
481
|
+
}
|
|
482
|
+
const policies = await conn.query(
|
|
483
|
+
"SELECT cmd FROM pg_policies WHERE schemaname = $1 AND tablename = $2",
|
|
484
|
+
[schema, table]
|
|
485
|
+
);
|
|
486
|
+
const covered = new Set(policies.rows.map((p) => p.cmd.toUpperCase()));
|
|
487
|
+
for (const command of REQUIRED_COMMANDS) {
|
|
488
|
+
if (!covered.has(command) && !covered.has("ALL")) {
|
|
489
|
+
missing.push(`${command} policy`);
|
|
490
|
+
}
|
|
491
|
+
}
|
|
492
|
+
if (missing.length > 0) {
|
|
493
|
+
throw new RlsCoverageError(`table ${qualified} has an incomplete RLS wall \u2014 missing: ${missing.join(", ")}`);
|
|
494
|
+
}
|
|
495
|
+
}
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
exports.MigrationError = MigrationError;
|
|
499
|
+
exports.MissingPrincipalContextError = MissingPrincipalContextError;
|
|
500
|
+
exports.MissingTenantContextError = MissingTenantContextError;
|
|
501
|
+
exports.NupError = NupError;
|
|
502
|
+
exports.PRINCIPAL_GUC_KEY = PRINCIPAL_GUC_KEY;
|
|
503
|
+
exports.RlsCoverageError = RlsCoverageError;
|
|
504
|
+
exports.RlsRoleViolationError = RlsRoleViolationError;
|
|
505
|
+
exports.TENANT_GUC_KEY = TENANT_GUC_KEY;
|
|
506
|
+
exports.TenantKeyEscapeError = TenantKeyEscapeError;
|
|
507
|
+
exports.ValidationError = ValidationError;
|
|
508
|
+
exports.assertAppRole = assertAppRole;
|
|
509
|
+
exports.assertConnectionRole = assertConnectionRole;
|
|
510
|
+
exports.assertRlsCoverage = assertRlsCoverage;
|
|
511
|
+
exports.buildAdvisoryLockSql = buildAdvisoryLockSql;
|
|
512
|
+
exports.buildPrincipalRlsPolicySql = buildPrincipalRlsPolicySql;
|
|
513
|
+
exports.buildTenantAndPrincipalRlsPolicySql = buildTenantAndPrincipalRlsPolicySql;
|
|
514
|
+
exports.buildTenantRlsPolicySql = buildTenantRlsPolicySql;
|
|
515
|
+
exports.buildTransitiveRlsPolicySql = buildTransitiveRlsPolicySql;
|
|
516
|
+
exports.createTenantCache = createTenantCache;
|
|
517
|
+
exports.createTenantObjectStore = createTenantObjectStore;
|
|
518
|
+
exports.getCurrentPrincipal = getCurrentPrincipal;
|
|
519
|
+
exports.getCurrentTenant = getCurrentTenant;
|
|
520
|
+
exports.isOrganizationId = isOrganizationId;
|
|
521
|
+
exports.isPrincipalId = isPrincipalId;
|
|
522
|
+
exports.makeOrganizationId = makeOrganizationId;
|
|
523
|
+
exports.makePrincipalId = makePrincipalId;
|
|
524
|
+
exports.planAddTenantColumn = planAddTenantColumn;
|
|
525
|
+
exports.readCurrentRole = readCurrentRole;
|
|
526
|
+
exports.requireCurrentPrincipal = requireCurrentPrincipal;
|
|
527
|
+
exports.requireCurrentTenant = requireCurrentTenant;
|
|
528
|
+
exports.runWithResolvedTenant = runWithResolvedTenant;
|
|
529
|
+
exports.runWithResolvedTenantAndPrincipal = runWithResolvedTenantAndPrincipal;
|
|
530
|
+
exports.runWithTenant = runWithTenant;
|
|
531
|
+
exports.runWithTenantAndPrincipal = runWithTenantAndPrincipal;
|
|
532
|
+
exports.tenantCacheNamespace = tenantCacheNamespace;
|
|
533
|
+
exports.tenantObjectPrefix = tenantObjectPrefix;
|
|
534
|
+
exports.withMigrationLock = withMigrationLock;
|
|
535
|
+
exports.withTenantAndPrincipalTransaction = withTenantAndPrincipalTransaction;
|
|
536
|
+
exports.withTenantTransaction = withTenantTransaction;
|
|
537
|
+
//# sourceMappingURL=index.cjs.map
|
|
538
|
+
//# sourceMappingURL=index.cjs.map
|