@sharadox/account-web-library 0.0.0-stage → 0.1.0-code-request.8

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 (149) hide show
  1. package/LICENCA.md +76 -0
  2. package/LICENSE.md +76 -0
  3. package/NOTICE.md +3 -0
  4. package/README.md +165 -2
  5. package/distribution/account-database/type.d.ts +73 -0
  6. package/distribution/account-database/type.d.ts.map +1 -0
  7. package/distribution/account-database/type.js +2 -0
  8. package/distribution/account-database/type.js.map +1 -0
  9. package/distribution/account-migration/index.d.ts +18 -0
  10. package/distribution/account-migration/index.d.ts.map +1 -0
  11. package/distribution/account-migration/index.js +122 -0
  12. package/distribution/account-migration/index.js.map +1 -0
  13. package/distribution/audit-event/index.d.ts +12 -0
  14. package/distribution/audit-event/index.d.ts.map +1 -0
  15. package/distribution/audit-event/index.js +25 -0
  16. package/distribution/audit-event/index.js.map +1 -0
  17. package/distribution/audit-event/type.d.ts +15 -0
  18. package/distribution/audit-event/type.d.ts.map +1 -0
  19. package/distribution/audit-event/type.js +2 -0
  20. package/distribution/audit-event/type.js.map +1 -0
  21. package/distribution/ban-length/index.d.ts +11 -0
  22. package/distribution/ban-length/index.d.ts.map +1 -0
  23. package/distribution/ban-length/index.js +21 -0
  24. package/distribution/ban-length/index.js.map +1 -0
  25. package/distribution/ban-length/type.d.ts +8 -0
  26. package/distribution/ban-length/type.d.ts.map +1 -0
  27. package/distribution/ban-length/type.js +2 -0
  28. package/distribution/ban-length/type.js.map +1 -0
  29. package/distribution/base-32/index.d.ts +16 -0
  30. package/distribution/base-32/index.d.ts.map +1 -0
  31. package/distribution/base-32/index.js +50 -0
  32. package/distribution/base-32/index.js.map +1 -0
  33. package/distribution/code-request/index.d.ts +16 -0
  34. package/distribution/code-request/index.d.ts.map +1 -0
  35. package/distribution/code-request/index.js +52 -0
  36. package/distribution/code-request/index.js.map +1 -0
  37. package/distribution/code-request/type.d.ts +25 -0
  38. package/distribution/code-request/type.d.ts.map +1 -0
  39. package/distribution/code-request/type.js +2 -0
  40. package/distribution/code-request/type.js.map +1 -0
  41. package/distribution/code-request-prune/index.d.ts +13 -0
  42. package/distribution/code-request-prune/index.d.ts.map +1 -0
  43. package/distribution/code-request-prune/index.js +12 -0
  44. package/distribution/code-request-prune/index.js.map +1 -0
  45. package/distribution/code-verification/index.d.ts +14 -0
  46. package/distribution/code-verification/index.d.ts.map +1 -0
  47. package/distribution/code-verification/index.js +43 -0
  48. package/distribution/code-verification/index.js.map +1 -0
  49. package/distribution/code-verification/type.d.ts +22 -0
  50. package/distribution/code-verification/type.d.ts.map +1 -0
  51. package/distribution/code-verification/type.js +2 -0
  52. package/distribution/code-verification/type.js.map +1 -0
  53. package/distribution/contact-addition/index.d.ts +13 -0
  54. package/distribution/contact-addition/index.d.ts.map +1 -0
  55. package/distribution/contact-addition/index.js +48 -0
  56. package/distribution/contact-addition/index.js.map +1 -0
  57. package/distribution/contact-addition/type.d.ts +15 -0
  58. package/distribution/contact-addition/type.d.ts.map +1 -0
  59. package/distribution/contact-addition/type.js +2 -0
  60. package/distribution/contact-addition/type.js.map +1 -0
  61. package/distribution/contact-kind/index.d.ts +12 -0
  62. package/distribution/contact-kind/index.d.ts.map +1 -0
  63. package/distribution/contact-kind/index.js +18 -0
  64. package/distribution/contact-kind/index.js.map +1 -0
  65. package/distribution/contact-kind/type.d.ts +6 -0
  66. package/distribution/contact-kind/type.d.ts.map +1 -0
  67. package/distribution/contact-kind/type.js +2 -0
  68. package/distribution/contact-kind/type.js.map +1 -0
  69. package/distribution/contact-lookup/index.d.ts +16 -0
  70. package/distribution/contact-lookup/index.d.ts.map +1 -0
  71. package/distribution/contact-lookup/index.js +20 -0
  72. package/distribution/contact-lookup/index.js.map +1 -0
  73. package/distribution/contact-removal/index.d.ts +19 -0
  74. package/distribution/contact-removal/index.d.ts.map +1 -0
  75. package/distribution/contact-removal/index.js +35 -0
  76. package/distribution/contact-removal/index.js.map +1 -0
  77. package/distribution/contact-verification/index.d.ts +20 -0
  78. package/distribution/contact-verification/index.d.ts.map +1 -0
  79. package/distribution/contact-verification/index.js +37 -0
  80. package/distribution/contact-verification/index.js.map +1 -0
  81. package/distribution/database-error/index.d.ts +12 -0
  82. package/distribution/database-error/index.d.ts.map +1 -0
  83. package/distribution/database-error/index.js +14 -0
  84. package/distribution/database-error/index.js.map +1 -0
  85. package/distribution/effective-permissions/index.d.ts +16 -0
  86. package/distribution/effective-permissions/index.d.ts.map +1 -0
  87. package/distribution/effective-permissions/index.js +31 -0
  88. package/distribution/effective-permissions/index.js.map +1 -0
  89. package/distribution/effective-permissions/type.d.ts +37 -0
  90. package/distribution/effective-permissions/type.d.ts.map +1 -0
  91. package/distribution/effective-permissions/type.js +2 -0
  92. package/distribution/effective-permissions/type.js.map +1 -0
  93. package/distribution/email-contact/index.d.ts +17 -0
  94. package/distribution/email-contact/index.d.ts.map +1 -0
  95. package/distribution/email-contact/index.js +27 -0
  96. package/distribution/email-contact/index.js.map +1 -0
  97. package/distribution/one-time-code/index.d.ts +26 -0
  98. package/distribution/one-time-code/index.d.ts.map +1 -0
  99. package/distribution/one-time-code/index.js +36 -0
  100. package/distribution/one-time-code/index.js.map +1 -0
  101. package/distribution/one-time-code/type.d.ts +6 -0
  102. package/distribution/one-time-code/type.d.ts.map +1 -0
  103. package/distribution/one-time-code/type.js +2 -0
  104. package/distribution/one-time-code/type.js.map +1 -0
  105. package/distribution/person-account/index.d.ts +14 -0
  106. package/distribution/person-account/index.d.ts.map +1 -0
  107. package/distribution/person-account/index.js +45 -0
  108. package/distribution/person-account/index.js.map +1 -0
  109. package/distribution/person-account/type.d.ts +17 -0
  110. package/distribution/person-account/type.d.ts.map +1 -0
  111. package/distribution/person-account/type.js +2 -0
  112. package/distribution/person-account/type.js.map +1 -0
  113. package/distribution/recovery-code/index.d.ts +17 -0
  114. package/distribution/recovery-code/index.d.ts.map +1 -0
  115. package/distribution/recovery-code/index.js +28 -0
  116. package/distribution/recovery-code/index.js.map +1 -0
  117. package/distribution/test-database/index.d.ts +13 -0
  118. package/distribution/test-database/index.d.ts.map +1 -0
  119. package/distribution/test-database/index.js +17 -0
  120. package/distribution/test-database/index.js.map +1 -0
  121. package/distribution/totp/index.d.ts +35 -0
  122. package/distribution/totp/index.d.ts.map +1 -0
  123. package/distribution/totp/index.js +70 -0
  124. package/distribution/totp/index.js.map +1 -0
  125. package/distribution/totp/type.d.ts +25 -0
  126. package/distribution/totp/type.d.ts.map +1 -0
  127. package/distribution/totp/type.js +2 -0
  128. package/distribution/totp/type.js.map +1 -0
  129. package/distribution/username/index.d.ts +23 -0
  130. package/distribution/username/index.d.ts.map +1 -0
  131. package/distribution/username/index.js +32 -0
  132. package/distribution/username/index.js.map +1 -0
  133. package/distribution/username/type.d.ts +10 -0
  134. package/distribution/username/type.d.ts.map +1 -0
  135. package/distribution/username/type.js +2 -0
  136. package/distribution/username/type.js.map +1 -0
  137. package/distribution/username-availability/index.d.ts +11 -0
  138. package/distribution/username-availability/index.d.ts.map +1 -0
  139. package/distribution/username-availability/index.js +21 -0
  140. package/distribution/username-availability/index.js.map +1 -0
  141. package/distribution/username-change/index.d.ts +15 -0
  142. package/distribution/username-change/index.d.ts.map +1 -0
  143. package/distribution/username-change/index.js +39 -0
  144. package/distribution/username-change/index.js.map +1 -0
  145. package/distribution/username-change/type.d.ts +7 -0
  146. package/distribution/username-change/type.d.ts.map +1 -0
  147. package/distribution/username-change/type.js +2 -0
  148. package/distribution/username-change/type.js.map +1 -0
  149. package/package.json +90 -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,166 @@
1
- # Temporary Holding Version
1
+ # @sharadox/account-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
+ Passwordless accounts for web applications, built on open standards, with no auth framework:
4
+
5
+ - one-time codes sent to a contact;
6
+ - two-factor codes from authenticator apps (TOTP);
7
+ - roles and bans per application;
8
+ - OpenID Connect for people and agents.
9
+
10
+ One deployment per company. Everything company-specific is configuration.
11
+
12
+ **Status: 0.1.0, in progress.** Building blocks (usernames, one-time codes, TOTP, recovery codes, email contacts,
13
+ effective permissions, ban lengths) and account storage in Postgres (accounts, usernames, contacts, audit log).
14
+ Sign-in codes, sessions and the OpenID Connect server come next (see `CHANGELOG.md`).
15
+
16
+ ## Install
17
+
18
+ ```sh
19
+ pnpm add @sharadox/account-web-library
20
+ ```
21
+
22
+ ## Storage
23
+
24
+ Postgres through Kysely (`@sharadox/database-web-library`). Run `migrateAccount(database)` when the application
25
+ migrates: the tables are tracked in their own table (`account_migration`). Type Kysely with `AccountDatabase`
26
+ (`account-database/type`). The database enforces the rules itself, as the last line behind the code:
27
+
28
+ - ids are UUIDv7;
29
+ - usernames follow the rules and are unique without regard to case;
30
+ - a verified contact belongs to one account only;
31
+ - every person keeps at least one verified sign-in contact, checked when a change commits;
32
+ - agents have an owner (and go with them);
33
+ - the audit log is never changed.
34
+
35
+ Tests: `createTestAccountDatabase()` (`test-database`) gives a migrated Postgres in memory (PGlite, a development
36
+ dependency).
37
+
38
+ ## API
39
+
40
+ Each export has its own entry point (`@sharadox/account-web-library/<name>`).
41
+
42
+ ### `username`: `checkUsername(name)`, `usernameKey(name)`, `USERNAME_MAXIMUM_LENGTH`
43
+
44
+ The rules:
45
+
46
+ - 1 to 50 characters;
47
+ - A–Z, a–z and 0–9, with `-`, `_` or `.` allowed only between letters or digits, never two in a row;
48
+ - shown as written, but unique without regard to case: `abc` and `aBc` are the same username.
49
+
50
+ ```ts
51
+ checkUsername("Luis-Pires"); // { valid: true, username: "Luis-Pires", key: "luis-pires" }
52
+ checkUsername("a--b"); // { valid: false, reason: "characters" }
53
+ ```
54
+
55
+ Store `key` under a unique index.
56
+
57
+ ### `one-time-code`: `createOneTimeCode(length = 8)`, `hashOneTimeCode(code, { pepper, purpose })`, `matchesOneTimeCode(code, hash, { pepper, purpose })`
58
+
59
+ - Codes are uniform random digits.
60
+ - Only an HMAC-SHA-256 is stored, under a pepper of at least 32 characters kept outside the database, and bound to
61
+ its purpose (`sign-in:<request id>`).
62
+ - Matching ignores spaces and runs in constant time.
63
+
64
+ ### `totp`: `createTotpSecret()`, `totpCode(secret, now, { digits = 6, period = 30 })`, `verifyTotp(secret, code, now, { lastUsedStep })`, `totpUri({ issuer, account, secret })`
65
+
66
+ RFC 6238 with SHA-1, 6 digits and 30-second steps.
67
+
68
+ - **Verification:** one step of drift is accepted either side. Steps at or before `lastUsedStep` are refused, so a code
69
+ can't be replayed. Store the returned `step`.
70
+ - **`totpUri`:** gives the `otpauth://` address to show as a QR code. Its `secret` parameter is the text to type in.
71
+
72
+ ```ts
73
+ const secret = createTotpSecret(); // store encrypted
74
+ const address = totpUri({ issuer: "Luis Pires Decor", account: "luis-pires", secret });
75
+ const result = verifyTotp(secret, typed, Date.now(), { lastUsedStep });
76
+ ```
77
+
78
+ ### `base-32`: `encodeBase32(bytes)`, `decodeBase32(text)`
79
+
80
+ RFC 4648 base 32 without padding. Decoding accepts lowercase, spaces and padding.
81
+
82
+ ### `effective-permissions`: `effectivePermissions({ application, resource?, now, defaultRole, roles, grants, scope?, ownerPermissions? })` → `Set<string>`
83
+
84
+ What an account may do in one application, now:
85
+
86
+ 1. Active grants count: started, not ended, in the application or global, and for the whole application or the
87
+ resource asked.
88
+ 2. An active **exclusive** role (a ban) leaves only its own permissions.
89
+ 3. Otherwise the result is the default role plus every active role.
90
+ 4. Only the application's permissions (`platform.…`) and the account system's own (`account.…`) are kept.
91
+ 5. The result is limited to `scope` (a token or key) and to `ownerPermissions` (an agent's owner).
92
+
93
+ ### `ban-length`: `banLength([{ schedule, previousOffenses }])` → seconds or `"permanent"`
94
+
95
+ - Each rule gives its schedule's penalty for this offense, and the last penalty repeats.
96
+ - Several rules broken at once give the longest of their penalties.
97
+
98
+ ### `recovery-code`: `createRecoveryCodes(count = 10)`, `normalizeRecoveryCode(code)`
99
+
100
+ Codes like `7KQM-W3HD-9TXA` (about 59 bits each), from characters that can't be misread. Hash each one with
101
+ `hashOneTimeCode(normalizeRecoveryCode(code), { pepper, purpose: "recovery:<account id>" })`.
102
+
103
+ ### `email-contact`: `normalizeEmail(address)`, `emailLedgerForm(address)`
104
+
105
+ - `normalizeEmail` trims and lowercases, and throws for text that isn't an email address.
106
+ - `emailLedgerForm` also drops `+tags`, for the banned-contact ledger.
107
+
108
+ ### `person-account`: `createPersonAccount(database, { username, contact, now? })`
109
+
110
+ Creates a person with the contact their one-time code just proved, stored verified, and records `account.created`.
111
+ Returns `{ created: true, accountId, contactId }`, or `{ created: false, reason }` with `username-invalid`,
112
+ `username-taken` or `contact-taken`.
113
+
114
+ ### `username-availability`: `usernameAvailability(database, username)` → `available` | `taken` | `invalid`
115
+
116
+ Rate limit it: it tells whether an account exists.
117
+
118
+ ### `username-change`: `changeUsername(database, { accountId, username })`
119
+
120
+ Any time, and the old name is free at once; the audit log keeps `{ from, to }`. Reasons: `username-invalid`,
121
+ `username-taken`, `no-account`.
122
+
123
+ ### `contact-lookup`: `findAccountByContact(database, contact)` → `{ accountId, contactId, signIn }` or undefined
124
+
125
+ Verified contacts only, normalized first.
126
+
127
+ ### `contact-addition`, `contact-verification`, `contact-removal`
128
+
129
+ - `addContact(database, { accountId, contact, now? })` adds it unverified. Reasons: `already-added`,
130
+ `contact-taken`, `no-account`.
131
+ - `verifyContact(database, { accountId, contactId, now? })` once its code came back. Reasons: `no-contact`,
132
+ `contact-taken` (another account verified it first).
133
+ - `removeContact(database, { accountId, contactId })`. Reasons: `no-contact`, `last-sign-in-contact`.
134
+
135
+ Each is recorded in the audit log. Ask for a fresh code first (step-up) and tell the other contacts.
136
+
137
+ ### `code-request`: `requestCode(database, { purpose, contact, accountId?, pepper, length = 8, lifetimeSeconds = 600, now? })` → `{ requestId, code, contact, expiresAt }`
138
+
139
+ Starts a one-time code for `sign-in`, `contact-verification` or `step-up`.
140
+
141
+ - Only an HMAC bound to the purpose and request is stored.
142
+ - A new request replaces the open one for the same contact and purpose.
143
+ - Send the code after answering the request, so timing reveals nothing. Rate limit and cap the sends first
144
+ (`limitRate`, `spendFromCap` from protection-web-library).
145
+
146
+ ### `code-verification`: `verifyCode(database, { requestId, code, purpose, pepper, maximumAttempts = 5, now? })`
147
+
148
+ Returns `{ valid: true, contact, accountId }` (the account that asked, null for sign-in), or `{ valid: false, reason }`
149
+ with `unknown`, `used`, `replaced`, `expired`, `attempts` or `wrong`. The row is locked, so concurrent guesses can't
150
+ pass the limit; after the last attempt even the right code is refused.
151
+
152
+ ### `code-request-prune`: `pruneCodeRequests(database, { before })` → deleted count
153
+
154
+ ### `contact-kind`: `normalizeContact({ kind, value })`, `CONTACT_KINDS`
155
+
156
+ `email` in this version; unknown kinds and invalid values throw.
157
+
158
+ ### `audit-event`: `recordAuditEvent(database, { action, accountId?, actorAccountId?, application?, detail?, now? })` → id
159
+
160
+ Pass the transaction of the change it describes. `detail` holds ids and kinds, never contact values or secrets.
161
+
162
+ ### `database-error`: `databaseError(error)` → `{ code, constraint }` or undefined
163
+
164
+ ## License
165
+
166
+ Sharadox Open Source License 0.1.0 (see `LICENSE.md`).
@@ -0,0 +1,73 @@
1
+ import type { ColumnType, Generated } from "kysely";
2
+ /** A timestamp the database fills in when not given. */
3
+ type DefaultTime = ColumnType<Date, Date | undefined, Date>;
4
+ /** An application the accounts sign in to (`account` itself, `platform`, `shop`…). */
5
+ export interface ApplicationTable {
6
+ id: string;
7
+ name: string;
8
+ created_at: DefaultTime;
9
+ }
10
+ /** A person, or an agent owned by a person. */
11
+ export interface AccountTable {
12
+ id: string;
13
+ kind: "person" | "agent";
14
+ /** Shown as written; unique without regard to case. */
15
+ username: string;
16
+ /** The person who owns an agent; null for people. */
17
+ owner_id: string | null;
18
+ created_at: DefaultTime;
19
+ last_active_at: DefaultTime;
20
+ }
21
+ /** A way to reach an account (email now; phone and messaging later). */
22
+ export interface ContactTable {
23
+ id: string;
24
+ account_id: string;
25
+ kind: string;
26
+ /** Normalized (see `normalizeContact`). */
27
+ value: string;
28
+ /** When a one-time code proved it; null until then. A verified contact belongs to one account only. */
29
+ verified_at: Date | null;
30
+ /** Whether codes for signing in may be sent to it. */
31
+ sign_in: Generated<boolean>;
32
+ created_at: DefaultTime;
33
+ }
34
+ /** One line of the append-only audit log. */
35
+ export interface AuditEventTable {
36
+ id: string;
37
+ at: DefaultTime;
38
+ /** The account it is about (kept after the account is deleted, as a bare id). */
39
+ account_id: string | null;
40
+ /** Who did it, when not the account itself (an administrator, an agent). */
41
+ actor_account_id: string | null;
42
+ application: string | null;
43
+ action: string;
44
+ detail: ColumnType<Record<string, unknown>, Record<string, unknown> | undefined, never>;
45
+ }
46
+ /** A one-time code sent to a contact, stored only as an HMAC bound to its purpose and request. */
47
+ export interface CodeRequestTable {
48
+ id: string;
49
+ /** `sign-in`, `contact-verification` or `step-up`. */
50
+ purpose: string;
51
+ /** The account asking (step-up, contact verification); null when signing in. */
52
+ account_id: string | null;
53
+ kind: string;
54
+ value: string;
55
+ code_hash: string;
56
+ created_at: Date;
57
+ expires_at: Date;
58
+ attempts: Generated<number>;
59
+ /** When the right code came back. */
60
+ used_at: Date | null;
61
+ /** When a newer request for the same contact and purpose replaced it. */
62
+ voided_at: Date | null;
63
+ }
64
+ /** The tables `migrateAccount` creates, for typing a Kysely instance. */
65
+ export interface AccountDatabase {
66
+ application: ApplicationTable;
67
+ account: AccountTable;
68
+ contact: ContactTable;
69
+ audit_event: AuditEventTable;
70
+ code_request: CodeRequestTable;
71
+ }
72
+ export {};
73
+ //# sourceMappingURL=type.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"type.d.ts","sourceRoot":"","sources":["../../source/account-database/type.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,SAAS,EAAE,MAAM,QAAQ,CAAC;AAEpD,wDAAwD;AACxD,KAAK,WAAW,GAAG,UAAU,CAAC,IAAI,EAAE,IAAI,GAAG,SAAS,EAAE,IAAI,CAAC,CAAC;AAE5D,sFAAsF;AACtF,MAAM,WAAW,gBAAgB;IAC/B,EAAE,EAAE,MAAM,CAAC;IACX,IAAI,EAAE,MAAM,CAAC;IACb,UAAU,EAAE,WAAW,CAAC;CACzB;AAED,+CAA+C;AAC/C,MAAM,WAAW,YAAY;IAC3B,EAAE,EAAE,MAAM,CAAC;IACX,IAAI,EAAE,QAAQ,GAAG,OAAO,CAAC;IACzB,uDAAuD;IACvD,QAAQ,EAAE,MAAM,CAAC;IACjB,qDAAqD;IACrD,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAC;IACxB,UAAU,EAAE,WAAW,CAAC;IACxB,cAAc,EAAE,WAAW,CAAC;CAC7B;AAED,wEAAwE;AACxE,MAAM,WAAW,YAAY;IAC3B,EAAE,EAAE,MAAM,CAAC;IACX,UAAU,EAAE,MAAM,CAAC;IACnB,IAAI,EAAE,MAAM,CAAC;IACb,2CAA2C;IAC3C,KAAK,EAAE,MAAM,CAAC;IACd,uGAAuG;IACvG,WAAW,EAAE,IAAI,GAAG,IAAI,CAAC;IACzB,sDAAsD;IACtD,OAAO,EAAE,SAAS,CAAC,OAAO,CAAC,CAAC;IAC5B,UAAU,EAAE,WAAW,CAAC;CACzB;AAED,6CAA6C;AAC7C,MAAM,WAAW,eAAe;IAC9B,EAAE,EAAE,MAAM,CAAC;IACX,EAAE,EAAE,WAAW,CAAC;IAChB,iFAAiF;IACjF,UAAU,EAAE,MAAM,GAAG,IAAI,CAAC;IAC1B,4EAA4E;IAC5E,gBAAgB,EAAE,MAAM,GAAG,IAAI,CAAC;IAChC,WAAW,EAAE,MAAM,GAAG,IAAI,CAAC;IAC3B,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,UAAU,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,SAAS,EAAE,KAAK,CAAC,CAAC;CACzF;AAED,kGAAkG;AAClG,MAAM,WAAW,gBAAgB;IAC/B,EAAE,EAAE,MAAM,CAAC;IACX,sDAAsD;IACtD,OAAO,EAAE,MAAM,CAAC;IAChB,gFAAgF;IAChF,UAAU,EAAE,MAAM,GAAG,IAAI,CAAC;IAC1B,IAAI,EAAE,MAAM,CAAC;IACb,KAAK,EAAE,MAAM,CAAC;IACd,SAAS,EAAE,MAAM,CAAC;IAClB,UAAU,EAAE,IAAI,CAAC;IACjB,UAAU,EAAE,IAAI,CAAC;IACjB,QAAQ,EAAE,SAAS,CAAC,MAAM,CAAC,CAAC;IAC5B,qCAAqC;IACrC,OAAO,EAAE,IAAI,GAAG,IAAI,CAAC;IACrB,yEAAyE;IACzE,SAAS,EAAE,IAAI,GAAG,IAAI,CAAC;CACxB;AAED,yEAAyE;AACzE,MAAM,WAAW,eAAe;IAC9B,WAAW,EAAE,gBAAgB,CAAC;IAC9B,OAAO,EAAE,YAAY,CAAC;IACtB,OAAO,EAAE,YAAY,CAAC;IACtB,WAAW,EAAE,eAAe,CAAC;IAC7B,YAAY,EAAE,gBAAgB,CAAC;CAChC"}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=type.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"type.js","sourceRoot":"","sources":["../../source/account-database/type.ts"],"names":[],"mappings":""}
@@ -0,0 +1,18 @@
1
+ import type { Kysely } from "kysely";
2
+ import type { Migration } from "@sharadox/database-web-library/migration/type";
3
+ /** The table that records which account migrations a database has applied (apart from the application's own). */
4
+ export declare const ACCOUNT_MIGRATION_TABLE = "account_migration";
5
+ /**
6
+ * The account tables, forward only. The database enforces the rules itself, as the last line behind the code:
7
+ * UUIDv7 ids, username rules and case-insensitive uniqueness, one account per verified contact, agents owned by a
8
+ * person, every person keeping a verified sign-in contact (checked at commit), and an audit log that is never changed.
9
+ */
10
+ export declare const accountMigrations: Migration[];
11
+ /**
12
+ * Creates or updates the account tables, tracked in their own migration table. Returns the names applied.
13
+ *
14
+ * @example
15
+ * await migrateAccount(database);
16
+ */
17
+ export declare function migrateAccount<Schema>(database: Kysely<Schema>): Promise<string[]>;
18
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../source/account-migration/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAErC,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,+CAA+C,CAAC;AAE/E,iHAAiH;AACjH,eAAO,MAAM,uBAAuB,sBAAsB,CAAC;AAE3D;;;;GAIG;AACH,eAAO,MAAM,iBAAiB,EAAE,SAAS,EAuGxC,CAAC;AAEF;;;;;GAKG;AACH,wBAAgB,cAAc,CAAC,MAAM,EAAE,QAAQ,EAAE,MAAM,CAAC,MAAM,CAAC,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC,CAElF"}
@@ -0,0 +1,122 @@
1
+ import { migrate } from "@sharadox/database-web-library/migration";
2
+ /** The table that records which account migrations a database has applied (apart from the application's own). */
3
+ export const ACCOUNT_MIGRATION_TABLE = "account_migration";
4
+ /**
5
+ * The account tables, forward only. The database enforces the rules itself, as the last line behind the code:
6
+ * UUIDv7 ids, username rules and case-insensitive uniqueness, one account per verified contact, agents owned by a
7
+ * person, every person keeping a verified sign-in contact (checked at commit), and an audit log that is never changed.
8
+ */
9
+ export const accountMigrations = [
10
+ {
11
+ name: "0001-application-account-contact-audit",
12
+ sql: `
13
+ create table application (
14
+ id text primary key check (id ~ '^[a-z][a-z0-9]*(-[a-z0-9]+)*$' and length(id) <= 50),
15
+ name text not null,
16
+ created_at timestamptz not null default now()
17
+ );
18
+ insert into application (id, name) values ('account', 'Account');
19
+
20
+ create table account (
21
+ id uuid primary key check (uuid_extract_version(id) = 7),
22
+ kind text not null check (kind in ('person', 'agent')),
23
+ username text not null
24
+ check (length(username) between 1 and 50 and username ~ '^[A-Za-z0-9]+([-_.][A-Za-z0-9]+)*$'),
25
+ owner_id uuid references account (id) on delete cascade,
26
+ created_at timestamptz not null default now(),
27
+ last_active_at timestamptz not null default now(),
28
+ constraint account_owner_check check ((kind = 'agent') = (owner_id is not null))
29
+ );
30
+ create unique index account_username_key on account (lower(username));
31
+ create index account_owner on account (owner_id) where owner_id is not null;
32
+ create index account_last_active_at on account (last_active_at);
33
+
34
+ create table contact (
35
+ id uuid primary key check (uuid_extract_version(id) = 7),
36
+ account_id uuid not null references account (id) on delete cascade,
37
+ kind text not null check (kind ~ '^[a-z][a-z0-9]*(-[a-z0-9]+)*$'),
38
+ value text not null check (length(value) between 1 and 320),
39
+ verified_at timestamptz,
40
+ sign_in boolean not null default true,
41
+ created_at timestamptz not null default now()
42
+ );
43
+ create unique index contact_verified on contact (kind, value) where verified_at is not null;
44
+ create unique index contact_per_account on contact (account_id, kind, value);
45
+
46
+ create function account_require_sign_in_contact(target uuid) returns void
47
+ language plpgsql set search_path = public as $$
48
+ begin
49
+ if exists (select 1 from account where id = target and kind = 'person')
50
+ and not exists (
51
+ select 1 from contact where account_id = target and verified_at is not null and sign_in
52
+ ) then
53
+ raise exception 'a person account needs at least one verified sign-in contact' using errcode = '23514';
54
+ end if;
55
+ end $$;
56
+ create function account_after_insert() returns trigger
57
+ language plpgsql set search_path = public as $$
58
+ begin
59
+ perform account_require_sign_in_contact(new.id);
60
+ return null;
61
+ end $$;
62
+ create function contact_after_change() returns trigger
63
+ language plpgsql set search_path = public as $$
64
+ begin
65
+ perform account_require_sign_in_contact(old.account_id);
66
+ return null;
67
+ end $$;
68
+ create constraint trigger account_sign_in_contact after insert on account
69
+ deferrable initially deferred for each row execute function account_after_insert();
70
+ create constraint trigger contact_sign_in_contact after update or delete on contact
71
+ deferrable initially deferred for each row execute function contact_after_change();
72
+
73
+ create table audit_event (
74
+ id uuid primary key check (uuid_extract_version(id) = 7),
75
+ at timestamptz not null default now(),
76
+ account_id uuid,
77
+ actor_account_id uuid,
78
+ application text,
79
+ action text not null check (length(action) between 1 and 100),
80
+ detail jsonb not null default '{}'
81
+ );
82
+ create index audit_event_account on audit_event (account_id, at);
83
+ create function audit_event_unchangeable() returns trigger
84
+ language plpgsql as $$
85
+ begin
86
+ raise exception 'audit events are never changed';
87
+ end $$;
88
+ create trigger audit_event_unchangeable before update on audit_event
89
+ for each row execute function audit_event_unchangeable();
90
+ `,
91
+ },
92
+ {
93
+ name: "0002-code-request",
94
+ sql: `
95
+ create table code_request (
96
+ id uuid primary key check (uuid_extract_version(id) = 7),
97
+ purpose text not null check (purpose in ('sign-in', 'contact-verification', 'step-up')),
98
+ account_id uuid,
99
+ kind text not null,
100
+ value text not null,
101
+ code_hash text not null,
102
+ created_at timestamptz not null,
103
+ expires_at timestamptz not null,
104
+ attempts integer not null default 0 check (attempts >= 0),
105
+ used_at timestamptz,
106
+ voided_at timestamptz
107
+ );
108
+ create index code_request_open on code_request (kind, value, purpose) where used_at is null and voided_at is null;
109
+ create index code_request_expires_at on code_request (expires_at);
110
+ `,
111
+ },
112
+ ];
113
+ /**
114
+ * Creates or updates the account tables, tracked in their own migration table. Returns the names applied.
115
+ *
116
+ * @example
117
+ * await migrateAccount(database);
118
+ */
119
+ export function migrateAccount(database) {
120
+ return migrate(database, accountMigrations, { table: ACCOUNT_MIGRATION_TABLE });
121
+ }
122
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../source/account-migration/index.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,OAAO,EAAE,MAAM,0CAA0C,CAAC;AAGnE,iHAAiH;AACjH,MAAM,CAAC,MAAM,uBAAuB,GAAG,mBAAmB,CAAC;AAE3D;;;;GAIG;AACH,MAAM,CAAC,MAAM,iBAAiB,GAAgB;IAC5C;QACE,IAAI,EAAE,wCAAwC;QAC9C,GAAG,EAAE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;KA8EJ;KACF;IACD;QACE,IAAI,EAAE,mBAAmB;QACzB,GAAG,EAAE;;;;;;;;;;;;;;;;KAgBJ;KACF;CACF,CAAC;AAEF;;;;;GAKG;AACH,MAAM,UAAU,cAAc,CAAS,QAAwB;IAC7D,OAAO,OAAO,CAAC,QAAQ,EAAE,iBAAiB,EAAE,EAAE,KAAK,EAAE,uBAAuB,EAAE,CAAC,CAAC;AAClF,CAAC"}
@@ -0,0 +1,12 @@
1
+ import type { Kysely } from "kysely";
2
+ import type { AccountDatabase } from "@sharadox/account-web-library/account-database/type";
3
+ import type { AuditEvent } from "@sharadox/account-web-library/audit-event/type";
4
+ /**
5
+ * Adds a line to the append-only audit log (the database refuses changes to it). Pass a transaction to record it
6
+ * together with the change it describes. Returns the event's UUIDv7.
7
+ *
8
+ * @example
9
+ * await recordAuditEvent(transaction, { accountId, action: "contact.removed", detail: { contactId } });
10
+ */
11
+ export declare function recordAuditEvent(database: Kysely<AccountDatabase>, { accountId, actorAccountId, application, action, detail, now }: AuditEvent): Promise<string>;
12
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../source/audit-event/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAErC,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,qDAAqD,CAAC;AAC3F,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,gDAAgD,CAAC;AAEjF;;;;;;GAMG;AACH,wBAAsB,gBAAgB,CACpC,QAAQ,EAAE,MAAM,CAAC,eAAe,CAAC,EACjC,EAAE,SAAgB,EAAE,cAAqB,EAAE,WAAkB,EAAE,MAAM,EAAE,MAAW,EAAE,GAAgB,EAAE,EAAE,UAAU,GACjH,OAAO,CAAC,MAAM,CAAC,CAejB"}
@@ -0,0 +1,25 @@
1
+ import { uuidVersion7 } from "@sharadox/web-library/identifier/uuid-version-7";
2
+ /**
3
+ * Adds a line to the append-only audit log (the database refuses changes to it). Pass a transaction to record it
4
+ * together with the change it describes. Returns the event's UUIDv7.
5
+ *
6
+ * @example
7
+ * await recordAuditEvent(transaction, { accountId, action: "contact.removed", detail: { contactId } });
8
+ */
9
+ export async function recordAuditEvent(database, { accountId = null, actorAccountId = null, application = null, action, detail = {}, now = Date.now() }) {
10
+ const id = uuidVersion7({ now });
11
+ await database
12
+ .insertInto("audit_event")
13
+ .values({
14
+ id,
15
+ at: new Date(now),
16
+ account_id: accountId,
17
+ actor_account_id: actorAccountId,
18
+ application,
19
+ action,
20
+ detail,
21
+ })
22
+ .execute();
23
+ return id;
24
+ }
25
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../source/audit-event/index.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,YAAY,EAAE,MAAM,iDAAiD,CAAC;AAI/E;;;;;;GAMG;AACH,MAAM,CAAC,KAAK,UAAU,gBAAgB,CACpC,QAAiC,EACjC,EAAE,SAAS,GAAG,IAAI,EAAE,cAAc,GAAG,IAAI,EAAE,WAAW,GAAG,IAAI,EAAE,MAAM,EAAE,MAAM,GAAG,EAAE,EAAE,GAAG,GAAG,IAAI,CAAC,GAAG,EAAE,EAAc;IAElH,MAAM,EAAE,GAAG,YAAY,CAAC,EAAE,GAAG,EAAE,CAAC,CAAC;IACjC,MAAM,QAAQ;SACX,UAAU,CAAC,aAAa,CAAC;SACzB,MAAM,CAAC;QACN,EAAE;QACF,EAAE,EAAE,IAAI,IAAI,CAAC,GAAG,CAAC;QACjB,UAAU,EAAE,SAAS;QACrB,gBAAgB,EAAE,cAAc;QAChC,WAAW;QACX,MAAM;QACN,MAAM;KACP,CAAC;SACD,OAAO,EAAE,CAAC;IACb,OAAO,EAAE,CAAC;AACZ,CAAC"}
@@ -0,0 +1,15 @@
1
+ /** What happened, to which account, done by whom, in which application. */
2
+ export interface AuditEvent {
3
+ /** The account it is about. */
4
+ accountId?: string | null;
5
+ /** Who did it, when not the account itself. */
6
+ actorAccountId?: string | null;
7
+ application?: string | null;
8
+ /** `<subject>.<verb>`: `account.created`, `contact.removed`, `role.granted`… */
9
+ action: string;
10
+ /** Ids and kinds, never contact values or secrets. */
11
+ detail?: Record<string, unknown>;
12
+ /** Milliseconds since 1970 (now by default). */
13
+ now?: number;
14
+ }
15
+ //# sourceMappingURL=type.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"type.d.ts","sourceRoot":"","sources":["../../source/audit-event/type.ts"],"names":[],"mappings":"AAAA,2EAA2E;AAC3E,MAAM,WAAW,UAAU;IACzB,+BAA+B;IAC/B,SAAS,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC1B,+CAA+C;IAC/C,cAAc,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC/B,WAAW,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC5B,gFAAgF;IAChF,MAAM,EAAE,MAAM,CAAC;IACf,sDAAsD;IACtD,MAAM,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IACjC,gDAAgD;IAChD,GAAG,CAAC,EAAE,MAAM,CAAC;CACd"}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=type.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"type.js","sourceRoot":"","sources":["../../source/audit-event/type.ts"],"names":[],"mappings":""}