@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/dist/index.js
ADDED
|
@@ -0,0 +1,498 @@
|
|
|
1
|
+
import { AsyncLocalStorage } from 'async_hooks';
|
|
2
|
+
|
|
3
|
+
// src/errors.ts
|
|
4
|
+
var NupError = class extends Error {
|
|
5
|
+
constructor(message, code, statusCode = 500) {
|
|
6
|
+
super(message);
|
|
7
|
+
this.code = code;
|
|
8
|
+
this.statusCode = statusCode;
|
|
9
|
+
this.name = this.constructor.name;
|
|
10
|
+
}
|
|
11
|
+
code;
|
|
12
|
+
statusCode;
|
|
13
|
+
};
|
|
14
|
+
var ValidationError = class extends NupError {
|
|
15
|
+
constructor(message) {
|
|
16
|
+
super(message, "VALIDATION_ERROR", 400);
|
|
17
|
+
}
|
|
18
|
+
};
|
|
19
|
+
var MissingTenantContextError = class extends NupError {
|
|
20
|
+
constructor(message = "no organization_id in context \u2014 refusing to touch tenant-scoped data (fail-closed)") {
|
|
21
|
+
super(message, "MISSING_TENANT_CONTEXT", 500);
|
|
22
|
+
}
|
|
23
|
+
};
|
|
24
|
+
var MissingPrincipalContextError = class extends NupError {
|
|
25
|
+
constructor(message = "no principal (user) in context \u2014 refusing to touch per-user data (fail-closed)") {
|
|
26
|
+
super(message, "MISSING_PRINCIPAL_CONTEXT", 500);
|
|
27
|
+
}
|
|
28
|
+
};
|
|
29
|
+
var RlsRoleViolationError = class extends NupError {
|
|
30
|
+
constructor(message) {
|
|
31
|
+
super(message, "RLS_ROLE_VIOLATION", 500);
|
|
32
|
+
}
|
|
33
|
+
};
|
|
34
|
+
var TenantKeyEscapeError = class extends NupError {
|
|
35
|
+
constructor(key) {
|
|
36
|
+
super(`object key "${key}" escapes the tenant prefix (absolute path or ".." segment)`, "TENANT_KEY_ESCAPE", 400);
|
|
37
|
+
}
|
|
38
|
+
};
|
|
39
|
+
var RlsCoverageError = class extends NupError {
|
|
40
|
+
constructor(message) {
|
|
41
|
+
super(message, "RLS_COVERAGE_INCOMPLETE", 500);
|
|
42
|
+
}
|
|
43
|
+
};
|
|
44
|
+
var MigrationError = class extends NupError {
|
|
45
|
+
constructor(message) {
|
|
46
|
+
super(message, "MIGRATION_FAILED", 500);
|
|
47
|
+
}
|
|
48
|
+
};
|
|
49
|
+
|
|
50
|
+
// src/tenant-id.ts
|
|
51
|
+
function makeOrganizationId(raw) {
|
|
52
|
+
const trimmed = raw.trim();
|
|
53
|
+
if (trimmed.length === 0) {
|
|
54
|
+
throw new ValidationError("organizationId must be a non-empty string");
|
|
55
|
+
}
|
|
56
|
+
return trimmed;
|
|
57
|
+
}
|
|
58
|
+
function isOrganizationId(value) {
|
|
59
|
+
return typeof value === "string" && value.trim().length > 0;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
// src/principal-id.ts
|
|
63
|
+
function makePrincipalId(raw) {
|
|
64
|
+
const trimmed = raw.trim();
|
|
65
|
+
if (trimmed.length === 0) {
|
|
66
|
+
throw new ValidationError("principalId must be a non-empty string");
|
|
67
|
+
}
|
|
68
|
+
return trimmed;
|
|
69
|
+
}
|
|
70
|
+
function isPrincipalId(value) {
|
|
71
|
+
return typeof value === "string" && value.trim().length > 0;
|
|
72
|
+
}
|
|
73
|
+
var storage = new AsyncLocalStorage();
|
|
74
|
+
function runWithTenant(organizationId, fn) {
|
|
75
|
+
return storage.run({ organizationId }, fn);
|
|
76
|
+
}
|
|
77
|
+
function runWithTenantAndPrincipal(organizationId, principalId, fn) {
|
|
78
|
+
return storage.run({ organizationId, principalId }, fn);
|
|
79
|
+
}
|
|
80
|
+
function getCurrentTenant() {
|
|
81
|
+
return storage.getStore()?.organizationId ?? null;
|
|
82
|
+
}
|
|
83
|
+
function requireCurrentTenant() {
|
|
84
|
+
const organizationId = storage.getStore()?.organizationId;
|
|
85
|
+
if (organizationId == null) {
|
|
86
|
+
throw new MissingTenantContextError();
|
|
87
|
+
}
|
|
88
|
+
return organizationId;
|
|
89
|
+
}
|
|
90
|
+
function getCurrentPrincipal() {
|
|
91
|
+
return storage.getStore()?.principalId ?? null;
|
|
92
|
+
}
|
|
93
|
+
function requireCurrentPrincipal() {
|
|
94
|
+
const principalId = storage.getStore()?.principalId;
|
|
95
|
+
if (principalId == null) {
|
|
96
|
+
throw new MissingPrincipalContextError();
|
|
97
|
+
}
|
|
98
|
+
return principalId;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
// src/identity.ts
|
|
102
|
+
function runWithResolvedTenant(reader, fn) {
|
|
103
|
+
const organizationId = reader.readOrganizationId();
|
|
104
|
+
if (organizationId == null) {
|
|
105
|
+
throw new MissingTenantContextError();
|
|
106
|
+
}
|
|
107
|
+
return runWithTenant(organizationId, fn);
|
|
108
|
+
}
|
|
109
|
+
function runWithResolvedTenantAndPrincipal(reader, fn) {
|
|
110
|
+
const organizationId = reader.readOrganizationId();
|
|
111
|
+
if (organizationId == null) {
|
|
112
|
+
throw new MissingTenantContextError();
|
|
113
|
+
}
|
|
114
|
+
const principalId = reader.readPrincipalId?.() ?? null;
|
|
115
|
+
if (principalId == null) {
|
|
116
|
+
throw new MissingPrincipalContextError();
|
|
117
|
+
}
|
|
118
|
+
return runWithTenantAndPrincipal(organizationId, principalId, fn);
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
// src/sql.ts
|
|
122
|
+
var TENANT_GUC_KEY = "app.current_organization_id";
|
|
123
|
+
var PRINCIPAL_GUC_KEY = "app.current_user_id";
|
|
124
|
+
|
|
125
|
+
// src/transaction.ts
|
|
126
|
+
async function withTenantTransaction(pool, work) {
|
|
127
|
+
const organizationId = requireCurrentTenant();
|
|
128
|
+
const conn = await pool.connect();
|
|
129
|
+
try {
|
|
130
|
+
await conn.query("BEGIN");
|
|
131
|
+
await conn.query("SELECT set_config($1, $2, true)", [TENANT_GUC_KEY, organizationId]);
|
|
132
|
+
const result = await work(conn);
|
|
133
|
+
await conn.query("COMMIT");
|
|
134
|
+
return result;
|
|
135
|
+
} catch (err) {
|
|
136
|
+
try {
|
|
137
|
+
await conn.query("ROLLBACK");
|
|
138
|
+
} catch {
|
|
139
|
+
}
|
|
140
|
+
throw err;
|
|
141
|
+
} finally {
|
|
142
|
+
await conn.release();
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
async function withTenantAndPrincipalTransaction(pool, work) {
|
|
146
|
+
const organizationId = requireCurrentTenant();
|
|
147
|
+
const principalId = requireCurrentPrincipal();
|
|
148
|
+
const conn = await pool.connect();
|
|
149
|
+
try {
|
|
150
|
+
await conn.query("BEGIN");
|
|
151
|
+
await conn.query("SELECT set_config($1, $2, true)", [TENANT_GUC_KEY, organizationId]);
|
|
152
|
+
await conn.query("SELECT set_config($1, $2, true)", [PRINCIPAL_GUC_KEY, principalId]);
|
|
153
|
+
const result = await work(conn);
|
|
154
|
+
await conn.query("COMMIT");
|
|
155
|
+
return result;
|
|
156
|
+
} catch (err) {
|
|
157
|
+
try {
|
|
158
|
+
await conn.query("ROLLBACK");
|
|
159
|
+
} catch {
|
|
160
|
+
}
|
|
161
|
+
throw err;
|
|
162
|
+
} finally {
|
|
163
|
+
await conn.release();
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
// src/rls-policy.ts
|
|
168
|
+
var IDENT = /^[a-z_][a-z0-9_]*$/;
|
|
169
|
+
var GUC_KEY = /^[a-z_][a-z0-9_]*\.[a-z_][a-z0-9_]*$/;
|
|
170
|
+
function assertIdent(value, label) {
|
|
171
|
+
if (!IDENT.test(value)) {
|
|
172
|
+
throw new ValidationError(`${label} "${value}" is not a valid lowercase SQL identifier`);
|
|
173
|
+
}
|
|
174
|
+
return value;
|
|
175
|
+
}
|
|
176
|
+
function assertGucKey(value) {
|
|
177
|
+
if (!GUC_KEY.test(value)) {
|
|
178
|
+
throw new ValidationError(`GUC key "${value}" is not a valid namespaced identifier (e.g. app.current_user_id)`);
|
|
179
|
+
}
|
|
180
|
+
return value;
|
|
181
|
+
}
|
|
182
|
+
var COMMAND_SUFFIXES = ["select", "insert", "update", "delete"];
|
|
183
|
+
var DEFAULT_RLS_PREFIXES = [
|
|
184
|
+
"tenant_isolation",
|
|
185
|
+
"principal_isolation",
|
|
186
|
+
"tenant_principal_isolation",
|
|
187
|
+
"transitive_isolation"
|
|
188
|
+
];
|
|
189
|
+
function siblingDropPrefixes(ownPrefix, custom) {
|
|
190
|
+
const customValidated = (custom ?? []).map((p) => assertIdent(p, "dropPolicyPrefix"));
|
|
191
|
+
const all = [...DEFAULT_RLS_PREFIXES, ...customValidated].filter((p) => p !== ownPrefix);
|
|
192
|
+
return [...new Set(all)];
|
|
193
|
+
}
|
|
194
|
+
function renderPolicySql(params) {
|
|
195
|
+
const { schema, table, prefix, match, indexColumns, createIndex, extraDropPrefixes = [] } = params;
|
|
196
|
+
const qualified = `${schema}.${table}`;
|
|
197
|
+
const selectUsing = params.selectUsing ?? match;
|
|
198
|
+
const insertCheck = params.insertCheck ?? match;
|
|
199
|
+
const updateUsing = params.updateUsing ?? match;
|
|
200
|
+
const updateCheck = params.updateCheck ?? match;
|
|
201
|
+
const deleteUsing = params.deleteUsing ?? match;
|
|
202
|
+
const statements = [
|
|
203
|
+
`ALTER TABLE ${qualified} ENABLE ROW LEVEL SECURITY;`,
|
|
204
|
+
`ALTER TABLE ${qualified} FORCE ROW LEVEL SECURITY;`,
|
|
205
|
+
...extraDropPrefixes.flatMap(
|
|
206
|
+
(p) => COMMAND_SUFFIXES.map((cmd) => `DROP POLICY IF EXISTS ${p}_${cmd} ON ${qualified};`)
|
|
207
|
+
),
|
|
208
|
+
`DROP POLICY IF EXISTS ${prefix}_select ON ${qualified};`,
|
|
209
|
+
`CREATE POLICY ${prefix}_select ON ${qualified} FOR SELECT USING (${selectUsing});`,
|
|
210
|
+
`DROP POLICY IF EXISTS ${prefix}_insert ON ${qualified};`,
|
|
211
|
+
`CREATE POLICY ${prefix}_insert ON ${qualified} FOR INSERT WITH CHECK (${insertCheck});`,
|
|
212
|
+
`DROP POLICY IF EXISTS ${prefix}_update ON ${qualified};`,
|
|
213
|
+
`CREATE POLICY ${prefix}_update ON ${qualified} FOR UPDATE USING (${updateUsing}) WITH CHECK (${updateCheck});`,
|
|
214
|
+
`DROP POLICY IF EXISTS ${prefix}_delete ON ${qualified};`,
|
|
215
|
+
`CREATE POLICY ${prefix}_delete ON ${qualified} FOR DELETE USING (${deleteUsing});`
|
|
216
|
+
];
|
|
217
|
+
if (createIndex && indexColumns.length > 0) {
|
|
218
|
+
const cols = indexColumns.join(", ");
|
|
219
|
+
const idxName = `${table}_${indexColumns.join("_")}_idx`;
|
|
220
|
+
statements.push(`CREATE INDEX IF NOT EXISTS ${idxName} ON ${qualified} (${cols});`);
|
|
221
|
+
}
|
|
222
|
+
return `${statements.join("\n")}
|
|
223
|
+
`;
|
|
224
|
+
}
|
|
225
|
+
function buildTenantRlsPolicySql(options) {
|
|
226
|
+
const schema = assertIdent(options.schema ?? "public", "schema");
|
|
227
|
+
const table = assertIdent(options.table, "table");
|
|
228
|
+
const column = assertIdent(options.tenantColumn ?? "organization_id", "tenantColumn");
|
|
229
|
+
const prefix = assertIdent(options.policyPrefix ?? "tenant_isolation", "policyPrefix");
|
|
230
|
+
const createIndex = options.createIndex ?? true;
|
|
231
|
+
const cast = options.tenantColumnType ? `::${assertIdent(options.tenantColumnType, "tenantColumnType")}` : "";
|
|
232
|
+
const match = `${column} = current_setting('${TENANT_GUC_KEY}', true)${cast}`;
|
|
233
|
+
const extraDropPrefixes = (options.dropPolicyPrefixes ?? []).map((p) => assertIdent(p, "dropPolicyPrefix"));
|
|
234
|
+
return renderPolicySql({ schema, table, prefix, match, indexColumns: [column], createIndex, extraDropPrefixes });
|
|
235
|
+
}
|
|
236
|
+
function buildPrincipalRlsPolicySql(options) {
|
|
237
|
+
const schema = assertIdent(options.schema ?? "public", "schema");
|
|
238
|
+
const table = assertIdent(options.table, "table");
|
|
239
|
+
const column = assertIdent(options.principalColumn ?? "user_id", "principalColumn");
|
|
240
|
+
const prefix = assertIdent(options.policyPrefix ?? "principal_isolation", "policyPrefix");
|
|
241
|
+
const createIndex = options.createIndex ?? true;
|
|
242
|
+
const cast = options.principalColumnType ? `::${assertIdent(options.principalColumnType, "principalColumnType")}` : "";
|
|
243
|
+
const own = `${column} = NULLIF(current_setting('${PRINCIPAL_GUC_KEY}', true), '')${cast}`;
|
|
244
|
+
const readPredicate = options.allowSharedNullOwner ? `(${own}) OR ${column} IS NULL` : own;
|
|
245
|
+
return renderPolicySql({
|
|
246
|
+
schema,
|
|
247
|
+
table,
|
|
248
|
+
prefix,
|
|
249
|
+
match: own,
|
|
250
|
+
selectUsing: readPredicate,
|
|
251
|
+
indexColumns: [column],
|
|
252
|
+
createIndex,
|
|
253
|
+
extraDropPrefixes: siblingDropPrefixes(prefix, options.dropPolicyPrefixes)
|
|
254
|
+
});
|
|
255
|
+
}
|
|
256
|
+
function buildTenantAndPrincipalRlsPolicySql(options) {
|
|
257
|
+
const schema = assertIdent(options.schema ?? "public", "schema");
|
|
258
|
+
const table = assertIdent(options.table, "table");
|
|
259
|
+
const tenantColumn = assertIdent(options.tenantColumn ?? "organization_id", "tenantColumn");
|
|
260
|
+
const principalColumn = assertIdent(options.principalColumn ?? "user_id", "principalColumn");
|
|
261
|
+
const prefix = assertIdent(options.policyPrefix ?? "tenant_principal_isolation", "policyPrefix");
|
|
262
|
+
const createIndex = options.createIndex ?? true;
|
|
263
|
+
const tenantCast = options.tenantColumnType ? `::${assertIdent(options.tenantColumnType, "tenantColumnType")}` : "";
|
|
264
|
+
const principalCast = options.principalColumnType ? `::${assertIdent(options.principalColumnType, "principalColumnType")}` : "";
|
|
265
|
+
const tenantMatch = `${tenantColumn} = NULLIF(current_setting('${TENANT_GUC_KEY}', true), '')${tenantCast}`;
|
|
266
|
+
const principalMatch = `${principalColumn} = NULLIF(current_setting('${PRINCIPAL_GUC_KEY}', true), '')${principalCast}`;
|
|
267
|
+
const match = `(${tenantMatch}) AND (${principalMatch})`;
|
|
268
|
+
return renderPolicySql({
|
|
269
|
+
schema,
|
|
270
|
+
table,
|
|
271
|
+
prefix,
|
|
272
|
+
match,
|
|
273
|
+
indexColumns: [tenantColumn, principalColumn],
|
|
274
|
+
createIndex,
|
|
275
|
+
extraDropPrefixes: siblingDropPrefixes(prefix, options.dropPolicyPrefixes)
|
|
276
|
+
});
|
|
277
|
+
}
|
|
278
|
+
function buildTransitiveRlsPolicySql(options) {
|
|
279
|
+
const schema = assertIdent(options.schema ?? "public", "schema");
|
|
280
|
+
const table = assertIdent(options.table, "table");
|
|
281
|
+
const fk = assertIdent(options.foreignKeyColumn, "foreignKeyColumn");
|
|
282
|
+
const parentSchema = assertIdent(options.parentSchema ?? options.schema ?? "public", "parentSchema");
|
|
283
|
+
const parentTable = assertIdent(options.parentTable, "parentTable");
|
|
284
|
+
const parentKey = assertIdent(options.parentKeyColumn ?? "id", "parentKeyColumn");
|
|
285
|
+
const ownerColumn = assertIdent(options.parentOwnerColumn ?? "user_id", "parentOwnerColumn");
|
|
286
|
+
const gucKey = assertGucKey(options.ownerGucKey ?? PRINCIPAL_GUC_KEY);
|
|
287
|
+
const prefix = assertIdent(options.policyPrefix ?? "transitive_isolation", "policyPrefix");
|
|
288
|
+
const createIndex = options.createIndex ?? true;
|
|
289
|
+
const childFk = `${table}.${fk}`;
|
|
290
|
+
const parentQualified = `${parentSchema}.${parentTable}`;
|
|
291
|
+
const ownerMatch = `p.${ownerColumn} = NULLIF(current_setting('${gucKey}', true), '')`;
|
|
292
|
+
const existsOwned = `EXISTS (SELECT 1 FROM ${parentQualified} p WHERE p.${parentKey} = ${childFk} AND ${ownerMatch})`;
|
|
293
|
+
const existsOwnedOrShared = `EXISTS (SELECT 1 FROM ${parentQualified} p WHERE p.${parentKey} = ${childFk} AND (${ownerMatch} OR p.${ownerColumn} IS NULL))`;
|
|
294
|
+
const readPredicate = options.parentAllowSharedNullOwner ? existsOwnedOrShared : existsOwned;
|
|
295
|
+
return renderPolicySql({
|
|
296
|
+
schema,
|
|
297
|
+
table,
|
|
298
|
+
prefix,
|
|
299
|
+
match: existsOwned,
|
|
300
|
+
// writes always require an OWNED parent
|
|
301
|
+
selectUsing: readPredicate,
|
|
302
|
+
indexColumns: [fk],
|
|
303
|
+
createIndex,
|
|
304
|
+
extraDropPrefixes: siblingDropPrefixes(prefix, options.dropPolicyPrefixes)
|
|
305
|
+
});
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
// src/boot-check.ts
|
|
309
|
+
async function readCurrentRole(conn) {
|
|
310
|
+
const result = await conn.query(
|
|
311
|
+
"SELECT current_user, rolsuper, rolbypassrls FROM pg_roles WHERE rolname = current_user"
|
|
312
|
+
);
|
|
313
|
+
const row = result.rows[0];
|
|
314
|
+
if (row === void 0) {
|
|
315
|
+
throw new RlsRoleViolationError("could not resolve the current database role from pg_roles");
|
|
316
|
+
}
|
|
317
|
+
return {
|
|
318
|
+
rolname: row.current_user,
|
|
319
|
+
isSuperuser: row.rolsuper === true,
|
|
320
|
+
bypassRls: row.rolbypassrls === true
|
|
321
|
+
};
|
|
322
|
+
}
|
|
323
|
+
function assertAppRole(caps) {
|
|
324
|
+
if (caps.isSuperuser) {
|
|
325
|
+
throw new RlsRoleViolationError(
|
|
326
|
+
`database role "${caps.rolname}" is a superuser and bypasses RLS \u2014 use a dedicated non-owner app role`
|
|
327
|
+
);
|
|
328
|
+
}
|
|
329
|
+
if (caps.bypassRls) {
|
|
330
|
+
throw new RlsRoleViolationError(`database role "${caps.rolname}" has BYPASSRLS \u2014 use a role with NOBYPASSRLS`);
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
async function assertConnectionRole(conn) {
|
|
334
|
+
const caps = await readCurrentRole(conn);
|
|
335
|
+
assertAppRole(caps);
|
|
336
|
+
return caps;
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
// src/storage.ts
|
|
340
|
+
function tenantObjectPrefix(organizationId) {
|
|
341
|
+
return `org/${organizationId}/`;
|
|
342
|
+
}
|
|
343
|
+
function assertSafeKey(key) {
|
|
344
|
+
if (key.startsWith("/") || key.split("/").some((segment) => segment === "..")) {
|
|
345
|
+
throw new TenantKeyEscapeError(key);
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
function createTenantObjectStore(backend) {
|
|
349
|
+
const scopedKey = (key) => {
|
|
350
|
+
assertSafeKey(key);
|
|
351
|
+
return `${tenantObjectPrefix(requireCurrentTenant())}${key}`;
|
|
352
|
+
};
|
|
353
|
+
return {
|
|
354
|
+
put: async (key, body, opts) => (
|
|
355
|
+
// exactOptionalPropertyTypes: only forward contentType when it is set.
|
|
356
|
+
backend.put(scopedKey(key), body, opts?.contentType !== void 0 ? { contentType: opts.contentType } : {})
|
|
357
|
+
),
|
|
358
|
+
get: async (key) => backend.get(scopedKey(key)),
|
|
359
|
+
delete: async (key) => backend.delete(scopedKey(key)),
|
|
360
|
+
list: async (prefix) => {
|
|
361
|
+
const tenantPrefix = tenantObjectPrefix(requireCurrentTenant());
|
|
362
|
+
const callerPrefix = prefix ?? "";
|
|
363
|
+
assertSafeKey(callerPrefix);
|
|
364
|
+
const keys = await backend.list(`${tenantPrefix}${callerPrefix}`);
|
|
365
|
+
return keys.map((key) => key.startsWith(tenantPrefix) ? key.slice(tenantPrefix.length) : key);
|
|
366
|
+
}
|
|
367
|
+
};
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
// src/cache.ts
|
|
371
|
+
function tenantCacheNamespace(organizationId) {
|
|
372
|
+
return `org:${organizationId}:`;
|
|
373
|
+
}
|
|
374
|
+
function createTenantCache(backend) {
|
|
375
|
+
const scopedKey = (key) => `${tenantCacheNamespace(requireCurrentTenant())}${key}`;
|
|
376
|
+
return {
|
|
377
|
+
get: async (key) => backend.get(scopedKey(key)),
|
|
378
|
+
set: async (key, value, opts) => (
|
|
379
|
+
// exactOptionalPropertyTypes: only forward ttlSeconds when it is set.
|
|
380
|
+
backend.set(scopedKey(key), value, opts?.ttlSeconds !== void 0 ? { ttlSeconds: opts.ttlSeconds } : {})
|
|
381
|
+
),
|
|
382
|
+
delete: async (key) => backend.delete(scopedKey(key))
|
|
383
|
+
};
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
// src/migration.ts
|
|
387
|
+
var IDENT2 = /^[a-z_][a-z0-9_]*$/;
|
|
388
|
+
function assertIdent2(value, label) {
|
|
389
|
+
if (!IDENT2.test(value)) {
|
|
390
|
+
throw new ValidationError(`${label} "${value}" is not a valid lowercase SQL identifier`);
|
|
391
|
+
}
|
|
392
|
+
return value;
|
|
393
|
+
}
|
|
394
|
+
function planAddTenantColumn(options) {
|
|
395
|
+
const schema = assertIdent2(options.schema ?? "public", "schema");
|
|
396
|
+
const table = assertIdent2(options.table, "table");
|
|
397
|
+
const column = assertIdent2(options.tenantColumn ?? "organization_id", "tenantColumn");
|
|
398
|
+
const type = assertIdent2(options.tenantColumnType ?? "text", "tenantColumnType");
|
|
399
|
+
const qualified = `${schema}.${table}`;
|
|
400
|
+
const expandSql = [
|
|
401
|
+
`ALTER TABLE ${qualified} ADD COLUMN IF NOT EXISTS ${column} ${type};`,
|
|
402
|
+
`CREATE INDEX IF NOT EXISTS ${table}_${column}_idx ON ${qualified} (${column});`
|
|
403
|
+
].join("\n");
|
|
404
|
+
const steps = [
|
|
405
|
+
{
|
|
406
|
+
id: `${table}.expand`,
|
|
407
|
+
phase: "expand",
|
|
408
|
+
description: `add nullable ${column} and its index to ${qualified} (compat with the running version)`,
|
|
409
|
+
sql: `${expandSql}
|
|
410
|
+
`
|
|
411
|
+
}
|
|
412
|
+
];
|
|
413
|
+
if (options.backfillValue !== void 0) {
|
|
414
|
+
const backfillValue = options.backfillValue;
|
|
415
|
+
steps.push({
|
|
416
|
+
id: `${table}.migrate`,
|
|
417
|
+
phase: "migrate",
|
|
418
|
+
description: `backfill ${column} on existing rows of ${qualified} (run as a Job, out of boot)`,
|
|
419
|
+
sql: `UPDATE ${qualified} SET ${column} = ${backfillValue} WHERE ${column} IS NULL;
|
|
420
|
+
`
|
|
421
|
+
});
|
|
422
|
+
}
|
|
423
|
+
const contractSql = [
|
|
424
|
+
`ALTER TABLE ${qualified} ALTER COLUMN ${column} SET NOT NULL;`,
|
|
425
|
+
buildTenantRlsPolicySql({
|
|
426
|
+
schema,
|
|
427
|
+
table,
|
|
428
|
+
tenantColumn: column,
|
|
429
|
+
// exactOptionalPropertyTypes: forward the cast only for a non-text column.
|
|
430
|
+
...type !== "text" ? { tenantColumnType: type } : {}
|
|
431
|
+
})
|
|
432
|
+
].join("\n");
|
|
433
|
+
steps.push({
|
|
434
|
+
id: `${table}.contract`,
|
|
435
|
+
phase: "contract",
|
|
436
|
+
description: `enforce NOT NULL and the full RLS wall on ${qualified} (after a stable deploy)`,
|
|
437
|
+
sql: `${contractSql}`
|
|
438
|
+
});
|
|
439
|
+
return steps;
|
|
440
|
+
}
|
|
441
|
+
function buildAdvisoryLockSql(lockKey) {
|
|
442
|
+
return `SELECT pg_advisory_xact_lock(${lockKey});`;
|
|
443
|
+
}
|
|
444
|
+
async function withMigrationLock(conn, lockKey, run) {
|
|
445
|
+
try {
|
|
446
|
+
await conn.query("BEGIN");
|
|
447
|
+
await conn.query(buildAdvisoryLockSql(lockKey));
|
|
448
|
+
const result = await run();
|
|
449
|
+
await conn.query("COMMIT");
|
|
450
|
+
return result;
|
|
451
|
+
} catch (err) {
|
|
452
|
+
try {
|
|
453
|
+
await conn.query("ROLLBACK");
|
|
454
|
+
} catch {
|
|
455
|
+
}
|
|
456
|
+
throw err;
|
|
457
|
+
}
|
|
458
|
+
}
|
|
459
|
+
var REQUIRED_COMMANDS = ["SELECT", "INSERT", "UPDATE", "DELETE"];
|
|
460
|
+
async function assertRlsCoverage(conn, tables) {
|
|
461
|
+
for (const ref of tables) {
|
|
462
|
+
const schema = assertIdent2(ref.schema ?? "public", "schema");
|
|
463
|
+
const table = assertIdent2(ref.table, "table");
|
|
464
|
+
const qualified = `${schema}.${table}`;
|
|
465
|
+
const flags = await conn.query(
|
|
466
|
+
"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",
|
|
467
|
+
[schema, table]
|
|
468
|
+
);
|
|
469
|
+
const row = flags.rows[0];
|
|
470
|
+
if (row === void 0) {
|
|
471
|
+
throw new RlsCoverageError(`table ${qualified} was not found in pg_class \u2014 cannot verify its RLS wall`);
|
|
472
|
+
}
|
|
473
|
+
const missing = [];
|
|
474
|
+
if (row.relrowsecurity !== true) {
|
|
475
|
+
missing.push("ENABLE ROW LEVEL SECURITY");
|
|
476
|
+
}
|
|
477
|
+
if (row.relforcerowsecurity !== true) {
|
|
478
|
+
missing.push("FORCE ROW LEVEL SECURITY");
|
|
479
|
+
}
|
|
480
|
+
const policies = await conn.query(
|
|
481
|
+
"SELECT cmd FROM pg_policies WHERE schemaname = $1 AND tablename = $2",
|
|
482
|
+
[schema, table]
|
|
483
|
+
);
|
|
484
|
+
const covered = new Set(policies.rows.map((p) => p.cmd.toUpperCase()));
|
|
485
|
+
for (const command of REQUIRED_COMMANDS) {
|
|
486
|
+
if (!covered.has(command) && !covered.has("ALL")) {
|
|
487
|
+
missing.push(`${command} policy`);
|
|
488
|
+
}
|
|
489
|
+
}
|
|
490
|
+
if (missing.length > 0) {
|
|
491
|
+
throw new RlsCoverageError(`table ${qualified} has an incomplete RLS wall \u2014 missing: ${missing.join(", ")}`);
|
|
492
|
+
}
|
|
493
|
+
}
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
export { MigrationError, MissingPrincipalContextError, MissingTenantContextError, NupError, PRINCIPAL_GUC_KEY, RlsCoverageError, RlsRoleViolationError, TENANT_GUC_KEY, TenantKeyEscapeError, ValidationError, assertAppRole, assertConnectionRole, assertRlsCoverage, buildAdvisoryLockSql, buildPrincipalRlsPolicySql, buildTenantAndPrincipalRlsPolicySql, buildTenantRlsPolicySql, buildTransitiveRlsPolicySql, createTenantCache, createTenantObjectStore, getCurrentPrincipal, getCurrentTenant, isOrganizationId, isPrincipalId, makeOrganizationId, makePrincipalId, planAddTenantColumn, readCurrentRole, requireCurrentPrincipal, requireCurrentTenant, runWithResolvedTenant, runWithResolvedTenantAndPrincipal, runWithTenant, runWithTenantAndPrincipal, tenantCacheNamespace, tenantObjectPrefix, withMigrationLock, withTenantAndPrincipalTransaction, withTenantTransaction };
|
|
497
|
+
//# sourceMappingURL=index.js.map
|
|
498
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/errors.ts","../src/tenant-id.ts","../src/principal-id.ts","../src/context.ts","../src/identity.ts","../src/sql.ts","../src/transaction.ts","../src/rls-policy.ts","../src/boot-check.ts","../src/storage.ts","../src/cache.ts","../src/migration.ts"],"names":["IDENT","assertIdent"],"mappings":";;;AAIO,IAAM,QAAA,GAAN,cAAuB,KAAA,CAAM;AAAA,EAClC,WAAA,CACE,OAAA,EACgB,IAAA,EACA,UAAA,GAAqB,GAAA,EACrC;AACA,IAAA,KAAA,CAAM,OAAO,CAAA;AAHG,IAAA,IAAA,CAAA,IAAA,GAAA,IAAA;AACA,IAAA,IAAA,CAAA,UAAA,GAAA,UAAA;AAGhB,IAAA,IAAA,CAAK,IAAA,GAAO,KAAK,WAAA,CAAY,IAAA;AAAA,EAC/B;AAAA,EALkB,IAAA;AAAA,EACA,UAAA;AAKpB;AAGO,IAAM,eAAA,GAAN,cAA8B,QAAA,CAAS;AAAA,EAC5C,YAAY,OAAA,EAAiB;AAC3B,IAAA,KAAA,CAAM,OAAA,EAAS,oBAAoB,GAAG,CAAA;AAAA,EACxC;AACF;AAOO,IAAM,yBAAA,GAAN,cAAwC,QA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AAQ,IAAA,CAAK,IAAI,CAAC,CAAA,CAAE,CAAA;AAAA,IAC7G;AAAA,EACF;AACF","file":"index.js","sourcesContent":["/**\n * Base error (inlined — this package is standalone and has no runtime deps).\n * Mirrors the shape the wall relies on: a stable `code` and an HTTP `statusCode`.\n */\nexport class NupError extends Error {\n constructor(\n message: string,\n public readonly code: string,\n public readonly statusCode: number = 500,\n ) {\n super(message);\n this.name = this.constructor.name;\n }\n}\n\n/** Raised when an argument fails validation (e.g. a bad SQL identifier). */\nexport class ValidationError extends NupError {\n constructor(message: string) {\n super(message, \"VALIDATION_ERROR\", 400);\n }\n}\n\n/**\n * Raised when a tenant-scoped operation is attempted with no tenant in the\n * async context. This is the heart of fail-closed (ADR-EA-010 D1, A4): the\n * wall refuses to touch data instead of silently running an unscoped query.\n */\nexport class MissingTenantContextError extends NupError {\n constructor(message = \"no organization_id in context — refusing to touch tenant-scoped data (fail-closed)\") {\n super(message, \"MISSING_TENANT_CONTEXT\", 500);\n }\n}\n\n/**\n * Raised when a per-user (principal) operation is attempted with no principal in\n * the async context. The per-user twin of {@link MissingTenantContextError}: a\n * per-principal unit of work refuses to touch data without a principal, instead\n * of silently binding only the org and letting a user-keyed policy return zero\n * rows (the silent-empty failure mode). Fail-closed (ADR-EA-010 A4).\n */\nexport class MissingPrincipalContextError extends NupError {\n constructor(message = \"no principal (user) in context — refusing to touch per-user data (fail-closed)\") {\n super(message, \"MISSING_PRINCIPAL_CONTEXT\", 500);\n }\n}\n\n/**\n * Raised at boot when the database connection runs under a role that can\n * bypass RLS (superuser or `BYPASSRLS`). Such a role silently defeats the\n * whole wall (ADR-EA-010 A2), so the process refuses to proceed.\n */\nexport class RlsRoleViolationError extends NupError {\n constructor(message: string) {\n super(message, \"RLS_ROLE_VIOLATION\", 500);\n }\n}\n\n/**\n * Raised when a caller key would escape its tenant prefix — an absolute key or\n * one with a `..` segment (ADR-EA-010 D1 #6, A4). Rejecting it keeps the\n * object-store wall fail-closed: a key can only ever live under the tenant's\n * own prefix.\n */\nexport class TenantKeyEscapeError extends NupError {\n constructor(key: string) {\n super(`object key \"${key}\" escapes the tenant prefix (absolute path or \"..\" segment)`, \"TENANT_KEY_ESCAPE\", 400);\n }\n}\n\n/**\n * Raised by the coverage guard when a tenant table does not have a complete RLS\n * wall (ADR-EA-010 A3, REQ-SC-07): it must ENABLE+FORCE row level security and\n * carry a policy for each of SELECT/INSERT/UPDATE/DELETE. An incomplete wall is\n * fail-open, so this fails CI/boot instead of shipping a leak.\n */\nexport class RlsCoverageError extends NupError {\n constructor(message: string) {\n super(message, \"RLS_COVERAGE_INCOMPLETE\", 500);\n }\n}\n\n/** Raised for a typed failure inside a migration run (ADR-EA-012 D3). */\nexport class MigrationError extends NupError {\n constructor(message: string) {\n super(message, \"MIGRATION_FAILED\", 500);\n }\n}\n","import { ValidationError } from \"./errors.js\";\n\ndeclare const organizationIdBrand: unique symbol;\n\n/**\n * The tenant key for the whole platform (ADR-EA-005, ADR-EA-010): the raw\n * `organization_id` the identify SDK resolves for the current request. Branded\n * so a plain string cannot be passed where an authenticated tenant is expected.\n */\nexport type OrganizationId = string & { readonly [organizationIdBrand]: \"OrganizationId\" };\n\n/** Narrows a raw string into an {@link OrganizationId}, rejecting empty/blank values. */\nexport function makeOrganizationId(raw: string): OrganizationId {\n const trimmed = raw.trim();\n if (trimmed.length === 0) {\n throw new ValidationError(\"organizationId must be a non-empty string\");\n }\n return trimmed as OrganizationId;\n}\n\n/** Type guard usable at a boundary that already holds a validated value. */\nexport function isOrganizationId(value: unknown): value is OrganizationId {\n return typeof value === \"string\" && value.trim().length > 0;\n}\n","import { ValidationError } from \"./errors.js\";\n\ndeclare const principalIdBrand: unique symbol;\n\n/**\n * The PER-USER axis of the wall (ADR-EA-010 addendum — per-principal isolation).\n *\n * Added ALONGSIDE {@link OrganizationId}, never replacing it: products whose data\n * belongs to a single USER (not shared within the org) isolate by this key. The\n * org axis stays the parkwide tenant; this one narrows WITHIN it, so a product\n * where many users share one organization (e.g. a school) still isolates each\n * user's own rows.\n *\n * It is the authenticated principal's id — the identify `sub` of the person (or\n * the machine principal's id). Branded so a plain string cannot be passed where\n * an authenticated principal is expected.\n */\nexport type PrincipalId = string & { readonly [principalIdBrand]: \"PrincipalId\" };\n\n/** Narrows a raw string into a {@link PrincipalId}, rejecting empty/blank values. */\nexport function makePrincipalId(raw: string): PrincipalId {\n const trimmed = raw.trim();\n if (trimmed.length === 0) {\n throw new ValidationError(\"principalId must be a non-empty string\");\n }\n return trimmed as PrincipalId;\n}\n\n/** Type guard usable at a boundary that already holds a validated value. */\nexport function isPrincipalId(value: unknown): value is PrincipalId {\n return typeof value === \"string\" && value.trim().length > 0;\n}\n","import { AsyncLocalStorage } from \"node:async_hooks\";\nimport { MissingPrincipalContextError, MissingTenantContextError } from \"./errors.js\";\nimport type { PrincipalId } from \"./principal-id.js\";\nimport type { OrganizationId } from \"./tenant-id.js\";\n\ninterface TenantStore {\n readonly organizationId: OrganizationId;\n /** Per-user axis — present only inside a `runWithTenantAndPrincipal` scope. */\n readonly principalId?: PrincipalId;\n}\n\n/**\n * Per-request/per-job tenant propagation (ADR-EA-010 D1 #2, A8). A fresh store\n * is created per `run()` and connections are never kept in it, so there is no\n * cross-request bleed and no stale handle.\n */\nconst storage = new AsyncLocalStorage<TenantStore>();\n\n/** Runs `fn` with `organizationId` bound as the current tenant for the whole async subtree. */\nexport function runWithTenant<T>(organizationId: OrganizationId, fn: () => T): T {\n return storage.run({ organizationId }, fn);\n}\n\n/**\n * Runs `fn` with BOTH the org tenant and the per-user principal bound for the\n * whole async subtree. Additive twin of {@link runWithTenant} for products whose\n * rows are per-user: the org axis still applies, the principal narrows within it.\n */\nexport function runWithTenantAndPrincipal<T>(organizationId: OrganizationId, principalId: PrincipalId, fn: () => T): T {\n return storage.run({ organizationId, principalId }, fn);\n}\n\n/** The tenant bound to the current async context, or `null` when none is set. */\nexport function getCurrentTenant(): OrganizationId | null {\n return storage.getStore()?.organizationId ?? null;\n}\n\n/**\n * The tenant bound to the current async context, or throws\n * {@link MissingTenantContextError}. Call this before any tenant-scoped side effect.\n */\nexport function requireCurrentTenant(): OrganizationId {\n const organizationId = storage.getStore()?.organizationId;\n if (organizationId == null) {\n throw new MissingTenantContextError();\n }\n return organizationId;\n}\n\n/** The principal (per-user axis) bound to the current async context, or `null`. */\nexport function getCurrentPrincipal(): PrincipalId | null {\n return storage.getStore()?.principalId ?? null;\n}\n\n/**\n * The principal bound to the current async context, or throws\n * {@link MissingPrincipalContextError}. Call before any per-user side effect so a\n * user-keyed policy never runs with an unset principal (silent zero rows).\n */\nexport function requireCurrentPrincipal(): PrincipalId {\n const principalId = storage.getStore()?.principalId;\n if (principalId == null) {\n throw new MissingPrincipalContextError();\n }\n return principalId;\n}\n","import { runWithTenant, runWithTenantAndPrincipal } from \"./context.js\";\nimport { MissingPrincipalContextError, MissingTenantContextError } from \"./errors.js\";\nimport type { PrincipalId } from \"./principal-id.js\";\nimport type { OrganizationId } from \"./tenant-id.js\";\n\n/**\n * The seam against the identify SDK (ADR-EA-010 D1 #1). The tenant is read from\n * the identity boundary — never from a method argument someone forgets to pass.\n * The exact identify SDK contract is NOT verified in this round (separate repo);\n * this port is what an adapter implements over it.\n *\n * `readPrincipalId` is OPTIONAL: readers that only do org-level isolation omit\n * it (unchanged behaviour). Readers for per-user products implement it so\n * {@link runWithResolvedTenantAndPrincipal} can bind the per-user axis too.\n */\nexport interface TenantIdentityReader {\n /** The `organization_id` resolved for the current request, or `null` if unauthenticated. */\n readOrganizationId(): OrganizationId | null;\n /** The per-user principal (identify `sub`) for the current request, or `null`. Optional. */\n readPrincipalId?(): PrincipalId | null;\n}\n\n/**\n * Resolves the tenant from the identity boundary and runs `fn` inside its\n * context. Fail-closed: if the reader yields no tenant, refuses before any work\n * ({@link MissingTenantContextError}). Use at every entrypoint — HTTP request,\n * job, queue consumer, cron (ADR-EA-010 A4).\n */\nexport function runWithResolvedTenant<T>(reader: TenantIdentityReader, fn: () => T): T {\n const organizationId = reader.readOrganizationId();\n if (organizationId == null) {\n throw new MissingTenantContextError();\n }\n return runWithTenant(organizationId, fn);\n}\n\n/**\n * Resolves BOTH the org tenant and the per-user principal from the identity\n * boundary and runs `fn` inside their context. Fail-closed on BOTH axes: no\n * tenant ⇒ {@link MissingTenantContextError}; no principal ⇒\n * {@link MissingPrincipalContextError}. Requires a reader that implements\n * `readPrincipalId`. Use at the entrypoint of a per-user product.\n */\nexport function runWithResolvedTenantAndPrincipal<T>(reader: TenantIdentityReader, fn: () => T): T {\n const organizationId = reader.readOrganizationId();\n if (organizationId == null) {\n throw new MissingTenantContextError();\n }\n const principalId = reader.readPrincipalId?.() ?? null;\n if (principalId == null) {\n throw new MissingPrincipalContextError();\n }\n return runWithTenantAndPrincipal(organizationId, principalId, fn);\n}\n","/**\n * The GUC the wall writes the tenant into, read back by RLS policies\n * (ADR-EA-010 D1 #3). Exported so policy SQL and the transaction binder never\n * drift apart.\n *\n * Canonical platform key: `app.current_organization_id` — the one the identify\n * SDK already uses in live RLS (ADR-EA-005 §Decision.2), confirmed by the PO as\n * the parkwide contract. ADR-EA-010 D1 #3 wrote `app.organization_id` as a\n * draft name; this package follows the PO's canonical key so every Fase B agent\n * reads/writes the same GUC.\n */\nexport const TENANT_GUC_KEY = \"app.current_organization_id\" as const;\n\n/**\n * The GUC the wall writes the PRINCIPAL (per-user axis) into, read back by\n * per-principal RLS policies (ADR-EA-010 addendum — per-user isolation).\n *\n * Added alongside {@link TENANT_GUC_KEY}, never replacing it. Products whose\n * rows belong to one USER (not shared within the org) key their policies on this\n * GUC; it narrows WITHIN the org axis, so users who share an organization (a\n * school) still never see each other's rows. New canonical key proposed here —\n * no prior per-user GUC existed in the park (to ratify by ADR addendum).\n */\nexport const PRINCIPAL_GUC_KEY = \"app.current_user_id\" as const;\n\nexport interface QueryResult<Row = Record<string, unknown>> {\n readonly rows: readonly Row[];\n}\n\n/**\n * The minimal database seam this package binds against — satisfied by\n * node-postgres `Client`/`PoolClient` and most Postgres drivers. Kept driver-\n * agnostic on purpose; the package owns the tenant binding, not the driver.\n */\nexport interface SqlConnection {\n query<Row = Record<string, unknown>>(sql: string, params?: readonly unknown[]): Promise<QueryResult<Row>>;\n}\n\n/** A connection checked out from a pool, returned to the pool via `release()`. */\nexport interface PooledConnection extends SqlConnection {\n release(): void | Promise<void>;\n}\n\n/** A pool able to hand out a dedicated connection for the span of one transaction. */\nexport interface ConnectionPool {\n connect(): Promise<PooledConnection>;\n}\n","import { requireCurrentPrincipal, requireCurrentTenant } from \"./context.js\";\nimport { type ConnectionPool, PRINCIPAL_GUC_KEY, type SqlConnection, TENANT_GUC_KEY } from \"./sql.js\";\n\n/**\n * Runs `work` inside a transaction scoped to the current tenant.\n *\n * - Fail-closed (ADR-EA-010 A4): resolves the tenant BEFORE acquiring a\n * connection, so no connection is touched when none is set.\n * - Pool/PgBouncer-safe (ADR-EA-010 A1): the tenant is pushed with\n * `set_config(key, value, true)` — transaction-local — inside an explicit\n * `BEGIN`/`COMMIT`. It is NEVER a session-level `SET`, so a recycled backend\n * cannot inherit the previous tenant. The scope dies on commit/rollback.\n *\n * `work` receives the same connection the binding was applied to; use it for\n * every query in the unit of work.\n */\nexport async function withTenantTransaction<T>(\n pool: ConnectionPool,\n work: (conn: SqlConnection) => Promise<T>,\n): Promise<T> {\n const organizationId = requireCurrentTenant();\n const conn = await pool.connect();\n try {\n await conn.query(\"BEGIN\");\n await conn.query(\"SELECT set_config($1, $2, true)\", [TENANT_GUC_KEY, organizationId]);\n const result = await work(conn);\n await conn.query(\"COMMIT\");\n return result;\n } catch (err) {\n try {\n await conn.query(\"ROLLBACK\");\n } catch {\n // A failed rollback (e.g. the connection already died) must not mask the\n // original error — swallow it and rethrow the cause.\n }\n throw err;\n } finally {\n await conn.release();\n }\n}\n\n/**\n * Runs `work` inside a transaction scoped to BOTH the current org tenant AND the\n * current per-user principal. The per-user twin of {@link withTenantTransaction},\n * for products whose rows are per-user (user-keyed RLS policies).\n *\n * - Fail-closed on BOTH axes BEFORE acquiring a connection (ADR-EA-010 A4):\n * resolves org and principal first, so a scope missing the principal throws\n * {@link MissingPrincipalContextError} instead of binding only the org and\n * letting a user-keyed policy silently return zero rows.\n * - Pool/PgBouncer-safe (A1): both GUCs are pushed with `set_config(..., true)`\n * (transaction-local) inside an explicit `BEGIN`/`COMMIT`; never a session SET.\n *\n * Both the org GUC (`TENANT_GUC_KEY`) and the principal GUC (`PRINCIPAL_GUC_KEY`)\n * are set, so a table protected by either axis — or by both (defence in depth) —\n * is covered by the same unit of work.\n */\nexport async function withTenantAndPrincipalTransaction<T>(\n pool: ConnectionPool,\n work: (conn: SqlConnection) => Promise<T>,\n): Promise<T> {\n const organizationId = requireCurrentTenant();\n const principalId = requireCurrentPrincipal();\n const conn = await pool.connect();\n try {\n await conn.query(\"BEGIN\");\n await conn.query(\"SELECT set_config($1, $2, true)\", [TENANT_GUC_KEY, organizationId]);\n await conn.query(\"SELECT set_config($1, $2, true)\", [PRINCIPAL_GUC_KEY, principalId]);\n const result = await work(conn);\n await conn.query(\"COMMIT\");\n return result;\n } catch (err) {\n try {\n await conn.query(\"ROLLBACK\");\n } catch {\n // A failed rollback (e.g. the connection already died) must not mask the\n // original error — swallow it and rethrow the cause.\n }\n throw err;\n } finally {\n await conn.release();\n }\n}\n","import { ValidationError } from \"./errors.js\";\nimport { PRINCIPAL_GUC_KEY, TENANT_GUC_KEY } from \"./sql.js\";\n\nexport interface TenantRlsOptions {\n /** Table to protect (unqualified). */\n readonly table: string;\n /** Schema the table lives in. Default `public`. */\n readonly schema?: string;\n /** Tenant-key column. Default `organization_id`. */\n readonly tenantColumn?: string;\n /**\n * SQL type to cast the GUC to before comparing, when the tenant column is not\n * `text` (e.g. `uuid`). Omit for a `text`/`varchar` column.\n */\n readonly tenantColumnType?: string;\n /** Prefix for generated policy names. Default `tenant_isolation`. */\n readonly policyPrefix?: string;\n /** Also emit an index led by the tenant column. Default `true`. */\n readonly createIndex?: boolean;\n /**\n * Extra policy-name prefixes to DROP on this table before creating this wall —\n * for a custom-prefixed wall of another axis that would otherwise OR-stack.\n * The default sibling prefixes are not dropped by the org builder (it stays\n * backward-compatible); pass them here to clean up on a downgrade.\n */\n readonly dropPolicyPrefixes?: readonly string[];\n}\n\n/**\n * Per-table RLS for the PER-USER axis (ADR-EA-010 addendum). Isolates rows by\n * the authenticated principal, read from {@link PRINCIPAL_GUC_KEY}. Use for data\n * owned by a single user even when several users share one organization.\n */\nexport interface PrincipalRlsOptions {\n /** Table to protect (unqualified). */\n readonly table: string;\n /** Schema the table lives in. Default `public`. */\n readonly schema?: string;\n /** Per-user key column. Default `user_id`. */\n readonly principalColumn?: string;\n /** SQL type to cast the GUC to (e.g. `uuid`). Omit for `text`/`varchar`. */\n readonly principalColumnType?: string;\n /** Prefix for generated policy names. Default `principal_isolation`. */\n readonly policyPrefix?: string;\n /** Also emit an index led by the per-user column. Default `true`. */\n readonly createIndex?: boolean;\n /** Extra custom policy-name prefixes to DROP on this table before creating this wall. */\n readonly dropPolicyPrefixes?: readonly string[];\n /**\n * Treat a NULL owner as a SHARED/built-in row (e.g. `mind_map_style_sheets`\n * where `user_id IS NULL` is a system stylesheet). Default `false`.\n *\n * When `true`, the policy READS wider than it WRITES: every user can SELECT\n * their own rows AND the shared (NULL-owner) rows, but INSERT/UPDATE/DELETE are\n * still limited to their OWN rows — a user can neither create, claim, modify nor\n * delete a shared row. So built-in rows stay visible without becoming writable.\n */\n readonly allowSharedNullOwner?: boolean;\n}\n\n/**\n * Per-table RLS for BOTH axes AT ONCE (org AND user), as a SINGLE predicate —\n * defence in depth for a table that carries both keys. One policy per command\n * with `org = … AND user = …`; NEVER two separate policy sets, because Postgres\n * OR-combines permissive policies, which would widen access back to org-only.\n */\nexport interface TenantAndPrincipalRlsOptions {\n readonly table: string;\n readonly schema?: string;\n readonly tenantColumn?: string;\n readonly tenantColumnType?: string;\n readonly principalColumn?: string;\n readonly principalColumnType?: string;\n readonly policyPrefix?: string;\n readonly createIndex?: boolean;\n /** Extra custom policy-name prefixes to DROP on this table before creating this wall. */\n readonly dropPolicyPrefixes?: readonly string[];\n}\n\nconst IDENT = /^[a-z_][a-z0-9_]*$/;\n/** A namespaced GUC key like `app.current_user_id` (two lowercase idents, one dot). */\nconst GUC_KEY = /^[a-z_][a-z0-9_]*\\.[a-z_][a-z0-9_]*$/;\n\nfunction assertIdent(value: string, label: string): string {\n if (!IDENT.test(value)) {\n throw new ValidationError(`${label} \"${value}\" is not a valid lowercase SQL identifier`);\n }\n return value;\n}\n\nfunction assertGucKey(value: string): string {\n if (!GUC_KEY.test(value)) {\n throw new ValidationError(`GUC key \"${value}\" is not a valid namespaced identifier (e.g. app.current_user_id)`);\n }\n return value;\n}\n\n/**\n * Shared renderer for the complete per-table RLS wall (ADR-EA-010 D1 #5, A3, A5),\n * as idempotent, forward-only DDL:\n *\n * - `ENABLE` + `FORCE ROW LEVEL SECURITY` (A3: `ENABLE` alone lets the table\n * owner bypass; `FORCE` closes it).\n * - One policy PER command. SELECT/DELETE use `USING`; INSERT uses `WITH CHECK`;\n * UPDATE uses both — the `WITH CHECK` blocks moving a row to another owner\n * (A3: `USING` without `WITH CHECK` is fail-open on writes).\n * - The predicate compares the key column to the GUC via `current_setting(key,\n * true)`, which is `NULL` when unset, so the policy matches zero rows — the\n * second, database-level layer of fail-closed (A4). GUC-vs-column only, which\n * stays LEAKPROOF so the planner can push it down (A5).\n * - An index led by the key column(s) (A5: avoids a seqscan to satisfy the policy).\n *\n * Column creation/backfill is NOT emitted here — that is an expand-and-contract\n * migration owned by the scaffold's migration engine (ADR-EA-012 D3).\n */\nconst COMMAND_SUFFIXES = [\"select\", \"insert\", \"update\", \"delete\"] as const;\n\n/** Default policy-name prefixes used by the three builders. */\nconst DEFAULT_RLS_PREFIXES = [\n \"tenant_isolation\",\n \"principal_isolation\",\n \"tenant_principal_isolation\",\n \"transitive_isolation\",\n] as const;\n\n/**\n * Prefixes of OTHER walls to drop when (re)building a table's wall: the default\n * prefixes that are not this builder's own, plus any caller-supplied custom\n * prefixes (validated). Deduped. Used so upgrading a table from one axis to\n * another replaces its wall instead of OR-stacking a second permissive set.\n */\nfunction siblingDropPrefixes(ownPrefix: string, custom: readonly string[] | undefined): string[] {\n const customValidated = (custom ?? []).map((p) => assertIdent(p, \"dropPolicyPrefix\"));\n const all = [...DEFAULT_RLS_PREFIXES, ...customValidated].filter((p) => p !== ownPrefix);\n return [...new Set(all)];\n}\n\nfunction renderPolicySql(params: {\n schema: string;\n table: string;\n prefix: string;\n /** Default predicate for every command. Per-command overrides fall back to it. */\n match: string;\n /** Per-command overrides (for policies that read wider than they write, e.g. shared rows). */\n selectUsing?: string;\n insertCheck?: string;\n updateUsing?: string;\n updateCheck?: string;\n deleteUsing?: string;\n indexColumns: readonly string[];\n createIndex: boolean;\n /**\n * Policy-name prefixes of OTHER walls to drop on this table before creating\n * this one. Postgres OR-combines permissive policies, so leaving a prior wall\n * (e.g. an org-only `tenant_isolation_*`) in place while adding a stricter one\n * would WIDEN access back. The new builders pass the sibling default prefixes\n * here so upgrading a table's axis replaces the wall instead of stacking it.\n */\n extraDropPrefixes?: readonly string[];\n}): string {\n const { schema, table, prefix, match, indexColumns, createIndex, extraDropPrefixes = [] } = params;\n const qualified = `${schema}.${table}`;\n // Per-command predicates default to `match`; overrides let reads be wider than\n // writes (shared rows are readable but not writable/forgeable).\n const selectUsing = params.selectUsing ?? match;\n const insertCheck = params.insertCheck ?? match;\n const updateUsing = params.updateUsing ?? match;\n const updateCheck = params.updateCheck ?? match;\n const deleteUsing = params.deleteUsing ?? match;\n\n const statements = [\n `ALTER TABLE ${qualified} ENABLE ROW LEVEL SECURITY;`,\n `ALTER TABLE ${qualified} FORCE ROW LEVEL SECURITY;`,\n ...extraDropPrefixes.flatMap((p) =>\n COMMAND_SUFFIXES.map((cmd) => `DROP POLICY IF EXISTS ${p}_${cmd} ON ${qualified};`),\n ),\n `DROP POLICY IF EXISTS ${prefix}_select ON ${qualified};`,\n `CREATE POLICY ${prefix}_select ON ${qualified} FOR SELECT USING (${selectUsing});`,\n `DROP POLICY IF EXISTS ${prefix}_insert ON ${qualified};`,\n `CREATE POLICY ${prefix}_insert ON ${qualified} FOR INSERT WITH CHECK (${insertCheck});`,\n `DROP POLICY IF EXISTS ${prefix}_update ON ${qualified};`,\n `CREATE POLICY ${prefix}_update ON ${qualified} FOR UPDATE USING (${updateUsing}) WITH CHECK (${updateCheck});`,\n `DROP POLICY IF EXISTS ${prefix}_delete ON ${qualified};`,\n `CREATE POLICY ${prefix}_delete ON ${qualified} FOR DELETE USING (${deleteUsing});`,\n ];\n\n if (createIndex && indexColumns.length > 0) {\n const cols = indexColumns.join(\", \");\n const idxName = `${table}_${indexColumns.join(\"_\")}_idx`;\n statements.push(`CREATE INDEX IF NOT EXISTS ${idxName} ON ${qualified} (${cols});`);\n }\n\n return `${statements.join(\"\\n\")}\\n`;\n}\n\n/**\n * Builds the complete per-table RLS wall for the ORG (tenant) axis. Behaviour is\n * unchanged from the original package: the predicate is a bare\n * `organization_id = current_setting('app.current_organization_id', true)`.\n */\nexport function buildTenantRlsPolicySql(options: TenantRlsOptions): string {\n const schema = assertIdent(options.schema ?? \"public\", \"schema\");\n const table = assertIdent(options.table, \"table\");\n const column = assertIdent(options.tenantColumn ?? \"organization_id\", \"tenantColumn\");\n const prefix = assertIdent(options.policyPrefix ?? \"tenant_isolation\", \"policyPrefix\");\n const createIndex = options.createIndex ?? true;\n\n const cast = options.tenantColumnType ? `::${assertIdent(options.tenantColumnType, \"tenantColumnType\")}` : \"\";\n const match = `${column} = current_setting('${TENANT_GUC_KEY}', true)${cast}`;\n\n // Org builder stays backward-compatible: drops only its own prefix by default;\n // extra prefixes only when the caller explicitly asks (downgrade cleanup).\n const extraDropPrefixes = (options.dropPolicyPrefixes ?? []).map((p) => assertIdent(p, \"dropPolicyPrefix\"));\n\n return renderPolicySql({ schema, table, prefix, match, indexColumns: [column], createIndex, extraDropPrefixes });\n}\n\n/**\n * Builds the complete per-table RLS wall for the PER-USER (principal) axis.\n * Predicate: `user_id = NULLIF(current_setting('app.current_user_id', true), '')`.\n * The `NULLIF` makes an EMPTY GUC behave like an unset one, so a recycled pooled\n * connection that reads the key back as `''` still matches zero rows (fail-closed).\n */\nexport function buildPrincipalRlsPolicySql(options: PrincipalRlsOptions): string {\n const schema = assertIdent(options.schema ?? \"public\", \"schema\");\n const table = assertIdent(options.table, \"table\");\n const column = assertIdent(options.principalColumn ?? \"user_id\", \"principalColumn\");\n const prefix = assertIdent(options.policyPrefix ?? \"principal_isolation\", \"policyPrefix\");\n const createIndex = options.createIndex ?? true;\n\n const cast = options.principalColumnType\n ? `::${assertIdent(options.principalColumnType, \"principalColumnType\")}`\n : \"\";\n const own = `${column} = NULLIF(current_setting('${PRINCIPAL_GUC_KEY}', true), '')${cast}`;\n\n // allowSharedNullOwner: SELECT sees own + shared(NULL); writes stay own-only, so\n // a shared row is readable but never created/claimed/modified/deleted by a user.\n const readPredicate = options.allowSharedNullOwner ? `(${own}) OR ${column} IS NULL` : own;\n\n return renderPolicySql({\n schema,\n table,\n prefix,\n match: own,\n selectUsing: readPredicate,\n indexColumns: [column],\n createIndex,\n extraDropPrefixes: siblingDropPrefixes(prefix, options.dropPolicyPrefixes),\n });\n}\n\n/**\n * Builds the complete per-table RLS wall for BOTH axes as ONE predicate\n * (`org AND user`). Defence in depth for a table carrying both keys. The single\n * AND predicate is deliberate: two separate policy sets would be OR-combined by\n * Postgres and widen access back to org-only.\n */\nexport function buildTenantAndPrincipalRlsPolicySql(options: TenantAndPrincipalRlsOptions): string {\n const schema = assertIdent(options.schema ?? \"public\", \"schema\");\n const table = assertIdent(options.table, \"table\");\n const tenantColumn = assertIdent(options.tenantColumn ?? \"organization_id\", \"tenantColumn\");\n const principalColumn = assertIdent(options.principalColumn ?? \"user_id\", \"principalColumn\");\n const prefix = assertIdent(options.policyPrefix ?? \"tenant_principal_isolation\", \"policyPrefix\");\n const createIndex = options.createIndex ?? true;\n\n const tenantCast = options.tenantColumnType ? `::${assertIdent(options.tenantColumnType, \"tenantColumnType\")}` : \"\";\n const principalCast = options.principalColumnType\n ? `::${assertIdent(options.principalColumnType, \"principalColumnType\")}`\n : \"\";\n\n const tenantMatch = `${tenantColumn} = NULLIF(current_setting('${TENANT_GUC_KEY}', true), '')${tenantCast}`;\n const principalMatch = `${principalColumn} = NULLIF(current_setting('${PRINCIPAL_GUC_KEY}', true), '')${principalCast}`;\n const match = `(${tenantMatch}) AND (${principalMatch})`;\n\n return renderPolicySql({\n schema,\n table,\n prefix,\n match,\n indexColumns: [tenantColumn, principalColumn],\n createIndex,\n extraDropPrefixes: siblingDropPrefixes(prefix, options.dropPolicyPrefixes),\n });\n}\n\n/**\n * Per-table RLS for a TRANSITIVE (child) table whose owner lives on a PARENT\n * row (a child with a FK to the parent but no owner column of its own, e.g.\n * `material_content_segments(material_id) → materials(id, user_id)`).\n *\n * For such a table, denormalizing the owner column + `buildPrincipalRlsPolicySql`\n * is the performance-optimal path (ADR-EA-005), but it needs a migration. This\n * builder is the no-schema-change alternative: the predicate is an `EXISTS` on\n * the parent, so a child row is reachable iff its parent is owned by the current\n * principal. INSERT/UPDATE `WITH CHECK` use the same `EXISTS`, so a child can\n * never be attached to a parent the user does not own.\n */\nexport interface TransitiveRlsOptions {\n /** Child table to protect (unqualified). */\n readonly table: string;\n /** Schema of the child table. Default `public`. */\n readonly schema?: string;\n /** FK column ON THE CHILD that points at the parent's key. */\n readonly foreignKeyColumn: string;\n /** Parent table that carries the owner. */\n readonly parentTable: string;\n /** Schema of the parent table. Default = the child's schema. */\n readonly parentSchema?: string;\n /** Parent key column the FK points at. Default `id`. */\n readonly parentKeyColumn?: string;\n /** Owner column ON THE PARENT. Default `user_id`. */\n readonly parentOwnerColumn?: string;\n /** GUC the owner is compared to. Default the per-user `PRINCIPAL_GUC_KEY`. */\n readonly ownerGucKey?: string;\n /** Prefix for generated policy names. Default `transitive_isolation`. */\n readonly policyPrefix?: string;\n /** Also emit an index led by the FK column. Default `true`. */\n readonly createIndex?: boolean;\n /** Extra custom policy-name prefixes to DROP before creating this wall. */\n readonly dropPolicyPrefixes?: readonly string[];\n /**\n * Treat a NULL owner ON THE PARENT as a SHARED/built-in parent (e.g. children of\n * a built-in `mind_map_style_sheets`). Default `false`. When `true`, SELECT also\n * returns children of shared parents, while writes still require an OWNED parent\n * (children of a shared parent are readable, not writable).\n *\n * Limitation: this builder resolves the owner on the DIRECT parent. A two-hop\n * chain (child → mid → owner) is not expressed here — point at the parent that\n * carries the owner, or denormalise the owner onto the child and use\n * `buildPrincipalRlsPolicySql`.\n */\n readonly parentAllowSharedNullOwner?: boolean;\n}\n\nexport function buildTransitiveRlsPolicySql(options: TransitiveRlsOptions): string {\n const schema = assertIdent(options.schema ?? \"public\", \"schema\");\n const table = assertIdent(options.table, \"table\");\n const fk = assertIdent(options.foreignKeyColumn, \"foreignKeyColumn\");\n const parentSchema = assertIdent(options.parentSchema ?? options.schema ?? \"public\", \"parentSchema\");\n const parentTable = assertIdent(options.parentTable, \"parentTable\");\n const parentKey = assertIdent(options.parentKeyColumn ?? \"id\", \"parentKeyColumn\");\n const ownerColumn = assertIdent(options.parentOwnerColumn ?? \"user_id\", \"parentOwnerColumn\");\n const gucKey = assertGucKey(options.ownerGucKey ?? PRINCIPAL_GUC_KEY);\n const prefix = assertIdent(options.policyPrefix ?? \"transitive_isolation\", \"policyPrefix\");\n const createIndex = options.createIndex ?? true;\n\n // Child column qualified by the table name to disambiguate from the parent alias.\n const childFk = `${table}.${fk}`;\n const parentQualified = `${parentSchema}.${parentTable}`;\n const ownerMatch = `p.${ownerColumn} = NULLIF(current_setting('${gucKey}', true), '')`;\n const existsOwned = `EXISTS (SELECT 1 FROM ${parentQualified} p WHERE p.${parentKey} = ${childFk} AND ${ownerMatch})`;\n // read-wider variant: children of an owned OR shared (NULL-owner) parent\n const existsOwnedOrShared = `EXISTS (SELECT 1 FROM ${parentQualified} p WHERE p.${parentKey} = ${childFk} AND (${ownerMatch} OR p.${ownerColumn} IS NULL))`;\n const readPredicate = options.parentAllowSharedNullOwner ? existsOwnedOrShared : existsOwned;\n\n return renderPolicySql({\n schema,\n table,\n prefix,\n match: existsOwned, // writes always require an OWNED parent\n selectUsing: readPredicate,\n indexColumns: [fk],\n createIndex,\n extraDropPrefixes: siblingDropPrefixes(prefix, options.dropPolicyPrefixes),\n });\n}\n","import { RlsRoleViolationError } from \"./errors.js\";\nimport type { SqlConnection } from \"./sql.js\";\n\nexport interface RoleCapabilities {\n readonly rolname: string;\n readonly isSuperuser: boolean;\n readonly bypassRls: boolean;\n}\n\ninterface RoleRow {\n readonly current_user: string;\n readonly rolsuper: boolean;\n readonly rolbypassrls: boolean;\n}\n\n/** Reads the capabilities of the role the connection authenticated as. */\nexport async function readCurrentRole(conn: SqlConnection): Promise<RoleCapabilities> {\n const result = await conn.query<RoleRow>(\n \"SELECT current_user, rolsuper, rolbypassrls FROM pg_roles WHERE rolname = current_user\",\n );\n const row = result.rows[0];\n if (row === undefined) {\n throw new RlsRoleViolationError(\"could not resolve the current database role from pg_roles\");\n }\n return {\n rolname: row.current_user,\n isSuperuser: row.rolsuper === true,\n bypassRls: row.rolbypassrls === true,\n };\n}\n\n/**\n * Throws {@link RlsRoleViolationError} if the role can bypass RLS. A superuser\n * or `BYPASSRLS` role silently ignores every policy even under `FORCE`\n * (ADR-EA-010 A2), so the wall is worthless under it.\n */\nexport function assertAppRole(caps: RoleCapabilities): void {\n if (caps.isSuperuser) {\n throw new RlsRoleViolationError(\n `database role \"${caps.rolname}\" is a superuser and bypasses RLS — use a dedicated non-owner app role`,\n );\n }\n if (caps.bypassRls) {\n throw new RlsRoleViolationError(`database role \"${caps.rolname}\" has BYPASSRLS — use a role with NOBYPASSRLS`);\n }\n}\n\n/** Boot guard: reads the connection's role and asserts it cannot bypass RLS. */\nexport async function assertConnectionRole(conn: SqlConnection): Promise<RoleCapabilities> {\n const caps = await readCurrentRole(conn);\n assertAppRole(caps);\n return caps;\n}\n","import { requireCurrentTenant } from \"./context.js\";\nimport { TenantKeyEscapeError } from \"./errors.js\";\nimport type { OrganizationId } from \"./tenant-id.js\";\n\n/**\n * Driver-agnostic object-store seam (ADR-EA-010 D1 #6, REQ-MT-04): an\n * S3-compatible surface the wall wraps. The package owns tenant prefixing, not\n * the driver — an adapter implements this over S3/MinIO/GCS/filesystem.\n */\nexport interface ObjectStorePort {\n put(key: string, body: Uint8Array | string, opts?: { readonly contentType?: string }): Promise<void>;\n get(key: string): Promise<Uint8Array | null>;\n delete(key: string): Promise<void>;\n list(prefix?: string): Promise<readonly string[]>;\n}\n\n/** The per-tenant key prefix every object lives under (ADR-EA-010 D1 #6). */\nexport function tenantObjectPrefix(organizationId: OrganizationId): string {\n return `org/${organizationId}/`;\n}\n\n/**\n * Rejects a caller key that could escape the tenant prefix (A4): an absolute\n * key (`/...`) or any `..` path segment. Everything else is relative to the\n * tenant and safe to prepend the prefix to.\n */\nfunction assertSafeKey(key: string): void {\n if (key.startsWith(\"/\") || key.split(\"/\").some((segment) => segment === \"..\")) {\n throw new TenantKeyEscapeError(key);\n }\n}\n\n/**\n * Wraps `backend` so every object operation is scoped to the current tenant\n * (ADR-EA-010 D1 #6, A4):\n *\n * - Fail-closed: the tenant is resolved with {@link requireCurrentTenant} BEFORE\n * the backend is touched — no tenant in context → MissingTenantContextError.\n * - Every caller key is prepended with {@link tenantObjectPrefix}, so two orgs\n * can never address each other's objects on a shared backend.\n * - `list()` scopes within the tenant prefix and strips it back off, so callers\n * only ever see their own relative keys.\n */\nexport function createTenantObjectStore(backend: ObjectStorePort): ObjectStorePort {\n // `async` so the fail-closed guard and the key-escape check surface as a\n // rejected promise, never a synchronous throw out of a Promise-returning method.\n const scopedKey = (key: string): string => {\n assertSafeKey(key);\n return `${tenantObjectPrefix(requireCurrentTenant())}${key}`;\n };\n\n return {\n put: async (key, body, opts) =>\n // exactOptionalPropertyTypes: only forward contentType when it is set.\n backend.put(scopedKey(key), body, opts?.contentType !== undefined ? { contentType: opts.contentType } : {}),\n get: async (key) => backend.get(scopedKey(key)),\n delete: async (key) => backend.delete(scopedKey(key)),\n list: async (prefix) => {\n const tenantPrefix = tenantObjectPrefix(requireCurrentTenant());\n const callerPrefix = prefix ?? \"\";\n assertSafeKey(callerPrefix);\n const keys = await backend.list(`${tenantPrefix}${callerPrefix}`);\n return keys.map((key) => (key.startsWith(tenantPrefix) ? key.slice(tenantPrefix.length) : key));\n },\n };\n}\n","import { requireCurrentTenant } from \"./context.js\";\nimport type { OrganizationId } from \"./tenant-id.js\";\n\n/**\n * Driver-agnostic cache seam (ADR-EA-010 D1 #6): a Redis/Memcached-style\n * surface the wall wraps. The package owns the per-tenant namespace, not the\n * driver.\n */\nexport interface CachePort {\n get(key: string): Promise<string | null>;\n set(key: string, value: string, opts?: { readonly ttlSeconds?: number }): Promise<void>;\n delete(key: string): Promise<void>;\n}\n\n/** The per-tenant key namespace every cache entry lives under (ADR-EA-010 D1 #6). */\nexport function tenantCacheNamespace(organizationId: OrganizationId): string {\n return `org:${organizationId}:`;\n}\n\n/**\n * Wraps `backend` so every cache key is namespaced to the current tenant\n * (ADR-EA-010 D1 #6, same fail-closed guard as A4): the tenant is resolved with\n * {@link requireCurrentTenant} BEFORE the backend is touched, and every key is\n * prefixed with {@link tenantCacheNamespace}, so two orgs can never read each\n * other's entries on a shared backend.\n */\nexport function createTenantCache(backend: CachePort): CachePort {\n // `async` so the fail-closed guard surfaces as a rejected promise, never a\n // synchronous throw out of a Promise-returning method.\n const scopedKey = (key: string): string => `${tenantCacheNamespace(requireCurrentTenant())}${key}`;\n\n return {\n get: async (key) => backend.get(scopedKey(key)),\n set: async (key, value, opts) =>\n // exactOptionalPropertyTypes: only forward ttlSeconds when it is set.\n backend.set(scopedKey(key), value, opts?.ttlSeconds !== undefined ? { ttlSeconds: opts.ttlSeconds } : {}),\n delete: async (key) => backend.delete(scopedKey(key)),\n };\n}\n","import { ValidationError } from \"./errors.js\";\nimport { RlsCoverageError } from \"./errors.js\";\nimport { buildTenantRlsPolicySql } from \"./rls-policy.js\";\nimport type { SqlConnection } from \"./sql.js\";\n\nconst IDENT = /^[a-z_][a-z0-9_]*$/;\n\nfunction assertIdent(value: string, label: string): string {\n if (!IDENT.test(value)) {\n throw new ValidationError(`${label} \"${value}\" is not a valid lowercase SQL identifier`);\n }\n return value;\n}\n\n/**\n * The three phases of an expand-and-contract migration (ADR-EA-011 RT4,\n * ADR-EA-012 D3). Forward-only: the running old version keeps working through\n * `expand` and `migrate`; `contract` closes the wall only after a stable deploy.\n */\nexport type MigrationPhase = \"expand\" | \"migrate\" | \"contract\";\n\nexport interface MigrationStep {\n readonly id: string;\n readonly phase: MigrationPhase;\n readonly description: string;\n readonly sql: string;\n}\n\nexport interface AddTenantColumnOptions {\n readonly table: string;\n readonly schema?: string;\n readonly tenantColumn?: string;\n readonly tenantColumnType?: string;\n readonly backfillValue?: string;\n}\n\n/**\n * Plans a forward-only expand → migrate → contract migration that makes an\n * existing table tenant-scoped WITHOUT destructive DDL (ADR-EA-010 D1 #5,\n * ADR-EA-012 D3, ADR-EA-011 RT4):\n *\n * - expand: add the tenant column NULLABLE (compat for the running old version)\n * plus the tenant-led index — both `IF NOT EXISTS`, safe to re-run.\n * - migrate: backfill existing rows (only when `backfillValue` is given), meant\n * to run as a Job out of the boot (ADR-EA-011: no heavy work in boot).\n * - contract: set the column `NOT NULL`, then the full RLS wall from\n * {@link buildTenantRlsPolicySql}. Runs only AFTER a stable deploy.\n */\nexport function planAddTenantColumn(options: AddTenantColumnOptions): readonly MigrationStep[] {\n const schema = assertIdent(options.schema ?? \"public\", \"schema\");\n const table = assertIdent(options.table, \"table\");\n const column = assertIdent(options.tenantColumn ?? \"organization_id\", \"tenantColumn\");\n const type = assertIdent(options.tenantColumnType ?? \"text\", \"tenantColumnType\");\n const qualified = `${schema}.${table}`;\n\n const expandSql = [\n `ALTER TABLE ${qualified} ADD COLUMN IF NOT EXISTS ${column} ${type};`,\n `CREATE INDEX IF NOT EXISTS ${table}_${column}_idx ON ${qualified} (${column});`,\n ].join(\"\\n\");\n\n const steps: MigrationStep[] = [\n {\n id: `${table}.expand`,\n phase: \"expand\",\n description: `add nullable ${column} and its index to ${qualified} (compat with the running version)`,\n sql: `${expandSql}\\n`,\n },\n ];\n\n if (options.backfillValue !== undefined) {\n const backfillValue = options.backfillValue;\n steps.push({\n id: `${table}.migrate`,\n phase: \"migrate\",\n description: `backfill ${column} on existing rows of ${qualified} (run as a Job, out of boot)`,\n sql: `UPDATE ${qualified} SET ${column} = ${backfillValue} WHERE ${column} IS NULL;\\n`,\n });\n }\n\n const contractSql = [\n `ALTER TABLE ${qualified} ALTER COLUMN ${column} SET NOT NULL;`,\n buildTenantRlsPolicySql({\n schema,\n table,\n tenantColumn: column,\n // exactOptionalPropertyTypes: forward the cast only for a non-text column.\n ...(type !== \"text\" ? { tenantColumnType: type } : {}),\n }),\n ].join(\"\\n\");\n\n steps.push({\n id: `${table}.contract`,\n phase: \"contract\",\n description: `enforce NOT NULL and the full RLS wall on ${qualified} (after a stable deploy)`,\n sql: `${contractSql}`,\n });\n\n return steps;\n}\n\n/**\n * A transaction-scoped advisory lock (ADR-EA-011 A1): one migration run per\n * release. The lock is released automatically at COMMIT/ROLLBACK, so a crashed\n * run never leaves it held.\n */\nexport function buildAdvisoryLockSql(lockKey: number): string {\n return `SELECT pg_advisory_xact_lock(${lockKey});`;\n}\n\n/**\n * Runs `run` inside a transaction holding the advisory lock `lockKey`\n * (ADR-EA-011 A1): BEGIN → lock → run → COMMIT, ROLLBACK on error. A failed\n * rollback is swallowed so it cannot mask the original error (as in\n * transaction.ts).\n */\nexport async function withMigrationLock<T>(conn: SqlConnection, lockKey: number, run: () => Promise<T>): Promise<T> {\n try {\n await conn.query(\"BEGIN\");\n await conn.query(buildAdvisoryLockSql(lockKey));\n const result = await run();\n await conn.query(\"COMMIT\");\n return result;\n } catch (err) {\n try {\n await conn.query(\"ROLLBACK\");\n } catch {\n // A failed rollback (e.g. the connection already died) must not mask the\n // original error — swallow it and rethrow the cause.\n }\n throw err;\n }\n}\n\nexport interface TenantTableRef {\n readonly schema?: string;\n readonly table: string;\n readonly tenantColumn?: string;\n}\n\ninterface RlsFlagsRow {\n readonly relrowsecurity: boolean;\n readonly relforcerowsecurity: boolean;\n}\n\ninterface PolicyCmdRow {\n readonly cmd: string;\n}\n\nconst REQUIRED_COMMANDS = [\"SELECT\", \"INSERT\", \"UPDATE\", \"DELETE\"] as const;\n\n/**\n * The coverage guard (ADR-EA-010 A3, REQ-SC-07): asserts every `table` carries\n * a complete RLS wall — ENABLE + FORCE row level security, and a policy for\n * each of SELECT/INSERT/UPDATE/DELETE (an `ALL` policy covers all four). An\n * incomplete wall is fail-open, so a gap throws {@link RlsCoverageError} and\n * fails CI/boot instead of shipping a leak.\n */\nexport async function assertRlsCoverage(conn: SqlConnection, tables: readonly TenantTableRef[]): Promise<void> {\n for (const ref of tables) {\n const schema = assertIdent(ref.schema ?? \"public\", \"schema\");\n const table = assertIdent(ref.table, \"table\");\n const qualified = `${schema}.${table}`;\n\n const flags = await conn.query<RlsFlagsRow>(\n \"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\",\n [schema, table],\n );\n const row = flags.rows[0];\n if (row === undefined) {\n throw new RlsCoverageError(`table ${qualified} was not found in pg_class — cannot verify its RLS wall`);\n }\n\n const missing: string[] = [];\n if (row.relrowsecurity !== true) {\n missing.push(\"ENABLE ROW LEVEL SECURITY\");\n }\n if (row.relforcerowsecurity !== true) {\n missing.push(\"FORCE ROW LEVEL SECURITY\");\n }\n\n const policies = await conn.query<PolicyCmdRow>(\n \"SELECT cmd FROM pg_policies WHERE schemaname = $1 AND tablename = $2\",\n [schema, table],\n );\n const covered = new Set(policies.rows.map((p) => p.cmd.toUpperCase()));\n for (const command of REQUIRED_COMMANDS) {\n if (!covered.has(command) && !covered.has(\"ALL\")) {\n missing.push(`${command} policy`);\n }\n }\n\n if (missing.length > 0) {\n throw new RlsCoverageError(`table ${qualified} has an incomplete RLS wall — missing: ${missing.join(\", \")}`);\n }\n }\n}\n"]}
|