@authyon/auth 0.1.5 → 0.2.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 MutualPay
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,158 +1,301 @@
1
- # @authyon/auth
2
-
3
- SDK JS/TS para o [Authyon](https://authyon.com) — autenticação, sessões, multi-tenant e 2FA, com armazenamento e refresh de tokens transparentes.
4
-
5
- Cobre todos os endpoints públicos documentados em [authyon.com/docs](https://authyon.com/docs), usando a **publishable key** (`pk_...`) — segura para expor no navegador.
6
-
7
- Para gestão de organização/membros (secret key) e verificação de token no backend, veja [`@authyon/server`](../server).
8
-
9
- ## Instalação
10
-
11
- ```bash
12
- npm install @authyon/auth
13
- ```
14
-
15
- ## Uso rápido
16
-
17
- ```ts
18
- import { createClient } from "@authyon/auth";
19
-
20
- const authyon = createClient({ envKey: "pk_live_..." });
21
-
22
- // Login (com suporte a 2FA)
23
- const result = await authyon.login({
24
- email: "alice@acme.com",
25
- password: "...",
26
- organizationSlug: "acme", // opcional
27
- });
28
-
29
- if (result.twoFactorRequired) {
30
- const code = prompt(`Código 2FA (${result.methods.join(", ")})`);
31
- await authyon.verifyTwoFactor({
32
- challengeToken: result.challengeToken,
33
- method: "authenticator",
34
- code: code!,
35
- });
36
- }
37
-
38
- // Usuário atual — o access token é renovado automaticamente quando necessário
39
- const user = await authyon.user.me();
40
- ```
41
-
42
- ## Sessão e tokens
43
-
44
- - Tokens persistem em `localStorage` por padrão (`memoryStorage()` ou um `TokenStorage` próprio via opção `storage`).
45
- - `getAccessToken()` renova o token automaticamente antes de expirar (refresh token é single-use e rotacionado, com single-flight para evitar corridas).
46
- - Chamadas autenticadas que retornam 401 fazem um refresh e uma retentativa automática.
47
-
48
- ```ts
49
- const token = await authyon.getAccessToken(); // sempre válido, ou null se deslogado
50
-
51
- const unsubscribe = authyon.onAuthStateChange((event) => {
52
- // "signed_in" | "refreshed" | "signed_out"
53
- console.log(event.type);
54
- });
55
- ```
56
-
57
- ## API
58
-
59
- Métodos de sessão/auth ficam soltos no client; os que giram em torno de um recurso específico ficam agrupados em namespaces (`user`, `organization`, `twoFactor`, `webauthn`, `sso`).
60
-
61
- | Método | Endpoint |
62
- | ------------------------------------------------------------------------ | ----------------------- |
63
- | `register({ email, username, password })` | `POST /auth/register` |
64
- | `login({ email \| username, password, organizationSlug? })` | `POST /auth/login` |
65
- | `verifyTwoFactor({ challengeToken, method, code?, webAuthnAssertion? })` | `POST /auth/2fa/verify` |
66
- | `refresh()` | `POST /auth/refresh` |
67
- | `logout({ everywhere? })` | `POST /auth/logout` |
68
- | `introspect(token?)` | `POST /auth/introspect` |
69
- | `validate(token?)` | `POST /auth/validate` |
70
-
71
- ### `authyon.user`
72
-
73
- | Método | Endpoint |
74
- | ----------------------------------------------- | ----------------------------------- |
75
- | `user.me()` | `GET /auth/me` |
76
- | `user.sessions()` | `GET /auth/sessions` |
77
- | `user.revokeSession(sessionId)` | `DELETE /auth/sessions/{id}` |
78
- | `user.activities(params?)` | `GET /auth/me/activities` |
79
- | `user.requestPasswordReset(email)` | `POST /auth/password-reset/request` |
80
- | `user.confirmPasswordReset(token, newPassword)` | `POST /auth/password-reset/confirm` |
81
-
82
- ### `authyon.organization`
83
-
84
- | Método | Endpoint |
85
- | ----------------------------------------------------- | ---------------------------------------------- |
86
- | `organization.list()` | `GET /auth/tenants` |
87
- | `organization.create(params?)` | `POST /auth/tenants` |
88
- | `organization.get(organizationId)` | `GET /auth/tenants/{id}` |
89
- | `organization.rename(organizationId, name)` | `PATCH /auth/tenants/{id}` |
90
- | `organization.switch(slug)` | `POST /auth/switch-tenant` |
91
- | `organization.current()` | — (lê `activeOrganization` da sessão em cache) |
92
- | `organization.members.list(organizationId, params?)` | `GET /auth/tenants/{id}/members` |
93
- | `organization.members.invite(organizationId, params)` | `POST /auth/tenants/{id}/members` |
94
- | `organization.members.remove(organizationId, userId)` | `DELETE /auth/tenants/{id}/members/{userId}` |
95
- | `organization.roles.list(organizationId)` | `GET /auth/tenants/{id}/roles` |
96
-
97
- ### `authyon.twoFactor`
98
-
99
- | Método | Endpoint |
100
- | ---------------------------------------------------- | -------------------------------------------- |
101
- | `twoFactor.status()` | `GET /auth/2fa/status` |
102
- | `twoFactor.resendEmail(challengeToken)` | `POST /auth/2fa/resend-email` |
103
- | `twoFactor.setupAuthenticator()` | `POST /auth/2fa/authenticator/setup` |
104
- | `twoFactor.confirmAuthenticator(code)` | `POST /auth/2fa/authenticator/confirm` |
105
- | `twoFactor.enableEmail(code?)` | `POST /auth/2fa/email/enable` |
106
- | `twoFactor.disable(method, currentPassword)` | `POST /auth/2fa/disable` |
107
- | `twoFactor.regenerateRecoveryCodes(currentPassword)` | `POST /auth/2fa/recovery-codes/regenerate` |
108
- | `twoFactor.webauthn.registerStart()` | `POST /auth/2fa/webauthn/register/start` |
109
- | `twoFactor.webauthn.registerFinish(...)` | `POST /auth/2fa/webauthn/register/finish` |
110
- | `twoFactor.webauthn.credentials()` | `GET /auth/2fa/webauthn/credentials` |
111
- | `twoFactor.webauthn.renameCredential(id, nickname)` | `PATCH /auth/2fa/webauthn/credentials/{id}` |
112
- | `twoFactor.webauthn.removeCredential(id, pwd)` | `DELETE /auth/2fa/webauthn/credentials/{id}` |
113
- | `twoFactor.webauthn.assertionStart(challengeToken)` | `POST /auth/2fa/webauthn/assertion/start` |
114
-
115
- ### `authyon.webauthn` (login sem senha)
116
-
117
- | Método | Endpoint |
118
- | --------------------------------- | ---------------------------------- |
119
- | `webauthn.loginStart(email?)` | `POST /auth/webauthn/login/start` |
120
- | `webauthn.loginFinish(assertion)` | `POST /auth/webauthn/login/finish` |
121
-
122
- ### `authyon.sso` (login social)
123
-
124
- | Método | Endpoint |
125
- | -------------------------------- | ------------------------------------------------------------------------------------- |
126
- | `sso.providers()` | `GET /auth/sso/providers` |
127
- | `sso.startUrl(provider, params)` | monta a URL de `GET /auth/sso/{provider}/start` (não faz a chamada — navegue até ela) |
128
- | `sso.exchange(code)` | `POST /auth/sso/exchange` |
129
-
130
- ## Invalidação de token
131
-
132
- - **Sessão atual**: `logout()` revoga o refresh token atual; `logout({ everywhere: true })` revoga todos os refresh tokens do usuário.
133
- - **Uma sessão específica**: `user.revokeSession(sessionId)`, usando o `id` retornado por `user.sessions()` — derruba um dispositivo sem afetar a sessão atual.
134
- - **Access token**: por ser um JWT stateless, o access token continua "válido" até expirar (`expiresIn`, tipicamente 30 min) mesmo após revogar o refresh token. Para checar revogação em tempo real no seu backend, use `validate()` (cross-checa o estado no banco) em vez de `introspect()`.
135
-
136
- ## Erros
137
-
138
- Toda resposta não-2xx vira um `AuthyonError` (problem+json). Compare pelo `code` legível por máquina, nunca pelo `title`:
139
-
140
- ```ts
141
- import { AuthyonError, ErrorCodes } from "@authyon/auth";
142
-
143
- try {
144
- await authyon.register({ email, password });
145
- } catch (err) {
146
- if (err instanceof AuthyonError && err.is(ErrorCodes.EmailTaken)) {
147
- // e-mail já cadastrado
148
- }
149
- }
150
- ```
151
-
152
- ## Build
153
-
154
- ```bash
155
- npm install
156
- npm run build # dist/ (ESM + CJS + .d.ts via tsup)
157
- npm run typecheck
158
- ```
1
+ # @authyon/auth
2
+
3
+ SDK JS/TS para o [Authyon](https://authyon.com) — autenticação, sessões, multi-tenant e 2FA, com armazenamento e refresh de tokens transparentes.
4
+
5
+ Cobre os endpoints públicos do Authyon usando a **publishable key** (`pk_...`) — segura para identificar o ambiente no navegador, sem conceder privilégios administrativos.
6
+
7
+ Para gestão de organização/membros (secret key) e verificação de token no backend, use `@authyon/server`.
8
+
9
+ ## Instalação
10
+
11
+ ```bash
12
+ npm install --save-exact @authyon/auth@0.2.0-beta.1
13
+ ```
14
+
15
+ Durante a beta, `npm install @authyon/auth@beta` acompanha o prerelease mais recente. Fixar a versão exata é recomendado para builds reproduzíveis.
16
+
17
+ ## Uso rápido
18
+
19
+ ```ts
20
+ import { createClient } from "@authyon/auth";
21
+
22
+ const authyon = createClient({ envKey: "pk_live_..." }); // tokens somente em memória por padrão
23
+
24
+ // Login (com suporte a 2FA)
25
+ const result = await authyon.login({
26
+ email: "alice@acme.com",
27
+ password: "...",
28
+ organizationSlug: "acme", // opcional
29
+ });
30
+
31
+ if (result.twoFactorRequired) {
32
+ const code = prompt(`Código 2FA (${result.methods.join(", ")})`);
33
+ await authyon.verifyTwoFactor({
34
+ challengeToken: result.challengeToken,
35
+ method: "authenticator",
36
+ code: code!,
37
+ });
38
+ }
39
+
40
+ // Usuário atual — o access token é renovado automaticamente quando necessário
41
+ const user = await authyon.user.me();
42
+ ```
43
+
44
+ ## Next.js e React
45
+
46
+ Use o entrypoint dedicado `@authyon/auth/react`:
47
+
48
+ ```tsx
49
+ <AuthyonProvider client={authyon}>
50
+ <SessionGuard loadingFallback={<Loading />}>
51
+ <PermissionGuard action="read" subject="reports">
52
+ <Reports />
53
+ </PermissionGuard>
54
+ </SessionGuard>
55
+ </AuthyonProvider>
56
+ ```
57
+
58
+ O provider faz refresh automático, valida a sessão por `GET /auth/me`, atualiza usuário e permissions, revalida quando a aba volta ao foco e não libera guards enquanto a validação inicial estiver pendente. Use `useAuthyon()`, `useAuthyonAbility()` e `useCan()` para fluxos programáticos.
59
+
60
+ Para configuração progressiva, use o builder:
61
+
62
+ ```ts
63
+ const authyon = new AuthyonClientBuilder("pk_live_...")
64
+ .withStorage(createMemoryStorage())
65
+ .withTimeout(10_000)
66
+ .build();
67
+ ```
68
+
69
+ ## Sessão e tokens
70
+
71
+ - Tokens ficam somente em memória por padrão, reduzindo o impacto de XSS e sendo removidos ao recarregar a página.
72
+ - Persistência é opt-in com `storage: createLocalStorage()`. Isso melhora conveniência, mas qualquer XSS na aplicação poderá ler os tokens; criptografar o valor não elimina esse risco porque o JavaScript também precisa acessar a chave.
73
+ - `getAccessToken()` renova o token automaticamente antes de expirar (refresh token é single-use e rotacionado, com single-flight para evitar corridas).
74
+ - Chamadas autenticadas que retornam 401 fazem um refresh e uma retentativa automática.
75
+
76
+ ```ts
77
+ import { createClient, createLocalStorage } from "@authyon/auth";
78
+
79
+ // Use somente quando a persistência for um requisito aceito conscientemente.
80
+ const persistentClient = createClient({
81
+ envKey: "pk_live_...",
82
+ storage: createLocalStorage(),
83
+ });
84
+
85
+ const token = await authyon.getAccessToken(); // sempre válido, ou null se deslogado
86
+
87
+ const unsubscribe = authyon.onAuthStateChange((event) => {
88
+ // "signed_in" | "refreshed" | "signed_out"
89
+ console.log(event.type);
90
+ });
91
+ ```
92
+
93
+ Para aplicações de maior risco, prefira um BFF que mantenha o refresh token em cookie `HttpOnly`, `Secure` e `SameSite`, com proteção CSRF. O SDK também exige HTTPS para APIs remotas e aplica timeout de 15 segundos por padrão (`timeoutMs: 0` desabilita).
94
+
95
+ ## HTTP Adapter
96
+
97
+ Use `httpAdapter` para integrar mocks, tracing ou outra biblioteca HTTP. O mesmo contrato está disponível em `@authyon/auth` e `@authyon/server`:
98
+
99
+ ```ts
100
+ import { createClient, type HttpAdapter } from "@authyon/auth";
101
+
102
+ const httpAdapter: HttpAdapter = {
103
+ async request(request) {
104
+ // tracing, métricas ou adaptação para sua stack HTTP
105
+ return fetch(request.url, {
106
+ method: request.method,
107
+ headers: request.headers,
108
+ body: request.body,
109
+ signal: request.signal,
110
+ });
111
+ },
112
+ };
113
+
114
+ const authyon = createClient({ envKey: "pk_live_...", httpAdapter });
115
+ ```
116
+
117
+ `FetchHttpAdapter` é a implementação padrão e também pode encapsular um `fetch` customizado. Não configure `httpAdapter` e `fetch` ao mesmo tempo.
118
+
119
+ O logger HTTP é desabilitado por padrão. Passe uma configuração mutável para observar e manipular eventos de request, response e erro; altere `enabled` a qualquer momento sem recriar o client:
120
+
121
+ ```ts
122
+ import { createClient, type HttpLoggerOptions } from "@authyon/auth";
123
+
124
+ const httpLogger: HttpLoggerOptions = {
125
+ enabled: true,
126
+ logger(event) {
127
+ observability.track(event.type, event);
128
+ },
129
+ };
130
+
131
+ const authyon = createClient({ envKey: "pk_live_...", httpLogger });
132
+
133
+ httpLogger.enabled = false; // desabilita
134
+ httpLogger.enabled = true; // habilita novamente
135
+ ```
136
+
137
+ Sem um `logger` customizado, os eventos usam `console.debug`. Headers, bodies e valores de query string são removidos dos eventos para evitar vazamento de tokens, senhas e dados pessoais. Falhas do logger são isoladas e não interrompem a autenticação. Para decorar um adapter manualmente, use `LoggingHttpAdapter`.
138
+
139
+ ## API
140
+
141
+ ## Autorização baseada em permissões
142
+
143
+ Crie uma ability diretamente do usuário da sessão. Permissões Authyon seguem `subject:action`, por exemplo `tickets:read` e `documents:update`:
144
+
145
+ ```ts
146
+ import { createAuthyonAbility } from "@authyon/auth";
147
+
148
+ const ability = createAuthyonAbility(session.user, {
149
+ rules: [
150
+ {
151
+ action: "update",
152
+ subject: "documents",
153
+ inverted: true,
154
+ conditions: { locked: true },
155
+ reason: "Documento bloqueado",
156
+ },
157
+ ],
158
+ });
159
+
160
+ ability.can("read", "tickets");
161
+ ability.can("update", { __type: "documents", locked: false });
162
+ ability.cannot("update", { __type: "documents", locked: true });
163
+ ```
164
+
165
+ Também estão disponíveis `AuthyonAbilityBuilder`, regras por role, campos, condições com operadores (`$eq`, `$ne`, `$in`, `$nin`, `$gt`, `$gte`, `$lt`, `$lte`, `$exists`, `$and`, `$or`), `rulesFor()`, `update()` e o evento `updated`. A autorização é local e nega por padrão; o backend continua responsável por validar toda ação sensível.
166
+
167
+ ### Next.js Client Side
168
+
169
+ `@authyon/auth` e o motor de abilities são isomórficos e podem ser usados em Client Components:
170
+
171
+ ```tsx
172
+ "use client";
173
+
174
+ import { createAuthyonAbility } from "@authyon/auth";
175
+
176
+ export function EditButton({ user, document }) {
177
+ const ability = createAuthyonAbility(user);
178
+ if (ability.cannot("update", { __type: "documents", ...document })) return null;
179
+ return <button>Editar</button>;
180
+ }
181
+ ```
182
+
183
+ Essa verificação controla a interface, não a segurança do backend. Nunca importe `@authyon/server` em Client Components nem envie `clientSecret` ao navegador.
184
+
185
+ Métodos de sessão/auth ficam soltos no client; os que giram em torno de um recurso específico ficam agrupados em namespaces (`user`, `organization`, `twoFactor`, `webauthn`, `sso`).
186
+
187
+ | Método | Endpoint |
188
+ | ------------------------------------------------------------------------ | --------------------------------- |
189
+ | `register({ email, username, password })` | `POST /auth/register` |
190
+ | `login({ email \| username, password, organizationSlug? })` | `POST /auth/login` |
191
+ | `verifyTwoFactor({ challengeToken, method, code?, webAuthnAssertion? })` | `POST /auth/2fa/verify` |
192
+ | `refresh()` | `POST /auth/refresh` |
193
+ | `logout({ everywhere? })` | `POST /auth/logout` |
194
+ | `introspect(token?)` | Deprecated: use `@authyon/server` |
195
+ | `validate(token?)` | Deprecated: use `@authyon/server` |
196
+
197
+ ### `authyon.user`
198
+
199
+ | Método | Endpoint |
200
+ | ----------------------------------------------- | ----------------------------------- |
201
+ | `user.me()` | `GET /auth/me` |
202
+ | `user.sessions()` | `GET /auth/sessions` |
203
+ | `user.revokeSession(sessionId)` | `DELETE /auth/sessions/{id}` |
204
+ | `user.activities(params?)` | `GET /auth/me/activities` |
205
+ | `user.requestPasswordReset(email)` | `POST /auth/password-reset/request` |
206
+ | `user.confirmPasswordReset(token, newPassword)` | `POST /auth/password-reset/confirm` |
207
+
208
+ ### `authyon.organization`
209
+
210
+ | Método | Endpoint |
211
+ | ----------------------------------------------------- | ---------------------------------------------- |
212
+ | `organization.list()` | `GET /auth/tenants` |
213
+ | `organization.create(params?)` | `POST /auth/tenants` |
214
+ | `organization.get(organizationId)` | `GET /auth/tenants/{id}` |
215
+ | `organization.rename(organizationId, name)` | `PATCH /auth/tenants/{id}` |
216
+ | `organization.switch(slug)` | `POST /auth/switch-tenant` |
217
+ | `organization.current()` | — (lê `activeOrganization` da sessão em cache) |
218
+ | `organization.members.list(organizationId, params?)` | `GET /auth/tenants/{id}/members` |
219
+ | `organization.members.invite(organizationId, params)` | `POST /auth/tenants/{id}/members` |
220
+ | `organization.members.remove(organizationId, userId)` | `DELETE /auth/tenants/{id}/members/{userId}` |
221
+ | `organization.roles.list(organizationId)` | `GET /auth/tenants/{id}/roles` |
222
+
223
+ ### `authyon.twoFactor`
224
+
225
+ | Método | Endpoint |
226
+ | ---------------------------------------------------- | -------------------------------------------- |
227
+ | `twoFactor.status()` | `GET /auth/2fa/status` |
228
+ | `twoFactor.resendEmail(challengeToken)` | `POST /auth/2fa/resend-email` |
229
+ | `twoFactor.setupAuthenticator()` | `POST /auth/2fa/authenticator/setup` |
230
+ | `twoFactor.confirmAuthenticator(code)` | `POST /auth/2fa/authenticator/confirm` |
231
+ | `twoFactor.enableEmail(code?)` | `POST /auth/2fa/email/enable` |
232
+ | `twoFactor.disable(method, currentPassword)` | `POST /auth/2fa/disable` |
233
+ | `twoFactor.regenerateRecoveryCodes(currentPassword)` | `POST /auth/2fa/recovery-codes/regenerate` |
234
+ | `twoFactor.webauthn.registerStart()` | `POST /auth/2fa/webauthn/register/start` |
235
+ | `twoFactor.webauthn.registerFinish(...)` | `POST /auth/2fa/webauthn/register/finish` |
236
+ | `twoFactor.webauthn.credentials()` | `GET /auth/2fa/webauthn/credentials` |
237
+ | `twoFactor.webauthn.renameCredential(id, nickname)` | `PATCH /auth/2fa/webauthn/credentials/{id}` |
238
+ | `twoFactor.webauthn.removeCredential(id, pwd)` | `DELETE /auth/2fa/webauthn/credentials/{id}` |
239
+ | `twoFactor.webauthn.assertionStart(challengeToken)` | `POST /auth/2fa/webauthn/assertion/start` |
240
+
241
+ ### `authyon.webauthn` (login sem senha)
242
+
243
+ | Método | Endpoint |
244
+ | --------------------------------- | ---------------------------------- |
245
+ | `webauthn.loginStart(email?)` | `POST /auth/webauthn/login/start` |
246
+ | `webauthn.loginFinish(assertion)` | `POST /auth/webauthn/login/finish` |
247
+
248
+ ### `authyon.sso` (login social)
249
+
250
+ | Método | Endpoint |
251
+ | -------------------------------- | ------------------------------------------------------------------------------------- |
252
+ | `sso.providers()` | `GET /auth/sso/providers` |
253
+ | `sso.startUrl(provider, params)` | monta a URL de `GET /auth/sso/{provider}/start` (não faz a chamada — navegue até ela) |
254
+ | `sso.exchange(code)` | `POST /auth/sso/exchange` |
255
+
256
+ ## Invalidação de token
257
+
258
+ - **Sessão atual**: `logout()` revoga o refresh token atual; `logout({ everywhere: true })` revoga todos os refresh tokens do usuário.
259
+ - **Uma sessão específica**: `user.revokeSession(sessionId)`, usando o `id` retornado por `user.sessions()` — derruba um dispositivo sem afetar a sessão atual.
260
+ - **Access token**: por ser um JWT stateless, o access token continua "válido" até expirar (`expiresIn`, tipicamente 30 min) mesmo após revogar o refresh token. Para checar revogação em tempo real no seu backend, use `validate()` (cross-checa o estado no banco) em vez de `introspect()`.
261
+
262
+ ## Erros
263
+
264
+ Toda resposta não-2xx vira um `AuthyonError` (problem+json). Compare pelo `code` legível por máquina, nunca pelo `title`:
265
+
266
+ Falhas de transporte usam `request.network_error` ou `request.timeout`. Quando presentes, `requestId` e `retryAfter` ajudam suporte e tratamento de rate limit sem expor o corpo da requisição.
267
+
268
+ `interpret()` converte códigos e status em uma decisão estável para a interface:
269
+
270
+ ```ts
271
+ try {
272
+ await authyon.login({ email, password });
273
+ } catch (cause) {
274
+ if (!(cause instanceof AuthyonError)) throw cause;
275
+ const { category, action, retryable, retryAfter } = cause.interpret();
276
+ // category: authentication | validation | rate_limit | network | ...
277
+ // action: reauthenticate | fix_input | retry | ...
278
+ }
279
+ ```
280
+
281
+ Veja o catálogo completo em `ERRORS.md` no repositório.
282
+
283
+ ```ts
284
+ import { AuthyonError, ErrorCodes } from "@authyon/auth";
285
+
286
+ try {
287
+ await authyon.register({ email, password });
288
+ } catch (err) {
289
+ if (err instanceof AuthyonError && err.is(ErrorCodes.EmailTaken)) {
290
+ // e-mail já cadastrado
291
+ }
292
+ }
293
+ ```
294
+
295
+ ## Build
296
+
297
+ ```bash
298
+ npm install
299
+ npm run build # dist/ (ESM + CJS + .d.ts via tsup)
300
+ npm run typecheck
301
+ ```