@authyon/server 0.2.0-beta.0 → 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
@@ -2,6 +2,56 @@
2
2
 
3
3
  SDK server-side para o [Authyon](https://authyon.com) — administração de ambiente/tenants (OAuth client-credentials) e verificação de access token (publishable key). Nunca importe este pacote em código de browser.
4
4
 
5
+ ## Instalação da beta
6
+
7
+ ```bash
8
+ npm install --save-exact @authyon/server@0.2.0-beta.1
9
+ ```
10
+
11
+ Durante a beta, `npm install @authyon/server@beta` acompanha o prerelease mais recente. Fixar a versão exata é recomendado para builds reproduzíveis.
12
+
13
+ O pacote possui uma condição de exportação `browser` que falha imediatamente se um bundler tentar incluí-lo no frontend. URLs remotas exigem HTTPS e cada request tem timeout padrão de 15 segundos, configurável por `timeoutMs`.
14
+
15
+ O client aceita o mesmo contrato `HttpAdapter` de `@authyon/auth`, útil para tracing, mocks e stacks HTTP próprias:
16
+
17
+ ```ts
18
+ import { createClient, FetchHttpAdapter } from "@authyon/server";
19
+
20
+ const authyon = createClient({
21
+ envKey: process.env.AUTHYON_ENV_KEY,
22
+ httpAdapter: new FetchHttpAdapter(globalThis.fetch),
23
+ });
24
+ ```
25
+
26
+ Quando houver credenciais, adapter e observabilidade, o builder mantém cada etapa explícita:
27
+
28
+ ```ts
29
+ const authyon = new AuthyonServerClientBuilder()
30
+ .withEnvironmentKey(process.env.AUTHYON_ENV_KEY)
31
+ .withEnvironmentCredentials(process.env.AUTHYON_CLIENT_ID, process.env.AUTHYON_CLIENT_SECRET)
32
+ .withHttpLogger(httpLogger)
33
+ .build();
34
+ ```
35
+
36
+ O client também aceita `httpLogger: { enabled, logger? }`. A configuração é mutável, portanto `enabled` pode ser alterado em runtime. Os eventos não incluem headers, bodies nem valores de query string, e erros do logger nunca interrompem requests.
37
+
38
+ `AuthyonError`, `ErrorCodes` e `error.interpret()` também são exportados por este pacote. Use `category`, `action`, `retryable`, `retryAfter` e `requestId` para implementar middleware e observabilidade sem comparar mensagens humanas.
39
+
40
+ ## Validação local com JWKS
41
+
42
+ Para APIs de alto volume, crie uma vez um verificador com discovery automático:
43
+
44
+ ```ts
45
+ const verifier = await authyon.createJwksTokenVerifier({
46
+ audience: process.env.AUTHYON_AUDIENCE,
47
+ algorithms: ["RS256"],
48
+ });
49
+
50
+ const { claims } = await verifier.verifyAccessToken(token);
51
+ ```
52
+
53
+ Ele valida assinatura, algoritmo, issuer, audience, tipo e claims temporais, com cache e rotação de chaves. Use `verification: "jwks"` em `authorizeRequest()` ou `createExpressAuthorizationMiddleware()`. Para ações sensíveis que precisam detectar revogação imediatamente, mantenha o padrão `validate`.
54
+
5
55
  ## Instalação
6
56
 
7
57
  ```bash
@@ -35,7 +85,7 @@ const { active, sub } = await authyon.introspect(token); // leve
35
85
  const { user, organization } = await authyon.validate(token); // recomendado — cross-checa revogação
36
86
  ```
37
87
 
38
- Veja [`examples/token-verification.ts`](./examples/token-verification.ts) para um middleware completo.
88
+ Veja [`examples/tokenVerification.ts`](./examples/tokenVerification.ts) para um middleware completo.
39
89
 
40
90
  ## Administração de ambiente (`environment.*`)
41
91
 
@@ -52,10 +102,79 @@ await authyon.environment.roles.create({ name: "support", permissions: ["tickets
52
102
  await authyon.environment.audit.list({ take: 50 });
53
103
  ```
54
104
 
55
- Veja [`examples/organization-membership.ts`](./examples/organization-membership.ts) para o fluxo completo, incluindo as rotas de backend que o `@authyon/auth` chamaria.
105
+ Veja [`examples/organizationMembership.ts`](./examples/organizationMembership.ts) para o fluxo completo, incluindo as rotas de backend que o `@authyon/auth` chamaria.
56
106
 
57
107
  Namespaces disponíveis: `environment.users`, `environment.tenants` (com `.members` e `.roles` aninhados), `environment.roles`, `environment.permissions`, `environment.audit`.
58
108
 
109
+ ## Autorização local
110
+
111
+ `createAuthyonAbility()` transforma o resultado de `validate()`, `introspect()` ou qualquer objeto com `permissions`, `roles` e `scope` em verificações locais no estilo CASL:
112
+
113
+ ```ts
114
+ import { createAuthyonAbility } from "@authyon/server";
115
+
116
+ const identity = await authyon.validate(token);
117
+ const ability = createAuthyonAbility(identity);
118
+
119
+ if (!ability.can("read", "reports")) {
120
+ throw new Error("Forbidden");
121
+ }
122
+ ```
123
+
124
+ Regras condicionais e de domínio podem ser acrescentadas no segundo argumento. O mecanismo é deny-by-default e não substitui a validação do token nem a autorização aplicada pela API.
125
+
126
+ ### Next.js Server Side
127
+
128
+ Em Route Handlers, Server Actions ou SSR, mantenha `@authyon/server` em um módulo marcado com `server-only`:
129
+
130
+ ```ts
131
+ import "server-only";
132
+ import { createAuthorizationErrorResponse, authorizeRequest, createClient } from "@authyon/server";
133
+
134
+ const authyon = createClient({
135
+ envKey: process.env.AUTHYON_ENV_KEY,
136
+ clientId: process.env.AUTHYON_CLIENT_ID,
137
+ clientSecret: process.env.AUTHYON_CLIENT_SECRET,
138
+ });
139
+
140
+ export async function GET(request: Request) {
141
+ try {
142
+ const auth = await authorizeRequest(authyon, request, {
143
+ requirement: { action: "read", subject: "reports" },
144
+ });
145
+ return Response.json({ userId: auth.userId });
146
+ } catch (error) {
147
+ return createAuthorizationErrorResponse(error);
148
+ }
149
+ }
150
+ ```
151
+
152
+ ### Express e frameworks Connect
153
+
154
+ O middleware não adiciona Express como dependência e disponibiliza `request.authyon`:
155
+
156
+ ```ts
157
+ import { createExpressAuthorizationMiddleware } from "@authyon/server";
158
+
159
+ app.get(
160
+ "/reports",
161
+ createExpressAuthorizationMiddleware(authyon, {
162
+ requirement: { action: "read", subject: "reports" },
163
+ }),
164
+ (request, response) => response.json({ userId: request.authyon.userId }),
165
+ );
166
+ ```
167
+
168
+ Use `authorizeToken()` em NestJS, Fastify, Hono, tRPC ou integrações próprias. `passErrorsToNext: true` encaminha erros ao middleware de erros do Express.
169
+
170
+ ### IP real do cliente
171
+
172
+ Chamadas server-side propagam `clientIp` em `X-Forwarded-For`. O middleware Express usa o IP do socket por padrão; atrás de um proxy confiável, configure o próprio Express e use `trustProxy: true`. Para Next.js, passe `resolveClientIp` ao `authorizeRequest()` lendo somente headers que sua infraestrutura sobrescreve. Não confie cegamente em `X-Forwarded-For` recebido da internet.
173
+
174
+ ```ts
175
+ await authyon.validate(token, { clientIp: "203.0.113.10" });
176
+ ```
177
+
59
178
  ## Administração por tenant (`tenant()`)
60
179
 
61
180
  As credenciais de um tenant são próprias dele — use `authyon.tenant(credentials)` para obter um cliente escopado, que minta e cacheia seu próprio token via `POST /tenant/oauth/token`:
@@ -0,0 +1,21 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __copyProps = (to, from, except, desc) => {
7
+ if (from && typeof from === "object" || typeof from === "function") {
8
+ for (let key of __getOwnPropNames(from))
9
+ if (!__hasOwnProp.call(to, key) && key !== except)
10
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
11
+ }
12
+ return to;
13
+ };
14
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
15
+
16
+ // src/browser.ts
17
+ var browser_exports = {};
18
+ module.exports = __toCommonJS(browser_exports);
19
+ throw new Error(
20
+ "@authyon/server cannot run in a browser. Use @authyon/auth in frontend code and keep client secrets on the server."
21
+ );
@@ -0,0 +1,2 @@
1
+
2
+ export { }
@@ -0,0 +1,2 @@
1
+
2
+ export { }
@@ -0,0 +1,4 @@
1
+ // src/browser.ts
2
+ throw new Error(
3
+ "@authyon/server cannot run in a browser. Use @authyon/auth in frontend code and keep client secrets on the server."
4
+ );