@acropole/skills 0.0.0-stage → 1.1.0
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/README.md +181 -2
- package/agents/revisor-deploy.md +73 -0
- package/agents/revisor-documentacao.md +78 -0
- package/agents/revisor-orfeu.md +80 -0
- package/agents/revisor-trismegisto.md +81 -0
- package/bin/install.js +252 -0
- package/package.json +15 -4
- package/skills/acropole/SKILL.md +80 -0
- package/skills/acropole/references/arquitetura.md +174 -0
- package/skills/acropole/references/fluxos/app-novo.md +34 -0
- package/skills/acropole/references/fluxos/doctor.md +55 -0
- package/skills/acropole/references/fluxos/endpoint-novo.md +22 -0
- package/skills/acropole/references/fluxos/revisar.md +56 -0
- package/skills/acropole/references/fluxos/tela-nova.md +27 -0
- package/skills/acropole/scripts/doctor.mjs +439 -0
- package/skills/angular/SKILL.md +155 -0
- package/skills/angular/references/armadilhas.md +99 -0
- package/skills/angular/references/dados.md +251 -0
- package/skills/angular/references/estrutura.md +279 -0
- package/skills/angular/references/features.md +219 -0
- package/skills/angular/references/testes-build.md +257 -0
- package/skills/angular/scripts/checar.mjs +182 -0
- package/skills/angular/scripts/nucleo.mjs +227 -0
- package/skills/apollo/SKILL.md +226 -0
- package/skills/apollo/references/armadilhas.md +99 -0
- package/skills/apollo/references/envelope-erros.md +120 -0
- package/skills/apollo/references/estrutura-bootstrap.md +310 -0
- package/skills/apollo/references/schema-resolvers.md +183 -0
- package/skills/apollo/references/subscriptions.md +224 -0
- package/skills/apollo/references/testes-build.md +181 -0
- package/skills/apollo/scripts/checar.mjs +160 -0
- package/skills/apollo/scripts/nucleo.mjs +227 -0
- package/skills/docker/SKILL.md +102 -0
- package/skills/docker/references/modelos.md +251 -0
- package/skills/docker/references/porques.md +286 -0
- package/skills/documentacao/SKILL.md +146 -0
- package/skills/documentacao/references/checklist-coerencia.md +59 -0
- package/skills/documentacao/references/ligar-app-novo.md +107 -0
- package/skills/documentacao/references/modelo-especificacao.md +51 -0
- package/skills/documentacao/references/modelo-readme.md +75 -0
- package/skills/documentacao/scripts/checar.mjs +454 -0
- package/skills/documentacao/scripts/nucleo.mjs +227 -0
- package/skills/express/SKILL.md +156 -0
- package/skills/express/references/dados.md +180 -0
- package/skills/express/references/estrutura.md +157 -0
- package/skills/express/references/middlewares.md +227 -0
- package/skills/express/references/rotas-erros.md +286 -0
- package/skills/express/references/testes-deploy.md +154 -0
- package/skills/express/scripts/checar.mjs +115 -0
- package/skills/express/scripts/nucleo.mjs +227 -0
- package/skills/fastapi/SKILL.md +132 -0
- package/skills/fastapi/references/banco.md +197 -0
- package/skills/fastapi/references/estrutura.md +325 -0
- package/skills/fastapi/references/integracoes.md +145 -0
- package/skills/fastapi/references/rotas-erros.md +140 -0
- package/skills/fastapi/references/testes-deploy.md +190 -0
- package/skills/fastapi/scripts/checar.mjs +108 -0
- package/skills/fastapi/scripts/nucleo.mjs +227 -0
- package/skills/hefesto/SKILL.md +119 -0
- package/skills/hefesto/references/conceitos.md +131 -0
- package/skills/hefesto/references/diagnostico.md +70 -0
- package/skills/hefesto/references/fluxo.md +122 -0
- package/skills/hefesto/references/preparar-app.md +105 -0
- package/skills/orfeu/SKILL.md +162 -0
- package/skills/orfeu/references/angular-api.md +201 -0
- package/skills/orfeu/references/angular-armadilhas.md +116 -0
- package/skills/orfeu/references/angular-recipes.md +474 -0
- package/skills/orfeu/references/angular.md +212 -0
- package/skills/orfeu/references/diferencas.md +56 -0
- package/skills/orfeu/references/node-api.md +354 -0
- package/skills/orfeu/references/node-armadilhas.md +158 -0
- package/skills/orfeu/references/node-recipes.md +541 -0
- package/skills/orfeu/references/node.md +204 -0
- package/skills/orfeu/references/python-api.md +346 -0
- package/skills/orfeu/references/python-recipes.md +479 -0
- package/skills/orfeu/references/python.md +240 -0
- package/skills/orfeu/scripts/checar.mjs +126 -0
- package/skills/orfeu/scripts/nucleo.mjs +227 -0
- package/skills/trismegisto/SKILL.md +194 -0
- package/skills/trismegisto/references/angular-api.md +2788 -0
- package/skills/trismegisto/references/angular-exports.md +4020 -0
- package/skills/trismegisto/references/angular-recipes.md +1883 -0
- package/skills/trismegisto/references/angular-types.md +492 -0
- package/skills/trismegisto/references/angular.md +390 -0
- package/skills/trismegisto/references/catalogo/icones.json +912 -0
- package/skills/trismegisto/references/catalogo/seletores.json +7013 -0
- package/skills/trismegisto/references/catalogo/tokens.json +240 -0
- package/skills/trismegisto/references/spine-api.md +1530 -0
- package/skills/trismegisto/references/spine-recipes.md +581 -0
- package/skills/trismegisto/references/spine.md +343 -0
- package/skills/trismegisto/scripts/checar.mjs +216 -0
- package/skills/trismegisto/scripts/nucleo.mjs +227 -0
|
@@ -0,0 +1,541 @@
|
|
|
1
|
+
# Receitas — @orfeu/node 1.0.1
|
|
2
|
+
|
|
3
|
+
Todas usam a API real da 1.0.1 ([node-api.md](node-api.md)). Variáveis de ambiente de exemplo: `AUTHORIZER_URL`,
|
|
4
|
+
`REALM_ID`, `APP_ID`, `APP_SECRET` — use os nomes que o projeto já tem.
|
|
5
|
+
|
|
6
|
+
## 1. Express
|
|
7
|
+
|
|
8
|
+
```ts
|
|
9
|
+
import express from 'express';
|
|
10
|
+
import { Level, Method, OrfeuClient, annotateOperation, getRegistry } from '@orfeu/node';
|
|
11
|
+
import { orfeu } from '@orfeu/node/express';
|
|
12
|
+
|
|
13
|
+
const client = new OrfeuClient({
|
|
14
|
+
authorizerUrl: process.env.AUTHORIZER_URL!,
|
|
15
|
+
realmId: process.env.REALM_ID!,
|
|
16
|
+
appId: process.env.APP_ID!,
|
|
17
|
+
secret: process.env.APP_SECRET!,
|
|
18
|
+
});
|
|
19
|
+
const { middleware, guard } = orfeu(client);
|
|
20
|
+
|
|
21
|
+
const app = express();
|
|
22
|
+
app.use(express.json(), middleware); // body parser ANTES dos guards; middleware só captura
|
|
23
|
+
|
|
24
|
+
app.get('/health', guard('health:check', Level.PUBLIC), (_req, res) => res.json({ ok: true }));
|
|
25
|
+
|
|
26
|
+
app.get('/clientes', guard('clientes:list', Level.PRIVATE), async (req, res) => {
|
|
27
|
+
res.json(await repo.list({ owner: req.orfeuUser?.sub }));
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
app.post('/clientes', guard('clientes:create', Level.PROTECTED), async (req, res) => {
|
|
31
|
+
const created = await repo.create(req.body);
|
|
32
|
+
annotateOperation({ target_type: 'cliente', target_id: created.id });
|
|
33
|
+
res.status(201).json(created);
|
|
34
|
+
});
|
|
35
|
+
|
|
36
|
+
app.delete('/clientes/:id', guard('clientes:delete', Level.PROTECTED), async (req, res) => {
|
|
37
|
+
await repo.remove(req.params.id);
|
|
38
|
+
annotateOperation({ target_type: 'cliente', target_id: req.params.id });
|
|
39
|
+
res.status(204).end();
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
// método explícito quando o nome não diz (sync = escrita)
|
|
43
|
+
app.post('/clientes/sync', guard('clientes:sync', Level.PRIVATE, Method.WRITE), syncHandler);
|
|
44
|
+
|
|
45
|
+
// rotas declaradas → catálogo → startup → listen
|
|
46
|
+
for (const op of getRegistry()) client.registerOperation(op);
|
|
47
|
+
await client.startup();
|
|
48
|
+
const server = app.listen(Number(process.env.PORT ?? 3000));
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
- Erro do handler: use o tratamento de erro do Express normalmente; status ≥ 400 vira `outcome: failure`.
|
|
52
|
+
- Express 4 não captura rejeição de handler `async`: envolva em `try/catch` (ou use Express 5).
|
|
53
|
+
|
|
54
|
+
## 2. Fastify
|
|
55
|
+
|
|
56
|
+
```ts
|
|
57
|
+
import Fastify from 'fastify';
|
|
58
|
+
import { Level, OrfeuClient, annotateOperation, getRegistry } from '@orfeu/node';
|
|
59
|
+
import { orfeuFastifyPlugin } from '@orfeu/node/fastify';
|
|
60
|
+
|
|
61
|
+
const client = new OrfeuClient({ /* §1 */ });
|
|
62
|
+
const fastify = Fastify();
|
|
63
|
+
await fastify.register(orfeuFastifyPlugin, { client }); // await: o decorador orfeuGuard precisa existir antes das rotas
|
|
64
|
+
|
|
65
|
+
fastify.get('/clientes', { preHandler: fastify.orfeuGuard('clientes:list', Level.PRIVATE) },
|
|
66
|
+
async (request) => repo.list({ owner: request.orfeuUser?.sub }));
|
|
67
|
+
|
|
68
|
+
fastify.delete<{ Params: { id: string } }>('/clientes/:id',
|
|
69
|
+
{ preHandler: fastify.orfeuGuard('clientes:delete', Level.PROTECTED) },
|
|
70
|
+
async (request, reply) => {
|
|
71
|
+
await repo.remove(request.params.id);
|
|
72
|
+
annotateOperation({ target_type: 'cliente', target_id: request.params.id });
|
|
73
|
+
return reply.code(204).send();
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
for (const op of getRegistry()) client.registerOperation(op);
|
|
77
|
+
await client.startup();
|
|
78
|
+
await fastify.listen({ port: 3000 });
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
`orfeuGuard` devolve um `preHandler` de callback (`(request, reply, done)`): passe-o direto, não o embrulhe
|
|
82
|
+
numa função `async`. Para vários: `preHandler: [outroHook, fastify.orfeuGuard(...)]`.
|
|
83
|
+
|
|
84
|
+
## 3. NestJS
|
|
85
|
+
|
|
86
|
+
```ts
|
|
87
|
+
// app.module.ts
|
|
88
|
+
import { Module } from '@nestjs/common';
|
|
89
|
+
import { OrfeuModule } from '@orfeu/node/nest';
|
|
90
|
+
import { ClientesController } from './clientes.controller';
|
|
91
|
+
|
|
92
|
+
@Module({
|
|
93
|
+
imports: [
|
|
94
|
+
OrfeuModule.forRootAsync({ // opções prontas (leia o env antes; não aceita useFactory)
|
|
95
|
+
authorizerUrl: process.env.AUTHORIZER_URL!,
|
|
96
|
+
realmId: process.env.REALM_ID!,
|
|
97
|
+
appId: process.env.APP_ID!,
|
|
98
|
+
secret: process.env.APP_SECRET!,
|
|
99
|
+
}),
|
|
100
|
+
],
|
|
101
|
+
controllers: [ClientesController],
|
|
102
|
+
})
|
|
103
|
+
export class AppModule {}
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
```ts
|
|
107
|
+
// clientes.controller.ts
|
|
108
|
+
import { Body, Controller, Delete, Get, Param, Post, Req, UseGuards } from '@nestjs/common';
|
|
109
|
+
import { Level, Method, annotateOperation, type TokenClaims } from '@orfeu/node';
|
|
110
|
+
import { Operation, OrfeuGuard, OrfeuUser } from '@orfeu/node/nest';
|
|
111
|
+
|
|
112
|
+
@Controller('clientes')
|
|
113
|
+
@UseGuards(OrfeuGuard)
|
|
114
|
+
export class ClientesController {
|
|
115
|
+
@Get()
|
|
116
|
+
@Operation('clientes:list', Level.PRIVATE)
|
|
117
|
+
list(@OrfeuUser() user: TokenClaims) {
|
|
118
|
+
return this.repo.list({ owner: user.sub });
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
@Post()
|
|
122
|
+
@Operation('clientes:create', Level.PROTECTED)
|
|
123
|
+
async create(@Body() dto: CreateClienteDto) {
|
|
124
|
+
const created = await this.repo.create(dto);
|
|
125
|
+
annotateOperation({ target_type: 'cliente', target_id: created.id });
|
|
126
|
+
return created;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
@Delete(':id')
|
|
130
|
+
@Operation('clientes:delete', Level.PROTECTED, Method.DELETE)
|
|
131
|
+
remove(@Param('id') id: string) {
|
|
132
|
+
annotateOperation({ target_type: 'cliente', target_id: id });
|
|
133
|
+
return this.repo.remove(id);
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
@Post('webhook')
|
|
137
|
+
@Operation('clientes:webhook', Level.PRIVATE, Method.WRITE)
|
|
138
|
+
webhook(@Req() req: { orfeuApiToken?: { tokenId: string; appId: string } }) {
|
|
139
|
+
// chamado por outro backend com x-api-token concedido a esta operação
|
|
140
|
+
return this.handle(req.orfeuApiToken!.appId);
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
- Guard global em vez de `@UseGuards` por controller: `{ provide: APP_GUARD, useClass: OrfeuGuard }` num
|
|
146
|
+
módulo do app. Métodos sem `@Operation` continuam **abertos** — confira todos.
|
|
147
|
+
- `OrfeuClient` é injetável (`constructor(private readonly orfeu: OrfeuClient) {}`) para `checkPermission`,
|
|
148
|
+
`flushAudit` etc.
|
|
149
|
+
- Encerramento: `app.enableShutdownHooks()`; o `OrfeuModule` para a recarga e envia a auditoria no `onModuleDestroy` (`@orfeu/node` ≥ 1.1 / `orfeu` ≥ 1.1). Antes, num provider, `async onApplicationShutdown() { await this.orfeu.flushAudit(); }`.
|
|
150
|
+
|
|
151
|
+
## 4. Apollo Server (HTTP + WebSocket)
|
|
152
|
+
|
|
153
|
+
```ts
|
|
154
|
+
import { createServer } from 'node:http';
|
|
155
|
+
import { ApolloServer } from '@apollo/server';
|
|
156
|
+
import { startStandaloneServer } from '@apollo/server/standalone';
|
|
157
|
+
import { makeExecutableSchema } from '@graphql-tools/schema';
|
|
158
|
+
import { WebSocketServer } from 'ws';
|
|
159
|
+
import { useServer } from 'graphql-ws/use/ws';
|
|
160
|
+
import { Level, Method, OrfeuClient, annotateOperation } from '@orfeu/node';
|
|
161
|
+
import {
|
|
162
|
+
assertSchemaSecured, operation, orfeuPlugin, orfeuWsContext, secureResolvers, type OrfeuContext,
|
|
163
|
+
} from '@orfeu/node/apollo';
|
|
164
|
+
|
|
165
|
+
const client = new OrfeuClient({ /* §1 */ });
|
|
166
|
+
|
|
167
|
+
const resolvers = {
|
|
168
|
+
Query: {
|
|
169
|
+
clientes: operation(Level.PRIVATE, async (_: unknown, __: unknown, ctx: OrfeuContext) => repo.list(ctx.orfeuUser!.sub)),
|
|
170
|
+
versao: operation(Level.PUBLIC, () => '1.0.0'),
|
|
171
|
+
},
|
|
172
|
+
Mutation: {
|
|
173
|
+
removerCliente: operation(Level.PROTECTED, async (_: unknown, { id }: { id: string }) => {
|
|
174
|
+
await repo.remove(id);
|
|
175
|
+
annotateOperation({ target_type: 'cliente', target_id: id });
|
|
176
|
+
return { status: 200, message: 'Cliente removido.', data: id };
|
|
177
|
+
}, { id: 'clientes:delete', method: Method.DELETE }),
|
|
178
|
+
},
|
|
179
|
+
Subscription: {
|
|
180
|
+
clienteAlterado: operation(Level.PRIVATE, {
|
|
181
|
+
subscribe: () => events.iterator('cliente'), // AsyncIterable
|
|
182
|
+
resolve: (payload: unknown) => payload,
|
|
183
|
+
}),
|
|
184
|
+
},
|
|
185
|
+
Cliente: { /* resolvers de campo de objeto não precisam de operation() */ },
|
|
186
|
+
};
|
|
187
|
+
|
|
188
|
+
const secured = secureResolvers(client, resolvers, {
|
|
189
|
+
// 403 em Query/Mutation vira resultado (envelope) em vez de erro; 401 continua GraphQLError
|
|
190
|
+
onForbidden: () => ({ status: 403, message: 'Você não tem permissão para esta operação.', data: null }),
|
|
191
|
+
});
|
|
192
|
+
const schema = makeExecutableSchema({ typeDefs, resolvers: secured });
|
|
193
|
+
assertSchemaSecured(schema); // falha na subida se algum campo raiz escapou
|
|
194
|
+
await client.startup(); // secureResolvers já registrou as operações no client
|
|
195
|
+
|
|
196
|
+
const apollo = new ApolloServer<OrfeuContext>({ schema, plugins: [orfeuPlugin(client)] });
|
|
197
|
+
const { url } = await startStandaloneServer(apollo, { listen: { port: 4000 }, context: async () => ({}) });
|
|
198
|
+
|
|
199
|
+
// subscriptions: o graphql-ws executa o schema sem os plugins do Apollo — o contexto precisa do orfeuWsContext
|
|
200
|
+
const httpServer = createServer();
|
|
201
|
+
const wsServer = new WebSocketServer({ server: httpServer, path: '/graphql' });
|
|
202
|
+
useServer({ schema, context: orfeuWsContext(client, wsExtra) }, wsServer);
|
|
203
|
+
httpServer.listen(4001);
|
|
204
|
+
```
|
|
205
|
+
|
|
206
|
+
O `extra` do `orfeuWsContext` recebe o `connectionParams` do cliente — dado que **o cliente escreve**.
|
|
207
|
+
Devolva só o que o app precisa (módulos, uma allowlist de headers), nunca `{ ...connectionParams }`:
|
|
208
|
+
|
|
209
|
+
```ts
|
|
210
|
+
// Headers de credencial e de rastreio que podem ir do connection_init para o contexto. Só string.
|
|
211
|
+
const WS_PARAMS = ['x-access-token', 'x-app-token', 'x-api-token', 'traceparent', 'x-route-id', 'x-client-id'] as const;
|
|
212
|
+
|
|
213
|
+
function wsExtra({ connectionParams }: { connectionParams?: Record<string, unknown> }) {
|
|
214
|
+
const out: Partial<Record<(typeof WS_PARAMS)[number], string>> = {};
|
|
215
|
+
if (!connectionParams || typeof connectionParams !== 'object') return out;
|
|
216
|
+
const headers = connectionParams.headers as Record<string, unknown> | undefined;
|
|
217
|
+
for (const key of WS_PARAMS) {
|
|
218
|
+
// mesma ordem do Orfeu: raiz primeiro, depois `headers`
|
|
219
|
+
const value = connectionParams[key] ?? (headers && typeof headers === 'object' ? headers[key] : undefined);
|
|
220
|
+
if (typeof value === 'string') out[key] = value;
|
|
221
|
+
}
|
|
222
|
+
return out;
|
|
223
|
+
}
|
|
224
|
+
```
|
|
225
|
+
|
|
226
|
+
Desde a 1.0.1 o `orfeuWsContext` já descarta as chaves reservadas (`ORFEU_RESERVED_CONTEXT_KEYS`) que o
|
|
227
|
+
`extra` devolver; a allowlist continua valendo como segunda barreira e impede que chave desconhecida do
|
|
228
|
+
cliente apareça no `ctx` dos resolvers.
|
|
229
|
+
|
|
230
|
+
### Contexto montado pelo app com usuário já validado (`trustUser`)
|
|
231
|
+
|
|
232
|
+
Quando o app valida o token por conta própria (sessão em cookie, token vindo de outro lugar) e monta o
|
|
233
|
+
contexto sem a credencial crua, o usuário entra por `trustUser` — atribuir `ctx.orfeuUser` direto dá 401
|
|
234
|
+
a partir da 1.0.1:
|
|
235
|
+
|
|
236
|
+
```ts
|
|
237
|
+
import { trustUser, type OrfeuContext } from '@orfeu/node/apollo';
|
|
238
|
+
|
|
239
|
+
// HTTP
|
|
240
|
+
context: async ({ req }) => trustUser<OrfeuContext>({}, await client.validateToken(tokenDaSessao(req))),
|
|
241
|
+
|
|
242
|
+
// WebSocket: o extra não recebe o contexto; embrulhe o que o orfeuWsContext devolve
|
|
243
|
+
const base = orfeuWsContext(client, wsExtra);
|
|
244
|
+
useServer({ schema, context: async (ctx) => trustUser(await base(ctx), await claimsDaConexao(ctx)) }, wsServer);
|
|
245
|
+
```
|
|
246
|
+
|
|
247
|
+
- A confiança vale por identidade: não copie o contexto com `{ ...ctx }` depois do `trustUser` (a marca não
|
|
248
|
+
vai junto) nem troque `ctx.orfeuUser` depois.
|
|
249
|
+
- Só passe claims que o app validou. `trustUser` não valida nada: ele declara.
|
|
250
|
+
|
|
251
|
+
- Ids padrão: `query:clientes`, `query:versao`, `subscription:clienteAlterado` (o 3º argumento troca).
|
|
252
|
+
- Cada campo precisa de uma **função nova**: `operation(Level.PRIVATE, listar)` em dois campos lança; use
|
|
253
|
+
`operation(Level.PRIVATE, (...a) => listar(...a))`.
|
|
254
|
+
- O envelope `{ status, message, data }` com `status >= 400` é auditado como falha (`envelopeOutcome`). Se o
|
|
255
|
+
app não usa envelope, nada muda.
|
|
256
|
+
- No cliente WebSocket, mande a credencial em `connectionParams: { 'x-access-token': token }` (ou dentro de
|
|
257
|
+
`headers`); `routeId`/`clientId` também podem ir ali. O `orfeuWsContext` lê tudo isso sozinho; o `extra`
|
|
258
|
+
não precisa (nem deve) repassar o `connectionParams`.
|
|
259
|
+
- Com Express (`expressMiddleware`), o `orfeuPlugin` funciona igual; o `context` pode trazer o que o app
|
|
260
|
+
quiser.
|
|
261
|
+
|
|
262
|
+
## 5. BFF chamando o backend em nome do usuário
|
|
263
|
+
|
|
264
|
+
```ts
|
|
265
|
+
// BFF (GraphQL): resolver protegido chama o backend REST repassando o contexto
|
|
266
|
+
import { orfeuHeaders } from '@orfeu/node';
|
|
267
|
+
|
|
268
|
+
const resolvers = {
|
|
269
|
+
Query: {
|
|
270
|
+
clientes: operation(Level.PRIVATE, async (_: unknown, __: unknown, ctx: OrfeuContext) => {
|
|
271
|
+
const res = await fetch(`${process.env.CLIENTES_API}/clientes`, { headers: orfeuHeaders(ctx) });
|
|
272
|
+
if (!res.ok) return { status: res.status, message: 'Falha ao listar clientes.', data: null };
|
|
273
|
+
return { status: 200, data: await res.json() };
|
|
274
|
+
}),
|
|
275
|
+
},
|
|
276
|
+
};
|
|
277
|
+
```
|
|
278
|
+
|
|
279
|
+
```ts
|
|
280
|
+
// backend (Express): a mesma regra, com o MESMO usuário
|
|
281
|
+
app.get('/clientes', guard('clientes:list', Level.PRIVATE), listHandler);
|
|
282
|
+
```
|
|
283
|
+
|
|
284
|
+
Resultado: dois eventos de auditoria com o mesmo `trace_id` — BFF `entry: true` (ação do usuário, com IP) e
|
|
285
|
+
backend `entry: false` com `parent_span_id` = span do BFF. Cada serviço audita só a própria operação. O
|
|
286
|
+
backend confere a permissão do usuário de novo: as duas operações precisam estar liberadas para ele.
|
|
287
|
+
|
|
288
|
+
Em Express: `fetch(url, { headers: orfeuHeaders(req) })`. Com axios: `axios.get(url, { headers: orfeuHeaders(ctx) })`.
|
|
289
|
+
|
|
290
|
+
## 6. Serviço chamando outro com credencial própria
|
|
291
|
+
|
|
292
|
+
Quando a chamada não é "do usuário" (job, integração), use um `x-api-token` emitido no Argos para o serviço
|
|
293
|
+
de destino e mantenha só o trace:
|
|
294
|
+
|
|
295
|
+
```ts
|
|
296
|
+
const headers = {
|
|
297
|
+
...orfeuHeaders(req, { credential: false }), // traceparent + x-route-id + x-client-id
|
|
298
|
+
'x-api-token': process.env.CLIENTES_API_TOKEN!, // concedido às operações do destino
|
|
299
|
+
};
|
|
300
|
+
await fetch(`${process.env.CLIENTES_API}/clientes/sync`, { method: 'POST', headers });
|
|
301
|
+
```
|
|
302
|
+
|
|
303
|
+
Se a requisição carregar **também** `x-access-token`/`x-app-token`, o destino usa a do usuário (precedência)
|
|
304
|
+
e ignora o `x-api-token`. Fora de uma requisição (cron), não há trace: mande só o `x-api-token` — o destino abre
|
|
305
|
+
um trace novo (`entry: true`).
|
|
306
|
+
|
|
307
|
+
## 7. Anotar o alvo na auditoria
|
|
308
|
+
|
|
309
|
+
```ts
|
|
310
|
+
annotateOperation({
|
|
311
|
+
target_type: 'pedido',
|
|
312
|
+
target_id: pedido.id,
|
|
313
|
+
details: { status_anterior: antes.status, status_novo: pedido.status }, // pequeno, sem segredos/PII
|
|
314
|
+
});
|
|
315
|
+
```
|
|
316
|
+
|
|
317
|
+
Chame dentro do handler/resolver protegido, depois de saber o alvo. Funciona através de `await`. Em código que
|
|
318
|
+
sai do contexto assíncrono (ex.: callback de `EventEmitter` registrado antes da requisição) a anotação se perde
|
|
319
|
+
— chame no fluxo do handler.
|
|
320
|
+
|
|
321
|
+
## 8. Operação fora dos adapters (fila, socket próprio, CLI)
|
|
322
|
+
|
|
323
|
+
```ts
|
|
324
|
+
import {
|
|
325
|
+
Level, Method, OrfeuTokenError, recordOperation, registerOperation, resolveActorType, resolveTrace,
|
|
326
|
+
type TokenClaims,
|
|
327
|
+
} from '@orfeu/node';
|
|
328
|
+
|
|
329
|
+
const OP = { identifier: 'relatorios:export', method: Method.READ, level: Level.PRIVATE } as const;
|
|
330
|
+
registerOperation(OP); // antes do startup (o loop getRegistry() → client.registerOperation copia)
|
|
331
|
+
|
|
332
|
+
export async function onMessage(msg: { token: string; traceparent?: string; reportId: string }): Promise<void> {
|
|
333
|
+
const startedAt = Date.now();
|
|
334
|
+
const trace = resolveTrace(msg.traceparent);
|
|
335
|
+
let user: TokenClaims | undefined;
|
|
336
|
+
let permissionResult = 'unauthorized';
|
|
337
|
+
let status = 401;
|
|
338
|
+
let errorMessage: string | undefined;
|
|
339
|
+
try {
|
|
340
|
+
user = await client.validateToken(msg.token); // JWT (x-access-token)
|
|
341
|
+
if (!client.checkPermission(user, OP.identifier, OP.method)) {
|
|
342
|
+
permissionResult = 'forbidden'; status = 403; errorMessage = 'Forbidden: Insufficient permissions.';
|
|
343
|
+
return;
|
|
344
|
+
}
|
|
345
|
+
permissionResult = 'allowed';
|
|
346
|
+
await exportReport(msg.reportId);
|
|
347
|
+
status = 200;
|
|
348
|
+
} catch (err) {
|
|
349
|
+
if (err instanceof OrfeuTokenError) errorMessage = 'Unauthorized: Invalid token.';
|
|
350
|
+
else { status = 500; errorMessage = (err as Error).message; throw err; }
|
|
351
|
+
} finally {
|
|
352
|
+
recordOperation(client, {
|
|
353
|
+
operationId: OP.identifier, method: OP.method, level: OP.level,
|
|
354
|
+
appId: client.appId,
|
|
355
|
+
actorType: resolveActorType(user, OP.level),
|
|
356
|
+
user: user?.sub,
|
|
357
|
+
permissionResult, status, success: status < 400, errorMessage,
|
|
358
|
+
durationMs: Date.now() - startedAt, startedAt, trace,
|
|
359
|
+
annotation: { target_type: 'relatorio', target_id: msg.reportId },
|
|
360
|
+
});
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
```
|
|
364
|
+
|
|
365
|
+
Use isto só onde não há adapter. Para tokens opacos: `validateAppToken(token)` (usuário) ou
|
|
366
|
+
`validateApiToken(token, id, method)` (serviço; `null` = sem acesso).
|
|
367
|
+
|
|
368
|
+
## 9. Log de operação em outro destino
|
|
369
|
+
|
|
370
|
+
```ts
|
|
371
|
+
import pino from 'pino';
|
|
372
|
+
const log = pino();
|
|
373
|
+
const client = new OrfeuClient({
|
|
374
|
+
...opts,
|
|
375
|
+
logger: (record) => (record.level === 'ERROR' ? log.warn(record, record.message) : log.info(record, record.message)),
|
|
376
|
+
// logger: false → desliga o log (a auditoria continua)
|
|
377
|
+
// audit: false → desliga a auditoria (o log continua)
|
|
378
|
+
});
|
|
379
|
+
```
|
|
380
|
+
|
|
381
|
+
O logger não deve lançar (erros são engolidos). A linha não volta ao chamador: pode ter o motivo detalhado
|
|
382
|
+
de uma negação.
|
|
383
|
+
|
|
384
|
+
## 10. Subida resiliente e permissões atualizadas
|
|
385
|
+
|
|
386
|
+
```ts
|
|
387
|
+
import { OrfeuConfigError } from '@orfeu/node';
|
|
388
|
+
|
|
389
|
+
async function startOrfeu(): Promise<void> {
|
|
390
|
+
for (let attempt = 0; ; attempt++) {
|
|
391
|
+
try {
|
|
392
|
+
await client.startup();
|
|
393
|
+
return;
|
|
394
|
+
} catch (err) {
|
|
395
|
+
if (err instanceof OrfeuConfigError) throw err; // configuração errada: não adianta repetir
|
|
396
|
+
const wait = Math.min(30_000, 1_000 * 2 ** attempt);
|
|
397
|
+
console.warn(`[app] Argos indisponível na subida (${(err as Error).message}); nova tentativa em ${wait / 1000}s`);
|
|
398
|
+
await new Promise((r) => setTimeout(r, wait));
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
```
|
|
404
|
+
|
|
405
|
+
Um `OrfeuAuthError` com HTTP 401 na subida quase sempre é `APP_ID`/`APP_SECRET` errados; repetir não resolve.
|
|
406
|
+
HTTP 400 `invalid_request` no `/apps/token` é `APP_ID` que não é UUID ou `APP_SECRET` **vazio** (variável não preenchida).
|
|
407
|
+
|
|
408
|
+
**Permissões atualizadas** (`@orfeu/node` ≥ 1.1 / `orfeu` ≥ 1.1): o client revalida sozinho o catálogo com os grupos liberados a cada 60 s
|
|
409
|
+
(±20%), com `If-None-Match` (304 quando nada mudou), troca o catálogo de uma vez, reautentica no 401 e, se o Argos
|
|
410
|
+
estiver fora, mantém o catálogo anterior (`permissionsStale` vira `true` depois de 5 ciclos sem sucesso). Liberar ou
|
|
411
|
+
**revogar** um grupo no Argos vale em até ~1 min, sem reiniciar. Ajuste ou desligue no construtor:
|
|
412
|
+
|
|
413
|
+
```ts
|
|
414
|
+
const client = new OrfeuClient({ /* … */, permissionsRefresh: { intervalMs: 60_000, jitter: 0.2 } }); // ou false
|
|
415
|
+
client.lastPermissionsSyncAt; // Date | null — último sucesso
|
|
416
|
+
client.permissionsStale; // true após 5 intervalos sem sucesso (bom para o /health, sem derrubar)
|
|
417
|
+
```
|
|
418
|
+
|
|
419
|
+
Versão anterior a essa: as permissões só eram lidas no `startup()` — recarregue com `fetchOperations()` num
|
|
420
|
+
`setInterval` (`unref()`), chamando `authenticate()` antes de repetir quando der 401 (o token do serviço vence).
|
|
421
|
+
|
|
422
|
+
## 11. Encerramento sem perder eventos
|
|
423
|
+
|
|
424
|
+
```ts
|
|
425
|
+
for (const signal of ['SIGTERM', 'SIGINT'] as const) {
|
|
426
|
+
process.once(signal, async () => {
|
|
427
|
+
server.close(); // para de aceitar conexões
|
|
428
|
+
await client.close(5_000); // para a recarga de permissões e envia a fila de auditoria (máx. 5 s)
|
|
429
|
+
process.exit(0);
|
|
430
|
+
});
|
|
431
|
+
}
|
|
432
|
+
```
|
|
433
|
+
|
|
434
|
+
Em container sem init, o processo Node é o PID 1 e só termina no SIGTERM se tratar o sinal (como acima).
|
|
435
|
+
`close()` existe a partir de `@orfeu/node` ≥ 1.1 / `orfeu` ≥ 1.1; antes, `flushAudit()` (não havia recarga para parar). Fastify (`fastify.close()`),
|
|
436
|
+
Nest (`app.close()`) e o `orfeuPlugin` do Apollo (`server.stop()`) já chamam o encerramento do client sozinhos.
|
|
437
|
+
|
|
438
|
+
## 12. Testes
|
|
439
|
+
|
|
440
|
+
### Handler isolado
|
|
441
|
+
|
|
442
|
+
```ts
|
|
443
|
+
const req = { orfeuUser: { sub: 'u1', realmId: 'r', groups: ['g'], exp: 0, raw: {} }, params: { id: '1' } } as any;
|
|
444
|
+
const res = { status: vi.fn().mockReturnThis(), json: vi.fn(), end: vi.fn() } as any;
|
|
445
|
+
await deleteHandler(req, res);
|
|
446
|
+
```
|
|
447
|
+
|
|
448
|
+
`annotateOperation` fora de uma operação devolve `false` e não quebra o teste.
|
|
449
|
+
|
|
450
|
+
Resolver do Apollo testado pelo `secureResolvers` (não chamando a função crua): monte o contexto com
|
|
451
|
+
`trustUser({}, claims)`. Um `{ orfeuUser: claims }` literal não tem a marca da lib e responde 401 desde a
|
|
452
|
+
1.0.1.
|
|
453
|
+
|
|
454
|
+
### Integração com um Argos simulado
|
|
455
|
+
|
|
456
|
+
```ts
|
|
457
|
+
// test/fake-argos.ts — só os endpoints que o SDK usa no caminho comum
|
|
458
|
+
import { createServer } from 'node:http';
|
|
459
|
+
import type { AddressInfo } from 'node:net';
|
|
460
|
+
import { exportJWK, generateKeyPair, SignJWT } from 'jose';
|
|
461
|
+
|
|
462
|
+
export async function startFakeArgos(opts: { realm?: string; appId?: string; secret?: string; allowedGroups?: Record<string, string[]> } = {}) {
|
|
463
|
+
const realm = opts.realm ?? 'test-realm';
|
|
464
|
+
const appId = opts.appId ?? '11111111-1111-4111-8111-111111111111';
|
|
465
|
+
const secret = opts.secret ?? 's3cret';
|
|
466
|
+
const { privateKey, publicKey } = await generateKeyPair('RS256');
|
|
467
|
+
const jwk = { ...(await exportJWK(publicKey)), kid: 'k1', alg: 'RS256', use: 'sig' };
|
|
468
|
+
let synced: Array<{ identifier: string; method: string; level: string }> = [];
|
|
469
|
+
const audits: any[] = [];
|
|
470
|
+
|
|
471
|
+
const server = createServer(async (req, res) => {
|
|
472
|
+
let raw = '';
|
|
473
|
+
for await (const chunk of req) raw += chunk;
|
|
474
|
+
const body = raw ? JSON.parse(raw) : undefined;
|
|
475
|
+
const path = new URL(req.url ?? '/', 'http://x').pathname.replace(`/realms/${realm}/`, '');
|
|
476
|
+
const send = (status: number, data: unknown) => { res.writeHead(status, { 'content-type': 'application/json' }); res.end(JSON.stringify(data)); };
|
|
477
|
+
|
|
478
|
+
if (path === 'protocol/openid-connect/certs') return send(200, { keys: [jwk] });
|
|
479
|
+
if (path === 'apps/token') {
|
|
480
|
+
return body?.app_id === appId && body?.secret === secret ? send(200, { access_token: 'app-token' }) : send(401, { error: 'unauthorized' });
|
|
481
|
+
}
|
|
482
|
+
if (path === 'apps/operations/sync') { synced = body.operations; return send(200, { synced: synced.length }); }
|
|
483
|
+
if (path === 'apps/operations') {
|
|
484
|
+
return send(200, { operations: synced.map((op, i) => ({
|
|
485
|
+
operation_id: `00000000-0000-4000-8000-${String(i).padStart(12, '0')}`,
|
|
486
|
+
...op, allowed_groups: opts.allowedGroups?.[op.identifier] ?? [],
|
|
487
|
+
})) });
|
|
488
|
+
}
|
|
489
|
+
if (path === 'audit/events') { audits.push(...body.events); return send(202, { accepted: body.events.length }); }
|
|
490
|
+
return send(404, { error: 'not_found' }); // sem introspecção: x-app-token é recusado, x-api-token cai no validate (404 → 401)
|
|
491
|
+
});
|
|
492
|
+
await new Promise<void>((resolve) => server.listen(0, 'localhost', resolve));
|
|
493
|
+
const { port } = server.address() as AddressInfo;
|
|
494
|
+
|
|
495
|
+
return {
|
|
496
|
+
url: `http://localhost:${port}`, realm, appId, secret, audits,
|
|
497
|
+
signUser: (sub: string, groups: string[] = []) =>
|
|
498
|
+
new SignJWT({ groups, realm_id: realm }).setProtectedHeader({ alg: 'RS256', kid: 'k1' })
|
|
499
|
+
.setSubject(sub).setIssuedAt().setExpirationTime('1h').sign(privateKey),
|
|
500
|
+
close: () => new Promise<void>((resolve) => server.close(() => resolve())),
|
|
501
|
+
};
|
|
502
|
+
}
|
|
503
|
+
```
|
|
504
|
+
|
|
505
|
+
```ts
|
|
506
|
+
// clientes.test.ts (vitest)
|
|
507
|
+
import { afterAll, beforeAll, expect, it } from 'vitest';
|
|
508
|
+
import { OrfeuClient, clearRegistry, getRegistry } from '@orfeu/node';
|
|
509
|
+
import { startFakeArgos } from './fake-argos';
|
|
510
|
+
|
|
511
|
+
let argos: Awaited<ReturnType<typeof startFakeArgos>>;
|
|
512
|
+
let base: string;
|
|
513
|
+
let client: OrfeuClient;
|
|
514
|
+
|
|
515
|
+
beforeAll(async () => {
|
|
516
|
+
clearRegistry();
|
|
517
|
+
argos = await startFakeArgos({ allowedGroups: { 'clientes:delete': ['admins'] } });
|
|
518
|
+
client = new OrfeuClient({ authorizerUrl: argos.url, realmId: argos.realm, appId: argos.appId, secret: argos.secret, logger: false });
|
|
519
|
+
const app = buildApp(client); // função do app que declara as rotas com guard()
|
|
520
|
+
for (const op of getRegistry()) client.registerOperation(op);
|
|
521
|
+
await client.startup();
|
|
522
|
+
const server = app.listen(0);
|
|
523
|
+
base = `http://localhost:${(server.address() as any).port}`;
|
|
524
|
+
});
|
|
525
|
+
afterAll(() => argos.close());
|
|
526
|
+
|
|
527
|
+
it('401 sem credencial, 403 sem grupo, 204 com grupo', async () => {
|
|
528
|
+
expect((await fetch(`${base}/clientes/1`, { method: 'DELETE' })).status).toBe(401);
|
|
529
|
+
const semGrupo = await argos.signUser('22222222-2222-4222-8222-222222222222', ['vendas']);
|
|
530
|
+
expect((await fetch(`${base}/clientes/1`, { method: 'DELETE', headers: { 'x-access-token': semGrupo } })).status).toBe(403);
|
|
531
|
+
const admin = await argos.signUser('33333333-3333-4333-8333-333333333333', ['admins']);
|
|
532
|
+
expect((await fetch(`${base}/clientes/1`, { method: 'DELETE', headers: { 'x-access-token': admin } })).status).toBe(204);
|
|
533
|
+
|
|
534
|
+
await client.flushAudit();
|
|
535
|
+
expect(argos.audits.map((e) => e.outcome)).toEqual(['denied', 'denied', 'success']);
|
|
536
|
+
});
|
|
537
|
+
```
|
|
538
|
+
|
|
539
|
+
- `jose` vem com o `@orfeu/node`, mas declare-o como `devDependency` do app se o teste o importa.
|
|
540
|
+
- `authorizerUrl` do simulado não tem `/api`: o SDK monta `<authorizerUrl>/realms/<realm>/…`.
|
|
541
|
+
- `clearRegistry()` antes de cada arquivo que declara rotas: o registro global é do processo.
|