@iskra-bun/db-kit 0.2.0 → 0.3.1
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/CHANGELOG.md +62 -0
- package/README.md +9 -3
- package/dist/index.d.ts +67 -13
- package/dist/index.js +222 -129
- package/dist/index.js.map +1 -1
- package/package.json +9 -6
- package/src/cli.ts +11 -2
- package/src/driver.ts +132 -41
- package/src/drizzle.config.template.ts +16 -5
- package/src/errors.ts +1 -1
- package/src/index.ts +1 -1
- package/src/migrations.ts +51 -14
- package/src/secrets.ts +2 -0
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,67 @@
|
|
|
1
1
|
# @iskra-bun/db-kit
|
|
2
2
|
|
|
3
|
+
## 0.3.1
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- Updated dependencies [e86ed55]
|
|
8
|
+
- Updated dependencies [ae7c798]
|
|
9
|
+
- Updated dependencies [ef10372]
|
|
10
|
+
- @iskra-bun/core@0.3.0
|
|
11
|
+
|
|
12
|
+
## 0.3.0
|
|
13
|
+
|
|
14
|
+
### Minor Changes
|
|
15
|
+
|
|
16
|
+
- bf6f901: Runtime fixes.
|
|
17
|
+
|
|
18
|
+
- `start()` does a `SELECT 1` round-trip before reporting "DB connected successfully". postgres-js and mysql2 connect lazily, so a wrong host or password used to surface only on the first query; `start()` now fails with a `ConnectionError` (credentials scrubbed) and closes the client.
|
|
19
|
+
- `runMigrations(schemaPath, migrationsDir)` now applies the migrations generated in `migrationsDir` over the live connection with Drizzle's migrator (postgres, mysql, sqlite, libsql). It used to spawn `drizzle-kit migrate`, which ignored both arguments and failed without a `drizzle.config.ts`. It requires a started driver; `schemaPath` is not needed to apply migrations. Failures are wrapped in `MigrationError`.
|
|
20
|
+
- Docs and CLI help: `drop` deletes a generated migration file (drizzle-kit's `drop`); it never dropped database tables as documented.
|
|
21
|
+
|
|
22
|
+
- ef2009b: **Security:** update dependencies with known vulnerabilities (`bun audit` went from 67 findings, 1 critical and 38 high, to one accepted dev-only finding).
|
|
23
|
+
|
|
24
|
+
- `better-auth` ^1.6.33 (account takeover via pre-account hijacking), `hono` ^4.12.34, `ajv` ^8.20.0, `mysql2` ^3.24.4 (web-kit, auth-kit, db-kit).
|
|
25
|
+
- `drizzle-orm` ^0.45.2 (SQL injection via improperly escaped identifiers). **db-kit moves from 0.30 to 0.45**, the same line web-kit and auth-kit already used, so schemas are shared across kits again; `drizzle-kit` ^0.31.11 now matches it (0.30 exited with "requires newer version of drizzle-orm", so migrations never ran), and `@libsql/client` ^0.18.0 satisfies drizzle's peer range.
|
|
26
|
+
- `c12` ^3.3.4 in core (drops the vulnerable `tar` 6 pulled in through `giget` 1).
|
|
27
|
+
- `nodemailer` ^10.0.10 in mailer-kit (arbitrary file read / SSRF via the raw option, SMTP command and header injection).
|
|
28
|
+
|
|
29
|
+
- 938dd41: **Security** fixes from the data-kits audit (round 2).
|
|
30
|
+
|
|
31
|
+
- `storage-kit` (**breaking**): files are stored and served with a type from their extension (`contentTypeFor`), and anything but a raster image as a download. The S3 adapter stores a `Content-Disposition` with each object (`attachment` unless it is a PNG, JPEG, GIF, WebP, AVIF, BMP or ICO image; `put(..., { contentDisposition })` to choose), and `url()` signs `response-content-type` and `response-content-disposition` into presigned URLs whatever the object was stored with (`url(path, expiresIn, { contentType, contentDisposition })` to choose): an upload named `logo.svg` or `invoice.html` was stored as `image/svg+xml`/`text/html` and ran its scripts on the bucket's origin. HTML, SVG, XML and JavaScript are now `application/octet-stream`. `put(..., { overwrite: false })` throws the new `FileExistsError` instead of replacing a stored file (S3 `If-None-Match: *`, an exclusive create locally); `@aws-sdk/client-s3` and `@aws-sdk/s3-request-presigner` now need 3.635 or later, the first releases that send `If-None-Match` on a put (earlier ones dropped it, and the file was replaced). The plaintext-endpoint guard parses the endpoint as a URL, as the SDK does: `http:/minio:9000`, `http:minio:9000` and `http:\\minio:9000` were accepted without `useSSL: false`; an endpoint that is not an `http(s)` URL is rejected.
|
|
32
|
+
- `web-kit` uploads (**breaking**): the upload route stores a file with the type of its extension, never `File.type` (which Bun derives from the name), and `uploadFromRequest()` too. Downloads are streamed with `getStream()` (each one was buffered twice), typed by extension, `attachment` unless a raster image, and sandboxed (`Content-Security-Policy: sandbox`). Without `allowedExtensions`, active web content (`.html`, `.svg`, `.xml`, `.js`...) is refused (400) unless listed. `authorize(c, action, target)` receives what the action touches (`{ key, subfolder, filename, size, type }`), and `upload` is asked again with it before the file is written. An upload no longer replaces a stored file: **409** unless `overwrite: true`.
|
|
33
|
+
- `mailer-kit` (**breaking**): every `to`, `cc`, `bcc` and `replyTo` entry must be one bare address, or a new `{ name, address }` object for a display name, in every adapter (the mock too); only `from` was checked. One value such as `"bob@example.com <attacker@evil.test>, x@example.com"`, a group (`"undisclosed: a@evil.test; b@x.com"`, `"a@evil.test:b@x.com"`) or `{ address: "bob@example.com\r\nBcc: …" }` mailed other recipients than the ones an allowlist checked. Addresses may not contain whitespace, control characters or `<>()[]\,;:"` and need exactly one `@`; `replyTo` takes one recipient. `checkRecipients()` is exported. Mailgun cuts the `subject` at a CR/LF, as it does header values.
|
|
34
|
+
- `web-kit` email: `EmailFeature`'s adapter checks recipients with mailer-kit's rules (object recipients were tested as `"[object Object]"`), and rejects through the returned promise instead of throwing synchronously.
|
|
35
|
+
- `kv-kit`: the `KVAdapter` contract gains an optional `clear(prefix?)` and expiring sets (`sadd(key, member, ttl?)`, `sdrain(key)`), implemented by both adapters and `KVManager`. `KVManager.clear()` deletes its namespace's keys; with Redis it uses `SCAN` + `DEL` (within ioredis' `keyPrefix` too) and, without a namespace, refuses to empty the whole database unless `new KVManager({ flushDb: true })`. Expiring sets are sorted sets scored by expiry, updated by one atomic script: cache-kit's tag index. The memory adapter stores and returns copies (`structuredClone`), as Redis does (**breaking** for values that cannot be cloned, such as functions): it returned the stored object itself, so one request's mutation showed up in every other.
|
|
36
|
+
- `cache-kit` (**breaking**): `clear()` runs the adapter's `clear()` with the cache's namespace instead of `disconnect()`/`connect()` of the shared adapter, which on Redis deleted nothing (cached permissions stayed), failed concurrent operations meanwhile, and left the adapter dead when the reconnect failed during a Redis blip. A namespaced cache now clears its own entries (it used to throw); an adapter without `clear()` makes it throw. The tag index is kv-kit's expiring set when the adapter has one (one atomic `sadd` per tagged `set()`; each one read and rewrote the whole index, and the last 10k of 40k tagged sets took 30 s), and otherwise a JSON list that drops expired keys, expires with its last entry and keeps at most 10,000 (the oldest are deleted with their data); indexes written before are still drained by `invalidateTag()`. A value with a `__proto__`/`constructor`/`prototype` key is a miss (deleted when read; not stored by `set()`), so `remember()` refetches instead of every read throwing until the TTL ran out. Data keys and namespaces containing `__cache_tag__:`/`__cache_tags__:` (at the start or after a `:`) are rejected: a caller-chosen key could rewrite a tag index, and `invalidateTag()` deleted whatever it listed.
|
|
37
|
+
- `db-kit` (**breaking**): `MigrationHelper` and the CLI run only the drizzle-kit installed in the project (`node_modules/.bin` of the working directory or a parent), with `bunx --no-install drizzle-kit`, and fail with a `MigrationError` where it is not installed. drizzle-kit is a devDependency, so in a production install `bunx drizzle-kit` downloaded its latest release from npm and ran it with `DATABASE_URL` in its environment.
|
|
38
|
+
|
|
39
|
+
### Patch Changes
|
|
40
|
+
|
|
41
|
+
- 58d4a8f: `import "@iskra-bun/db-kit"` no longer requires `drizzle-kit` at runtime. Bun loads the package from `src/` (the `bun` export condition), where `createDrizzleConfig` imported `defineConfig` from `drizzle-kit`, a devDependency, so apps installed with `--production` (like the template Docker builds) failed to start. `createDrizzleConfig` now returns a plain object typed as the new `DrizzleKitConfig`, and the published types no longer reference `drizzle-kit`.
|
|
42
|
+
- 7e89103: `transaction()` with `sqlite` now rolls back when the async callback throws: Drizzle's bun-sqlite transaction is synchronous and committed as soon as the callback returned its promise. sqlite transactions run one at a time, and a nested `transaction()` call is rejected instead of waiting for itself. `scrubUrl()` and `scrubCredentials()` also redact secret query parameters such as libsql's `authToken`, and passwords containing a raw `@` or `/`; the connection error's context no longer carries the libsql token.
|
|
43
|
+
- 840439a: Packages declare the runtime they are tested on: `engines.bun` `>=1.3.0` (the monorepo now builds and tests on Bun 1.3). `create-iskra`, a CLI that also runs under `npm create iskra`, declares `engines.node` `>=18`.
|
|
44
|
+
|
|
45
|
+
Every package is published with an npm provenance attestation (`publishConfig.provenance`), linking each version to the commit and CI run that built it.
|
|
46
|
+
|
|
47
|
+
- cb3ec43: Register what each kit puts on the app with core's new registries: `app.context.get('db' | 'kv' | 'oracle')` returns the kit's driver, and the `process:*`, `socket:connected` / `socket:disconnected` and `worker:dead-letter` events have typed payloads. `ProcessManager.send()` takes `unknown` data.
|
|
48
|
+
- 87f6de2: `KVManager` throws when its constructor gets `adapter`, `driver` or `connection`: the store is chosen by the App config (`kv: { driver, connection }`), and the README's `new KVManager({ adapter: 'redis' })` was silently ignored, leaving the app on per-process memory. Without a `kv` driver it now logs a warning in production instead of an info line. The READMEs of kv-kit, worker-kit (`connection` and `queueName`, not `queue`), db-kit (the App's `db` config) and process-kit (the App's `processes` config) show working examples.
|
|
49
|
+
- Updated dependencies [620da18]
|
|
50
|
+
- Updated dependencies [b635a2c]
|
|
51
|
+
- Updated dependencies [5b2b0fd]
|
|
52
|
+
- Updated dependencies [58d4a8f]
|
|
53
|
+
- Updated dependencies [5c70c5b]
|
|
54
|
+
- Updated dependencies [ec198d4]
|
|
55
|
+
- Updated dependencies [cb3ec43]
|
|
56
|
+
- Updated dependencies [ef2009b]
|
|
57
|
+
- Updated dependencies [840439a]
|
|
58
|
+
- Updated dependencies [dbf8817]
|
|
59
|
+
- Updated dependencies [3dc5581]
|
|
60
|
+
- Updated dependencies [9872d30]
|
|
61
|
+
- Updated dependencies [f2346f5]
|
|
62
|
+
- Updated dependencies [3579944]
|
|
63
|
+
- @iskra-bun/core@0.2.0
|
|
64
|
+
|
|
3
65
|
## 0.2.0
|
|
4
66
|
|
|
5
67
|
### Minor Changes
|
package/README.md
CHANGED
|
@@ -14,15 +14,21 @@ bun add @iskra-bun/db-kit @iskra-bun/core
|
|
|
14
14
|
import { App } from '@iskra-bun/core'
|
|
15
15
|
import { DbDriver } from '@iskra-bun/db-kit'
|
|
16
16
|
|
|
17
|
-
const app = new App({
|
|
18
|
-
|
|
17
|
+
const app = new App({
|
|
18
|
+
name: 'mi-app',
|
|
19
|
+
db: { driver: 'sqlite', url: 'app.db' }, // o 'postgres' / 'mysql' con su URL
|
|
20
|
+
})
|
|
21
|
+
const db = new DbDriver()
|
|
22
|
+
app.register(db)
|
|
19
23
|
|
|
20
24
|
await app.start()
|
|
21
25
|
```
|
|
22
26
|
|
|
27
|
+
La conexion se configura en la config de la App (`db`), no en el constructor de `DbDriver`.
|
|
28
|
+
|
|
23
29
|
## Documentacion
|
|
24
30
|
|
|
25
|
-
Guia completa: [
|
|
31
|
+
Guia completa: [@iskra-bun/db-kit](https://iskra-docs.fly.dev/es/packages/db-kit/) · [Migraciones](https://iskra-docs.fly.dev/es/guides/migrations/)
|
|
26
32
|
|
|
27
33
|
## Licencia
|
|
28
34
|
|
package/dist/index.d.ts
CHANGED
|
@@ -3,7 +3,6 @@ import { PostgresJsDatabase } from 'drizzle-orm/postgres-js';
|
|
|
3
3
|
import { MySql2Database } from 'drizzle-orm/mysql2';
|
|
4
4
|
import { BunSQLiteDatabase } from 'drizzle-orm/bun-sqlite';
|
|
5
5
|
import { LibSQLDatabase } from 'drizzle-orm/libsql';
|
|
6
|
-
import * as drizzle_kit from 'drizzle-kit';
|
|
7
6
|
|
|
8
7
|
/**
|
|
9
8
|
* Observability callback invoked for every SQL statement Drizzle executes.
|
|
@@ -27,15 +26,20 @@ type IskraDrizzleTx<TSchema extends Record<string, unknown> = Record<string, nev
|
|
|
27
26
|
*/
|
|
28
27
|
type IskraDrizzleDb<TSchema extends Record<string, unknown> = Record<string, never>> = PostgresJsDatabase<TSchema> | MySql2Database<TSchema> | BunSQLiteDatabase<TSchema> | LibSQLDatabase<TSchema>;
|
|
29
28
|
/**
|
|
30
|
-
* Redact username
|
|
29
|
+
* Redact the username, password and secret query parameters (`authToken`,
|
|
30
|
+
* `password`, `sslpassword`...) from a database URL so it is safe to log.
|
|
31
31
|
* Returns the scrubbed URL string, or undefined if parsing fails.
|
|
32
32
|
*
|
|
33
33
|
* e.g. postgres://user:pass@host:5432/db → postgres://***:***@host:5432/db
|
|
34
|
+
* libsql://db.turso.io?authToken=eyJ… → libsql://db.turso.io?authToken=***
|
|
34
35
|
*/
|
|
35
36
|
declare function scrubUrl(url: string): string | undefined;
|
|
36
37
|
declare class DbDriver<TSchema extends Record<string, unknown> = Record<string, never>> implements Driver {
|
|
37
38
|
name: string;
|
|
38
39
|
private client;
|
|
40
|
+
/** Serializes transactions on the single bun:sqlite connection. */
|
|
41
|
+
private sqliteTxQueue;
|
|
42
|
+
private readonly inSqliteTx;
|
|
39
43
|
db: IskraDrizzleDb<TSchema> | undefined;
|
|
40
44
|
private app;
|
|
41
45
|
private onQuery;
|
|
@@ -54,25 +58,49 @@ declare class DbDriver<TSchema extends Record<string, unknown> = Record<string,
|
|
|
54
58
|
init(app: App): Promise<void>;
|
|
55
59
|
start(): Promise<void>;
|
|
56
60
|
/**
|
|
57
|
-
*
|
|
61
|
+
* Applies the pending migrations in `migrationsDir` (generated with
|
|
62
|
+
* `drizzle-kit generate`) over the live connection, using Drizzle's
|
|
63
|
+
* migrator for the configured dialect. Requires `start()`.
|
|
64
|
+
*
|
|
65
|
+
* It used to shell out to `drizzle-kit migrate`, which ignored both
|
|
66
|
+
* arguments and failed without a drizzle.config.ts. `schemaPath` is kept for
|
|
67
|
+
* compatibility; applying migrations does not need the schema.
|
|
58
68
|
*/
|
|
59
|
-
runMigrations(
|
|
69
|
+
runMigrations(_schemaPath?: string, migrationsDir?: string): Promise<void>;
|
|
60
70
|
/**
|
|
61
71
|
* Run `fn` inside a database transaction, delegating to Drizzle's
|
|
62
72
|
* `db.transaction`. Callers receive the transaction-scoped db handle instead
|
|
63
73
|
* of reaching into the raw `db`. The dialect union means `tx` is typed as
|
|
64
74
|
* {@link IskraDrizzleTx}; narrow by dialect if you need dialect-specific APIs.
|
|
65
|
-
* Failures are wrapped in {@link QueryError}
|
|
75
|
+
* Failures are wrapped in {@link QueryError}; the transaction is rolled back.
|
|
76
|
+
*
|
|
77
|
+
* With `sqlite`, transactions run one at a time on the single connection,
|
|
78
|
+
* and a query made outside `tx` while one is open is part of it. A nested
|
|
79
|
+
* `transaction()` call is rejected: it would wait for itself.
|
|
66
80
|
*/
|
|
67
81
|
transaction<R>(fn: (tx: IskraDrizzleTx<TSchema>) => Promise<R>): Promise<R>;
|
|
82
|
+
/**
|
|
83
|
+
* Drizzle's bun-sqlite `transaction()` is synchronous: it commits as soon
|
|
84
|
+
* as the callback returns its promise, so an async callback that threw
|
|
85
|
+
* afterwards never rolled back. The transaction is opened and closed here
|
|
86
|
+
* around the awaited callback instead.
|
|
87
|
+
*/
|
|
88
|
+
private sqliteTransaction;
|
|
68
89
|
/**
|
|
69
90
|
* Liveness probe for readiness checks (e.g. web-kit's addReadinessCheck /
|
|
70
91
|
* k8s readiness). Runs a trivial `SELECT 1` against the active dialect and
|
|
71
92
|
* resolves `true` on success or `false` on any failure — it never rejects.
|
|
72
93
|
*/
|
|
73
94
|
ping(): Promise<boolean>;
|
|
95
|
+
/** `SELECT 1` on the active connection; throws on failure. */
|
|
96
|
+
private roundTrip;
|
|
74
97
|
stop(): Promise<void>;
|
|
75
98
|
}
|
|
99
|
+
declare module '@iskra-bun/core' {
|
|
100
|
+
interface AppContextRegistry {
|
|
101
|
+
db: DbDriver;
|
|
102
|
+
}
|
|
103
|
+
}
|
|
76
104
|
|
|
77
105
|
declare class ConnectionError extends IskraError {
|
|
78
106
|
constructor(message: string, options?: {
|
|
@@ -94,10 +122,20 @@ declare class MigrationError extends IskraError {
|
|
|
94
122
|
}
|
|
95
123
|
|
|
96
124
|
/**
|
|
97
|
-
*
|
|
98
|
-
*
|
|
99
|
-
*
|
|
100
|
-
*
|
|
125
|
+
* The drizzle-kit command to run `args` with, from the project's own install:
|
|
126
|
+
* `node_modules/.bin` in `cwd` or a parent (workspaces hoist it). drizzle-kit
|
|
127
|
+
* is a devDependency, and `bunx drizzle-kit` downloaded its latest release
|
|
128
|
+
* from npm where it was missing (a production install) and ran it with
|
|
129
|
+
* DATABASE_URL in its environment. `--no-install` keeps bunx from doing so.
|
|
130
|
+
*/
|
|
131
|
+
declare function drizzleKitCommand(args: string[], cwd?: string): string[];
|
|
132
|
+
/**
|
|
133
|
+
* Redacta credenciales `//user:pass@host` y parámetros secretos (`authToken`,
|
|
134
|
+
* `password`...) embebidos en texto arbitrario (p. ej. el stderr de drizzle-kit,
|
|
135
|
+
* que suele imprimir la cadena de conexión completa al fallar). A diferencia de
|
|
136
|
+
* `scrubUrl`, opera sobre texto libre y no requiere que el contenido sea una
|
|
137
|
+
* URL parseable, dejando intacto el resto del diagnóstico. Una contraseña con
|
|
138
|
+
* `@` o `/` sin codificar también se redacta: se toma hasta el último `@`.
|
|
101
139
|
*
|
|
102
140
|
* e.g. "... postgres://user:pass@host:5432/db" → "... postgres://***:***@host:5432/db"
|
|
103
141
|
*/
|
|
@@ -116,7 +154,8 @@ interface MigrationConfig {
|
|
|
116
154
|
}
|
|
117
155
|
/**
|
|
118
156
|
* Helper para ejecutar migraciones de Drizzle Kit.
|
|
119
|
-
* Usa
|
|
157
|
+
* Usa el drizzle-kit instalado en el proyecto (`bunx --no-install drizzle-kit`)
|
|
158
|
+
* como subproceso para generar y aplicar migraciones; nunca lo descarga.
|
|
120
159
|
*/
|
|
121
160
|
declare class MigrationHelper {
|
|
122
161
|
private config;
|
|
@@ -140,7 +179,8 @@ declare class MigrationHelper {
|
|
|
140
179
|
*/
|
|
141
180
|
push(): Promise<void>;
|
|
142
181
|
/**
|
|
143
|
-
* Elimina
|
|
182
|
+
* Elimina un archivo de migración ya generado (`drizzle-kit drop`, interactivo).
|
|
183
|
+
* No borra tablas ni datos de la base.
|
|
144
184
|
* `drop` acepta --out (dónde viven las migraciones) pero no --schema.
|
|
145
185
|
*/
|
|
146
186
|
drop(): Promise<void>;
|
|
@@ -161,6 +201,20 @@ interface DrizzleConfigOptions {
|
|
|
161
201
|
/** Directorio de migraciones (ej: './drizzle') */
|
|
162
202
|
migrationsDir?: string;
|
|
163
203
|
}
|
|
204
|
+
/**
|
|
205
|
+
* La configuración que lee drizzle-kit (el `export default` de `drizzle.config.ts`).
|
|
206
|
+
* Se declara aquí para no importar drizzle-kit: es una herramienta de desarrollo,
|
|
207
|
+
* y el entry point de db-kit (que usa Bun vía la condición `bun`) fallaba al
|
|
208
|
+
* importarse donde no estaba instalada, por ejemplo con `--production`.
|
|
209
|
+
*/
|
|
210
|
+
interface DrizzleKitConfig {
|
|
211
|
+
dialect: DrizzleConfigOptions['dialect'];
|
|
212
|
+
schema: string;
|
|
213
|
+
out: string;
|
|
214
|
+
dbCredentials: {
|
|
215
|
+
url: string;
|
|
216
|
+
};
|
|
217
|
+
}
|
|
164
218
|
/**
|
|
165
219
|
* Crea una configuración de drizzle-kit reutilizable.
|
|
166
220
|
*
|
|
@@ -176,6 +230,6 @@ interface DrizzleConfigOptions {
|
|
|
176
230
|
* });
|
|
177
231
|
* ```
|
|
178
232
|
*/
|
|
179
|
-
declare function createDrizzleConfig(options: DrizzleConfigOptions):
|
|
233
|
+
declare function createDrizzleConfig(options: DrizzleConfigOptions): DrizzleKitConfig;
|
|
180
234
|
|
|
181
|
-
export { ConnectionError, DbDriver, type DrizzleConfigOptions, type IskraDrizzleDb, type IskraDrizzleTx, type MigrationConfig, MigrationError, MigrationHelper, type OnQueryHook, QueryError, createDrizzleConfig, mapDialect, scrubCredentials, scrubUrl };
|
|
235
|
+
export { ConnectionError, DbDriver, type DrizzleConfigOptions, type DrizzleKitConfig, type IskraDrizzleDb, type IskraDrizzleTx, type MigrationConfig, MigrationError, MigrationHelper, type OnQueryHook, QueryError, createDrizzleConfig, drizzleKitCommand, mapDialect, scrubCredentials, scrubUrl };
|