@sharadox/account-web-library 0.0.0-stage → 0.1.0-development.3

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 (57) hide show
  1. package/LICENCA.md +76 -0
  2. package/LICENSE.md +76 -0
  3. package/NOTICE.md +3 -0
  4. package/README.md +93 -2
  5. package/distribution/ban-length/index.d.ts +11 -0
  6. package/distribution/ban-length/index.d.ts.map +1 -0
  7. package/distribution/ban-length/index.js +21 -0
  8. package/distribution/ban-length/index.js.map +1 -0
  9. package/distribution/ban-length/type.d.ts +8 -0
  10. package/distribution/ban-length/type.d.ts.map +1 -0
  11. package/distribution/ban-length/type.js +2 -0
  12. package/distribution/ban-length/type.js.map +1 -0
  13. package/distribution/base-32/index.d.ts +16 -0
  14. package/distribution/base-32/index.d.ts.map +1 -0
  15. package/distribution/base-32/index.js +50 -0
  16. package/distribution/base-32/index.js.map +1 -0
  17. package/distribution/effective-permissions/index.d.ts +16 -0
  18. package/distribution/effective-permissions/index.d.ts.map +1 -0
  19. package/distribution/effective-permissions/index.js +31 -0
  20. package/distribution/effective-permissions/index.js.map +1 -0
  21. package/distribution/effective-permissions/type.d.ts +37 -0
  22. package/distribution/effective-permissions/type.d.ts.map +1 -0
  23. package/distribution/effective-permissions/type.js +2 -0
  24. package/distribution/effective-permissions/type.js.map +1 -0
  25. package/distribution/email-contact/index.d.ts +17 -0
  26. package/distribution/email-contact/index.d.ts.map +1 -0
  27. package/distribution/email-contact/index.js +27 -0
  28. package/distribution/email-contact/index.js.map +1 -0
  29. package/distribution/one-time-code/index.d.ts +26 -0
  30. package/distribution/one-time-code/index.d.ts.map +1 -0
  31. package/distribution/one-time-code/index.js +36 -0
  32. package/distribution/one-time-code/index.js.map +1 -0
  33. package/distribution/one-time-code/type.d.ts +6 -0
  34. package/distribution/one-time-code/type.d.ts.map +1 -0
  35. package/distribution/one-time-code/type.js +2 -0
  36. package/distribution/one-time-code/type.js.map +1 -0
  37. package/distribution/recovery-code/index.d.ts +17 -0
  38. package/distribution/recovery-code/index.d.ts.map +1 -0
  39. package/distribution/recovery-code/index.js +28 -0
  40. package/distribution/recovery-code/index.js.map +1 -0
  41. package/distribution/totp/index.d.ts +35 -0
  42. package/distribution/totp/index.d.ts.map +1 -0
  43. package/distribution/totp/index.js +70 -0
  44. package/distribution/totp/index.js.map +1 -0
  45. package/distribution/totp/type.d.ts +25 -0
  46. package/distribution/totp/type.d.ts.map +1 -0
  47. package/distribution/totp/type.js +2 -0
  48. package/distribution/totp/type.js.map +1 -0
  49. package/distribution/username/index.d.ts +23 -0
  50. package/distribution/username/index.d.ts.map +1 -0
  51. package/distribution/username/index.js +32 -0
  52. package/distribution/username/index.js.map +1 -0
  53. package/distribution/username/type.d.ts +10 -0
  54. package/distribution/username/type.d.ts.map +1 -0
  55. package/distribution/username/type.js +2 -0
  56. package/distribution/username/type.js.map +1 -0
  57. package/package.json +87 -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,94 @@
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, building blocks.** Usernames, one-time codes, TOTP, recovery codes, email contacts, effective
13
+ permissions and ban lengths. Accounts, contacts, sessions, storage and the OpenID Connect server come next (see
14
+ `CHANGELOG.md`).
15
+
16
+ ## Install
17
+
18
+ ```sh
19
+ pnpm add @sharadox/account-web-library
20
+ ```
21
+
22
+ ## API
23
+
24
+ Each export has its own entry point (`@sharadox/account-web-library/<name>`).
25
+
26
+ ### `username`: `checkUsername(name)`, `usernameKey(name)`, `USERNAME_MAXIMUM_LENGTH`
27
+
28
+ The rules:
29
+
30
+ - 1 to 50 characters;
31
+ - A–Z, a–z and 0–9, with `-`, `_` or `.` allowed only between letters or digits, never two in a row;
32
+ - shown as written, but unique without regard to case: `abc` and `aBc` are the same username.
33
+
34
+ ```ts
35
+ checkUsername("Luis-Pires"); // { valid: true, username: "Luis-Pires", key: "luis-pires" }
36
+ checkUsername("a--b"); // { valid: false, reason: "characters" }
37
+ ```
38
+
39
+ Store `key` under a unique index.
40
+
41
+ ### `one-time-code`: `createOneTimeCode(length = 8)`, `hashOneTimeCode(code, { pepper, purpose })`, `matchesOneTimeCode(code, hash, { pepper, purpose })`
42
+
43
+ - Codes are uniform random digits.
44
+ - Only an HMAC-SHA-256 is stored, under a pepper of at least 32 characters kept outside the database, and bound to
45
+ its purpose (`sign-in:<request id>`).
46
+ - Matching ignores spaces and runs in constant time.
47
+
48
+ ### `totp`: `createTotpSecret()`, `totpCode(secret, now, { digits = 6, period = 30 })`, `verifyTotp(secret, code, now, { lastUsedStep })`, `totpUri({ issuer, account, secret })`
49
+
50
+ RFC 6238 with SHA-1, 6 digits and 30-second steps.
51
+
52
+ - **Verification:** one step of drift is accepted either side. Steps at or before `lastUsedStep` are refused, so a code
53
+ can't be replayed. Store the returned `step`.
54
+ - **`totpUri`:** gives the `otpauth://` address to show as a QR code. Its `secret` parameter is the text to type in.
55
+
56
+ ```ts
57
+ const secret = createTotpSecret(); // store encrypted
58
+ const address = totpUri({ issuer: "Luis Pires Decor", account: "luis-pires", secret });
59
+ const result = verifyTotp(secret, typed, Date.now(), { lastUsedStep });
60
+ ```
61
+
62
+ ### `base-32`: `encodeBase32(bytes)`, `decodeBase32(text)`
63
+
64
+ RFC 4648 base 32 without padding. Decoding accepts lowercase, spaces and padding.
65
+
66
+ ### `effective-permissions`: `effectivePermissions({ application, resource?, now, defaultRole, roles, grants, scope?, ownerPermissions? })` → `Set<string>`
67
+
68
+ What an account may do in one application, now:
69
+
70
+ 1. Active grants count: started, not ended, in the application or global, and for the whole application or the
71
+ resource asked.
72
+ 2. An active **exclusive** role (a ban) leaves only its own permissions.
73
+ 3. Otherwise the result is the default role plus every active role.
74
+ 4. Only the application's permissions (`platform.…`) and the account system's own (`account.…`) are kept.
75
+ 5. The result is limited to `scope` (a token or key) and to `ownerPermissions` (an agent's owner).
76
+
77
+ ### `ban-length`: `banLength([{ schedule, previousOffenses }])` → seconds or `"permanent"`
78
+
79
+ - Each rule gives its schedule's penalty for this offense, and the last penalty repeats.
80
+ - Several rules broken at once give the longest of their penalties.
81
+
82
+ ### `recovery-code`: `createRecoveryCodes(count = 10)`, `normalizeRecoveryCode(code)`
83
+
84
+ Codes like `7KQM-W3HD-9TXA` (about 59 bits each), from characters that can't be misread. Hash each one with
85
+ `hashOneTimeCode(normalizeRecoveryCode(code), { pepper, purpose: "recovery:<account id>" })`.
86
+
87
+ ### `email-contact`: `normalizeEmail(address)`, `emailLedgerForm(address)`
88
+
89
+ - `normalizeEmail` trims and lowercases, and throws for text that isn't an email address.
90
+ - `emailLedgerForm` also drops `+tags`, for the banned-contact ledger.
91
+
92
+ ## License
93
+
94
+ Sharadox Open Source License 0.1.0 (see `LICENSE.md`).
@@ -0,0 +1,11 @@
1
+ import type { BrokenRule } from "@sharadox/account-web-library/ban-length/type";
2
+ /**
3
+ * How long a ban lasts, from the rules it cites, so equal offenses get equal penalties:
4
+ * - each rule gives the penalty of its schedule for this offense (1st, 2nd…), and the last penalty repeats;
5
+ * - several rules broken at once give the longest of their penalties.
6
+ *
7
+ * @example
8
+ * banLength([{ schedule: [7 * 86_400, 30 * 86_400, "permanent"], previousOffenses: 1 }]); // 2_592_000 (30 days)
9
+ */
10
+ export declare function banLength(rules: BrokenRule[]): number | "permanent";
11
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../source/ban-length/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,+CAA+C,CAAC;AAEhF;;;;;;;GAOG;AACH,wBAAgB,SAAS,CAAC,KAAK,EAAE,UAAU,EAAE,GAAG,MAAM,GAAG,WAAW,CAQnE"}
@@ -0,0 +1,21 @@
1
+ /**
2
+ * How long a ban lasts, from the rules it cites, so equal offenses get equal penalties:
3
+ * - each rule gives the penalty of its schedule for this offense (1st, 2nd…), and the last penalty repeats;
4
+ * - several rules broken at once give the longest of their penalties.
5
+ *
6
+ * @example
7
+ * banLength([{ schedule: [7 * 86_400, 30 * 86_400, "permanent"], previousOffenses: 1 }]); // 2_592_000 (30 days)
8
+ */
9
+ export function banLength(rules) {
10
+ if (rules.length === 0)
11
+ throw new Error("a ban must cite at least one rule");
12
+ const penalties = rules.map(({ schedule, previousOffenses }) => {
13
+ if (schedule.length === 0)
14
+ throw new Error("a rule has no penalty");
15
+ return schedule[Math.min(previousOffenses, schedule.length - 1)];
16
+ });
17
+ if (penalties.includes("permanent"))
18
+ return "permanent";
19
+ return Math.max(...penalties);
20
+ }
21
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../source/ban-length/index.ts"],"names":[],"mappings":"AAEA;;;;;;;GAOG;AACH,MAAM,UAAU,SAAS,CAAC,KAAmB;IAC3C,IAAI,KAAK,CAAC,MAAM,KAAK,CAAC;QAAE,MAAM,IAAI,KAAK,CAAC,mCAAmC,CAAC,CAAC;IAC7E,MAAM,SAAS,GAAG,KAAK,CAAC,GAAG,CAAC,CAAC,EAAE,QAAQ,EAAE,gBAAgB,EAAE,EAAE,EAAE;QAC7D,IAAI,QAAQ,CAAC,MAAM,KAAK,CAAC;YAAE,MAAM,IAAI,KAAK,CAAC,uBAAuB,CAAC,CAAC;QACpE,OAAO,QAAQ,CAAC,IAAI,CAAC,GAAG,CAAC,gBAAgB,EAAE,QAAQ,CAAC,MAAM,GAAG,CAAC,CAAC,CAAE,CAAC;IACpE,CAAC,CAAC,CAAC;IACH,IAAI,SAAS,CAAC,QAAQ,CAAC,WAAW,CAAC;QAAE,OAAO,WAAW,CAAC;IACxD,OAAO,IAAI,CAAC,GAAG,CAAC,GAAI,SAAsB,CAAC,CAAC;AAC9C,CAAC"}
@@ -0,0 +1,8 @@
1
+ /** A rule's penalties for the 1st, 2nd, 3rd… offense: seconds, or "permanent". The last one repeats. */
2
+ export type PenaltySchedule = Array<number | "permanent">;
3
+ /** One broken rule: its schedule and how many times the account broke it before (in that application). */
4
+ export interface BrokenRule {
5
+ schedule: PenaltySchedule;
6
+ previousOffenses: number;
7
+ }
8
+ //# sourceMappingURL=type.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"type.d.ts","sourceRoot":"","sources":["../../source/ban-length/type.ts"],"names":[],"mappings":"AAAA,wGAAwG;AACxG,MAAM,MAAM,eAAe,GAAG,KAAK,CAAC,MAAM,GAAG,WAAW,CAAC,CAAC;AAE1D,0GAA0G;AAC1G,MAAM,WAAW,UAAU;IACzB,QAAQ,EAAE,eAAe,CAAC;IAC1B,gBAAgB,EAAE,MAAM,CAAC;CAC1B"}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=type.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"type.js","sourceRoot":"","sources":["../../source/ban-length/type.ts"],"names":[],"mappings":""}
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Bytes as RFC 4648 base 32, without padding: how authenticator apps take a two-factor secret.
3
+ *
4
+ * @example
5
+ * encodeBase32(new TextEncoder().encode("foobar")); // "MZXW6YTBOI"
6
+ */
7
+ export declare function encodeBase32(bytes: Uint8Array): string;
8
+ /**
9
+ * Base 32 back to bytes, forgiving how people type it: lowercase, spaces and `=` padding are fine. Throws on any
10
+ * other character.
11
+ *
12
+ * @example
13
+ * decodeBase32("mzxw 6ytb oi"); // the bytes of "foobar"
14
+ */
15
+ export declare function decodeBase32(text: string): Uint8Array;
16
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../source/base-32/index.ts"],"names":[],"mappings":"AAGA;;;;;GAKG;AACH,wBAAgB,YAAY,CAAC,KAAK,EAAE,UAAU,GAAG,MAAM,CActD;AAED;;;;;;GAMG;AACH,wBAAgB,YAAY,CAAC,IAAI,EAAE,MAAM,GAAG,UAAU,CAgBrD"}
@@ -0,0 +1,50 @@
1
+ /** RFC 4648's base 32 alphabet. */
2
+ const ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
3
+ /**
4
+ * Bytes as RFC 4648 base 32, without padding: how authenticator apps take a two-factor secret.
5
+ *
6
+ * @example
7
+ * encodeBase32(new TextEncoder().encode("foobar")); // "MZXW6YTBOI"
8
+ */
9
+ export function encodeBase32(bytes) {
10
+ let bits = 0;
11
+ let value = 0;
12
+ let output = "";
13
+ for (const byte of bytes) {
14
+ value = (value << 8) | byte;
15
+ bits += 8;
16
+ while (bits >= 5) {
17
+ output += ALPHABET[(value >>> (bits - 5)) & 31];
18
+ bits -= 5;
19
+ }
20
+ }
21
+ if (bits > 0)
22
+ output += ALPHABET[(value << (5 - bits)) & 31];
23
+ return output;
24
+ }
25
+ /**
26
+ * Base 32 back to bytes, forgiving how people type it: lowercase, spaces and `=` padding are fine. Throws on any
27
+ * other character.
28
+ *
29
+ * @example
30
+ * decodeBase32("mzxw 6ytb oi"); // the bytes of "foobar"
31
+ */
32
+ export function decodeBase32(text) {
33
+ const clean = text.toUpperCase().replace(/[\s=]/g, "");
34
+ let bits = 0;
35
+ let value = 0;
36
+ const output = [];
37
+ for (const character of clean) {
38
+ const index = ALPHABET.indexOf(character);
39
+ if (index === -1)
40
+ throw new Error(`"${character}" is not base 32`);
41
+ value = (value << 5) | index;
42
+ bits += 5;
43
+ if (bits >= 8) {
44
+ output.push((value >>> (bits - 8)) & 255);
45
+ bits -= 8;
46
+ }
47
+ }
48
+ return new Uint8Array(output);
49
+ }
50
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../source/base-32/index.ts"],"names":[],"mappings":"AAAA,mCAAmC;AACnC,MAAM,QAAQ,GAAG,kCAAkC,CAAC;AAEpD;;;;;GAKG;AACH,MAAM,UAAU,YAAY,CAAC,KAAiB;IAC5C,IAAI,IAAI,GAAG,CAAC,CAAC;IACb,IAAI,KAAK,GAAG,CAAC,CAAC;IACd,IAAI,MAAM,GAAG,EAAE,CAAC;IAChB,KAAK,MAAM,IAAI,IAAI,KAAK,EAAE,CAAC;QACzB,KAAK,GAAG,CAAC,KAAK,IAAI,CAAC,CAAC,GAAG,IAAI,CAAC;QAC5B,IAAI,IAAI,CAAC,CAAC;QACV,OAAO,IAAI,IAAI,CAAC,EAAE,CAAC;YACjB,MAAM,IAAI,QAAQ,CAAC,CAAC,KAAK,KAAK,CAAC,IAAI,GAAG,CAAC,CAAC,CAAC,GAAG,EAAE,CAAC,CAAC;YAChD,IAAI,IAAI,CAAC,CAAC;QACZ,CAAC;IACH,CAAC;IACD,IAAI,IAAI,GAAG,CAAC;QAAE,MAAM,IAAI,QAAQ,CAAC,CAAC,KAAK,IAAI,CAAC,CAAC,GAAG,IAAI,CAAC,CAAC,GAAG,EAAE,CAAC,CAAC;IAC7D,OAAO,MAAM,CAAC;AAChB,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,YAAY,CAAC,IAAY;IACvC,MAAM,KAAK,GAAG,IAAI,CAAC,WAAW,EAAE,CAAC,OAAO,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAC;IACvD,IAAI,IAAI,GAAG,CAAC,CAAC;IACb,IAAI,KAAK,GAAG,CAAC,CAAC;IACd,MAAM,MAAM,GAAa,EAAE,CAAC;IAC5B,KAAK,MAAM,SAAS,IAAI,KAAK,EAAE,CAAC;QAC9B,MAAM,KAAK,GAAG,QAAQ,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC;QAC1C,IAAI,KAAK,KAAK,CAAC,CAAC;YAAE,MAAM,IAAI,KAAK,CAAC,IAAI,SAAS,kBAAkB,CAAC,CAAC;QACnE,KAAK,GAAG,CAAC,KAAK,IAAI,CAAC,CAAC,GAAG,KAAK,CAAC;QAC7B,IAAI,IAAI,CAAC,CAAC;QACV,IAAI,IAAI,IAAI,CAAC,EAAE,CAAC;YACd,MAAM,CAAC,IAAI,CAAC,CAAC,KAAK,KAAK,CAAC,IAAI,GAAG,CAAC,CAAC,CAAC,GAAG,GAAG,CAAC,CAAC;YAC1C,IAAI,IAAI,CAAC,CAAC;QACZ,CAAC;IACH,CAAC;IACD,OAAO,IAAI,UAAU,CAAC,MAAM,CAAC,CAAC;AAChC,CAAC"}
@@ -0,0 +1,16 @@
1
+ import type { EffectivePermissionsInput } from "@sharadox/account-web-library/effective-permissions/type";
2
+ /**
3
+ * What an account may do in one application, now. In order:
4
+ * 1. Active grants count: started, not ended, in this application or global, and for the whole application or this
5
+ * resource.
6
+ * 2. An active exclusive grant (a ban) leaves only the exclusive roles' permissions.
7
+ * 3. Otherwise the result is the default role plus every active role.
8
+ * 4. Only this application's permissions (`platform.…`) and the account system's own (`account.…`) are kept.
9
+ * 5. The result is limited to `scope` (a token or key) and to `ownerPermissions` (an agent).
10
+ *
11
+ * @example
12
+ * const permissions = effectivePermissions({ application: "platform", now: Date.now(), defaultRole, roles, grants });
13
+ * if (!permissions.has("platform.job.create")) return forbidden();
14
+ */
15
+ export declare function effectivePermissions({ application, resource, now, defaultRole, roles, grants, scope, ownerPermissions, }: EffectivePermissionsInput): Set<string>;
16
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../source/effective-permissions/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,yBAAyB,EAAS,MAAM,0DAA0D,CAAC;AAKjH;;;;;;;;;;;;GAYG;AACH,wBAAgB,oBAAoB,CAAC,EACnC,WAAW,EACX,QAAQ,EACR,GAAG,EACH,WAAW,EACX,KAAK,EACL,MAAM,EACN,KAAK,EACL,gBAAgB,GACjB,EAAE,yBAAyB,GAAG,GAAG,CAAC,MAAM,CAAC,CAiBzC"}
@@ -0,0 +1,31 @@
1
+ /** A permission the account system itself handles (`account.ban.read`, `account.data.export`…), in every application. */
2
+ const ACCOUNT_PERMISSION = "account.";
3
+ /**
4
+ * What an account may do in one application, now. In order:
5
+ * 1. Active grants count: started, not ended, in this application or global, and for the whole application or this
6
+ * resource.
7
+ * 2. An active exclusive grant (a ban) leaves only the exclusive roles' permissions.
8
+ * 3. Otherwise the result is the default role plus every active role.
9
+ * 4. Only this application's permissions (`platform.…`) and the account system's own (`account.…`) are kept.
10
+ * 5. The result is limited to `scope` (a token or key) and to `ownerPermissions` (an agent).
11
+ *
12
+ * @example
13
+ * const permissions = effectivePermissions({ application: "platform", now: Date.now(), defaultRole, roles, grants });
14
+ * if (!permissions.has("platform.job.create")) return forbidden();
15
+ */
16
+ export function effectivePermissions({ application, resource, now, defaultRole, roles, grants, scope, ownerPermissions, }) {
17
+ const byId = new Map(roles.map((role) => [role.id, role]));
18
+ const applies = (grant) => grant.startsAt <= now &&
19
+ (grant.endsAt === null || now < grant.endsAt) &&
20
+ (grant.application === null || grant.application === application) &&
21
+ (grant.resource === null || grant.resource === resource);
22
+ const active = grants.filter(applies).flatMap((grant) => byId.get(grant.roleId) ?? []);
23
+ const exclusive = active.filter((role) => role.exclusive);
24
+ const granted = exclusive.length > 0 ? exclusive : [defaultRole, ...active];
25
+ const permissions = new Set(granted
26
+ .flatMap((role) => role.permissions)
27
+ .filter((permission) => permission.startsWith(`${application}.`) || permission.startsWith(ACCOUNT_PERMISSION)));
28
+ const limits = [scope && new Set(scope), ownerPermissions].filter((limit) => limit !== undefined);
29
+ return new Set([...permissions].filter((permission) => limits.every((limit) => limit.has(permission))));
30
+ }
31
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../source/effective-permissions/index.ts"],"names":[],"mappings":"AAEA,yHAAyH;AACzH,MAAM,kBAAkB,GAAG,UAAU,CAAC;AAEtC;;;;;;;;;;;;GAYG;AACH,MAAM,UAAU,oBAAoB,CAAC,EACnC,WAAW,EACX,QAAQ,EACR,GAAG,EACH,WAAW,EACX,KAAK,EACL,MAAM,EACN,KAAK,EACL,gBAAgB,GACU;IAC1B,MAAM,IAAI,GAAG,IAAI,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC,IAAI,CAAC,EAAE,EAAE,IAAI,CAAC,CAAC,CAAC,CAAC;IAC3D,MAAM,OAAO,GAAG,CAAC,KAAY,EAAE,EAAE,CAC/B,KAAK,CAAC,QAAQ,IAAI,GAAG;QACrB,CAAC,KAAK,CAAC,MAAM,KAAK,IAAI,IAAI,GAAG,GAAG,KAAK,CAAC,MAAM,CAAC;QAC7C,CAAC,KAAK,CAAC,WAAW,KAAK,IAAI,IAAI,KAAK,CAAC,WAAW,KAAK,WAAW,CAAC;QACjE,CAAC,KAAK,CAAC,QAAQ,KAAK,IAAI,IAAI,KAAK,CAAC,QAAQ,KAAK,QAAQ,CAAC,CAAC;IAC3D,MAAM,MAAM,GAAG,MAAM,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,OAAO,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,MAAM,CAAC,IAAI,EAAE,CAAC,CAAC;IACvF,MAAM,SAAS,GAAG,MAAM,CAAC,MAAM,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;IAC1D,MAAM,OAAO,GAAG,SAAS,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,WAAW,EAAE,GAAG,MAAM,CAAC,CAAC;IAC5E,MAAM,WAAW,GAAG,IAAI,GAAG,CACzB,OAAO;SACJ,OAAO,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,WAAW,CAAC;SACnC,MAAM,CAAC,CAAC,UAAU,EAAE,EAAE,CAAC,UAAU,CAAC,UAAU,CAAC,GAAG,WAAW,GAAG,CAAC,IAAI,UAAU,CAAC,UAAU,CAAC,kBAAkB,CAAC,CAAC,CACjH,CAAC;IACF,MAAM,MAAM,GAAG,CAAC,KAAK,IAAI,IAAI,GAAG,CAAC,KAAK,CAAC,EAAE,gBAAgB,CAAC,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,KAAK,SAAS,CAAC,CAAC;IAClG,OAAO,IAAI,GAAG,CAAC,CAAC,GAAG,WAAW,CAAC,CAAC,MAAM,CAAC,CAAC,UAAU,EAAE,EAAE,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,CAAC;AAC1G,CAAC"}
@@ -0,0 +1,37 @@
1
+ /** A role: its application (`null` for every application), its permissions, and whether it is a ban (`exclusive`). */
2
+ export interface Role {
3
+ id: string;
4
+ application: string | null;
5
+ permissions: string[];
6
+ /** While active, the account has only this role's permissions in its application (how bans work). */
7
+ exclusive: boolean;
8
+ }
9
+ /** A role given to an account: in an application (or `null`, all), maybe for one resource, between two moments. */
10
+ export interface Grant {
11
+ roleId: string;
12
+ application: string | null;
13
+ /** `platform:project:42`, or `null` for the whole application. */
14
+ resource: string | null;
15
+ /** Milliseconds since 1970. */
16
+ startsAt: number;
17
+ /** Milliseconds since 1970, or `null` for permanent. */
18
+ endsAt: number | null;
19
+ }
20
+ export interface EffectivePermissionsInput {
21
+ /** The application asking, for example `platform`; its permissions start with `platform.`. */
22
+ application: string;
23
+ /** The resource the action is on, for roles limited to one resource. */
24
+ resource?: string;
25
+ now: number;
26
+ /** The application's default role, which every account holds. */
27
+ defaultRole: Role;
28
+ /** Every role that may be granted. */
29
+ roles: Role[];
30
+ /** The account's grants. */
31
+ grants: Grant[];
32
+ /** A token's or key's scope: at most these. */
33
+ scope?: string[];
34
+ /** An agent's owner's effective permissions: at most these. */
35
+ ownerPermissions?: Set<string>;
36
+ }
37
+ //# sourceMappingURL=type.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"type.d.ts","sourceRoot":"","sources":["../../source/effective-permissions/type.ts"],"names":[],"mappings":"AAAA,sHAAsH;AACtH,MAAM,WAAW,IAAI;IACnB,EAAE,EAAE,MAAM,CAAC;IACX,WAAW,EAAE,MAAM,GAAG,IAAI,CAAC;IAC3B,WAAW,EAAE,MAAM,EAAE,CAAC;IACtB,qGAAqG;IACrG,SAAS,EAAE,OAAO,CAAC;CACpB;AAED,mHAAmH;AACnH,MAAM,WAAW,KAAK;IACpB,MAAM,EAAE,MAAM,CAAC;IACf,WAAW,EAAE,MAAM,GAAG,IAAI,CAAC;IAC3B,kEAAkE;IAClE,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAC;IACxB,+BAA+B;IAC/B,QAAQ,EAAE,MAAM,CAAC;IACjB,wDAAwD;IACxD,MAAM,EAAE,MAAM,GAAG,IAAI,CAAC;CACvB;AAED,MAAM,WAAW,yBAAyB;IACxC,8FAA8F;IAC9F,WAAW,EAAE,MAAM,CAAC;IACpB,wEAAwE;IACxE,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,GAAG,EAAE,MAAM,CAAC;IACZ,iEAAiE;IACjE,WAAW,EAAE,IAAI,CAAC;IAClB,sCAAsC;IACtC,KAAK,EAAE,IAAI,EAAE,CAAC;IACd,4BAA4B;IAC5B,MAAM,EAAE,KAAK,EAAE,CAAC;IAChB,+CAA+C;IAC/C,KAAK,CAAC,EAAE,MAAM,EAAE,CAAC;IACjB,+DAA+D;IAC/D,gBAAgB,CAAC,EAAE,GAAG,CAAC,MAAM,CAAC,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/effective-permissions/type.ts"],"names":[],"mappings":""}
@@ -0,0 +1,17 @@
1
+ /**
2
+ * An email contact in the one form it is stored and compared in: trimmed and lowercase. Throws for text that isn't
3
+ * an email address.
4
+ *
5
+ * @example
6
+ * normalizeEmail(" Luis@Example.com "); // "luis@example.com"
7
+ */
8
+ export declare function normalizeEmail(address: string): string;
9
+ /**
10
+ * The form a banned email takes in the ban ledger: normalized, and without a `+tag`, so `name+1@…` can't stand in
11
+ * for a banned `name@…`.
12
+ *
13
+ * @example
14
+ * emailLedgerForm("Luis+Shop@Example.com"); // "luis@example.com"
15
+ */
16
+ export declare function emailLedgerForm(address: string): string;
17
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../source/email-contact/index.ts"],"names":[],"mappings":"AAGA;;;;;;GAMG;AACH,wBAAgB,cAAc,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,CAItD;AAED;;;;;;GAMG;AACH,wBAAgB,eAAe,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,CAGvD"}
@@ -0,0 +1,27 @@
1
+ /** One `@`, something either side, no spaces: the shape, not deliverability (the one-time code proves that). */
2
+ const SHAPE = /^[^\s@]+@[^\s@]+$/;
3
+ /**
4
+ * An email contact in the one form it is stored and compared in: trimmed and lowercase. Throws for text that isn't
5
+ * an email address.
6
+ *
7
+ * @example
8
+ * normalizeEmail(" Luis@Example.com "); // "luis@example.com"
9
+ */
10
+ export function normalizeEmail(address) {
11
+ const normalized = address.trim().toLowerCase();
12
+ if (!SHAPE.test(normalized))
13
+ throw new Error("this is not an email address");
14
+ return normalized;
15
+ }
16
+ /**
17
+ * The form a banned email takes in the ban ledger: normalized, and without a `+tag`, so `name+1@…` can't stand in
18
+ * for a banned `name@…`.
19
+ *
20
+ * @example
21
+ * emailLedgerForm("Luis+Shop@Example.com"); // "luis@example.com"
22
+ */
23
+ export function emailLedgerForm(address) {
24
+ const [local, domain] = normalizeEmail(address).split("@");
25
+ return `${local.split("+")[0]}@${domain}`;
26
+ }
27
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../source/email-contact/index.ts"],"names":[],"mappings":"AAAA,gHAAgH;AAChH,MAAM,KAAK,GAAG,mBAAmB,CAAC;AAElC;;;;;;GAMG;AACH,MAAM,UAAU,cAAc,CAAC,OAAe;IAC5C,MAAM,UAAU,GAAG,OAAO,CAAC,IAAI,EAAE,CAAC,WAAW,EAAE,CAAC;IAChD,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,UAAU,CAAC;QAAE,MAAM,IAAI,KAAK,CAAC,8BAA8B,CAAC,CAAC;IAC7E,OAAO,UAAU,CAAC;AACpB,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,eAAe,CAAC,OAAe;IAC7C,MAAM,CAAC,KAAK,EAAE,MAAM,CAAC,GAAG,cAAc,CAAC,OAAO,CAAC,CAAC,KAAK,CAAC,GAAG,CAAqB,CAAC;IAC/E,OAAO,GAAG,KAAK,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,IAAI,MAAM,EAAE,CAAC;AAC5C,CAAC"}
@@ -0,0 +1,26 @@
1
+ import type { OneTimeCodeHashOptions } from "@sharadox/account-web-library/one-time-code/type";
2
+ /**
3
+ * A new one-time code: `length` digits (8 by default, one in a hundred million), each drawn uniformly by the
4
+ * operating system's secure random source. Send it to the contact; store only `hashOneTimeCode`.
5
+ *
6
+ * @example
7
+ * const code = createOneTimeCode(); // "04718263"
8
+ */
9
+ export declare function createOneTimeCode(length?: number): string;
10
+ /**
11
+ * What is stored instead of the code: HMAC-SHA-256 of the purpose and the code under a pepper kept outside the
12
+ * database. A leaked table gives nothing to try, and a code can't be used for another request or purpose.
13
+ *
14
+ * @example
15
+ * const codeHash = hashOneTimeCode(code, { pepper: process.env.ACCOUNT_PEPPER!, purpose: `sign-in:${request.id}` });
16
+ */
17
+ export declare function hashOneTimeCode(code: string, { pepper, purpose }: OneTimeCodeHashOptions): string;
18
+ /**
19
+ * Whether a typed code matches a stored hash (spaces ignored, compared in constant time). Count the attempt either
20
+ * way: after 5 wrong tries, the code is void.
21
+ *
22
+ * @example
23
+ * if (!matchesOneTimeCode(typed, request.codeHash, { pepper, purpose: `sign-in:${request.id}` })) await countFailure();
24
+ */
25
+ export declare function matchesOneTimeCode(code: string, hash: string, options: OneTimeCodeHashOptions): boolean;
26
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../source/one-time-code/index.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,kDAAkD,CAAC;AAE/F;;;;;;GAMG;AACH,wBAAgB,iBAAiB,CAAC,MAAM,SAAI,GAAG,MAAM,CAEpD;AAED;;;;;;GAMG;AACH,wBAAgB,eAAe,CAAC,IAAI,EAAE,MAAM,EAAE,EAAE,MAAM,EAAE,OAAO,EAAE,EAAE,sBAAsB,GAAG,MAAM,CAGjG;AAED;;;;;;GAMG;AACH,wBAAgB,kBAAkB,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,sBAAsB,GAAG,OAAO,CAIvG"}
@@ -0,0 +1,36 @@
1
+ import { createHmac, randomInt, timingSafeEqual } from "node:crypto";
2
+ /**
3
+ * A new one-time code: `length` digits (8 by default, one in a hundred million), each drawn uniformly by the
4
+ * operating system's secure random source. Send it to the contact; store only `hashOneTimeCode`.
5
+ *
6
+ * @example
7
+ * const code = createOneTimeCode(); // "04718263"
8
+ */
9
+ export function createOneTimeCode(length = 8) {
10
+ return Array.from({ length }, () => randomInt(10)).join("");
11
+ }
12
+ /**
13
+ * What is stored instead of the code: HMAC-SHA-256 of the purpose and the code under a pepper kept outside the
14
+ * database. A leaked table gives nothing to try, and a code can't be used for another request or purpose.
15
+ *
16
+ * @example
17
+ * const codeHash = hashOneTimeCode(code, { pepper: process.env.ACCOUNT_PEPPER!, purpose: `sign-in:${request.id}` });
18
+ */
19
+ export function hashOneTimeCode(code, { pepper, purpose }) {
20
+ if (pepper.length < 32)
21
+ throw new Error("the one-time code pepper must have at least 32 characters");
22
+ return createHmac("sha256", pepper).update(`${purpose}\n${code}`).digest("base64url");
23
+ }
24
+ /**
25
+ * Whether a typed code matches a stored hash (spaces ignored, compared in constant time). Count the attempt either
26
+ * way: after 5 wrong tries, the code is void.
27
+ *
28
+ * @example
29
+ * if (!matchesOneTimeCode(typed, request.codeHash, { pepper, purpose: `sign-in:${request.id}` })) await countFailure();
30
+ */
31
+ export function matchesOneTimeCode(code, hash, options) {
32
+ const expected = Buffer.from(hash);
33
+ const given = Buffer.from(hashOneTimeCode(code.replace(/\s/g, ""), options));
34
+ return expected.length === given.length && timingSafeEqual(expected, given);
35
+ }
36
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../source/one-time-code/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAGrE;;;;;;GAMG;AACH,MAAM,UAAU,iBAAiB,CAAC,MAAM,GAAG,CAAC;IAC1C,OAAO,KAAK,CAAC,IAAI,CAAC,EAAE,MAAM,EAAE,EAAE,GAAG,EAAE,CAAC,SAAS,CAAC,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;AAC9D,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,eAAe,CAAC,IAAY,EAAE,EAAE,MAAM,EAAE,OAAO,EAA0B;IACvF,IAAI,MAAM,CAAC,MAAM,GAAG,EAAE;QAAE,MAAM,IAAI,KAAK,CAAC,2DAA2D,CAAC,CAAC;IACrG,OAAO,UAAU,CAAC,QAAQ,EAAE,MAAM,CAAC,CAAC,MAAM,CAAC,GAAG,OAAO,KAAK,IAAI,EAAE,CAAC,CAAC,MAAM,CAAC,WAAW,CAAC,CAAC;AACxF,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,kBAAkB,CAAC,IAAY,EAAE,IAAY,EAAE,OAA+B;IAC5F,MAAM,QAAQ,GAAG,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IACnC,MAAM,KAAK,GAAG,MAAM,CAAC,IAAI,CAAC,eAAe,CAAC,IAAI,CAAC,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC,EAAE,OAAO,CAAC,CAAC,CAAC;IAC7E,OAAO,QAAQ,CAAC,MAAM,KAAK,KAAK,CAAC,MAAM,IAAI,eAAe,CAAC,QAAQ,EAAE,KAAK,CAAC,CAAC;AAC9E,CAAC"}
@@ -0,0 +1,6 @@
1
+ /** The secret pepper (at least 32 characters, from the environment) and what the code is for (`sign-in:<request id>`). */
2
+ export interface OneTimeCodeHashOptions {
3
+ pepper: string;
4
+ purpose: string;
5
+ }
6
+ //# sourceMappingURL=type.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"type.d.ts","sourceRoot":"","sources":["../../source/one-time-code/type.ts"],"names":[],"mappings":"AAAA,0HAA0H;AAC1H,MAAM,WAAW,sBAAsB;IACrC,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,EAAE,MAAM,CAAC;CACjB"}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=type.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"type.js","sourceRoot":"","sources":["../../source/one-time-code/type.ts"],"names":[],"mappings":""}
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Two-factor recovery codes, offered once two-factor is on: `count` codes (10 by default) like `7KQM-W3HD-9TXA`,
3
+ * about 59 bits each, single use. Show them once, and store each with `hashOneTimeCode(normalizeRecoveryCode(code),
4
+ * { pepper, purpose: "recovery:<account id>" })`. Making new ones voids the old ones.
5
+ *
6
+ * @example
7
+ * const codes = createRecoveryCodes();
8
+ */
9
+ export declare function createRecoveryCodes(count?: number): string[];
10
+ /**
11
+ * A recovery code however it was typed (case, spaces, hyphens), in the one form that is hashed.
12
+ *
13
+ * @example
14
+ * normalizeRecoveryCode(" 7kqm w3hd-9txa "); // "7KQMW3HD9TXA"
15
+ */
16
+ export declare function normalizeRecoveryCode(code: string): string;
17
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../source/recovery-code/index.ts"],"names":[],"mappings":"AAOA;;;;;;;GAOG;AACH,wBAAgB,mBAAmB,CAAC,KAAK,SAAK,GAAG,MAAM,EAAE,CAIxD;AAED;;;;;GAKG;AACH,wBAAgB,qBAAqB,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAE1D"}
@@ -0,0 +1,28 @@
1
+ import { randomInt } from "node:crypto";
2
+ /** Digits and capitals without 0/O, 1/I/L and U: nothing to misread when typing a code back. */
3
+ const ALPHABET = "23456789ABCDEFGHJKMNPQRSTVWXYZ";
4
+ const group = () => Array.from({ length: 4 }, () => ALPHABET[randomInt(ALPHABET.length)]).join("");
5
+ /**
6
+ * Two-factor recovery codes, offered once two-factor is on: `count` codes (10 by default) like `7KQM-W3HD-9TXA`,
7
+ * about 59 bits each, single use. Show them once, and store each with `hashOneTimeCode(normalizeRecoveryCode(code),
8
+ * { pepper, purpose: "recovery:<account id>" })`. Making new ones voids the old ones.
9
+ *
10
+ * @example
11
+ * const codes = createRecoveryCodes();
12
+ */
13
+ export function createRecoveryCodes(count = 10) {
14
+ const codes = new Set();
15
+ while (codes.size < count)
16
+ codes.add(`${group()}-${group()}-${group()}`);
17
+ return [...codes];
18
+ }
19
+ /**
20
+ * A recovery code however it was typed (case, spaces, hyphens), in the one form that is hashed.
21
+ *
22
+ * @example
23
+ * normalizeRecoveryCode(" 7kqm w3hd-9txa "); // "7KQMW3HD9TXA"
24
+ */
25
+ export function normalizeRecoveryCode(code) {
26
+ return code.toUpperCase().replace(/[\s-]/g, "");
27
+ }
28
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../source/recovery-code/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAExC,gGAAgG;AAChG,MAAM,QAAQ,GAAG,gCAAgC,CAAC;AAElD,MAAM,KAAK,GAAG,GAAG,EAAE,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,EAAE,GAAG,EAAE,CAAC,QAAQ,CAAC,SAAS,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;AAEnG;;;;;;;GAOG;AACH,MAAM,UAAU,mBAAmB,CAAC,KAAK,GAAG,EAAE;IAC5C,MAAM,KAAK,GAAG,IAAI,GAAG,EAAU,CAAC;IAChC,OAAO,KAAK,CAAC,IAAI,GAAG,KAAK;QAAE,KAAK,CAAC,GAAG,CAAC,GAAG,KAAK,EAAE,IAAI,KAAK,EAAE,IAAI,KAAK,EAAE,EAAE,CAAC,CAAC;IACzE,OAAO,CAAC,GAAG,KAAK,CAAC,CAAC;AACpB,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,qBAAqB,CAAC,IAAY;IAChD,OAAO,IAAI,CAAC,WAAW,EAAE,CAAC,OAAO,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAC;AAClD,CAAC"}
@@ -0,0 +1,35 @@
1
+ import type { TotpOptions, TotpUriOptions, TotpVerification, VerifyTotpOptions } from "@sharadox/account-web-library/totp/type";
2
+ /**
3
+ * The time-based one-time code (RFC 6238, SHA-1, as every authenticator app does it) for a moment in milliseconds.
4
+ *
5
+ * @example
6
+ * totpCode(secret, Date.now()); // "287082"
7
+ */
8
+ export declare function totpCode(secret: Uint8Array, now: number, { digits, period }?: TotpOptions): string;
9
+ /**
10
+ * Checks a code typed from an authenticator app. The current step and one either side are accepted, for clocks that
11
+ * drift. Comparison is constant-time. A step at or before `lastUsedStep` is refused, so a code someone saw can't be
12
+ * replayed. On success, store the returned `step`.
13
+ *
14
+ * @example
15
+ * const result = verifyTotp(secret, typed, Date.now(), { lastUsedStep: account.totpLastStep });
16
+ * if (result.valid) await saveLastStep(result.step);
17
+ */
18
+ export declare function verifyTotp(secret: Uint8Array, code: string, now: number, { digits, period, lastUsedStep }?: VerifyTotpOptions): TotpVerification;
19
+ /**
20
+ * A new two-factor secret: 20 random bytes (160 bits, as RFC 4226 recommends). Store it encrypted.
21
+ *
22
+ * @example
23
+ * const secret = createTotpSecret();
24
+ */
25
+ export declare function createTotpSecret(): Uint8Array;
26
+ /**
27
+ * The `otpauth://totp/…` address an authenticator app adds an account from. Show it as a QR code, and show the
28
+ * `secret` parameter as text for people who type it in.
29
+ *
30
+ * @example
31
+ * totpUri({ issuer: "Luis Pires Decor", account: "luis-pires", secret });
32
+ * // "otpauth://totp/Luis%20Pires%20Decor:luis-pires?secret=…&issuer=Luis%20Pires%20Decor&algorithm=SHA1&digits=6&period=30"
33
+ */
34
+ export declare function totpUri({ issuer, account, secret }: TotpUriOptions): string;
35
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../source/totp/index.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EACV,WAAW,EACX,cAAc,EACd,gBAAgB,EAChB,iBAAiB,EAClB,MAAM,yCAAyC,CAAC;AAYjD;;;;;GAKG;AACH,wBAAgB,QAAQ,CAAC,MAAM,EAAE,UAAU,EAAE,GAAG,EAAE,MAAM,EAAE,EAAE,MAAU,EAAE,MAAW,EAAE,GAAE,WAAgB,GAAG,MAAM,CAE/G;AAED;;;;;;;;GAQG;AACH,wBAAgB,UAAU,CACxB,MAAM,EAAE,UAAU,EAClB,IAAI,EAAE,MAAM,EACZ,GAAG,EAAE,MAAM,EACX,EAAE,MAAU,EAAE,MAAW,EAAE,YAAiB,EAAE,GAAE,iBAAsB,GACrE,gBAAgB,CASlB;AAED;;;;;GAKG;AACH,wBAAgB,gBAAgB,IAAI,UAAU,CAE7C;AAED;;;;;;;GAOG;AACH,wBAAgB,OAAO,CAAC,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,EAAE,cAAc,GAAG,MAAM,CAU3E"}
@@ -0,0 +1,70 @@
1
+ import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
2
+ import { encodeBase32 } from "@sharadox/account-web-library/base-32";
3
+ /** The code for one time step (RFC 4226 HOTP with SHA-1, dynamic truncation). */
4
+ function codeForStep(secret, step, digits) {
5
+ const counter = Buffer.alloc(8);
6
+ counter.writeBigUInt64BE(BigInt(step));
7
+ const hash = createHmac("sha1", secret).update(counter).digest();
8
+ const offset = hash[hash.length - 1] & 0xf;
9
+ const binary = hash.readUInt32BE(offset) & 0x7fffffff;
10
+ return String(binary % 10 ** digits).padStart(digits, "0");
11
+ }
12
+ /**
13
+ * The time-based one-time code (RFC 6238, SHA-1, as every authenticator app does it) for a moment in milliseconds.
14
+ *
15
+ * @example
16
+ * totpCode(secret, Date.now()); // "287082"
17
+ */
18
+ export function totpCode(secret, now, { digits = 6, period = 30 } = {}) {
19
+ return codeForStep(secret, Math.floor(now / (period * 1000)), digits);
20
+ }
21
+ /**
22
+ * Checks a code typed from an authenticator app. The current step and one either side are accepted, for clocks that
23
+ * drift. Comparison is constant-time. A step at or before `lastUsedStep` is refused, so a code someone saw can't be
24
+ * replayed. On success, store the returned `step`.
25
+ *
26
+ * @example
27
+ * const result = verifyTotp(secret, typed, Date.now(), { lastUsedStep: account.totpLastStep });
28
+ * if (result.valid) await saveLastStep(result.step);
29
+ */
30
+ export function verifyTotp(secret, code, now, { digits = 6, period = 30, lastUsedStep = -1 } = {}) {
31
+ if (!new RegExp(`^\\d{${digits}}$`).test(code))
32
+ return { valid: false };
33
+ const current = Math.floor(now / (period * 1000));
34
+ for (const step of [current - 1, current, current + 1]) {
35
+ if (step <= lastUsedStep)
36
+ continue;
37
+ if (timingSafeEqual(Buffer.from(codeForStep(secret, step, digits)), Buffer.from(code)))
38
+ return { valid: true, step };
39
+ }
40
+ return { valid: false };
41
+ }
42
+ /**
43
+ * A new two-factor secret: 20 random bytes (160 bits, as RFC 4226 recommends). Store it encrypted.
44
+ *
45
+ * @example
46
+ * const secret = createTotpSecret();
47
+ */
48
+ export function createTotpSecret() {
49
+ return new Uint8Array(randomBytes(20));
50
+ }
51
+ /**
52
+ * The `otpauth://totp/…` address an authenticator app adds an account from. Show it as a QR code, and show the
53
+ * `secret` parameter as text for people who type it in.
54
+ *
55
+ * @example
56
+ * totpUri({ issuer: "Luis Pires Decor", account: "luis-pires", secret });
57
+ * // "otpauth://totp/Luis%20Pires%20Decor:luis-pires?secret=…&issuer=Luis%20Pires%20Decor&algorithm=SHA1&digits=6&period=30"
58
+ */
59
+ export function totpUri({ issuer, account, secret }) {
60
+ const label = `${encodeURIComponent(issuer)}:${encodeURIComponent(account)}`;
61
+ const parameters = new URLSearchParams({
62
+ secret: encodeBase32(secret),
63
+ issuer,
64
+ algorithm: "SHA1",
65
+ digits: "6",
66
+ period: "30",
67
+ });
68
+ return `otpauth://totp/${label}?${parameters.toString().replace(/\+/g, "%20")}`;
69
+ }
70
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../source/totp/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AACvE,OAAO,EAAE,YAAY,EAAE,MAAM,uCAAuC,CAAC;AAQrE,iFAAiF;AACjF,SAAS,WAAW,CAAC,MAAkB,EAAE,IAAY,EAAE,MAAc;IACnE,MAAM,OAAO,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;IAChC,OAAO,CAAC,gBAAgB,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC;IACvC,MAAM,IAAI,GAAG,UAAU,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,MAAM,EAAE,CAAC;IACjE,MAAM,MAAM,GAAG,IAAI,CAAC,IAAI,CAAC,MAAM,GAAG,CAAC,CAAE,GAAG,GAAG,CAAC;IAC5C,MAAM,MAAM,GAAG,IAAI,CAAC,YAAY,CAAC,MAAM,CAAC,GAAG,UAAU,CAAC;IACtD,OAAO,MAAM,CAAC,MAAM,GAAG,EAAE,IAAI,MAAM,CAAC,CAAC,QAAQ,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;AAC7D,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,QAAQ,CAAC,MAAkB,EAAE,GAAW,EAAE,EAAE,MAAM,GAAG,CAAC,EAAE,MAAM,GAAG,EAAE,KAAkB,EAAE;IACrG,OAAO,WAAW,CAAC,MAAM,EAAE,IAAI,CAAC,KAAK,CAAC,GAAG,GAAG,CAAC,MAAM,GAAG,IAAI,CAAC,CAAC,EAAE,MAAM,CAAC,CAAC;AACxE,CAAC;AAED;;;;;;;;GAQG;AACH,MAAM,UAAU,UAAU,CACxB,MAAkB,EAClB,IAAY,EACZ,GAAW,EACX,EAAE,MAAM,GAAG,CAAC,EAAE,MAAM,GAAG,EAAE,EAAE,YAAY,GAAG,CAAC,CAAC,KAAwB,EAAE;IAEtE,IAAI,CAAC,IAAI,MAAM,CAAC,QAAQ,MAAM,IAAI,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC;QAAE,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC;IACxE,MAAM,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,GAAG,CAAC,MAAM,GAAG,IAAI,CAAC,CAAC,CAAC;IAClD,KAAK,MAAM,IAAI,IAAI,CAAC,OAAO,GAAG,CAAC,EAAE,OAAO,EAAE,OAAO,GAAG,CAAC,CAAC,EAAE,CAAC;QACvD,IAAI,IAAI,IAAI,YAAY;YAAE,SAAS;QACnC,IAAI,eAAe,CAAC,MAAM,CAAC,IAAI,CAAC,WAAW,CAAC,MAAM,EAAE,IAAI,EAAE,MAAM,CAAC,CAAC,EAAE,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;YACpF,OAAO,EAAE,KAAK,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC;IACjC,CAAC;IACD,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC;AAC1B,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,gBAAgB;IAC9B,OAAO,IAAI,UAAU,CAAC,WAAW,CAAC,EAAE,CAAC,CAAC,CAAC;AACzC,CAAC;AAED;;;;;;;GAOG;AACH,MAAM,UAAU,OAAO,CAAC,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAkB;IACjE,MAAM,KAAK,GAAG,GAAG,kBAAkB,CAAC,MAAM,CAAC,IAAI,kBAAkB,CAAC,OAAO,CAAC,EAAE,CAAC;IAC7E,MAAM,UAAU,GAAG,IAAI,eAAe,CAAC;QACrC,MAAM,EAAE,YAAY,CAAC,MAAM,CAAC;QAC5B,MAAM;QACN,SAAS,EAAE,MAAM;QACjB,MAAM,EAAE,GAAG;QACX,MAAM,EAAE,IAAI;KACb,CAAC,CAAC;IACH,OAAO,kBAAkB,KAAK,IAAI,UAAU,CAAC,QAAQ,EAAE,CAAC,OAAO,CAAC,KAAK,EAAE,KAAK,CAAC,EAAE,CAAC;AAClF,CAAC"}
@@ -0,0 +1,25 @@
1
+ /** Code length (6, what authenticator apps show) and step length in seconds (30). */
2
+ export interface TotpOptions {
3
+ digits?: number;
4
+ period?: number;
5
+ }
6
+ /** Verification also takes the step of the last accepted code, so it can't be used twice. */
7
+ export interface VerifyTotpOptions extends TotpOptions {
8
+ lastUsedStep?: number;
9
+ }
10
+ /** A valid code (store `step` as the new last used step), or not. */
11
+ export type TotpVerification = {
12
+ valid: true;
13
+ step: number;
14
+ } | {
15
+ valid: false;
16
+ };
17
+ /** What the otpauth address shows in the authenticator app. */
18
+ export interface TotpUriOptions {
19
+ /** The company, shown above the code. */
20
+ issuer: string;
21
+ /** Which account: the username. */
22
+ account: string;
23
+ secret: Uint8Array;
24
+ }
25
+ //# sourceMappingURL=type.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"type.d.ts","sourceRoot":"","sources":["../../source/totp/type.ts"],"names":[],"mappings":"AAAA,qFAAqF;AACrF,MAAM,WAAW,WAAW;IAC1B,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB;AAED,6FAA6F;AAC7F,MAAM,WAAW,iBAAkB,SAAQ,WAAW;IACpD,YAAY,CAAC,EAAE,MAAM,CAAC;CACvB;AAED,qEAAqE;AACrE,MAAM,MAAM,gBAAgB,GAAG;IAAE,KAAK,EAAE,IAAI,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,GAAG;IAAE,KAAK,EAAE,KAAK,CAAA;CAAE,CAAC;AAEhF,+DAA+D;AAC/D,MAAM,WAAW,cAAc;IAC7B,yCAAyC;IACzC,MAAM,EAAE,MAAM,CAAC;IACf,mCAAmC;IACnC,OAAO,EAAE,MAAM,CAAC;IAChB,MAAM,EAAE,UAAU,CAAC;CACpB"}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=type.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"type.js","sourceRoot":"","sources":["../../source/totp/type.ts"],"names":[],"mappings":""}
@@ -0,0 +1,23 @@
1
+ import type { UsernameCheck } from "@sharadox/account-web-library/username/type";
2
+ /** The longest username. */
3
+ export declare const USERNAME_MAXIMUM_LENGTH = 50;
4
+ /**
5
+ * Checks a username against the rules:
6
+ * - 1 to 50 characters;
7
+ * - only A–Z, a–z and 0–9, with `-`, `_` or `.` allowed only between letters or digits, never two in a row;
8
+ * - shown as written, unique without regard to case (see `usernameKey`).
9
+ *
10
+ * @example
11
+ * checkUsername("Luis-Pires"); // { valid: true, username: "Luis-Pires", key: "luis-pires" }
12
+ * checkUsername("a--b"); // { valid: false, reason: "characters" }
13
+ */
14
+ export declare function checkUsername(username: string): UsernameCheck;
15
+ /**
16
+ * The form a username is unique in: lowercase, so `abc` and `aBc` are the same username (the database's unique index
17
+ * is on this key).
18
+ *
19
+ * @example
20
+ * usernameKey("aBc"); // "abc"
21
+ */
22
+ export declare function usernameKey(username: string): string;
23
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../source/username/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,6CAA6C,CAAC;AAKjF,4BAA4B;AAC5B,eAAO,MAAM,uBAAuB,KAAK,CAAC;AAE1C;;;;;;;;;GASG;AACH,wBAAgB,aAAa,CAAC,QAAQ,EAAE,MAAM,GAAG,aAAa,CAI7D;AAED;;;;;;GAMG;AACH,wBAAgB,WAAW,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM,CAEpD"}
@@ -0,0 +1,32 @@
1
+ /** Letters and digits, with single `-`, `_` or `.` only between them. */
2
+ const PATTERN = /^[A-Za-z0-9]+(?:[-_.][A-Za-z0-9]+)*$/;
3
+ /** The longest username. */
4
+ export const USERNAME_MAXIMUM_LENGTH = 50;
5
+ /**
6
+ * Checks a username against the rules:
7
+ * - 1 to 50 characters;
8
+ * - only A–Z, a–z and 0–9, with `-`, `_` or `.` allowed only between letters or digits, never two in a row;
9
+ * - shown as written, unique without regard to case (see `usernameKey`).
10
+ *
11
+ * @example
12
+ * checkUsername("Luis-Pires"); // { valid: true, username: "Luis-Pires", key: "luis-pires" }
13
+ * checkUsername("a--b"); // { valid: false, reason: "characters" }
14
+ */
15
+ export function checkUsername(username) {
16
+ if (username.length < 1 || username.length > USERNAME_MAXIMUM_LENGTH)
17
+ return { valid: false, reason: "length" };
18
+ if (!PATTERN.test(username))
19
+ return { valid: false, reason: "characters" };
20
+ return { valid: true, username, key: usernameKey(username) };
21
+ }
22
+ /**
23
+ * The form a username is unique in: lowercase, so `abc` and `aBc` are the same username (the database's unique index
24
+ * is on this key).
25
+ *
26
+ * @example
27
+ * usernameKey("aBc"); // "abc"
28
+ */
29
+ export function usernameKey(username) {
30
+ return username.toLowerCase();
31
+ }
32
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../source/username/index.ts"],"names":[],"mappings":"AAEA,yEAAyE;AACzE,MAAM,OAAO,GAAG,sCAAsC,CAAC;AAEvD,4BAA4B;AAC5B,MAAM,CAAC,MAAM,uBAAuB,GAAG,EAAE,CAAC;AAE1C;;;;;;;;;GASG;AACH,MAAM,UAAU,aAAa,CAAC,QAAgB;IAC5C,IAAI,QAAQ,CAAC,MAAM,GAAG,CAAC,IAAI,QAAQ,CAAC,MAAM,GAAG,uBAAuB;QAAE,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,MAAM,EAAE,QAAQ,EAAE,CAAC;IAChH,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,QAAQ,CAAC;QAAE,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,MAAM,EAAE,YAAY,EAAE,CAAC;IAC3E,OAAO,EAAE,KAAK,EAAE,IAAI,EAAE,QAAQ,EAAE,GAAG,EAAE,WAAW,CAAC,QAAQ,CAAC,EAAE,CAAC;AAC/D,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,WAAW,CAAC,QAAgB;IAC1C,OAAO,QAAQ,CAAC,WAAW,EAAE,CAAC;AAChC,CAAC"}
@@ -0,0 +1,10 @@
1
+ /** A username that follows the rules (with its `key` for uniqueness), or why not. */
2
+ export type UsernameCheck = {
3
+ valid: true;
4
+ username: string;
5
+ key: string;
6
+ } | {
7
+ valid: false;
8
+ reason: "length" | "characters";
9
+ };
10
+ //# sourceMappingURL=type.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"type.d.ts","sourceRoot":"","sources":["../../source/username/type.ts"],"names":[],"mappings":"AAAA,qFAAqF;AACrF,MAAM,MAAM,aAAa,GACvB;IAAE,KAAK,EAAE,IAAI,CAAC;IAAC,QAAQ,EAAE,MAAM,CAAC;IAAC,GAAG,EAAE,MAAM,CAAA;CAAE,GAAG;IAAE,KAAK,EAAE,KAAK,CAAC;IAAC,MAAM,EAAE,QAAQ,GAAG,YAAY,CAAA;CAAE,CAAC"}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=type.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"type.js","sourceRoot":"","sources":["../../source/username/type.ts"],"names":[],"mappings":""}
package/package.json CHANGED
@@ -1,6 +1,90 @@
1
1
  {
2
2
  "name": "@sharadox/account-web-library",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0-development.3",
4
+ "description": "Passwordless accounts for web applications: one-time codes, two-factor, roles, bans and OpenID Connect for people and agents.",
5
+ "private": false,
6
+ "license": "SEE LICENSE IN LICENCA.md",
7
+ "author": "Sharadox <contact@sharadox.com>",
8
+ "type": "module",
9
+ "exports": {
10
+ "./*/type": {
11
+ "sharadox-source": "./source/*/type.ts",
12
+ "types": "./distribution/*/type.d.ts"
13
+ },
14
+ "./*": {
15
+ "sharadox-source": [
16
+ "./source/*/index.ts"
17
+ ],
18
+ "types": "./distribution/*/index.d.ts",
19
+ "default": "./distribution/*/index.js"
20
+ }
21
+ },
22
+ "files": [
23
+ "distribution",
24
+ "LICENCA.md",
25
+ "LICENSE.md",
26
+ "NOTICE.md"
27
+ ],
28
+ "sideEffects": false,
29
+ "engines": {
30
+ "node": ">=26"
31
+ },
32
+ "publishConfig": {
33
+ "access": "public"
34
+ },
35
+ "lint-staged": {
36
+ "*.{ts,js,mjs,cjs}": [
37
+ "prettier --write",
38
+ "eslint --fix --max-warnings=0"
39
+ ],
40
+ "*.{json,md,yml,yaml}": "prettier --write"
41
+ },
42
+ "dependencies": {
43
+ "@sharadox/web-library": "^0.11.1"
44
+ },
45
+ "devDependencies": {
46
+ "@sharadox/es-lint-configuration-web-library": "^0.1.3",
47
+ "@sharadox/library-build-web-library": "^0.2.1",
48
+ "@sharadox/prettier-configuration-web-library": "^0.1.2",
49
+ "@sharadox/turborepo-configuration-web-library": "^0.1.4",
50
+ "@sharadox/type-script-configuration-web-library": "^0.2.3",
51
+ "@sharadox/vitest-configuration-web-library": "^0.2.1",
52
+ "@types/node": "^26.6.6",
53
+ "@vitest/coverage-v8": "^5.1.1",
54
+ "eslint": "9.39.5",
55
+ "happy-dom": "^21.0.4",
56
+ "husky": "^9.1.7",
57
+ "lint-staged": "^17.6.2",
58
+ "prettier": "^3.10.1",
59
+ "turbo": "^2.11.13",
60
+ "typedoc": "^0.28.20",
61
+ "typescript": "6.0.3",
62
+ "vitest": "^5.1.1"
63
+ },
64
+ "repository": {
65
+ "type": "git",
66
+ "url": "git+https://github.com/Sharadox/account-web-library.git"
67
+ },
68
+ "homepage": "https://github.com/Sharadox/account-web-library#readme",
69
+ "keywords": [
70
+ "authentication",
71
+ "authorization",
72
+ "passwordless",
73
+ "one-time-code",
74
+ "totp",
75
+ "openid-connect",
76
+ "oauth",
77
+ "roles"
78
+ ],
79
+ "scripts": {
80
+ "build": "library-build",
81
+ "lint": "eslint --max-warnings=0 .",
82
+ "format": "prettier --write .",
83
+ "format:check": "prettier --check .",
84
+ "type-check": "tsc --noEmit",
85
+ "test:unit": "vitest run --coverage",
86
+ "test:benchmark": "vitest bench --run --passWithNoTests",
87
+ "documentation": "typedoc",
88
+ "verify": "turbo run format:check lint type-check test:unit test:benchmark build"
89
+ }
6
90
  }