@sharadox/database-web-library 0.0.0-stage → 0.1.0-database-backup.12

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.
Files changed (105) hide show
  1. package/LICENCA.md +76 -0
  2. package/LICENSE.md +76 -0
  3. package/NOTICE.md +3 -0
  4. package/README.md +151 -2
  5. package/distribution/backup-command/index.d.ts +21 -0
  6. package/distribution/backup-command/index.d.ts.map +1 -0
  7. package/distribution/backup-command/index.js +87 -0
  8. package/distribution/backup-command/index.js.map +1 -0
  9. package/distribution/backup-command/type.d.ts +17 -0
  10. package/distribution/backup-command/type.d.ts.map +1 -0
  11. package/distribution/backup-command/type.js +2 -0
  12. package/distribution/backup-command/type.js.map +1 -0
  13. package/distribution/backup-dump/index.d.ts +18 -0
  14. package/distribution/backup-dump/index.d.ts.map +1 -0
  15. package/distribution/backup-dump/index.js +30 -0
  16. package/distribution/backup-dump/index.js.map +1 -0
  17. package/distribution/backup-dump/type.d.ts +9 -0
  18. package/distribution/backup-dump/type.d.ts.map +1 -0
  19. package/distribution/backup-dump/type.js +2 -0
  20. package/distribution/backup-dump/type.js.map +1 -0
  21. package/distribution/backup-encryption/index.d.ts +17 -0
  22. package/distribution/backup-encryption/index.d.ts.map +1 -0
  23. package/distribution/backup-encryption/index.js +38 -0
  24. package/distribution/backup-encryption/index.js.map +1 -0
  25. package/distribution/backup-storage/index.d.ts +11 -0
  26. package/distribution/backup-storage/index.d.ts.map +1 -0
  27. package/distribution/backup-storage/index.js +27 -0
  28. package/distribution/backup-storage/index.js.map +1 -0
  29. package/distribution/backup-storage/type.d.ts +16 -0
  30. package/distribution/backup-storage/type.d.ts.map +1 -0
  31. package/distribution/backup-storage/type.js +2 -0
  32. package/distribution/backup-storage/type.js.map +1 -0
  33. package/distribution/database/index.d.ts +15 -0
  34. package/distribution/database/index.d.ts.map +1 -0
  35. package/distribution/database/index.js +17 -0
  36. package/distribution/database/index.js.map +1 -0
  37. package/distribution/database-backup/index.d.ts +20 -0
  38. package/distribution/database-backup/index.d.ts.map +1 -0
  39. package/distribution/database-backup/index.js +49 -0
  40. package/distribution/database-backup/index.js.map +1 -0
  41. package/distribution/database-backup/type.d.ts +28 -0
  42. package/distribution/database-backup/type.d.ts.map +1 -0
  43. package/distribution/database-backup/type.js +2 -0
  44. package/distribution/database-backup/type.js.map +1 -0
  45. package/distribution/database-configuration/index.d.ts +10 -0
  46. package/distribution/database-configuration/index.d.ts.map +1 -0
  47. package/distribution/database-configuration/index.js +20 -0
  48. package/distribution/database-configuration/index.js.map +1 -0
  49. package/distribution/database-configuration/type.d.ts +6 -0
  50. package/distribution/database-configuration/type.d.ts.map +1 -0
  51. package/distribution/database-configuration/type.js +2 -0
  52. package/distribution/database-configuration/type.js.map +1 -0
  53. package/distribution/es-lint-plugin/index.d.ts +29 -0
  54. package/distribution/es-lint-plugin/index.d.ts.map +1 -0
  55. package/distribution/es-lint-plugin/index.js +56 -0
  56. package/distribution/es-lint-plugin/index.js.map +1 -0
  57. package/distribution/git-hub-web-identity/index.d.ts +9 -0
  58. package/distribution/git-hub-web-identity/index.d.ts.map +1 -0
  59. package/distribution/git-hub-web-identity/index.js +18 -0
  60. package/distribution/git-hub-web-identity/index.js.map +1 -0
  61. package/distribution/memory-backup-storage/index.d.ts +12 -0
  62. package/distribution/memory-backup-storage/index.d.ts.map +1 -0
  63. package/distribution/memory-backup-storage/index.js +22 -0
  64. package/distribution/memory-backup-storage/index.js.map +1 -0
  65. package/distribution/memory-database/index.d.ts +14 -0
  66. package/distribution/memory-database/index.d.ts.map +1 -0
  67. package/distribution/memory-database/index.js +20 -0
  68. package/distribution/memory-database/index.js.map +1 -0
  69. package/distribution/memory-database/type.d.ts +9 -0
  70. package/distribution/memory-database/type.d.ts.map +1 -0
  71. package/distribution/memory-database/type.js +2 -0
  72. package/distribution/memory-database/type.js.map +1 -0
  73. package/distribution/migration/index.d.ts +13 -0
  74. package/distribution/migration/index.d.ts.map +1 -0
  75. package/distribution/migration/index.js +64 -0
  76. package/distribution/migration/index.js.map +1 -0
  77. package/distribution/migration/type.d.ts +11 -0
  78. package/distribution/migration/type.d.ts.map +1 -0
  79. package/distribution/migration/type.js +2 -0
  80. package/distribution/migration/type.js.map +1 -0
  81. package/distribution/migration-error/index.d.ts +18 -0
  82. package/distribution/migration-error/index.d.ts.map +1 -0
  83. package/distribution/migration-error/index.js +20 -0
  84. package/distribution/migration-error/index.js.map +1 -0
  85. package/distribution/migration-error/type.d.ts +7 -0
  86. package/distribution/migration-error/type.d.ts.map +1 -0
  87. package/distribution/migration-error/type.js +2 -0
  88. package/distribution/migration-error/type.js.map +1 -0
  89. package/distribution/migration-file/index.d.ts +11 -0
  90. package/distribution/migration-file/index.d.ts.map +1 -0
  91. package/distribution/migration-file/index.js +32 -0
  92. package/distribution/migration-file/index.js.map +1 -0
  93. package/distribution/pglite-pool/index.d.ts +15 -0
  94. package/distribution/pglite-pool/index.d.ts.map +1 -0
  95. package/distribution/pglite-pool/index.js +44 -0
  96. package/distribution/pglite-pool/index.js.map +1 -0
  97. package/distribution/restore-drill/index.d.ts +12 -0
  98. package/distribution/restore-drill/index.d.ts.map +1 -0
  99. package/distribution/restore-drill/index.js +35 -0
  100. package/distribution/restore-drill/index.js.map +1 -0
  101. package/distribution/restore-drill/type.d.ts +20 -0
  102. package/distribution/restore-drill/type.d.ts.map +1 -0
  103. package/distribution/restore-drill/type.js +2 -0
  104. package/distribution/restore-drill/type.js.map +1 -0
  105. package/package.json +103 -3
package/LICENCA.md ADDED
@@ -0,0 +1,76 @@
1
+ # Licença Sharadox de Código Aberto
2
+
3
+ Versão 0.1.0
4
+
5
+ O texto em língua portuguesa é o único texto original e vinculativo desta licença. A tradução para inglês (`LICENSE.md`) é meramente informativa; em caso de divergência prevalece o texto em português.
6
+
7
+ ## 1. Definições
8
+
9
+ Para efeitos desta licença:
10
+
11
+ 1. **«Obra»** — o programa de computador, a sua documentação e quaisquer outros conteúdos disponibilizados pelo Licenciante ao abrigo desta licença, em código-fonte ou em qualquer outra forma.
12
+ 2. **«Licenciante»** — o titular dos direitos de autor identificado no aviso de direitos de autor que acompanha a Obra.
13
+ 3. **«Licenciado»** — qualquer pessoa, singular ou coletiva, que exerça os direitos concedidos por esta licença.
14
+ 4. **«Obra Derivada»** — qualquer obra baseada na Obra ou que a incorpore, total ou parcialmente, com ou sem modificações, incluindo traduções, adaptações e programas que a integrem.
15
+ 5. **«Aviso»** — o aviso de direitos de autor do Licenciante e a indicação de que a Obra está licenciada ao abrigo desta licença, incluindo a respetiva versão.
16
+
17
+ ## 2. Concessão de direitos
18
+
19
+ 1. Nos termos desta licença, o Licenciante concede ao Licenciado uma licença mundial, gratuita, não exclusiva e por todo o prazo de proteção dos direitos de autor para:
20
+ 1. utilizar a Obra para qualquer finalidade, incluindo finalidades comerciais;
21
+ 2. reproduzir a Obra, total ou parcialmente, por qualquer meio e sob qualquer forma;
22
+ 3. modificar, traduzir, adaptar e transformar a Obra e criar Obras Derivadas;
23
+ 4. distribuir, publicar, comunicar ao público, colocar à disposição, vender e sublicenciar a Obra e as Obras Derivadas.
24
+ 2. Na medida em que o Licenciante seja titular de patentes necessariamente infringidas pela Obra tal como por si disponibilizada, concede igualmente ao Licenciado, nos mesmos termos, uma licença para utilizar essas patentes no exercício dos direitos previstos no número anterior.
25
+ 3. Esta licença não transmite a titularidade de quaisquer direitos, que permanecem do Licenciante.
26
+
27
+ ## 3. Condições
28
+
29
+ O exercício dos direitos concedidos fica sujeito às seguintes condições:
30
+
31
+ 1. Todas as cópias da Obra, ou de partes substanciais da mesma, e todas as Obras Derivadas distribuídas devem incluir o Aviso e uma cópia desta licença ou uma ligação estável para o seu texto.
32
+ 2. Quem distribuir uma versão modificada da Obra deve indicar de forma visível que a mesma foi modificada, não podendo apresentá-la como versão original do Licenciante.
33
+ 3. O Licenciado pode licenciar as suas próprias modificações ao abrigo de outros termos, desde que a parte da Obra que delas faça parte continue sujeita às condições desta licença.
34
+
35
+ ## 4. Nomes e marcas
36
+
37
+ Esta licença não concede qualquer direito sobre o nome, as marcas, os logótipos ou outros sinais distintivos do Licenciante, incluindo a designação «Sharadox», salvo na medida estritamente necessária para cumprir o dever de incluir o Aviso. É proibido utilizá-los para promover ou sugerir o apoio do Licenciante a Obras Derivadas ou a quaisquer produtos ou serviços sem autorização prévia e escrita.
38
+
39
+ ## 5. Exclusão de garantias
40
+
41
+ A Obra é disponibilizada «tal como está» e «conforme disponível», sem qualquer garantia, expressa ou tácita, incluindo, designadamente, garantias de comerciabilidade, de adequação a um fim específico, de ausência de erros ou de não violação de direitos de terceiros, na medida máxima permitida pela lei aplicável.
42
+
43
+ ## 6. Limitação de responsabilidade
44
+
45
+ 1. Na medida máxima permitida pela lei aplicável, o Licenciante não é responsável por quaisquer danos, diretos ou indiretos, incluindo lucros cessantes, perda de dados ou interrupção de atividade, resultantes da utilização ou da impossibilidade de utilização da Obra, ainda que tenha sido avisado da possibilidade da sua ocorrência.
46
+ 2. Nada nesta licença exclui ou limita a responsabilidade do Licenciante nos casos em que tal exclusão ou limitação não seja permitida por lei, designadamente por atos praticados com dolo ou culpa grave, nos termos do artigo 809.º e do n.º 2 do artigo 800.º do Código Civil, nem afeta os direitos que a lei imperativamente reconheça aos consumidores.
47
+
48
+ ## 7. Cessação
49
+
50
+ 1. Os direitos concedidos por esta licença cessam automaticamente se o Licenciado violar qualquer das suas condições.
51
+ 2. Os direitos são repostos se a violação for sanada no prazo de 30 dias a contar do momento em que o Licenciado dela tome conhecimento, salvo se o Licenciante tiver entretanto comunicado por escrito a sua oposição.
52
+ 3. A cessação não afeta as licenças validamente concedidas pelo Licenciado a terceiros que cumpram esta licença.
53
+
54
+ ## 8. Lei aplicável e foro
55
+
56
+ 1. Esta licença rege-se pela lei portuguesa, designadamente pelo Código do Direito de Autor e dos Direitos Conexos, aprovado pelo Decreto-Lei n.º 63/85, de 14 de março, e pelo Decreto-Lei n.º 252/94, de 20 de outubro, relativo à proteção jurídica dos programas de computador.
57
+ 2. Para a resolução de quaisquer litígios emergentes desta licença é competente o Tribunal Judicial da Comarca de Faro, sem prejuízo das normas imperativas de competência aplicáveis, nomeadamente as que protegem os consumidores.
58
+
59
+ ## 9. Versões da licença
60
+
61
+ O Licenciante pode publicar novas versões desta licença, identificadas por um número de versão. A Obra fica sujeita à versão indicada no Aviso. O Licenciado pode, se o Aviso o permitir, optar por qualquer versão posterior.
62
+
63
+ ## 10. Disposições finais
64
+
65
+ 1. Se alguma disposição desta licença for considerada inválida ou ineficaz, as restantes mantêm-se em vigor, devendo a disposição afetada ser interpretada de forma a aproximar-se, tanto quanto possível, da intenção original.
66
+ 2. A não exigência, em qualquer momento, do cumprimento de uma disposição desta licença não constitui renúncia ao direito de o exigir posteriormente.
67
+
68
+ ## Como aplicar esta licença
69
+
70
+ Inclua na Obra um ficheiro `LICENCA.md` com este texto, a tradução `LICENSE.md` e o seguinte aviso, preenchendo o ano e o titular:
71
+
72
+ ```
73
+ Direitos de autor © <ano> <titular>.
74
+ Licenciado ao abrigo da Licença Sharadox de Código Aberto, versão 0.1.0.
75
+ https://github.com/Sharadox/sharadox-open-source-license
76
+ ```
package/LICENSE.md ADDED
@@ -0,0 +1,76 @@
1
+ # Sharadox Open Source Licence
2
+
3
+ Version 0.1.0
4
+
5
+ This is an informative English translation. The Portuguese text (`LICENCA.md`) is the only original and binding text of this licence; if the two differ, the Portuguese text prevails.
6
+
7
+ ## 1. Definitions
8
+
9
+ For the purposes of this licence:
10
+
11
+ 1. **"Work"** — the computer program, its documentation and any other content made available by the Licensor under this licence, in source code or in any other form.
12
+ 2. **"Licensor"** — the copyright holder identified in the copyright notice that accompanies the Work.
13
+ 3. **"Licensee"** — any natural or legal person exercising the rights granted by this licence.
14
+ 4. **"Derivative Work"** — any work based on or incorporating the Work, in whole or in part, with or without modifications, including translations, adaptations and programs that integrate it.
15
+ 5. **"Notice"** — the Licensor's copyright notice and the statement that the Work is licensed under this licence, including its version.
16
+
17
+ ## 2. Grant of rights
18
+
19
+ 1. Under this licence, the Licensor grants the Licensee a worldwide, royalty-free, non-exclusive licence, for the whole term of copyright protection, to:
20
+ 1. use the Work for any purpose, including commercial purposes;
21
+ 2. reproduce the Work, in whole or in part, by any means and in any form;
22
+ 3. modify, translate, adapt and transform the Work and create Derivative Works;
23
+ 4. distribute, publish, communicate to the public, make available, sell and sublicense the Work and Derivative Works.
24
+ 2. To the extent the Licensor holds patents necessarily infringed by the Work as made available by it, the Licensor also grants the Licensee, on the same terms, a licence to use those patents in exercising the rights in the previous paragraph.
25
+ 3. This licence does not transfer ownership of any rights, which remain with the Licensor.
26
+
27
+ ## 3. Conditions
28
+
29
+ The exercise of the rights granted is subject to the following conditions:
30
+
31
+ 1. Every copy of the Work, or of substantial parts of it, and every distributed Derivative Work must include the Notice and a copy of this licence or a stable link to its text.
32
+ 2. Anyone distributing a modified version of the Work must state visibly that it has been modified and may not present it as the Licensor's original version.
33
+ 3. The Licensee may license their own modifications under other terms, provided the part of the Work included in them remains subject to the conditions of this licence.
34
+
35
+ ## 4. Names and trademarks
36
+
37
+ This licence grants no rights to the Licensor's name, trademarks, logos or other distinctive signs, including the name "Sharadox", except as strictly necessary to comply with the duty to include the Notice. Using them to promote or suggest the Licensor's endorsement of Derivative Works or of any products or services without prior written permission is prohibited.
38
+
39
+ ## 5. Disclaimer of warranties
40
+
41
+ The Work is provided "as is" and "as available", without any warranty, express or implied, including in particular warranties of merchantability, fitness for a particular purpose, absence of errors or non-infringement of third-party rights, to the maximum extent permitted by applicable law.
42
+
43
+ ## 6. Limitation of liability
44
+
45
+ 1. To the maximum extent permitted by applicable law, the Licensor is not liable for any damages, direct or indirect, including loss of profits, loss of data or business interruption, arising from the use of or inability to use the Work, even if advised of the possibility of such damages.
46
+ 2. Nothing in this licence excludes or limits the Licensor's liability where such exclusion or limitation is not permitted by law, in particular for acts committed with intent or gross negligence, under article 809 and article 800(2) of the Portuguese Civil Code, nor does it affect rights that the law mandatorily grants to consumers.
47
+
48
+ ## 7. Termination
49
+
50
+ 1. The rights granted by this licence terminate automatically if the Licensee breaches any of its conditions.
51
+ 2. The rights are reinstated if the breach is remedied within 30 days of the Licensee becoming aware of it, unless the Licensor has meanwhile objected in writing.
52
+ 3. Termination does not affect licences validly granted by the Licensee to third parties who comply with this licence.
53
+
54
+ ## 8. Governing law and jurisdiction
55
+
56
+ 1. This licence is governed by Portuguese law, in particular the Code of Copyright and Related Rights, approved by Decree-Law no. 63/85 of 14 March, and Decree-Law no. 252/94 of 20 October on the legal protection of computer programs.
57
+ 2. The Judicial Court of the District of Faro has jurisdiction over any dispute arising from this licence, without prejudice to applicable mandatory rules of jurisdiction, in particular those protecting consumers.
58
+
59
+ ## 9. Licence versions
60
+
61
+ The Licensor may publish new versions of this licence, identified by a version number. The Work is subject to the version stated in the Notice. If the Notice allows it, the Licensee may choose any later version.
62
+
63
+ ## 10. Final provisions
64
+
65
+ 1. If any provision of this licence is held invalid or unenforceable, the remaining provisions stay in force, and the affected provision shall be interpreted as closely as possible to its original intent.
66
+ 2. Failure to enforce any provision of this licence at any time does not waive the right to enforce it later.
67
+
68
+ ## How to apply this licence
69
+
70
+ Include in the Work a `LICENCA.md` file with the Portuguese text, this translation as `LICENSE.md`, and the following notice, filling in the year and holder:
71
+
72
+ ```
73
+ Direitos de autor © <ano> <titular>.
74
+ Licenciado ao abrigo da Licença Sharadox de Código Aberto, versão 0.1.0.
75
+ https://github.com/Sharadox/sharadox-open-source-license
76
+ ```
package/NOTICE.md ADDED
@@ -0,0 +1,3 @@
1
+ Direitos de autor © 2026 Micael Pires (Sharadox).
2
+ Licenciado ao abrigo da Licença Sharadox de Código Aberto, versão 0.1.0.
3
+ https://github.com/Sharadox/sharadox-open-source-license
package/README.md CHANGED
@@ -1,3 +1,152 @@
1
- # Temporary Holding Version
1
+ # @sharadox/database-web-library
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Typed, injection-safe Postgres for web applications: [Kysely](https://kysely.dev) queries over a
4
+ [Neon](https://neon.tech) pool, forward-only SQL migrations, a Postgres in memory for tests, and a lint rule that keeps
5
+ values out of SQL text.
6
+
7
+ - **Typed:** queries are checked against the schema's TypeScript types.
8
+ - **No SQL injection by construction:** values always travel as bound parameters. The `no-raw-sql` ESLint rule
9
+ reports the few calls that could send unchecked text (`sql.raw`, `sql.lit`, `.unsafe()`, SQL built with `+` or
10
+ `${…}`).
11
+ - **Migrations:** plain `.sql` files, run forward only, all or none, behind a lock, refused when an applied one was
12
+ edited, removed or overtaken.
13
+ - **Tests without a server:** `createMemoryDatabase()` is a real Postgres 18 in memory (PGlite).
14
+
15
+ ## Install
16
+
17
+ ```sh
18
+ pnpm add @sharadox/database-web-library
19
+ pnpm add -D @electric-sql/pglite # for createMemoryDatabase in tests
20
+ ```
21
+
22
+ ## Configuration
23
+
24
+ | Variable | Meaning |
25
+ | -------------- | ------------------------------------------------------------------------------------------- |
26
+ | `DATABASE_URL` | `postgresql://…` address (set by Vercel's Neon integration). A secret: it holds a password. |
27
+
28
+ ## API
29
+
30
+ Each export has its own entry point (`@sharadox/database-web-library/<name>`).
31
+
32
+ ### `database`: `createDatabase<Schema>({ connectionString })` → `Kysely<Schema>`
33
+
34
+ The production database over a Neon pool. Nothing connects until the first query.
35
+
36
+ ```ts
37
+ import { createDatabase } from "@sharadox/database-web-library/database";
38
+ import { readDatabaseConfiguration } from "@sharadox/database-web-library/database-configuration";
39
+
40
+ const database = createDatabase<Schema>(readDatabaseConfiguration());
41
+ const account = await database.selectFrom("account").selectAll().where("id", "=", id).executeTakeFirst();
42
+ ```
43
+
44
+ ### `database-configuration`: `readDatabaseConfiguration(environment = process.env)` → `{ connectionString }`
45
+
46
+ Reads `DATABASE_URL`, which must start with `postgres://` or `postgresql://`. The error names the variable, never its
47
+ value.
48
+
49
+ ### `migration`: `migrate(database, migrations, { table = "schema_migration" })` → names applied
50
+
51
+ Applies, in order and in one transaction, the migrations not applied yet. Each is recorded with a SHA-256 of its
52
+ SQL, under a UUIDv7 `id` like every other row (a record table made before ids gets one). Throws `MigrationError` with one of these codes:
53
+
54
+ - `changed`: an applied migration was edited;
55
+ - `missing`: an applied migration was removed;
56
+ - `out-of-order`: a new migration is numbered before one already applied;
57
+ - `invalid-name`: the record table's name isn't plain.
58
+
59
+ ### `migration-file`: `readMigrations(folder: URL | string)` → `Migration[]`
60
+
61
+ Reads `<four digits>-<kebab-case>.sql` files in number order and ignores other files. A badly named `.sql` file is
62
+ refused with `invalid-name`, a repeated number with `duplicate`.
63
+
64
+ ```ts
65
+ import { migrate } from "@sharadox/database-web-library/migration";
66
+ import { readMigrations } from "@sharadox/database-web-library/migration-file";
67
+
68
+ await migrate(database, await readMigrations(new URL("../../migration/", import.meta.url)));
69
+ ```
70
+
71
+ ### `migration-error`: `MigrationError`
72
+
73
+ `{ name: "MigrationError", code, message }`, with `code` one of `invalid-name`, `duplicate`, `changed`, `missing` or
74
+ `out-of-order`.
75
+
76
+ ### `memory-database`: `createMemoryDatabase<Schema>()` → `{ database, close }`
77
+
78
+ A fresh, empty Postgres 18 in memory, behind the same Kysely, for unit tests. It needs `@electric-sql/pglite`.
79
+
80
+ ```ts
81
+ const { database, close } = await createMemoryDatabase<Schema>();
82
+ await migrate(database, await readMigrations(new URL("../migration/", import.meta.url)));
83
+ // … test …
84
+ await close();
85
+ ```
86
+
87
+ ### `pglite-pool`: `pglitePool(pglite)` → Kysely `PostgresPool`
88
+
89
+ The adapter `createMemoryDatabase` uses. It hands out one connection at a time, and a query without parameters may
90
+ hold several statements.
91
+
92
+ ### `es-lint-plugin`: `databaseEsLintPlugin`, `noRawSql`
93
+
94
+ ```js
95
+ // eslint.config.mjs
96
+ import { nodeConfiguration } from "@sharadox/es-lint-configuration-web-library/node";
97
+ import { databaseEsLintPlugin } from "@sharadox/database-web-library/es-lint-plugin";
98
+
99
+ export default [...nodeConfiguration(), ...databaseEsLintPlugin.configs.recommended];
100
+ ```
101
+
102
+ Rule `@sharadox/database/no-raw-sql` reports:
103
+
104
+ - `sql.raw()`, `sql.lit()`, `CompiledQuery.raw()` and any `.unsafe()`;
105
+ - a `.query()` whose SQL is built with `+` or a template with `${…}`.
106
+
107
+ Kysely's tagged ``sql`…${value}…` `` is allowed: its values are parameters.
108
+
109
+ ## Ids
110
+
111
+ Use UUIDv7 ids, in a `uuid` column guarded by a check:
112
+
113
+ ```sql
114
+ create table account (
115
+ id uuid primary key default uuidv7() check (uuid_extract_version(id) = 7)
116
+ );
117
+ ```
118
+
119
+ Generate them in code with `uuidVersion7` from `@sharadox/web-library` when the id is needed before the insert.
120
+
121
+ ## Backups and restore drills
122
+
123
+ A daily, encrypted copy of the production database in an S3 bucket nobody can empty, and a monthly proof that it
124
+ restores. The pieces, usable on their own:
125
+
126
+ - `dumpDatabase(url, { program?, run? })` (`backup-dump`): `pg_dump` of the public schema as plain INSERTs, without
127
+ owners or grants (needs `pg_dump` of the server's major version or later). The address goes in `PGDATABASE`, never
128
+ on the command line. `restorableSql(dump)` drops psql's own commands (`\restrict`) so any Postgres can replay it.
129
+ - `encryptBackup(bytes, key)`, `decryptBackup(bytes, key)` (`backup-encryption`): AES-256-GCM under
130
+ `BACKUP_ENCRYPTION_KEY` (at least 32 characters, kept apart from the backups); any change is detected.
131
+ - `backupDatabase({ dump, counts, storage, key, now? })` (`database-backup`): gzip, encrypt, store
132
+ `YYYY/MM/DD/<time>.sql.gz.enc` and its manifest `<time>.json` (time, size, SHA-256, rows per table).
133
+ `tableCounts(database)` gives the rows per table.
134
+ - `restoreDrill({ storage, key, into })` (`restore-drill`): the newest backup, checked against its SHA-256,
135
+ decrypted, replayed into an empty database (`createMemoryDatabase()`), and every table's rows compared with the
136
+ manifest → `{ ok, createdAt, tables: [{ table, expected, restored }] }`.
137
+ - `createBackupStorage({ bucket, region, prefix, credentials })` (`backup-storage`): S3, write, read and list only;
138
+ the bucket's Object Lock (compliance mode, 35 days) keeps every file unchangeable. `createMemoryBackupStorage()`
139
+ for tests.
140
+ - `gitHubWebIdentityToken()` (`git-hub-web-identity`): the GitHub Actions job's identity token for AWS, so the job
141
+ takes an IAM role with no stored key (the job needs `permissions: { id-token: write }`).
142
+ - `runBackupCommand("backup" | "drill")` (`backup-command`): what a site's workflow runs, reading `BACKUP_BUCKET`,
143
+ `BACKUP_REGION`, `BACKUP_PREFIX`, `BACKUP_ROLE`, `BACKUP_ENCRYPTION_KEY` and, for a backup,
144
+ `DATABASE_BACKUP_URL` (a read-only role). It returns the exit code:
145
+
146
+ ```sh
147
+ node -e 'import("@sharadox/database-web-library/backup-command").then(async (m) => process.exit(await m.runBackupCommand("backup")))'
148
+ ```
149
+
150
+ ## License
151
+
152
+ Sharadox Open Source License 0.1.0 (see `LICENSE.md`).
@@ -0,0 +1,21 @@
1
+ import type { BackupParts } from "@sharadox/database-web-library/backup-command/type";
2
+ /**
3
+ * Short-lived AWS credentials for `role`, taken with the GitHub Actions job's own identity (no stored key).
4
+ *
5
+ * @example
6
+ * createBackupStorage({ bucket, region, prefix, credentials: gitHubRoleCredentials(role) });
7
+ */
8
+ export declare function gitHubRoleCredentials(role: string, environment?: Record<string, string | undefined>): () => Promise<import("@smithy/types").AwsCredentialIdentity>;
9
+ /** In a GitHub Actions job: S3 through the job's own identity (no stored key), Neon, and `pg_dump`. */
10
+ export declare const defaultBackupParts: BackupParts;
11
+ /**
12
+ * What a site's backup workflow runs: `backup` (the production database, dumped, encrypted and stored) or `drill`
13
+ * (the newest backup restored into Postgres in memory and checked). Settings: `BACKUP_BUCKET`, `BACKUP_REGION`,
14
+ * `BACKUP_PREFIX`, `BACKUP_ROLE` (the IAM role the job's GitHub identity takes), `BACKUP_ENCRYPTION_KEY`, and for a
15
+ * backup `DATABASE_BACKUP_URL` (a read-only role). Returns the exit code.
16
+ *
17
+ * @example
18
+ * // node -e 'import("@sharadox/database-web-library/backup-command").then(async (m) => process.exit(await m.runBackupCommand("backup")))'
19
+ */
20
+ export declare function runBackupCommand(command: string, environment?: Record<string, string | undefined>, parts?: Partial<BackupParts>): Promise<number>;
21
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../source/backup-command/index.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,oDAAoD,CAAC;AAQtF;;;;;GAKG;AACH,wBAAgB,qBAAqB,CAAC,IAAI,EAAE,MAAM,EAAE,WAAW,GAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAe,gEAOhH;AAED,uGAAuG;AACvG,eAAO,MAAM,kBAAkB,EAAE,WAOhC,CAAC;AAQF;;;;;;;;GAQG;AACH,wBAAsB,gBAAgB,CACpC,OAAO,EAAE,MAAM,EACf,WAAW,GAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAe,EAC7D,KAAK,GAAE,OAAO,CAAC,WAAW,CAAM,GAC/B,OAAO,CAAC,MAAM,CAAC,CAwCjB"}
@@ -0,0 +1,87 @@
1
+ import { fromWebToken } from "@aws-sdk/credential-providers";
2
+ import { dumpDatabase } from "@sharadox/database-web-library/backup-dump";
3
+ import { createBackupStorage } from "@sharadox/database-web-library/backup-storage";
4
+ import { createDatabase } from "@sharadox/database-web-library/database";
5
+ import { backupDatabase, tableCounts } from "@sharadox/database-web-library/database-backup";
6
+ import { gitHubWebIdentityToken } from "@sharadox/database-web-library/git-hub-web-identity";
7
+ import { createMemoryDatabase } from "@sharadox/database-web-library/memory-database";
8
+ import { restoreDrill } from "@sharadox/database-web-library/restore-drill";
9
+ /**
10
+ * Short-lived AWS credentials for `role`, taken with the GitHub Actions job's own identity (no stored key).
11
+ *
12
+ * @example
13
+ * createBackupStorage({ bucket, region, prefix, credentials: gitHubRoleCredentials(role) });
14
+ */
15
+ export function gitHubRoleCredentials(role, environment = process.env) {
16
+ return async () => fromWebToken({
17
+ roleArn: role,
18
+ webIdentityToken: await gitHubWebIdentityToken(environment),
19
+ roleSessionName: "backup",
20
+ })();
21
+ }
22
+ /** In a GitHub Actions job: S3 through the job's own identity (no stored key), Neon, and `pg_dump`. */
23
+ export const defaultBackupParts = {
24
+ storage: ({ bucket, region, prefix, role }) => createBackupStorage({ bucket, region, prefix, credentials: gitHubRoleCredentials(role) }),
25
+ database: (url) => createDatabase({ connectionString: url }),
26
+ dump: dumpDatabase,
27
+ memory: createMemoryDatabase,
28
+ log: (line) => console.log(line),
29
+ };
30
+ const required = (environment, name) => {
31
+ const value = environment[name];
32
+ if (!value)
33
+ throw new Error(`${name} is missing`);
34
+ return value;
35
+ };
36
+ /**
37
+ * What a site's backup workflow runs: `backup` (the production database, dumped, encrypted and stored) or `drill`
38
+ * (the newest backup restored into Postgres in memory and checked). Settings: `BACKUP_BUCKET`, `BACKUP_REGION`,
39
+ * `BACKUP_PREFIX`, `BACKUP_ROLE` (the IAM role the job's GitHub identity takes), `BACKUP_ENCRYPTION_KEY`, and for a
40
+ * backup `DATABASE_BACKUP_URL` (a read-only role). Returns the exit code.
41
+ *
42
+ * @example
43
+ * // node -e 'import("@sharadox/database-web-library/backup-command").then(async (m) => process.exit(await m.runBackupCommand("backup")))'
44
+ */
45
+ export async function runBackupCommand(command, environment = process.env, parts = {}) {
46
+ if (command !== "backup" && command !== "drill")
47
+ throw new Error(`"${command}": the command is backup or drill`);
48
+ const { storage, database, dump, memory, log } = { ...defaultBackupParts, ...parts };
49
+ const store = storage({
50
+ bucket: required(environment, "BACKUP_BUCKET"),
51
+ region: required(environment, "BACKUP_REGION"),
52
+ prefix: required(environment, "BACKUP_PREFIX"),
53
+ role: required(environment, "BACKUP_ROLE"),
54
+ });
55
+ const key = required(environment, "BACKUP_ENCRYPTION_KEY");
56
+ if (command === "backup") {
57
+ const url = required(environment, "DATABASE_BACKUP_URL");
58
+ const source = database(url);
59
+ try {
60
+ const result = await backupDatabase({
61
+ dump: () => dump(url),
62
+ counts: () => tableCounts(source),
63
+ storage: store,
64
+ key,
65
+ });
66
+ const rows = Object.entries(result.tables).map(([table, count]) => `${table} ${count}`);
67
+ log(`backed up ${result.file}: ${rows.join(", ")}`);
68
+ return 0;
69
+ }
70
+ finally {
71
+ await source.destroy();
72
+ }
73
+ }
74
+ const into = await memory();
75
+ try {
76
+ const result = await restoreDrill({ storage: store, key, into: into.database });
77
+ const wrong = result.tables.filter(({ expected, restored }) => expected !== restored);
78
+ log(result.ok
79
+ ? `restore drill passed: the backup of ${result.createdAt}, ${result.tables.length} tables`
80
+ : `restore drill FAILED: ${wrong.map(({ table, expected, restored }) => `${table} ${restored} of ${expected}`).join(", ")}`);
81
+ return result.ok ? 0 : 1;
82
+ }
83
+ finally {
84
+ await into.close();
85
+ }
86
+ }
87
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../source/backup-command/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,+BAA+B,CAAC;AAC7D,OAAO,EAAE,YAAY,EAAE,MAAM,4CAA4C,CAAC;AAE1E,OAAO,EAAE,mBAAmB,EAAE,MAAM,+CAA+C,CAAC;AACpF,OAAO,EAAE,cAAc,EAAE,MAAM,yCAAyC,CAAC;AACzE,OAAO,EAAE,cAAc,EAAE,WAAW,EAAE,MAAM,gDAAgD,CAAC;AAC7F,OAAO,EAAE,sBAAsB,EAAE,MAAM,qDAAqD,CAAC;AAC7F,OAAO,EAAE,oBAAoB,EAAE,MAAM,gDAAgD,CAAC;AACtF,OAAO,EAAE,YAAY,EAAE,MAAM,8CAA8C,CAAC;AAE5E;;;;;GAKG;AACH,MAAM,UAAU,qBAAqB,CAAC,IAAY,EAAE,cAAkD,OAAO,CAAC,GAAG;IAC/G,OAAO,KAAK,IAAI,EAAE,CAChB,YAAY,CAAC;QACX,OAAO,EAAE,IAAI;QACb,gBAAgB,EAAE,MAAM,sBAAsB,CAAC,WAAW,CAAC;QAC3D,eAAe,EAAE,QAAQ;KAC1B,CAAC,EAAE,CAAC;AACT,CAAC;AAED,uGAAuG;AACvG,MAAM,CAAC,M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,GAAG,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,EAAE,EAAE,CAAC,QAAQ,KAAK,QAAQ,CAAC,CAAC;QACtF,GAAG,CACD,MAAM,CAAC,EAAE;YACP,CAAC,CAAC,uCAAuC,MAAM,CAAC,SAAS,KAAK,MAAM,CAAC,MAAM,CAAC,MAAM,SAAS;YAC3F,CAAC,CAAC,yBAAyB,KAAK,CAAC,GAAG,CAAC,CAAC,EAAE,KAAK,EAAE,QAAQ,EAAE,QAAQ,EAAE,EAAE,EAAE,CAAC,GAAG,KAAK,IAAI,QAAQ,OAAO,QAAQ,EAAE,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAC9H,CAAC;QACF,OAAO,MAAM,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IAC3B,CAAC;YAAS,CAAC;QACT,MAAM,IAAI,CAAC,KAAK,EAAE,CAAC;IACrB,CAAC;AACH,CAAC"}
@@ -0,0 +1,17 @@
1
+ import type { Kysely } from "kysely";
2
+ import type { BackupStorage } from "@sharadox/database-web-library/backup-storage/type";
3
+ import type { MemoryDatabase } from "@sharadox/database-web-library/memory-database/type";
4
+ /** Where a backup command's pieces come from (tests give their own). */
5
+ export interface BackupParts {
6
+ storage: (options: {
7
+ bucket: string;
8
+ region: string;
9
+ prefix: string;
10
+ role: string;
11
+ }) => BackupStorage;
12
+ database: (url: string) => Kysely<unknown>;
13
+ dump: (url: string) => Promise<Uint8Array>;
14
+ memory: () => Promise<MemoryDatabase<unknown>>;
15
+ log: (line: string) => void;
16
+ }
17
+ //# sourceMappingURL=type.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"type.d.ts","sourceRoot":"","sources":["../../source/backup-command/type.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AACrC,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,oDAAoD,CAAC;AACxF,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,qDAAqD,CAAC;AAE1F,wEAAwE;AACxE,MAAM,WAAW,WAAW;IAC1B,OAAO,EAAE,CAAC,OAAO,EAAE;QAAE,MAAM,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,MAAM,CAAC;QAAC,IAAI,EAAE,MAAM,CAAA;KAAE,KAAK,aAAa,CAAC;IACtG,QAAQ,EAAE,CAAC,GAAG,EAAE,MAAM,KAAK,MAAM,CAAC,OAAO,CAAC,CAAC;IAC3C,IAAI,EAAE,CAAC,GAAG,EAAE,MAAM,KAAK,OAAO,CAAC,UAAU,CAAC,CAAC;IAC3C,MAAM,EAAE,MAAM,OAAO,CAAC,cAAc,CAAC,OAAO,CAAC,CAAC,CAAC;IAC/C,GAAG,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,CAAC;CAC7B"}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=type.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"type.js","sourceRoot":"","sources":["../../source/backup-command/type.ts"],"names":[],"mappings":""}
@@ -0,0 +1,18 @@
1
+ import type { DumpOptions } from "@sharadox/database-web-library/backup-dump/type";
2
+ /**
3
+ * A plain SQL dump of the database's public schema, made by `pg_dump`: one INSERT per row (so any Postgres, PGlite
4
+ * included, can replay it), without owners or grants. The address goes in the environment (`PGDATABASE`), never on
5
+ * the command line, so the password isn't visible in the process list.
6
+ *
7
+ * @example
8
+ * const sql = await dumpDatabase(process.env.DATABASE_BACKUP_URL!);
9
+ */
10
+ export declare function dumpDatabase(databaseUrl: string, { program, run }?: DumpOptions): Promise<Uint8Array>;
11
+ /**
12
+ * A dump without psql's own commands (`\restrict`, `\unrestrict`, which pg_dump 18 adds), so it runs as plain SQL.
13
+ *
14
+ * @example
15
+ * await sql.raw(restorableSql(text)).execute(database);
16
+ */
17
+ export declare function restorableSql(dump: string): string;
18
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../source/backup-dump/index.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,WAAW,EAAiB,MAAM,iDAAiD,CAAC;AAalG;;;;;;;GAOG;AACH,wBAAsB,YAAY,CAChC,WAAW,EAAE,MAAM,EACnB,EAAE,OAAmB,EAAE,GAAgB,EAAE,GAAE,WAAgB,GAC1D,OAAO,CAAC,UAAU,CAAC,CAIrB;AAED;;;;;GAKG;AACH,wBAAgB,aAAa,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAKlD"}
@@ -0,0 +1,30 @@
1
+ import { execFile } from "node:child_process";
2
+ const runProgram = (program, parameters, environment) => new Promise((resolve, reject) => {
3
+ execFile(program, parameters, { env: { ...process.env, ...environment }, encoding: "buffer", maxBuffer: 1024 * 1024 * 1024 }, (error, output) => error ? reject(new Error(`${program} failed: ${error.message}`)) : resolve(new Uint8Array(output)));
4
+ });
5
+ /**
6
+ * A plain SQL dump of the database's public schema, made by `pg_dump`: one INSERT per row (so any Postgres, PGlite
7
+ * included, can replay it), without owners or grants. The address goes in the environment (`PGDATABASE`), never on
8
+ * the command line, so the password isn't visible in the process list.
9
+ *
10
+ * @example
11
+ * const sql = await dumpDatabase(process.env.DATABASE_BACKUP_URL!);
12
+ */
13
+ export async function dumpDatabase(databaseUrl, { program = "pg_dump", run = runProgram } = {}) {
14
+ return run(program, ["--schema=public", "--inserts", "--no-owner", "--no-privileges", "--quote-all-identifiers"], {
15
+ PGDATABASE: databaseUrl,
16
+ });
17
+ }
18
+ /**
19
+ * A dump without psql's own commands (`\restrict`, `\unrestrict`, which pg_dump 18 adds), so it runs as plain SQL.
20
+ *
21
+ * @example
22
+ * await sql.raw(restorableSql(text)).execute(database);
23
+ */
24
+ export function restorableSql(dump) {
25
+ return dump
26
+ .split("\n")
27
+ .filter((line) => !line.startsWith("\\"))
28
+ .join("\n");
29
+ }
30
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../source/backup-dump/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,oBAAoB,CAAC;AAG9C,MAAM,UAAU,GAAkB,CAAC,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,EAAE,CACrE,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;IAC9B,QAAQ,CACN,OAAO,EACP,UAAU,EACV,EAAE,GAAG,EAAE,EAAE,GAAG,OAAO,CAAC,GAAG,EAAE,GAAG,WAAW,EAAE,EAAE,QAAQ,EAAE,QAAQ,EAAE,SAAS,EAAE,IAAI,GAAG,IAAI,GAAG,IAAI,EAAE,EAC9F,CAAC,KAAK,EAAE,MAAM,EAAE,EAAE,CAChB,KAAK,CAAC,CAAC,CAAC,MAAM,CAAC,IAAI,KAAK,CAAC,GAAG,OAAO,YAAY,KAAK,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,IAAI,UAAU,CAAC,MAAM,CAAC,CAAC,CACrG,CAAC;AACJ,CAAC,CAAC,CAAC;AAEL;;;;;;;GAOG;AACH,MAAM,CAAC,KAAK,UAAU,YAAY,CAChC,WAAmB,EACnB,EAAE,OAAO,GAAG,SAAS,EAAE,GAAG,GAAG,UAAU,KAAkB,EAAE;IAE3D,OAAO,GAAG,CAAC,OAAO,EAAE,CAAC,iBAAiB,EAAE,WAAW,EAAE,YAAY,EAAE,iBAAiB,EAAE,yBAAyB,CAAC,EAAE;QAChH,UAAU,EAAE,WAAW;KACxB,CAAC,CAAC;AACL,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,aAAa,CAAC,IAAY;IACxC,OAAO,IAAI;SACR,KAAK,CAAC,IAAI,CAAC;SACX,MAAM,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC;SACxC,IAAI,CAAC,IAAI,CAAC,CAAC;AAChB,CAAC"}
@@ -0,0 +1,9 @@
1
+ /** Runs a program with arguments and extra environment variables; resolves with what it printed. */
2
+ export type ProgramRunner = (program: string, parameters: string[], environment: Record<string, string | undefined>) => Promise<Uint8Array>;
3
+ export interface DumpOptions {
4
+ /** `pg_dump` by default (its major version must be the server's or later). */
5
+ program?: string;
6
+ /** How to run it (tests give their own). */
7
+ run?: ProgramRunner;
8
+ }
9
+ //# sourceMappingURL=type.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"type.d.ts","sourceRoot":"","sources":["../../source/backup-dump/type.ts"],"names":[],"mappings":"AAAA,oGAAoG;AACpG,MAAM,MAAM,aAAa,GAAG,CAC1B,OAAO,EAAE,MAAM,EACf,UAAU,EAAE,MAAM,EAAE,EACpB,WAAW,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC,KAC5C,OAAO,CAAC,UAAU,CAAC,CAAC;AAEzB,MAAM,WAAW,WAAW;IAC1B,8EAA8E;IAC9E,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,4CAA4C;IAC5C,GAAG,CAAC,EAAE,aAAa,CAAC;CACrB"}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=type.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"type.js","sourceRoot":"","sources":["../../source/backup-dump/type.ts"],"names":[],"mappings":""}
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Encrypts a backup with AES-256-GCM under a key kept apart from it (`BACKUP_ENCRYPTION_KEY`), so a copy of the
3
+ * bucket reveals nothing and any change is detected. Layout: `SHARADOX-BACKUP-1`, a 12-byte IV, the 16-byte tag,
4
+ * then the ciphertext.
5
+ *
6
+ * @example
7
+ * const sealed = encryptBackup(gzipSync(dump), process.env.BACKUP_ENCRYPTION_KEY!);
8
+ */
9
+ export declare function encryptBackup(plain: Uint8Array, key: string): Uint8Array;
10
+ /**
11
+ * Decrypts what `encryptBackup` made; throws for a wrong key, a changed byte, or anything else.
12
+ *
13
+ * @example
14
+ * const plain = decryptBackup(sealed, process.env.BACKUP_ENCRYPTION_KEY!);
15
+ */
16
+ export declare function decryptBackup(sealed: Uint8Array, key: string): Uint8Array;
17
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../source/backup-encryption/index.ts"],"names":[],"mappings":"AASA;;;;;;;GAOG;AACH,wBAAgB,aAAa,CAAC,KAAK,EAAE,UAAU,EAAE,GAAG,EAAE,MAAM,GAAG,UAAU,CAKxE;AAED;;;;;GAKG;AACH,wBAAgB,aAAa,CAAC,MAAM,EAAE,UAAU,EAAE,GAAG,EAAE,MAAM,GAAG,UAAU,CAQzE"}
@@ -0,0 +1,38 @@
1
+ import { createCipheriv, createDecipheriv, createHash, randomBytes } from "node:crypto";
2
+ const MAGIC = new TextEncoder().encode("SHARADOX-BACKUP-1");
3
+ const keyBytes = (key) => {
4
+ if (key.length < 32)
5
+ throw new Error("the backup key must have at least 32 characters");
6
+ return createHash("sha256").update(key).digest();
7
+ };
8
+ /**
9
+ * Encrypts a backup with AES-256-GCM under a key kept apart from it (`BACKUP_ENCRYPTION_KEY`), so a copy of the
10
+ * bucket reveals nothing and any change is detected. Layout: `SHARADOX-BACKUP-1`, a 12-byte IV, the 16-byte tag,
11
+ * then the ciphertext.
12
+ *
13
+ * @example
14
+ * const sealed = encryptBackup(gzipSync(dump), process.env.BACKUP_ENCRYPTION_KEY!);
15
+ */
16
+ export function encryptBackup(plain, key) {
17
+ const iv = randomBytes(12);
18
+ const cipher = createCipheriv("aes-256-gcm", keyBytes(key), iv);
19
+ const body = Buffer.concat([cipher.update(plain), cipher.final()]);
20
+ return new Uint8Array(Buffer.concat([MAGIC, iv, cipher.getAuthTag(), body]));
21
+ }
22
+ /**
23
+ * Decrypts what `encryptBackup` made; throws for a wrong key, a changed byte, or anything else.
24
+ *
25
+ * @example
26
+ * const plain = decryptBackup(sealed, process.env.BACKUP_ENCRYPTION_KEY!);
27
+ */
28
+ export function decryptBackup(sealed, key) {
29
+ const bytes = Buffer.from(sealed);
30
+ if (!bytes.subarray(0, MAGIC.length).equals(Buffer.from(MAGIC)))
31
+ throw new Error("this is not a backup file");
32
+ const iv = bytes.subarray(MAGIC.length, MAGIC.length + 12);
33
+ const tag = bytes.subarray(MAGIC.length + 12, MAGIC.length + 28);
34
+ const decipher = createDecipheriv("aes-256-gcm", keyBytes(key), iv);
35
+ decipher.setAuthTag(tag);
36
+ return new Uint8Array(Buffer.concat([decipher.update(bytes.subarray(MAGIC.length + 28)), decipher.final()]));
37
+ }
38
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../source/backup-encryption/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,gBAAgB,EAAE,UAAU,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAExF,MAAM,KAAK,GAAG,IAAI,WAAW,EAAE,CAAC,MAAM,CAAC,mBAAmB,CAAC,CAAC;AAE5D,MAAM,QAAQ,GAAG,CAAC,GAAW,EAAE,EAAE;IAC/B,IAAI,GAAG,CAAC,MAAM,GAAG,EAAE;QAAE,MAAM,IAAI,KAAK,CAAC,iDAAiD,CAAC,CAAC;IACxF,OAAO,UAAU,CAAC,QAAQ,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,CAAC;AACnD,CAAC,CAAC;AAEF;;;;;;;GAOG;AACH,MAAM,UAAU,aAAa,CAAC,KAAiB,EAAE,GAAW;IAC1D,MAAM,EAAE,GAAG,WAAW,CAAC,EAAE,CAAC,CAAC;IAC3B,MAAM,MAAM,GAAG,cAAc,CAAC,aAAa,EAAE,QAAQ,CAAC,GAAG,CAAC,EAAE,EAAE,CAAC,CAAC;IAChE,MAAM,IAAI,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11 @@
1
+ import type { BackupStorage, BackupStorageOptions } from "@sharadox/database-web-library/backup-storage/type";
2
+ /**
3
+ * Backups in an S3 bucket, under the environment's folder. The bucket's Object Lock (compliance mode) keeps every
4
+ * file for its retention, so nobody, not even the account's owner, can delete or change one: this storage only
5
+ * writes, reads and lists.
6
+ *
7
+ * @example
8
+ * const storage = createBackupStorage({ bucket, region: "eu-central-1", prefix: "production", credentials });
9
+ */
10
+ export declare function createBackupStorage({ bucket, region, prefix, credentials }: BackupStorageOptions): BackupStorage;
11
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../source/backup-storage/index.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,aAAa,EAAE,oBAAoB,EAAE,MAAM,oDAAoD,CAAC;AAE9G;;;;;;;GAOG;AACH,wBAAgB,mBAAmB,CAAC,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,WAAW,EAAE,EAAE,oBAAoB,GAAG,aAAa,CAgBhH"}