@acropole/skills 0.0.0-stage → 1.0.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.
Files changed (90) hide show
  1. package/README.md +180 -2
  2. package/agents/revisor-deploy.md +73 -0
  3. package/agents/revisor-documentacao.md +78 -0
  4. package/agents/revisor-orfeu.md +80 -0
  5. package/agents/revisor-trismegisto.md +81 -0
  6. package/bin/install.js +252 -0
  7. package/package.json +15 -4
  8. package/skills/acropole/SKILL.md +75 -0
  9. package/skills/acropole/references/fluxos/doctor.md +55 -0
  10. package/skills/acropole/references/fluxos/endpoint-novo.md +22 -0
  11. package/skills/acropole/references/fluxos/revisar.md +56 -0
  12. package/skills/acropole/references/fluxos/tela-nova.md +27 -0
  13. package/skills/acropole/scripts/doctor.mjs +439 -0
  14. package/skills/angular/SKILL.md +152 -0
  15. package/skills/angular/references/armadilhas.md +95 -0
  16. package/skills/angular/references/dados.md +251 -0
  17. package/skills/angular/references/estrutura.md +260 -0
  18. package/skills/angular/references/features.md +219 -0
  19. package/skills/angular/references/testes-build.md +230 -0
  20. package/skills/angular/scripts/checar.mjs +182 -0
  21. package/skills/angular/scripts/nucleo.mjs +227 -0
  22. package/skills/apollo/SKILL.md +222 -0
  23. package/skills/apollo/references/armadilhas.md +95 -0
  24. package/skills/apollo/references/envelope-erros.md +120 -0
  25. package/skills/apollo/references/estrutura-bootstrap.md +299 -0
  26. package/skills/apollo/references/schema-resolvers.md +183 -0
  27. package/skills/apollo/references/subscriptions.md +224 -0
  28. package/skills/apollo/references/testes-build.md +180 -0
  29. package/skills/apollo/scripts/checar.mjs +160 -0
  30. package/skills/apollo/scripts/nucleo.mjs +227 -0
  31. package/skills/docker/SKILL.md +102 -0
  32. package/skills/docker/references/modelos.md +251 -0
  33. package/skills/docker/references/porques.md +282 -0
  34. package/skills/documentacao/SKILL.md +146 -0
  35. package/skills/documentacao/references/checklist-coerencia.md +59 -0
  36. package/skills/documentacao/references/ligar-app-novo.md +107 -0
  37. package/skills/documentacao/references/modelo-especificacao.md +51 -0
  38. package/skills/documentacao/references/modelo-readme.md +75 -0
  39. package/skills/documentacao/scripts/checar.mjs +454 -0
  40. package/skills/documentacao/scripts/nucleo.mjs +227 -0
  41. package/skills/express/SKILL.md +154 -0
  42. package/skills/express/references/dados.md +180 -0
  43. package/skills/express/references/estrutura.md +154 -0
  44. package/skills/express/references/middlewares.md +227 -0
  45. package/skills/express/references/rotas-erros.md +274 -0
  46. package/skills/express/references/testes-deploy.md +150 -0
  47. package/skills/express/scripts/checar.mjs +115 -0
  48. package/skills/express/scripts/nucleo.mjs +227 -0
  49. package/skills/fastapi/SKILL.md +129 -0
  50. package/skills/fastapi/references/banco.md +185 -0
  51. package/skills/fastapi/references/estrutura.md +281 -0
  52. package/skills/fastapi/references/integracoes.md +145 -0
  53. package/skills/fastapi/references/rotas-erros.md +140 -0
  54. package/skills/fastapi/references/testes-deploy.md +190 -0
  55. package/skills/fastapi/scripts/checar.mjs +108 -0
  56. package/skills/fastapi/scripts/nucleo.mjs +227 -0
  57. package/skills/hefesto/SKILL.md +119 -0
  58. package/skills/hefesto/references/conceitos.md +131 -0
  59. package/skills/hefesto/references/diagnostico.md +70 -0
  60. package/skills/hefesto/references/fluxo.md +122 -0
  61. package/skills/hefesto/references/preparar-app.md +105 -0
  62. package/skills/orfeu/SKILL.md +162 -0
  63. package/skills/orfeu/references/angular-api.md +201 -0
  64. package/skills/orfeu/references/angular-armadilhas.md +116 -0
  65. package/skills/orfeu/references/angular-recipes.md +474 -0
  66. package/skills/orfeu/references/angular.md +212 -0
  67. package/skills/orfeu/references/diferencas.md +56 -0
  68. package/skills/orfeu/references/node-api.md +348 -0
  69. package/skills/orfeu/references/node-armadilhas.md +158 -0
  70. package/skills/orfeu/references/node-recipes.md +534 -0
  71. package/skills/orfeu/references/node.md +204 -0
  72. package/skills/orfeu/references/python-api.md +346 -0
  73. package/skills/orfeu/references/python-recipes.md +479 -0
  74. package/skills/orfeu/references/python.md +234 -0
  75. package/skills/orfeu/scripts/checar.mjs +126 -0
  76. package/skills/orfeu/scripts/nucleo.mjs +227 -0
  77. package/skills/trismegisto/SKILL.md +194 -0
  78. package/skills/trismegisto/references/angular-api.md +2788 -0
  79. package/skills/trismegisto/references/angular-exports.md +4020 -0
  80. package/skills/trismegisto/references/angular-recipes.md +1883 -0
  81. package/skills/trismegisto/references/angular-types.md +492 -0
  82. package/skills/trismegisto/references/angular.md +390 -0
  83. package/skills/trismegisto/references/catalogo/icones.json +912 -0
  84. package/skills/trismegisto/references/catalogo/seletores.json +7013 -0
  85. package/skills/trismegisto/references/catalogo/tokens.json +240 -0
  86. package/skills/trismegisto/references/spine-api.md +1530 -0
  87. package/skills/trismegisto/references/spine-recipes.md +581 -0
  88. package/skills/trismegisto/references/spine.md +343 -0
  89. package/skills/trismegisto/scripts/checar.mjs +216 -0
  90. package/skills/trismegisto/scripts/nucleo.mjs +227 -0
@@ -0,0 +1,534 @@
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()` e, 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
+ // grupos liberados (allowed_groups) só são lidos no startup: recarregue de tempos em tempos
404
+ async function refreshPermissions(): Promise<void> {
405
+ try {
406
+ await client.fetchOperations();
407
+ } catch {
408
+ await client.authenticate(); // token do serviço vence; fetchOperations não reautentica sozinho
409
+ await client.fetchOperations();
410
+ }
411
+ }
412
+ setInterval(() => { refreshPermissions().catch((e) => console.warn('[app] permissões não recarregadas', e)); }, 5 * 60_000).unref();
413
+ ```
414
+
415
+ Um `OrfeuAuthError` com HTTP 401 na subida quase sempre é `APP_ID`/`APP_SECRET` errados; repetir não resolve.
416
+
417
+ ## 11. Encerramento sem perder eventos
418
+
419
+ ```ts
420
+ for (const signal of ['SIGTERM', 'SIGINT'] as const) {
421
+ process.once(signal, async () => {
422
+ server.close(); // para de aceitar conexões
423
+ await client.flushAudit(5_000); // envia a fila de auditoria (espera no máximo 5 s)
424
+ process.exit(0);
425
+ });
426
+ }
427
+ ```
428
+
429
+ Em container sem init, o processo Node é o PID 1 e só termina no SIGTERM se tratar o sinal (como acima).
430
+
431
+ ## 12. Testes
432
+
433
+ ### Handler isolado
434
+
435
+ ```ts
436
+ const req = { orfeuUser: { sub: 'u1', realmId: 'r', groups: ['g'], exp: 0, raw: {} }, params: { id: '1' } } as any;
437
+ const res = { status: vi.fn().mockReturnThis(), json: vi.fn(), end: vi.fn() } as any;
438
+ await deleteHandler(req, res);
439
+ ```
440
+
441
+ `annotateOperation` fora de uma operação devolve `false` e não quebra o teste.
442
+
443
+ Resolver do Apollo testado pelo `secureResolvers` (não chamando a função crua): monte o contexto com
444
+ `trustUser({}, claims)`. Um `{ orfeuUser: claims }` literal não tem a marca da lib e responde 401 desde a
445
+ 1.0.1.
446
+
447
+ ### Integração com um Argos simulado
448
+
449
+ ```ts
450
+ // test/fake-argos.ts — só os endpoints que o SDK usa no caminho comum
451
+ import { createServer } from 'node:http';
452
+ import type { AddressInfo } from 'node:net';
453
+ import { exportJWK, generateKeyPair, SignJWT } from 'jose';
454
+
455
+ export async function startFakeArgos(opts: { realm?: string; appId?: string; secret?: string; allowedGroups?: Record<string, string[]> } = {}) {
456
+ const realm = opts.realm ?? 'test-realm';
457
+ const appId = opts.appId ?? '11111111-1111-4111-8111-111111111111';
458
+ const secret = opts.secret ?? 's3cret';
459
+ const { privateKey, publicKey } = await generateKeyPair('RS256');
460
+ const jwk = { ...(await exportJWK(publicKey)), kid: 'k1', alg: 'RS256', use: 'sig' };
461
+ let synced: Array<{ identifier: string; method: string; level: string }> = [];
462
+ const audits: any[] = [];
463
+
464
+ const server = createServer(async (req, res) => {
465
+ let raw = '';
466
+ for await (const chunk of req) raw += chunk;
467
+ const body = raw ? JSON.parse(raw) : undefined;
468
+ const path = new URL(req.url ?? '/', 'http://x').pathname.replace(`/realms/${realm}/`, '');
469
+ const send = (status: number, data: unknown) => { res.writeHead(status, { 'content-type': 'application/json' }); res.end(JSON.stringify(data)); };
470
+
471
+ if (path === 'protocol/openid-connect/certs') return send(200, { keys: [jwk] });
472
+ if (path === 'apps/token') {
473
+ return body?.app_id === appId && body?.secret === secret ? send(200, { access_token: 'app-token' }) : send(401, { error: 'unauthorized' });
474
+ }
475
+ if (path === 'apps/operations/sync') { synced = body.operations; return send(200, { synced: synced.length }); }
476
+ if (path === 'apps/operations') {
477
+ return send(200, { operations: synced.map((op, i) => ({
478
+ operation_id: `00000000-0000-4000-8000-${String(i).padStart(12, '0')}`,
479
+ ...op, allowed_groups: opts.allowedGroups?.[op.identifier] ?? [],
480
+ })) });
481
+ }
482
+ if (path === 'audit/events') { audits.push(...body.events); return send(202, { accepted: body.events.length }); }
483
+ return send(404, { error: 'not_found' }); // sem introspecção: x-app-token é recusado, x-api-token cai no validate (404 → 401)
484
+ });
485
+ await new Promise<void>((resolve) => server.listen(0, 'localhost', resolve));
486
+ const { port } = server.address() as AddressInfo;
487
+
488
+ return {
489
+ url: `http://localhost:${port}`, realm, appId, secret, audits,
490
+ signUser: (sub: string, groups: string[] = []) =>
491
+ new SignJWT({ groups, realm_id: realm }).setProtectedHeader({ alg: 'RS256', kid: 'k1' })
492
+ .setSubject(sub).setIssuedAt().setExpirationTime('1h').sign(privateKey),
493
+ close: () => new Promise<void>((resolve) => server.close(() => resolve())),
494
+ };
495
+ }
496
+ ```
497
+
498
+ ```ts
499
+ // clientes.test.ts (vitest)
500
+ import { afterAll, beforeAll, expect, it } from 'vitest';
501
+ import { OrfeuClient, clearRegistry, getRegistry } from '@orfeu/node';
502
+ import { startFakeArgos } from './fake-argos';
503
+
504
+ let argos: Awaited<ReturnType<typeof startFakeArgos>>;
505
+ let base: string;
506
+ let client: OrfeuClient;
507
+
508
+ beforeAll(async () => {
509
+ clearRegistry();
510
+ argos = await startFakeArgos({ allowedGroups: { 'clientes:delete': ['admins'] } });
511
+ client = new OrfeuClient({ authorizerUrl: argos.url, realmId: argos.realm, appId: argos.appId, secret: argos.secret, logger: false });
512
+ const app = buildApp(client); // função do app que declara as rotas com guard()
513
+ for (const op of getRegistry()) client.registerOperation(op);
514
+ await client.startup();
515
+ const server = app.listen(0);
516
+ base = `http://localhost:${(server.address() as any).port}`;
517
+ });
518
+ afterAll(() => argos.close());
519
+
520
+ it('401 sem credencial, 403 sem grupo, 204 com grupo', async () => {
521
+ expect((await fetch(`${base}/clientes/1`, { method: 'DELETE' })).status).toBe(401);
522
+ const semGrupo = await argos.signUser('22222222-2222-4222-8222-222222222222', ['vendas']);
523
+ expect((await fetch(`${base}/clientes/1`, { method: 'DELETE', headers: { 'x-access-token': semGrupo } })).status).toBe(403);
524
+ const admin = await argos.signUser('33333333-3333-4333-8333-333333333333', ['admins']);
525
+ expect((await fetch(`${base}/clientes/1`, { method: 'DELETE', headers: { 'x-access-token': admin } })).status).toBe(204);
526
+
527
+ await client.flushAudit();
528
+ expect(argos.audits.map((e) => e.outcome)).toEqual(['denied', 'denied', 'success']);
529
+ });
530
+ ```
531
+
532
+ - `jose` vem com o `@orfeu/node`, mas declare-o como `devDependency` do app se o teste o importa.
533
+ - `authorizerUrl` do simulado não tem `/api`: o SDK monta `<authorizerUrl>/realms/<realm>/…`.
534
+ - `clearRegistry()` antes de cada arquivo que declara rotas: o registro global é do processo.