@frogfish/k2db 2.0.7 → 3.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +391 -21
- package/{dist/db.d.ts → db.d.ts} +144 -28
- package/db.js +1761 -0
- package/package.json +13 -35
- package/dist/LICENSE +0 -674
- package/dist/README.md +0 -315
- package/dist/db.js +0 -1063
- package/dist/package.json +0 -32
- /package/{dist/data.d.ts → data.d.ts} +0 -0
- /package/{dist/data.js → data.js} +0 -0
package/README.md
CHANGED
|
@@ -23,9 +23,10 @@ Where it fits in the stack
|
|
|
23
23
|
|
|
24
24
|
Deployment tips (Nomad, Lambda, etc.)
|
|
25
25
|
- Environments: Targets Node.js runtimes (Node 18/20). Not suitable for non‑TCP “edge JS” (e.g., Cloudflare Workers) that cannot open Mongo sockets.
|
|
26
|
-
- Connection reuse: Create
|
|
27
|
-
-
|
|
28
|
-
-
|
|
26
|
+
- Connection reuse: Create and reuse `K2DB` instances.
|
|
27
|
+
- The underlying MongoDB connection pool is shared across `K2DB` instances created with the same cluster/auth settings (hosts/user/password/authSource/replicaset).
|
|
28
|
+
- This means you can safely keep one `K2DB` instance per logical database name (`name`) without creating a new TCP pool per database.
|
|
29
|
+
- `release()` is ref-counted: it only closes the shared pool when the last instance releases it.
|
|
29
30
|
- Example (AWS Lambda):
|
|
30
31
|
```ts
|
|
31
32
|
import { K2DB } from "@frogfish/k2db";
|
|
@@ -34,11 +35,28 @@ Deployment tips (Nomad, Lambda, etc.)
|
|
|
34
35
|
export const handler = async (event) => {
|
|
35
36
|
ready = ready || db.init();
|
|
36
37
|
await ready; // reused across warm invocations
|
|
37
|
-
const res = await db.find("hello", {
|
|
38
|
+
const res = await db.find("hello", {}, {}, 0, 10, event.userId);
|
|
38
39
|
return { statusCode: 200, body: JSON.stringify(res) };
|
|
39
40
|
};
|
|
40
41
|
```
|
|
41
|
-
-
|
|
42
|
+
If you serve multiple logical databases (multi-project / multi-tenant), cache `K2DB` by database name. Instances will still share a single underlying connection pool:
|
|
43
|
+
|
|
44
|
+
```ts
|
|
45
|
+
import { K2DB } from "@frogfish/k2db";
|
|
46
|
+
|
|
47
|
+
const base = { hosts: [{ host: "cluster0.example.mongodb.net" }], user: process.env.DB_USER, password: process.env.DB_PASS };
|
|
48
|
+
const byName = new Map<string, K2DB>();
|
|
49
|
+
|
|
50
|
+
function dbFor(name: string) {
|
|
51
|
+
let db = byName.get(name);
|
|
52
|
+
if (!db) {
|
|
53
|
+
db = new K2DB({ ...base, name });
|
|
54
|
+
byName.set(name, db);
|
|
55
|
+
}
|
|
56
|
+
return db;
|
|
57
|
+
}
|
|
58
|
+
```
|
|
59
|
+
- Pooling and timeouts: The MongoDB driver manages a small pool by default, and k2db reuses that pool across `K2DB` instances that share cluster/auth config.
|
|
42
60
|
- Serverless: keep `minPoolSize=0` (default), consider `maxIdleTimeMS` to drop idle sockets faster.
|
|
43
61
|
- Long‑lived services (Nomad): you can tune pool sizing if needed.
|
|
44
62
|
- You can adjust `connectTimeoutMS/serverSelectionTimeoutMS` in the code if your environment needs higher values.
|
|
@@ -82,7 +100,8 @@ Ownership (`_owner`)
|
|
|
82
100
|
- Purpose: `_owner` is not a tenant ID nor a technical auth scope. It’s a required, opinionated piece of metadata that records who a document belongs to (the data subject or system principal that created/owns it).
|
|
83
101
|
- Why it matters: Enables clear data lineage and supports privacy/jurisdiction workflows (GDPR/DSAR: “export all my data”, “delete my data”), audits, and stewardship.
|
|
84
102
|
- Typical values: a user’s UUID when a signed-in human creates the record; for automated/system operations use a stable identifier like `"system"`, `"service:mailer"`, or `"migration:2024-09-01"`.
|
|
85
|
-
- Not
|
|
103
|
+
- Not authentication: k2db does not authenticate callers. Your API/service still decides *who* the caller is and whether they are allowed to act.
|
|
104
|
+
- Optional enforcement: k2db can enforce owner scoping when you provide a per-call scope (see “Scope”), and can require scope on all calls when `ownershipMode: "strict"` is enabled.
|
|
86
105
|
- Multi-tenant setups: If you have tenants, keep a distinct `tenantId` (or similar) alongside `_owner`. `_owner` continues to model “who owns this record” rather than “which tenant it belongs to”.
|
|
87
106
|
|
|
88
107
|
Config
|
|
@@ -90,10 +109,11 @@ Config
|
|
|
90
109
|
import { K2DB } from "@frogfish/k2db";
|
|
91
110
|
|
|
92
111
|
const db = new K2DB({
|
|
93
|
-
name: "mydb",
|
|
112
|
+
name: "mydb", // logical database name; instances with the same hosts/auth share one connection pool
|
|
94
113
|
hosts: [{ host: "cluster0.example.mongodb.net" }], // SRV if single host without port
|
|
95
114
|
user: process.env.DB_USER,
|
|
96
115
|
password: process.env.DB_PASS,
|
|
116
|
+
authSource: process.env.DB_AUTH_SOURCE, // optional (defaults to "admin" when user+password provided)
|
|
97
117
|
slowQueryMs: 300,
|
|
98
118
|
hooks: {
|
|
99
119
|
beforeQuery: (op, d) => {},
|
|
@@ -105,9 +125,358 @@ await db.init();
|
|
|
105
125
|
await db.ensureIndexes("myCollection");
|
|
106
126
|
```
|
|
107
127
|
|
|
128
|
+
### Scope config
|
|
129
|
+
|
|
130
|
+
- `ownershipMode?: "lax" | "strict"` (default: `"lax"`)
|
|
131
|
+
- `"lax"` (default): Passing a scope is optional. If you provide a scope, k2db enforces it as an owner filter; if omitted, behavior is unchanged from historical (no owner enforcement, but still enforces soft-delete).
|
|
132
|
+
- `"strict"`: Scope is *required* on all scopified methods (see “Scope” below). If you omit scope, k2db throws an error. This helps prevent accidental missing owner filters.
|
|
133
|
+
|
|
134
|
+
Example config with strict mode:
|
|
135
|
+
```ts
|
|
136
|
+
const db = new K2DB({
|
|
137
|
+
name: "mydb",
|
|
138
|
+
hosts: [{ host: "cluster0.example.mongodb.net" }],
|
|
139
|
+
user: process.env.DB_USER,
|
|
140
|
+
password: process.env.DB_PASS,
|
|
141
|
+
ownershipMode: "strict",
|
|
142
|
+
});
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
### Aggregation config
|
|
146
|
+
|
|
147
|
+
- `aggregationMode?: "loose" | "guarded" | "strict"` (default: `"loose"`)
|
|
148
|
+
- `"loose"`: No aggregation pipeline validation (all MongoDB stages permitted).
|
|
149
|
+
- `"guarded"`: Denies `$out`, `$merge`, `$function`, `$accumulator`; requires a positive limit, caps max limit, and adds `maxTimeMS`.
|
|
150
|
+
- `"strict"`: Allows only `$match`, `$project`, `$sort`, `$skip`, `$limit` stages; also requires and caps limit.
|
|
151
|
+
|
|
152
|
+
Example:
|
|
153
|
+
```ts
|
|
154
|
+
const db = new K2DB({
|
|
155
|
+
name: "mydb",
|
|
156
|
+
hosts: [{ host: "cluster0.example.mongodb.net" }],
|
|
157
|
+
aggregationMode: "guarded", // disables dangerous stages, enforces limit
|
|
158
|
+
});
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
## Scope
|
|
162
|
+
|
|
163
|
+
Scope is an optional per-call “owner filter” that k2db can apply to most data access and mutation methods. It provides a safety guardrail to help prevent missing `_owner` filters, especially in multi-tenant or user-data contexts.
|
|
164
|
+
|
|
165
|
+
**Scope is not authentication or authorization:** It does not decide *who* may act. Your API/service is still responsible for authenticating callers and deciding what scopes/owners they are allowed to access.
|
|
166
|
+
|
|
167
|
+
### Type
|
|
168
|
+
|
|
169
|
+
```ts
|
|
170
|
+
type Scope = string | "*";
|
|
171
|
+
```
|
|
172
|
+
- If a `string` is provided, only documents with `_owner === scope` are included or affected.
|
|
173
|
+
- If `"*"` is provided, *all* owners are included (no owner filter). This is intended for admin/service-to-service operations—never pass untrusted `"*"` from user input.
|
|
174
|
+
|
|
175
|
+
### Modes
|
|
176
|
+
|
|
177
|
+
- In `ownershipMode: "lax"` (default):
|
|
178
|
+
- If `scope` is omitted: No owner filtering is applied (historical behavior; still enforces soft-delete).
|
|
179
|
+
- If `scope` is provided: Only docs with `_owner === scope` (or all docs if `"*"`).
|
|
180
|
+
- In `ownershipMode: "strict"`:
|
|
181
|
+
- `scope` is *required* for all scopified methods (see below). If not provided, k2db throws an error.
|
|
182
|
+
- Use `"*"` for admin/system/service calls (do not invent a magic owner like `_system`).
|
|
183
|
+
|
|
184
|
+
### Methods that support scope
|
|
185
|
+
|
|
186
|
+
The following methods accept an optional `scope?: Scope | string` as their final argument:
|
|
187
|
+
- `get`
|
|
188
|
+
- `findOne`
|
|
189
|
+
- `find`
|
|
190
|
+
- `count`
|
|
191
|
+
- `update`
|
|
192
|
+
- `updateAll`
|
|
193
|
+
- `delete`
|
|
194
|
+
- `deleteAll`
|
|
195
|
+
- `restore`
|
|
196
|
+
- `purge`
|
|
197
|
+
- `purgeDeletedOlderThan`
|
|
198
|
+
- `drop` and `dropDatabase`: For destructive/admin operations, use `"*"` as scope to indicate you intend to operate without owner restriction.
|
|
199
|
+
|
|
200
|
+
### Examples
|
|
201
|
+
|
|
202
|
+
#### a) User reads own docs
|
|
203
|
+
```ts
|
|
204
|
+
// Only docs owned by this user
|
|
205
|
+
await db.find("posts", {}, {}, 0, 20, userId);
|
|
206
|
+
```
|
|
207
|
+
|
|
208
|
+
#### b) Admin/service reads or mutates all docs
|
|
209
|
+
```ts
|
|
210
|
+
// Read all posts (no owner restriction)
|
|
211
|
+
await db.find("posts", {}, {}, 0, 20, "*");
|
|
212
|
+
|
|
213
|
+
// Delete a user (admin only)
|
|
214
|
+
await db.delete("users", id, "*");
|
|
215
|
+
```
|
|
216
|
+
|
|
217
|
+
#### c) Strict mode with HTTP header mapping
|
|
218
|
+
Suppose your API receives:
|
|
219
|
+
```
|
|
220
|
+
X-Scope: <userId> | *
|
|
221
|
+
```
|
|
222
|
+
You should map this header to the `scope` argument:
|
|
223
|
+
```ts
|
|
224
|
+
const scope = req.headers["x-scope"];
|
|
225
|
+
// Only allow "*" for trusted admin/service credentials!
|
|
226
|
+
await db.find("posts", {}, {}, 0, 20, scope);
|
|
227
|
+
```
|
|
228
|
+
|
|
229
|
+
### Rules of thumb
|
|
230
|
+
- Never pass untrusted `"*"` as a scope—restrict this to trusted admin/service credentials only.
|
|
231
|
+
- Prefer passing a scope everywhere; enabling strict mode helps you catch missing owner filters.
|
|
232
|
+
- Normalize `_owner` values consistently—prefer lowercase and a single convention (e.g., always userId as lowercase UUID).
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
## Aggregation
|
|
236
|
+
|
|
237
|
+
Aggregation in k2db lets you run MongoDB pipelines with guardrails for soft-delete, secure fields, and pipeline safety.
|
|
238
|
+
|
|
239
|
+
### `aggregate(collection, pipeline, skip?, limit?)`
|
|
240
|
+
|
|
241
|
+
Runs an aggregation pipeline on the given collection, returning an array of documents. k2db automatically injects filters and enforces restrictions for safety and consistency.
|
|
242
|
+
|
|
243
|
+
#### What k2db enforces automatically
|
|
244
|
+
|
|
245
|
+
- **Soft-delete enforcement:** Automatically inserts a `$match: { _deleted: { $ne: true } }` stage near the start of your pipeline so only non-deleted documents are returned. For pipelines beginning with `$search`, `$geoNear`, or `$vectorSearch`, the filter is injected after the first stage to avoid breaking those operators.
|
|
246
|
+
- **Nested enforcement:** For `$lookup`, `$unionWith`, `$graphLookup`, and `$facet`, any sub-pipeline is rewritten to ensure the non-deleted filter applies to foreign collections as well. Simple `$lookup` with `localField`/`foreignField` is rewritten to pipeline form so the non-deleted filter can be injected.
|
|
247
|
+
- **Pagination:** If you pass `skip`/`limit`, those are appended to the pipeline. In `"guarded"`/`"strict"` aggregationMode, a positive limit is required and capped to a safe maximum, and `maxTimeMS` is set to prevent long-running queries.
|
|
248
|
+
- **Secure fields:** If `secureFieldPrefixes` is configured (e.g. `["#"]`), any pipeline referencing a secure-prefixed field (such as `"#passport_number"`) is rejected, even in expressions. Returned documents are also stripped of any keys beginning with a secure prefix.
|
|
249
|
+
|
|
250
|
+
#### What you cannot do (by default)
|
|
251
|
+
|
|
252
|
+
- **Return soft-deleted documents:** The injected `$match: { _deleted: { $ne: true } }` filter means aggregate will never return soft-deleted docs, regardless of your pipeline.
|
|
253
|
+
- **Use secure fields in aggregate:** Any pipeline referencing a field like `"#passport_number"` (including in `$project`, `$addFields`, or expressions) is rejected with an error. Even if a document contains a secure-prefixed field, it is stripped from the output.
|
|
254
|
+
- **Use dangerous or non-allowlisted stages:** In `"guarded"` mode, you cannot use `$out`, `$merge`, `$function`, or `$accumulator`. In `"strict"` mode, only `$match`, `$project`, `$sort`, `$skip`, and `$limit` are allowed.
|
|
255
|
+
|
|
256
|
+
#### Filtering level: root vs nested pipelines
|
|
257
|
+
|
|
258
|
+
- The root pipeline always gets the non-deleted filter injected (unless the first stage is `$search`, `$geoNear`, or `$vectorSearch`, in which case it's injected after).
|
|
259
|
+
- For nested pipelines in `$lookup`, `$unionWith`, `$graphLookup`, and `$facet`, k2db rewrites or injects the non-deleted filter into each sub-pipeline, so deleted foreign documents are excluded.
|
|
260
|
+
- If a `$lookup` uses the simple `localField`/`foreignField` form, k2db rewrites it to a pipeline `$lookup` so filtering can be enforced.
|
|
261
|
+
|
|
262
|
+
#### Examples
|
|
263
|
+
|
|
264
|
+
**1) Basic aggregation: injected soft-delete filter**
|
|
265
|
+
|
|
266
|
+
Suppose you call:
|
|
267
|
+
```js
|
|
268
|
+
const pipeline = [
|
|
269
|
+
{ $match: { status: "active" } },
|
|
270
|
+
{ $project: { name: 1, status: 1 } }
|
|
271
|
+
];
|
|
272
|
+
await db.aggregate("users", pipeline);
|
|
273
|
+
```
|
|
274
|
+
**Effective pipeline after k2db injection:**
|
|
275
|
+
```js
|
|
276
|
+
[
|
|
277
|
+
{ $match: { _deleted: { $ne: true } } }, // injected
|
|
278
|
+
{ $match: { status: "active" } },
|
|
279
|
+
{ $project: { name: 1, status: 1 } }
|
|
280
|
+
]
|
|
281
|
+
```
|
|
282
|
+
|
|
283
|
+
**2) `$lookup` rewritten for non-deleted foreign docs**
|
|
284
|
+
|
|
285
|
+
Original pipeline:
|
|
286
|
+
```js
|
|
287
|
+
[
|
|
288
|
+
{
|
|
289
|
+
$lookup: {
|
|
290
|
+
from: "orders",
|
|
291
|
+
localField: "_uuid",
|
|
292
|
+
foreignField: "user_id",
|
|
293
|
+
as: "orders"
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
]
|
|
297
|
+
```
|
|
298
|
+
k2db rewrites this to:
|
|
299
|
+
```js
|
|
300
|
+
[
|
|
301
|
+
{
|
|
302
|
+
$lookup: {
|
|
303
|
+
from: "orders",
|
|
304
|
+
let: { local_id: "$_uuid" },
|
|
305
|
+
pipeline: [
|
|
306
|
+
{ $match: { _deleted: { $ne: true } } }, // injected for foreign docs
|
|
307
|
+
{ $match: { $expr: { $eq: ["$user_id", "$$local_id"] } } }
|
|
308
|
+
],
|
|
309
|
+
as: "orders"
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
]
|
|
313
|
+
```
|
|
314
|
+
|
|
315
|
+
**3) Secure field reference is rejected**
|
|
316
|
+
|
|
317
|
+
Pipeline:
|
|
318
|
+
```js
|
|
319
|
+
[
|
|
320
|
+
{ $project: { name: 1, passport: "$#passport_number" } }
|
|
321
|
+
]
|
|
322
|
+
```
|
|
323
|
+
Result: **Throws an error** — referencing a secure-prefixed field (`"#passport_number"`) is not allowed in aggregate pipelines.
|
|
324
|
+
|
|
325
|
+
**4) Attempting to aggregate deleted docs returns nothing**
|
|
326
|
+
|
|
327
|
+
Pipeline:
|
|
328
|
+
```js
|
|
329
|
+
[
|
|
330
|
+
{ $match: { _deleted: true } }
|
|
331
|
+
]
|
|
332
|
+
```
|
|
333
|
+
Result: Returns **no documents** — k2db injects `{ _deleted: { $ne: true } }` before your match, so the result set is always empty.
|
|
334
|
+
|
|
335
|
+
---
|
|
336
|
+
|
|
337
|
+
> **Note:** k2db's aggregation guardrails ensure you cannot accidentally leak deleted or secure data, or run dangerous stages in stricter modes.
|
|
338
|
+
|
|
339
|
+
## Secure fields and encryption at rest
|
|
340
|
+
|
|
341
|
+
k2db supports **secure fields**: fields whose keys start with a configurable prefix (recommended: `#`). Secure fields are designed to be hard to accidentally leak in bulk queries and hard to casually access in code.
|
|
342
|
+
|
|
343
|
+
This feature has two layers:
|
|
344
|
+
|
|
345
|
+
1) **Guardrails (always):** Secure fields are stripped from multi-record reads (`find`, `aggregate`) and cannot be explicitly projected. Aggregation pipelines are also rejected if they reference secure fields.
|
|
346
|
+
2) **Encryption at rest (optional):** When enabled, secure-field values are encrypted before being written to MongoDB and decrypted on single-record reads.
|
|
347
|
+
|
|
348
|
+
### Why `#` (friction) instead of `__somethingNice`
|
|
349
|
+
|
|
350
|
+
The goal is to make secure fields “visually wrong” and **ergonomically annoying** to access on purpose:
|
|
351
|
+
|
|
352
|
+
- `doc["#passport_number"]` is explicit and reviewable.
|
|
353
|
+
- `doc.#passport_number` is impossible (forces bracket access).
|
|
354
|
+
- It discourages lazy DTO copying and casual destructuring that can accidentally leak secrets.
|
|
355
|
+
|
|
356
|
+
Using `__private` looks “normal”, which increases the chance developers will treat it like any other field and accidentally return it in list endpoints.
|
|
357
|
+
|
|
358
|
+
Also, `_...` is reserved for k2db’s metadata (`_uuid`, `_owner`, `_created`, …), so `#...` cleanly avoids that namespace.
|
|
359
|
+
|
|
360
|
+
### Configuration
|
|
361
|
+
|
|
362
|
+
Enable secure fields by setting `secureFieldPrefixes`. To also encrypt them at rest, provide a base64 AES-256 key and a key id.
|
|
363
|
+
|
|
364
|
+
```ts
|
|
365
|
+
const db = new K2DB({
|
|
366
|
+
name: "mydb",
|
|
367
|
+
hosts: [{ host: "cluster0.example.mongodb.net" }],
|
|
368
|
+
|
|
369
|
+
// Treat "#..." fields as secure
|
|
370
|
+
secureFieldPrefixes: ["#"],
|
|
371
|
+
|
|
372
|
+
// Optional encryption-at-rest for secure fields:
|
|
373
|
+
// - must decode to 32 bytes (AES-256)
|
|
374
|
+
// - values are stored as "<keyid>:<payload>"
|
|
375
|
+
secureFieldEncryptionKeyId: "k1",
|
|
376
|
+
secureFieldEncryptionKey: process.env.K2DB_SECURE_KEY_B64,
|
|
377
|
+
});
|
|
378
|
+
```
|
|
379
|
+
|
|
380
|
+
Key requirements:
|
|
381
|
+
- `secureFieldEncryptionKey` must be **base64** and decode to **32 bytes**.
|
|
382
|
+
- Encryption is enabled only when **both** `secureFieldEncryptionKey` and `secureFieldEncryptionKeyId` are provided.
|
|
383
|
+
|
|
384
|
+
> Note: Today k2db decrypts only ciphertexts whose `keyid` matches the configured `secureFieldEncryptionKeyId`. If the stored `keyid` differs, the encrypted string is returned as-is (useful during key rotation rollout, but plan your rotation strategy accordingly).
|
|
385
|
+
|
|
386
|
+
### Storage format
|
|
387
|
+
|
|
388
|
+
When encryption is enabled, each secure field value is stored as a single string:
|
|
389
|
+
|
|
390
|
+
```
|
|
391
|
+
<keyid>:<ivB64>.<tagB64>.<ctB64>
|
|
392
|
+
```
|
|
393
|
+
|
|
394
|
+
- Algorithm: AES-256-GCM
|
|
395
|
+
- Plaintext: `JSON.stringify(value)` (so secure fields may be strings, numbers, objects, arrays, etc.)
|
|
396
|
+
|
|
397
|
+
### Behavior by method
|
|
398
|
+
|
|
399
|
+
With `secureFieldPrefixes: ["#"]`:
|
|
400
|
+
|
|
401
|
+
- **create / update / updateAll**:
|
|
402
|
+
- If encryption is enabled, `#...` values are encrypted before write.
|
|
403
|
+
- If encryption is disabled, values are stored as provided.
|
|
404
|
+
- **get / findOne** (single-record reads):
|
|
405
|
+
- If encryption is enabled, `#...` values are decrypted and returned in the object.
|
|
406
|
+
- If encryption is disabled, values are returned as stored.
|
|
407
|
+
- **find** (multi-record reads):
|
|
408
|
+
- Secure fields are **stripped** from every returned document (even if encryption is disabled).
|
|
409
|
+
- **aggregate**:
|
|
410
|
+
- Secure fields are **not allowed to be referenced** in the pipeline (k2db throws).
|
|
411
|
+
- Secure fields are also **stripped** from returned documents as a second safety net.
|
|
412
|
+
- **projections**:
|
|
413
|
+
- `findOne(fields=[...])` and `find(params.filter=[...])` cannot include secure fields (throws).
|
|
414
|
+
|
|
415
|
+
### Examples
|
|
416
|
+
|
|
417
|
+
#### 1) Store a secure field
|
|
418
|
+
|
|
419
|
+
```ts
|
|
420
|
+
const owner = userId.toLowerCase();
|
|
421
|
+
|
|
422
|
+
const { id } = await db.create("profiles", owner, {
|
|
423
|
+
name: "Ada",
|
|
424
|
+
"#passport_number": "123456789",
|
|
425
|
+
"#home_address": { line1: "1 Example St", city: "Perth" },
|
|
426
|
+
});
|
|
427
|
+
```
|
|
428
|
+
|
|
429
|
+
- If encryption is enabled, MongoDB stores `"#passport_number"` and `"#home_address"` as encrypted strings.
|
|
430
|
+
- If encryption is disabled, they are stored as plaintext (still guarded on reads).
|
|
431
|
+
|
|
432
|
+
#### 2) Single-record read returns secure fields
|
|
433
|
+
|
|
434
|
+
```ts
|
|
435
|
+
const profile = await db.get("profiles", id, owner);
|
|
436
|
+
|
|
437
|
+
// Explicit access (friction by design)
|
|
438
|
+
console.log(profile["#passport_number"]);
|
|
439
|
+
```
|
|
440
|
+
|
|
441
|
+
#### 3) Multi-record read strips secure fields
|
|
442
|
+
|
|
443
|
+
```ts
|
|
444
|
+
const list = await db.find("profiles", {}, {}, 0, 50, owner);
|
|
445
|
+
|
|
446
|
+
// "#..." fields are removed from each document in list
|
|
447
|
+
console.log(list[0]["#passport_number"]); // undefined
|
|
448
|
+
```
|
|
449
|
+
|
|
450
|
+
#### 4) Aggregation cannot reference secure fields
|
|
451
|
+
|
|
452
|
+
```ts
|
|
453
|
+
await db.aggregate("profiles", [
|
|
454
|
+
{ $project: { name: 1, passport: "$#passport_number" } },
|
|
455
|
+
]);
|
|
456
|
+
// throws: secure-prefixed field referenced in pipeline
|
|
457
|
+
```
|
|
458
|
+
|
|
459
|
+
### What this is (and isn’t)
|
|
460
|
+
|
|
461
|
+
- This is a **data safety guardrail** and optional encryption-at-rest mechanism.
|
|
462
|
+
- It is **not authentication/authorization**: you still must decide who the caller is and what they’re allowed to do.
|
|
463
|
+
- For admin/service operations, combine this with **Scope** rules: do not accept `"*"` from untrusted callers.
|
|
464
|
+
|
|
108
465
|
Environment loader
|
|
109
466
|
```ts
|
|
110
|
-
const conf = K2DB.fromEnv(); // K2DB_NAME, K2DB_HOSTS, K2DB_USER, K2DB_PASSWORD, K2DB_REPLICASET, K2DB_SLOW_MS
|
|
467
|
+
const conf = K2DB.fromEnv(); // K2DB_NAME (logical db), K2DB_HOSTS, K2DB_USER, K2DB_PASSWORD, K2DB_AUTH_SOURCE, K2DB_REPLICASET, K2DB_SLOW_MS
|
|
468
|
+
```
|
|
469
|
+
|
|
470
|
+
Testing
|
|
471
|
+
|
|
472
|
+
If you run many test suites in a single Node process and want to fully tear down shared MongoDB pools between suites, you can use the test helper:
|
|
473
|
+
|
|
474
|
+
```ts
|
|
475
|
+
import { resetSharedMongoClientsForTests } from "@frogfish/k2db";
|
|
476
|
+
|
|
477
|
+
afterAll(async () => {
|
|
478
|
+
await resetSharedMongoClientsForTests();
|
|
479
|
+
});
|
|
111
480
|
```
|
|
112
481
|
|
|
113
482
|
Tips
|
|
@@ -168,6 +537,7 @@ export K2DB_NAME=mydb
|
|
|
168
537
|
export K2DB_HOSTS=cluster0.xxxxxx.mongodb.net
|
|
169
538
|
export K2DB_USER=your_user
|
|
170
539
|
export K2DB_PASSWORD=your_pass
|
|
540
|
+
export K2DB_AUTH_SOURCE=admin
|
|
171
541
|
node hello.mjs
|
|
172
542
|
```
|
|
173
543
|
```ts
|
|
@@ -194,7 +564,7 @@ const db = new K2DB({
|
|
|
194
564
|
password: process.env.DB_PASS,
|
|
195
565
|
});
|
|
196
566
|
|
|
197
|
-
await db.init();
|
|
567
|
+
await db.init(); // safe to call multiple times; concurrent calls are deduped
|
|
198
568
|
await db.ensureIndexes("hello"); // unique _uuid among non-deleted, plus helpful indexes
|
|
199
569
|
|
|
200
570
|
// Create a document (owner is required)
|
|
@@ -273,19 +643,19 @@ db.clearSchema("hello");
|
|
|
273
643
|
- `VersionInfo`: `{ _uuid: string; _v: number; _at: number }`
|
|
274
644
|
|
|
275
645
|
Returns by method
|
|
276
|
-
- `get(collection, id)`: `Promise<BaseDocument>`
|
|
277
|
-
- `find(collection, filter, params?, skip?, limit?)`: `Promise<BaseDocument[]>`
|
|
278
|
-
- `findOne(collection, criteria, fields?)`: `Promise<BaseDocument|null>`
|
|
646
|
+
- `get(collection, id, scope?)`: `Promise<BaseDocument>`
|
|
647
|
+
- `find(collection, filter, params?, skip?, limit?, scope?)`: `Promise<BaseDocument[]>`
|
|
648
|
+
- `findOne(collection, criteria, fields?, scope?)`: `Promise<BaseDocument|null>`
|
|
279
649
|
- `aggregate(collection, pipeline, skip?, limit?)`: `Promise<BaseDocument[]>`
|
|
280
650
|
- `create(collection, owner, data)`: `Promise<CreateResult>`
|
|
281
|
-
- `update(collection, id, data, replace?)`: `Promise<UpdateResult>`
|
|
282
|
-
- `updateAll(collection, criteria, values)`: `Promise<UpdateResult>`
|
|
283
|
-
- `delete(collection, id)`: `Promise<DeleteResult>`
|
|
284
|
-
- `deleteAll(collection, criteria)`: `Promise<DeleteResult>`
|
|
285
|
-
- `purge(collection, id)`: `Promise<PurgeResult>`
|
|
286
|
-
- `restore(collection, criteria)`: `Promise<RestoreResult>`
|
|
287
|
-
- `count(collection, criteria)`: `Promise<CountResult>`
|
|
288
|
-
- `drop(collection)`: `Promise<DropResult>`
|
|
651
|
+
- `update(collection, id, data, replace?, scope?)`: `Promise<UpdateResult>`
|
|
652
|
+
- `updateAll(collection, criteria, values, scope?)`: `Promise<UpdateResult>`
|
|
653
|
+
- `delete(collection, id, scope?)`: `Promise<DeleteResult>`
|
|
654
|
+
- `deleteAll(collection, criteria, scope?)`: `Promise<DeleteResult>`
|
|
655
|
+
- `purge(collection, id, scope?)`: `Promise<PurgeResult>`
|
|
656
|
+
- `restore(collection, criteria, scope?)`: `Promise<RestoreResult>`
|
|
657
|
+
- `count(collection, criteria, scope?)`: `Promise<CountResult>`
|
|
658
|
+
- `drop(collection, scope?)`: `Promise<DropResult>`
|
|
289
659
|
- `ensureIndexes(collection, opts?)`: `Promise<void>`
|
|
290
660
|
- `ensureHistoryIndexes(collection)`: `Promise<void>`
|
|
291
661
|
- `updateVersioned(collection, id, data, replace?, maxVersions?)`: `Promise<VersionedUpdateResult[]>`
|
|
@@ -302,7 +672,7 @@ _uuid = Crockford Base32 encoded UUID V7, Uppercase, with hyphens
|
|
|
302
672
|
|
|
303
673
|
0J4F2-H6M8Q-7RX4V-9D3TN-8K2WZ
|
|
304
674
|
|
|
305
|
-
// Canonical uppercase form with hyphens
|
|
675
|
+
// Canonical uppercase form with hyphens Crockford 32
|
|
306
676
|
const CROCKFORD_ID_REGEX = /^[0-9A-HJKMNP-TV-Z]{5}-[0-9A-HJKMNP-TV-Z]{5}-[0-9A-HJKMNP-TV-Z]{5}-[0-9A-HJKMNP-TV-Z]{5}-[0-9A-HJKMNP-TV-Z]{6}$/;
|
|
307
677
|
|
|
308
678
|
// Example usage:
|