@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.
Files changed (92) hide show
  1. package/README.md +181 -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 +80 -0
  9. package/skills/acropole/references/arquitetura.md +174 -0
  10. package/skills/acropole/references/fluxos/app-novo.md +34 -0
  11. package/skills/acropole/references/fluxos/doctor.md +55 -0
  12. package/skills/acropole/references/fluxos/endpoint-novo.md +22 -0
  13. package/skills/acropole/references/fluxos/revisar.md +56 -0
  14. package/skills/acropole/references/fluxos/tela-nova.md +27 -0
  15. package/skills/acropole/scripts/doctor.mjs +439 -0
  16. package/skills/angular/SKILL.md +155 -0
  17. package/skills/angular/references/armadilhas.md +99 -0
  18. package/skills/angular/references/dados.md +251 -0
  19. package/skills/angular/references/estrutura.md +279 -0
  20. package/skills/angular/references/features.md +219 -0
  21. package/skills/angular/references/testes-build.md +257 -0
  22. package/skills/angular/scripts/checar.mjs +182 -0
  23. package/skills/angular/scripts/nucleo.mjs +227 -0
  24. package/skills/apollo/SKILL.md +226 -0
  25. package/skills/apollo/references/armadilhas.md +99 -0
  26. package/skills/apollo/references/envelope-erros.md +120 -0
  27. package/skills/apollo/references/estrutura-bootstrap.md +310 -0
  28. package/skills/apollo/references/schema-resolvers.md +183 -0
  29. package/skills/apollo/references/subscriptions.md +224 -0
  30. package/skills/apollo/references/testes-build.md +181 -0
  31. package/skills/apollo/scripts/checar.mjs +160 -0
  32. package/skills/apollo/scripts/nucleo.mjs +227 -0
  33. package/skills/docker/SKILL.md +102 -0
  34. package/skills/docker/references/modelos.md +251 -0
  35. package/skills/docker/references/porques.md +286 -0
  36. package/skills/documentacao/SKILL.md +146 -0
  37. package/skills/documentacao/references/checklist-coerencia.md +59 -0
  38. package/skills/documentacao/references/ligar-app-novo.md +107 -0
  39. package/skills/documentacao/references/modelo-especificacao.md +51 -0
  40. package/skills/documentacao/references/modelo-readme.md +75 -0
  41. package/skills/documentacao/scripts/checar.mjs +454 -0
  42. package/skills/documentacao/scripts/nucleo.mjs +227 -0
  43. package/skills/express/SKILL.md +156 -0
  44. package/skills/express/references/dados.md +180 -0
  45. package/skills/express/references/estrutura.md +157 -0
  46. package/skills/express/references/middlewares.md +227 -0
  47. package/skills/express/references/rotas-erros.md +286 -0
  48. package/skills/express/references/testes-deploy.md +154 -0
  49. package/skills/express/scripts/checar.mjs +115 -0
  50. package/skills/express/scripts/nucleo.mjs +227 -0
  51. package/skills/fastapi/SKILL.md +132 -0
  52. package/skills/fastapi/references/banco.md +197 -0
  53. package/skills/fastapi/references/estrutura.md +325 -0
  54. package/skills/fastapi/references/integracoes.md +145 -0
  55. package/skills/fastapi/references/rotas-erros.md +140 -0
  56. package/skills/fastapi/references/testes-deploy.md +190 -0
  57. package/skills/fastapi/scripts/checar.mjs +108 -0
  58. package/skills/fastapi/scripts/nucleo.mjs +227 -0
  59. package/skills/hefesto/SKILL.md +119 -0
  60. package/skills/hefesto/references/conceitos.md +131 -0
  61. package/skills/hefesto/references/diagnostico.md +70 -0
  62. package/skills/hefesto/references/fluxo.md +122 -0
  63. package/skills/hefesto/references/preparar-app.md +105 -0
  64. package/skills/orfeu/SKILL.md +162 -0
  65. package/skills/orfeu/references/angular-api.md +201 -0
  66. package/skills/orfeu/references/angular-armadilhas.md +116 -0
  67. package/skills/orfeu/references/angular-recipes.md +474 -0
  68. package/skills/orfeu/references/angular.md +212 -0
  69. package/skills/orfeu/references/diferencas.md +56 -0
  70. package/skills/orfeu/references/node-api.md +354 -0
  71. package/skills/orfeu/references/node-armadilhas.md +158 -0
  72. package/skills/orfeu/references/node-recipes.md +541 -0
  73. package/skills/orfeu/references/node.md +204 -0
  74. package/skills/orfeu/references/python-api.md +346 -0
  75. package/skills/orfeu/references/python-recipes.md +479 -0
  76. package/skills/orfeu/references/python.md +240 -0
  77. package/skills/orfeu/scripts/checar.mjs +126 -0
  78. package/skills/orfeu/scripts/nucleo.mjs +227 -0
  79. package/skills/trismegisto/SKILL.md +194 -0
  80. package/skills/trismegisto/references/angular-api.md +2788 -0
  81. package/skills/trismegisto/references/angular-exports.md +4020 -0
  82. package/skills/trismegisto/references/angular-recipes.md +1883 -0
  83. package/skills/trismegisto/references/angular-types.md +492 -0
  84. package/skills/trismegisto/references/angular.md +390 -0
  85. package/skills/trismegisto/references/catalogo/icones.json +912 -0
  86. package/skills/trismegisto/references/catalogo/seletores.json +7013 -0
  87. package/skills/trismegisto/references/catalogo/tokens.json +240 -0
  88. package/skills/trismegisto/references/spine-api.md +1530 -0
  89. package/skills/trismegisto/references/spine-recipes.md +581 -0
  90. package/skills/trismegisto/references/spine.md +343 -0
  91. package/skills/trismegisto/scripts/checar.mjs +216 -0
  92. package/skills/trismegisto/scripts/nucleo.mjs +227 -0
@@ -0,0 +1,56 @@
1
+ # Diferenças entre as implementações — comportamento atual (1.0.0; `@orfeu/node` 1.0.1)
2
+
3
+ Levantado no código-fonte dos três pacotes na **1.0.0** e, no Node, na **1.0.1** (só o adapter Apollo mudou). A padronização está planejada: quando sair uma versão
4
+ nova, confira de novo antes de confiar nesta tabela. O que **não** está aqui é igual nas duas linguagens de
5
+ backend: precedência e nomes dos headers de credencial (`x-access-token`, `x-app-token`, `x-api-token`),
6
+ `traceparent`, `x-route-id`, `x-client-id`, regra 401/403 por nível, `Level`/`Method`, cache de
7
+ introspecção (60 s; inativo 10 s), parâmetros do lote de auditoria e campos do log de operação.
8
+
9
+ ## Backend: Node (`@orfeu/node`) × Python (`orfeu`)
10
+
11
+ | Assunto | Node | Python |
12
+ |---|---|---|
13
+ | Nomes da API | camelCase: `orfeuHeaders`, `annotateOperation({ ... })` (objeto), `flushAudit()`, `fetchOperations()` | snake_case: `orfeu_headers`, `annotate_operation(target_type=..., ...)` (kwargs), `flush_audit()`, `fetch_operations()` |
14
+ | Configuração | objeto `{ authorizerUrl, realmId, appId, secret, ... }`; nunca lê variável de ambiente | parâmetros `authorizer_url, realm_id, app_id, secret, *, tls_verify, audit`; não lê variável de ambiente, **exceto** o Django (settings `ORFEU_*`) |
15
+ | Nomes de variáveis de ambiente nos exemplos | `AUTHORIZER_URL`, `REALM_ID`, `APP_ID`, `APP_SECRET` | `ORFEU_AUTHORIZER_URL`, `ORFEU_REALM_ID`, `ORFEU_APP_ID`, `ORFEU_SECRET` (convenção do Django) |
16
+ | Token de outro realm | `acceptAnyRealm: true` aceita (busca o JWKS do realm da claim `realm_id`) | sempre recusado; não há opção equivalente |
17
+ | Validação do JWT | `jose` com JWKS remoto (cache interno da lib); JWKS buscado **sob demanda** | exige `kid` e RS256; JWKS buscado **na subida** (falha a subida se não vier), cache de 1 h e nova busca se o `kid` for desconhecido |
18
+ | Timeouts das chamadas ao Argos | só a auditoria tem (10 s); token do serviço, sync, operações e introspecção **sem timeout** | 10 s em todas (introspecção: 5 s) |
19
+ | Erro de rede na subida | erro cru do `fetch` (não é `OrfeuError`) | embrulhado: `OrfeuAuthError` / `OrfeuSyncError` / `OrfeuError` |
20
+ | Quem chama a subida | o app: `client.startup()` / `OrfeuClient.create()` depois de declarar as rotas; Nest: `OrfeuModule.forRootAsync` | FastAPI: automático no lifespan (`Orfeu(app, ...)`); Flask e Django: **na construção**, síncrono; Strawberry: o app chama `startup_async()` no lifespan |
21
+ | Permissões (`allowed_groups`) | revalidadas a cada 60 s por padrão (`@orfeu/node` ≥ 1.1 / `orfeu` ≥ 1.1; opção `permissionsRefresh`); antes, só na subida ou em `fetchOperations()` manual | idem (`permissions_refresh`); antes, só na subida ou em `fetch_operations()` manual |
22
+ | `fetchOperations` / `fetch_operations` com token do serviço vencido (401) | reautentica uma vez e repete (`@orfeu/node` ≥ 1.1 / `orfeu` ≥ 1.1); antes lançava `OrfeuError` | idem (`@orfeu/node` ≥ 1.1 / `orfeu` ≥ 1.1) |
23
+ | Reautenticação automática no 401 | só na auditoria e na introspecção | idem |
24
+ | Inferência de `Method` sem `method` explícito | pelo **último segmento do id** após `:` (`tasks:list` → `read`); Apollo: pelo tipo raiz (Query → `read`, Mutation → `write`/`delete`, Subscription → `stream`) | pelo **nome da função** (`get_`/`list_`/... → `read`) |
25
+ | Convenção de id nos exemplos | `recurso:acao` | `recurso.acao` |
26
+ | `description` da operação no catálogo | não enviada pelos adapters (`null`) | docstring da função |
27
+ | `ApiTokenClaims` | tipo **não** reexportado na raiz (`NonNullable<Request['orfeuApiToken']>`) | **não** exportado em `orfeu`; importe de `orfeu.models` |
28
+ | Usuário injetado pelo app (contexto sem credencial crua) | Apollo: só por `trustUser(ctx, claims)` (1.0.1); `ctx.orfeuUser` gravado direto é ignorado (401 fora de `public`) e removido do contexto. Express/Fastify/Nest: não existe — o guard sempre decide pela credencial dos headers e regrava `orfeuUser` | não existe: a guarda sempre decide pela credencial da requisição |
29
+ | Contexto do WebSocket | Apollo `orfeuWsContext(client, extra)`: o `extra` entra antes dos campos do Orfeu e perde as chaves de `ORFEU_RESERVED_CONTEXT_KEYS` (1.0.1) | FastAPI: a guarda lê os 3 headers do handshake, sem `extra`; Strawberry/graphql-ws lê do `connection_init` (python-recipes.md §11) |
30
+ | Onde fica o usuário | `req.orfeuUser` / `req.orfeuApiToken`; Apollo `ctx.orfeuUser`; Nest `@OrfeuUser()` | FastAPI `request.state.user` / `.api_token` (**ausente** no anônimo); Flask `g.orfeu_user` (`None` no anônimo); Django `request.orfeu_user`; Strawberry `info.context["orfeu_user"]` |
31
+ | Declaração | por rota: `guard(id, level, method?)`, `preHandler: fastify.orfeuGuard(...)`, `@Operation(...)`, `operation(level, resolver)` | decorator `@operation(id=..., level=..., method=...)` logo abaixo do decorator de rota; a guarda resolve a rota pelo roteador |
32
+ | Rota sem operação | passa sem proteção nem auditoria | idem; no FastAPI há uma rede de segurança: se o roteador cair num endpoint com `@operation` que a guarda não resolveu, a resposta vira 500 `route_unresolved` (WebSocket: fecha 1008) |
33
+ | NestJS | `OrfeuModule.forRootAsync(opts)` recebe as **opções prontas** (sem `useFactory`/`inject`: não dá para usar `ConfigService`); falha na subida derruba o bootstrap. `OrfeuGuard` não é global: `@UseGuards(OrfeuGuard)` no controller; método **sem `@Operation` é liberado** (o guard devolve `true`) | — |
34
+ | GraphQL: campo sem operação | Apollo: `secureResolvers` lança `OrfeuConfigError` e `assertSchemaSecured(schema)` confere o schema | Strawberry: campo sem `@operation` simplesmente roda sem proteção (sem verificação equivalente) |
35
+ | Corpo do 401/403 (REST) | Express/Fastify: `{ error, detail }`; Nest: `UnauthorizedException`/`ForbiddenException` | envelope `{ status, message, data: null, error, detail }` |
36
+ | Texto do 401 | varia: `Access token required.`, `Invalid token.`, `Invalid, expired, revoked or unauthorized api token.` | sempre `Invalid or missing credentials.` |
37
+ | Erro GraphQL negado | `GraphQLError` com `extensions.code` **numérico** (401/403), `status`, `reason` (`UNAUTHENTICATED`/`FORBIDDEN`), `operation`; `onForbidden` pode trocar o 403 por um valor | `OrfeuUnauthorizedError`/`OrfeuForbiddenError` com `extensions.code` **texto** (`UNAUTHENTICATED`/`FORBIDDEN`) e `status` |
38
+ | Classes de erro | 401 do `createGuard` é `Error` comum; não existe `OrfeuUnauthorizedError` | existe `OrfeuUnauthorizedError` (e as negações também são `PermissionError`) |
39
+ | WebSocket negado | Apollo/graphql-ws: `GraphQLError` | FastAPI: fecha com **1008** antes do `accept` |
40
+ | Envelope de resposta do app | não existe no SDK | `install_envelope(app)`, `ok`/`fail`, `NotFound`, `Conflict`… |
41
+ | Flush da auditoria no encerramento | `await client.close()` no SIGTERM do app (para a recarga + flush; `@orfeu/node` ≥ 1.1 / `orfeu` ≥ 1.1) — Fastify/Nest/Apollo fazem sozinhos; antes, `flushAudit()` manual | automático no shutdown do lifespan (FastAPI); Flask `orfeu.shutdown()`/`atexit`; Django `atexit` |
42
+ | Log de operação padrão | uma linha JSON no **stdout** (`jsonLineLogger`); `logger: false` desliga | `logging` padrão (`orfeu.operation`), **sem handler**: sem configurar, as linhas INFO não aparecem; `JsonLogFormatter` opcional |
43
+ | `traceparent` repassado | flags propagadas como chegaram | só o bit *sampled* é propagado |
44
+ | `orfeuHeaders` / `orfeu_headers` fora de operação protegida | Express/Fastify: funciona em qualquer rota que passou pela captura global (mesmo sem guard); Nest: só em método com `@Operation`; Apollo: com o plugin/contexto instalado | devolve `{}` fora de chamada guardada |
45
+
46
+ ## Front: `@orfeu/angular` × backends
47
+
48
+ | Assunto | `@orfeu/angular` | Node / Python |
49
+ |---|---|---|
50
+ | URL do Argos | `authority` = **origem** do Argos, sem `/api`; a lib monta `${authority}/api/realms/${realmId}/...` | `authorizerUrl` / `authorizer_url` = URL base **com** o prefixo da API (`…/api`) |
51
+ | Identidade | `clientId` (client OIDC do app front) + `realmId` | `appId`/`app_id` + `secret` (serviço cadastrado no Argos) |
52
+ | Envio do token às APIs | a lib **não exporta interceptor**: o app escreve um que manda `x-access-token` só para as próprias APIs (receita em [angular-recipes.md](angular-recipes.md) §4) | leem `x-access-token` cru |
53
+ | `x-client-id` / `x-route-id` | o interceptor do app que acrescenta (opcional) | repassados por `orfeuHeaders`/`orfeu_headers` |
54
+ | `traceparent` | nunca envia | gera/continua |
55
+ | Claims | decodificadas **sem** verificar assinatura, só para exibir | verificadas (JWKS) e usadas na decisão |
56
+ | Helpers de teste | não publicados | não publicados (Node: Argos simulado; Python: mocks no `OrfeuClient`) |
@@ -0,0 +1,354 @@
1
+ # API — @orfeu/node 1.0.1
2
+
3
+ > Conferida contra o código-fonte da 1.0.1 (`src/index.ts` e `src/adapters/*`). O que não está aqui é
4
+ > interno. A 1.0.1 só mudou o adapter Apollo (`trustUser`, `ORFEU_RESERVED_CONTEXT_KEYS`, confiança no
5
+ > `orfeuUser` por marca da lib); peça `^1.0.1`. Endpoints citados são relativos a `authorizerUrl` (que já inclui o prefixo da API).
6
+
7
+ ## `@orfeu/node` (núcleo)
8
+
9
+ ### `OrfeuClient`
10
+
11
+ ```ts
12
+ interface OrfeuClientOptions {
13
+ authorizerUrl: string; // barra final é removida
14
+ realmId: string;
15
+ appId: string;
16
+ secret: string;
17
+ acceptAnyRealm?: boolean; // padrão false
18
+ tlsVerify?: boolean; // padrão true
19
+ audit?: boolean | AuditOptions; // padrão true
20
+ logger?: OperationLogger | false; // padrão jsonLineLogger
21
+ }
22
+
23
+ class OrfeuClient {
24
+ constructor(options: OrfeuClientOptions);
25
+ static create(options: OrfeuClientOptions): Promise<OrfeuClient>; // registra getRegistry() + startup()
26
+
27
+ readonly appId: string; // getter
28
+ readonly operationLogger: OperationLogger | null;
29
+ readonly pendingAudit: number; // getter: eventos esperando envio
30
+
31
+ registerOperation(op: OperationDescriptor): void;
32
+ startup(): Promise<void>;
33
+ authenticate(): Promise<void>;
34
+ syncOperations(): Promise<void>;
35
+ fetchOperations(): Promise<boolean>; // true se o catálogo mudou; reautentica uma vez no 401
36
+ refreshOperations(): Promise<boolean>; // revalidação (If-None-Match); nunca lança; true = sucesso
37
+ startPermissionsRefresh(): void; stopPermissionsRefresh(): void;
38
+ readonly lastPermissionsSyncAt: Date | null; readonly permissionsStale: boolean;
39
+ close(timeoutMs?: number): Promise<void>; // para a recarga + flushAudit
40
+ validateToken(token: string): Promise<TokenClaims>;
41
+ validateAppToken(token: string): Promise<TokenClaims>;
42
+ validateApiToken(token: string, identifier: string, method: string): Promise<ApiTokenClaims | null>;
43
+ checkPermission(claims: TokenClaims, identifier: string, method: string): boolean;
44
+ operationIdOf(identifier: string, method: string): string | undefined;
45
+ recordAudit(event: AuditEvent): void;
46
+ flushAudit(timeoutMs?: number): Promise<void>; // padrão 3000 ms
47
+ }
48
+ ```
49
+
50
+ | Método | Comportamento |
51
+ |---|---|
52
+ | `registerOperation(op)` | valida (`assertValidOperation`, lança `OrfeuConfigError`) e acrescenta ao catálogo **deste client**; deduplica por `identifier`+`method` (a primeira vence). |
53
+ | `startup()` | sem operações → `OrfeuConfigError`. Depois `authenticate()`, prepara o JWKS, `syncOperations()`, `fetchOperations()`. |
54
+ | `authenticate()` | `POST /realms/{realm}/apps/token` com `{ app_id, secret }` → guarda o token do serviço. Não-2xx ou sem `access_token` → `OrfeuAuthError`. |
55
+ | `syncOperations()` | `POST /realms/{realm}/apps/operations/sync` com `{ operations: [{ identifier, method, level, description }] }`. Exige token do serviço (`OrfeuAuthError` se não houver). Não-2xx → `OrfeuSyncError`. **Não** reautentica sozinho em 401. |
56
+ | `fetchOperations()` | `GET /realms/{realm}/apps/operations` → substitui o cache local de operações (`operation_id`, `level`, `allowed_groups`). Não-2xx → `OrfeuError`. **Não** reautentica sozinho em 401. |
57
+ | `validateToken(jwt)` | verifica assinatura com o JWKS de `/realms/{realm}/protocol/openid-connect/certs` (cache do `jose`) e exige `realm_id` = `realmId` (com `acceptAnyRealm`, usa o JWKS do realm do token). Lança `OrfeuTokenError`. |
58
+ | `validateAppToken(token)` | introspecção (`POST /realms/{realm}/tokens/introspect`, autenticada com o token do serviço; reautentica uma vez em 401). Cache por hash do token: 60 s ativo (limitado ao `exp`), 10 s inativo. Devolve `TokenClaims` com `raw.token_type = 'app_token'` e `raw.token_id`. Inativo, outro tipo, outro realm ou Argos sem introspecção → `OrfeuTokenError`. |
59
+ | `validateApiToken(token, id, method)` | introspecção; `{ tokenId, appId }` se o token for do tipo `api` **e** tiver a operação concedida neste serviço; senão `null`. Argos sem introspecção (404) → `POST /realms/{realm}/apps/tokens/validate` (cache 30 s por token+operação). Erro de rede/servidor → `OrfeuTokenError`. |
60
+ | `checkPermission(claims, id, method)` | usa o cache do `fetchOperations()`: operação desconhecida → `false`; `public` → `true`; `private`/`optional` → `claims.groups.length > 0`; `protected` → algum grupo em `allowed_groups`. |
61
+ | `operationIdOf(id, method)` | UUID da operação no Argos (depois do `fetchOperations()`), para logs. |
62
+ | `recordAudit(event)` | põe um evento na fila (no-op com `audit: false`). Nunca bloqueia. |
63
+ | `flushAudit(timeoutMs = 3000)` | envia o que estiver na fila, esperando no máximo `timeoutMs`. |
64
+ | `close(timeoutMs = 3000)` | (`@orfeu/node` ≥ 1.1 / `orfeu` ≥ 1.1) para a recarga de permissões e faz o `flushAudit`. Use no encerramento. |
65
+ | `permissionsRefresh` (opção) | (`@orfeu/node` ≥ 1.1 / `orfeu` ≥ 1.1) `true` (padrão: 60 s, ±20%), `false` ou `{ enabled, intervalMs, jitter }`. O `startup()` agenda a recarga; timer com `unref()`. |
66
+
67
+ ### Tipos de identidade
68
+
69
+ ```ts
70
+ interface TokenClaims {
71
+ sub: string; // id do usuário
72
+ realmId: string;
73
+ groups: string[];
74
+ exp: number; // epoch em segundos
75
+ raw: Record<string, unknown>; // todas as claims (JWT) ou a resposta da introspecção (app token)
76
+ }
77
+ interface ApiTokenClaims { tokenId: string; appId: string; } // não reexportado na raiz: use NonNullable<Request['orfeuApiToken']>
78
+ interface OperationDescriptor { identifier: string; method: Method; level: Level; description?: string | null; }
79
+ interface OperationWithGroups extends OperationDescriptor { operationId: string; allowedGroups: string[]; }
80
+ ```
81
+
82
+ ### Níveis, métodos e registro global
83
+
84
+ ```ts
85
+ const Level = { PUBLIC: 'public', PRIVATE: 'private', PROTECTED: 'protected', OPTIONAL: 'optional' } as const;
86
+ type Level = typeof Level[keyof typeof Level];
87
+ const Method = { READ: 'read', WRITE: 'write', DELETE: 'delete', STREAM: 'stream' } as const;
88
+ type Method = typeof Method[keyof typeof Method];
89
+
90
+ function assertValidOperation(op: Pick<OperationDescriptor, 'identifier' | 'method' | 'level'>): void; // OrfeuConfigError
91
+ function detectMethod(id: string): Method;
92
+ function registerOperation(op: OperationDescriptor): void; // registro GLOBAL do processo (Symbol.for('orfeu.registry'))
93
+ function getRegistry(): OperationDescriptor[]; // cópia
94
+ function clearRegistry(): void; // para testes
95
+ ```
96
+
97
+ `detectMethod`: último segmento após `:` em minúsculas; começa com `get|list|fetch|read` → `read`; com
98
+ `delete|remove|destroy` → `delete`; contém `stream|subscribe|watch|listen` → `stream`; senão `write`.
99
+
100
+ `guard()`, `orfeuGuard()`, `@Operation()` e `createGuard()` registram no **registro global** no momento da
101
+ declaração; `secureResolvers()` registra no global **e** no client. Antes do `startup()`, copie o global para o
102
+ client (`for (const op of getRegistry()) client.registerOperation(op)`) — ou use `OrfeuClient.create`.
103
+
104
+ ### Headers (constantes)
105
+
106
+ | Constante | Valor |
107
+ |---|---|
108
+ | `ACCESS_TOKEN_HEADER` | `x-access-token` |
109
+ | `APP_TOKEN_HEADER` | `x-app-token` |
110
+ | `API_TOKEN_HEADER` | `x-api-token` |
111
+ | `ROUTE_ID_HEADER` | `x-route-id` |
112
+ | `CLIENT_ID_HEADER` | `x-client-id` |
113
+ | `TRACEPARENT_HEADER` | `traceparent` |
114
+
115
+ ### Trace
116
+
117
+ ```ts
118
+ interface OrfeuTrace {
119
+ traceId: string; // 32 hex
120
+ spanId: string; // 16 hex, novo a cada serviço
121
+ parentSpanId?: string; // span de quem chamou
122
+ entry: boolean; // true = chegou sem traceparent (ação do usuário)
123
+ flags?: string; // trace-flags recebidas; '01' em trace novo
124
+ }
125
+ function parseTraceparent(value: string | null | undefined): { traceId: string; spanId: string; flags: string } | undefined;
126
+ function resolveTrace(incoming: string | null | undefined): OrfeuTrace;
127
+ function formatTraceparent(t: OrfeuTrace): string; // '00-<traceId>-<spanId>-<flags>'
128
+ ```
129
+
130
+ `parseTraceparent` é estrito ao W3C: só hex minúsculo; versão `ff` inválida; ids zerados inválidos; versão `00`
131
+ com exatamente 55 caracteres; versões futuras lidas pelos 4 primeiros campos. Inválido → `undefined` (e
132
+ `resolveTrace` começa um trace novo).
133
+
134
+ ### `orfeuHeaders`
135
+
136
+ ```ts
137
+ interface OrfeuForwardSource {
138
+ orfeuTrace?: OrfeuTrace; orfeuRouteId?: string; orfeuClientId?: string;
139
+ orfeuCredential?: { header: string; value: string };
140
+ }
141
+ interface OrfeuHeadersOptions { credential?: boolean } // padrão true
142
+ function orfeuHeaders(source: OrfeuForwardSource, options?: OrfeuHeadersOptions): Record<string, string>;
143
+ ```
144
+
145
+ `source` é o `req` do Express, o `request` do Fastify/Nest ou o contexto do Apollo. Devolve só o que existe:
146
+ credencial (`x-access-token`/`x-app-token` como chegou; `x-api-token` nunca é repassado), `traceparent`
147
+ (deste passo), `x-route-id`, `x-client-id`.
148
+
149
+ ### Auditoria
150
+
151
+ ```ts
152
+ interface OperationAnnotation {
153
+ target_type?: string; // até 100 caracteres no evento
154
+ target_id?: string | number; // vira string, até 200
155
+ details?: Record<string, unknown>; // até 4 KB em JSON; acima vira { truncated: true, original_bytes }
156
+ }
157
+ function annotateOperation(annotation: OperationAnnotation): boolean; // false fora de uma operação protegida
158
+ interface AuditOptions { enabled?: boolean; flushIntervalMs?: number /*1000*/; maxBuffer?: number /*10000*/; batchSize?: number /*200*/ }
159
+ ```
160
+
161
+ `annotateOperation` chamado várias vezes: `target_type`/`target_id` sobrescrevem; `details` é mesclado.
162
+
163
+ Evento (`AuditEvent`, formato de `POST /realms/{realm}/audit/events`, snake_case): `event_id`, `occurred_at`,
164
+ `duration_ms` (inteiro 0..86 400 000), `trace_id`, `span_id`, `parent_span_id?`, `entry`, `actor_type`,
165
+ `user_id?`/`token_id?`/`client_id?`/`route_id?` (só GUIDs), `client_ip?` (só IP válido e só com `entry`),
166
+ `service_instance` (`host:pid`), `sdk` (`node/<versão>`), `operation: { identifier, method, level }`,
167
+ `target_type?`, `target_id?`, `permission_result`, `outcome` (`success` | `failure` | `denied`), `status?`
168
+ (0..999), `message?` (≤ 500), `details?`.
169
+
170
+ `AuditSink` (classe exportada) é o buffer interno usado pelo client; apps não precisam instanciá-lo.
171
+
172
+ Funções de baixo nível (para operação fora dos adapters — `node-recipes.md` §8):
173
+
174
+ ```ts
175
+ function recordOperation(client: AuditRecorder, input: OperationLogInput): void; // log + evento; nunca lança
176
+ function buildAuditEvent(input: OperationLogInput & { trace: OrfeuTrace; method: string; level: string }): AuditEvent;
177
+ interface AuditRecorder { // OrfeuClient satisfaz
178
+ appId: string;
179
+ recordAudit(event: AuditEvent): void;
180
+ operationLogger?: OperationLogger | null;
181
+ operationIdOf?(identifier: string, method: string): string | undefined;
182
+ }
183
+ ```
184
+
185
+ `recordOperation` só gera evento de auditoria quando `input.trace`, `input.method` e `input.level` existem.
186
+
187
+ ### Log de operação
188
+
189
+ ```ts
190
+ type ActorType = 'user' | 'public' | 'unauthenticated' | 'api_token' | 'app_token';
191
+ interface OperationLogInput {
192
+ operationId: string; // o IDENTIFICADOR (ex.: 'clientes:list')
193
+ argosOperationId?: string; // UUID no Argos (recordOperation preenche)
194
+ appId: string;
195
+ actorType: ActorType;
196
+ user?: string; tokenId?: string;
197
+ permissionResult: string; // 'allowed' | 'forbidden' | 'unauthorized' | 'public'
198
+ durationMs: number;
199
+ success: boolean;
200
+ routeId?: string; clientId?: string;
201
+ errorMessage?: string;
202
+ method?: string; level?: string; status?: number;
203
+ trace?: OrfeuTrace; clientIp?: string; startedAt?: number; annotation?: OperationAnnotation;
204
+ }
205
+ interface OperationLogRecord {
206
+ timestamp: string; level: 'INFO' | 'ERROR'; logger: 'orfeu.operation';
207
+ message: string; // 'operação executada' ou o erro ('operação falhou' sem mensagem)
208
+ operation: string; operation_id?: string; operation_method?: string; operation_level?: string;
209
+ agent_id: string; actor_type: ActorType; permission_result: string; duration_ms: number;
210
+ user?: string; token_id?: string; route_id?: string; client_id?: string; trace_id?: string; span_id?: string;
211
+ }
212
+ type OperationLogger = (record: OperationLogRecord) => void;
213
+ const jsonLineLogger: OperationLogger; // JSON por linha no stdout
214
+ function buildOperationLog(input: OperationLogInput): OperationLogRecord;
215
+ function emitOperationLog(input: OperationLogInput, logger?: OperationLogger): void;
216
+ function resolveActorType(user: TokenClaims | undefined, level: string, apiToken?: ApiTokenClaims): ActorType;
217
+ function resolveTokenId(user: TokenClaims | undefined, apiToken?: ApiTokenClaims): string | undefined;
218
+ ```
219
+
220
+ ### Exceções
221
+
222
+ ```ts
223
+ class OrfeuError extends Error {} // name = nome da classe
224
+ class OrfeuAuthError extends OrfeuError {}
225
+ class OrfeuTokenError extends OrfeuError {}
226
+ class OrfeuForbiddenError extends OrfeuError {}
227
+ class OrfeuSyncError extends OrfeuError {}
228
+ class OrfeuConfigError extends OrfeuError {}
229
+ ```
230
+
231
+ ## `@orfeu/node/express`
232
+
233
+ ```ts
234
+ function orfeu(client: OrfeuClient): OrfeuMiddleware;
235
+ interface OrfeuMiddleware {
236
+ middleware: (req, res, next) => Promise<void>; // captura credencial, trace e correlação
237
+ guard: (id: string, level: Level, method?: Method) => (req, res, next) => Promise<void>;
238
+ }
239
+ ```
240
+
241
+ - `guard()` registra a operação (global) **quando é chamado** (na definição da rota). Na requisição: decide;
242
+ negado → responde `401/403` JSON e não chama `next`; permitido → `req.orfeuUser`/`req.orfeuApiToken` e
243
+ `next()` dentro do contexto da auditoria. Log + evento quando a resposta termina (`finish`), com o status final.
244
+ - Funciona sem o `middleware` (captura sob demanda), mas o `middleware` global deixa `req.orfeuTrace` etc.
245
+ disponíveis também em rotas sem guard (útil para `orfeuHeaders`).
246
+ - Campos em `Request`: `orfeuUser?`, `orfeuApiToken?`, `orfeuTrace?`, `orfeuClientIp?`, `orfeuRouteId?`,
247
+ `orfeuClientId?`, `orfeuCredential?` (tipagem global de `Express.Request` incluída).
248
+
249
+ ## `@orfeu/node/fastify`
250
+
251
+ ```ts
252
+ const orfeuFastifyPlugin: FastifyPluginAsync<OrfeuPluginOptions>; // nome 'orfeu', fastify >= 4, encapsulamento desligado (fastify-plugin)
253
+ interface OrfeuPluginOptions { client: OrfeuClient }
254
+ type OrfeuFastifyGuard = (request, reply, done: (err?: Error) => void) => void;
255
+ // decorador: fastify.orfeuGuard(id: string, level: Level, method?: Method): OrfeuFastifyGuard
256
+ ```
257
+
258
+ - Hook `onRequest` captura; `fastify.orfeuGuard(...)` registra a operação e devolve um `preHandler` **no estilo
259
+ callback** (o handler roda dentro do contexto da auditoria). Negado → `reply.code(401|403).send({ error, detail })`.
260
+ - `request.orfeuUser`, `orfeuApiToken`, `orfeuTrace`, `orfeuClientIp`, `orfeuRouteId`, `orfeuClientId`,
261
+ `orfeuCredential` (decorados e tipados).
262
+
263
+ ## `@orfeu/node/nest`
264
+
265
+ ```ts
266
+ class OrfeuModule { static forRootAsync(options: OrfeuModuleOptions): DynamicModule } // OrfeuModuleOptions = OrfeuClientOptions
267
+ function Operation(id: string, level: Level, method?: Method): MethodDecorator; // SetMetadata(OPERATION_KEY, { id, level, method })
268
+ const OPERATION_KEY = 'orfeu:operation';
269
+ interface OperationMeta { id: string; level: Level; method: Method; }
270
+ const OrfeuUser: () => ParameterDecorator; // request.orfeuUser (TokenClaims | undefined)
271
+ class OrfeuGuard implements CanActivate {}
272
+ class OrfeuAnnotationInterceptor implements NestInterceptor {}
273
+ ```
274
+
275
+ - `forRootAsync(options)` recebe as opções **prontas** (não é `useFactory`): módulo **global** que cria o
276
+ `OrfeuClient`, copia `getRegistry()`, faz `startup()` (falha → o app não sobe), exporta `OrfeuClient` e
277
+ `OrfeuGuard` e registra `OrfeuAnnotationInterceptor` como `APP_INTERCEPTOR`.
278
+ - `OrfeuGuard`: método **sem** `@Operation` → libera (sem checar nada). Com `@Operation`: negado lança
279
+ `UnauthorizedException(detail)`/`ForbiddenException(detail)`. Só contexto HTTP (Express ou Fastify por baixo).
280
+ - `@Operation` lê-se no **método** (handler), não na classe.
281
+ - `OrfeuClient` é injetável em qualquer provider (`constructor(private readonly orfeu: OrfeuClient)`).
282
+
283
+ ## `@orfeu/node/apollo`
284
+
285
+ ```ts
286
+ function orfeuPlugin(client: OrfeuClient): ApolloServerPlugin<OrfeuContext>;
287
+ function orfeuWsContext<TExtra>(client: OrfeuClient, extra?: (ctx: { connectionParams?: Record<string, any> }) => TExtra | Promise<TExtra>)
288
+ : (ctx: { connectionParams?: Record<string, any> }) => Promise<OrfeuContext & { connectionParams?: Record<string, any> } & TExtra>;
289
+ function trustUser<TContext extends OrfeuContext>(context: TContext, claims: TokenClaims): TContext; // 1.0.1
290
+ const ORFEU_RESERVED_CONTEXT_KEYS: readonly ['orfeuUser', 'orfeuApiToken', 'orfeuApiTokenStr', 'orfeuRouteId',
291
+ 'orfeuClientId', 'orfeuTrace', 'orfeuClientIp', 'orfeuCredential', 'connectionParams']; // 1.0.1
292
+ type OrfeuReservedContextKey = (typeof ORFEU_RESERVED_CONTEXT_KEYS)[number];
293
+ function operation<T>(level: Level, resolver: T, options?: OperationOptions): T;
294
+ function secureResolvers<T extends Record<string, any>>(client: OrfeuClient, resolvers: T, options?: SecureResolversOptions): T;
295
+ function assertSchemaSecured(schema: GraphQLSchema): void;
296
+ function createGuard(client: OrfeuClient): <TParent, TArgs, TContext extends OrfeuContext, TReturn>(
297
+ id: string, level: Level, resolver: (parent: TParent, args: TArgs, context: TContext, info: unknown) => TReturn, method?: Method,
298
+ ) => (parent: TParent, args: TArgs, context: TContext, info: unknown) => Promise<TReturn>;
299
+ const envelopeOutcome: OutcomeResolver;
300
+
301
+ interface OrfeuContext extends BaseContext {
302
+ orfeuUser?: TokenClaims; orfeuApiToken?: ApiTokenClaims; orfeuApiTokenStr?: string;
303
+ orfeuRouteId?: string; orfeuClientId?: string; orfeuTrace?: OrfeuTrace; orfeuClientIp?: string;
304
+ orfeuCredential?: { header: string; value: string };
305
+ }
306
+ interface OperationOptions { id?: string; method?: Method; description?: string; }
307
+ interface SecureResolversOptions {
308
+ onForbidden?: (denial: OperationDenial) => unknown; // valor ≠ undefined vira o resultado do campo no 403
309
+ outcome?: OutcomeResolver; // padrão envelopeOutcome
310
+ }
311
+ interface OperationDenial { status: 403; message: string; operationId: string; type: 'Query' | 'Mutation'; field: string; }
312
+ interface ResolvedOutcome { success: boolean; status?: number; message?: string; }
313
+ type OutcomeResolver = (result: unknown) => ResolvedOutcome | undefined;
314
+ type OperationLevel = Level;
315
+ type DenialReason = 'unauthenticated' | 'forbidden';
316
+ class OrfeuDenied extends Error { readonly status: 401 | 403; readonly reason: DenialReason; readonly operationId: string; }
317
+ ```
318
+
319
+ - `orfeuPlugin` captura (em `didResolveOperation`) credencial, trace, IP, `x-route-id`/`x-client-id` (HTTP) ou
320
+ `routeId`/`clientId` (connectionParams). Valida por campo, no máximo **uma vez por requisição** para a
321
+ credencial de usuário; `ctx.orfeuUser` vale para todos os campos do documento.
322
+ - `operation(level, resolver, opts)` marca a **função** (resolver, ou o `subscribe` de uma Subscription; aceita
323
+ também `{ resolve }`/`{ subscribe, resolve }`). Reusar a mesma função em dois campos → `OrfeuConfigError`.
324
+ - `secureResolvers` percorre `Query`/`Mutation`/`Subscription`: cada campo vira operação (id padrão
325
+ `query:<campo>`, `mutation:<campo>`, `subscription:<campo>`), registrada no client e no global. Campo sem
326
+ `operation()` → `OrfeuConfigError` listando todos. Devolve os campos no formato `{ resolve }`/`{ subscribe }`.
327
+ Outros tipos (resolvers de campo de objeto) passam intactos.
328
+ - Negação: 401 sempre `GraphQLError` (`extensions: { code: 401, status: 401, reason: 'UNAUTHENTICATED', operation }`);
329
+ 403 em Query/Mutation → `onForbidden(denial)` se devolver algo, senão `GraphQLError` (`code: 403`,
330
+ `reason: 'FORBIDDEN'`); Subscription → sempre `GraphQLError`. Mensagens `Unauthorized: …`/`Forbidden: …`.
331
+ - `envelopeOutcome`: resultado `{ status: number, message? }` com `status >= 400` é auditado como `failure`
332
+ (com `status` e `message`); outros resultados: sem exceção = `success`.
333
+ - `assertSchemaSecured(schema)`: lança `OrfeuConfigError` listando campos raiz cujo `resolve`/`subscribe` não
334
+ passou pelo `secureResolvers`.
335
+ - `orfeuWsContext(client, extra?)`: contexto do `graphql-ws`. Lê `x-access-token` → `x-app-token` →
336
+ `x-api-token`, `traceparent`, `routeId`/`x-route-id`, `clientId`/`x-client-id` na raiz de `connectionParams`
337
+ ou em `connectionParams.headers`. A credencial é lida **na conexão**. O retorno do `extra` entra **antes**
338
+ dos campos do Orfeu e perde as chaves de `ORFEU_RESERVED_CONTEXT_KEYS` e as marcas `Symbol.for('orfeu.*')`
339
+ (com um aviso `[orfeu] orfeuWsContext: ... chave reservada` por chave, só fora de produção). Mesmo assim,
340
+ o `extra` deve devolver uma allowlist, não o `connectionParams` espalhado (receita em node-recipes.md §4).
341
+ - `trustUser(ctx, claims)`: declara `claims` como o usuário **já validado** deste contexto e devolve o
342
+ próprio `ctx`. É a única forma de injetar usuário num contexto montado pelo app sem credencial crua.
343
+ Grava `ctx.orfeuUser` e uma marca não enumerável (Symbol) que a lib confere por **identidade**: `{ ...ctx }`
344
+ perde a marca, trocar `ctx.orfeuUser` depois desfaz a confiança e JSON (corpo, `connectionParams`) nunca a
345
+ carrega. Claims vazias → `OrfeuConfigError`. Só passe claims que o app validou (`await client.validateToken(t)`).
346
+ - `ORFEU_RESERVED_CONTEXT_KEYS`: as chaves que só a lib grava no contexto. Útil para quem monta o próprio
347
+ contexto e quer filtrar a mesma lista.
348
+ - `createGuard(client)(id, level, resolver, method?)`: proteção resolver a resolver (alternativa antiga).
349
+ Negado → `Error('Unauthorized: …')` (401) ou `OrfeuForbiddenError('Forbidden: …')` (403).
350
+ - Decisão (`decide()`): sem credencial no contexto, a permissão só é decidida sobre um `ctx.orfeuUser`
351
+ **marcado pela lib** (validado neste contexto ou por `trustUser`). Um `orfeuUser`/`orfeuApiToken` sem a marca
352
+ é ignorado (cai na regra comum: 401 fora de `public`) e removido do contexto antes do resolver, inclusive
353
+ em campos `public`/`optional` anônimos. Até a 1.0.0 qualquer `orfeuUser` no contexto valia como
354
+ autenticado — por isso o mínimo é `^1.0.1`.
@@ -0,0 +1,158 @@
1
+ # Armadilhas e erros comuns — @orfeu/node 1.0.1
2
+
3
+ Cada item: sintoma → causa → o que fazer.
4
+
5
+ ## Subida
6
+
7
+ **`OrfeuConfigError: No operations registered. Call registerOperation() before startup().`**
8
+ As rotas foram declaradas depois do `startup()`, ou faltou copiar o registro global para o client
9
+ (`for (const op of getRegistry()) client.registerOperation(op)`). Ordem: declarar → copiar → `startup()` →
10
+ `listen`. Ou use `OrfeuClient.create(opts)` depois de declarar.
11
+
12
+ **`OrfeuAuthError: Authentication failed: HTTP 401`.** `APP_ID`/`APP_SECRET` errados, serviço de outro realm, ou
13
+ `authorizerUrl` sem o prefixo da API (o SDK chama `<authorizerUrl>/realms/<realm>/apps/token`). Repetir não
14
+ resolve.
15
+
16
+ **`OrfeuSyncError` na subida.** O Argos recusou o catálogo (geralmente nível/método inválido vindo de JS sem
17
+ tipos — o SDK já barra isso no registro — ou serviço sem permissão de sincronizar). Leia a mensagem: ela traz o
18
+ corpo da resposta.
19
+
20
+ **Serviço não sobe quando o Argos está fora.** `startup()` precisa do Argos. Use subida com nova tentativa
21
+ (`node-recipes.md` §10) se o serviço deve esperar em vez de cair. No Nest, a falha do `forRootAsync` derruba o
22
+ bootstrap.
23
+
24
+ **`OrfeuConfigError` "Invalid operation … level 'admin' …".** Nível/método fora de `Level`/`Method`. Use as
25
+ constantes; em TypeScript, variáveis `string` precisam do tipo `Level`/`Method`.
26
+
27
+ **Certificado autoassinado no Argos (`UNABLE_TO_VERIFY_LEAF_SIGNATURE`, `self signed certificate`).**
28
+ `tlsVerify: false` no client (vale só para as chamadas dele). Não use `NODE_TLS_REJECT_UNAUTHORIZED=0`.
29
+
30
+ ## 401 / 403 inesperados
31
+
32
+ **403 para todo mundo numa operação nova `protected`.** A operação acabou de ser sincronizada e ainda não tem
33
+ grupos em `allowed_groups` no Argos. Libere os grupos no Argos; com `@orfeu/node` ≥ 1.1 / `orfeu` ≥ 1.1 o serviço recarrega sozinho em até
34
+ ~1 min (antes: reinício ou `fetchOperations()` periódico — `node-recipes.md` §10).
35
+
36
+ **403 em `private` para um usuário logado.** `private`/`optional` exigem **pelo menos um grupo** na claim
37
+ `groups`. Usuário sem grupo no client/badge recebe 403.
38
+
39
+ **403 numa rota declarada "depois".** Operação registrada após o `startup()` (rota criada sob demanda, plugin
40
+ registrado tarde, módulo carregado com `import()` dinâmico): ela não está no catálogo buscado e
41
+ `checkPermission` devolve `false` (só `public` escapa). Declare tudo antes do `startup()`.
42
+
43
+ **Permissão mudou no Argos e o serviço não percebeu.** O catálogo com `allowed_groups` é lido no `startup()`.
44
+ Com `@orfeu/node` ≥ 1.1 / `orfeu` ≥ 1.1 a recarga é automática; antes, recarregue com `fetchOperations()` (reautenticando se der 401). Grupos do **usuário** mudam quando o token dele
45
+ é renovado.
46
+
47
+ **401 com token válido.**
48
+ - O front mandou `Authorization: Bearer …`. O SDK só lê `x-access-token` / `x-app-token` / `x-api-token`, valor
49
+ cru.
50
+ - Token de outro realm (o SDK exige `realm_id` = `realmId`). Para aceitar vários realms: `acceptAnyRealm: true`.
51
+ - Token vencido numa rota `optional`: credencial presente e inválida é 401 (não vira anônimo). O front renova
52
+ e repete.
53
+ - Duas credenciais: `x-access-token` vencido + `x-api-token` válido → vale a primeira (access) → 401. Quem quer
54
+ agir como serviço manda **só** o `x-api-token`.
55
+ - `x-app-token` contra um Argos sem introspecção → sempre 401.
56
+
57
+ **401 em todo campo não público depois de atualizar para a 1.0.1 (Apollo), sem credencial no contexto.**
58
+ O app montava o contexto gravando `ctx.orfeuUser` direto (usuário validado por fora, sem `x-access-token`
59
+ no contexto). Gravar `ctx.orfeuUser` direto dá 401 a partir da 1.0.1: a lib só confia em usuário marcado por
60
+ ela. Use `trustUser(ctx, claims)` (`node-recipes.md` §4). Também quebra a marca: copiar o contexto com
61
+ `{ ...ctx }` depois do `trustUser` ou trocar `ctx.orfeuUser` depois dele.
62
+
63
+ **Teste de resolver que passava e virou 401 na 1.0.1.** O teste montava `{ orfeuUser: { sub, groups } }` à mão
64
+ e chamava o resolver protegido. Monte com `trustUser({}, claims)`.
65
+
66
+ **`x-api-token` dá 401 mesmo válido.** O token não tem **esta** operação (identificador + método) concedida
67
+ **neste** serviço. Conferir no Argos.
68
+
69
+ ## Rotas abertas sem querer
70
+
71
+ **Rota Express/Fastify sem `guard`/`orfeuGuard`** ou **método Nest sem `@Operation`**: executa sem checar nada,
72
+ sem usuário e sem auditoria. O `OrfeuGuard` do Nest libera métodos sem `@Operation` de propósito. Revise toda
73
+ rota de negócio; no Apollo, `secureResolvers` + `assertSchemaSecured` impedem isso na subida.
74
+
75
+ **Handler que lia o usuário sem guard.** O `middleware`/plugin só captura headers; `req.orfeuUser` só existe
76
+ depois do guard. Proteja a rota (mesmo que `Level.PUBLIC`, para ter o usuário quando houver).
77
+
78
+ **`@Operation` na classe.** Não funciona: o guard lê o metadado do método.
79
+
80
+ ## GraphQL
81
+
82
+ **`OrfeuConfigError: Operações sem nível declarado (…)`.** Campo de Query/Mutation/Subscription sem
83
+ `operation()`. Todo campo raiz precisa de nível; não existe padrão.
84
+
85
+ **`OrfeuConfigError: operation(): esta função já foi declarada como operação`.** A mesma função em dois campos.
86
+ Envolva: `operation(Level.PRIVATE, (...a) => fn(...a))`.
87
+
88
+ **`assertSchemaSecured` falha listando campos.** O campo está no SDL sem resolver, foi mesclado depois do
89
+ `secureResolvers`, ou outro middleware de resolvers (aplicado depois) trocou a função e perdeu a marca. Aplique
90
+ `secureResolvers` por último, sobre o mapa já mesclado.
91
+
92
+ **Toda Subscription negada.** O servidor WebSocket não usa os plugins do Apollo: passe
93
+ `context: orfeuWsContext(client, extra)` ao `useServer` e mande a credencial em `connectionParams`. A credencial é
94
+ lida na conexão: quando o token do front muda, reconecte o socket.
95
+
96
+ **`connectionParams` espalhado no contexto do WebSocket** (`orfeuWsContext(client, ({ connectionParams }) =>
97
+ ({ ...connectionParams }))`). Tudo que o cliente manda no `connection_init` vira chave do `ctx`. Até a 1.0.0 um
98
+ cliente **sem token** mandava `orfeuUser: { groups: [...] }` e passava em `private`/`protected`. A 1.0.1 descarta
99
+ as chaves reservadas (com aviso `[orfeu] orfeuWsContext: ... chave reservada` fora de produção), mas o resto do
100
+ `connectionParams` continua chegando aos resolvers como se fosse do servidor. O `extra` devolve só uma
101
+ allowlist (`x-access-token`, `x-app-token`, `x-api-token`, `traceparent`, `x-route-id`, `x-client-id`, valor
102
+ string) — receita em `node-recipes.md` §4. Viu o aviso de chave reservada no log? Alguém tentou forjar o
103
+ contexto, ou o `extra` está espalhando o `connectionParams`.
104
+
105
+ **403 virou `{ status: 403, … }` em vez de erro.** É o `onForbidden`. 401 sempre continua `GraphQLError` (o
106
+ cliente usa para renovar o token). Subscriptions sempre recebem `GraphQLError`.
107
+
108
+ **Erro de negócio auditado como sucesso.** O resolver captura a exceção e devolve algo que não é
109
+ `{ status >= 400 }`. Devolva o envelope com `status`, lance a exceção, ou passe `outcome` próprio ao
110
+ `secureResolvers`.
111
+
112
+ ## Trace e propagação
113
+
114
+ **Todo evento sai `entry: false`.** Algo na frente (proxy, gateway, cliente HTTP instrumentado) injeta
115
+ `traceparent` em toda requisição. Só serviços seus devem mandar `traceparent` (via `orfeuHeaders`).
116
+
117
+ **Backend não aparece ligado ao BFF.** O BFF chamou sem `orfeuHeaders(req|ctx)` (trace novo, `entry: true` nos
118
+ dois) ou montou o `traceparent` à mão em maiúsculas/formato errado (inválido → trace novo).
119
+
120
+ **Backend responde 401 para o BFF.** O BFF chamou sem a credencial (`orfeuHeaders(req, { credential: false })`
121
+ ou sem `orfeuHeaders`) e a operação do backend não é `public`.
122
+
123
+ **Token do usuário vazando.** `orfeuHeaders` usado em chamada a terceiros. Use só entre serviços seus.
124
+
125
+ **`route_id`/`client_id` vazios na auditoria.** Os valores de `x-route-id`/`x-client-id` não são GUIDs (são
126
+ descartados do evento, mas continuam no log).
127
+
128
+ ## Auditoria e log
129
+
130
+ **Eventos perdidos ao reiniciar.** Faltou `await client.close()` (ou `flushAudit()` em versão antiga) no SIGTERM (`node-recipes.md` §11).
131
+
132
+ **Aviso `[orfeu] authorizer has no audit endpoint (404); auditing paused for 10 min`.** O Argos não tem a
133
+ ingestão de auditoria; a fila é descartada e o SDK tenta de novo depois. Se a auditoria não é desejada:
134
+ `audit: false`.
135
+
136
+ **Aviso `[orfeu] audit buffer full`.** O Argos está inalcançável há muito tempo e a fila (10 mil) encheu;
137
+ leituras bem-sucedidas são descartadas primeiro. Aumente `audit.maxBuffer` se fizer sentido.
138
+
139
+ **Aviso `[orfeu] authorizer rejected N audit event(s)`.** Evento malformado (não deveria acontecer: o SDK ajusta
140
+ os campos aos limites). Verifique `annotateOperation({ details })` com valores não serializáveis.
141
+
142
+ **`annotateOperation` "não grava".** Chamado fora do handler protegido (rota sem guard, callback que perdeu o
143
+ contexto assíncrono, código antes do guard). Ele devolve `false` nesses casos.
144
+
145
+ **stdout poluído com JSON.** É o log de operação padrão. `logger: false` ou um logger próprio (`node-recipes.md` §9).
146
+
147
+ ## Pacote e build
148
+
149
+ **Registro vazio em CommonJS com adapters.** Não acontece desde a 1.0.0 (registro global por `Symbol.for`), mas
150
+ duas **versões** diferentes do `@orfeu/node` no mesmo processo não compartilham o client nem os tipos:
151
+ `npm ls @orfeu/node` deve mostrar uma só.
152
+
153
+ **`ApiTokenClaims` não é exportado pela raiz.** Use `NonNullable<Request['orfeuApiToken']>` (Express) ou
154
+ declare `{ tokenId: string; appId: string }`.
155
+
156
+ **Nest: `Nest can't resolve dependencies of the OrfeuGuard`.** Falta `OrfeuModule.forRootAsync(...)` no módulo
157
+ raiz (é ele que fornece o `OrfeuClient`, global). Não declare `OrfeuGuard`/`OrfeuClient` em `providers` de
158
+ outros módulos.