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