@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,474 @@
1
+ # Receitas — @orfeu/angular 1.0.0
2
+
3
+ Todas usam a API real da 1.0.0 ([angular-api.md](angular-api.md)). Componentes standalone, `inject()`, controle de fluxo
4
+ `@if`/`@for`. Troque textos e estilos pelos do app (design system, i18n).
5
+
6
+ ## 1. Bootstrap
7
+
8
+ ```ts
9
+ // app.config.ts
10
+ import { ApplicationConfig } from '@angular/core';
11
+ import { provideHttpClient, withInterceptors } from '@angular/common/http';
12
+ import { provideRouter } from '@angular/router';
13
+ import { provideAuth } from '@orfeu/angular/core';
14
+ import { environment } from '../environments/environment';
15
+ import { routes } from './app.routes';
16
+ import { orfeuTokenInterceptor } from './core/orfeu-token.interceptor';
17
+
18
+ export const appConfig: ApplicationConfig = {
19
+ providers: [
20
+ provideHttpClient(withInterceptors([orfeuTokenInterceptor])),
21
+ provideRouter(routes),
22
+ provideAuth({
23
+ authority: environment.argosUrl, // ex.: 'https://argos.exemplo.com' (sem barra no fim)
24
+ realmId: environment.realmId,
25
+ clientId: environment.clientId,
26
+ redirectUrl: `${location.origin}/callback`, // ajuste se o app tem base href (ex.: /app/callback)
27
+ scope: 'openid profile',
28
+ }),
29
+ ],
30
+ };
31
+ ```
32
+
33
+ Com SSR, não use `location` no config (não existe no servidor): ponha a URL absoluta no `environment`.
34
+
35
+ ## 2. Rotas
36
+
37
+ ```ts
38
+ // app.routes.ts
39
+ import { Routes } from '@angular/router';
40
+ import { PrivateGuard } from '@orfeu/angular/core';
41
+
42
+ export const routes: Routes = [
43
+ // públicas — NUNCA com PrivateGuard
44
+ { path: 'callback', loadComponent: () => import('./auth/callback.component').then(m => m.CallbackComponent) },
45
+ { path: 'logoff', loadComponent: () => import('./auth/logoff.component').then(m => m.LogoffComponent) },
46
+
47
+ // protegidas
48
+ {
49
+ path: '',
50
+ canActivateChild: [PrivateGuard],
51
+ loadComponent: () => import('./shell/shell.component').then(m => m.ShellComponent),
52
+ children: [
53
+ { path: '', pathMatch: 'full', redirectTo: 'home' },
54
+ { path: 'home', loadComponent: () => import('./home/home.component').then(m => m.HomeComponent) },
55
+ { path: 'clientes/:id', loadComponent: () => import('./clientes/cliente.component').then(m => m.ClienteComponent) },
56
+ ],
57
+ },
58
+ { path: '**', redirectTo: 'home' },
59
+ ];
60
+ ```
61
+
62
+ - `canActivateChild` no pai protege todos os filhos; para uma rota solta use `canActivate: [PrivateGuard]`.
63
+ - A URL pedida (ex.: `/clientes/42`) é gravada e restaurada depois do login.
64
+ - Sem URL de retorno, o login termina em `routes[0].route_redirect` do `/view` ou em `/home`: garanta que
65
+ esse caminho existe.
66
+
67
+ ## 3. Callback e logoff
68
+
69
+ ```ts
70
+ // auth/callback.component.ts
71
+ import { Component, inject, OnInit, signal } from '@angular/core';
72
+ import { ActivatedRoute } from '@angular/router';
73
+ import { AuthorizationService, OrfeuAuthError } from '@orfeu/angular/core';
74
+
75
+ @Component({
76
+ selector: 'app-callback',
77
+ template: `
78
+ @if (error(); as message) {
79
+ <p role="alert">{{ message }}</p>
80
+ <button type="button" (click)="retry()">Entrar de novo</button>
81
+ } @else {
82
+ <p role="status">Entrando…</p>
83
+ }
84
+ `,
85
+ })
86
+ export class CallbackComponent implements OnInit {
87
+ private readonly auth = inject(AuthorizationService);
88
+ private readonly route = inject(ActivatedRoute);
89
+ protected readonly error = signal<string | null>(null);
90
+
91
+ async ngOnInit(): Promise<void> {
92
+ try {
93
+ // confere state/nonce, troca o code, carrega o /view e navega para a URL de retorno
94
+ await this.auth.handleCallback(this.route.snapshot.queryParams);
95
+ } catch (err) {
96
+ this.error.set(this.describe(err));
97
+ }
98
+ }
99
+
100
+ protected retry(): void {
101
+ void this.auth.authorize('/');
102
+ }
103
+
104
+ private describe(err: unknown): string {
105
+ if (err instanceof OrfeuAuthError) {
106
+ switch (err.code) {
107
+ case 'callback_error': return `O servidor de autenticação recusou o login: ${err.message}`;
108
+ case 'invalid_callback': // recarregou esta página ou abriu o link em outra aba
109
+ case 'state_mismatch':
110
+ case 'nonce_mismatch': return 'Este link de login não é mais válido. Entre de novo.';
111
+ }
112
+ }
113
+ return 'Não foi possível concluir o login.'; // ex.: HttpErrorResponse do /token (code já usado, rede)
114
+ }
115
+ }
116
+ ```
117
+
118
+ ```ts
119
+ // auth/logoff.component.ts — a lib navega para /logoff?loggedOut=true no logout (desta ou de outra aba)
120
+ import { Component, inject } from '@angular/core';
121
+ import { AuthorizationService } from '@orfeu/angular/core';
122
+
123
+ @Component({
124
+ selector: 'app-logoff',
125
+ template: `
126
+ <h1>Você saiu</h1>
127
+ <button type="button" (click)="login()">Entrar de novo</button>
128
+ `,
129
+ })
130
+ export class LogoffComponent {
131
+ private readonly auth = inject(AuthorizationService);
132
+ protected login(): void { void this.auth.authorize('/'); }
133
+ }
134
+ ```
135
+
136
+ Botão "Sair" em qualquer lugar: `inject(AuthorizationService).logout()` (não devolve promise; a navegação para
137
+ `/logoff` acontece sozinha).
138
+
139
+ ## 4. Interceptor: token nas APIs do app
140
+
141
+ As APIs com `@orfeu/node` leem o token cru em `x-access-token`. Opcionalmente, `x-client-id` (id do client
142
+ deste front) e `x-route-id` (o `routed_id` da página atual no `/view`) entram na auditoria — só são gravados
143
+ se forem GUIDs.
144
+
145
+ ```ts
146
+ // core/orfeu-token.interceptor.ts
147
+ import { HttpErrorResponse, HttpInterceptorFn, HttpRequest } from '@angular/common/http';
148
+ import { inject } from '@angular/core';
149
+ import { AUTH_CONFIG, AuthorizationService } from '@orfeu/angular/core';
150
+ import { catchError, from, switchMap, throwError } from 'rxjs';
151
+ import { environment } from '../../environments/environment';
152
+
153
+ /** Só as APIs DESTE app. Nunca o Argos (preflight CORS com header estranho quebra o refresh) nem terceiros (vazaria o token). */
154
+ const API_PREFIXES: string[] = [environment.apiUrl, '/api/'];
155
+
156
+ export const orfeuTokenInterceptor: HttpInterceptorFn = (req, next) => {
157
+ if (!API_PREFIXES.some(prefix => req.url.startsWith(prefix))) return next(req);
158
+
159
+ const auth = inject(AuthorizationService);
160
+ const { clientId } = inject(AUTH_CONFIG);
161
+
162
+ const withToken = (request: HttpRequest<unknown>, token: string | null) =>
163
+ token ? request.clone({ setHeaders: { 'x-access-token': token, 'x-client-id': clientId } }) : request;
164
+
165
+ const sent = auth.getToken();
166
+ return next(withToken(req, sent)).pipe(
167
+ catchError((err: unknown) => {
168
+ // 401 com sessão viva = token vencido/recusado: espera uma renovação e repete UMA vez.
169
+ if (!(err instanceof HttpErrorResponse) || err.status !== 401 || !auth.authenticated) {
170
+ return throwError(() => err);
171
+ }
172
+ return from(auth.silentRenew().catch(() => undefined)).pipe(
173
+ switchMap(() => {
174
+ const renewed = auth.getToken();
175
+ return renewed && renewed !== sent ? next(withToken(req, renewed)) : throwError(() => err);
176
+ }),
177
+ );
178
+ }),
179
+ );
180
+ };
181
+ ```
182
+
183
+ - `silentRenew()` reaproveita uma renovação em andamento (desta ou de outra aba): várias requisições com 401
184
+ ao mesmo tempo geram um único refresh.
185
+ - Se o refresh falhar, o erro original sobe. **Não** chame `logout()`: a lib segue tentando e, se o Argos
186
+ recusou, reautoriza (veja §5/§6).
187
+ - Para mandar `x-route-id`, guarde o `routed_id` da página atual num serviço do app (ex.: ao montar o
188
+ breadcrumb, §8) e acrescente-o em `setHeaders`.
189
+ - GraphQL por WebSocket: mande o mesmo token em `connectionParams` (`{ 'x-access-token': token }`), lido na
190
+ conexão; reconecte quando o token mudar.
191
+
192
+ ## 5. Banner de conexão
193
+
194
+ ```ts
195
+ import { AsyncPipe } from '@angular/common';
196
+ import { Component, inject } from '@angular/core';
197
+ import { Router } from '@angular/router';
198
+ import { AuthorizationService } from '@orfeu/angular/core';
199
+
200
+ @Component({
201
+ selector: 'app-connection-banner',
202
+ imports: [AsyncPipe],
203
+ template: `
204
+ @switch (auth.connectionState$ | async) {
205
+ @case ('offline') {
206
+ <div role="status">Sem conexão com o servidor. Seu trabalho continua aqui; reconectando…</div>
207
+ }
208
+ @case ('reconnecting') { <div role="status">Reconectando…</div> }
209
+ @case ('reauthorizing') {
210
+ @if (auth.reauthorizationRequired$ | async) {
211
+ <div role="alert">
212
+ Sua sessão precisa ser confirmada.
213
+ <button type="button" (click)="auth.authorize(router.url)">Entrar de novo</button>
214
+ </div>
215
+ } @else {
216
+ <div role="status">Renovando sua sessão…</div>
217
+ }
218
+ }
219
+ }
220
+ `,
221
+ })
222
+ export class ConnectionBannerComponent {
223
+ protected readonly auth = inject(AuthorizationService);
224
+ protected readonly router = inject(Router);
225
+ }
226
+ ```
227
+
228
+ Coloque-o uma vez no shell. Enquanto `connectionState !== 'online'`, telas podem trocar a mensagem de erro de
229
+ API pelo banner (consulte `auth.connectionState` no tratamento de erro).
230
+
231
+ Com signals: `connection = toSignal(inject(AuthorizationService).connectionState$, { initialValue: 'online' })`.
232
+
233
+ ## 6. Reautorização sob controle do app
234
+
235
+ Para apps que não podem ser redirecionados sozinhos (formulário longo, tela de operação):
236
+
237
+ ```ts
238
+ provideAuth(config, { autoReauthorize: false });
239
+ ```
240
+
241
+ Com isso, um refresh recusado só emite `reauthorizationRequired$ = true` (e `connectionState$ =
242
+ 'reauthorizing'`). O app avisa e, quando a pessoa puder, chama `auth.authorize(router.url)` — ela volta para
243
+ a mesma URL depois do login. Salve rascunhos antes, porque `authorize()` sai da página.
244
+
245
+ ## 7. Badge (perfil de acesso) e troca
246
+
247
+ ```ts
248
+ import { Component, DestroyRef, inject, signal } from '@angular/core';
249
+ import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
250
+ import { AuthorizationService, Badge } from '@orfeu/angular/core';
251
+
252
+ @Component({
253
+ selector: 'app-badge-switcher',
254
+ template: `
255
+ <label for="badge">Perfil</label>
256
+ <select id="badge" [value]="current()?.id ?? ''" (change)="switch($any($event.target).value)" [disabled]="busy()">
257
+ @for (b of badges(); track b.id) { <option [value]="b.id">{{ b.name }}</option> }
258
+ </select>
259
+ `,
260
+ })
261
+ export class BadgeSwitcherComponent {
262
+ private readonly auth = inject(AuthorizationService);
263
+ protected readonly badges = signal<Badge[]>(this.auth.badges);
264
+ protected readonly current = signal<Badge | null>(this.auth.badge);
265
+ protected readonly busy = signal(false);
266
+
267
+ constructor() {
268
+ this.auth.badgeChanged$.pipe(takeUntilDestroyed(inject(DestroyRef))).subscribe(() => {
269
+ this.badges.set(this.auth.badges);
270
+ this.current.set(this.auth.badge);
271
+ });
272
+ }
273
+
274
+ protected async switch(id: string): Promise<void> {
275
+ this.busy.set(true);
276
+ try {
277
+ await this.auth.switchBadge(id); // novo token + /view recarregado; outras abas recebem o token
278
+ } catch {
279
+ // mostre um aviso; a sessão continua com o badge anterior
280
+ } finally {
281
+ this.busy.set(false);
282
+ }
283
+ }
284
+ }
285
+ ```
286
+
287
+ Telas com dados dependentes do badge escutam `badgeChanged$` e recarregam. O menu (`currentView$`) já
288
+ atualiza sozinho.
289
+
290
+ ## 8. Menu e breadcrumb a partir do `/view`
291
+
292
+ ```ts
293
+ import { AsyncPipe } from '@angular/common';
294
+ import { Component, inject } from '@angular/core';
295
+ import { RouterLink } from '@angular/router';
296
+ import { Route, ViewService } from '@orfeu/angular/core';
297
+ import { map } from 'rxjs';
298
+
299
+ @Component({
300
+ selector: 'app-menu',
301
+ imports: [AsyncPipe, RouterLink],
302
+ template: `
303
+ <nav aria-label="Navegação principal">
304
+ <ul>
305
+ @for (r of (routes$ | async) ?? []; track r.routed_id) {
306
+ <li>
307
+ <a [routerLink]="r.route_redirect">{{ r.route_display_name }}</a>
308
+ @if (r.routes?.length) {
309
+ <ul>
310
+ @for (c of r.routes; track c.routed_id) {
311
+ <li><a [routerLink]="c.route_redirect">{{ c.route_display_name }}</a></li>
312
+ }
313
+ </ul>
314
+ }
315
+ </li>
316
+ }
317
+ </ul>
318
+ </nav>
319
+ `,
320
+ })
321
+ export class MenuComponent {
322
+ private readonly view = inject(ViewService);
323
+ protected readonly routes$ = this.view.currentView$.pipe(
324
+ map(v => [...(v?.routes ?? [])].sort((a, b) => (a.route_order ?? 0) - (b.route_order ?? 0))),
325
+ );
326
+ }
327
+ ```
328
+
329
+ - `currentView` começa `null` (antes do primeiro `/view`): sempre `v?.routes ?? []`.
330
+ - Falha do `/view` vira `{ routes: [], apps: [] }` + `viewError$`: mostre um aviso observando `viewError$`
331
+ em vez de um menu vazio sem explicação.
332
+ - Breadcrumb: monte a cadeia `[raiz, nível1, …, página]` de nós `Route` que casa com a URL atual e chame
333
+ `view.updateBreadcrumb(cadeia)`; leia `breadCrumb$` (`{ icon, urls: [{ label, routerLink }] }`). O
334
+ `routed_id` do último nó é o `x-route-id` da página (§4).
335
+
336
+ ## 9. Lançador de apps do realm
337
+
338
+ ```ts
339
+ const apps = await inject(RealmAppsService).getApplications(inject(AuthorizationService).getToken());
340
+ // AppDef[]: { id, name, app_url } — links externos (<a [href]="a.app_url">)
341
+ ```
342
+
343
+ Chame `inject()` no contexto de injeção (construtor/campo) e guarde os serviços; `getApplications` só faz
344
+ requisição se o token mudou desde o último `/view`.
345
+
346
+ ## 10. Perfil no cabeçalho
347
+
348
+ ```ts
349
+ import { Component, computed, inject } from '@angular/core';
350
+ import { toSignal } from '@angular/core/rxjs-interop';
351
+ import { AuthorizationService } from '@orfeu/angular/core';
352
+
353
+ @Component({
354
+ selector: 'app-user-menu',
355
+ template: `
356
+ @if (loggedIn()) {
357
+ <span>{{ profile().name ?? 'Usuário' }}</span>
358
+ <button type="button" (click)="auth.logout()">Sair</button>
359
+ }
360
+ `,
361
+ })
362
+ export class UserMenuComponent {
363
+ protected readonly auth = inject(AuthorizationService);
364
+ protected readonly loggedIn = toSignal(this.auth.isAuth$, { initialValue: this.auth.authenticated });
365
+ protected readonly profile = computed(() => (this.loggedIn(), this.auth.profile));
366
+ }
367
+ ```
368
+
369
+ `profile` é um getter (não observable): recalcule quando `isAuth$` ou `badgeChanged$` emitirem.
370
+
371
+ ## 11. Variações de boot
372
+
373
+ **Página pública que não deve esperar o Argos** (vitrine em `/`): `provideAuth(config, { eagerInit: false })`.
374
+ Nada acontece no boot; a primeira rota protegida faz o refresh pelo cookie e só vai ao login se não houver
375
+ sessão. Num componente público que quer saber se há sessão sem forçar login:
376
+ `await auth.ensureAuthenticated()` (não redireciona).
377
+
378
+ **App embutido em iframe de propósito**: `provideAuth(config, { initInIframe: true })`. O cookie de refresh
379
+ precisa ser `SameSite=None; Secure` (configuração do Argos). O login interativo (`authorize`) navega o
380
+ próprio iframe; se a página de login do Argos não puder ser exibida em iframe, o primeiro login tem de
381
+ acontecer fora dele (na janela principal) — depois disso o iframe recupera a sessão pelo cookie.
382
+
383
+ ## 12. Testes
384
+
385
+ ### Tela que depende da sessão — serviço falso
386
+
387
+ ```ts
388
+ import { TestBed } from '@angular/core/testing';
389
+ import { provideRouter } from '@angular/router';
390
+ import { AuthorizationService } from '@orfeu/angular/core';
391
+ import { BehaviorSubject, EMPTY, of } from 'rxjs';
392
+
393
+ const fakeAuth = {
394
+ authenticated: true,
395
+ isAuth$: of(true),
396
+ tokenExpired$: of(false),
397
+ connectionState$: new BehaviorSubject<'online' | 'reconnecting' | 'offline' | 'reauthorizing'>('online'),
398
+ connectionState: 'online',
399
+ reauthorizationRequired$: of(false),
400
+ badgeChanged$: EMPTY,
401
+ badge: { id: 'b1', name: 'Operação' },
402
+ badges: [{ id: 'b1', name: 'Operação' }],
403
+ profile: { name: 'Ana', role: 'analista', picture: null },
404
+ getToken: () => 'token-de-teste',
405
+ ensureAuthenticated: vi.fn().mockResolvedValue(true), // o PrivateGuard real usa estes dois
406
+ startLogin: vi.fn().mockResolvedValue(undefined),
407
+ authorize: vi.fn().mockResolvedValue(undefined),
408
+ handleCallback: vi.fn().mockResolvedValue(undefined),
409
+ switchBadge: vi.fn().mockResolvedValue(undefined),
410
+ silentRenew: vi.fn().mockResolvedValue(undefined),
411
+ logout: vi.fn(),
412
+ };
413
+
414
+ TestBed.configureTestingModule({
415
+ providers: [provideRouter([]), { provide: AuthorizationService, useValue: fakeAuth }],
416
+ });
417
+ ```
418
+
419
+ (Com Jasmine, troque `vi.fn().mockResolvedValue(x)` por `jasmine.createSpy().and.resolveTo(x)`.) Para testar o
420
+ banner, emita em `fakeAuth.connectionState$.next('offline')`.
421
+
422
+ ### Interceptor ou integração — serviço real
423
+
424
+ ```ts
425
+ import { TestBed } from '@angular/core/testing';
426
+ import { HttpClient, provideHttpClient, withInterceptors } from '@angular/common/http';
427
+ import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
428
+ import { provideRouter } from '@angular/router';
429
+ import { AuthorizationService, provideAuth } from '@orfeu/angular/core';
430
+
431
+ const config = {
432
+ authority: 'https://argos.test', realmId: 'realm-1', clientId: 'app-client',
433
+ redirectUrl: 'https://app.test/callback', scope: 'openid profile',
434
+ };
435
+ const OIDC = `${config.authority}/api/realms/${config.realmId}/protocol/openid-connect`;
436
+
437
+ /** JWT sem assinatura válida: a lib só decodifica. */
438
+ function makeJwt(payload: Record<string, unknown>): string {
439
+ const b64 = (o: unknown) => btoa(JSON.stringify(o)).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
440
+ return `${b64({ alg: 'RS256', typ: 'JWT' })}.${b64(payload)}.sig`;
441
+ }
442
+
443
+ beforeEach(() => {
444
+ TestBed.configureTestingModule({
445
+ providers: [
446
+ provideRouter([]),
447
+ provideHttpClient(withInterceptors([orfeuTokenInterceptor])),
448
+ provideHttpClientTesting(),
449
+ provideAuth(config, { eagerInit: false, expiryLog: false, autoReauthorize: false }),
450
+ ],
451
+ });
452
+ });
453
+
454
+ it('manda o token em x-access-token', async () => {
455
+ const auth = TestBed.inject(AuthorizationService);
456
+ const http = TestBed.inject(HttpTestingController);
457
+ const now = Math.floor(Date.now() / 1000);
458
+ const token = makeJwt({ sub: 'u1', iat: now, exp: now + 600, name: 'Ana' });
459
+
460
+ const renewing = auth.silentRenew();
461
+ http.expectOne(`${OIDC}/token`).flush({ access_token: token });
462
+ await renewing;
463
+
464
+ TestBed.inject(HttpClient).get('/api/itens').subscribe();
465
+ expect(http.expectOne('/api/itens').request.headers.get('x-access-token')).toBe(token);
466
+ });
467
+ ```
468
+
469
+ - `eagerInit: false` evita o refresh no boot do TestBed; `autoReauthorize: false` evita redirecionamento.
470
+ - O serviço real agenda timers de renovação: use fake timers se o teste avança o relógio; o `TestBed` destrói
471
+ o serviço (e os timers) entre testes.
472
+ - `authorize()` faz `window.location.href = …`: num teste que o exercita, substitua `location`
473
+ (`vi.stubGlobal('location', { href: '', origin: 'https://app.test' })`) e confira `href`.
474
+ - Sem `BroadcastChannel` no ambiente de teste a lib funciona (sem sincronizar abas).
@@ -0,0 +1,212 @@
1
+ # @orfeu/angular — guia de uso (front)
2
+
3
+ > Escrito para a **1.0.0**. Se a versão instalada for outra, confira os nomes de [angular-api.md](angular-api.md)
4
+ > contra os `.d.ts` de `node_modules/@orfeu/angular/types/` antes de copiar código. Conceitos comuns às três
5
+ > implementações (níveis, headers, trace, auditoria) estão no `SKILL.md` da skill; diferenças entre elas em
6
+ > [diferencas.md](diferencas.md).
7
+
8
+ O `@orfeu/angular` faz o login no Argos (Authorization Code + PKCE S256), guarda o token de acesso **só em
9
+ memória**, renova pelo refresh token em cookie httpOnly do Argos, sincroniza as abas, carrega o `/view` (rotas e
10
+ apps do usuário) e mantém a sessão viva quando o servidor fica inalcançável. **Não escreva nada disso à mão.**
11
+
12
+ Leia sob demanda:
13
+ - [angular-api.md](angular-api.md) — todos os exports dos três pontos de import, com assinatura e comportamento exato.
14
+ - [angular-recipes.md](angular-recipes.md) — receitas prontas: bootstrap, rotas, callback, logoff, interceptor do
15
+ token, banner de conexão, reautorização manual, troca de badge, menu/breadcrumb do `/view`, lançador de apps,
16
+ perfil no cabeçalho, `eagerInit: false`, app em iframe, testes.
17
+ - [angular-armadilhas.md](angular-armadilhas.md) — erros comuns e como diagnosticar (loop de login, 401 nas APIs,
18
+ CORS, contexto inseguro, duas cópias da lib…).
19
+
20
+ Padrões gerais de app Angular (estrutura, estado, formulários) são da skill `angular`; shell, layout e
21
+ componentes visuais (menu, cabeçalho, banner) são da skill `trismegisto`.
22
+
23
+ ## 1. Princípio que guia tudo: a sessão nunca cai sozinha
24
+
25
+ A lib **nunca desloga o usuário**. A sessão só termina por `logout()` chamado pelo app (ou pela mensagem
26
+ `LOGOUT` que esse logout manda às outras abas). Token vencido, refresh falhando, servidor fora do ar,
27
+ callback inválido, SSR, iframe ou navegador sem `BroadcastChannel` **não** encerram a sessão.
28
+
29
+ Consequências para quem integra:
30
+ - `authenticated`/`isAuth$` continuam `true` com o token vencido. Para saber se o token está vencido, use
31
+ `tokenExpired`/`tokenExpired$`. Para saber se o servidor responde, use `connectionState$`.
32
+ - **Não** chame `logout()` por causa de erro de rede, 401 de API ou token vencido. A lib já está renovando.
33
+ `logout()` é só para o botão "Sair".
34
+ - Se o app precisa encerrar a sessão por regra própria (ex.: inatividade), ele chama `logout()` explicitamente.
35
+
36
+ ## 2. Instalação e requisitos
37
+
38
+ ```bash
39
+ npm install @orfeu/angular
40
+ ```
41
+
42
+ | Peer | Versão |
43
+ |---|---|
44
+ | `@angular/common`, `@angular/core`, `@angular/router` | `>= 21.0.0` |
45
+ | `rxjs` | `^7.0.0` |
46
+
47
+ - O app fornece `provideHttpClient()` e `provideRouter(...)`. A lib não tem dependências próprias.
48
+ - Navegador: `crypto.subtle` e `crypto.randomUUID` (só existem em **contexto seguro**: HTTPS ou
49
+ `http://localhost`), `sessionStorage`. `BroadcastChannel` é opcional (sem ele, as abas não se sincronizam).
50
+ - Uma única cópia da lib no bundle: `AUTH_CONFIG` e os serviços são identificados pela instância. Bibliotecas
51
+ internas que usam a sessão devem declarar `@orfeu/angular` como **peer**, não como dependência.
52
+
53
+ Pontos de import:
54
+
55
+ | Import | Conteúdo |
56
+ |---|---|
57
+ | `@orfeu/angular` | `AUTH_CONFIG` e `AuthConfig` |
58
+ | `@orfeu/angular/core` | tudo o que um app usa: `provideAuth`, `AuthorizationService`, `PrivateGuard`, `ViewService`, `RealmAppsService`, `OrfeuAuthError`, `AUTH_OPTIONS`, tipos. Reexporta `AUTH_CONFIG`/`AuthConfig` |
59
+ | `@orfeu/angular/util` | `decodeJwt`, `isJwtExpired`, PKCE (sem Angular) |
60
+
61
+ Na dúvida, importe de `@orfeu/angular/core`.
62
+
63
+ ## 3. Configuração (bootstrap)
64
+
65
+ ```ts
66
+ // app.config.ts
67
+ import { ApplicationConfig } from '@angular/core';
68
+ import { provideHttpClient, withInterceptors } from '@angular/common/http';
69
+ import { provideRouter } from '@angular/router';
70
+ import { provideAuth } from '@orfeu/angular/core';
71
+ import { routes } from './app.routes';
72
+ import { orfeuTokenInterceptor } from './core/orfeu-token.interceptor'; // angular-recipes.md §4
73
+
74
+ export const appConfig: ApplicationConfig = {
75
+ providers: [
76
+ provideHttpClient(withInterceptors([orfeuTokenInterceptor])),
77
+ provideRouter(routes),
78
+ provideAuth(
79
+ {
80
+ authority: environment.argosUrl, // origem do Argos, sem barra no fim; '' = mesma origem da UI
81
+ realmId: environment.realmId, // nome ou id do realm
82
+ clientId: environment.clientId, // client do app cadastrado no Argos
83
+ redirectUrl: `${location.origin}/callback`, // EXATAMENTE como cadastrado no client
84
+ scope: 'openid profile',
85
+ },
86
+ { /* AuthOptions: tudo opcional, ver tabela */ },
87
+ ),
88
+ ],
89
+ };
90
+ ```
91
+
92
+ Todas as chamadas vão para `${authority}/api/realms/${realmId}/...` (`/protocol/openid-connect/authorize`,
93
+ `/token`, `/view`, `/logout` e `/auth/switch-badge`). `responseType` ainda é aceito no tipo, mas é ignorado
94
+ (deprecated): o fluxo é sempre `code`.
95
+
96
+ | `AuthOptions` | Padrão | Efeito |
97
+ |---|---|---|
98
+ | `eagerInit` | `true` | Registra `initialize()` como app initializer: o primeiro render espera a tentativa de refresh pelo cookie e o `/view`. Quem tem sessão no Argos entra direto, sem passar pela tela de login. |
99
+ | `autoReauthorize` | `true` | Se o Argos **recusar** o refresh, redireciona sozinho para `/authorize?prompt=none` (e, se preciso, login interativo), no máximo 1 vez a cada 5 min por aba, voltando para a mesma URL. Com `false`, só emite `reauthorizationRequired$`. |
100
+ | `expiryLog` | `isDevMode()` | Log `[orfeu-angular] token expira em Ns` a cada 10 s. |
101
+ | `initInIframe` | `false` | Dentro de iframe, `initialize()` não faz nada, a menos que seja `true`. |
102
+
103
+ ## 4. Rotas obrigatórias
104
+
105
+ | Rota | Por quê |
106
+ |---|---|
107
+ | a do `redirectUrl` (ex.: `/callback`) | o Argos volta para ela com `?code&state` (ou `?error`). Componente chama `handleCallback()`. **Sem guard.** |
108
+ | `/logoff` | `logout()` (e o `LOGOUT` vindo de outra aba) navega para `/logoff?loggedOut=true`. **Sem guard.** O caminho é fixo. |
109
+ | a 1ª rota do `/view` ou `/home` | depois do login sem URL de retorno, a lib navega para `views.routes[0].route_redirect` ou, sem isso, `/home`. |
110
+ | as rotas protegidas | `canActivate: [PrivateGuard]` ou `canActivateChild: [PrivateGuard]` num pai. |
111
+
112
+ Receita completa em [angular-recipes.md](angular-recipes.md) §2–§3.
113
+
114
+ ## 5. Fluxos
115
+
116
+ **Boot** (`eagerInit: true`): `initialize()` → `POST /token` com `grant_type=refresh_token` e o cookie
117
+ (`withCredentials`) → com sucesso, token em memória + `GET /view`; sem sessão, `isAuth$ = false` (não lança).
118
+
119
+ **Rota protegida** (`PrivateGuard`): com sessão (mesmo com token vencido) libera e, se vencido, renova na
120
+ hora. Sem sessão e sem tentativa anterior, tenta o refresh. Se não der, chama `startLogin(url)`:
121
+ - servidor alcançável → `authorize(url)`: grava verifier/state/nonce e a URL de retorno no `sessionStorage` e
122
+ redireciona para o `/authorize` do Argos. O guard devolve `false`;
123
+ - servidor inalcançável (`connectionState === 'offline'`) → não redireciona para uma página que não carrega:
124
+ guarda a URL e navega para ela sozinho quando a conexão voltar e a sessão for recuperada pelo cookie.
125
+
126
+ **Callback**: `handleCallback(route.snapshot.queryParams)` confere `state`, troca o `code` com o
127
+ `code_verifier`, confere o `nonce` do `id_token`, aplica o token, avisa as outras abas, carrega o `/view` e
128
+ navega para a URL de retorno (ou a 1ª rota do `/view`, ou `/home`). Rejeita com `OrfeuAuthError` — sempre
129
+ envolva em `try/catch`.
130
+
131
+ **Renovação** (automática, não chame nada): ≥ 120 s de vida → renova 60 s antes de vencer (+ 0–5 s); vida
132
+ curta → na metade do tempo restante (mínimo 5 s). Falhou por rede/5xx → `connectionState$ = 'offline'` e
133
+ tenta de novo com backoff 15 s, 30 s, 60 s, 60 s… para sempre. Eventos `online`, `focus` e aba visível
134
+ renovam na hora (debounce 1 s).
135
+
136
+ **Refresh recusado** pelo Argos (400/401 com `invalid_refresh`, `expired_refresh`, `revoked`,
137
+ `client_mismatch`, `no_refresh_cookie`, `invalid_grant`, `invalid_client`, `unauthorized_client`):
138
+ `connectionState$ = 'reauthorizing'`, `reauthorizationRequired$ = true` e, com `autoReauthorize`, uma aba
139
+ redireciona para `/authorize?prompt=none`; se o Argos responder `login_required`, `handleCallback()` segue
140
+ para o login interativo mantendo a URL. Nunca desloga.
141
+
142
+ **Multi-aba**: canal `BroadcastChannel('auth_<clientId>')`. Login, refresh e troca de badge propagam o token
143
+ (`TOKEN_UPDATED`); só uma aba chama `/token` por vez (`REFRESH_STARTED`); `logout()` desloga todas
144
+ (`LOGOUT`); só uma aba reautoriza (`REAUTH_STARTED`). O token **não** vai para `localStorage`: uma aba nova
145
+ sem outra aberta recupera a sessão pelo cookie no boot.
146
+
147
+ **Logout**: `logout()` → `GET /logout?client_id=…` (com cookie); com sucesso ou erro, limpa o estado local,
148
+ avisa as abas e navega para `/logoff?loggedOut=true`.
149
+
150
+ ## 6. Chamando as APIs do app
151
+
152
+ A lib **não** tem interceptor: ela só põe credencial nas próprias chamadas ao Argos. As APIs do app que usam
153
+ `@orfeu/node` leem o token **cru** no header **`x-access-token`** (não usam `Authorization: Bearer`).
154
+ Use o interceptor de [angular-recipes.md](angular-recipes.md) §4, que:
155
+ - só toca nas URLs das **suas** APIs (lista explícita) — nunca nas do Argos nem de terceiros;
156
+ - manda `x-access-token: <auth.getToken()>` e, opcionalmente, `x-client-id`/`x-route-id` para a auditoria;
157
+ - num 401 com sessão viva, espera uma renovação (`silentRenew()`) e repete **uma** vez.
158
+
159
+ O browser **não** manda `traceparent`: a chamada do usuário é a entrada do trace (`entry: true`) na API.
160
+
161
+ ## 7. Estado para a interface
162
+
163
+ | Quero mostrar… | Use |
164
+ |---|---|
165
+ | logado / não logado | `isAuth$` / `authenticated` |
166
+ | "sem conexão com o servidor", "reconectando…" | `connectionState$` (`'online' \| 'reconnecting' \| 'offline' \| 'reauthorizing'`) — `angular-recipes.md` §5 |
167
+ | botão "Entrar de novo" quando a reautorização automática não aconteceu | `reauthorizationRequired$` + `authorize(router.url)` |
168
+ | nome, cargo, foto | `profile` (`{ name, role, picture }`, das claims do token) |
169
+ | badge ativo e troca | `badge`, `badges`, `switchBadge(id)`, `badgeChanged$` — `angular-recipes.md` §7 |
170
+ | menu e breadcrumb | `ViewService.currentView$` (`routes`), `updateBreadcrumb()`, `breadCrumb$` — `angular-recipes.md` §8 |
171
+ | outros apps do realm | `RealmAppsService.getApplications(auth.getToken())` — `angular-recipes.md` §9 |
172
+
173
+ As claims são lidas com `decodeJwt` **sem verificar assinatura**: servem para exibir, nunca para decidir
174
+ permissão. Quem decide é a API (`@orfeu/node`) e o `/view` (o que o usuário pode ver).
175
+
176
+ ## 8. Erros
177
+
178
+ `OrfeuAuthError` (`err.code`):
179
+
180
+ | `code` | Quando |
181
+ |---|---|
182
+ | `callback_error` | o Argos voltou com `?error=...` (mensagem = `error_description` ou `error`) |
183
+ | `invalid_callback` | callback sem `code` ou sem `code_verifier` no `sessionStorage` (recarregou o callback, abriu em outra aba, storage limpo) |
184
+ | `state_mismatch` | `state` ausente ou diferente do gravado em `authorize()` |
185
+ | `nonce_mismatch` | `nonce` do `id_token` diferente do gravado |
186
+ | `not_authenticated` | `switchBadge()` sem sessão; `silentRenew()` no servidor (SSR) |
187
+
188
+ Erros HTTP (`HttpErrorResponse`) do `/token` no callback e do `switch-badge` são repassados como vieram.
189
+ `ViewService.update()`/`view()` não lançam (fallback `{ routes: [], apps: [] }` + `viewError$`).
190
+ Nenhum desses erros encerra uma sessão existente.
191
+
192
+ ## 9. SSR
193
+
194
+ No servidor o serviço é criado sem erro e fica inerte: sem timers, sem canal, sem storage;
195
+ `initialize()`/`authorize()` não fazem nada, `ensureAuthenticated()` devolve `false` e o `PrivateGuard`
196
+ bloqueia. Rotas protegidas devem ser renderizadas no cliente.
197
+
198
+ ## 10. Testes
199
+
200
+ A lib não publica helpers de teste. Para telas, forneça um `AuthorizationService` falso; para testar a
201
+ integração, use o serviço real com `provideHttpClientTesting()` e um JWT montado à mão (a lib só decodifica,
202
+ não confere assinatura). `angular-recipes.md` §12.
203
+
204
+ ## 11. Não faça
205
+
206
+ - Não guarde o token em `localStorage`/`sessionStorage`, nem o leia de lá: use `getToken()`.
207
+ - Não implemente refresh, PKCE, troca de code ou canal entre abas: chame a lib.
208
+ - Não ponha `PrivateGuard` nas rotas de callback e `/logoff`.
209
+ - Não chame `logout()` em erro de API, 401 ou offline.
210
+ - Não mande `x-access-token` (nem nenhum header próprio) para o Argos ou para APIs de terceiros.
211
+ - Não use as claims decodificadas no front para liberar ação: a API decide.
212
+ - Não chame `token()` direto no callback: use `handleCallback()`.