@authyon/server 0.2.0-beta.0 → 0.2.0-beta.2
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 +21 -0
- package/README.md +126 -2
- package/dist/browser.cjs +21 -0
- package/dist/browser.d.cts +2 -0
- package/dist/browser.d.ts +2 -0
- package/dist/browser.js +4 -0
- package/dist/index.cjs +909 -70
- package/dist/index.d.cts +352 -65
- package/dist/index.d.ts +352 -65
- package/dist/index.js +895 -69
- package/package.json +58 -36
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.2
|
|
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/
|
|
88
|
+
Veja [`examples/tokenVerification.ts`](./examples/tokenVerification.ts) para um middleware completo.
|
|
39
89
|
|
|
40
90
|
## Administração de ambiente (`environment.*`)
|
|
41
91
|
|
|
@@ -43,6 +93,11 @@ Usa as credenciais de ambiente (`clientId`/`clientSecret`) automaticamente — o
|
|
|
43
93
|
|
|
44
94
|
```ts
|
|
45
95
|
const org = await authyon.environment.tenants.create({ name: "Acme", slug: "acme" });
|
|
96
|
+
const tenants = await authyon.environment.tenants.list({
|
|
97
|
+
search: "acme",
|
|
98
|
+
skip: 0,
|
|
99
|
+
take: 20,
|
|
100
|
+
});
|
|
46
101
|
await authyon.environment.tenants.members.add(org.id, userId, ["owner"]);
|
|
47
102
|
await authyon.environment.tenants.members.assignRole(org.id, userId, "billing-admin");
|
|
48
103
|
await authyon.environment.tenants.members.remove(org.id, userId);
|
|
@@ -52,10 +107,79 @@ await authyon.environment.roles.create({ name: "support", permissions: ["tickets
|
|
|
52
107
|
await authyon.environment.audit.list({ take: 50 });
|
|
53
108
|
```
|
|
54
109
|
|
|
55
|
-
Veja [`examples/
|
|
110
|
+
Veja [`examples/organizationMembership.ts`](./examples/organizationMembership.ts) para o fluxo completo, incluindo as rotas de backend que o `@authyon/auth` chamaria.
|
|
56
111
|
|
|
57
112
|
Namespaces disponíveis: `environment.users`, `environment.tenants` (com `.members` e `.roles` aninhados), `environment.roles`, `environment.permissions`, `environment.audit`.
|
|
58
113
|
|
|
114
|
+
## Autorização local
|
|
115
|
+
|
|
116
|
+
`createAuthyonAbility()` transforma o resultado de `validate()`, `introspect()` ou qualquer objeto com `permissions`, `roles` e `scope` em verificações locais no estilo CASL:
|
|
117
|
+
|
|
118
|
+
```ts
|
|
119
|
+
import { createAuthyonAbility } from "@authyon/server";
|
|
120
|
+
|
|
121
|
+
const identity = await authyon.validate(token);
|
|
122
|
+
const ability = createAuthyonAbility(identity);
|
|
123
|
+
|
|
124
|
+
if (!ability.can("read", "reports")) {
|
|
125
|
+
throw new Error("Forbidden");
|
|
126
|
+
}
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
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.
|
|
130
|
+
|
|
131
|
+
### Next.js Server Side
|
|
132
|
+
|
|
133
|
+
Em Route Handlers, Server Actions ou SSR, mantenha `@authyon/server` em um módulo marcado com `server-only`:
|
|
134
|
+
|
|
135
|
+
```ts
|
|
136
|
+
import "server-only";
|
|
137
|
+
import { createAuthorizationErrorResponse, authorizeRequest, createClient } from "@authyon/server";
|
|
138
|
+
|
|
139
|
+
const authyon = createClient({
|
|
140
|
+
envKey: process.env.AUTHYON_ENV_KEY,
|
|
141
|
+
clientId: process.env.AUTHYON_CLIENT_ID,
|
|
142
|
+
clientSecret: process.env.AUTHYON_CLIENT_SECRET,
|
|
143
|
+
});
|
|
144
|
+
|
|
145
|
+
export async function GET(request: Request) {
|
|
146
|
+
try {
|
|
147
|
+
const auth = await authorizeRequest(authyon, request, {
|
|
148
|
+
requirement: { action: "read", subject: "reports" },
|
|
149
|
+
});
|
|
150
|
+
return Response.json({ userId: auth.userId });
|
|
151
|
+
} catch (error) {
|
|
152
|
+
return createAuthorizationErrorResponse(error);
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
```
|
|
156
|
+
|
|
157
|
+
### Express e frameworks Connect
|
|
158
|
+
|
|
159
|
+
O middleware não adiciona Express como dependência e disponibiliza `request.authyon`:
|
|
160
|
+
|
|
161
|
+
```ts
|
|
162
|
+
import { createExpressAuthorizationMiddleware } from "@authyon/server";
|
|
163
|
+
|
|
164
|
+
app.get(
|
|
165
|
+
"/reports",
|
|
166
|
+
createExpressAuthorizationMiddleware(authyon, {
|
|
167
|
+
requirement: { action: "read", subject: "reports" },
|
|
168
|
+
}),
|
|
169
|
+
(request, response) => response.json({ userId: request.authyon.userId }),
|
|
170
|
+
);
|
|
171
|
+
```
|
|
172
|
+
|
|
173
|
+
Use `authorizeToken()` em NestJS, Fastify, Hono, tRPC ou integrações próprias. `passErrorsToNext: true` encaminha erros ao middleware de erros do Express.
|
|
174
|
+
|
|
175
|
+
### IP real do cliente
|
|
176
|
+
|
|
177
|
+
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.
|
|
178
|
+
|
|
179
|
+
```ts
|
|
180
|
+
await authyon.validate(token, { clientIp: "203.0.113.10" });
|
|
181
|
+
```
|
|
182
|
+
|
|
59
183
|
## Administração por tenant (`tenant()`)
|
|
60
184
|
|
|
61
185
|
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`:
|
package/dist/browser.cjs
ADDED
|
@@ -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
|
+
);
|
package/dist/browser.js
ADDED