@eduzz/miau-client 1.4.3 → 1.4.4-rc.16

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.
@@ -1,4 +1,4 @@
1
1
 
2
- > @eduzz/miau-client@1.4.3 build:types /home/runner/work/eduzz-miau/eduzz-miau/clients/node-client
2
+ > @eduzz/miau-client@1.4.4 build:types /home/runner/work/eduzz-miau/eduzz-miau/clients/node-client
3
3
  > tsc --emitDeclarationOnly --outDir dist
4
4
 
package/README.md CHANGED
@@ -1,14 +1,18 @@
1
1
  # @eduzz/miau-client
2
2
 
3
- Node.js client for the Eduzz Miau authentication and authorization service. Includes Express and Fastify middleware for automatic request validation.
3
+ Client Node.js para o serviço de autenticação e autorização Eduzz Miau. Inclui middleware para Express e Fastify com validação automática de requisições.
4
4
 
5
- ## Installation
5
+ ## Instalação
6
6
 
7
7
  ```bash
8
8
  npm install @eduzz/miau-client
9
9
  ```
10
10
 
11
- ## Usage
11
+ ## Requisitos
12
+
13
+ - Node.js >= 18
14
+
15
+ ## Uso
12
16
 
13
17
  ```typescript
14
18
  import { MiauClient } from '@eduzz/miau-client';
@@ -21,7 +25,7 @@ const client = new MiauClient({
21
25
  const token = await client.getToken();
22
26
  ```
23
27
 
24
- ## Example
28
+ ## Exemplo
25
29
 
26
30
  ```typescript
27
31
  import { MiauClient } from '@eduzz/miau-client';
@@ -41,9 +45,9 @@ const data = await response.json();
41
45
  console.log(JSON.stringify(data, null, 2));
42
46
  ```
43
47
 
44
- ## Express Middleware
48
+ ## Middleware Express
45
49
 
46
- Validates incoming requests using Miau tokens and checks permissions automatically.
50
+ O client inclui um middleware Express que autentica requisições usando tokens Miau e verifica permissões automaticamente.
47
51
 
48
52
  ```typescript
49
53
  import express from 'express';
@@ -55,89 +59,103 @@ const miau = new MiauClient({ apiUrl: MIAU_API_URL, appSecret: MIAU_APP_SECRET }
55
59
  app.use(miau.middleware());
56
60
 
57
61
  app.get('/your/endpoint', (req, res) => {
58
- // req.miauApplication - the authenticated application
59
- // req.miauMetadata - permission metadata
62
+ // req.miauApplication - { id: '...', name: '...' }
63
+ // req.miauMetadata - metadata de permissão
60
64
  res.json({ app: req.miauApplication });
61
65
  });
62
66
  ```
63
67
 
64
- With custom request augmentation:
68
+ ### Handler de fallback
65
69
 
66
- ```typescript
67
- app.use(
68
- miau.middleware({
69
- requestAugmentation: ({ req, app, meta }) => {
70
- // Attach custom data to the request
71
- },
72
- fallbackMiddleware: (req, res, next) => {
73
- // Called when token is missing/malformed (400 errors)
74
- next();
75
- },
76
- })
77
- );
78
- ```
79
-
80
- ## Fastify Hook
70
+ O middleware aciona o fallback quando o token está ausente ou não é um token Miau válido (erros HTTP 400). Isso permite lidar com esquemas de autenticação alternativos nas mesmas rotas -- por exemplo, aceitar Basic Auth para clients legados enquanto ainda suporta tokens Miau.
81
71
 
82
72
  ```typescript
83
- import Fastify from 'fastify';
73
+ import express, { type Request, type Response, type NextFunction } from 'express';
84
74
  import { MiauClient } from '@eduzz/miau-client';
85
75
 
86
- const app = Fastify();
76
+ const app = express();
87
77
  const miau = new MiauClient({ apiUrl: MIAU_API_URL, appSecret: MIAU_APP_SECRET });
88
78
 
89
- app.addHook('preHandler', miau.hook());
90
-
91
- app.get('/your/endpoint', async (request, reply) => {
92
- // request.miauApplication - the authenticated application
93
- // request.miauMetadata - permission metadata
94
- return { app: request.miauApplication };
95
- });
96
- ```
79
+ const basicAuthFallback = (req: Request, res: Response, next: NextFunction) => {
80
+ const authHeader = req.headers.authorization || '';
97
81
 
98
- ## API
82
+ if (!authHeader.startsWith('Basic ')) {
83
+ res.status(401).json({ error: 'Unauthorized', message: 'Credenciais não fornecidas' });
84
+ return;
85
+ }
99
86
 
100
- ### `new MiauClient({ apiUrl, appSecret })`
87
+ const [username, password] = Buffer.from(authHeader.slice(6), 'base64').toString().split(':');
101
88
 
102
- Creates a new client instance.
89
+ // Valide as credenciais com sua própria lógica
90
+ if (!validateCredentials(username, password)) {
91
+ res.status(401).json({ error: 'Unauthorized', message: 'Credenciais inválidas' });
92
+ return;
93
+ }
103
94
 
104
- | Parameter | Type | Description |
105
- |------------|----------|------------------------------|
106
- | `apiUrl` | `string` | Miau API base URL |
107
- | `appSecret`| `string` | Application secret from Miau |
95
+ req.username = username;
96
+ next();
97
+ };
108
98
 
109
- ### `client.getToken(): Promise<string>`
99
+ app.use('/legacy-route', miau.middleware({ fallbackMiddleware: basicAuthFallback }));
110
100
 
111
- Returns a valid JWT access token. Tokens are cached in memory and automatically refreshed when they are within 60 seconds of expiration.
101
+ app.get('/legacy-route', (req, res) => {
102
+ if (req.miauApplication) {
103
+ // Autenticado via token Miau
104
+ res.json({ auth: 'miau', application: req.miauApplication });
105
+ return;
106
+ }
112
107
 
113
- ### `client.getTokenData(): Promise<MiauClientToken>`
108
+ // Autenticado via fallback Basic Auth
109
+ res.json({ auth: 'basic', username: req.username });
110
+ });
111
+ ```
114
112
 
115
- Returns the decoded token payload.
113
+ ## Hook Fastify
116
114
 
117
- ### `client.getEnvironment(): SecretEnv`
115
+ O client também oferece um hook `preHandler` para Fastify com o mesmo fluxo de autenticação.
118
116
 
119
- Returns the environment extracted from the app secret (e.g. `production`, `staging`).
117
+ ```typescript
118
+ import Fastify from 'fastify';
119
+ import { MiauClient } from '@eduzz/miau-client';
120
120
 
121
- ### `client.getPublicKey(kid: string): Promise<string>`
121
+ const app = Fastify();
122
+ const miau = new MiauClient({ apiUrl: MIAU_API_URL, appSecret: MIAU_APP_SECRET });
122
123
 
123
- Fetches and caches the public key for the given key ID from the JWKS endpoint.
124
+ app.addHook('preHandler', miau.hook());
124
125
 
125
- ### `client.verify(token: string, publicKey: string): Promise<MiauClientToken>`
126
+ app.get('/your/endpoint', async (request, reply) => {
127
+ // request.miauApplication - { id: '...', name: '...' }
128
+ // request.miauMetadata - metadata de permissão
129
+ return { app: request.miauApplication };
130
+ });
131
+ ```
126
132
 
127
- Verifies a JWT token using the provided public key (RS256).
133
+ ### Handler de fallback
128
134
 
129
- ### `client.hasPermission(sourceAppId: string, resource: Resource): Promise<HasPermissionResponse>`
135
+ ```typescript
136
+ import Fastify from 'fastify';
137
+ import { MiauClient } from '@eduzz/miau-client';
130
138
 
131
- Checks if a source application has permission to access a given resource.
139
+ const app = Fastify();
140
+ const miau = new MiauClient({ apiUrl: MIAU_API_URL, appSecret: MIAU_APP_SECRET });
132
141
 
133
- ### `client.middleware(config?): RequestHandler`
142
+ const basicAuthFallback = async (request: FastifyRequest, reply: FastifyReply) => {
143
+ const authHeader = request.headers.authorization || '';
134
144
 
135
- Returns an Express middleware that authenticates requests and checks permissions.
145
+ if (!authHeader.startsWith('Basic ')) {
146
+ reply.code(401).send({ error: 'Unauthorized', message: 'Credenciais não fornecidas' });
147
+ return;
148
+ }
136
149
 
137
- ### `client.hook(config?): FastifyHook`
150
+ const [username, password] = Buffer.from(authHeader.slice(6), 'base64').toString().split(':');
138
151
 
139
- Returns a Fastify `preHandler` hook that authenticates requests and checks permissions.
152
+ if (!validateCredentials(username, password)) {
153
+ reply.code(401).send({ error: 'Unauthorized', message: 'Credenciais inválidas' });
154
+ return;
155
+ }
140
156
 
141
- ## Requirements
157
+ request.username = username;
158
+ };
142
159
 
143
- - Node.js >= 18
160
+ app.addHook('preHandler', miau.hook({ fallbackMiddleware: basicAuthFallback }));
161
+ ```
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@eduzz/miau-client",
3
- "version": "1.4.3",
3
+ "version": "1.4.4-rc.16",
4
4
  "description": "Eduzz Miau Client",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",